函数调用

让大语言模型调用外部工具和 API,实现搜索、计算、数据库查询等能力。UloveGPT 兼容 OpenAI 和 Anthropic 两大函数调用规范。

工作原理

函数调用是一个三步流程:

  1. 定义工具:在请求中声明可用函数的名称、描述和参数格式
  2. 模型决定:模型分析用户输入,决定是否调用工具及传递什么参数
  3. 执行并返回:你的代码执行函数,将结果返回给模型生成最终回答

OpenAI 函数调用

定义工具

工具定义Typescript
const tools = [
  {
    type: "function",
    function: {
      name: "get_weather",
      description: "获取指定城市的天气信息",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "城市名称,例如 '北京' 或 'Shanghai'"
          },
          unit: {
            type: "string",
            enum: ["celsius", "fahrenheit"],
            description: "温度单位"
          }
        },
        required: ["location"]
      }
    }
  }
]

完整示例

Python 完整流程Python
from openai import OpenAI
import json

client = OpenAI(
    base_url="https://www.ulovegpt.com/v1",
    api_key="<你的 API_KEY>"
)

# 定义工具
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "获取指定城市的天气信息",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "城市名称"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["location"]
        }
    }
}]

# 第一轮:模型决定是否调用工具
messages = [{"role": "user", "content": "今天北京的天气怎么样?"}]

response = client.chat.completions.create(
    model="openai/gpt-5.4-mini",
    messages=messages,
    tools=tools
)

# 检查是否有工具调用
if response.choices[0].message.tool_calls:
    tool_call = response.choices[0].message.tool_calls[0]
    args = json.loads(tool_call.function.arguments)
    
    # 执行工具(这里是模拟)
    weather_result = f"北京,晴,25°C"
    
    # 第二轮:把工具结果返回给模型
    messages.append(response.choices[0].message)
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": weather_result
    })
    
    final = client.chat.completions.create(
        model="openai/gpt-5.4-mini",
        messages=messages,
        tools=tools
    )
    print(final.choices[0].message.content)

Anthropic 工具使用

Anthropic 使用 tool_use block 而非 OpenAI 的 tool_calls 格式。

Anthropic Tool UsePython
import anthropic

client = anthropic.Anthropic(
    base_url="https://www.ulovegpt.com/anthropic",
    api_key="<你的 API_KEY>"
)

# Anthropic 工具定义格式
tools = [{
    "name": "get_weather",
    "description": "获取指定城市的天气信息",
    "input_schema": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "城市名称"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
        },
        "required": ["location"]
    }
}]

message = client.messages.create(
    model="anthropic/claude-sonnet-4.6",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "今天北京的天气怎么样?"}]
)

# 检查工具调用
for content in message.content:
    if content.type == "tool_use":
        print(f"工具: {content.name}")
        print(f"参数: {content.input}")

工具定义参数

字段类型说明
typestring固定值 "function"
function.namestring函数名称,只能包含字母、数字、下划线
function.descriptionstring函数描述,帮助模型理解何时调用
function.parametersobjectJSON Schema 格式的参数定义
strictboolean是否强制模型严格遵循参数 schema

最佳实践

  • 描述要清晰:函数名和描述越清晰,模型调用越准确
  • 参数必填标记:使用 required 标注必填参数
  • 错误处理:工具执行失败时,将错误信息作为 tool 响应返回,让模型自行处理
  • 并行调用:模型可以同时调用多个工具(tool_calls 数组)
  • 流式模式:函数调用也支持流式返回,但需要自行拼接参数