跳转到主要内容

Function Calling

Function Calling 允许模型在对话中调用你定义的函数。模型不会直接执行函数,而是返回函数名和参数,由你的代码执行后将结果返回给模型。

工作流程

  1. 发送消息和工具定义给模型
  2. 模型判断是否需要调用工具,返回 tool_calls
  3. 你的代码执行函数,获取结果
  4. 将函数结果以 tool 角色消息发回模型
  5. 模型根据函数结果生成最终回复

定义工具

tools 参数中定义可用的函数:
curl https://crazyrouter.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "北京今天天气怎么样?"}
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "获取指定城市的当前天气信息",
          "parameters": {
            "type": "object",
            "properties": {
              "city": {
                "type": "string",
                "description": "城市名称,如:北京、上海"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "温度单位"
              }
            },
            "required": ["city"]
          }
        }
      }
    ],
    "tool_choice": "auto"
  }'

模型返回 tool_calls

当模型决定调用函数时,响应如下:
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\": \"北京\", \"unit\": \"celsius\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

tool_choice 参数

说明
"auto"默认值,模型自行决定是否调用工具
"none"禁止调用工具
"required"强制模型调用至少一个工具
{"type": "function", "function": {"name": "get_weather"}}强制调用指定函数

并行函数调用

模型可以在一次回复中请求调用多个函数:
{
  "tool_calls": [
    {
      "id": "call_001",
      "type": "function",
      "function": {
        "name": "get_weather",
        "arguments": "{\"city\": \"北京\"}"
      }
    },
    {
      "id": "call_002",
      "type": "function",
      "function": {
        "name": "get_weather",
        "arguments": "{\"city\": \"上海\"}"
      }
    }
  ]
}
此时需要为每个 tool_call 返回对应的 tool 消息,tool_call_id 必须匹配。
function.arguments 是 JSON 字符串,需要用 JSON.parse()json.loads() 解析。模型生成的参数可能不完全符合 schema,建议做好错误处理。
不是所有模型都支持 Function Calling。请确认所使用的模型支持此功能。