Appearance
DeepSeek V3 有历史消息时 Function Call 不触发
问题
调用 DeepSeek /chat/completions 接口时,messages 数组中包含多条历史消息,function call 无法触发,模型直接返回文本回复。但如果 messages 只有一条消息,function call 正常触发。
根因
DeepSeek API 对 messages 的顺序和角色排列高度敏感。多轮对话中如果消息顺序不严格符合 user → assistant → user 的交替模式,模型会"困惑"并跳过 function call。
常见错误场景:
- 连续两条
user消息 assistant消息后面接system消息tool_result/function消息的位置不正确
解决方案
确保 messages 严格交替排列:
python
messages = [
{"role": "system", "content": "You are a helpful assistant with tools."},
{"role": "user", "content": "第一个问题"},
{
"role": "assistant",
"content": None,
"tool_calls": [{
"id": "call_1",
"type": "function",
"function": {"name": "get_weather", "arguments": '{"city":"Beijing"}'}
}]
},
{
"role": "tool",
"tool_call_id": "call_1",
"content": '{"temperature": 20}'
},
{"role": "assistant", "content": "北京今天气温 20°C"},
{"role": "user", "content": "第二个问题"} # ← 下一轮的 user 消息放最后
]关键要点:
tool_calls的assistant消息之后必须紧跟对应的tool消息- 不能跳过任何一轮的
assistant回复直接接user - 历史消息中的
assistantcontent 可以为null(有 tool_calls 时)