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);
相关推荐
云烟成雨TD2 小时前
LlamaIndex 系列【31】检索增强策略:命名实体识别(NER)
ai·agent·rag·llamaindex
slacker-kian2 小时前
本地大模型 + 自建 MCP Server + SAP OData:让 LLM 代理 SAP 业务操作
大模型·llm·sap·agent·mcp·odata
Flynt2 小时前
Shopify 弃 React Native 上了 HN 1272 分,我复现了它给 Agent 用的那套无头架构
react native·前端框架·agent
leoZ2312 小时前
第 10 篇 数据飞轮与冷启动:AI 产品的数据从哪来
人工智能·大模型·agent
坐吃山猪4 小时前
Harness Engineering知识总结
llm·agent·harness
杨杨杨大侠4 小时前
RAG 到底是怎么工作的?从用户提问到模型回答的完整链路
spring·openai·ai编程
李燚4 小时前
Agent 要用 API key,但明文一次都不能进模型——Secret Runtime 落地实录(第110篇)
ai·agent·credential·secret·eino·deepflux·secret runtime
invicinble4 小时前
agent操作Windows的原理,以及操作其他的操作系统里面的数据
agent
wangruofeng5 小时前
把AI判断做成「智能if语句」!Jev实测:一次调用3个判断,置信度直接路由
aigc·agent·ai编程