本指南將介紹如何使用 DeepSeek /chat/completions API 進(jìn)行多輪對話。
DeepSeek /chat/completions API 是一個“無狀態(tài)” API,即服務(wù)端不記錄用戶請求的上下文,用戶在每次請求時,需將之前所有對話歷史拼接好后,傳遞給對話 API。
下面的代碼以 Python 語言,展示了如何進(jìn)行上下文拼接,以實現(xiàn)多輪對話。
from openai import OpenAI
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
# Round 1
messages = [{"role": "user", "content": "What's the highest mountain in the world?"}]
response = client.chat.completions.create(
model="deepseek-chat",
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-chat",
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?"}
]
在第二輪請求時:
最終傳遞給 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?"}
]
更多建議: