工具调用

工具调用(Tool Calls,也称函数调用)使模型能够调用外部函数执行特定操作,如获取数据、执行计算或与 API 交互。这使模型超越文本生成,执行实际任务。

支持的模型

TB 目录中所有模型均支持工具调用,除非模型目录中另有说明。

工作原理

  1. 定义工具:在 tools 参数中提供函数定义列表。
  2. 模型决定:模型可能在响应中调用一个或多个工具。
  3. 执行:你的代码执行工具调用并返回结果。
  4. 模型生成最终响应:模型使用工具结果生成最终响应。

工具定义格式

每个工具包含名称、描述和参数的 JSON Schema:

{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "获取某地的当前天气",
    "parameters": {
      "type": "object",
      "properties": {
        "location": {
          "type": "string",
          "description": "城市名称或坐标"
        },
        "unit": {
          "type": "string",
          "enum": ["celsius", "fahrenheit"]
        }
      },
      "required": ["location"]
    }
  }
}

支持的 JSON Schema 类型

类型支持
string
number
integer
boolean
object是(支持嵌套)
array
enum

带工具的请求示例

{
  "model": "deepseek-r1",
  "messages": [{ "role": "user", "content": "今天东京的天气怎么样?" }],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "获取当前天气",
        "parameters": {
          "type": "object",
          "properties": {
            "location": { "type": "string" }
          },
          "required": ["location"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}

带工具调用的响应

当模型决定调用工具时,响应包含 tool_calls

{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"location\": \"Tokyo\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

执行工具调用并返回结果

你的代码应该:

  1. 从响应中解析 tool_calls
  2. 用提供的参数执行每个工具。
  3. 在对话中添加包含工具结果的新消息。
  4. 将更新的对话发送回 API。
{
  "model": "deepseek-r1",
  "messages": [
    { "role": "user", "content": "今天东京的天气怎么样?" },
    {
      "role": "assistant",
      "tool_calls": [
        {
          "id": "call_abc123",
          "type": "function",
          "function": {
            "name": "get_weather",
            "arguments": "{\"location\": \"Tokyo\"}"
          }
        }
      ]
    },
    {
      "role": "tool",
      "tool_call_id": "call_abc123",
      "content": "{\"temperature\": 22, \"condition\": \"晴天\"}"
    }
  ],
  "tools": [...]
}

然后模型使用工具结果生成最终响应。

工具选择策略

策略说明
"none"模型不调用任何工具。等同于不提供 tools
"auto"模型自行决定是否调用工具以及调用哪些工具。
指定工具强制模型调用特定工具:{ "type": "function", "function": { "name": "get_weather" } }

Strict Mode

部分模型支持在工具定义中设 strict: true,强制更严格的 JSON Schema 验证:

{
  "type": "function",
  "function": {
    "name": "get_weather",
    "strict": true,
    "parameters": { ... }
  }
}

strict mode 下:

  • 所有参数必须在 schema 中定义。
  • 不允许额外属性。
  • 模型必须严格遵守 schema。

最佳实践

  1. 描述要具体:具体的函数和参数描述帮助模型选择正确的工具。
  2. tool_choice: "auto" 获得灵活性:让模型决定何时需要工具。
  3. 优雅处理错误:工具调用失败时,在 content 字段返回描述性错误。
  4. 保持工具结果简洁:大型工具结果可能触及 token 限制。尽量总结。

相关文档