聊天越聊越长,对话历史怎样管理?
查看完整题解
参考回答
直接回答
应用可以自行存历史,也可以在支持的接口使用会话状态。每次请求要保持角色顺序。历史变长时,保留当前任务的近期问答、已确认约束和可核对事实,再删掉无关细节。
讲清原理
明确区分原文和摘要。关键订单号、权限或用户确认要回到业务记录。不要把整个历史跨用户复用,也不能寄希望于摘要长期不失真。
例子与易错点
下面组装一次新请求,核对开发者规则、旧问答和本轮问题处在约定位置。
import json
import httpx
from openai import OpenAI
requests = []
def serve(request):
body = json.loads(request.content)
requests.append((request, body))
return httpx.Response(200, json={
"id": "local-demo", "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.openai.com/v1",
http_client=httpx.Client(transport=httpx.MockTransport(serve))) as client:
messages = [
{"role": "developer", "content": "期限要保留单位和依据"},
{"role": "user", "content": "查 X2 的报修期"},
{"role": "assistant", "content": "请提供手册版本"},
{"role": "user", "content": "使用第三版手册"},
]
client.chat.completions.create(model="gpt-6.2-sol", messages=messages)
_, body = requests[0]
assert body["messages"] == messages
assert body["messages"][-1]["content"] == "使用第三版手册"
print("the new request kept the historical roles and the current clarification")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。