林逍遥 AI林逍遥 AI
登录
Tool UseFunction Calling

工具调用入门:让 Claude 调用函数

·12 分钟阅读

Tool Use(工具调用)是 Claude 最强大的能力之一。它让 Claude 不再只能生成文字——而是可以调用你定义的函数来执行实际操作:查询数据库、调用外部 API、执行计算、操作文件系统。这是构建 AI Agent 的基石。

你将学到什么

  • Tool Use 的工作原理(请求-响应循环)
  • 如何定义工具的 JSON Schema
  • 完整的工具调用流程代码
  • 多工具场景和最佳实践

工作原理

Tool Use 是一个多步交互过程:

  1. 你定义可用的工具(名称、描述、参数 Schema)
  2. 用户提问,Claude 分析后决定是否需要调用工具
  3. Claude 返回 tool_use 内容块(包含工具名和参数)
  4. 你的代码执行实际操作,获得结果
  5. 你把结果以 tool_result 传回 Claude
  6. Claude 基于结果生成最终回答

Note: Claude 自己不能执行函数——它只是决定「调用什么函数、传什么参数」。实际执行在你的代码中完成。

定义工具

tools = [
    {
        "name": "get_weather",
        "description": "获取指定城市的当前天气信息",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称,如:北京、上海"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "温度单位,默认摄氏度"
                }
            },
            "required": ["city"]
        }
    }
]

描述的重要性: Claude 根据 description 判断什么时候使用这个工具。描述越清晰,Claude 的判断越准确。

完整的调用流程

import anthropic
import json

client = anthropic.Anthropic()

# 1. 定义工具
tools = [{
    "name": "get_weather",
    "description": "获取指定城市的当前天气",
    "input_schema": {
        "type": "object",
        "properties": {
            "city": {"type": "string", "description": "城市名称"}
        },
        "required": ["city"]
    }
}]

# 2. 模拟天气查询函数
def get_weather(city: str) -> str:
    # 实际项目中调用天气 API
    weather_data = {"北京": "晴天 25°C", "上海": "多云 22°C", "广州": "小雨 28°C"}
    return weather_data.get(city, f"{city}:暂无数据")

# 3. 发送请求
response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "北京和上海今天天气怎么样?"}]
)

# 4. 处理工具调用
messages = [{"role": "user", "content": "北京和上海今天天气怎么样?"}]
messages.append({"role": "assistant", "content": response.content})

# 收集所有 tool_use 块的结果
tool_results = []
for block in response.content:
    if block.type == "tool_use":
        # 执行工具
        result = get_weather(**block.input)
        tool_results.append({
            "type": "tool_result",
            "tool_use_id": block.id,
            "content": result
        })

# 5. 把结果传回 Claude
messages.append({"role": "user", "content": tool_results})

final_response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    tools=tools,
    messages=messages,
)

print(final_response.content[0].text)

工具调用循环

实际应用中,Claude 可能需要多次调用工具。用一个循环处理:

def run_agent(user_message: str, tools: list, tool_handlers: dict):
    messages = [{"role": "user", "content": user_message}]

    while True:
        response = client.messages.create(
            model="claude-sonnet-4-6",
            max_tokens=4096,
            tools=tools,
            messages=messages,
        )

        # 如果没有工具调用,返回文本回答
        if response.stop_reason == "end_turn":
            return response.content[0].text

        # 处理工具调用
        messages.append({"role": "assistant", "content": response.content})

        tool_results = []
        for block in response.content:
            if block.type == "tool_use":
                handler = tool_handlers[block.name]
                result = handler(**block.input)
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": str(result),
                })

        messages.append({"role": "user", "content": tool_results})

tool_choice 控制

# 自动选择(默认):Claude 自己决定是否调用工具
tool_choice={"type": "auto"}

# 强制使用某个工具
tool_choice={"type": "tool", "name": "get_weather"}

# 强制使用任意一个工具
tool_choice={"type": "any"}

# 禁止使用工具
tool_choice={"type": "none"}

多工具示例

定义多个工具,让 Claude 自主选择:

tools = [
    {
        "name": "search_products",
        "description": "搜索商品,返回名称和价格",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "搜索关键词"},
                "max_results": {"type": "integer", "description": "最大结果数", "default": 5}
            },
            "required": ["query"]
        }
    },
    {
        "name": "get_order_status",
        "description": "查询订单状态",
        "input_schema": {
            "type": "object",
            "properties": {
                "order_id": {"type": "string", "description": "订单编号"}
            },
            "required": ["order_id"]
        }
    },
    {
        "name": "calculate_discount",
        "description": "计算折扣后的价格",
        "input_schema": {
            "type": "object",
            "properties": {
                "price": {"type": "number"},
                "discount_percent": {"type": "number"}
            },
            "required": ["price", "discount_percent"]
        }
    }
]

Claude 会根据用户的问题自动选择合适的工具:

  • 「搜索一下无线耳机」→ search_products
  • 「我的订单 ORD-123 到哪了」→ get_order_status
  • 「500 块打 8 折多少钱」→ calculate_discount

最佳实践

  • 工具描述要清晰:Claude 根据描述选择工具,描述不清会导致选错
  • 参数要有 description:帮助 Claude 填入正确的参数值
  • 错误处理:tool_result 可以返回错误信息,Claude 会据此调整
  • 限制工具数量:同时提供太多工具(>20)可能降低选择准确率

实战练习

Tip: 构建你的第一个工具调用应用。

  1. 定义 2-3 个工具(如天气查询、汇率换算、翻译),实现完整调用循环
  2. 测试 Claude 是否能正确选择工具
  3. 尝试一个需要连续调用两个工具才能回答的问题

关键要点

Note: 本文核心总结

  • Tool Use 让 Claude 调用你定义的函数,实现真正的「行动」能力
  • 核心流程:定义工具 → Claude 选择 → 你执行 → 返回结果 → Claude 总结
  • 用 tool_choice 控制 Claude 的工具使用行为
  • 工具描述的质量直接决定调用准确率

延伸阅读

二维码
微信公众号:lingxiaoyao

关注公众号,获取最新 AI 教程和课程更新

加载评论中...