Function Calling 协议与执行流程
约 433 字大约 1 分钟
布欧-Lewyon
2026-06-08
首页 › Agent Spring Boot › Function Calling
子项目:agent-function-calling
在 agent-web-flux 基础上增加 AgentService,手写 OpenAI 兼容的 Function Calling 全流程。仍用 WebClient,不用 Spring AI @Tool。
六步循环
AgentService 类注释写清了流程:
1. 用户发消息
2. 带着 tools 定义请求 LLM
3. LLM 返回 tool_calls(finish_reason = tool_calls)
4. 本地执行工具
5. 将 tool 结果追加到 messages
6. 再次请求 LLM,直到 finish_reason = stop请求体差异
| 模式 | stream | tools | 端点 |
|---|---|---|---|
| 聊天 | true | 无 | /api/chat/stream |
| Agent | false | TOOLS 列表 | /api/agent/chat |
Agent 必须非流式:要等 tool 往返完成才能给出可靠答案。
body.put("model", model);
body.put("messages", messages);
body.put("tools", TOOLS);
body.put("stream", false);Message 角色
| role | 用途 |
|---|---|
system | 工具使用策略 |
user | 用户输入 |
assistant | 模型回复;有 tool_calls 时 content 须为 null |
tool | 工具执行结果,带 tool_call_id |
ChatMessage 用 @JsonInclude(ALWAYS) 保证 content: null 被序列化,否则 DeepSeek 返回 400。
学习点
- Function Calling 是协议行为:
tools模式 +finish_reason分支。 - 框架(Spring AI)帮你注册 Tool;本项目手写是为了看清协议细节。
- 多 Tool 时模型可能一次返回多个
tool_calls,需并行执行再合并。
小结
agent-function-calling在流式聊天旁路增加 Agent 非流式 JSON 接口。- 核心是
finish_reason:stop结束,tool_calls递归下一轮。 ChatMessage四角色序列化是常见踩坑点。
