我們建議使用最新的 Claude Opus (4.6) 模型來處理複雜工具和模糊查詢;它能更好地處理多個工具,並在需要時尋求澄清。
對於簡單的工具,可以使用 Claude Haiku 模型,但請注意它可能會推斷缺失的參數。
如果將 Claude 與工具使用和延伸思考一起使用,請參閱我們的指南此處以獲取更多資訊。
客戶端工具(包括 Anthropic 定義的和使用者定義的)在 API 請求的 tools 頂層參數中指定。每個工具定義包括:
| 參數 | 描述 |
|---|---|
name | 工具的名稱。必須匹配正則表達式 ^[a-zA-Z0-9_-]{1,64}$。 |
description | 工具功能、使用時機和行為方式的詳細純文字描述。 |
input_schema | 一個 JSON Schema 物件,定義工具的預期參數。 |
input_examples | (可選,beta)一個範例輸入物件的陣列,幫助 Claude 理解如何使用工具。請參閱提供工具使用範例。 |
當您使用 tools 參數呼叫 Claude API 時,我們會從工具定義、工具配置和任何使用者指定的系統提示構建一個特殊的系統提示。構建的提示旨在指示模型使用指定的工具,並為工具正常運作提供必要的上下文:
In this environment you have access to a set of tools you can use to answer the user's question.
{{ FORMATTING INSTRUCTIONS }}
String and scalar parameters should be specified as is, while lists and objects should use JSON format. Note that spaces for string values are not stripped. The output is not expected to be valid XML and is parsed with regular expressions.
Here are the functions available in JSONSchema format:
{{ TOOL DEFINITIONS IN JSON SCHEMA }}
{{ USER SYSTEM PROMPT }}
{{ TOOL CONFIGURATION }}為了在使用工具時從 Claude 獲得最佳效能,請遵循以下指南:
input_examples。 清晰的描述最為重要,但對於具有複雜輸入、巢狀物件或格式敏感參數的工具,您可以使用 input_examples 欄位(beta)來提供經過 schema 驗證的範例。詳情請參閱提供工具使用範例。良好的描述清楚地解釋了工具的功能、使用時機、返回的資料以及 ticker 參數的含義。不良的描述過於簡短,讓 Claude 對工具的行為和用法有許多未解答的問題。
您可以提供有效工具輸入的具體範例,幫助 Claude 更有效地理解如何使用您的工具。這對於具有巢狀物件、可選參數或格式敏感輸入的複雜工具特別有用。
工具使用範例是 beta 功能。請為您的提供者包含適當的 beta 標頭:
| 提供者 | Beta 標頭 | 支援的模型 |
|---|---|---|
| Claude API, Microsoft Foundry | advanced-tool-use-2025-11-20 | 所有模型 |
| Vertex AI, Amazon Bedrock | tool-examples-2025-10-29 | Claude Opus 4.6, Claude Opus 4.5 |
在您的工具定義中添加一個可選的 input_examples 欄位,包含一個範例輸入物件的陣列。每個範例必須根據工具的 input_schema 有效:
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
betas=["advanced-tool-use-2025-11-20"],
tools=[
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The unit of temperature"
}
},
"required": ["location"]
},
"input_examples": [
{
"location": "San Francisco, CA",
"unit": "fahrenheit"
},
{
"location": "Tokyo, Japan",
"unit": "celsius"
},
{
"location": "New York, NY" # 'unit' is optional
}
]
}
],
messages=[
{"role": "user", "content": "What's the weather like in San Francisco?"}
]
)範例會與您的工具 schema 一起包含在提示中,向 Claude 展示格式正確的工具呼叫的具體模式。這有助於 Claude 理解何時包含可選參數、使用什麼格式以及如何構建複雜輸入。
input_schema 有效。無效的範例會返回 400 錯誤工具執行器提供了一個開箱即用的解決方案,用於使用 Claude 執行工具。工具執行器不需要手動處理工具呼叫、工具結果和對話管理,而是自動:
我們建議您在大多數工具使用實作中使用工具執行器。
工具執行器目前處於 beta 階段,可在 Python、TypeScript 和 Ruby SDK 中使用。
使用壓縮的自動上下文管理
工具執行器支援自動壓縮,當 token 使用量超過閾值時會生成摘要。這允許長時間運行的代理任務超越上下文視窗限制繼續執行。
使用 SDK 輔助工具定義工具,然後使用工具執行器來執行它們。
工具函式必須返回一個內容區塊或內容區塊陣列,包括文字、圖片或文件區塊。這允許工具返回豐富的多模態回應。返回的字串將被轉換為文字內容區塊。如果您想向 Claude 返回結構化的 JSON 物件,請在返回之前將其編碼為 JSON 字串。數字、布林值或其他非字串原始型別也必須轉換為字串。
工具執行器是一個可迭代物件,會產生來自 Claude 的訊息。這通常被稱為「工具呼叫迴圈」。每次迭代時,執行器會檢查 Claude 是否請求了工具使用。如果是,它會呼叫工具並自動將結果發送回 Claude,然後產生 Claude 的下一條訊息以繼續您的迴圈。
您可以在任何迭代中使用 break 語句結束迴圈。執行器會持續迴圈直到 Claude 返回一條不包含工具使用的訊息。
如果您不需要中間訊息,可以直接獲取最終訊息:
在迴圈中,您可以完全自訂工具執行器對 Messages API 的下一個請求。執行器會自動將工具結果附加到訊息歷史中,因此您不需要手動管理它們。您可以選擇性地檢查工具結果以進行日誌記錄或除錯,並在下一次 API 呼叫之前修改請求參數。
當工具拋出異常時,工具執行器會捕獲它並將錯誤作為帶有 is_error: true 的工具結果返回給 Claude。預設情況下,只包含異常訊息,不包含完整的堆疊追蹤。
要查看完整的堆疊追蹤和除錯資訊,請設定 ANTHROPIC_LOG 環境變數:
# View info-level logs including tool errors
export ANTHROPIC_LOG=info
# View debug-level logs for more verbose output
export ANTHROPIC_LOG=debug啟用後,SDK 會記錄完整的異常詳情(使用 Python 的 logging 模組、TypeScript 的 console 或 Ruby 的 logger),包括工具失敗時的完整堆疊追蹤。
預設情況下,工具錯誤會傳回給 Claude,然後 Claude 可以做出適當的回應。但是,您可能想要偵測錯誤並以不同方式處理它們——例如,提前停止執行或實作自訂錯誤處理。
使用工具回應方法來攔截工具結果,並在它們發送給 Claude 之前檢查錯誤:
您可以在工具結果發送回 Claude 之前修改它們。這對於添加元資料(如 cache_control)以啟用工具結果的提示快取,或轉換工具輸出非常有用。
使用工具回應方法來獲取工具結果,修改它,然後將修改後的版本添加到訊息中:
當工具返回大量資料(如文件搜尋結果)且您希望為後續 API 呼叫快取這些資料時,向工具結果添加 cache_control 特別有用。有關快取策略的更多詳情,請參閱提示快取。
啟用串流以在事件到達時接收它們。每次迭代會產生一個串流物件,您可以迭代它以獲取事件。
SDK 工具執行器處於 beta 階段。本文件的其餘部分涵蓋手動工具實作。
在某些情況下,您可能希望 Claude 使用特定工具來回答使用者的問題,即使 Claude 認為它可以在不使用工具的情況下提供答案。您可以透過在 tool_choice 欄位中指定工具來實現這一點,如下所示:
tool_choice = {"type": "tool", "name": "get_weather"}使用 tool_choice 參數時,我們有四個可能的選項:
auto 允許 Claude 決定是否呼叫任何提供的工具。這是提供 tools 時的預設值。any 告訴 Claude 它必須使用提供的工具之一,但不強制使用特定工具。tool 允許我們強制 Claude 始終使用特定工具。none 防止 Claude 使用任何工具。這是未提供 tools 時的預設值。使用提示快取時,對 tool_choice 參數的更改將使快取的訊息區塊失效。工具定義和系統提示仍保持快取,但訊息內容必須重新處理。
此圖說明了每個選項的工作方式:

