選擇模型

我們建議對複雜工具和模糊查詢使用最新的 Claude Sonnet (4.5) 或 Claude Opus (4.1) 模型;它們能更好地處理多個工具並在需要時尋求澄清。 對於直接的工具使用 Claude Haiku 模型,但請注意它們可能會推斷缺失的參數。
如果使用 Claude 進行工具使用和擴展思考,請參考我們的指南 此處 以獲取更多信息。

指定客戶端工具

客戶端工具(包括 Anthropic 定義的和用戶定義的)在 API 請求的 tools 頂級參數中指定。每個工具定義包括:
參數描述
name工具的名稱。必須符合正則表達式 ^[a-zA-Z0-9_-]{1,64}$
description工具功能、何時應使用以及其行為方式的詳細純文本描述。
input_schema定義工具預期參數的 JSON Schema 對象。
JSON
{
  "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, either 'celsius' or 'fahrenheit'"
      }
    },
    "required": ["location"]
  }
}
此工具名為 get_weather,期望輸入對象包含必需的 location 字符串和可選的 unit 字符串,該字符串必須是「celsius」或「fahrenheit」之一。

工具使用系統提示

當您使用 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 中獲得最佳性能,請遵循以下指南:
  • 提供極其詳細的描述。 這是迄今為止影響工具性能的最重要因素。您的描述應解釋有關工具的每個細節,包括:
    • 工具的功能
    • 何時應使用它(以及何時不應使用)
    • 每個參數的含義以及它如何影響工具的行為
    • 任何重要的注意事項或限制,例如如果工具名稱不清楚,工具不會返回什麼信息。您能為 Claude 提供的有關工具的上下文越多,它在決定何時以及如何使用它們時就會越好。每個工具描述至少應有 3-4 句話,如果工具複雜則更多。
  • 優先考慮描述而不是示例。 雖然您可以在工具描述或附帶提示中包含如何使用工具的示例,但這不如清晰全面的工具目的和參數說明重要。只有在完全充實描述後才添加示例。
JSON
{
  "name": "get_stock_price",
  "description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
  "input_schema": {
    "type": "object",
    "properties": {
      "ticker": {
        "type": "string",
        "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
      }
    },
    "required": ["ticker"]
  }
}
JSON
{
  "name": "get_stock_price",
  "description": "Gets the stock price for a ticker.",
  "input_schema": {
    "type": "object",
    "properties": {
      "ticker": {
        "type": "string"
      }
    },
    "required": ["ticker"]
  }
}
良好的描述清楚地解釋了工具的功能、何時使用、返回的數據以及 ticker 參數的含義。不佳的描述過於簡潔,讓 Claude 對工具的行為和使用方式有許多疑問。

工具運行器(測試版)

工具運行器為使用 Claude 執行工具提供了開箱即用的解決方案。工具運行器不是手動處理工具調用、工具結果和對話管理,而是自動:
  • 在 Claude 調用工具時執行工具
  • 處理請求/響應週期
  • 管理對話狀態
  • 提供類型安全性和驗證
我們建議您對大多數工具使用實現使用工具運行器。
工具運行器目前處於測試版,僅在 PythonTypeScript SDK 中可用。

基本用法

使用 @beta_tool 裝飾器定義工具,並使用 client.beta.messages.tool_runner() 執行它們。
如果您使用異步客戶端,請將 @beta_tool 替換為 @beta_async_tool 並使用 async def 定義函數。
import anthropic
import json
from anthropic import beta_tool

# Initialize client
client = anthropic.Anthropic()

# Define tools using the decorator
@beta_tool
def get_weather(location: str, unit: str = "fahrenheit") -> str:
    """Get the current weather in a given location.

    Args:
        location: The city and state, e.g. San Francisco, CA
        unit: Temperature unit, either 'celsius' or 'fahrenheit'
    """
    # In a full implementation, you'd call a weather API here
    return json.dumps({"temperature": "20°C", "condition": "Sunny"})

@beta_tool
def calculate_sum(a: int, b: int) -> str:
    """Add two numbers together.

    Args:
        a: First number
        b: Second number
    """
    return str(a + b)

# Use the tool runner
with client.beta.messages.tool_runner(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=[get_weather, calculate_sum],
    messages=[
        {"role": "user", "content": "What's the weather like in Paris? Also, what's 15 + 27?"}
    ]
) as runner:
    for message in runner:
        print(message.content[0].text)
