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);