AI 的根本局限

普通 AI 对话:用户问 → AI 从训练数据里"回忆"答案 → 输出文字

问题:
- AI 不知道今天的天气(训练数据有截止日期)
- AI 不能查你们数据库里的课程信息
- AI 不能帮你发邮件、下单、调用内部 API
- AI 只能"说",不能"做"

Function Calling 就是给 AI 装上"手",让它能调用真实世界的功能。

核心工作流程
不是 AI 直接调用函数,而是一个协商过程:

你          →    AI           →    你的代码        →    AI
"查一下        "我需要调用        执行真实的          "根据查询
 小明的         get_user_info     数据库查询           结果,小明
 学习进度"      函数,参数         SELECT ...          的学习进度
               userId: '小明'"                        是..."

一个完整的例子

场景:让 AI 能查询学生的课程进度。

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

const tools = [
  {
    type: 'function',
    function: {
      name: 'get_student_progress',           // 函数名
      description: '查询学生的课程学习进度',    // 关键!AI 靠这个决定要不要调用
      parameters: {
        type: 'object',
        properties: {
          studentId: {
            type: 'string',
            description: '学生ID',
          },
          courseId: {
            type: 'string', 
            description: '课程ID,不传则查所有课程',
          },
        },
        required: ['studentId'],
      },
    },
  },
];

第二步:第一次请求 AI

const response = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [
    { role: 'user', content: '帮我查一下学生 stu_123 的学习进度' }
  ],
  tools,  // 把工具定义传给 AI
});

const message = response.choices[0].message;

第三步:判断 AI 是否要调用函数

if (message.tool_calls) {
  // AI 决定要调用函数了
  const toolCall = message.tool_calls[0];
  
  console.log(toolCall.function.name);      // "get_student_progress"
  console.log(toolCall.function.arguments); // '{"studentId":"stu_123"}'
  
  // 解析参数
  const args = JSON.parse(toolCall.function.arguments);
  
  // 第四步:你的代码真正去执行
  const result = await getStudentProgress(args.studentId, args.courseId);
  
  // 第五步:把执行结果告诉 AI,让它继续回答
  const finalResponse = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [
      { role: 'user', content: '帮我查一下学生 stu_123 的学习进度' },
      message,  // AI 说"我要调用函数"的那条消息
      {
        role: 'tool',
        tool_call_id: toolCall.id,
        content: JSON.stringify(result),  // 函数执行结果
      },
    ],
    tools,
  });
  
  // AI 现在根据真实数据给出回答
  console.log(finalResponse.choices[0].message.content);
  // "学生 stu_123 目前已完成《React 入门》课程的 73%,..."
}

整个过程的时序图

用户: "查一下学生进度"
         ↓
    第一次请求 AI
         ↓
AI 返回: { tool_calls: [{ name: "get_student_progress", args: {...} }] }
         ↓
    你的代码执行真实查询(数据库/API)
         ↓
    把结果放进消息里,第二次请求 AI
         ↓
AI 返回: "根据查询结果,该学生的进度是..."
         ↓
      展示给用户

所有你看到的"AI 自动完成任务",底层都是这个循环:
想 → 调工具 → 看结果 → 想 → 调工具 → 看结果 → ... → 完成

标签: none

添加新评论