選擇模型

一般來說,對於複雜工具和模糊查詢,請使用 Claude Opus 4、Claude Sonnet 4、Claude Sonnet 3.7、Claude Sonnet 3.5 或 Claude Opus 3;它們能更好地處理多個工具,並在需要時尋求澄清。

對於簡單直接的工具,可以使用 Claude Haiku 3.5 或 Claude Haiku 3,但請注意它們可能會推斷缺失的參數。

如果使用 Claude Sonnet 3.7 進行工具使用和延伸思考,請參考我們的指南 這裡 獲取更多信息。

指定客戶端工具

客戶端工具(包括 Anthropic 定義和用戶定義的工具)在 API 請求的頂層參數 tools 中指定。每個工具定義包括:

參數描述
name工具的名稱。必須符合正則表達式 ^[a-zA-Z0-9_-]{1,64}$
description詳細的純文本描述,說明工具的功能、應該何時使用以及其行為方式。
input_schema一個 JSON Schema 對象,定義工具預期的參數。

工具使用系統提示

當您使用 tools 參數調用 Anthropic 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 的最佳性能,請遵循以下指導原則:

  • 提供極其詳細的描述。 這是影響工具性能的最重要因素。您的描述應該解釋有關工具的每個細節,包括:
    • 工具的功能
    • 何時應該使用(以及何時不應該使用)
    • 每個參數的含義及其如何影響工具的行為
    • 任何重要的注意事項或限制,例如如果工具名稱不明確,該工具不會返回哪些信息。您能給 Claude 提供的關於工具的上下文越多,它就越能更好地決定何時以及如何使用它們。每個工具描述至少應有 3-4 個句子,如果工具複雜,則需要更多。
  • 優先考慮描述而非示例。 雖然您可以在工具描述或附帶的提示中包含如何使用工具的示例,但這比清晰全面地解釋工具的目的和參數要次要。只有在您完全充實了描述之後才添加示例。

良好的描述清楚地解釋了工具的功能、何時使用它、它返回什麼數據以及 ticker 參數的含義。較差的描述過於簡短,讓 Claude 對工具的行為和用法產生許多疑問。

控制 Claude 的輸出

強制使用工具

在某些情況下,您可能希望 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 設置為 anytool 時,我們會預填助手消息以強制使用工具。這意味著即使明確要求,模型也不會在 tool_use 內容塊之前發出思維鏈 text 內容塊。

我們的測試表明,這不應該降低性能。如果您希望保持思維鏈(特別是使用 Opus)同時仍然要求模型使用特定工具,您可以為 tool_choice 使用 {"type": "auto"} (默認值),並在 user 消息中添加明確的指示。例如:What's the weather like in London? Use the get_weather tool in your response.

JSON 輸出

工具不一定需要是客戶端函數 — 您可以在任何時候使用工具,只要您希望模型返回遵循提供的模式的 JSON 輸出。例如,您可能使用具有特定模式的 record_summary 工具。有關完整的工作示例,請參見工具使用示例

思維鏈

使用工具時,Claude 通常會顯示其”思維鏈”,即它用來分解問題並決定使用哪些工具的逐步推理。如果 tool_choice 設置為 auto(這是默認值,請參見強制使用工具),Claude Opus 3 模型會這樣做,而 Sonnet 和 Haiku 可以通過提示來實現這一點。

例如,給定提示”What’s the weather like in San Francisco right now, and what time is it there?”,Claude 可能會回應:

JSON
{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "<thinking>To answer this question, I will: 1. Use the get_weather tool to get the current weather in San Francisco. 2. Use the get_time tool to get the current time in the America/Los_Angeles timezone, which covers San Francisco, CA.</thinking>"
    },
    {
      "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lq9",
      "name": "get_weather",
      "input": {"location": "San Francisco, CA"}
    }
  ]
}

這種思維鏈提供了對 Claude 推理過程的洞察,可以幫助您調試意外行為。

對於 Claude Sonnet 3 模型,默認情況下思維鏈不太常見,但您可以通過在用戶消息或系統提示中添加類似 "Before answering, explain your reasoning step-by-step in tags." 的內容來提示 Claude 顯示其推理過程。

重要的是要注意,雖然 <thinking> 標籤是 Claude 用來表示其思維鏈的常見約定,但確切的格式(例如這個 XML 標籤的名稱)可能會隨時間而變化。您的代碼應該將思維鏈視為任何其他助手生成的文本,而不依賴於 <thinking> 標籤的存在或特定格式。

並行工具使用

默認情況下,Claude 可能會使用多個工具來回答用戶查詢。您可以通過以下方式禁用此行為:

  • 當 tool_choice 類型為 auto 時設置 disable_parallel_tool_use=true,這確保 Claude 最多使用一個工具
  • 當 tool_choice 類型為 anytool 時設置 disable_parallel_tool_use=true,這確保 Claude 恰好使用一個工具

Claude Sonnet 3.7 的並行工具使用

即使您沒有設置 disable_parallel_tool_use,Claude Sonnet 3.7 在回應中可能不太可能進行並行工具調用。為了解決這個問題,我們建議啟用令牌高效工具使用,這有助於鼓勵 Claude 使用並行工具。這個測試版功能還可以減少延遲,並平均節省 14% 的輸出令牌。

如果您不想選擇加入令牌高效工具使用測試版,您也可以引入一個”批處理工具”,作為元工具來同時包裝對其他工具的調用。我們發現,如果存在這個工具,模型將使用它為您同時並行調用多個工具。

有關如何使用此解決方法的示例,請參見我們的 cookbook 中的這個示例

處理工具使用和工具結果內容塊

Claude 的回應根據它使用的是客戶端工具還是服務器工具而有所不同。

處理客戶端工具的結果

回應將有一個 stop_reasontool_use 和一個或多個 tool_use 內容塊,包括:

  • id:此特定工具使用塊的唯一標識符。這將用於稍後匹配工具結果。
  • name:正在使用的工具的名稱。
  • input:包含傳遞給工具的輸入的對象,符合工具的 input_schema

當您收到客戶端工具的工具使用回應時,您應該:

  1. tool_use 塊中提取 nameidinput
  2. 運行您代碼庫中與該工具名稱對應的實際工具,傳入工具 input
  3. 通過發送一個 roleuser 的新消息繼續對話,並包含一個包含 tool_result 類型的 content 塊和以下信息:
    • tool_use_id:這是結果對應的工具使用請求的 id
    • content:工具的結果,作為字符串(例如 "content": "15 degrees")或嵌套內容塊列表(例如 "content": [{"type": "text", "text": "15 degrees"}])。這些內容塊可以使用 textimage 類型。
    • is_error(可選):如果工具執行導致錯誤,則設置為 true

在收到工具結果後,Claude 將使用該信息繼續生成對原始用戶提示的回應。

處理服務器工具的結果

Claude 在內部執行工具並直接將結果納入其回應,無需額外的用戶交互。

與其他 API 的區別

與分離工具使用或使用特殊角色如 toolfunction 的 API 不同,Anthropic 的 API 將工具直接集成到 userassistant 消息結構中。

消息包含 textimagetool_usetool_result 塊的數組。user 消息包括客戶端內容和 tool_result,而 assistant 消息包含 AI 生成的內容和 tool_use

處理 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 時:

  • 繼續對話:在後續請求中按原樣傳回暫停的回應,讓 Claude 繼續其回合
  • 如需要可修改:如果您想中斷或重定向對話,可以選擇在繼續之前修改內容
  • 保留工具狀態:在繼續請求中包含相同的工具,以維持功能

故障排除錯誤

使用 Claude 的工具時可能會出現幾種不同類型的錯誤: