Function Calling 解锁Agent与外部系统交互

LLM 具有强大的推理能力,它能够根据训练数据和输入的 Prompt 生成文本。但是它无法获取实时数据(比如今天的天气),也无法执行具体操作(比如发邮件)。

问题在于现有的程序只能通过结构化的函数调用,例如:

js 复制代码
function toolCall(param: ToolParam): ToolResult;

所以 LLM 需要将用户的自然语言需求转换为结构化的函数调用,才能与其它程序交互。

Function Calling 是一种 LLM 调用 Tool 的机制。当 LLM 识别用户需求需要调用 Tool 时,它会生成结构化的函数调用指令,然后由 Agent 执行指定函数并将结果反馈给 LLM,最后 LLM 基于结果进行下一步操作。

LLM生成结构化的函数调用指令:

js 复制代码
{
  "id": "chatcmpl-abc123",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{"city": "北京", "date": "today"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

Agent解析函数调用指令,根据 function.name 找到对应的函数,解析 function.arguments 获取参数,然后执行调用。

js 复制代码
// 1. 解析LLM返回的函数调用指令
const toolCall = response.choices[0].message.tool_calls[0];
const functionName = toolCall.function.name;  
const functionArgs = JSON.parse(toolCall.function.arguments);  

// 2. 根据工具名称找到对应的函数
const tools = {
    get_weather: ({city, date}) => {    
        // 调用天气查询API   
        return {
            "temperature": 22,
            "condition": "晴天",
            "humidity": 45
        };  
    },  
};
// 3. 执行工具调用
const result = tools[functionName](functionArgs);
相关推荐
前端双越老师11 分钟前
程序员 1v1 访谈系列第九期:要不要晋升管理层?
agent·ai编程·全栈
vipxieliang14 分钟前
数字员工上岗实录:各行业 Agent 部署案例集
openai
威哥爱编程38 分钟前
Python 智能体开发实战 03:聊十轮就“失忆”,账单还翻倍?管好上下文,Token 立省一半
python·agent
墨林陌40 分钟前
AI 热点日报(2026-10-30):新芯航途发布 700 TOPS 大模型芯片,微软发债 250 亿加码 AI,谷歌财报现现金流红灯
openai
威哥爱编程1 小时前
Python 智能体开发实战 04:模型答得挺漂亮,程序却读不懂?让回答直接变成能入库的 JSON
python·agent
mudtools1 小时前
在飞书 SDK 上用 Microsoft Agent Framework 搭一个能干活的工作搭子
人工智能·ai·.net·飞书·agent
海盗12341 小时前
微软技术日报 2026-10-29:Copilot harness 进 Foundry,云重建能拉镜像
人工智能·microsoft·机器人·aigc·copilot
lucas_AI2 小时前
别让大模型一个字一个字点手机了:GUI-JEPA 用「打分」替代「解码」,快 3 倍只花 6% 参数
人工智能·agent
前进的李工2 小时前
Agent 学习笔记 04:KV Cache 与上下文缓存
笔记·学习·缓存·agent·注意力机制·kv cache·prompt cache
愤怒的代码2 小时前
什么是Paged Attention?
人工智能·agent