Skip to content

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_callsassistant 消息之后必须紧跟对应的 tool 消息
  • 不能跳过任何一轮的 assistant 回复直接接 user
  • 历史消息中的 assistant content 可以为 null(有 tool_calls 时)

来源Issue #878 - deepseek-ai/DeepSeek-V3