tool-use

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Tool Use Skill

工具使用技能

Comprehensive guide to implementing tool use with Claude, covering schema design, tool choice modes, multi-turn conversations, error handling patterns, and advanced features like extended thinking and strict schema conformance.
关于在Claude中实现工具使用的综合指南,涵盖Schema设计、工具选择模式、多轮对话、错误处理模式,以及扩展思维、严格Schema一致性等高级功能。

When to Use This Skill

何时使用此技能

Activate this skill when:
  • Defining custom tools with JSON schemas
  • Building agentic workflows with tool use
  • Implementing tool result handling
  • Building parallel vs sequential tool orchestration
  • Requiring guaranteed schema conformance
  • Implementing error recovery patterns
  • Combining tools with extended thinking
在以下场景中启用此技能:
  • 定义带有JSON Schema的自定义工具
  • 构建包含工具使用的Agent工作流
  • 实现工具结果处理
  • 构建并行与串行工具编排
  • 需要保证Schema一致性
  • 实现错误恢复模式
  • 将工具与扩展思维结合

Core Concepts

核心概念

Tool Definition Schema

工具定义Schema

Every tool requires a JSON Schema input definition with:
  • name: Tool identifier (regex:
    ^[a-zA-Z0-9_-]{1,64}$
    )
  • description: Detailed explanation of purpose, when to use, behavior (3-4+ sentences)
  • input_schema: JSON Schema defining parameters
  • input_examples (optional, beta): Concrete examples of valid inputs
每个工具都需要一个JSON Schema输入定义,包含:
  • name:工具标识符(正则规则:
    ^[a-zA-Z0-9_-]{1,64}$
  • description:对工具用途、使用场景、行为的详细说明(3-4句及以上)
  • input_schema:定义参数的JSON Schema
  • input_examples(可选,测试版):有效输入的具体示例

Best Practices for Tool Definitions

工具定义最佳实践

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. Use this 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 beyond the price.",
  "input_schema": {
    "type": "object",
    "properties": {
      "ticker": {
        "type": "string",
        "description": "The stock ticker symbol, e.g. AAPL for Apple Inc. Must be uppercase."
      },
      "include_historical": {
        "type": "boolean",
        "description": "Optional. Whether to include 52-week high/low prices.",
        "default": false
      }
    },
    "required": ["ticker"],
    "additionalProperties": false
  },
  "input_examples": [
    {"ticker": "AAPL"},
    {"ticker": "MSFT", "include_historical": true},
    {"ticker": "GOOGL"}
  ]
}
Key Guidelines:
  • Descriptions should be 3-4+ sentences minimum
  • Explain what the tool does, when to use it, what it returns, limitations
  • Use
    input_examples
    for complex nested objects or format-sensitive parameters
  • Set
    additionalProperties: false
    for strict validation
  • Use enums for constrained parameters
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. Use this 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 beyond the price.",
  "input_schema": {
    "type": "object",
    "properties": {
      "ticker": {
        "type": "string",
        "description": "The stock ticker symbol, e.g. AAPL for Apple Inc. Must be uppercase."
      },
      "include_historical": {
        "type": "boolean",
        "description": "Optional. Whether to include 52-week high/low prices.",
        "default": false
      }
    },
    "required": ["ticker"],
    "additionalProperties": false
  },
  "input_examples": [
    {"ticker": "AAPL"},
    {"ticker": "MSFT", "include_historical": true},
    {"ticker": "GOOGL"}
  ]
}
关键指南:
  • 描述内容至少3-4句
  • 说明工具的功能、使用场景、返回内容和局限性
  • 对于复杂嵌套对象或格式敏感的参数,使用
    input_examples
  • 设置
    additionalProperties: false
    以实现严格验证
  • 对受限参数使用枚举类型

Tool Choice Modes

工具选择模式

