平台支持 DeepSeek /chat/completions API 进行多轮对话。该 API 为“无状态” API,所以服务端不记录用户请求的上下文,所以用户在每次请求时,需将之前的所有对话历史进行拼接,并传递给对话 API。

以 Python 语言为例,展示如何进行上下文拼接,实现多轮对话。

from openai import OpenAI
client = OpenAI(api_key='sk-xxxxxxxxxx', base_url='https://openapi.coreshub.cn/v1')

# Round 1
messages = [{"role": "user", "content": "What's the highest mountain in the world?"}]
response = client.chat.completions.create(
    model="DeepSeek-V3",
    messages=messages
)

messages.append(response.choices[0].message)
print(f"Messages Round 1: {messages}")

# Round 2
messages.append({"role": "user", "content": "What is the second?"})
response = client.chat.completions.create(
    model="DeepSeek-V3",
    messages=messages
)

messages.append(response.choices[0].message)
print(f"Messages Round 2: {messages}")

示例中,第一轮对话请求中,传递给 API 的 messages 内容为:

[
    {"role": "user", "content": "What's the highest mountain in the world?"}
]

在第二轮请求中,需将第一轮中模型输出添加至 messages 末尾,并将新的提问添加至 messages 末尾,故最终传递给 API 的 messages 内容为:

[
    {"role": "user", "content": "What's the highest mountain in the world?"},
    {"role": "assistant", "content": "The highest mountain in the world is Mount Everest."},
    {"role": "user", "content": "What is the second?"}
]