請注意,當您將 tool_choice 設為 any 或 tool 時,我們會預填助手訊息以強制使用工具。這意味著模型不會在 tool_use 內容區塊之前發出自然語言回應或解釋,即使被明確要求這樣做。
使用延伸思考搭配工具使用時,不支援 tool_choice: {"type": "any"} 和 tool_choice: {"type": "tool", "name": "..."},將會導致錯誤。只有 tool_choice: {"type": "auto"}(預設值)和 tool_choice: {"type": "none"} 與延伸思考相容。
我們的測試顯示這不應降低效能。如果您希望模型在仍然要求模型使用特定工具的同時提供自然語言上下文或解釋,您可以將 tool_choice 使用 {"type": "auto"}(預設值),並在 user 訊息中添加明確的指示。例如:What's the weather like in London? Use the get_weather tool in your response.
使用嚴格工具保證工具呼叫
將 tool_choice: {"type": "any"} 與嚴格工具使用結合使用,以保證您的工具之一將被呼叫,並且工具輸入嚴格遵循您的結構描述。在您的工具定義上設定 strict: true 以啟用結構描述驗證。
工具不一定需要是客戶端函式——您可以在任何時候希望模型返回遵循提供的結構描述的 JSON 輸出時使用工具。例如,您可能使用具有特定結構描述的 record_summary 工具。請參閱使用 Claude 的工具以獲取完整的工作範例。
使用工具時,Claude 通常會在呼叫工具之前評論它正在做什麼或自然地回應使用者。
例如,給定提示「What's the weather like in San Francisco right now, and what time is it there?」,Claude 可能會回應:
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "I'll help you check the current weather and time in San Francisco."
},
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "get_weather",
"input": {"location": "San Francisco, CA"}
}
]
}這種自然的回應風格幫助使用者了解 Claude 正在做什麼,並創造更具對話性的互動。您可以透過系統提示和在提示中提供 <examples> 來引導這些回應的風格和內容。
重要的是要注意,Claude 在解釋其操作時可能會使用各種措辭和方法。您的程式碼應將這些回應視為任何其他助手生成的文字,而不依賴特定的格式慣例。
預設情況下,Claude 可能會使用多個工具來回答使用者的查詢。您可以透過以下方式停用此行為:
auto 時設定 disable_parallel_tool_use=true,這確保 Claude 最多使用一個工具any 或 tool 時設定 disable_parallel_tool_use=true,這確保 Claude 恰好使用一個工具雖然 Claude 4 模型預設具有出色的平行工具使用能力,但您可以透過有針對性的提示來增加所有模型平行工具執行的可能性:
Claude Sonnet 3.7 的平行工具使用
Claude Sonnet 3.7 在回應中進行平行工具呼叫的可能性可能較低,即使您沒有設定 disable_parallel_tool_use。我們建議升級到 Claude 4 模型,這些模型具有內建的 token 高效工具使用和改進的平行工具呼叫。
如果您仍在使用 Claude Sonnet 3.7,您可以啟用 token-efficient-tools-2025-02-19 beta 標頭,這有助於鼓勵 Claude 使用平行工具。您也可以引入一個「批次工具」,作為元工具來同時包裝對其他工具的呼叫。
請參閱我們 cookbook 中的此範例了解如何使用此解決方法。
使用 Tool runner 更簡單:本節描述的手動工具處理由 tool runner 自動管理。當您需要自訂控制工具執行時,請使用本節。
Claude 的回應會根據它使用的是客戶端工具還是伺服器工具而有所不同。
回應將具有 tool_use 的 stop_reason 和一個或多個 tool_use 內容區塊,其中包括:
id:此特定工具使用區塊的唯一識別碼。這將用於稍後匹配工具結果。name:正在使用的工具名稱。input:包含傳遞給工具的輸入的物件,符合工具的 input_schema。當您收到客戶端工具的工具使用回應時,您應該:
tool_use 區塊中提取 name、id 和 input。input。role 為 user 的新訊息來繼續對話,其中包含 tool_result 類型的 content 區塊和以下資訊:
tool_use_id:這是結果所對應的工具使用請求的 id。content:工具的結果,可以是字串(例如 "content": "15 degrees")、巢狀內容區塊列表(例如 "content": [{"type": "text", "text": "15 degrees"}])或文件區塊列表(例如 "content": ["type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "15 degrees"}])。這些內容區塊可以使用 text、image 或 document 類型。is_error(可選):如果工具執行導致錯誤,則設為 true。重要的格式要求:
例如,這將導致 400 錯誤:
{"role": "user", "content": [
{"type": "text", "text": "Here are the results:"}, // ❌ Text before tool_result
{"type": "tool_result", "tool_use_id": "toolu_01", ...}
]}這是正確的:
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "toolu_01", ...},
{"type": "text", "text": "What should I do next?"} // ✅ Text after tool_result
]}如果您收到類似「tool_use ids were found without tool_result blocks immediately after」的錯誤,請檢查您的工具結果格式是否正確。
收到工具結果後,Claude 將使用該資訊繼續生成對原始使用者提示的回應。
Claude 在內部執行工具並將結果直接納入其回應中,無需額外的使用者互動。
與其他 API 的差異
與分離工具使用或使用特殊角色(如 tool 或 function)的 API 不同,Claude API 將工具直接整合到 user 和 assistant 訊息結構中。
訊息包含 text、image、tool_use 和 tool_result 區塊的陣列。user 訊息包含客戶端內容和 tool_result,而 assistant 訊息包含 AI 生成的內容和 tool_use。
max_tokens 停止原因如果 Claude 的回應因達到 max_tokens 限制而被截斷,且截斷的回應包含不完整的工具使用區塊,您需要使用更高的 max_tokens 值重試請求以獲取完整的工具使用。
# Check if response was truncated during tool use
if response.stop_reason == "max_tokens":
# Check if the last content block is an incomplete tool_use
last_block = response.content[-1]
if last_block.type == "tool_use":
# Send the request with higher max_tokens
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096, # Increased limit
messages=messages,
tools=tools
)pause_turn 停止原因使用伺服器工具(如網路搜尋)時,API 可能會返回 pause_turn 停止原因,表示 API 已暫停了一個長時間執行的回合。
以下是如何處理 pause_turn 停止原因:
import anthropic
client = anthropic.Anthropic()
# Initial request with web search
response = client.messages.create(
model="claude-3-7-sonnet-latest",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Search for comprehensive information about quantum computing breakthroughs in 2025"
}
],
tools=[{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 10
}]
)
# Check if the response has pause_turn stop reason
if response.stop_reason == "pause_turn":
# Continue the conversation with the paused content
messages = [
{"role": "user", "content": "Search for comprehensive information about quantum computing breakthroughs in 2025"},
{"role": "assistant", "content": response.content}
]
# Send the continuation request
continuation = client.messages.create(
model="claude-3-7-sonnet-latest",
max_tokens=1024,
messages=messages,
tools=[{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 10
}]
)
print(continuation)
else:
print(response)處理 pause_turn 時:
內建錯誤處理:Tool runner 為大多數常見場景提供自動錯誤處理。本節涵蓋進階使用案例的手動錯誤處理。
使用 Claude 的工具時可能會發生幾種不同類型的錯誤:
Was this page helpful?