Control how Claude decides whether and how to use tools:
ModeBehaviorUse Case
"auto"
Claude decides to use tools or not (default)General tool use, letting Claude decide
"any"
Claude must use one tool but can choose whichForcing tool use without specific tool
"tool"
Force specific tool (e.g.,
{"type": "tool", "name": "get_weather"}
)
Structured JSON output, specific tool required
"none"
Prevent all tool useNormal text-only responses
python
undefined
控制Claude决定是否以及如何使用工具:
模式行为使用场景
"auto"
Claude自行决定是否使用工具(默认)通用工具使用场景,由Claude自主判断
"any"
Claude必须使用某个工具,但可选择具体工具强制使用工具,但不指定具体工具
"tool"
强制使用特定工具(例如:
{"type": "tool", "name": "get_weather"}
结构化JSON输出,需要特定工具
"none"
禁止使用所有工具仅返回纯文本响应
python
undefined

Allow Claude to decide

允许Claude自行决定

tool_choice="auto" (default)

tool_choice="auto" (默认)

Force any tool to be used

强制使用任意工具

tool_choice={"type": "any"}
tool_choice={"type": "any"}

Force specific tool (useful for JSON output)

强制使用特定工具(适用于JSON输出)

tool_choice={"type": "tool", "name": "record_summary"}
tool_choice={"type": "tool", "name": "record_summary"}

Prevent tool use

禁止使用工具

tool_choice={"type": "none"}

**Important Constraints with Extended Thinking:**
- Extended thinking only supports `tool_choice: {"type": "auto"}` or `{"type": "none"}`
- Cannot use `{"type": "any"}` or `{"type": "tool"}` with extended thinking
- Use the separate "think" tool instead for complex reasoning with tool use
tool_choice={"type": "none"}

**扩展思维的重要约束:**
- 扩展思维仅支持`tool_choice: {"type": "auto"}`或`{"type": "none"}`
- 无法在扩展思维中使用`{"type": "any"}`或`{"type": "tool"}`
- 如需结合工具使用进行复杂推理,请使用独立的"think"工具

Strict Schema Conformance (Beta)

严格Schema一致性(测试版)

Enable guaranteed schema validation with
strict: true
:
python
tools=[{
    "name": "search_flights",
    "strict": True,  # Enable strict mode
    "input_schema": {
        "type": "object",
        "properties": {
            "destination": {"type": "string"},
            "departure_date": {"type": "string", "format": "date"},
            "passengers": {"type": "integer"}
        },
        "required": ["destination", "departure_date"],
        "additionalProperties": False
    }
}]
Benefits:
  • Guaranteed type-safe parameters (never
    "2"
    instead of
    2
    )
  • No missing required fields
  • No runtime schema validation needed
  • Production-ready reliability
Limitations:
  • Refusals override schema (safety takes precedence)
  • Token limit truncation may break schema
  • Some recursive schemas not supported
  • Requires
    structured-outputs-2025-11-13
    beta header
通过设置
strict: true
启用保证性Schema验证:
python
tools=[{
    "name": "search_flights",
    "strict": True,  # 启用严格模式
    "input_schema": {
        "type": "object",
        "properties": {
            "destination": {"type": "string"},
            "departure_date": {"type": "string", "format": "date"},
            "passengers": {"type": "integer"}
        },
        "required": ["destination", "departure_date"],
        "additionalProperties": False
    }
}]
优势:
  • 保证参数类型安全(绝不会出现
    "2"
    代替
    2
    的情况)
  • 不会缺失必填字段
  • 无需运行时Schema验证
  • 具备生产环境级别的可靠性
局限性:
  • 安全规则优先,会覆盖Schema要求
  • 令牌限制截断可能破坏Schema
  • 部分递归Schema不被支持
  • 需要
    structured-outputs-2025-11-13
    测试版请求头

Single Tool Use Pattern

单工具使用模式

Basic pattern: Define tool → Claude calls tool → Return result → Claude responds
python
import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=[{
        "name": "get_weather",
        "description": "Get current weather in a location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and state, e.g. San Francisco, CA"
                }
            },
            "required": ["location"]
        }
    }],
    messages=[{"role": "user", "content": "What's the weather in SF?"}]
)
基础模式:定义工具 → Claude调用工具 → 返回结果 → Claude响应
python
import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=[{
        "name": "get_weather",
        "description": "Get current weather in a location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and state, e.g. San Francisco, CA"
                }
            },
            "required": ["location"]
        }
    }],
    messages=[{"role": "user", "content": "What's the weather in SF?"}]
)