裝飾的函數必須返回內容區塊或內容區塊數組,包括文本、圖像或文檔區塊。這允許工具返回豐富的多模態響應。返回的字符串將轉換為文本內容區塊。 如果您想向 Claude 返回結構化 JSON 對象,請在返回前將其編碼為 JSON 字符串。數字、布爾值或其他非字符串基元也必須轉換為字符串。@beta_tool 裝飾器將檢查函數參數和文檔字符串,以提取給定函數的 json 模式表示,在上面的示例中 calculate_sum 將轉換為:
{
  "name": "calculate_sum",
  "description": "Adds two integers together.",
  "input_schema": {
    "additionalProperties": false,
    "properties": {
      "left": {
        "description": "The first integer to add.",
        "title": "Left",
        "type": "integer"
      },
      "right": {
        "description": "The second integer to add.",
        "title": "Right",
        "type": "integer"
      }
    },
    "required": ["left", "right"],
    "type": "object"
  }
}
SDK 工具運行器處於測試版。本文檔的其餘部分涵蓋手動工具實現。

控制 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 參數的更改將使緩存的消息區塊失效。工具定義和系統提示保持緩存,但消息內容必須重新處理。
此圖表說明了每個選項的工作方式:
請注意,當您有 tool_choiceanytool 時,我們將預填充助手消息以強制使用工具。這意味著模型不會在 tool_use 內容區塊之前發出自然語言響應或解釋,即使被明確要求這樣做。
使用 擴展思考 與工具使用時,不支持 tool_choice: {"type": "any"}tool_choice: {"type": "tool", "name": "..."} 並將導致錯誤。只有 tool_choice: {"type": "auto"} (默認值)和 tool_choice: {"type": "none"} 與擴展思考兼容。
我們的測試表明這不應該降低性能。如果您希望模型在仍然請求模型使用特定工具的同時提供自然語言上下文或解釋,您可以對 tool_choice 使用 {"type": "auto"} (默認值),並在 user 消息中添加明確的指示。例如:倫敦的天氣如何?在您的回應中使用 get_weather 工具。

JSON 輸出

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

使用工具的模型響應

使用工具時,Claude 通常會評論它正在做什麼或在調用工具之前自然地回應用戶。 例如,給定提示「舊金山現在的天氣如何,那裡現在幾點?」,Claude 可能會回應:
JSON
{
  "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 可能使用多個工具來回答用戶查詢。您可以通過以下方式禁用此行為:
  • 當 tool_choice 類型為 auto 時設置 disable_parallel_tool_use=true,這確保 Claude 最多使用 一個 工具
  • 當 tool_choice 類型為 anytool 時設置 disable_parallel_tool_use=true,這確保 Claude 使用 恰好一個 工具
使用工具運行器更簡單:下面的示例展示了手動並行工具處理。對於大多數用例,工具運行器 自動處理並行工具執行,代碼少得多。
以下是展示如何在消息歷史中正確格式化並行工具調用的完整示例:
import anthropic

client = anthropic.Anthropic()

# Define tools
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"
                }
            },
            "required": ["location"]
        }
    },
    {
        "name": "get_time",
        "description": "Get the current time in a given timezone",
        "input_schema": {
            "type": "object",
            "properties": {
                "timezone": {
                    "type": "string",
                    "description": "The timezone, e.g. America/New_York"
                }
            },
            "required": ["timezone"]
        }
    }
]

# Initial request
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=tools,
    messages=[
        {
            "role": "user",
            "content": "What's the weather in SF and NYC, and what time is it there?"
        }
    ]
)

# Claude's response with parallel tool calls
print("Claude wants to use tools:", response.stop_reason == "tool_use")
print("Number of tool calls:", len([c for c in response.content if c.type == "tool_use"]))

