400

tool 结果对不上:unexpected tool_use_id found in tool_result blocks

你回传了一个工具执行结果,但前一条 assistant 消息里没有对应 ID 的工具调用。

报错原文2026-10-23 实测

直接发了一条 role=tool 的消息,前面没有对应的工具调用
{
  "error": {
    "message": "the upstream rejected this request as invalid (our request id: <请求ID>) — upstream said: messages.0.content.2: unexpected `tool_use_id` found in `tool_result` blocks: call_123. Each `tool_result` block must have a corresponding `tool_use` block in the previous message.; retrying the same payload will fail the same way — check the payload (most often a tool/function JSON Schema the upstream rejects). quote OUR request id to support",
    "type": "invalid_request_error",
    "param": null,
    "code": "upstream_rejected_request"
  }
}

原因

工具调用要成对出现:assistant 消息里带 tool_calls(每个有一个 id),紧接着用 role=tool 的消息回传结果,tool_call_id 必须等于那个 id。

我们直接发了一条 tool 消息(tool_call_id 是随便写的 call_123),前面没有 assistant 的调用,Claude 的上游就拒绝了。常见的真实场景是:裁剪对话历史时,把 assistant 的 tool_calls 那条删了,tool 结果却留着。

排查步骤

  1. 确认 tool 消息的前一条是带 tool_calls 的 assistant 消息。
  2. tool_call_id 原样使用模型返回的 id,不要自己生成。
  3. 裁剪历史时,把“assistant 调用 + tool 结果”当成一个整体,要删一起删。
  4. 一次返回多个 tool_calls 时,每个都要回传结果。

正确写法

messages += [
  {"role": "assistant", "content": None, "tool_calls": resp.choices[0].message.tool_calls},
  *[{"role": "tool", "tool_call_id": c.id, "content": run(c)} for c in resp.choices[0].message.tool_calls]
]