Check if Claude wants to use tool

检查Claude是否想要使用工具

if response.stop_reason == "tool_use": tool_use = next(b for b in response.content if b.type == "tool_use") print(f"Tool: {tool_use.name}") print(f"Input: {tool_use.input}")
# Execute tool (simulate)
tool_result = "68°F, partly cloudy"

# Return result to Claude
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=[...],  # Same tools
    messages=[
        {"role": "user", "content": "What's the weather in SF?"},
        {"role": "assistant", "content": response.content},
        {"role": "user", "content": [{
            "type": "tool_result",
            "tool_use_id": tool_use.id,
            "content": tool_result
        }]}
    ]
)

print(response.content[0].text)
undefined
if response.stop_reason == "tool_use": tool_use = next(b for b in response.content if b.type == "tool_use") print(f"Tool: {tool_use.name}") print(f"Input: {tool_use.input}")
# 执行工具(模拟)
tool_result = "68°F, partly cloudy"

# 将结果返回给Claude
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=[...],  # 相同的工具
    messages=[
        {"role": "user", "content": "What's the weather in SF?"},
        {"role": "assistant", "content": response.content},
        {"role": "user", "content": [{
            "type": "tool_result",
            "tool_use_id": tool_use.id,
            "content": tool_result
        }]}
    ]
)

print(response.content[0].text)
undefined

Multi-Turn Tool Conversations

多轮工具对话

Tools often require sequential calls where one tool's output feeds into another:
python
undefined
工具通常需要串行调用,一个工具的输出作为另一个工具的输入:
python
undefined

User asks: "What's the weather where I am?"

用户提问: "What's the weather where I am?"

Flow: get_location() → get_weather(location)

流程: get_location() → get_weather(location)

response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[ { "name": "get_location", "description": "Get user's location from IP address", "input_schema": {"type": "object", "properties": {}} }, { "name": "get_weather", "description": "Get weather for location", "input_schema": { "type": "object", "properties": { "location": {"type": "string"} }, "required": ["location"] } } ], messages=[{"role": "user", "content": "What's the weather where I am?"}] )
response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[ { "name": "get_location", "description": "Get user's location from IP address", "input_schema": {"type": "object", "properties": {}} }, { "name": "get_weather", "description": "Get weather for location", "input_schema": { "type": "object", "properties": { "location": {"type": "string"} }, "required": ["location"] } } ], messages=[{"role": "user", "content": "What's the weather where I am?"}] )

Claude calls get_location first

Claude先调用get_location

tool_use = next(b for b in response.content if b.type == "tool_use") location_result = "San Francisco, CA"
tool_use = next(b for b in response.content if b.type == "tool_use") location_result = "San Francisco, CA"

Send location result back

发送位置结果返回

response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], messages=[ {"role": "user", "content": "What's the weather where I am?"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use.id, "content": location_result }]} ] )
response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], messages=[ {"role": "user", "content": "What's the weather where I am?"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use.id, "content": location_result }]} ] )

Claude now calls get_weather with the location

Claude现在使用位置信息调用get_weather

tool_use2 = next(b for b in response.content if b.type == "tool_use") weather_result = "68°F, sunny"
tool_use2 = next(b for b in response.content if b.type == "tool_use") weather_result = "68°F, sunny"

Final result

最终结果

response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], messages=[ {"role": "user", "content": "What's the weather where I am?"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use.id, "content": location_result }]}, {"role": "assistant", "content": response.content}, {"role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use2.id, "content": weather_result }]} ] )
print(response.content[0].text)
undefined
response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], messages=[ {"role": "user", "content": "What's the weather where I am?"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use.id, "content": location_result }]}, {"role": "assistant", "content": response.content}, {"role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use2.id, "content": weather_result }]} ] )
print(response.content[0].text)
undefined

Parallel Tool Use Pattern

并行工具使用模式

Claude can call multiple independent tools simultaneously:
python
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=[...],
    messages=[{
        "role": "user",
        "content": "What's the weather in SF and NYC? What time is it there?"
    }]
)
Claude可以同时调用多个独立工具:
python
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=[...],
    messages=[{
        "role": "user",
        "content": "What's the weather in SF and NYC? What time is it there?"
    }]
)