# Build the conversation with tool results
messages = [
    {
        "role": "user",
        "content": "What's the weather in SF and NYC, and what time is it there?"
    },
    {
        "role": "assistant",
        "content": response.content  # Contains multiple tool_use blocks
    },
    {
        "role": "user",
        "content": [
            {
                "type": "tool_result",
                "tool_use_id": "toolu_01",  # Must match the ID from tool_use
                "content": "San Francisco: 68°F, partly cloudy"
            },
            {
                "type": "tool_result",
                "tool_use_id": "toolu_02",
                "content": "New York: 45°F, clear skies"
            },
            {
                "type": "tool_result",
                "tool_use_id": "toolu_03",
                "content": "San Francisco time: 2:30 PM PST"
            },
            {
                "type": "tool_result",
                "tool_use_id": "toolu_04",
                "content": "New York time: 5:30 PM EST"
            }
        ]
    }
]

# Get final response
final_response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=tools,
    messages=messages
)

print(final_response.content[0].text)
具有並行工具調用的助手消息如下所示:
{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll check the weather and time for both San Francisco and New York City."
    },
    {
      "type": "tool_use",
      "id": "toolu_01",
      "name": "get_weather",
      "input": {"location": "San Francisco, CA"}
    },
    {
      "type": "tool_use",
      "id": "toolu_02",
      "name": "get_weather",
      "input": {"location": "New York, NY"}
    },
    {
      "type": "tool_use",
      "id": "toolu_03",
      "name": "get_time",
      "input": {"timezone": "America/Los_Angeles"}
    },
    {
      "type": "tool_use",
      "id": "toolu_04",
      "name": "get_time",
      "input": {"timezone": "America/New_York"}
    }
  ]
}
以下是一個完整的、可運行的腳本,用於測試和驗證並行工具調用是否正常工作:
#!/usr/bin/env python3
"""Test script to verify parallel tool calls with the Claude API"""

import os
from anthropic import Anthropic

# Initialize client
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

# Define tools
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"
                }
            },
            "required": ["location"]
        }
    },
    {
        "name": "get_time",
        "description": "Get the current time in a given timezone",
        "input_schema": {
            "type": "object",
            "properties": {
                "timezone": {
                    "type": "string",
                    "description": "The timezone, e.g. America/New_York"
                }
            },
            "required": ["timezone"]
        }
    }
]

# Test conversation with parallel tool calls
messages = [
    {
        "role": "user",
        "content": "What's the weather in SF and NYC, and what time is it there?"
    }
]

# Make initial request
print("Requesting parallel tool calls...")
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=messages,
    tools=tools
)

# Check for parallel tool calls
tool_uses = [block for block in response.content if block.type == "tool_use"]
print(f"\n✓ Claude made {len(tool_uses)} tool calls")

if len(tool_uses) > 1:
    print("✓ Parallel tool calls detected!")
    for tool in tool_uses:
        print(f"  - {tool.name}: {tool.input}")
else:
    print("✗ No parallel tool calls detected")

# Simulate tool execution and format results correctly
tool_results = []
for tool_use in tool_uses:
    if tool_use.name == "get_weather":
        if "San Francisco" in str(tool_use.input):
            result = "San Francisco: 68°F, partly cloudy"
        else:
            result = "New York: 45°F, clear skies"
    else:  # get_time
        if "Los_Angeles" in str(tool_use.input):
            result = "2:30 PM PST"
        else:
            result = "5:30 PM EST"

    tool_results.append({
        "type": "tool_result",
        "tool_use_id": tool_use.id,
        "content": result
    })

# Continue conversation with tool results
messages.extend([
    {"role": "assistant", "content": response.content},
    {"role": "user", "content": tool_results}  # All results in one message!
])

# Get final response
print("\nGetting final response...")
final_response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=messages,
    tools=tools
)

print(f"\nClaude's response:\n{final_response.content[0].text}")

# Verify formatting
print("\n--- Verification ---")
print(f"✓ Tool results sent in single user message: {len(tool_results)} results")
print("✓ No text before tool results in content array")
print("✓ Conversation formatted correctly for future parallel tool use")
此腳本演示了:
  • 如何正確格式化並行工具調用和結果
  • 如何驗證正在進行並行調用
  • 鼓勵未來並行工具使用的正確消息結構
  • 要避免的常見錯誤(如工具結果之前的文本)
運行此腳本以測試您的實現並確保 Claude 正在有效地進行並行工具調用。

最大化並行工具使用

