模块二 原生API调用——多轮对话与上下文管理
模块二:原生API调用——多轮对话与上下文管理(Day 2-4)
2.1 理解ChatCompletion的消息结构
DeepSeek的Chat Completions API与OpenAI格式完全一致,采用无状态设计。多轮对话的核心是手动维护 messages 列表,每轮将完整历史发送给模型。
messages 的角色与OpenAI相同:
| 角色 | 含义 |
|---|---|
system |
设定模型的行为准则和身份 |
user |
用户输入 |
assistant |
模型回复 |
2.2 基础API调用
response = client.chat.completions.create(
model="deepseek-v4-pro",
messages=[
{"role": "system", "content": "你是一个简洁的技术助手。"},
{"role": "user", "content": "什么是列表推导式?"}
]
)
print(response.choices[0].message.content)
2.3 DeepSeek特有参数:思考模式
DeepSeek V4 Pro支持通过 extra_body 控制思考模式,这是与OpenAI API的主要区别之一:
response = client.chat.completions.create(
model="deepseek-v4-pro",
messages=[...],
extra_body={
"thinking": {"type": "enabled"},
"reasoning_effort": "high" # 可选 low / high / max
}
)
thinking.type:设为"enabled"开启思考模式,设为"disabled"关闭reasoning_effort:控制推理深度。low适合简单问答;high适合日常Agent任务和中等复杂度推理;max适合高度复杂场景
开启思考模式后,响应中会包含 reasoning_content 字段,记录模型的思考过程,可以与最终回复分开处理。
2.4 手动管理对话历史
核心模式:每轮对话后将用户消息和模型回复追加到 history,下一轮发送完整 history。
history = [
{"role": "system", "content": "你是一个友好的技术助手。"}
]
def chat(user_input, thinking=False):
history.append({"role": "user", "content": user_input})
kwargs = {}
if thinking:
kwargs["extra_body"] = {"thinking": {"type": "enabled"}, "reasoning_effort": "high"}
response = client.chat.completions.create(
model="deepseek-v4-pro",
messages=history,
**kwargs
)
assistant_reply = response.choices[0].message.content
history.append({"role": "assistant", "content": assistant_reply})
return assistant_reply
print(chat("Python中如何读取文件?"))
print(chat("那如果是大文件呢?")) # 模型保持上下文
print(chat("json格式的文件也一样吗?"))
关键理解:
- DeepSeek的
response.choices[0].message对象可直接append到history,包含role、content等字段 - 每次请求发送不断增长的完整历史,Token消耗随轮次线性增长
- DeepSeek V4 Pro上下文窗口达100万Token,可承载长对话历史,但需注意成本
2.5 实现交互式对话循环
history = [{"role": "system", "content": "你是一个有帮助的助手。"}]
print("输入 'quit' 退出,输入 '/think' 切换思考模式")
thinking = False
while True:
user_input = input("\n你: ")
if user_input.lower() == "quit":
break
if user_input.lower() == "/think":
thinking = not thinking
print(f"思考模式: {'开启' if thinking else '关闭'}")
continue
history.append({"role": "user", "content": user_input})
kwargs = {}
if thinking:
kwargs["extra_body"] = {"thinking": {"type": "enabled"}, "reasoning_effort": "high"}
response = client.chat.completions.create(
model="deepseek-v4-pro",
messages=history,
**kwargs
)
reply = response.choices[0].message.content
history.append({"role": "assistant", "content": reply})
print(f"\n助手: {reply}")
2.6 完成标准
- 能解释
messages列表结构和角色作用 - 能实现多轮记忆对话程序
- 能说明DeepSeek思考模式的启用方式和
reasoning_effort的三档含义
2.7 代码
https://gitcode.com/chzhang16/LangChainLearning/blob/master/phase 1/example2.py

浙公网安备 33010602011771号