Claude makes 4 parallel tool calls (2 weather + 2 time)

Claude进行4次并行工具调用(2次天气查询 + 2次时间查询)

tool_uses = [b for b in response.content if b.type == "tool_use"] print(f"Parallel calls: {len(tool_uses)}") # 4
tool_uses = [b for b in response.content if b.type == "tool_use"] print(f"Parallel calls: {len(tool_uses)}") # 4

Execute all tools and collect results

执行所有工具并收集结果

tool_results = [] for tool_use in tool_uses: if tool_use.name == "get_weather": if "San Francisco" in str(tool_use.input): result = "68°F, partly cloudy" else: result = "45°F, clear" 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
})
tool_results = [] for tool_use in tool_uses: if tool_use.name == "get_weather": if "San Francisco" in str(tool_use.input): result = "68°F, partly cloudy" else: result = "45°F, clear" 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
})

IMPORTANT: Return all results in ONE user message

重要提示:所有结果必须放在同一条用户消息中返回

response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], messages=[ {"role": "user", "content": "What's the weather in SF and NYC? What time is it there?"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": tool_results} # All results together! ] )
print(response.content[0].text)

**Critical Formatting Rules for Parallel Tools:**
- All tool results must be in a SINGLE user message
- Tool result blocks must come FIRST in content array
- Text can come AFTER tool results if needed
- Incorrect formatting teaches Claude to avoid parallel calls
response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], messages=[ {"role": "user", "content": "What's the weather in SF and NYC? What time is it there?"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": tool_results} # 所有结果放在一起! ] )
print(response.content[0].text)

**并行工具的关键格式规则:**
- 所有工具结果必须放在单条用户消息中
- 工具结果块必须位于内容数组的最前面
- 如有需要,文本内容可放在工具结果之后
- 格式错误会导致Claude避免使用并行调用

Tool Result Handling

工具结果处理

Basic Tool Result Format

基础工具结果格式

python
{
    "type": "tool_result",
    "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
    "content": "15 degrees"
}
python
{
    "type": "tool_result",
    "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
    "content": "15 degrees"
}

Tool Result with Images

包含图片的工具结果

python
{
    "type": "tool_result",
    "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
    "content": [
        {"type": "text", "text": "Current weather screenshot:"},
        {
            "type": "image",
            "source": {
                "type": "base64",
                "media_type": "image/jpeg",
                "data": "/9j/4AAQSkZJRg..."
            }
        }
    ]
}
python
{
    "type": "tool_result",
    "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
    "content": [
        {"type": "text", "text": "Current weather screenshot:"},
        {
            "type": "image",
            "source": {
                "type": "base64",
                "media_type": "image/jpeg",
                "data": "/9j/4AAQSkZJRg..."
            }
        }
    ]
}

Tool Result with Documents

包含文档的工具结果

python
{
    "type": "tool_result",
    "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
    "content": [
        {"type": "text", "text": "Document content:"},
        {
            "type": "document",
            "source": {
                "type": "text",
                "media_type": "text/plain",
                "data": "Full document content here"
            }
        }
    ]
}
python
{
    "type": "tool_result",
    "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
    "content": [
        {"type": "text", "text": "Document content:"},
        {
            "type": "document",
            "source": {
                "type": "text",
                "media_type": "text/plain",
                "data": "Full document content here"
            }
        }
    ]
}

Error Handling in Tool Results

工具结果中的错误处理

python
undefined
python
undefined

Tool execution error

工具执行错误

{ "type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9", "content": "ConnectionError: Weather API is unavailable (HTTP 500)", "is_error": True }
{ "type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9", "content": "ConnectionError: Weather API is unavailable (HTTP 500)", "is_error": True }

Missing parameter error

参数缺失错误

{ "type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9", "content": "Error: Missing required 'location' parameter", "is_error": True }
undefined
{ "type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9", "content": "Error: Missing required 'location' parameter", "is_error": True }
undefined

Error Recovery Patterns

错误恢复模式

Pattern 1: Graceful Error Reporting

模式1:优雅错误报告

When tool execution fails, report error and Claude retries with corrections:
python
if tool_execution_failed:
    tool_result = {
        "type": "tool_result",
        "tool_use_id": tool_use.id,
        "content": f"Error: {error_message}",
        "is_error": True
    }
Claude typically retries 2-3 times before apologizing to the user.
当工具执行失败时,报告错误,Claude会修正后重试:
python
if tool_execution_failed:
    tool_result = {
        "type": "tool_result",
        "tool_use_id": tool_use.id,
        "content": f"Error: {error_message}",
        "is_error": True
    }
Claude通常会重试2-3次,然后向用户致歉。

Pattern 2: Strict Schema Enforcement

模式2:严格Schema强制执行

With
strict: true
, invalid parameters are prevented before execution:
python
undefined
启用
strict: true
后,会在执行前阻止无效参数:
python
undefined

With strict: true, Claude CANNOT send invalid parameters

启用strict: true后,Claude无法发送无效参数

Invalid type: "passengers": "two" → prevented by schema

无效类型: "passengers": "two" → 被Schema阻止

Missing required field → prevented by schema

缺失必填字段 → 被Schema阻止

Type mismatch: int vs string → prevented by schema

类型不匹配: 整数 vs 字符串 → 被Schema阻止

undefined
undefined

Pattern 3: Max Tokens Handling

模式3:最大令牌数处理

If response is cut off during tool use, retry with higher limit:
python
if response.stop_reason == "max_tokens":
    last_block = response.content[-1]
    if last_block.type == "tool_use":
        # Incomplete tool use, retry with more tokens
        response = client.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=4096,  # Increased
            messages=messages,
            tools=tools
        )
如果工具使用过程中响应被截断,使用更高的令牌限制重试:
python
if response.stop_reason == "max_tokens":
    last_block = response.content[-1]
    if last_block.type == "tool_use":
        # 工具使用不完整,使用更高令牌限制重试
        response = client.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=4096,  # 提高令牌限制
            messages=messages,
            tools=tools
        )

Tool Use for Structured JSON Output

工具用于结构化JSON输出

Use tools to guarantee structured JSON output without tool execution:
python
response = client.beta.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    betas=["structured-outputs-2025-11-13"],
    tools=[{
        "name": "record_summary",
        "description": "Record structured image summary",
        "input_schema": {
            "type": "object",
            "properties": {
                "key_colors": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "r": {"type": "number"},
                            "g": {"type": "number"},
                            "b": {"type": "number"},
                            "name": {"type": "string"}
                        },
                        "required": ["r", "g", "b", "name"]
                    }
                },
                "description": {"type": "string"},
                "estimated_year": {"type": "integer"}
            },
            "required": ["key_colors", "description"]
        }
    }],
    tool_choice={"type": "tool", "name": "record_summary"},
    messages=[{
        "role": "user",
        "content": [
            {"type": "image", "source": {"type": "url", "url": "https://..."}},
            {"type": "text", "text": "Describe this image"}
        ]
    }]
)
使用工具来保证结构化JSON输出,无需实际执行工具:
python
response = client.beta.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    betas=["structured-outputs-2025-11-13"],
    tools=[{
        "name": "record_summary",
        "description": "Record structured image summary",
        "input_schema": {
            "type": "object",
            "properties": {
                "key_colors": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "r": {"type": "number"},
                            "g": {"type": "number"},
                            "b": {"type": "number"},
                            "name": {"type": "string"}
                        },
                        "required": ["r", "g", "b", "name"]
                    }
                },
                "description": {"type": "string"},
                "estimated_year": {"type": "integer"}
            },
            "required": ["key_colors", "description"]
        }
    }],
    tool_choice={"type": "tool", "name": "record_summary"},
    messages=[{
        "role": "user",
        "content": [
            {"type": "image", "source": {"type": "url", "url": "https://..."}},
            {"type": "text", "text": "Describe this image"}
        ]
    }]
)