雖然 Claude 4 模型默認具有出色的並行工具使用功能,但您可以通過有針對性的提示在所有模型中增加並行工具執行的可能性:
對於 Claude 4 模型(Opus 4.1、Opus 4 和 Sonnet 4),將以下內容添加到您的系統提示:
For maximum efficiency, whenever you need to perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially.
為了獲得更強的並行工具使用(如果默認值不夠,建議使用),請使用:
<use_parallel_tool_calls>
For maximum efficiency, whenever you perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially. Prioritize calling tools in parallel whenever possible. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. When running multiple read-only commands like `ls` or `list_dir`, always run all of the commands in parallel. Err on the side of maximizing parallel tool calls rather than running too many tools sequentially.
</use_parallel_tool_calls>
您也可以在特定用戶消息中鼓勵並行工具使用:
# Instead of:
"What's the weather in Paris? Also check London."

# Use:
"Check the weather in Paris and London simultaneously."

# Or be explicit:
"Please use parallel tool calls to get the weather for Paris, London, and Tokyo at the same time."
Claude Sonnet 3.7 的並行工具使用Claude Sonnet 3.7 可能不太可能在響應中進行並行工具調用,即使您未設置 disable_parallel_tool_use。為了解決這個問題,我們建議啟用 令牌高效工具使用,這有助於鼓勵 Claude 使用並行工具。此測試版功能還降低了延遲並平均節省了 14% 的輸出令牌。如果您不想選擇令牌高效工具使用測試版,您也可以引入一個「批量工具」,該工具可以充當元工具以同時包裝對其他工具的調用。我們發現如果存在此工具,模型將使用它為您同時並行調用多個工具。有關如何使用此解決方法的信息,請參閱我們 cookbook 中的 此示例

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

使用工具運行器更簡單:本節中描述的手動工具處理由 工具運行器 自動管理。當您需要對工具執行進行自定義控制時,請使用本節。
Claude 的響應根據它是使用客戶端工具還是服務器工具而有所不同。

處理來自客戶端工具的結果

響應將具有 tool_usestop_reason 和一個或多個 tool_use 內容區塊,包括:
  • id:此特定工具使用區塊的唯一標識符。這將用於稍後匹配工具結果。
  • name:正在使用的工具的名稱。
  • input:包含傳遞給工具的輸入的對象,符合工具的 input_schema
JSON
{
  "id": "msg_01Aq9w938a90dw8q",
  "model": "claude-sonnet-4-5",
  "stop_reason": "tool_use",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll check the current weather in San Francisco for you."
    },
    {
      "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lq9",
      "name": "get_weather",
      "input": {"location": "San Francisco, CA", "unit": "celsius"}
    }
  ]
}
當您收到客戶端工具的工具使用響應時,您應該:
  1. tool_use 區塊中提取 nameidinput
  2. 在您的代碼庫中運行與該工具名稱對應的實際工具,傳入工具 input
  3. 通過發送角色為 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"}])。這些內容區塊可以使用 textimagedocument 類型。
    • is_error (可選):如果工具執行導致錯誤,設置為 true
重要的格式要求
  • 工具結果區塊必須立即跟在消息歷史中的相應工具使用區塊之後。您不能在助手的工具使用消息和用戶的工具結果消息之間包含任何消息。
  • 在包含工具結果的用戶消息中,tool_result 區塊必須首先出現在內容數組中。任何文本必須在所有工具結果之後。
例如,這將導致 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」的錯誤,請檢查您的工具結果格式是否正確。
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "15 degrees"
    }
  ]
}
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": [
        {"type": "text", "text": "15 degrees"},
        {
          "type": "image",
          "source": {
            "type": "base64",
            "media_type": "image/jpeg",
            "data": "/9j/4AAQSkZJRg...",
          }
        }
      ]
    }
  ]
}
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
    }
  ]
}
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": [
        {"type": "text", "text": "The weather is"},
        {
          "type": "document",
          "source": {
            "type": "text",
            "media_type": "text/plain",
            "data": "15 degrees"
          }
        }
      ]
    }
  ]
}
收到工具結果後,Claude 將使用該信息繼續生成對原始用戶提示的響應。

處理來自服務器工具的結果

Claude 在內部執行工具並將結果直接合併到其響應中,無需額外的用戶交互。
與其他 API 的區別與分離工具使用或使用特殊角色(如 toolfunction)的 API 不同,Claude API 將工具直接集成到 userassistant 消息結構中。消息包含 textimagetool_usetool_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-sonnet-4-5",
            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 時:
  • 繼續對話:在後續請求中按原樣傳遞暫停的響應,讓 Claude 繼續其轉換
  • 如果需要修改:如果您想中斷或重定向對話,您可以選擇在繼續之前修改內容
  • 保留工具狀態:在繼續請求中包含相同的工具以維持功能

