Skip to content

工具调用

Tool Use 让 Claude 在需要外部数据或业务动作时请求调用工具。模型负责判断是否需要工具、生成工具参数;你的服务端负责执行工具、校验权限,并把结果返回给 Claude。

什么是 Tool Use

工具调用适合以下场景:

  • 查询订单
  • 查询数据库
  • 搜索知识库
  • 调用内部 API
  • 获取实时信息
  • 执行受控业务操作

工具定义结构

工具通常包含名称、描述和输入参数 schema。

json
{
  "name": "get_order_status",
  "description": "Check order shipping status",
  "input_schema": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string",
        "description": "Order ID"
      }
    },
    "required": ["order_id"]
  }
}

工具调用流程

  1. 服务端在请求中传入 tools
  2. 用户提出需要外部信息的问题
  3. Claude 返回 tool_use
  4. 服务端读取工具名称和参数
  5. 服务端执行真实工具
  6. 服务端把 tool_result 返回给 Claude
  7. Claude 根据工具结果生成最终回复

模型什么时候会调用工具

当用户问题需要实时数据、私有数据或系统操作时,Claude 可能选择调用工具。

json
{
  "model": "claude-sonnet-4-5",
  "max_tokens": 1024,
  "tools": [
    {
      "name": "get_order_status",
      "description": "Check order status",
      "input_schema": {
        "type": "object",
        "properties": {
          "order_id": { "type": "string" }
        },
        "required": ["order_id"]
      }
    }
  ],
  "messages": [
    { "role": "user", "content": "Check where order A1001 is now" }
  ]
}

服务端如何执行工具

服务端应只执行白名单内的工具,并对参数进行校验。

javascript
const toolHandlers = {
  async get_order_status(input) {
    if (!/^[A-Z0-9-]+$/.test(input.order_id)) {
      throw new Error("Invalid order_id");
    }

    return await queryOrderStatus(input.order_id);
  },
};

如何把工具结果返回给 Claude

当 Claude 返回 tool_use 后,服务端执行工具,再把结果作为 tool_result 放回下一轮消息。

json
{
  "model": "claude-sonnet-4-5",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": "Check where order A1001 is now"
    },
    {
      "role": "assistant",
      "content": [
        {
          "type": "tool_use",
          "id": "toolu_01Example",
          "name": "get_order_status",
          "input": {
            "order_id": "A1001"
          }
        }
      ]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_01Example",
          "content": "Order A1001 has arrived at the Shanghai distribution center and is expected to be delivered tomorrow."
        }
      ]
    }
  ]
}

多工具场景

多工具适合同时提供订单查询、用户资料、知识库搜索、工单创建等能力。

设计多工具时要注意:

  • 工具名称清晰,不要语义重叠
  • 每个工具只做一类明确动作
  • 高风险动作必须二次确认
  • 工具结果尽量返回结构化数据
  • 不要把内部密钥、SQL 或敏感配置暴露给模型

工具调用最佳实践

  • 工具执行必须在服务端
  • 所有参数都要做 schema 校验和业务校验
  • 工具调用要记录日志,便于排查
  • 写操作要增加权限控制和确认流程
  • 给工具写清楚能力边界,避免模型误用
  • 工具结果中只返回回答所需的信息