Extract structured output from tool use input

从工具使用输入中提取结构化输出

tool_use = next(b for b in response.content if b.type == "tool_use") structured_data = tool_use.input
undefined
tool_use = next(b for b in response.content if b.type == "tool_use") structured_data = tool_use.input
undefined

Parallel Tool Use Best Practices

并行工具使用最佳实践

Encouraging Parallel Execution

鼓励并行执行

Add to system prompt for stronger parallel tool use:
text
<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. When reading 3 files, run 3 tool
calls in parallel. When running multiple commands like 'ls' or 'list_dir',
always run all commands in parallel.
</use_parallel_tool_calls>
在系统提示中添加以下内容,强化并行工具使用:
text
<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. When reading 3 files, run 3 tool
calls in parallel. When running multiple commands like 'ls' or 'list_dir',
always run all commands in parallel.
</use_parallel_tool_calls>

Measuring Parallel Tool Use

衡量并行工具使用情况

python
def measure_parallel_efficiency(messages):
    # Find assistant messages with tool use
    tool_call_messages = [
        msg for msg in messages
        if msg.get("role") == "assistant"
        and any(b.get("type") == "tool_use" for b in msg.get("content", []))
    ]

    total_tools = sum(
        len([b for b in msg.get("content", []) if b.get("type") == "tool_use"])
        for msg in tool_call_messages
    )

    if not tool_call_messages:
        return 0

    avg_per_message = total_tools / len(tool_call_messages)
    print(f"Average tools per message: {avg_per_message}")
    # > 1.0 indicates parallel tool use working
