深度

Claude API 工具调用完全指南:Tool Use 函数调用从入门到实战

Claude API Tool Use(工具调用/函数调用)完整教程:工具定义格式、单工具/多工具调用、工具结果传回、并行工具调用、流式工具调用、Python/Node.js 代码示例,以及构建 AI Agent 工具调用循环的最佳实践。

2026/3/154分钟 阅读ClaudeEagle

Tool Use(工具调用)是构建 AI Agent 的核心能力——让 Claude 能够调用你定义的函数,获取实时数据、执行操作、与外部系统交互。本文从原理到实战完整讲解。

工作原理

你定义工具 -> 发送给 Claude -> Claude 决定是否调用 -> 你执行工具 -> 把结果发回 -> Claude 基于结果给出最终答案

Claude 本身不执行工具,它只是决定调用哪个工具、传什么参数。实际执行由你的代码完成。

基础示例:天气查询工具

python
import anthropic, json
client = anthropic.Anthropic()

# Step 1:定义工具(JSON Schema)
tools = [{
    "name": "get_weather",
    "description": "Get current weather for a location. Returns temperature and conditions.",
    "input_schema": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "City name, e.g. Shanghai, Beijing"
            },
            "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "Temperature unit"
            }
        },
        "required": ["location"]
    }
}]

# Step 2:发送请求(带工具定义)
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "What's the weather in Shanghai?"}]
)

# Step 3:处理工具调用请求
if response.stop_reason == 'tool_use':
    tool_use_block = next(b for b in response.content if b.type == 'tool_use')
    tool_name = tool_use_block.name
    tool_input = tool_use_block.input
    
    print(f'Claude wants to call: {tool_name}({tool_input})')
    
    # Step 4:你来执行工具(这里是模拟)
    if tool_name == 'get_weather':
        result = {'temperature': 22, 'condition': 'Sunny', 'humidity': '60%'}
    
    # Step 5:把工具结果发回给 Claude
    final_response = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=1024,
        tools=tools,
        messages=[
            {"role": "user", "content": "What's the weather in Shanghai?"},
            {"role": "assistant", "content": response.content},
            {
                "role": "user",
                "content": [{
                    "type": "tool_result",
                    "tool_use_id": tool_use_block.id,
                    "content": json.dumps(result)
                }]
            }
        ]
    )
    print(final_response.content[0].text)

多工具定义

python
tools = [
    {
        "name": "search_web",
        "description": "Search the web for current information",
        "input_schema": {
            "type": "object",
            "properties": {"query": {"type": "string"}},
            "required": ["query"]
        }
    },
    {
        "name": "get_stock_price",
        "description": "Get current stock price for a ticker symbol",
        "input_schema": {
            "type": "object",
            "properties": {
                "ticker": {"type": "string", "description": "Stock ticker, e.g. AAPL"}
            },
            "required": ["ticker"]
        }
    },
    {
        "name": "calculate",
        "description": "Evaluate a mathematical expression",
        "input_schema": {
            "type": "object",
            "properties": {"expression": {"type": "string"}},
            "required": ["expression"]
        }
    }
]

并行工具调用

Claude 可以在一次响应中调用多个工具(并行):

python
def process_tool_calls(response, tools_dict):
    tool_results = []
    for block in response.content:
        if block.type == 'tool_use':
            func = tools_dict.get(block.name)
            if func:
                result = func(**block.input)
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": json.dumps(result)
                })
    return tool_results

# 工具实现映射
tools_dict = {
    'get_weather': lambda location, unit='celsius': {'temp': 22, 'unit': unit},
    'get_stock_price': lambda ticker: {'ticker': ticker, 'price': 150.25},
    'calculate': lambda expression: {'result': eval(expression)}
}

完整 Agent 循环

