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 > 第 10 章 Agent 运行时:工具调用循环与流式 · AI Agent 脚手架项目学习< / title >
< meta name = "description" content = "拆 runLLM 的四步循环与 streamLLM 的 Done 语义,讲清 Runner 的会话、插件生命周期,以及会话 ID 生成方式的缺陷。" >
< meta name = "keywords" content = "Agent运行时,工具调用循环,流式,Runner,插件,会话" >
< 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" > 篇 1 知识学习< / a > < a href = "part-2.html" class = "on" > 篇 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" > 篇 2< / span > < span class = "ts-name" > 项目拆解< / span > < a class = "ts-all" href = "index.html" > 全部篇章 →< / a > < / div > < a class = "toc-a" href = "05-bootstrap.html" > < i class = "cn" > 5< / i > 启动与装配: main → bootstrap → Gin< / a > < a class = "toc-a" href = "06-config.html" > < i class = "cn" > 6< / i > 配置体系:三层配置怎么生效< / a > < a class = "toc-a" href = "07-domain-ports.html" > < i class = "cn" > 7< / i > 领域模型与端口:接口清单< / a > < a class = "toc-a" href = "08-armory.html" > < i class = "cn" > 8< / i > Armory 装配链:责任链把 YAML 变成 Agent< / a > < a class = "toc-a" href = "09-workflow.html" > < i class = "cn" > 9< / i > 工作流编排: sequential / parallel / loop< / a > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 10< / i > Agent 运行时:工具调用循环与流式< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-10-1" > 10.1 ADK 包在这里承担什么< / a > < a class = "toc-a lv3" href = "#sec-10-2" > 10.2 runLLM: 四步循环怎么收敛< / a > < a class = "toc-a lv3" href = "#sec-10-3" > 10.3 streamLLM 与 Done 语义< / a > < a class = "toc-a lv3" href = "#sec-10-4" > 10.4 Runner: 会话、插件与生命周期< / a > < a class = "toc-a lv3" href = "#sec-10-5" > 10.5 会话 ID 的生成方式与缺陷< / a > < / div > < a class = "toc-a" href = "11-model-client.html" > < i class = "cn" > 11< / i > 模型层: OpenAI 兼容客户端< / a > < a class = "toc-a" href = "12-mcp.html" > < i class = "cn" > 12< / i > MCP 工具: SSE 客户端与全局路由< / a > < a class = "toc-a" href = "13-skills.html" > < i class = "cn" > 13< / i > Skill 机制: SKILL.md 扫描与命名< / a > < a class = "toc-a" href = "14-http-api.html" > < i class = "cn" > 14< / i > HTTP 接口层:五个端点< / a > < a class = "toc-a" href = "15-frontend.html" > < i class = "cn" > 15< / i > 前端: Next.js + draw.io 交互绘图< / a > < a class = "toc-a" href = "16-infra-deploy.html" > < i class = "cn" > 16< / i > 基础设施与部署< / a > < / 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-2.html" > 篇 2 项目拆解< / a >
< span > ·< / span >
2026-10-22 21:59:12 +08:00
< span > 第 < b class = "pos" > 10< / b > / 23 章< / span >
2026-10-20 21:02:26 +08:00
< / p >
< h2 id = "ch10" > < span class = "n" > 10< / span > Agent 运行时:工具调用循环与流式< / h2 >
< div class = "lead" >
2026-10-20 21:44:55 +08:00
< b > 这一章解决什么:< / b > 前面几章把 YAML 变成了 < code > ports.Agent< / code > ,这一章看它< b > 跑起来< / b > 之后到底发生了什么。
< code > internal/infrastructure/adk/adapter.go< / code > 一共 572 行,却同时塞着五件事:类型定义、两套端口的实现、
工具调用循环(< code > runLLM< / code > / < code > streamLLM< / code > )、插件生命周期、会话 ID 生成。
读完你要能答三个问题——那个叫 adk 的包到底用了 Google ADK 的什么?模型连续要工具时循环靠什么终止?为什么客户端断开也停不下上游请求?
2026-10-20 21:02:26 +08:00
< / div >
< h3 id = "sec-10-1" > 10.1 ADK 包在这里承担什么< / h3 >
2026-10-20 21:44:55 +08:00
< p > 先破除一个误解。包名是 < code > adk< / code > ,目录是 < code > adk< / code > ,文件名也是 < code > adapter.go< / code > ,看起来像是对 Google ADK 的适配层。
但整份文件对 < code > google.golang.org/adk< / code > 的依赖只有两条 import: < code > plugin< / code > 与 < code > loggingplugin< / code > ( < code > adapter.go:11-12< / code > )。
下面这段就是全部:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:3-15" > package adk
2026-10-20 21:02:26 +08:00
2026-10-20 21:44:55 +08:00
import (
"context"
"fmt"
"strings"
"sync/atomic"
2026-10-20 21:02:26 +08:00
2026-10-20 21:44:55 +08:00
"ai-agent-scaffold-go/internal/domain/agent/model"
"ai-agent-scaffold-go/internal/domain/agent/ports"
"google.golang.org/adk/plugin"
"google.golang.org/adk/plugin/loggingplugin"
)
2026-10-20 21:02:26 +08:00
2026-10-20 21:44:55 +08:00
const maxToolCallIterations = 4< / pre >
< p > 其余全是自家定义:< code > Factory< / code > ( 17-21) 只有三个字段——会话计数器、插件工厂表、工具路由器;
< code > Agent< / code > ( 23-32) 是一个「字段袋」, 装着名字、kind、instruction、chatModel、router、subAgents;
< code > Runner< / code > ( 34-39) 更薄, 只有 appName、agent、plugins、counter。三者都不实现 ADK 的任何接口。< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 能力< / th > < th > ADK 提供< / th > < th > 项目自建< / th > < / tr > < / thead >
< tbody >
< tr > < td > Agent 抽象< / td > < td > —< / td > < td > < code > Agent< / code > ( 23-32) , 对外方法只有 < code > Name()< / code > / < code > Description()< / code > ( 110-117) < / td > < / tr >
< tr > < td > Runner< / td > < td > —< / td > < td > < code > Runner< / code > ( 34-39) , < code > Run< / code > / < code > Stream< / code > / < code > CreateSession< / code > < / td > < / tr >
< tr > < td > 插件接口< / td > < td > < code > plugin.Plugin< / code > < / td > < td > < code > ports.RunnerPlugin< / code > ( < code > ports.go:88-92< / code > ),两个回调< / td > < / tr >
< tr > < td > 日志插件< / td > < td > < code > loggingplugin.New< / code > < / td > < td > < code > adkRunnerPlugin< / code > 包装( 548-572) , 只做 printf< / td > < / tr >
< tr > < td > 工具调用循环< / td > < td > —< / td > < td > < code > runLLM< / code > ( 173-195) 、< code > streamLLM< / code > ( 202-268) < / td > < / tr >
< tr > < td > 工作流编排< / td > < td > —< / td > < td > < code > runSequential< / code > ( 301-324) 、< code > runFanOut< / code > ( 330-348) < / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 两套端口由同一个 < code > Factory< / code > 实现:< code > NewLLMAgent< / code > / < code > NewLoopAgent< / code > / < code > NewParallelAgent< / code > /
< code > NewSequentialAgent< / code > ( 52-80) 凑齐 < code > ports.AgentFactory< / code > ( < code > ports.go:77-82< / code > ) , < code > NewRunner< / code > ( 82-94)
凑齐 < code > ports.RunnerFactory< / code > ( < code > ports.go:94-96< / code > ) 。Go 的隐式接口让这件事不需要任何声明,而 Armory 装配链(第 8 章)只认端口,
所以更换实现不会波及上层。< / p >
< p > 那 < code > plugin.Plugin< / code > 被怎么用了?全项目只有一处:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:548-572" > type adkRunnerPlugin struct {
name string
plugin *plugin.Plugin
}
2026-10-20 21:02:26 +08:00
2026-10-20 21:48:52 +08:00
// Name 返回 ADK 插件包装器的名称.
func (p adkRunnerPlugin) Name() string {
return p.name
}
2026-10-20 21:02:26 +08:00
2026-10-20 21:44:55 +08:00
func (p adkRunnerPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ ports.Agent, content model.ChatContent) error {
if p.plugin.OnUserMessageCallback() != nil {
fmt.Printf("[%s] USER MESSAGE RECEIVED %s\n", p.name, firstText(content))
}
return nil
}
2026-10-20 21:02:26 +08:00
2026-10-20 21:44:55 +08:00
func (p adkRunnerPlugin) BeforeAgent(_ context.Context, _, _, _ string, agent ports.Agent) error {
if p.plugin.BeforeAgentCallback() != nil {
fmt.Printf("[%s] AGENT STARTING %s\n", p.name, agent.Name())
}
return nil
}< / pre >
< p > < code > OnUserMessageCallback()< / code > 只被用来判 nil, 判完就 < code > fmt.Printf< / code > 一行。< b > < code > p.plugin< / code > 上注册的回调从头到尾没有被调用< / b > ,
模型的请求、消息、工具调用都不经过它。也就是说 < code > myLogPlugin< / code > 的真实行为是「如果 ADK 插件注册过回调,就打印一句话」,与日志采集毫无关系——
这就是 P1-13 记的「ADK 插件是空壳」。另一个内置插件更直接:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:529-546" > type myTestPlugin struct{}
2026-10-20 21:48:52 +08:00
// Name 返回插件名, 用于错误信息和日志展示.
func (myTestPlugin) Name() string {
return "myTestPlugin"
}
2026-10-20 21:44:55 +08:00
// OnUserMessage 在用户消息到达时打印调试信息.
func (myTestPlugin) OnUserMessage(_ context.Context, _, _, _ string, _ ports.Agent, content model.ChatContent) error {
fmt.Printf("[myTestPlugin] 用户输入信息:%s\n", firstText(content))
return nil
}
2026-10-20 21:02:26 +08:00
2026-10-20 21:44:55 +08:00
// BeforeAgent 在 Agent 开始执行前打印 Agent 名称.
func (myTestPlugin) BeforeAgent(_ context.Context, _, _, _ string, agent ports.Agent) error {
fmt.Printf("[myTestPlugin] 智能体名称:%s\n", agent.Name())
return nil
}< / pre >
< p > 两处 < code > fmt.Printf< / code > 直接写 stdout, < b > 绕过了项目装配的 zap logger< / b > ( P2-15) : 日志级别、结构化字段、采样、落盘全部失效,
容器里只能靠 < code > docker logs< / code > 去捞这几行中文。同一份代码里,别的组件都规规矩矩走 logger, 只有插件例外。< / p >
< div class = "box note" >
< span class = "bt" > 结论:把 ADK 拿掉,执行逻辑一字不改< / span >
< p > 删掉 11-12 两条 import、< code > defaultPlugins< / code > 里的 < code > myLogPlugin< / code > 分支( 488-494) 、以及 548-572 整个类型,文件依旧编译,
< code > runLLM< / code > / < code > streamLLM< / code > / < code > Runner< / code > 一个字符都不用动。所以「基于 Google ADK」这句话只在依赖清单上成立,
在运行时是站不住的。< br >
2026-10-20 21:48:52 +08:00
顺带一个可维护性风险:< code > go.mod< / code > 里那个依赖一旦改 API, < code > p.plugin< / code > 的两个 nil 判断就可能编译不过,而它对功能没有任何贡献。
2026-10-20 21:44:55 +08:00
这种「只被当作类型标签的依赖」,升也不是、删也不是,属于典型的过早引入。< / p >
< / div >
< h3 id = "sec-10-2" > 10.2 runLLM: 四步循环怎么收敛< / h3 >
< p > 非流式路径的全部逻辑就是下面 23 行,没有别的隐藏分支:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:173-195" > func (a *Agent) runLLM(ctx context.Context, content model.ChatContent, vars map[string]string) (string, error) {
messages := initialMessages(applyVars(a.instruction, vars), firstText(content))
// 最多执行 maxToolCallIterations 轮 模型调用 -> 工具执行 -> 结果回灌
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
}
// 追加 assistant 消息, 保留模型请求的 tool_calls
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 > 拆成四步看,每一步都能对上代码:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 步< / th > < th > 代码< / th > < th > 关键点< / th > < / tr > < / thead >
< tbody >
< tr > < td > ① 构造消息< / td > < td > 174, 实现见 379-386< / td > < td > 只有 system + user 两条; instruction 为空时连 system 都没有< / td > < / tr >
< tr > < td > ② 进入循环< / td > < td > 176, 上限见 15< / td > < td > < code > maxToolCallIterations = 4< / code > ,硬编码常量,不可配置< / td > < / tr >
< tr > < td > ③ 收敛< / td > < td > 182-184< / td > < td > < code > len(reply.ToolCalls) == 0< / code > 即最终答案,直接返回文本< / td > < / tr >
< tr > < td > ④ 工具往返< / td > < td > 186-192< / td > < td > assistant( 带 ToolCalls) → 执行 → tool 消息,成对追加< / td > < / tr >
< tr > < td > ⑤ 超限< / td > < td > 194< / td > < td > 报错,不返回已经拿到的任何部分结果< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 「4 轮」的算术值得单独说:循环体每转一次调一次模型,所以< b > 4 轮 = 最多 4 次模型调用 = 最多 3 次完整的工具往返< / b > 。
更别扭的是第 4 轮:如果模型还在要工具,代码会先 append assistant、真把工具执行一遍( 187-192) , 然后才掉出循环报错——
< b > 副作用已经发生,结果却被丢弃< / b > 。一个会写库或发消息的工具,在这里可能已经改完数据,用户看到的却是一个 500。< / p >
< p > < code > initialMessages< / code > ( 379-386) 只放 system + user 两条,注释也写明「当前实现不保存跨轮对话历史,每次执行都从 system + user 重新开始」。
这意味着多轮对话在模型侧< b > 完全无状态< / b > :上一句用户说了什么、模型答了什么,下一次 < code > Run< / code > 一概不知道。
sessionID 只用于在 < code > SessionStore< / code > 里查,从不进消息列表。< b > 所谓「会话」在这个项目里只有一个 ID, 没有上下文< / b > ——
这比 10.5 要讲的 ID 格式问题严重得多,因为它直接决定了「多轮对话」这个功能在语义上是不存在的。< / p >
< p > 工具执行这一段是整轮失败的:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:274-294" > func (a *Agent) executeToolCalls(ctx context.Context, calls []ports.ChatToolCall) ([]ports.ChatMessage, error) {
// 模型请求了工具但未注入路由器, 属于非法状态
if a.router == nil {
return nil, fmt.Errorf("agent %q has no tool router but model requested tool calls", a.name)
}
out := make([]ports.ChatMessage, 0, len(calls))
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)
}
// 包装为 role=tool 的消息, 通过 ToolCallID 与 assistant 消息对应
out = append(out, ports.ChatMessage{
Role: ports.ChatRoleTool,
Content: result,
ToolCallID: call.ID,
Name: call.Name,
})
}
return out, nil
}< / pre >
< p > 两处硬失败: router 为 nil 直接报错( 276-278) , 因为「模型要工具但没有路由器」属于装配错误; 任一工具返回 err 就 < code > return nil, err< / code > ( 282-284) ,
< b > 不把错误包成 role=tool 的消息< / b > 。另外它是串行 < code > for< / code > ( 280-292) : 模型一次要 3 个工具就按顺序跑三次,总耗时是三者之和,
没有并发、也没有独立超时,超时只能靠 < code > router.CallTool< / code > 内部自己管。< / p >
< div class = "box warn" >
< span class = "bt" > 工具失败的代价:模型永远学不到「这个工具坏了」< / span >
< p > 因为错误被直接抛出而不是回灌,模型没有机会换参数重试、也没有机会改口告诉用户「查询失败了」。一次 MCP 超时、一次参数 JSON 不合法,
整个 < code > /chat< / code > 请求就 500, 前面已经花掉的 token 全部作废。< br >
业界通行做法是把 < code > {"error": "..."}< / code > 作为 tool 消息发回去, 让模型自己决定重试还是解释; 只在「router 不存在」这类装配错误上才硬失败。
改法很小——把 282-284 换成 append 一条 < code > Role: ChatRoleTool, Content: "error: " + err.Error()< / code > ,然后 < code > continue< / code > 。< / p >
< / div >
< h3 id = "sec-10-3" > 10.3 streamLLM 与 Done 语义< / h3 >
< p > 流式版本共用同一副骨架:同样的 < code > initialMessages< / code > 、同样的 4 轮上限、同样的工具往返。差别集中在两个问题上——文本什么时候出去,
以及「这一轮到底结束了没有」怎么判定。< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:205-268" > for iter := 0; iter < maxToolCallIterations; iter++ {
events, errs := a.chatModel.Stream(ctx, messages)
var (
finalText strings.Builder
toolCalls []ports.ChatToolCall
done bool
)
streamErr := error(nil)
streamLoop:
for {
select {
case < -ctx.Done():
streamErr = ctx.Err()
break streamLoop
case ev, ok := < -events:
if !ok {
break streamLoop
}
if ev.Done {
done = true
}
if ev.Delta != "" {
finalText.WriteString(ev.Delta)
select {
case out < - ev.Delta:
case < -ctx.Done():
streamErr = ctx.Err()
break streamLoop
}
}
if len(ev.ToolCalls) > 0 {
toolCalls = append(toolCalls, ev.ToolCalls...)
}
case err, ok := < -errs:
if ok & & err != nil {
streamErr = err
}
break streamLoop
}
}
if streamErr != nil {
return streamErr
}
// 没有工具调用, 本轮文本就是最终答案
if len(toolCalls) == 0 {
// 缺少 Done 标记, 视为流异常关闭
if !done {
return fmt.Errorf("agent %q stream closed without completion", a.name)
}
return nil
}
messages = append(messages, ports.ChatMessage{Role: ports.ChatRoleAssistant, Content: finalText.String(), ToolCalls: toolCalls})
toolMessages, err := a.executeToolCalls(ctx, 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 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 维度< / th > < th > runLLM< / th > < th > streamLLM< / th > < / tr > < / thead >
< tbody >
< tr > < td > 模型入口< / td > < td > < code > Generate< / code > ( 177) < / td > < td > < code > Stream< / code > ,拿回两个 channel( 206) < / td > < / tr >
< tr > < td > 文本可见时机< / td > < td > 全部结束后一次性返回< / td > < td > 每个 < code > Delta< / code > 立刻写 < code > out< / code > ( 229-237) < / td > < / tr >
< tr > < td > 本轮完整文本< / td > < td > < code > reply.Content< / code > < / td > < td > < code > strings.Builder finalText< / code > ( 209、230) , 用于回填 assistant 消息< / td > < / tr >
< tr > < td > 结束判定< / td > < td > 没有 tool_calls 就结束< / td > < td > 还要求 < code > ev.Done< / code > , 但只在收尾轮强校验( 252-258) < / td > < / tr >
< tr > < td > 错误来源< / td > < td > < code > Generate< / code > 的返回值< / td > < td > < code > streamErr< / code > , 三处赋值( 219、234、243) < / td > < / tr >
< / tbody >
< / table >
< / div >
< p > < code > streamLoop< / code > 标签 + 三重 < code > select< / code > ( 215-247) 是为了从嵌套结构里一次跳出去: < code > ctx.Done()< / code > 取消、< code > events< / code > 关闭、
< code > errs< / code > 有值,三条路都 < code > break streamLoop< / code > ,然后在 248 统一判 < code > streamErr< / code > 。内层那个 < code > select< / code > ( 231-236) 在往 < code > out< / code >
写增量时也要监听取消,否则下游不读 channel 时生产者会永久阻塞——这是 Go channel 背压的经典写法,本项目在这里做对了。< / p >
< p > < code > Done< / code > 的语义比看上去微妙,得先看上游怎么发:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/ai/openai_client.go:116-135" > for {
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
emitToolCalls(events, toolCallBuf)
events < - ports.ChatStreamEvent{Done: true}
return
}
errs < - fmt.Errorf("openai stream read: %w", err)
return
}
line = strings.TrimRight(line, "\r\n")
if line == "" || !strings.HasPrefix(line, "data:") {
continue
}
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
if payload == "[DONE]" {
emitToolCalls(events, toolCallBuf)
events < - ports.ChatStreamEvent{Done: true}
return
}< / pre >
< p > < code > io.EOF< / code > 与 < code > data: [DONE]< / code > 两条正常出口都是「先 < code > emitToolCalls< / code > ,再发一条 < code > Done: true< / code > ,然后 return」( 120-121、133-134) 。
所以正常路径下 < code > done< / code > 恒真,而且工具调用一定在 < code > Done< / code > 之前到达——这正是 adapter 里敢于「读完整个流再判 < code > len(toolCalls)< / code > 」的前提。
注意 225-227 行:收到 < code > Done< / code > 只置标记、不 break, 循环继续等 channel 关闭;因为上游发完就 return, 这个差别目前观察不到, 但它说明 < code > done< / code > 只是「见过收尾信号」,不是「流已结束」。< / p >
< p > 真正的隐患在异常路径。< code > Stream< / code > 的 goroutine 有六处 < code > errs < - err< / code > 之后直接 return( 98、103、109、124、139、150) ,
这些分支< b > 都不发 Done< / b > 。< / p >
< div class = "box danger" >
< span class = "bt" > 关闭顺序 + select 随机 = 真实错误有概率被吞掉< / span >
< p > 两个 channel 都用 < code > defer close< / code > ( 93-94) , defer 后进先出,所以实际是 < code > errs< / code > 先关、< code > events< / code > 后关;
而在关闭之前, goroutine 已经把错误塞进了 < code > errs< / code > 的一格缓冲( 431) 。于是 adapter 的 < code > select< / code > 在「两个 channel 都已关闭」时是随机挑分支的:
挑到 < code > errs< / code > 就拿到真实错误;挑到 < code > events< / code > 的 < code > !ok< / code > 分支就 < code > break< / code > ,此时 < code > streamErr< / code > 仍是 nil,
接着因为 < code > len(toolCalls) == 0< / code > 且 < code > !done< / code > ,返回 < code > agent %q stream closed without completion< / code > ( 255) 。
< b > 同一个上游 500, 有一半概率被报成「流异常关闭」< / b > ,排查时会误以为是对端提前断开,而不是 4xx/5xx。< br >
改法:< code > !ok< / code > 之后先非阻塞补读一次 < code > errs< / code > ( < code > select { case e := < -errs: ... default: }< / code > ) ,
或者更彻底——把两个 channel 合成一个带 < code > Err< / code > 字段的事件,从协议上消灭这个竞态。< / p >
< / div >
< p > 还有一处语义漏洞:< code > if !done< / code > 的强校验只在 < code > len(toolCalls) == 0< / code > 的分支里做( 252-258) 。
如果本轮收到了工具调用但流没正常结束,代码会跳过校验、直接进入下一轮。当前这不算 bug, 因为 < code > emitToolCalls< / code > 只在 EOF/< code > [DONE]< / code > 时调用,
拿到的工具调用必然完整; 但这个保证来自上游实现, adapter 自己并不校验。第 11 章如果换一个流式实现,这条隐含契约就没人守了。< / p >
< p > 最后一个事实:只有 < code > kind == "llm"< / code > 走真正的流式。工作流类型( sequential / loop / parallel) 的 < code > stream< / code > 是「先 < code > run< / code > 完整跑完,
再把结果一次性写进 < code > out< / code > 」( 147-165) , 前端在这类 Agent 上看到的是「长时间空白 + 整段出现」。要改就得让 < code > runSequential< / code > /
< code > runFanOut< / code > 支持向下游转发子 Agent 的增量,改动量不小——这也是为什么第 9 章说工作流层「编排对了、执行没对」。< / p >
< h3 id = "sec-10-4" > 10.4 Runner: 会话、插件与生命周期< / h3 >
< p > < code > Runner< / code > 本身不含任何模型逻辑,它是一层很薄的粘合:校参数、通知插件、类型断言、把活交给 Agent。< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:403-423" > func (r *Runner) Run(userID, sessionID string, content model.ChatContent) ([]string, error) {
if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" {
return nil, fmt.Errorf("user id and session id are required")
}
if err := r.notifyPlugins(userID, sessionID, content); err != nil {
return nil, err
}
// Runner 只能运行 adk.Agent, 这里做类型断言
impl, ok := r.agent.(*Agent)
if !ok {
return nil, fmt.Errorf("runner agent %q is not runnable", r.agent.Name())
}
output, err := impl.run(context.Background(), content)
if err != nil {
return nil, err
}
if output == "" {
return []string{}, nil
}
return []string{output}, nil
}< / pre >
< p > 顺序是固定的: 参数校验( 404-406) → < code > notifyPlugins< / code > ( 407-409) → 断言 < code > r.agent.(*Agent)< / code > ( 411-414) →
< code > impl.run(context.Background(), content)< / code > ( 415) → 空串归一成 < code > []string{}< / code > ( 419-421) 。最后这一步是为了让 HTTP 层永远拿到数组,
而不是 < code > nil< / code > ——序列化成 JSON 时一个是 < code > []< / code > 、一个是 < code > null< / code > ,前端会炸。< / p >
< p > < code > notifyPlugins< / code > ( 460-470) 对每个插件依次触发 < code > OnUserMessage< / code > → < code > BeforeAgent< / code > ,任一返回 error 就中止,
错误被包上插件名(< code > plugin %q on user message: %w< / code > )。注意它是< b > 按插件循环而不是按阶段循环< / b > :插件 A 的两个回调都跑完,才轮到插件 B。
所以「所有插件的 OnUserMessage 都先于所有 BeforeAgent」并不成立, 写有状态的插件时这个顺序会造成很隐蔽的 bug。< / p >
< div class = "box danger" >
< span class = "bt" > P1-4: ctx 在 Service 层就丢了,客户端断开也停不下上游< / span >
< p > < code > Runner.Run< / code > 的签名里没有 < code > ctx< / code > ( < code > model/command.go< / code > 的 < code > Runner< / code > 接口只有 userID / sessionID / content) ,
< code > chat.Service.HandleCommand< / code > 直接 < code > registered.Runner.Run(...)< / code > ( < code > service.go:71< / code > )。所以 HTTP 层无论怎样把
< code > c.Request.Context()< / code > 往下传,到 adapter 只剩 < code > context.Background()< / code > ( 415、449) , 连插件回调也是自己新建的( 462、465) 。< br >
后果很直接: 浏览器一断开, Gin 的 ctx 立即取消,但没有任何人监听,上游 LLM 请求继续跑到吐完, token 照扣、工具照执行。
< b > 这是整个运行时最贵的一个 bug< / b > ,而且它在压测时表现为「上游 QPS 降不下来」而不是报错,很难归因。
改法只有一条:把 < code > ctx< / code > 加进 < code > Runner.Run< / code > / < code > Stream< / code > 的签名,一路透传到 < code > Generate< / code > / < code > Stream< / code > 。< / p >
< / div >
< p > < code > Stream< / code > ( 429-454) 把执行体扔进 goroutine, 返回两个 channel: < / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > channel< / th > < th > 缓冲< / th > < th > 谁关< / th > < th > 语义< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > outputs< / code > < / td > < td > 8( 430) < / td > < td > goroutine 的 < code > defer close< / code > ( 433) < / td > < td > 文本增量;关闭表示不会再有文本< / td > < / tr >
< tr > < td > < code > errs< / code > < / td > < td > 1( 431) < / td > < td > goroutine 的 < code > defer close< / code > ( 434) < / td > < td > 至多一条错误;关闭表示执行体已退出< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 缓冲 8 是有意义的:消费者慢的时候最多积压 8 个增量,第 9 个开始写阻塞,进而阻塞上游 SSE 读取 goroutine, 形成背压而不是无限吃内存。
< code > errs< / code > 缓冲 1 则保证「只发一次错误」不会卡住发送方——三个前置失败分支( 436、440、446) 都只发一条就 return。< / p >
< p > 但 goroutine 里没有 < code > recover< / code > : < code > notifyPlugins< / code > 或 < code > impl.stream< / code > 一旦 panic, Gin 的 recovery 中间件不在这个栈上,
整个进程直接挂掉。对一个靠 HTTP 活着的容器服务,这是把「一次请求出错」升级成「服务不可用」。三行 < code > defer func(){ if p := recover(); p != nil {
errs < - fmt.Errorf("panic: %v", p) } }()< / code > 就能挡住。< / p >
< p > 插件在装配期就定型:< code > NewRunner< / code > 调 < code > resolvePlugins< / code > ( 89) , 未注册的名字直接报错( 511-515) , < code > defaultPlugins< / code > ( 485-496)
里只有 < code > myTestPlugin< / code > 与 < code > myLogPlugin< / code > 两个。所以 YAML 里 < code > plugin-name-list< / code > 写错一个字母,启动就失败——
这是配置层少见的「早失败」,比运行期才发现要好得多,值得保留。< / p >
2026-10-20 21:02:26 +08:00
< h3 id = "sec-10-5" > 10.5 会话 ID 的生成方式与缺陷< / h3 >
2026-10-20 21:44:55 +08:00
< p > 会话 ID 的生成只有六行,但每一行都能引出问题:< / p >
< pre data-lang = "go" data-name = "internal/infrastructure/adk/adapter.go:391-398" > func (r *Runner) CreateSession(userID string) (string, error) {
if strings.TrimSpace(userID) == "" {
return "", fmt.Errorf("user id is required")
}
// 全局原子自增, 保证所有 Runner 的会话序号不冲突
next := r.counter.Add(1)
return fmt.Sprintf("%s:%s:%d", r.appName, userID, next), nil
}< / pre >
< p > 结构是 < code > appName:userID:序号< / code > ,序号来自 < code > Factory< / code > 的 < code > atomic.Uint64< / code > ( 18) ; < code > NewRunner< / code > 把 < code > & f.sessionCounter< / code >
塞进 Runner( 93) , 所以< b > 同一个 Factory 造出来的所有 Runner 共用一个计数器< / b > ——注释说的「保证所有 Runner 的会话序号不冲突」( 395) 就是指这个。
四个缺陷逐条拆:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > #< / th > < th > 现象< / th > < th > 后果< / th > < th > 改法< / th > < / tr > < / thead >
< tbody >
< tr > < td > ①< / td > < td > 序号全进程递增,不按用户或 Agent 分组( 18、396) < / td > < td > 同一用户跟同一个 Agent 说话拿到 < code > :2< / code > ,换个 Agent 就跳到 < code > :17< / code > ;从 ID 反推不出「这是第几次会话」,日志对齐很痛苦< / td > < td > 计数键改成 < code > appName:userID:agentID< / code > ,或者干脆放弃序号< / td > < / tr >
< tr > < td > ②< / td > < td > 没有任何唯一性或冲突校验( 391-398) < / td > < td > 进程重启计数器归零,可能与历史 ID 重复。当前 < code > InMemorySessionStore< / code > 也在内存里(< code > ports.go:142-149< / code > ),重启即清空所以无害;一旦换 Redis, 重复 ID 就是< b > 覆盖别人的会话< / b > < / td > < td > UUIDv7 / 雪花 ID; 写入 Store 时用 < code > SETNX< / code > 兜底< / td > < / tr >
< tr > < td > ③< / td > < td > < code > userID< / code > 明文拼进 ID( 397) < / td > < td > ID 会进 zap 日志、前端 localStorage, 甚至 URL 与分享链接;用户标识直接外泄,还能被用来枚举他人会话< / td > < td > ID 用不可逆随机串,归属信息只存服务端< / td > < / tr >
< tr > < td > ④< / td > < td > 只校验 userID 非空,不查 Agent 是否存在( 392-394) < / td > < td > Agent 存在性校验在 < code > chat.Service.CreateSession< / code > ( < code > service.go:41-44< / code > );绕过 Service 直接调 Runner 就能建出「不存在的 Agent」的会话< / td > < td > 把 < code > {userID, agentID, createdAt}< / code > 写进 Store, 运行期比对< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 第 ④ 条要看清「设计」与「缺陷」的边界。< code > InMemorySessionStore< / code > 按 < code > userID:agentID< / code > 做 key( < code > ports.go:165-167< / code > ) ,
所以同一个人在不同 Agent 下天然是多个独立会话——< b > 这是设计,不是 bug< / b > 。真正的缺陷在下游:< code > resolveRunnerSession< / code > ( < code > service.go:97-117< / code > )
拿到请求里的 sessionID 后只判空( 102-109) , 从不校验「这个 ID 属于这个 userID + agentID」。也就是说, 调用方在请求体里手填一个别人的 sessionID,
只要格式对(< code > app:user:1< / code > 这种随手就能编),就能接着别人的上下文说话——这就是 P1-7「sessionId 不校验归属」。配合第 ③ 条( ID 可猜),
从「可能被利用」变成「很容易被利用」。< / p >
< p > 改造建议分三步,从「难猜」到「不可能越权」:< / p >
< pre data-lang = "go" data-name = "改造示意(非现有代码)" > type sessionMeta struct {
UserID string
AgentID string
CreatedAt time.Time
}
2026-10-20 21:02:26 +08:00
2026-10-20 21:44:55 +08:00
func (s *Service) resolveRunnerSession(cmd model.ChatCommand) (model.RegisteredAgent, string, error) {
id := cmd.SessionID
if id == "" {
id = newSessionID() // ① UUIDv7 / 雪花
s.sessions.SetMeta(id, sessionMeta{UserID: cmd.UserID, AgentID: cmd.AgentID, CreatedAt: time.Now()})
return resolve(cmd, id)
}
meta, ok := s.sessions.GetMeta(id) // ② Store 存元信息而不是裸字符串
if !ok {
return model.RegisteredAgent{}, "", types.NewAppError(types.CodeSessionNotFound, types.InfoSessionNotFound)
}
if meta.UserID != cmd.UserID || meta.AgentID != cmd.AgentID {
return model.RegisteredAgent{}, "", types.NewAppError(types.CodeForbidden, types.InfoForbidden) // ③ 比对归属
}
return resolve(cmd, id)
}< / pre >
< p > 三步的分工:① 换成 UUIDv7 或雪花,去掉可猜性,同时消灭重启重复;② < code > SessionStore< / code > 从 < code > map[string]string< / code > 换成带元信息的结构,
顺带能为「最近会话列表」「会话过期」留出扩展点;③ 在 < code > resolveRunnerSession< / code > 里比对三元组,不匹配返回 403 而不是继续执行。
< b > 只有第 ③ 步能真正堵住越权< / b > ,前两步只是让攻击成本变高——这也是安全改造里常见的顺序错误:先换 ID 格式、却忘了校验归属。< / p >
< div class = "box ok" >
< span class = "bt" > 这一章要能脱口而出的四句话< / span >
< p > ① 名字里的「ADK」只是两条用不上的 import, 它在运行时不承担任何职责; < br >
② 工具循环上限是 4 次模型调用(最多 3 次往返),任一工具失败整轮就废,错误不给模型看;< br >
③ 流式的 < code > Done< / code > 只在收尾轮强校验,异常路径下真实错误有概率被 < code > stream closed without completion< / code > 掩盖;< br >
④ 会话 ID 是「app:user:序号」的人造字符串——可猜、重启会重复、且从不校验归属。< / p >
< / div >
2026-10-20 21:02:26 +08:00
< nav class = "pager" >
< a class = "prev" href = "09-workflow.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 9 章 · 工作流编排: sequential / parallel / loop< / span > < / a >
< a class = "next" href = "11-model-client.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 11 章 · 模型层: OpenAI 兼容客户端< / span > < / a >
< / nav >
< p class = "foot" >
AI Agent 脚手架项目学习 · 第 10 章 Agent 运行时:工具调用循环与流式< br >
2026-10-22 21:59:12 +08:00
< a href = "index.html" > 学习地图< / a > · < a href = "part-2.html" > 篇 2 项目拆解< / 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 >