2026-10-20 21:02:26 +08:00
<!DOCTYPE html>
< html lang = "zh-CN" data-theme = "light" >
< head >
< meta charset = "utf-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< title > 第 4 章 AI Agent 前置:模型协议、工具调用与 MCP · AI Agent 脚手架项目学习< / title >
< meta name = "description" content = "把 Chat Completions、Function Calling、MCP、Skill 这四件事讲到能直接对上代码的程度,重点讲清一轮工具调用的闭环。" >
< meta name = "keywords" content = "LLM,Chat Completions,Function Calling,MCP,JSON-RPC,Skill,流式" >
< link rel = "stylesheet" href = "assets/doc.css" >
< / head >
< body >
< header class = "topbar" >
< div class = "tb-in" >
< a class = "brand" href = "index.html" > < span class = "logo" > AG< / span > < div > AI Agent 脚手架项目学习< small > Go + Agent · 源码拆解 / 装配链 / 面试模拟< / small > < / div > < / a >
< nav class = "partnav" id = "partnav" > < a class = "home" href = "index.html" > 学习地图< / a > < span class = "pn-sep" > < / span > < a href = "part-0.html" > 篇 0 前言< / a > < a href = "part-1.html" class = "on" > 篇 1 知识学习< / a > < a href = "part-2.html" > 篇 2 项目拆解< / a > < a href = "part-3.html" > 篇 3 缺陷与演进< / a > < a href = "part-4.html" > 篇 4 场景还原< / a > < a href = "part-5.html" > 篇 5 收尾< / a > < / nav >
< div class = "spacer" > < / div >
< button class = "btn" id = "tocToggle" > ☰ 导航< / button >
< button class = "btn" id = "themeBtn" title = "切换到深色主题" > 深色< / button >
< / div >
< / header >
< div class = "layout" id = "layout" >
< aside class = "sidebar" >
< h2 > 章节目录< / h2 >
< nav id = "chapters" > < div class = "toc-scope" > < span class = "ts-label" > 篇 1< / span > < span class = "ts-name" > 知识学习< / span > < a class = "ts-all" href = "index.html" > 全部篇章 →< / a > < / div > < a class = "toc-a" href = "03-basics-go.html" > < i class = "cn" > 3< / i > Go 与 Web 基础: Gin、YAML、SSE 与泛型< / a > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 4< / i > AI Agent 前置:模型协议、工具调用与 MCP< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-4-1" > 4.1 Chat Completions 协议:消息角色与字段< / a > < a class = "toc-a lv3" href = "#sec-4-2" > 4.2 工具调用闭环:模型说要用什么,谁来执行< / a > < a class = "toc-a lv3" href = "#sec-4-3" > 4.3 MCP: 一个标准化的工具协议< / a > < a class = "toc-a lv3" href = "#sec-4-4" > 4.4 MCP 的 SSE 传输与 JSON-RPC 2.0< / a > < a class = "toc-a lv3" href = "#sec-4-5" > 4.5 Skill: 把长提示词拆成可复用目录< / a > < a class = "toc-a lv3" href = "#sec-4-6" > 4.6 流式输出与增量拼接的两个难点< / a > < / div > < / nav >
2026-10-22 21:59:12 +08:00
< div class = "side-foot" >
2026-10-20 21:02:26 +08:00
< a class = "btn" href = "index.html" > ← 学习地图< / a >
2026-10-22 21:59:12 +08:00
< a class = "btn" href = "23-cheatsheet.html" > 速查与自测< / a >
2026-10-20 21:02:26 +08:00
< / div >
< / aside >
< div class = "mask" id = "mask" > < / div >
< main class = "main-col" >
< article >
< p class = "chapnav" >
< a href = "index.html" > AI Agent 脚手架项目学习< / a >
< span > ·< / span >
< a href = "part-1.html" > 篇 1 知识学习< / a >
< span > ·< / span >
2026-10-22 21:59:12 +08:00
< span > 第 < b class = "pos" > 4< / b > / 23 章< / span >
2026-10-20 21:02:26 +08:00
< / p >
< h2 id = "ch4" > < span class = "n" > 4< / span > AI Agent 前置:模型协议、工具调用与 MCP< / h2 >
< div class = "lead" >
2026-10-20 21:09:36 +08:00
< b > 这一章解决什么:< / b > 只要涉及 Agent, 就绕不开四件事: 怎么和模型说话( Chat Completions) 、
怎么让模型用工具( Function Calling) 、工具从哪来( MCP) 、长提示词怎么复用( Skill) 。
这一章不追求协议大全,而是把每个概念讲到< b > 能直接对上本项目代码< / b > 的程度,重点是 4.2 那一轮工具调用的闭环——
读懂它,后面第 10、11、12 章都是在给这条闭环补细节。
2026-10-20 21:02:26 +08:00
< / div >
< h3 id = "sec-4-1" > 4.1 Chat Completions 协议:消息角色与字段< / h3 >
2026-10-20 21:09:36 +08:00
< p > 所有 OpenAI 兼容服务都只认一个形状:< code > POST /v1/chat/completions< / code > ,请求体三个必填 + 一个可选:< / p >
< ul >
< li > < code > model< / code > :模型名,本项目来自 YAML 的 < code > chat-model.model< / code > ; < / li >
< li > < code > messages< / code > :一个数组,元素是 < code > {role, content, ...}< / code > ,整轮对话就是靠它「重放」的;< / li >
< li > < code > stream< / code > : < code > true< / code > 时逐块返回,< code > false< / code > 时一次性返回;< / li >
< li > < code > tools< / code > (可选):模型可用的函数清单,见 4.2。< / li >
< / ul >
< p > 四个角色各有分工,< b > 最容易搞错的是 assistant 与 tool< / b > : assistant 负责「提出调用」, tool 负责「回传结果」,两者靠
< code > tool_call_id< / code > 配对。本项目把这种「没有聊天历史」的用法写死在 < code > initialMessages< / code > 里:
每次请求都是 < code > system< / code > + < code > user< / code > 两条起步,工具轮才追加 assistant/tool。< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > role< / th > < th > 谁产生< / th > < th > 关键字段< / th > < th > 本项目里的位置< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > system< / code > < / td > < td > 应用( instruction) < / td > < td > < code > content< / code > < / td > < td > < code > adapter.go:379-386< / code > < code > initialMessages< / code > < / td > < / tr >
< tr > < td > < code > user< / code > < / td > < td > 用户消息的第一段文本< / td > < td > < code > content< / code > < / td > < td > < code > adapter.go:475-480< / code > < code > firstText< / code > < / td > < / tr >
< tr > < td > < code > assistant< / code > < / td > < td > 模型自己< / td > < td > < code > content< / code > 可为空,< code > tool_calls[]< / code > < / td > < td > < code > adapter.go:186< / code > 追加< / td > < / tr >
< tr > < td > < code > tool< / code > < / td > < td > 应用(工具执行结果)< / td > < td > < code > content< / code > + < code > tool_call_id< / code > + < code > name< / code > < / td > < td > < code > adapter.go:286-291< / code > 构造< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 编码逻辑集中在 < code > encodeMessages< / code > , 它处理了协议的两个边角: assistant 消息如果只有 tool_calls、没有文本,
要< b > 省略 content 字段< / b > 而不是传空串;其它角色则必须显式带上 < code > content: ""< / code > 。这个差异不写对,
部分上游会直接 400: < / p >
< pre data-lang = "go" data-name = "internal/infrastructure/ai/openai_client.go:240-272( 有删节) " > for _, m := range messages {
entry := map[string]any{"role": string(m.Role)}
if m.Content != "" {
entry["content"] = m.Content
} else if m.Role != ports.ChatRoleAssistant || len(m.ToolCalls) == 0 {
entry["content"] = "" // 非「纯工具调用的 assistant」, 必须给空串
}
if m.ToolCallID != "" { entry["tool_call_id"] = m.ToolCallID }
if len(m.ToolCalls) > 0 { entry["tool_calls"] = ... } // id / type=function / function{name,arguments}
encoded = append(encoded, entry)
}< / pre >
< p > 一次真实的请求长这样(省略了 tools) : < / p >
< pre data-lang = "json" data-name = "工具轮请求的消息数组(示意)" > [
{"role":"system","content":"你是一个 draw.io 绘图专家……"},
{"role":"user","content":"画一个用户登录流程图"},
{"role":"assistant","content":"我查一下行业惯例",
"tool_calls":[{"id":"call_1","type":"function",
"function":{"name":"baidu-search","arguments":"{\"query\":\"登录流程 图\"}"}}]},
{"role":"tool","content":"(搜索结果文本)","tool_call_id":"call_1","name":"baidu-search"}
]< / pre >
2026-10-20 21:02:26 +08:00
< h3 id = "sec-4-2" > 4.2 工具调用闭环:模型说要用什么,谁来执行< / h3 >
2026-10-20 21:09:36 +08:00
< p > 「Function Calling」这个名字容易误解: < b > 模型从不执行工具,它只会输出一段「我想调谁、参数是什么」的 JSON< / b > 。
执行是应用的事。所以完整闭环有四个动作,缺一不可:< / p >
< ol >
< li > < b > 声明< / b > :请求里带 < code > tools< / code > ,每个工具一个 name + description + JSON Schema; < / li >
< li > < b > 请求< / b > :模型返回 < code > tool_calls< / code > ( id、name、arguments 是一个< b > 字符串形式的 JSON< / b > ) ; < / li >
< li > < b > 执行< / b > :应用解析 arguments, 调用真实工具, 拿到结果; < / li >
< li > < b > 回灌< / b > :把结果作为 < code > role=tool< / code > 消息追加,带上同一个 < code > tool_call_id< / code > ,再请求一次模型。< / li >
< / ol >
< p > 本项目把第 2– 4 步包成一个循环,上限硬编码 4 轮(< code > maxToolCallIterations< / code > ),超过就直接报错而不是「尽力而为」:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:173-195" > for iter := 0; iter < maxToolCallIterations; iter++ {
reply, err := a.chatModel.Generate(ctx, messages)
if err != nil { return "", err }
if len(reply.ToolCalls) == 0 { // ① 没工具调用 = 最终答案
return reply.Content, nil
}
messages = append(messages, ports.ChatMessage{ // ② 保留模型提出的调用
Role: ports.ChatRoleAssistant, Content: reply.Content, ToolCalls: reply.ToolCalls})
toolMessages, err := a.executeToolCalls(ctx, reply.ToolCalls) // ③ 真的去执行
if err != nil { return "", err }
messages = append(messages, toolMessages...) // ④ 结果回灌,进入下一轮
}
return "", fmt.Errorf("agent %q exceeded tool-call iteration limit %d", a.name, maxToolCallIterations)< / pre >
< p > < code > executeToolCalls< / code > 只做两件事:把 arguments 原样交给 < code > ToolRouter< / code > ,再把返回文本包成 tool 消息。
注意< b > 任何一个工具失败都会让整轮失败< / b > ,而不是把错误当成工具结果交给模型自我纠正:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:274-294( 有删节) " > if a.router == nil { return nil, fmt.Errorf("agent %q has no tool router but model requested tool calls", a.name) }
for _, call := range calls {
result, err := a.router.CallTool(ctx, call.Name, call.Arguments)
if err != nil { return nil, fmt.Errorf("tool %q: %w", call.Name, err) } // 直接中断
out = append(out, ports.ChatMessage{Role: ports.ChatRoleTool, Content: result,
ToolCallID: call.ID, Name: call.Name})
}< / pre >
< div class = "box warn" >
< span class = "bt" > 这个项目在工具协议上最硬的一处妥协< / span >
< p > 声明工具时,所有工具的参数都被写死成同一个 < code > query: string< / code > ( < code > openai_client.go:278-299< / code > ) ,
而不是各自的 JSON Schema。这意味着模型只知道「有个叫 baidu-search 的工具,收一个 query」;
可执行时 < code > CallTool< / code > 又把这段 arguments < b > 原样< / b > 转发给 MCP 服务端,服务端按自己的 schema 校验就会失败。
正确的做法是让工具自己提供 schema( < code > ports.Tool< / code > 目前只有 < code > Name()< / code > ,缺 < code > Description()< / code > 与 < code > Schema()< / code > ) ,
这也是 P0-3 与 P1-9 两条缺陷的共同根因。< / p >
< / div >
2026-10-20 21:02:26 +08:00
< h3 id = "sec-4-3" > 4.3 MCP: 一个标准化的工具协议< / h3 >
2026-10-20 21:09:36 +08:00
< p > 如果每个工具都要在代码里手写一份声明 + 一份执行逻辑, 工具生态就长不起来。MCP( Model Context Protocol) 解决的就是这件事:
< b > 工具由服务端自描述,客户端在启动时问它「你有什么」,运行期按名字调用< / b > 。它是 JSON-RPC 2.0 之上的一层约定,
和具体传输无关( stdio、HTTP+SSE、Streamable HTTP 都能承载)。< / p >
< p > 生命周期只有五步,本项目全部实现:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 阶段< / th > < th > 方法< / th > < th > 方向< / th > < th > 本项目位置< / th > < / tr > < / thead >
< tbody >
< tr > < td > 建连< / td > < td > < code > GET /sse< / code > ( Accept: text/event-stream) < / td > < td > 客户端 → 服务端< / td > < td > < code > mcp_sse_client.go:107-125< / code > < code > openSSE< / code > < / td > < / tr >
< tr > < td > 拿投递地址< / td > < td > < code > event: endpoint< / code > < / td > < td > 服务端 → 客户端< / td > < td > < code > handleEndpoint< / code > < / td > < / tr >
< tr > < td > 握手< / td > < td > < code > initialize< / code > + < code > notifications/initialized< / code > < / td > < td > 客户端 → 服务端< / td > < td > < code > initialize:305-321< / code > < / td > < / tr >
< tr > < td > 发现< / td > < td > < code > tools/list< / code > < / td > < td > 客户端 → 服务端< / td > < td > < code > ListTools:348-369< / code > < / td > < / tr >
< tr > < td > 调用< / td > < td > < code > tools/call< / code > < / td > < td > 客户端 → 服务端< / td > < td > < code > CallTool:326-345< / code > < / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 本项目的支持程度并不均等,读配置时要心里有数:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 传输< / th > < th > 配置校验< / th > < th > 启动期发现< / th > < th > 运行期执行< / th > < / tr > < / thead >
< tbody >
< tr > < td > sse< / td > < td > 要求 name + base-uri, 超时非负< / td > < td > 真连服务端 < code > tools/list< / code > ( 10s 超时)< / td > < td > 可执行,转发 < code > tools/call< / code > < / td > < / tr >
< tr > < td > stdio< / td > < td > 要求 name + command< / td > < td > 只构造 < code > MCPTool< / code > ,不起子进程< / td > < td > 不可执行,报 < code > transport not supported in runtime< / code > < / td > < / tr >
< tr > < td > local< / td > < td > 只认 < code > echoLocalTool< / code > < / td > < td > 构造占位工具< / td > < td > 不可执行< / td > < / tr >
< / tbody >
< / table >
< / div >
< div class = "box note" >
< span class = "bt" > MCP 与「自己写个 HTTP 接口当工具」的本质区别< / span >
< p > 区别不在传输,而在< b > 谁拥有 schema< / b > 。自研接口里 schema 写在你自己的代码里,服务端改了你就得跟着改;
MCP 里 schema 由服务端在 < code > tools/list< / code > 时下发,客户端只需要一个泛化的「名字 + 参数」调用通道。
代价是客户端必须处理「发现失败」——本项目选择降级成占位工具继续启动(< code > mcp_sse_client.go:538-543< / code > ) ,
于是配置错了不会报错,只会在第一次调用时失败。< / p >
< / div >
2026-10-20 21:02:26 +08:00
< h3 id = "sec-4-4" > 4.4 MCP 的 SSE 传输与 JSON-RPC 2.0< / h3 >
2026-10-20 21:09:36 +08:00
< p > SSE 传输有个反直觉的设计:< b > 请求走 POST, 响应从 GET 的长连接回来< / b > 。两条通道靠 JSON-RPC 的 < code > id< / code > 关联,
客户端必须自己维护一张「id → 等待中的 channel」的表。完整时序是: < / p >
< pre data-lang = "text" data-name = "SSE 传输的握手与一次调用" > 客户端 服务端
│ ── GET /sse (Accept: text/event-stream) ──────→ │
│ ←── event: endpoint │
│ data: /messages?sessionId=abc │ ← 告诉客户端往哪 POST
│ │
│ ── POST /messages?sessionId=abc ─────────────→ │ {"jsonrpc":"2.0","id":1,"method":"initialize",...}
│ ←── event: message │
│ data: {"jsonrpc":"2.0","id":1,"result":{…}} │ ← 响应回到 SSE 长连接上
│ ── POST …/messages ──────────────────────────→ │ {"method":"notifications/initialized"}(无 id, 不等响应)
│ ── POST …/messages ──────────────────────────→ │ {"id":2,"method":"tools/list"}
│ ←── event: message {"id":2,"result":{"tools":[…]}}
│ ── POST …/messages ──────────────────────────→ │ {"id":3,"method":"tools/call","params":{…}}
│ ←── event: message {"id":3,"result":{"content":[{"type":"text","text":"…"}]}}< / pre >
< p > 客户端这边,最关键的是 < code > pending< / code > 这张表:发出请求前登记 channel, 收到同 id 的响应就把结果投进去并删除。
能不能正确清理,决定了长时间运行会不会内存泄漏:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/ai/mcp_sse_client.go:402-453( 有删节) " > id := c.nextID.Add(1)
ch := make(chan json.RawMessage, 1)
c.mu.Lock()
postURL := c.postURL
c.pending[id] = ch // 先登记
c.mu.Unlock()
if postURL == "" { return nil, fmt.Errorf("mcp post url is not set") } // ← 这里直接返回, pending 没删( P0-4)
// …POST 出去,丢弃响应体(真正的结果从 SSE 通道回来)…
select {
case msg, ok := < -ch: // readLoop 收到同 id 的结果后投递
if !ok { return nil, fmt.Errorf("mcp call %s closed unexpectedly", method) }
return msg, nil
case < -waitCtx.Done(): // ← 超时同样没删 pending( P0-4)
return nil, fmt.Errorf("mcp call %s timeout: %w", method, waitCtx.Err())
}< / pre >
< p > 握手里的两个常量固定为 < code > protocolVersion = "2024-11-05"< / code > 、客户端自报 < code > ai-agent-scaffold-go/0.1.0< / code >
( < code > mcp_sse_client.go:20-24< / code > )。超时分两层:发现用固定 10 秒(< code > listTimeout< / code > ) ,
单次调用用配置里的毫秒值,缺省下沉到 300000ms( 5 分钟)。< / p >
< div class = "box danger" >
< span class = "bt" > 重名工具:本项目最隐蔽的一个坑< / span >
< p > 两张示例表都配了 < code > name: baidu-search< / code > 。第二个 Agent 装配时,< code > RegisterAndExpand< / code > 发现
< code > r.clients["baidu-search"]< / code > 已存在,直接 < code > return nil< / code > ( < code > mcp_sse_client.go:530-532< / code > ) ,
上层拿到空列表就回退成占位 < code > MCPTool< / code > 。于是第二个 Agent 的工具列表里有个叫 < code > baidu-search< / code > 的东西,
点下去却被转发给第一张表创建的那个客户端,服务端回「工具不存在」。
< b > 现象是「一个 Agent 能用工具、另一个不能」,根因是「工具名当成了全局唯一键」< / b > 。< / p >
< / div >
2026-10-20 21:02:26 +08:00
< h3 id = "sec-4-5" > 4.5 Skill: 把长提示词拆成可复用目录< / h3 >
2026-10-20 21:09:36 +08:00
< p > Skill 是比 MCP 更轻的一层复用:它不执行代码,只提供< b > 一段写好的作业指导书< / b > 。一个技能就是一个目录,里面至少有一个
< code > SKILL.md< / code > ,头部用 YAML front matter 写元数据,正文写给模型看的步骤,旁边可以放脚本和参考资料:< / p >
< pre data-lang = "markdown" data-name = "configs/agent/skills/battle-plan/SKILL.md( 真实文件) " > ---
name: battle-plan
description: 电脑性能优化
license: MIT
---
2026-10-20 21:02:26 +08:00
2026-10-20 21:09:36 +08:00
# 电脑性能优化
2026-10-20 21:02:26 +08:00
2026-10-20 21:09:36 +08:00
1. 先执行 `./scripts/get_system_info.sh` 收集硬件与系统信息
2. 再执行 `./scripts/check_cleanable_files.sh` 找出可清理目录
3. 按 `reference.md` 里的话术给出优化建议,不要直接删用户文件
...< / pre >
< p > 本项目的加载逻辑是「扫描 → 解析 → 注册成工具」,工具名统一加 < code > skill_< / code > 前缀避免与 MCP 冲突,
非法字符会被替换成下划线:< code > battle-plan< / code > → < code > skill_battle-plan< / code > ( < code > tools.go:287-315< / code > )。
路径解析则从当前工作目录逐级向上试若干候选,所以它在「仓库根目录起服务」和「子目录起服务」两种情况下都能找到技能:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/ai/tools.go:117-156( 有删节) " > skillType := strings.TrimSpace(config.Type) // 空值默认 directory
root, err := resolveSkillRoot(skillType, config.Path) // 绝对路径或逐级向上找
manifests, err := findSkillManifests(root) // 递归找所有 SKILL.md, 排序保证稳定
tools := make([]ports.Tool, 0, len(manifests))
for _, manifest := range manifests {
tool, err := loadSkillTool(manifest) // front matter → name/description
tools = append(tools, tool) // ToolName = "skill_" + sanitize(name)
}< / pre >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 对比项< / th > < th > MCP 工具< / th > < th > Skill< / th > < / tr > < / thead >
< tbody >
< tr > < td > 谁提供< / td > < td > 独立服务端进程< / td > < td > 本地目录里的 Markdown + 脚本< / td > < / tr >
< tr > < td > 模型看到什么< / td > < td > 工具名 + 参数 schema< / td > < td > 工具名 + 一段描述,正文要模型自己读文件< / td > < / tr >
< tr > < td > 执行< / td > < td > 客户端转发 JSON-RPC< / td > < td > 模型需要文件/命令工具配合;< b > 本项目没接,所以调不动< / b > < / td > < / tr >
< tr > < td > 典型用途< / td > < td > 搜索、数据库、第三方 API< / td > < td > 固定流程的作业指导书(如 PDF 处理、性能优化)< / td > < / tr >
< / tbody >
< / table >
< / div >
< div class = "box tip" >
< span class = "bt" > 为什么 Skill 在本项目里「只能看不能用」< / span >
< p > < code > SkillFactory< / code > 构造工具时没有拿到 < code > MCPToolRouter< / code > ( < code > bootstrap.go:54-55< / code > 里两者是分开 new 的),
所以 < code > skill_*< / code > 只进了模型可见列表,< code > CallTool< / code > 走到 < code > MCPToolRouter< / code > 找不到对应客户端,
直接返回 < code > tool "skill_pdf" is not callable in current runtime< / code > ( < code > mcp_sse_client.go:568-577< / code > )。
要让它可用,得给 < code > SkillTool< / code > 配一个「读文件 / 执行脚本」的执行器并注册进 router——第 19 章会给出改造方向。< / p >
< / div >
2026-10-20 21:02:26 +08:00
2026-10-20 21:09:36 +08:00
< h3 id = "sec-4-6" > 4.6 流式输出与增量拼接的两个难点< / h3 >
< p > 流式看起来只是「把响应一块块发出去」,真写起来有两个必须处理的难点,也是面试常问的点。< / p >
< p > < b > 难点一: tool_calls 是分片到达的。< / b > 模型不会一次给完整的 < code > arguments< / code > ,而是按
< code > index< / code > 分多块吐,< code > arguments< / code > 还是 JSON 字符串的片段。所以客户端必须先用 map 按 index 暂存,
再把字符串< b > 累加< / b > ,最后一次性排好序发出去。漏掉任何一步,收到的 JSON 就是残的:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/ai/openai_client.go:154-193( 有删节) " > for _, tc := range delta.ToolCalls {
current, ok := toolCallBuf[tc.Index]
if !ok { current = & ports.ChatToolCall{}; toolCallBuf[tc.Index] = current }
if tc.ID != "" { current.ID = tc.ID }
if tc.Function.Name != "" { current.Name = tc.Function.Name }
if tc.Function.Arguments != "" {
current.Arguments += tc.Function.Arguments // 关键:拼接,不是覆盖
}
}
// 收尾时按 index 0..n-1 顺序取出,保证调用顺序稳定
for i := 0; i < len(buf); i++ { if call, ok := buf[i]; ok { calls = append(calls, *call) } }< / pre >
< p > < b > 难点二:怎么判断「这一轮结束了」。< / b > 纯文本流靠 < code > [DONE]< / code > 收尾就够了;但一旦有工具调用,
结束意味着「文本说完了、工具参数也拼完了、接下来该执行工具」。本项目用三种信号组合判断,
并且在「没有工具调用却没收到 Done」时判定流异常: < / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:252-258" > // 没有工具调用,本轮文本就是最终答案
if len(toolCalls) == 0 {
if !done { // 没见过 Done 事件
return fmt.Errorf("agent %q stream closed without completion", a.name)
}
return nil
}< / pre >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 现象< / th > < th > 根因< / th > < th > 正确做法< / th > < th > 本项目位置< / th > < / tr > < / thead >
< tbody >
< tr > < td > 工具参数 JSON 解析失败< / td > < td > 按 chunk 覆盖而非拼接< / td > < td > 按 index 累积字符串< / td > < td > < code > openai_client.go:160-170< / code > < / td > < / tr >
< tr > < td > 多个工具调用顺序错乱< / td > < td > map 遍历无序< / td > < td > 按 index 0..n-1 取出< / td > < td > < code > openai_client.go:180-193< / code > < / td > < / tr >
< tr > < td > SSE 帧被 TCP 拆开< / td > < td > 按「一次读」当成一帧< / td > < td > < code > bufio.Reader.ReadString('\n')< / code > 逐行读< / td > < td > < code > openai_client.go:115-131< / code > < / td > < / tr >
< tr > < td > 前端看到「说完又重复」< / td > < td > 工具轮的文本也被转发,下一轮重新生成< / td > < td > 要么缓冲工具轮文本,要么前端去重< / td > < td > < code > adapter.go:229-237< / code > (未处理)< / td > < / tr >
< / tbody >
< / table >
< / div >
< div class = "box ok" >
< span class = "bt" > 这一章的四句话< / span >
< p > ① 聊天的本质是< b > 每次重放整个 messages 数组< / b > ,四个角色靠 < code > tool_call_id< / code > 配对。< br >
② 模型只提出调用、不执行;执行器是应用,闭环 = 声明 → 请求 → 执行 → 回灌,本项目上限 4 轮。< br >
③ MCP 的价值是< b > 服务端自描述 schema< / b > , SSE 传输的关键是「POST 发请求、GET 收响应、id 配对」。< br >
④ 流式的两个难点是「增量拼接」与「结束判定」,前者错在覆盖,后者错在把 < code > Done< / code > 当可选。< / p >
< / div >
2026-10-20 21:02:26 +08:00
< nav class = "pager" >
< a class = "prev" href = "03-basics-go.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 3 章 · Go 与 Web 基础: Gin、YAML、SSE 与泛型< / span > < / a >
< a class = "next" href = "05-bootstrap.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 5 章 · 启动与装配: main → bootstrap → Gin< / span > < / a >
< / nav >
< p class = "foot" >
AI Agent 脚手架项目学习 · 第 4 章 AI Agent 前置:模型协议、工具调用与 MCP< br >
2026-10-22 21:59:12 +08:00
< a href = "index.html" > 学习地图< / a > · < a href = "part-1.html" > 篇 1 知识学习< / a > · < a href = "23-cheatsheet.html" > 速查与自测< / a >
2026-10-20 21:02:26 +08:00
< / p >
< / article >
< / main >
< / div >
< button id = "toTop" title = "回到顶部" > ↑< / button >
< script src = "assets/doc.js" > < / script >
< script src = "../../assets/back.js" data-portal-back = "project/ai-agent-scafford-go" data-portal-label = "工程项目 › AI Agent 脚手架项目学习( Go 智能体框架)" > < / script >
< / body >
< / html >