故障排除錯誤

內置錯誤處理工具運行器 為大多數常見場景提供自動錯誤處理。本節涵蓋高級用例的手動錯誤處理。
使用工具與 Claude 時可能會發生幾種不同類型的錯誤:
如果工具本身在執行期間拋出錯誤(例如獲取天氣數據時的網絡錯誤),您可以在 content 中返回錯誤消息以及 "is_error": true
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "ConnectionError: the weather service API is not available (HTTP 500)",
      "is_error": true
    }
  ]
}
Claude 將隨後將此錯誤合併到對用戶的響應中,例如「抱歉,我無法檢索當前天氣,因為天氣服務 API 不可用。請稍後重試。」
如果 Claude 嘗試使用的工具無效(例如缺少必需的參數),通常意味著 Claude 沒有足夠的信息來正確使用該工具。在開發期間,最好的辦法是使用工具定義中更詳細的 description 值重試請求。但是,您也可以使用指示錯誤的 tool_result 繼續對話,Claude 將嘗試使用填入缺失信息的工具:
JSON
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "Error: Missing required 'location' parameter",
      "is_error": true
    }
  ]
}
如果工具請求無效或缺少參數,Claude 將在向用戶道歉之前重試 2-3 次進行更正。
為了防止 Claude 使用 <search_quality_reflection> 標籤反思搜索質量,請在您的提示中添加「Do not reflect on the quality of the returned search results in your response」。
當服務器工具遇到錯誤時(例如網絡搜索的網絡問題),Claude 將透明地處理這些錯誤並嘗試向用戶提供替代響應或解釋。與客戶端工具不同,您不需要為服務器工具處理 is_error 結果。對於網絡搜索,可能的錯誤代碼包括:
  • too_many_requests:超過速率限制
  • invalid_input:無效的搜索查詢參數
  • max_uses_exceeded:超過最大網絡搜索工具使用次數
  • query_too_long:查詢超過最大長度
  • unavailable:發生內部錯誤
如果 Claude 在預期時不進行並行工具調用,請檢查這些常見問題:1. 工具結果格式不正確最常見的問題是在對話歷史中不正確地格式化工具結果。這「教導」Claude 避免並行調用。特別是對於並行工具使用:
  • 錯誤:為每個工具結果發送單獨的用戶消息
  • 正確:所有工具結果必須在單個用戶消息中
// ❌ This reduces parallel tool use
[
  {"role": "assistant", "content": [tool_use_1, tool_use_2]},
  {"role": "user", "content": [tool_result_1]},
  {"role": "user", "content": [tool_result_2]}  // Separate message
]

// ✅ This maintains parallel tool use
[
  {"role": "assistant", "content": [tool_use_1, tool_use_2]},
  {"role": "user", "content": [tool_result_1, tool_result_2]}  // Single message
]
有關其他格式規則,請參閱上面的 常規格式要求2. 提示不夠強默認提示可能不夠。使用更強的語言:
<use_parallel_tool_calls>
For maximum efficiency, whenever you perform multiple independent operations,
invoke all relevant tools simultaneously rather than sequentially.
Prioritize calling tools in parallel whenever possible.
</use_parallel_tool_calls>
3. 測量並行工具使用要驗證並行工具調用是否正常工作:
# Calculate average tools per tool-calling message
tool_call_messages = [msg for msg in messages if any(
    block.type == "tool_use" for block in msg.content
)]
total_tool_calls = sum(
    len([b for b in msg.content if b.type == "tool_use"])
    for msg in tool_call_messages
)
avg_tools_per_message = total_tool_calls / len(tool_call_messages)
print(f"Average tools per message: {avg_tools_per_message}")
# Should be > 1.0 if parallel calls are working
4. 模型特定行為
  • Claude Opus 4.1、Opus 4 和 Sonnet 4:在最少提示的情況下擅長並行工具使用
  • Claude Sonnet 3.7:可能需要更強的提示或 令牌高效工具使用
  • Claude Haiku:在沒有明確提示的情況下不太可能使用並行工具