python
def measure_parallel_efficiency(messages):
    # 查找包含工具使用的助手消息
    tool_call_messages = [
        msg for msg in messages
        if msg.get("role") == "assistant"
        and any(b.get("type") == "tool_use" for b in msg.get("content", []))
    ]

    total_tools = sum(
        len([b for b in msg.get("content", []) if b.get("type") == "tool_use"])
        for msg in tool_call_messages
    )

    if not tool_call_messages:
        return 0

    avg_per_message = total_tools / len(tool_call_messages)
    print(f"Average tools per message: {avg_per_message}")
    # > 1.0 表示并行工具使用生效

Extended Thinking Integration

扩展思维集成

Extended Thinking Constraints

扩展思维约束

python
undefined
python
undefined

✅ ALLOWED with extended thinking

✅ 扩展思维允许的用法

response = client.messages.create( model="claude-opus-4-5", thinking={"type": "enabled", "budget_tokens": 2048}, tools=[...], tool_choice={"type": "auto"}, # Default messages=[...] )
response = client.messages.create( model="claude-opus-4-5", thinking={"type": "enabled", "budget_tokens": 2048}, tools=[...], tool_choice={"type": "auto"}, # 默认 messages=[...] )

✅ ALLOWED with extended thinking

✅ 扩展思维允许的用法

tool_choice={"type": "none"} # No tools
tool_choice={"type": "none"} # 不使用工具

❌ NOT ALLOWED with extended thinking

❌ 扩展思维不允许的用法

tool_choice={"type": "any"} → Error

tool_choice={"type": "any"} → 错误

tool_choice={"type": "tool", "name": "..."} → Error

tool_choice={"type": "tool", "name": "..."} → 错误

undefined
undefined

"Think" Tool for Complex Reasoning

用于复杂推理的"Think"工具

When you need extended reasoning with tool use, use the "think" tool:
python
tools=[{
    "name": "think",
    "description": "Pause and think carefully before proceeding",
    "input_schema": {
        "type": "object",
        "properties": {
            "reasoning": {
                "type": "string",
                "description": "Your detailed reasoning"
            }
        },
        "required": ["reasoning"]
    }
}, {
    "name": "get_weather",
    "description": "Get weather information",
    "input_schema": {...}
}]
当需要结合工具使用进行扩展推理时,使用"think"工具:
python
tools=[{
    "name": "think",
    "description": "Pause and think carefully before proceeding",
    "input_schema": {
        "type": "object",
        "properties": {
            "reasoning": {
                "type": "string",
                "description": "Your detailed reasoning"
            }
        },
        "required": ["reasoning"]
    }
}, {
    "name": "get_weather",
    "description": "Get weather information",
    "input_schema": {...}
}]

SDK Tool Runner (Simplified Implementation)

SDK工具运行器(简化实现)

Python and TypeScript SDKs provide tool runners for automatic tool execution:
python
import anthropic
from anthropic import beta_tool

client = anthropic.Anthropic()

@beta_tool
def get_weather(location: str, unit: str = "fahrenheit") -> str:
    """Get current weather in a location.

    Args:
        location: City and state, e.g. San Francisco, CA
        unit: Temperature unit, either 'celsius' or 'fahrenheit'
    """
    # Tool implementation
    return '{"temperature": "20°C", "condition": "Sunny"}'
Python和TypeScript SDK提供工具运行器,可自动执行工具:
python
import anthropic
from anthropic import beta_tool

client = anthropic.Anthropic()

@beta_tool
def get_weather(location: str, unit: str = "fahrenheit") -> str:
    """Get current weather in a location.

    Args:
        location: City and state, e.g. San Francisco, CA
        unit: Temperature unit, either 'celsius' or 'fahrenheit'
    """
    # 工具实现
    return '{"temperature": "20°C", "condition": "Sunny"}'

Tool runner automatically handles tool execution loop

工具运行器自动处理工具执行循环

runner = client.beta.messages.tool_runner( model="claude-sonnet-4-5", max_tokens=1024, tools=[get_weather], messages=[{"role": "user", "content": "What's the weather in Paris?"}] )
runner = client.beta.messages.tool_runner( model="claude-sonnet-4-5", max_tokens=1024, tools=[get_weather], messages=[{"role": "user", "content": "What's the weather in Paris?"}] )

Iterate through responses

遍历响应

for message in runner: print(message.content[0].text)
for message in runner: print(message.content[0].text)

Or get final message directly

或直接获取最终消息

final_message = runner.until_done()
undefined
final_message = runner.until_done()
undefined

JSON Schema Support and Limitations

JSON Schema支持与局限性

Supported Features

支持的功能

  • All basic types: object, array, string, integer, number, boolean, null
  • enum
    for constrained values
  • const
    for fixed values
  • anyOf
    ,
    allOf
    for complex types
  • $ref
    ,
    $def
    ,
    definitions
    for schema composition
  • String formats: date-time, time, date, duration, email, hostname, uri, ipv4, ipv6, uuid
  • Array
    minItems
    (0 and 1 only)
  • 所有基础类型:object、array、string、integer、number、boolean、null
  • 用于受限值的
    enum
  • 用于固定值的
    const
  • 用于复杂类型的
    anyOf
    allOf
  • 用于Schema组合的
    $ref
    $def
    definitions
  • 字符串格式:date-time、time、date、duration、email、hostname、uri、ipv4、ipv6、uuid
  • 数组
    minItems
    (仅支持0和1)

Not Supported

不支持的功能

  • Recursive schemas (limit nesting depth)
  • Complex types within enums
  • External
    $ref
    (e.g., HTTP URLs)
  • Numerical constraints (minimum, maximum, multipleOf)
  • String constraints (minLength, maxLength)
  • Advanced array constraints
  • additionalProperties
    as anything other than false
  • Backreferences in regex patterns
  • 递归Schema(限制嵌套深度)
  • 枚举中的复杂类型
  • 外部
    $ref
    (例如HTTP URL)
  • 数值约束(minimum、maximum、multipleOf)
  • 字符串约束(minLength、maxLength)
  • 高级数组约束
  • additionalProperties
    设为false以外的值
  • 正则表达式中的反向引用

Common Use Cases

常见使用场景

Data Extraction

数据提取

python
tools=[{
    "name": "extract_info",
    "description": "Extract structured data from text",
    "input_schema": {
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "email": {"type": "string"},
            "company": {"type": "string"}
        },
        "required": ["name", "email"]
    }
}]
python
tools=[{
    "name": "extract_info",
    "description": "Extract structured data from text",
    "input_schema": {
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "email": {"type": "string"},
            "company": {"type": "string"}
        },
        "required": ["name", "email"]
    }
}]

