深度

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 企业 AI Agent 现状报告:80% 已获可量化 ROI,编程是突破口Anthropic 联合 Material 公司调研 500+ 技术领导者的《2026 State of AI Agents Report》:57% 已部署多阶段工作流;86% 在生产代码部署 Agent;80% 报告可量化 ROI;编程时间节省覆盖规划/代码生成/文档/测试各 58-59%;真实案例(Doctolib 功能交付快 40%、eSentire 威胁分析从 5 小时到 7 分钟、L'Oréal 44000 月活数据直查);三大规模化挑战;以及企业 Claude Code 四阶段部署路径。2026/5/7深度Anthropic 2026 Agentic Coding 趋势报告:8 大预测解读,工程师角色从实施者转向编排者Anthropic《2026 Agentic Coding Trends Report》完整解读:60% AI 协作但只有 0-20% 完全委托的关键数据、8 大趋势(SDLC 压缩/多 Agent 团队/长时间 Agent/智能监督扩展/新用户群/经济重塑/全组织扩展/安全架构),以及 Rakuten/Fountain/TELUS/Zapier 的真实案例数据。2026/4/22深度MCP 代码执行模式深度解析:Anthropic 官方揭秘如何减少 98.7% 的 Token 消耗Anthropic 工程博客深度解析:传统 MCP 直接调用的两大 Token 浪费问题(工具定义占满上下文 + 中间结果来回传递),以及代码执行模式如何把 150,000 Token 降到 2,000 Token。涵盖文件树结构设计、按需加载工具、数据过滤、隐私保护和 Skill 持久化。2026/4/21深度LangGraph vs CrewAI vs AutoGen:2026 年 AI Agent 框架选型完全指南2026 年主流 AI Agent 框架深度对比:LangGraph 图结构(生产首选)、CrewAI 角色制(原型最快)、AutoGen 对话式(推理最强)。含架构原理、代码示例、实际基准数据、MCP 集成现状和选型决策框架。2026/4/17深度Hermes Agent 自学习技能系统实战:让 AI Agent 越用越聪明的完整指南Hermes Agent 技能系统完整指南:三级渐进加载机制、自动生成技能触发条件、手动编写和市场安装、技能自进化原理、团队共享技能库,以及与 Claude Code CLAUDE.md 的深度对比。2026/4/13深度Hermes Agent 是什么?NousResearch 开源 AI Agent 深度解析:自学习、持久记忆、多平台Hermes Agent 深度解析:NousResearch MIT 开源,33k stars。四阶段自学习闭环、三层记忆(MEMORY.md+SQLite FTS5)、技能三级渐进加载、7 平台消息网关、200+ LLM,以及 v0.7.0 安全强化详解。2026/4/13