登录

Function Calling

Function Calling 允许模型在需要时调用你预定义的函数,适用于构建 Agent、RAG 等场景。

定义工具

json
{
  "model": "gemini-2.5-flash",
  "messages": [
    {"role": "user", "content": "What's the weather in Beijing?"}
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get weather for a city",
        "parameters": {
          "type": "object",
          "properties": {
            "city": { "type": "string", "description": "City name" },
            "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
          },
          "required": ["city"]
        }
      }
    }
  ]
}

模型返回工具调用

当模型决定调用工具时,响应中的 finish_reason 为 "tool_calls"。

json
{
  "choices": [
    {
      "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"
    }
  ]
}

提交工具结果

执行函数后,将结果以 tool 角色消息返回。

json
{
  "model": "gemini-2.5-flash",
  "messages": [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
      "role": "assistant",
      "content": null,
      "tool_calls": [{"id": "call_abc123", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\": \"Beijing\"}"}}]
    },
    {
      "role": "tool",
      "tool_call_id": "call_abc123",
      "content": "{\"temperature\": 22, \"conditions\": \"sunny\", \"humidity\": 45}"
    }
  ],
  "tools": [...]
}

tool_choice 参数

ValueDescription
"auto"模型自行决定是否调用工具(默认)
"required"强制模型必须调用至少一个工具
"none"禁止模型调用工具
{"type":"function",...}强制调用指定函数

流式 Function Calling

首个 delta 包含 id、type、function.name;后续 delta 仅追加 function.arguments 片段,客户端需拼接完整 JSON。

text
data: {...,"delta":{"tool_calls":[{"index":0,"id":"call_abc","type":"function","function":{"name":"get_weather","arguments":""}}]},...}

data: {...,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"city\""}}]},...}

data: {...,"delta":{"tool_calls":[{"index":0,"function":{"arguments":": \"Beijing\"}"}}]},...}

data: {...,"delta":{},"finish_reason":"tool_calls",...}

data: [DONE]