DeepSeek AI continues to push the boundaries of AI interaction with its innovative Chat Completion API. One standout feature currently in Beta is the Chat Prefix Completion, offering users enhanced control over the AI's responses. This article explores this feature in detail, explaining how it works and providing a practical example to get you started.
The Chat Prefix Completion feature builds upon DeepSeek's existing Chat Completion API, allowing users to provide a starting "prefix" for the AI assistant's message. The model then completes the message, building upon this foundation. This is particularly useful when you want to guide the AI's output towards a specific style, format, or topic.
prefix
parameter of this last message to True
. This tells the model to use the content of that message as a starting point.base_url="https://api.deepseek.com/beta"
in your API client configuration.One powerful use case for prefix completion is code generation. Let's say you want the AI to write Python code, and you want to ensure it's properly formatted within a code block. You can achieve this using the following approach:
"Please write quick sort code"
."```python\n"
. Set prefix
to True
for this message.stop
parameter to prevent the model from adding extra explanations after the code. In this case, set stop=["```"]
to stop generation after the closing code block.Here's a complete Python code example demonstrating chat prefix completion for code generation:
from openai import OpenAI
client = OpenAI(
api_key="<your api key>",
base_url="https://api.deepseek.com/beta",
)
messages = [
{"role": "user", "content": "Please write quick sort code"},
{"role": "assistant", "content": "```python\n", "prefix": True}
]
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages,
stop=["```"],
)
print(response.choices[0].message.content)
In this example, the model will generate Python code for quicksort, automatically enclosed within a properly formatted code block. The stop
parameter ensures a clean code output without any extra text. You can compare this to the standard Multi-round Conversation API flow, and see the added benefits.
Chat Prefix Completion is just one of the many powerful features offered by DeepSeek's API. Check out the FIM Completion (Beta) feature for another way to extend DeepSeek's functionality. For more information and updates: