Skip to content

DeepSeek Anthropic API 并行 tool use 返回 400 错误

问题

使用 Anthropic Python SDK 连接 DeepSeek 的 Anthropic 兼容端点,当对话中包含并行 tool call(一次返回多个 tool_use)时,提交 tool_result 时报 400 错误:

anthropic.BadRequestError: Error code: 400 - 
'tool_use' ids were found without 'tool_result' blocks immediately after: call_1_xxx

根因

Anthropic 官方 API 和 DeepSeek 兼容端点对并行 tool result 的解析逻辑不同:

  • Anthropic 官方:只检查最后一个 tool_use 块是否有对应的 tool_result
  • DeepSeek 兼容端点:检查所有 tool_use 块,每一个都必须有紧随其后的 tool_result

解决方案

确保每个并行 tool_use 都有对应的 tool_result,且放在同一个消息块内:

python
# 假设模型并行调用了两个工具
tool_calls = response.content  # [tool_use(id=call_1), tool_use(id=call_2)]

# 正确做法:在同一条 user 消息里包含所有 tool_result
messages.append({
    "role": "user",
    "content": [
        {
            "type": "tool_result",
            "tool_use_id": "call_1",
            "content": "工具1的结果"
        },
        {
            "type": "tool_result", 
            "tool_use_id": "call_2",
            "content": "工具2的结果"
        }
    ]
})

# 错误做法:分开两条消息
# messages.append({"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", ...}]})
# messages.append({"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_2", ...}]})

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