UniterRouter
API 参考OpenAI 兼容

函数调用

OpenAI Function Calling API - 让 GPT-4、GPT-3.5 调用外部工具和 API。构建 AI Agent、结构化数据提取和自动化工作流。

函数调用

函数调用允许模型为预定义函数生成结构化参数,实现与外部工具和 API 的集成。

支持的模型: GPT-4o, GPT-4 Turbo, GPT-3.5 Turbo, Claude 3.5 Sonnet/Haiku, Gemini 2.0/1.5 等现代 LLM。

工作原理

  1. 使用 JSON Schema 定义函数
  2. 在请求中发送函数定义
  3. 模型返回函数调用及参数
  4. 执行函数并返回结果
  5. 模型生成最终响应

定义函数

{
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "获取某个位置的当前天气",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "城市名称,如:北京"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    }
  ]
}

示例请求

from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api.uniterouter.ai/v1",
    api_key="your_api_key",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "获取某个位置的当前天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市名称,如:东京"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

messages = [{"role": "user", "content": "东京的天气怎么样?"}]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=messages,
    tools=tools,
    tool_choice="auto"
)

# 检查模型是否要调用函数
if response.choices[0].message.tool_calls:
    tool_call = response.choices[0].message.tool_calls[0]
    function_name = tool_call.function.name
    arguments = json.loads(tool_call.function.arguments)
    
    # 执行函数
    result = get_weather(arguments["location"])
    
    # 将结果发送回去
    messages.append(response.choices[0].message)
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": json.dumps(result)
    })
    
    # 获取最终响应
    final_response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        tools=tools
    )
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.uniterouter.ai/v1",
  apiKey: process.env.UNITEROUTER_API_KEY,
});

const tools: OpenAI.Chat.ChatCompletionTool[] = [
  {
    type: "function",
    function: {
      name: "get_weather",
      description: "获取某个位置的当前天气",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "城市名称,如:东京",
          },
        },
        required: ["location"],
      },
    },
  },
];

const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [
  { role: "user", content: "东京的天气怎么样?" },
];

const response = await client.chat.completions.create({
  model: "gpt-4o",
  messages,
  tools,
  tool_choice: "auto",
});

if (response.choices[0].message.tool_calls) {
  const toolCall = response.choices[0].message.tool_calls[0];
  const args = JSON.parse(toolCall.function.arguments);
  
  // 执行函数并获取结果
  const result = await getWeather(args.location);
  
  // 继续对话
  messages.push(response.choices[0].message);
  messages.push({
    role: "tool",
    tool_call_id: toolCall.id,
    content: JSON.stringify(result),
  });
  
  const finalResponse = await client.chat.completions.create({
    model: "gpt-4o",
    messages,
    tools,
  });
}
curl https://api.uniterouter.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $UNITEROUTER_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "东京的天气怎么样?"}],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "获取当前天气",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {"type": "string"}
            },
            "required": ["location"]
          }
        }
      }
    ],
    "tool_choice": "auto"
  }'

工具响应格式

当模型调用函数时:

{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": null,
      "tool_calls": [
        {
          "id": "call_abc123",
          "type": "function",
          "function": {
            "name": "get_weather",
            "arguments": "{\"location\": \"东京\"}"
          }
        }
      ]
    },
    "finish_reason": "tool_calls"
  }]
}

Tool Choice 选项

控制模型何时使用工具:

# 让模型决定
tool_choice="auto"

# 强制调用特定函数
tool_choice={"type": "function", "function": {"name": "get_weather"}}

# 禁用函数调用
tool_choice="none"

# 要求必须调用某个函数
tool_choice="required"

并行函数调用

模型可以同时调用多个函数:

tools = [
    {"type": "function", "function": {"name": "get_weather", ...}},
    {"type": "function", "function": {"name": "get_time", ...}}
]

# 用户: "东京和纽约的天气和时间是什么?"
# 模型可能返回多个 tool_calls

处理并行调用:

if response.choices[0].message.tool_calls:
    messages.append(response.choices[0].message)
    
    for tool_call in response.choices[0].message.tool_calls:
        result = execute_function(tool_call.function.name, 
                                  tool_call.function.arguments)
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": json.dumps(result)
        })

严格模式

启用严格的 schema 验证(OpenAI 模型):

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "strict": True,  # 强制执行 schema
        "parameters": {...}
    }
}]

最佳实践

  1. 清晰的描述 - 编写详细的函数和参数描述
  2. 验证参数 - 执行前始终验证参数
  3. 处理错误 - 返回模型能理解的错误消息
  4. 限制工具数量 - 只使用必要的函数(通常 < 20)
  5. 使用枚举 - 尽可能约束值的范围

相关文档

How is this guide?