函数调用(Function Calling)

通过 tools 参数定义可调用的函数,模型会根据用户意图决定是否调用函数并生成参数。

支持函数调用的模型

在模型列表页筛选「函数调用」标签查看所有支持的模型。

→ 查看模型列表

请求示例

JSON
{
  "model": "deepseek-v4-flash",
  "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"
          ]
        }
      }
    }
  ]
}

模型响应

当模型决定调用函数时,finish_reason 为 "tool_calls",消息中包含 tool_calls 数组。

JSON
{
  "id": "chatcmpl-abc123",
  "model": "deepseek-v4-flash",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\":\"Beijing\",\"unit\":\"celsius\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

调用流程

1

发送请求,tools 参数定义可用函数

2

模型返回 tool_calls(函数名 + 参数)

3

你的代码执行函数,获取结果

4

将结果作为 tool 角色消息发送给模型

5

模型根据函数结果生成最终回答