跳转到主要内容

Responses Function Calling

Responses API 支持 Function Calling,让模型调用你定义的函数来获取外部数据或执行操作。
POST /v1/responses

定义工具并调用

curl https://crazyrouter.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "input": "北京和上海今天的天气怎么样?",
    "tools": [
      {
        "type": "function",
        "name": "get_weather",
        "description": "获取指定城市的当前天气",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string",
              "description": "城市名称"
            }
          },
          "required": ["city"]
        }
      }
    ]
  }'

函数调用响应

当模型决定调用函数时,响应中会包含 function_call 类型的输出:
{
  "id": "resp_abc123",
  "object": "response",
  "output": [
    {
      "type": "function_call",
      "id": "fc_001",
      "call_id": "call_abc123",
      "name": "get_weather",
      "arguments": "{\"city\": \"北京\"}"
    },
    {
      "type": "function_call",
      "id": "fc_002",
      "call_id": "call_def456",
      "name": "get_weather",
      "arguments": "{\"city\": \"上海\"}"
    }
  ],
  "status": "incomplete"
}

返回函数结果

将函数执行结果通过 function_call_output 返回:
{
  "model": "gpt-4o",
  "input": [
    {"role": "user", "content": "北京和上海今天的天气怎么样?"},
    {
      "type": "function_call",
      "call_id": "call_abc123",
      "name": "get_weather",
      "arguments": "{\"city\": \"北京\"}"
    },
    {
      "type": "function_call_output",
      "call_id": "call_abc123",
      "output": "{\"temperature\": 22, \"condition\": \"\"}"
    },
    {
      "type": "function_call",
      "call_id": "call_def456",
      "name": "get_weather",
      "arguments": "{\"city\": \"上海\"}"
    },
    {
      "type": "function_call_output",
      "call_id": "call_def456",
      "output": "{\"temperature\": 26, \"condition\": \"多云\"}"
    }
  ],
  "tools": [...]
}

流式 Function Calling

Python
stream = client.responses.create(
    model="gpt-4o",
    input="查询苹果公司的股价",
    tools=tools,
    stream=True
)

for event in stream:
    if event.type == "response.function_call_arguments.delta":
        print(event.delta, end="")
    elif event.type == "response.function_call_arguments.done":
        print("\n函数调用完成:", event.arguments)
    elif event.type == "response.output_text.delta":
        print(event.delta, end="")
Responses API 的 Function Calling 与 Chat Completions API 的主要区别在于:工具定义直接使用 nameparameters 字段,不需要嵌套在 function 对象中。