函数调用API

让大模型智能调用您定义的函数,实现与外部系统的无缝集成

高级功能工具集成自动化

什么是函数调用?

函数调用(Function Calling)允许大模型理解用户意图,并智能地选择和调用您预定义的函数, 将自然语言转换为结构化的函数调用参数。

🎯

智能识别

自动识别何时需要调用函数

🔧

参数提取

从对话中提取函数参数

🔄

结果整合

将函数结果整合到回复中

工作流程

  1. 1

    定义函数

    在API请求中描述可用函数及其参数

  2. 2

    模型判断

    AI分析是否需要调用函数

  3. 3

    返回调用信息

    返回函数名和参数

  4. 4

    执行函数

    您的代码执行实际函数

  5. 5

    返回结果

    将函数结果发送回模型生成最终回复

完整示例

Step 1: 定义函数结构

函数定义
const functions = [
  {
    "name": "get_weather",
    "description": "获取指定城市的天气信息",
    "parameters": {
      "type": "object",
      "properties": {
        "location": {
          "type": "string",
          "description": "城市名称,如:北京、上海"
        },
        "unit": {
          "type": "string",
          "enum": ["celsius", "fahrenheit"],
          "description": "温度单位"
        }
      },
      "required": ["location"]
    }
  },
  {
    "name": "search_product",
    "description": "搜索产品信息",
    "parameters": {
      "type": "object",
      "properties": {
        "query": {
          "type": "string",
          "description": "搜索关键词"
        },
        "category": {
          "type": "string",
          "description": "产品类别"
        },
        "max_price": {
          "type": "number",
          "description": "最高价格"
        }
      },
      "required": ["query"]
    }
  }
];

Step 2: 发送带函数的请求

const response = await fetch('https://api.n1n.ai/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
  },
  body: JSON.stringify({
    model: "gpt-3.5-turbo",
    messages: [
      {
        role: "user",
        content: "北京今天天气怎么样?"
      }
    ],
    functions: functions,
    function_call: "auto"  // auto | none | {"name": "function_name"}
  })
});

const data = await response.json();

Step 3: 处理函数调用响应

// API响应示例
{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": null,
      "function_call": {
        "name": "get_weather",
        "arguments": "{\"location\": \"北京\", \"unit\": \"celsius\"}"
      }
    }
  }]
}

// 解析并执行函数
const functionCall = data.choices[0].message.function_call;
if (functionCall) {
  const functionName = functionCall.name;
  const functionArgs = JSON.parse(functionCall.arguments);
  
  // 执行实际函数
  let functionResult;
  if (functionName === 'get_weather') {
    functionResult = await getWeather(functionArgs.location, functionArgs.unit);
  }
  
  console.log(`调用函数: ${functionName}`);
  console.log(`参数: `, functionArgs);
}

Step 4: 将函数结果返回给模型

// 函数执行结果
const functionResult = {
  temperature: 22,
  condition: "晴天",
  humidity: 45,
  wind_speed: 10
};

// 发送第二次请求,包含函数结果
const finalResponse = await fetch('https://api.n1n.ai/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
  },
  body: JSON.stringify({
    model: "gpt-3.5-turbo",
    messages: [
      { role: "user", content: "北京今天天气怎么样?" },
      { 
        role: "assistant",
        content: null,
        function_call: {
          name: "get_weather",
          arguments: "{\"location\": \"北京\", \"unit\": \"celsius\"}"
        }
      },
      {
        role: "function",
        name: "get_weather",
        content: JSON.stringify(functionResult)
      }
    ]
  })
});

// 最终回复: "北京今天天气晴朗,温度22°C,湿度45%,风速10km/h,适合外出。"

实战应用

📱 智能助手

可用函数:

  • • send_email() - 发送邮件
  • • schedule_meeting() - 安排会议
  • • set_reminder() - 设置提醒
  • • search_files() - 搜索文件

用户:"帮我给张三发邮件,提醒明天的会议"

AI:调用send_email()函数 ✓

🛍️ 电商机器人

可用函数:

  • • search_products() - 搜索商品
  • • check_inventory() - 检查库存
  • • calculate_discount() - 计算折扣
  • • create_order() - 创建订单

用户:"有没有红色的运动鞋?"

AI:调用search_products()函数 ✓

高级技巧

并行函数调用

GPT-4支持在一次响应中调用多个函数:

// 用户:"查询北京和上海的天气" // AI可能返回: { "function_calls": [ { "name": "get_weather", "arguments": "{\"location\": \"北京\"}" }, { "name": "get_weather", "arguments": "{\"location\": \"上海\"}" } ] }

条件函数调用

使用function_call参数控制函数调用行为:

// 强制调用特定函数 "function_call": {"name": "get_weather"} // 禁止函数调用 "function_call": "none" // 自动判断(默认) "function_call": "auto"

错误处理

try { const args = JSON.parse(functionCall.arguments); const result = await executeFunction(functionCall.name, args); return result; } catch (error) { // 返回错误信息给模型 return { error: true, message: `函数执行失败: ${error.message}` }; }

最佳实践

✅ 推荐做法

  • 函数描述要清晰准确
  • 参数类型定义要完整
  • 提供参数示例和说明
  • 实现函数结果验证
  • 处理异常和边界情况

❌ 避免做法

  • 函数名称模糊不清
  • 参数过于复杂嵌套
  • 忽略参数验证
  • 函数执行时间过长
  • 返回格式不一致

重要提醒

  • • 函数调用会消耗额外的Token
  • • 不是所有模型都支持函数调用(需要gpt-3.5-turbo-0613或更新版本)
  • • 函数执行的安全性由您负责
  • • 建议对函数调用进行权限控制
  • • 函数结果大小有限制(建议不超过1000 tokens)