深色模式
工具调用 / Function Calling
是什么
向模型声明一组函数(名称、描述、JSON Schema 参数),模型在需要时返回"要调用哪个函数 + 参数",由你的代码真正执行,再把结果回传给模型。
这是 Agent 与纯聊天机器人的分水岭:模型负责决策,代码负责执行。
为什么需要
只有能调用工具(查数据库、跑命令、发消息、调 API),Agent 才能作用于真实世界,而不只是生成文本。
核心概念
- 工具定义:
name+description+parameters(JSON Schema)。 - 调用循环:模型输出
tool_calls→ 你执行 → 以role: tool回传结果 → 模型继续。 - 并行调用:模型一次可返回多个工具调用,需并发执行后合并。
- Human-in-the-loop:高危操作(删除、支付)先暂停,等人确认。
最小代码范式
python
tools = [{
"type": "function",
"function": {
"name": "get_pod_status",
"description": "查询指定命名空间下 Pod 的状态",
"parameters": {
"type": "object",
"properties": {
"namespace": {"type": "string"},
"pod": {"type": "string"},
},
"required": ["namespace", "pod"],
},
},
}]
messages = [{"role": "user", "content": "查一下 default 下 nginx 的状态"}]
resp = client.chat.completions.create(
model="gpt-4o-mini", messages=messages, tools=tools, tool_choice="auto"
)
msg = resp.choices[0].message
if msg.tool_calls:
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = get_pod_status(**args) # 你的真实执行
messages.append(msg) # 保留模型原消息
messages.append({ # 回传工具结果
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False),
})
follow = client.chat.completions.create(model="gpt-4o-mini", messages=messages)
print(follow.choices[0].message.content)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
常见陷阱
- 工具描述太宽:模型乱调用。描述要写清"何时该用、何时不该用"。
- 无超时 / 无沙箱:执行外部命令必须加超时与权限边界,否则模型可触发危险操作。
- 无限循环:模型反复调用工具不停止,需设最大轮次(max steps)。
- 不校验参数:直接使用模型给的参数,可能越权访问其他资源。
何时需要 Human-in-the-loop
删除/修改生产资源、发送对外消息、调用付费 API——这类动作应在执行前暂停并请求确认,确认结果再以 tool 消息回传。
参考
- OpenAI Function Calling 文档
- Anthropic Tool Use 文档
- MCP(Model Context Protocol)规范