AI知识篇

什么是Function Calling

让AI不只是"说",还能"做"

大语言模型天生只会生成文字。但通过 Function Calling(函数调用),AI 可以调用你定义的函数来执行实际操作——查数据库、发邮件、控制设备、调用API。

💡 类比:普通 AI 就像一个只会说话的顾问("你应该查一下天气"),Function Calling 让 AI 变成一个能动手的助手(直接帮你查好天气告诉你结果)。

加载图表中...

工作原理

Function Calling 的流程分为三步:

加载图表中...

三个关键步骤

步骤谁来做做什么
AI 决定调用大语言模型分析用户意图,选择函数和参数
执行函数你的代码实际调用API或执行操作
AI 总结结果大语言模型把函数结果组织成自然语言回复

重要:AI 不直接执行函数,它只是告诉你应该调用哪个函数、传什么参数。实际执行是你的代码负责的。

代码实现

第一步:定义函数(告诉 AI 有哪些工具可用)

const tools = [
  {
    type: "function",
    function: {
      name: "get_weather",
      description: "获取指定城市的当前天气",
      parameters: {
        type: "object",
        properties: {
          city: {
            type: "string",
            description: "城市名称,如'北京'、'上海'",
          },
        },
        required: ["city"],
      },
    },
  },
  {
    type: "function",
    function: {
      name: "send_email",
      description: "发送邮件",
      parameters: {
        type: "object",
        properties: {
          to: { type: "string", description: "收件人邮箱" },
          subject: { type: "string", description: "邮件主题" },
          body: { type: "string", description: "邮件内容" },
        },
        required: ["to", "subject", "body"],
      },
    },
  },
];

第二步:发送请求,AI 决定调用哪个函数

import OpenAI from "openai";
const openai = new OpenAI();

const response = await openai.chat.completions.create({
  model: "gpt-4",
  messages: [
    { role: "user", content: "北京今天天气怎么样?" },
  ],
  tools,  // 告诉AI有哪些函数可用
});

const choice = response.choices[0];

if (choice.finish_reason === "tool_calls") {
  // AI 决定调用函数
  const toolCall = choice.message.tool_calls[0];
  console.log(toolCall.function.name);       // "get_weather"
  console.log(toolCall.function.arguments);  // '{"city": "北京"}'
}

第三步:执行函数,把结果返回给 AI

// 你的函数实现
async function get_weather(city) {
  const res = await fetch(`https://api.weather.com?city=${city}`);
  return await res.json();
}

// 执行 AI 选择的函数
const args = JSON.parse(toolCall.function.arguments);
const result = await get_weather(args.city);

// 把结果传回 AI,让它生成最终回复
const finalResponse = await openai.chat.completions.create({
  model: "gpt-4",
  messages: [
    { role: "user", content: "北京今天天气怎么样?" },
    choice.message,  // AI 的函数调用决定
    {
      role: "tool",
      tool_call_id: toolCall.id,
      content: JSON.stringify(result),  // 函数执行结果
    },
  ],
});

console.log(finalResponse.choices[0].message.content);
// "北京今天天气晴朗,气温25°C,微风,适合户外活动!"

Function Calling 的应用场景

加载图表中...
场景函数AI 的作用
"帮我查一下订单状态"get_order(id)提取订单号,调用函数
"给张三发一封会议邀请"send_email(to, subject, body)组织邮件内容,调用发送
"把这个文件重命名"rename_file(old, new)理解意图,调用文件操作
"帮我订一张明天的机票"book_flight(from, to, date)提取出发地、目的地、日期

并行调用多个函数

AI 可以一次决定调用多个函数

// 用户: "帮我查北京和上海的天气"
// AI 返回两个 tool_calls:
// tool_calls: [
//   { function: { name: "get_weather", arguments: '{"city":"北京"}' } },
//   { function: { name: "get_weather", arguments: '{"city":"上海"}' } },
// ]

Function Calling vs 直接在 Prompt 中写

对比Prompt 中让 AI 输出 JSONFunction Calling
结构化AI 可能输出格式不对严格按定义输出
可靠性不稳定稳定可靠
参数校验有类型和必填校验
多函数选择需要复杂提示词AI 自动选择

Function Calling 与 Agent 的关系

加载图表中...

Function Calling 是 Agent 的基础能力。Agent 通过 Function Calling 来"动手"做事情,每一轮循环中都可能调用多个函数。

🎯 AI编程小贴士:想给你的 AI 应用加上"能力"?先想清楚你需要哪些函数(查数据、发消息、操作文件等),然后用 Function Calling 让 AI 自动判断什么时候调用它们。告诉 AI"帮我实现一个能查天气和发邮件的AI助手",它会帮你搭建完整的 Function Calling 架构。

小结

  • Function Calling 让 AI 能调用你定义的函数,从"只会说"变成"能做事"
  • 三步流程:AI 决定调用 → 你的代码执行 → AI 总结结果
  • AI 不直接执行函数,只是告诉你该调用什么、传什么参数
  • 是构建 AI Agent 的核心基础能力
  • 支持并行调用多个函数,输出结构化、可靠