Was this page helpful?
本頁涵蓋工具呼叫生命週期:從 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 的工具時可能會發生幾種不同類型的錯誤:
"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」的錯誤,請檢查您的工具結果是否格式化正確。