选择模型

我们建议对复杂工具和模糊查询使用最新的 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 schema 表示,在上面的示例中 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_choice 设置为 anytool 时,我们将预填充助手消息以强制使用工具。这意味着模型不会在 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. 通过发送一条新消息来继续对话,其 roleusercontent 块包含 tool_result 类型和以下信息:
    • 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 停止原因

使用 Web 搜索等服务器工具时,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”。
当服务器工具遇到错误(例如 Web 搜索的网络问题)时,Claude 将透明地处理这些错误并尝试向用户提供替代响应或解释。与客户端工具不同,您不需要为服务器工具处理 is_error 结果。对于 Web 搜索,可能的错误代码包括:
  • too_many_requests:超过速率限制
  • invalid_input:无效的搜索查询参数
  • max_uses_exceeded:超过最大 Web 搜索工具使用次数
  • 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:不太可能在没有明确提示的情况下使用并行工具