python
def run_agent(user_message, tools, tools_dict, max_steps=10):
    messages = [{"role": "user", "content": user_message}]
    
    for step in range(max_steps):
        response = client.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=4096,
            tools=tools,
            messages=messages
        )
        
        messages.append({"role": "assistant", "content": response.content})
        
        # 任务完成
        if response.stop_reason == 'end_turn':
            return next(b.text for b in response.content if b.type == 'text')
        
        # 执行工具调用
        if response.stop_reason == 'tool_use':
            tool_results = process_tool_calls(response, tools_dict)
            messages.append({"role": "user", "content": tool_results})
    
    return 'Max steps reached'

result = run_agent(
    'Search for the latest Claude Code news and calculate how many days since its launch',
    tools, tools_dict
)
print(result)

控制工具调用行为

python
# 强制调用特定工具
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=tools,
    tool_choice={"type": "tool", "name": "get_weather"},  # 强制调用
    messages=[{"role": "user", "content": "Tell me about Shanghai"}]
)

# 禁止调用工具(纯文本回复)
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=tools,
    tool_choice={"type": "none"},
    messages=[{"role": "user", "content": "What can you do?"}]
)

常见错误

错误 1:tool_result 顺序错误 tool_result 必须紧跟在包含 tool_use 的 assistant 消息之后。

错误 2:tool_use_id 不匹配 tool_result 里的 tool_use_id 必须和 Claude 请求里的完全一致。

错误 3:description 写得不够清楚 Claude 根据 description 决定何时调用工具,描述越准确调用越准确。


来源:Tool Use Overview - Anthropic 官方文档

相关文章推荐

深度高级提示词工程完全指南 2026:CoT、Few-Shot 与 XML 结构化技巧面向 Claude API 开发者的高级提示词工程完整指南:Chain-of-Thought(思维链)的原理与触发方式、Few-Shot 示例选取策略、Zero-Shot CoT 触发词、XML 标签结构化输出控制(强制 JSON)、角色扮演提示的正确姿势、多步骤任务分解、Claude 专属优化技巧(正向指令 vs 禁止指令)以及提示词 A/B 测试框架。2026/3/21深度Claude Computer Use 完全指南:让 AI 直接操控电脑执行任何任务Anthropic Claude Computer Use 功能完整介绍:Computer Use 是什么(AI 控制桌面环境)、支持的工具(screenshot/click/type/key/scroll)、通过 Docker 安全运行演示环境、Python API 调用示例、实际使用场景(自动填表/UI 测试/跨应用自动化)、当前能力局限与注意事项、与传统 RPA(Robotic Process Automation)的对比,以及在 AWS Bedrock 和 Google Vertex AI 上启用 Computer Use 的方法。2026/3/20深度Claude API 错误码完全手册:所有错误类型、原因与解决方案Anthropic Claude API 错误码完整参考:authentication_error(401/403)、rate_limit_error(429)、invalid_request_error(400)、api_error(500)、overloaded_error(529)的详细说明,每种错误的常见触发原因、标准解决方案和代码示例(Python/Node.js),以及生产环境的错误处理最佳实践(区分可重试/不可重试错误)。2026/3/18深度Claude API 速率限制完全指南:限额说明、错误处理与优化策略Anthropic Claude API 速率限制完整说明:请求频率限制(RPM)、Token 用量限制(TPM/TPD)、不同使用层级的限额对比(免费层/Build/Scale/Enterprise)、429 错误的标准处理方式(指数退避重试)、提升限额的申请方法、Prompt Caching 和 Batch API 绕过限制的技巧,以及高并发场景的队列设计方案。2026/3/18深度Claude API 批量处理完全指南:Message Batches API 大规模数据处理实战Claude API Message Batches 完整教程:批量 API 原理、与普通 API 的区别(50% 成本折扣)、Python/Node.js 提交批次代码示例、进度追踪与结果获取、错误处理策略、并发批次管理,以及文档摘要/数据分类/批量翻译等典型大规模处理场景实战。2026/3/16深度Claude API 限流完全指南:Rate Limit 报错原因、重试策略与生产环境最佳实践Claude API Rate Limit 完整应对指南:限流类型(RPM/TPM/并发)、各套餐限额表、429 错误处理、指数退避重试实现、Prompt Caching 降低用量、请求队列设计、Tier 升级申请,以及高并发生产环境架构方案。2026/3/15