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);
相关推荐
苏灿烤鱼44 分钟前
连庄+2,729,空降榜眼只+440
rust·openai·agent
SeaDhdhdhdhdh9 小时前
MCP Server 搭建与使用指南
java·ai·agent·mcp
李姆斯9 小时前
为啥Agent在coding表现这么好,但是在别的领域就是差的不少?
前端·agent·ai编程
nix.gnehc9 小时前
工具表之外 -- 派生、注入与两条原语
agent
芯小途202610 小时前
微短剧新规 9 月 1 日施行:AIGC 微短剧的「AI 标识 + 占比追溯」怎么在制作流水线里落地(附自查脚本)
人工智能·aigc
kaliarch11 小时前
WorkBuddy Skill:把重复 SOP 打成可调用的手册包
aigc
HIT_Weston12 小时前
181、【Agent】【OpenCode】TuiThreadCmd(类型增长)(编译&运行时)
人工智能·agent·opencode
Dawson Zhu13 小时前
图结构(Graph)如何重构智能体认知?从DAG规划到GraphRAG的技术拆解
人工智能·语言模型·重构·架构·aigc
奈斯先生Vector14 小时前
从 127.0.0.1:3080 到插件运行时:DeepSeek Harness 远程开发与版本治理实战
linux·运维·人工智能·ubuntu·aigc