Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
本页涵盖工具调用生命周期:从 Claude 的响应中读取 tool_use 块、在您的回复中格式化 tool_result 块,以及发出错误信号。有关自动处理此问题的 SDK 抽象,请参阅 Tool Runner。
使用 Tool Runner 更简单:本页面描述的手动工具处理由 Tool Runner 自动管理。当您需要对工具执行进行自定义控制时,请使用本页面。
Claude 的响应因其使用客户端工具还是服务器工具而异。
响应将具有 tool_use 的 stop_reason 和一个或多个 tool_use 内容块,其中包括:
id:此特定工具使用块的唯一标识符。这将用于稍后匹配工具结果。name:正在使用的工具的名称。input:包含传递给工具的输入的对象,符合工具的 input_schema。当您收到客户端工具的工具使用响应时,您应该:
tool_use 块中提取 name、id 和 input。input。role 为 user,content 块包含 tool_result 类型和以下信息:
tool_use_id:此结果所针对的工具使用请求的 id。content:工具的结果,可以是字符串(例如,"content": "15 degrees")、嵌套内容块列表(例如,"content": [{"type": "text", "text": "15 degrees"}])或文档块列表(例如,)。这些内容块可以使用 、 或 类型。重要的格式化要求:
例如,这将导致 400 错误:
{
"role": "user",
"content": [
{ "type": "text", "text": "Here are the results:" }, // ❌ tool_result 之前的文本
{ "type": "tool_result", "tool_use_id": "toolu_01" /* ... */ }
]
}收到工具结果后,Claude 将使用该信息继续生成对原始用户提示的响应。
Claude 在内部执行工具,并将结果直接合并到其响应中,无需额外的用户交互。
与其他 API 的区别
与分离工具使用或使用特殊角色(如 tool 或 function)的 API 不同,Claude API 将工具直接集成到 user 和 assistant 消息结构中。
消息包含 text、image、tool_use 和 tool_result 块的数组。user 消息包括客户端内容和 tool_result,而 assistant 消息包含 AI 生成的内容和 tool_use。
使用 Claude 的工具时可能会发生几种不同类型的错误:
Was this page helpful?
"content": [{"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "15 degrees"}}]textimagedocumentis_error(可选):如果工具执行导致错误,设置为 true。这是正确的:
{
"role": "user",
"content": [
{ "type": "tool_result", "tool_use_id": "toolu_01" /* ... */ },
{ "type": "text", "text": "What should I do next?" } // ✅ tool_result 之后的文本
]
}如果您收到类似"tool_use ids were found without tool_result blocks immediately after"的错误,请检查您的工具结果是否格式正确。