AI 智能体是怎么调用工具的?
-
用户问:“现在几点”,内部会把【当前可以使用的工具有“系统时间查询”】也一并发给 LLM。 -
LLM 判断用户的问题结合可用的工具列表,回答:调用系统时间查询工具。 -
然后用户把工具的调用结果,重新发送给 LLM。 -
LLM 收到信息,系统时间查询工具调用成功,最终回答:最终时间答案。
{"role": "user","content": "现在是几点"},{"role": "assistant","content": null,"tool_calls": [{"id": "toolu_vrtx_01TUfx63H6ANfy4tvam3gswL","type": "function","function": {"name": "get_current_time","arguments": "{}"}}]},{"role": "tool","tool_call_id": "toolu_vrtx_01TUfx63H6ANfy4tvam3gswL","content": "2026-05-02 11:39:19"},{"role": "assistant","content": "现在是 **2026年5月2日 11点39分19秒**。"}
┌─────────────┐│ User ││ "现在几点?" │└──────┬──────┘│▼┌─────────────────────────────────────────────────┐│ Agent 主循环 ││ ││ ┌─────────────────────────────────────────┐ ││ │ 组装消息列表 messages │ ││ │ │ ││ │ [{"role": "user", "content": "现在几点"}] │ ││ │ + tools (函数描述列表) │ ││ └─────────────────────────────────────────┘ ││ │ ││ ▼ ││ POST /v1/chat/completions │└──────────────────────┬──────────────────────────┘│▼┌──────────────────────────────────────────────┐│ LLM Hub 服务端 ││ ││ LLM 分析:用户问时间 → 需要调用 get_current_time ││ ││ 返回带 tool_calls 的响应 │└──────────────────────┬───────────────────────┘│▼┌─────────────────────────────────┐│ choices[0].message: ││ role: assistant ││ content: null ││ tool_calls: [ ││ { ││ id: "call_abc123", ││ function: { ││ name: "get_current_time",││ arguments: "{}" ││ } ││ } ││ ] │└──────────────┬──────────────────┘│ 检测到 tool_calls,进入工具执行分支▼┌────────────────────────────────────────────────────┐│ Agent 执行工具 ││ ││ 1. 将 tool_calls 追加到 conversation_history.json ││ 2. 本地执行 get_current_time() ││ 3. 得到结果 "2026-05-02 14:30:00" ││ 4. 将 tool_result 追加到消息列表 ││ ││ 消息列表现在是: ││ ┌─────────────────────────────────────────────┐ ││ │ 1. user: "现在几点?" │ ││ │ 2. assistant: tool_calls=[...] │ ││ │ 3. tool: id=call_abc123, content="2026-..." │ ││ └─────────────────────────────────────────────┘ │└────────────────────┬───────────────────────────────┘│ 继续循环,将含 tool_result 的消息发回 LLM▼┌─────────────────────────────────────────────────────┐│ 再次 POST /v1/chat/completions ││ ││ LLM 拿到工具结果 → 生成最终回答 │└──────────────────────┬──────────────────────────────┘│▼┌──────────────────────────┐│ choices[0].message: ││ role: assistant ││ content: "现在是..." ││ tool_calls: null ✅ │└──────────┬───────────────┘│ 没有 tool_calls,循环结束▼┌──────────────┐│ 返回给用户 ││ "现在是14:30" │└──────────────┘核心就是一个循环对话:1. LLM 决定要不要用工具 → 返回 tool_calls2. Agent 执行工具 → 把结果作为 tool 消息追加3. 把完整消息列表再发给 LLM → 如果没有 tool_calls 了就结束
夜雨聆风