函数调用

让支持工具的模型请求函数,并把执行结果返回给对话。

函数调用(Function Calling)用于把模型连接到你控制的应用代码、API、数据库和其他工具。

glm-5.3glm-5.2glm-5kimi-k3kimi-k2deepseek-v4-prodeepseek-v4-flash 支持工具调用;deepseek-r1 当前不支持。

GLM 5 使用 OpenAI 风格的 function tools。当前端点只负责函数调用;Web Search、文件解析、代码执行等内置工具不会自动提供。

1. 定义函数

在请求中提供一个或多个 OpenAI 兼容的工具定义:

{
  "model": "glm-5.3",
  "messages": [
    {
      "role": "user",
      "content": "上海现在天气怎么样?"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "获取指定城市的当前天气。",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string",
              "description": "城市名称,例如上海。"
            }
          },
          "required": ["city"],
          "additionalProperties": false
        }
      }
    }
  ],
  "tool_choice": "auto",
  "max_completion_tokens": 800
}

2. 读取工具调用

当模型决定调用函数时,finish_reason 会是 tool_calls

{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_123",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"city\":\"上海\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

你的应用需要解析并校验 function.arguments,再真正执行对应函数。模型只负责请求调用,并不会替你的服务端执行函数。

3. 返回工具结果

把 assistant 的工具调用和一个匹配 tool_call_idtool 消息一起追加到后续请求:

{
  "model": "glm-5.3",
  "messages": [
    {
      "role": "user",
      "content": "上海现在天气怎么样?"
    },
    {
      "role": "assistant",
      "content": null,
      "tool_calls": [
        {
          "id": "call_123",
          "type": "function",
          "function": {
            "name": "get_weather",
            "arguments": "{\"city\":\"上海\"}"
          }
        }
      ]
    },
    {
      "role": "tool",
      "tool_call_id": "call_123",
      "content": "{\"temperature_c\":24,\"condition\":\"clear\"}"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "获取指定城市的当前天气。",
        "parameters": {
          "type": "object",
          "properties": {
            "city": { "type": "string" }
          },
          "required": ["city"]
        }
      }
    }
  ],
  "max_completion_tokens": 800
}

下一次响应可以把工具结果整理成自然语言,也可以继续请求其他工具。

tool_choice

行为
auto由模型决定是否调用函数。
none不调用函数。
required模型必须调用一个或多个可用函数。
指定函数对象在模型支持时强制调用指定函数。

可靠性建议

  • 执行函数前验证全部参数,不要直接信任模型生成的 JSON。
  • 权限校验放在你的应用代码中,不要只写在 Prompt 里。
  • 为外部工具设置超时和响应大小限制。
  • 可能时返回结构化 JSON,减少模型二次理解成本。
  • 裁剪历史消息时,把 assistant 的 tool call 与对应 tool result 成对保留。

工具定义也属于输入上下文

较大的 JSON Schema 会随请求一起发送,并在每次调用时计入输入 Token。只发送当前任务真正需要的工具定义。

函数调用 | GLM 5 API