API Integration

API集成

python
tools=[{
    "name": "search_api",
    "description": "Search external API",
    "input_schema": {
        "type": "object",
        "properties": {
            "query": {"type": "string"},
            "limit": {"type": "integer", "minimum": 1, "maximum": 100}
        },
        "required": ["query"]
    }
}]
python
tools=[{
    "name": "search_api",
    "description": "Search external API",
    "input_schema": {
        "type": "object",
        "properties": {
            "query": {"type": "string"},
            "limit": {"type": "integer", "minimum": 1, "maximum": 100}
        },
        "required": ["query"]
    }
}]

Multi-Step Orchestration

多步骤编排

python
tools=[
    {"name": "validate_input", ...},
    {"name": "process_data", ...},
    {"name": "save_result", ...}
]
python
tools=[
    {"name": "validate_input", ...},
    {"name": "process_data", ...},
    {"name": "save_result", ...}
]

Claude orchestrates the workflow

Claude编排工作流

undefined
undefined

Performance Considerations

性能考量

Token Cost of Tools

工具的令牌成本

  • Tool definitions added to input tokens
  • Tool use blocks in requests/responses count as tokens
  • Tool result blocks count as tokens
  • System prompt for tool use: 313-346 tokens depending on tool_choice
  • 工具定义会被计入输入令牌
  • 请求/响应中的工具使用块会占用令牌
  • 工具结果块会占用令牌
  • 工具使用的系统提示:根据tool_choice不同,占用313-346个令牌

