Claude Tool Use 教程

Claude Tool Use(工具调用)是构建 AI Agent 的核心能力。通过定义工具,Claude 可以调用外部函数获取实时数据、操作数据库、执行计算等。本文详细讲解 Tool Use 的定义、调用流程和实战案例。

Tool Use 工作原理

Tool Use 遵循以下流程:

  1. 开发者在 API 请求中定义可用工具(工具名称、描述、参数 JSON Schema)
  2. Claude 根据用户需求决定是否调用工具,并生成工具调用参数
  3. 开发者执行工具函数,将结果返回给 Claude
  4. Claude 基于工具结果生成最终回复

定义工具

工具定义使用 JSON Schema 描述参数格式:

import anthropic

client = anthropic.Anthropic(
    api_key="your-api-key",
    base_url="https://claude4u.com/v1"
)

tools = [
    {
        "name": "get_weather",
        "description": "获取指定城市的当前天气信息,包括温度、湿度和天气状况",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称,如 '北京'、'上海'"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "温度单位,默认摄氏度"
                }
            },
            "required": ["city"]
        }
    }
]
提示:工具描述应尽可能详细,Claude 会根据描述决定何时使用该工具。好的描述包含:功能说明、返回内容、适用场景。

处理工具调用

import json

def get_weather(city, unit="celsius"):
    """模拟天气 API 调用"""
    weather_data = {
        "北京": {"temp": 22, "humidity": 45, "condition": "晴"},
        "上海": {"temp": 26, "humidity": 72, "condition": "多云"},
    }
    return weather_data.get(city, {"temp": 20, "humidity": 50, "condition": "未知"})

# 第一次调用:发送用户消息
response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "北京今天天气怎么样?"}]
)

# 检查是否需要调用工具
if response.stop_reason == "tool_use":
    tool_block = next(b for b in response.content if b.type == "tool_use")
    tool_name = tool_block.name
    tool_input = tool_block.input

    # 执行工具函数
    result = get_weather(**tool_input)

    # 第二次调用:返回工具结果
    final_response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        tools=tools,
        messages=[
            {"role": "user", "content": "北京今天天气怎么样?"},
            {"role": "assistant", "content": response.content},
            {
                "role": "user",
                "content": [
                    {
                        "type": "tool_result",
                        "tool_use_id": tool_block.id,
                        "content": json.dumps(result, ensure_ascii=False)
                    }
                ]
            }
        ]
    )
    print(final_response.content[0].text)

Node.js 示例

import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
  apiKey: 'your-api-key',
  baseURL: 'https://claude4u.com/v1'
});

const tools = [{
  name: 'search_database',
  description: '在数据库中搜索用户信息',
  input_schema: {
    type: 'object',
    properties: {
      query: { type: 'string', description: '搜索关键词' },
      limit: { type: 'number', description: '返回结果数量' }
    },
    required: ['query']
  }
}];

const response = await client.messages.create({
  model: 'claude-sonnet-4-20250514',
  max_tokens: 1024,
  tools,
  messages: [{ role: 'user', content: '查找姓张的用户' }]
});

构建多工具 Agent

真正的 AI Agent 需要支持多轮工具调用。以下是一个循环处理模式:

def run_agent(user_message, tools, tool_functions):
    messages = [{"role": "user", "content": user_message}]

    while True:
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            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":
                func = tool_functions[block.name]
                result = func(**block.input)
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": json.dumps(result, ensure_ascii=False)
                })
        messages.append({"role": "user", "content": tool_results})

工具设计最佳实践

注意:Tool Use 请求会消耗额外 token(工具定义本身占用输入 token)。建议通过 claude4u.com 轻舟 AI 中转服务使用,内置用量统计和成本监控,帮你精确追踪每次工具调用的开销。

Start Using 轻舟 AI

Stable, fast AI API relay — supports Claude, OpenAI, Gemini and more

Sign Up Now