AI Agent / 系统课时

Function Calling 原理

Function Calling 原理

模型可以提出工具调用。应用把工具名称和参数结构告诉模型,接到调用请求后解析参数、检查权限、执行工具,并把结果交回模型。一次模型响应可以不调用工具,也可以请求多个工具。

Function Calling 从模型决策到工具结果回传的闭环

区分三份数据

数据 来自哪里 用途
工具描述 应用提供 告诉模型工具能做什么及参数结构
调用请求 模型返回 指明工具名、参数和调用 ID
调用结果 应用生成 告知模型哪个调用成功、失败或缺少数据

即使启用严格结构,应用也要检查权限和业务约束。例如一个字符串城市名可能符合参数结构,但该城市不在示例服务的覆盖范围内。调用参数来自模型,工具结果也可能含有外部文字,两者都按输入数据处理。

用离线数据走完消息往返

以下沿用本课程的 Chat Completions 消息格式。模型返回的 function.arguments 是 JSON 字符串,工具消息使用 tool_call_id 对应那次请求。示例不接天气服务,返回的是固定测试数据。

python
import json

FORECASTS = {"Shanghai": {"temperature_c": 26, "condition": "cloudy"}}

def execute(call):
    function = call["function"]
    if function["name"] != "get_weather":
        return {"error": "unknown_tool"}
    try:
        args = json.loads(function["arguments"])
    except json.JSONDecodeError:
        return {"error": "invalid_json"}
    if (not isinstance(args, dict) or set(args) != {"city"}
            or not isinstance(args["city"], str)):
        return {"error": "invalid_arguments"}
    city = args["city"]
    if city not in FORECASTS:
        return {"error": "out_of_coverage"}
    return {"city": city, **FORECASTS[city]}

assistant = {
    "role": "assistant",
    "content": None,
    "tool_calls": [
        {"id": "call_1", "type": "function",
         "function": {"name": "get_weather", "arguments": '{"city":"Shanghai"}'}},
        {"id": "call_2", "type": "function",
         "function": {"name": "get_weather", "arguments": '{"city":"Atlantis"}'}},
    ],
}
messages = [{"role": "user", "content": "查上海和 Atlantis 的天气。"}, assistant]
for call in assistant["tool_calls"]:
    messages.append({
        "role": "tool",
        "tool_call_id": call["id"],
        "content": json.dumps(execute(call), ensure_ascii=False),
    })

for message in messages[2:]:
    print(message["tool_call_id"], json.loads(message["content"]))

call_1 对应上海测试数据,call_2 对应 out_of_coverage。把两条结果和原助手消息一起提交下一轮。即使一次调用失败,也要把对应结果交回去。下一轮模型可以回答,也可能继续请求工具,应用应设定循环上限。换成 Responses API 时,结果项使用 function_call_output 和 call_id,消息结构应按各接口文档分别构造。

用什么判断链路接通

先查调用 ID 和结果是否一一对应,再核对最终文字有没有忠实反映工具结果。本例若模型把测试值说成实时观测,或给 Atlantis 编出温度,即使所有消息发送成功,答案仍然不合格。真实工具还需把参数错误、权限拒绝、超时和空结果区分开,避免原样返回内部堆栈。

按自己的节奏,确认真正理解。

目录与阅读设置

记录一个想法

Function Calling 原理

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通