Grammar Compilation

语法编译

  • First use of schema: additional latency for grammar compilation
  • Subsequent uses: grammar cached for 24 hours
  • Cache invalidated by schema changes or tool set changes
  • Name/description changes don't invalidate cache
  • 首次使用Schema:额外的语法编译延迟
  • 后续使用:语法会被缓存24小时
  • Schema变更或工具集变更会使缓存失效
  • 名称/描述变更不会使缓存失效

Context Window Management

上下文窗口管理

Tool use can quickly consume context in long conversations. Strategies:
  1. Compression: Summarize tool results
  2. Chunking: Break large operations into smaller requests
  3. Tool Runner: Uses automatic context compaction when needed
  4. Checkpointing: Save conversation state between phases
在长对话中,工具使用会快速消耗上下文。应对策略:
  1. 压缩:总结工具结果
  2. 分块:将大型操作拆分为较小的请求
  3. 工具运行器:必要时自动压缩上下文
  4. 检查点:在不同阶段之间保存对话状态

Forcing Tool Use (Structured Output)

强制工具使用(结构化输出)

Use
tool_choice
to force specific behavior:
python
undefined
使用
tool_choice
强制特定行为:
python
undefined

Force use of a tool (for JSON output)

强制使用某个工具(用于JSON输出)

response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[sentiment_tool], tool_choice={"type": "tool", "name": "sentiment_tool"}, messages=[{"role": "user", "content": "Analyze this text..."}] )
response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[sentiment_tool], tool_choice={"type": "tool", "name": "sentiment_tool"}, messages=[{"role": "user", "content": "Analyze this text..."}] )

No prefilled explanations with forced tool_choice

强制工具使用时不会有预先填充的解释

Claude goes straight to tool use

Claude直接调用工具

For explanations WITH tool use, use tool_choice="auto" (default)

如需在工具使用时附带解释,使用tool_choice="auto"(默认)

and add instruction: "Use the sentiment_tool in your response"

并添加指令: "Use the sentiment_tool in your response"

undefined
undefined

Handling Stop Reasons

处理停止原因

tool_use

tool_use

Claude wants to use a tool. Extract tool use blocks and execute tools.
Claude想要使用工具。提取工具使用块并执行工具。

end_turn

end_turn

Claude finished generating response. No more tool calls.
Claude完成响应生成。无需更多工具调用。

max_tokens

max_tokens

Response cut off. If last block is incomplete tool_use, retry with higher max_tokens.
响应被截断。如果最后一个块是不完整的tool_use,使用更高的max_tokens重试。

pause_turn
(with server tools)

pause_turn
(适用于服务器工具)

Long operation paused. Continue the conversation to resume.

长时间操作被暂停。继续对话以恢复操作。

Resources

资源