多轮聊天的历史应该存在哪里,怎样发给 DeepSeek?
查看完整题解
参考回答
直接回答
在应用侧按会话存消息。每次调用先写稳定的规则,再拼最近的问答、重要摘要和本轮用户消息。按时间保留角色,单独核对工具回合需要的字段。
讲清原理
长会话先留可核对的事实和用户已经确认的约束,再裁掉可重建的细节。摘要经常需要刷新,关键名称、日期和单位应有原消息来源。服务端还要验证当前用户可以访问该会话。
例子与易错点
下面拼接两轮示例,核对系统规则、历史和新问题的顺序。带工具的思考模式需按对应文档保留相关字段。
import json
import httpx
from openai import OpenAI
events = []
def fake_service(request):
body = json.loads(request.content)
events.append((request, body))
return httpx.Response(200, json={
"id": "local-chat", "object": "chat.completion", "created": 0,
"model": body["model"], "choices": [{
"index": 0, "finish_reason": "stop",
"message": {"role": "assistant", "content": "收到"},
}],
})
with OpenAI(api_key="local-test-key", base_url="https://api.deepseek.com",
http_client=httpx.Client(transport=httpx.MockTransport(fake_service)),
max_retries=0) as client:
history = [
{"role": "user", "content": "把每周报表按部门统计"},
{"role": "assistant", "content": "可以,先用本周数据。"},
]
messages = [{"role": "system", "content": "保留已确认的统计口径"}]
messages.extend(history)
messages.append({"role": "user", "content": "补上上周的对照。"})
client.chat.completions.create(model="deepseek-flash", messages=messages)
_, body = events[0]
assert body["messages"] == messages
assert body["messages"][1:3] == history
assert body["messages"][-1]["content"] == "补上上周的对照。"
print("the new request preserved the agreed scope and both historical messages")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。