Skip to content

feat(ai): make the agent observable through OTel GenAI conventions - #1616

Open
ambiguous-pointer wants to merge 7 commits into
apache:aifrom
ambiguous-pointer:feat/ai_otel_genai
Open

ambiguous-pointer wants to merge 7 commits into
apache:aifrom
ambiguous-pointer:feat/ai_otel_genai

Conversation

@ambiguous-pointer

@ambiguous-pointer ambiguous-pointer commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

概要

把 Dubbo Admin 的 AI 助手变成可观测、可调试的对象——不翻 console 日志,就能看清它是怎么跑的:怎么发起调用、调了哪些 tools、思考过程是什么、输入输出长什么样。

做法是让 Agent 的执行过程符合 OpenTelemetry generative AI 语义约定,导出标准 OTLP。结果是采集端的可视化直接可用,Langfuse / OpenLIT / 任何 OTel 后端都能认出来,不需要写任何一行适配代码。

这是周会条目「trace 的观测加强」中 AI 助手自身 的那一半。Agent 去诊断 Dubbo 业务链路的检索与诊断能力是另一件事,见 #1618。

采集端能看到什么

OpenLIT —— 链路树被原生重建,Agent 被识别为 Coding Agent:

OpenLIT 中的 Agent 链路

Langfuse —— 会话、模型用量、token 全部对上,sessionId 直接来自 gen_ai.conversation.id:

Langfuse 中的 Agent 链路

上面两张图不是设计稿,是实测——在本地统一收集点(OTel Collector → Langfuse / OpenLIT / Greptime)上跑真实的 Agent 交互导出来的。


为什么是「可观测性 + 采集端配合」,而不是别的

Agent 此前是个黑盒。它跑完一次会话,中间调了哪些工具、模型返回了什么、有没有走降级、思考过程是什么,只能翻 Admin 的 console 日志。而 console 日志有两个根本缺陷:

  • 没有会话维度:一次会话的第 3 轮和第 40 轮混在同一条时间线里,无法还原「这一轮 Agent 到底拿到了什么上下文」;
  • 不记录工具调用的返回值:Agent 拿到一段格式错误的 JSON 却继续往下走,日志里看不出任何异常;
  • 不是因果结构:日志是时间序的文本流,看不出「哪个工具调用是哪个模型调用发起的」。

这三件事不是「补几个日志字段」能解决的——它们需要一个带会话维度、带因果结构、能被通用工具消费的数据模型。OTel 的 GenAI 语义约定正好给了这个模型:把 Agent 的执行过程表达成规范的 trace,导出 OTLP,后端按规范自己认。

为什么不用私有的 ai.model.* 命名空间:短期省事,但代价是后端认不出来——每个平台都要写一层适配,而适配层永远追不上规范演进。(规范没有定义的内部信息——交互 id、迭代序号、阶段、降级与兜底——仍然用 agent.* 前缀,它们不参与后端对 Agent 的识别。)上面两张截图里 OpenLIT 把它显示成 Coding Agent、Langfuse 把它映射成 Session,全是因为我们发的是规范属性。


改了什么

1. 对齐语义约定(ai/component/hooks/tracing.go)

改动 规范依据 为什么
Agent 相关 span 带 gen_ai.agent.name gen_ai.invoke_agent.internal 上是 Conditionally Required 缺了它,span 在链路里就是匿名的——分析器能识别出「有个 Agent span」,但叫不出它是谁
invoke_agent span 名为 invoke_agent {gen_ai.agent.name} 规范:agent name 可得时用 invoke_agent {name} 后端据此把它识别成一条 Agent 链路(见 OpenLIT 截图的 CODING AGENT)
失败 span 必有非空低基数 error.type,兜底 _OTHER 规范:失败时 Conditionally Required 把错误原文塞进 error.type 会直接毁掉它的基数
失败时记 gen_ai.client.operation.exception 事件,带 exception.type / exception.message / exception.stacktrace gen-ai-exceptions.md:事件名 MUST 为此 这才是 GenAI 侧的异常面。标准 exception 事件保留——Dubbo RPC 链路里全是传统异常,读它们是分析器的基本盘
gen_ai.provider.name 映射到规范的 well-known 值 规范给了 16 个值 gemini → gcp.gemini(依据是 base_url 为 generativelanguage.googleapis.com,而规范对 gcp.gemini 的描述正是 "Also known as the AI Studio API")
移除私有 agent.usage.total_tokens 规范只定义 input / output 两个 token 属性 同一个数字给两套可能不一致的定义没有意义;成本由企业 API 网关核算,Admin 只需给出「模型名 + token 数」

provider 映射不做过滤:规范原文允许自定义值("otherwise, a custom value MAY be used"),所以 dashscope、siliconflow 这类值原样保留,不会凭空消失。

2. 思考过程(ai/component/hooks/reasoning.go、ai/component/agent/react/hook_content.go)

思考过程此前是被直接丢弃的:模型响应转消息时只处理 text / tool_call / tool_call_response 三种 part,thinking 内容没有对应分支。

规范里思考过程就装在消息的 part 里(ReasoningPart,type: "reasoning"),不需要新造属性,只差转换和一个策略。

新增 capture_reasoning,与既有的 capture_content 正交:

capture_content capture_reasoning 效果
none 任意 完全不发任何内容属性
truncated / full none 发消息内容,不含思考过程
truncated / full truncated 发消息内容,思考过程截断保留
truncated / full full 发消息内容,思考过程原样保留

为什么拆成两个开关:它们是两类不同的风险。提示词与工具入参/返回值是业务数据(可能含用户标识、订单信息);思考过程是另一类内容,敏感度与用途都不同。合成一个开关,就没法做到「开发期要盯思考过程、生产期要把它藏起来」的同时不误开业务数据。

两个开关默认都是 none —— 默认情况下链路里不存在任何明文提示词,这是刻意的隐私保护,也让「在共享环境里打开采集」是安全的。

3. 文档

  • docs/ai-agent-observability.md —— 属性与后端字段的映射表、怎么开采集、调试速查表(我想知道 X → 去哪看)、已验证结果、已知限制。
  • ai/component/hooks/README.md —— 配置项说明。

调试速查(节选)

我想知道… 去哪看
某次会话的全过程 gen_ai.conversation.id(Langfuse 里就是 Session ID)
Agent 怎么发起调用 span 层级:interaction → iteration → stage → model_call / tool_call
用了哪些 tools gen_ai.tool.name + span 名 execute_tool <tool>
工具的入参与返回值 gen_ai.tool.call.arguments / .result(需开 capture_content)
思考过程 output messages 里的 type: "reasoning" part(需开 capture_reasoning)
哪里失败了、为什么 span 状态 + error.type + gen_ai.client.operation.exception 事件
模型与 token / 成本 gen_ai.request.model + gen_ai.usage.*

验证

单测:ai 模块 go build ./... && go vet ./... && go test ./... 全绿(18 个包),其中 hooks 包 38 个用例。

真实采集平台:在本地统一收集点(OTel Collector → Langfuse / OpenLIT / Greptime)上连跑 3 次完整 Agent 交互(invoke_agent → iteration → stage → 一次模型调用 + 两次工具调用,其中一次失败),3/3 全部入库,18/18 span 无缺失:

  • span 层级与父子关系完整;模型 span 的 SpanKind 为 Client(规范要求),失败的工具 span 状态为 Error;
  • gen_ai.provider.name = gcp.gemini(映射生效)、gen_ai.agent.name = dubbo-admin-sre-agent;
  • 每次运行恰好一条 gen_ai.client.operation.exception 事件(异常事件按 span 去重);
  • output messages 中思考过程的形状为 {"type":"reasoning"},符合规范;
  • OpenLIT 识别为 Coding Agent 并重建 span 树,Chat 视图还原出「用户提问 → 两次工具调用(含错误)→ 助手回答」;
  • Langfuse 把它识别为一条 trace,sessionId 来自 gen_ai.conversation.id,模型用量面板显示 gemini-pro / 192 tokens。

两个与本改动无关、但排查时值得知道的事实:

  1. 采集端的 tail sampling 会丢链路。若收集平台配置了 tail_sampling(常见策略:错误必留、慢链路必留、其余按百分比),没有错误且不够慢的链路会被按概率丢弃。此时「某段时间没有失败链路」这个结论并不可靠。
  2. span 必须有配对的结束事件才会被导出。未闭合的 span 不会出现在链路里。

已知限制

限制 说明
工具内部的下游调用不在链路里 Agent 侧 MCP client 会注入 trace context,但 Admin 的 MCP Server 没有接收它、也没建 server 端 span,所以工具耗时能看到、但「工具内部又调了谁」看不到。这是下一步要补的,建议单独 PR
span 事件无法表达 severity GenAI 异常事件规范要求 severity 为 WARN(13),但 OTel Go SDK 的 span 事件结构里没有 severity 字段,trace.EventOption 也无法在包外实现。当前用 span status = Error 兜底
总量口径只有一种 规范只定义输入与输出两个 token 属性,总量是两者之和;provider 自报的非规范总量只留在单次调用明细里
内容默认不采集 默认两个开关都是 none。看不到提示词与思考过程是默认行为,不是故障
敏感工具返回未过滤 工具返回按设计保留上游原文(用户可以直接追问「上一次调用的模型与返回结果」),其中可能携带的业务敏感数据尚无过滤机制
truncated 下的长对话保留前几轮 内容属性上限 4096 字符、单条字符串上限 512。先缩字符串,仍然超限就丢最外层数组的尾部元素,直到装下——所以长对话保留的是前几轮,不是空列表(空列表会被后端读成「没有对话」)。真正压不下去时仍退化为空容器
gen_ai.response.model 未上报 规范把「请求的模型」与「实际响应的模型」分成两个属性,网关把请求路由到另一个模型时链路里看不出来。当前只上报请求侧的 gen_ai.request.model:genkit 的 ModelResponse 与 ModelRequest 都不带模型名,要拿到实际服务的模型得侵入 OpenAI 兼容插件去解析原始响应

关联

@ambiguous-pointer ambiguous-pointer changed the title feat(ai): strengthen trace observability with discovery, diagnosis and GenAI conventions feat(ai): make the agent observable through OTel GenAI conventions Oct 26, 2026
@ambiguous-pointer

ambiguous-pointer commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

修一个 reasoning 策略的绕过(来自 #1618 的评审意见)

#1618 的评审指出 rewriteReasoningParts 有一个策略绕过:它先在原始文本里搜 reasoning 这个词,命中才继续解码。JSON 转义之后原文字节里并不含这个词 —— 比如 "type":"reasoning" —— 早退命中后整份文档原样返回,CaptureNone 形同虚设,reasoning 内容会原样进入 trace。

本 PR 才是这段代码的归属地(#1618 那边已经把 ai/component/hooks/reasoning.go 与 reasoning_test.go 移除,因为它俩在这条分支上缺了 TracingSpec.CaptureReasoning / Registration.CaptureReasoning / Manager.ReasoningPolicy 的接线,ai 模块编译不过)。所以修在这里(现已并入本 PR 的单个提交 d0bf0e1)。

改法:去掉原始文本的字符串早退,一律先解码再判定 type 判别符。解码后的比较本来就认得转义形式,所以 filterReasoningElements 里的 element["type"] != reasoningPartType 不需要改;遍历在没有 reasoning part 时返回 changed=false,文档依旧原样返回,行为不变。

回归用例 TestApplyReasoningPolicyRemovesEscapedReasoningParts:构造一个把 type 写成 JSON 转义形式的文档,断言 CaptureNone 之后只剩 text part、reasoning 内容消失。

已验证这个用例确实能抓到问题:把解码顺序改回旧写法,它会失败,报错里被转义的 reasoning part 原样保留。

补充一句上下文:ai 模块与 ui-vue3/src/components/ai-chat/ 下一批文件此前一直缺 license header(这条分支的流水线此前从不在 ai 上跑)。#1618 打开了 ci.yml 对 ai 分支的触发后,license 检查把 37 个文件挑了出来,已在 #1618 里补齐。

@ambiguous-pointer

ambiguous-pointer commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

本 PR 的范围收敛

按「只保留单纯的 GenAI OTel 可观察性」的要求,把工作区里混在一起的东西拆开了。

留在本 PR(现已并入本 PR 的单个提交 d0bf0e1):

  • invoke_agent 这条 agent span 携带 gen_ai.input.messages / gen_ai.output.messages——装的是这次交互的完整对话与最终回答。
    • interactionTrace 增加 Conversation(最后一次模型调用看到的消息窗口)与 Answer(流给用户的最终回答)
    • runIteration 记录这两个值,EventInteractionEnd 时把它们挂到 endState
    • semanticContent 增加 EventInteractionEnd 分支
    • tracing hook 在 agent span 上按 content 策略决定是否输出
    • 文档 docs/ai-agent-observability.md 补了对应的说明

动机:多数后端(Langfuse 就是)从 trace 的根 span 上取 Input / Output,根上没有这两条属性时 trace 会渲染成「no input or output」;之前消息只写在模型 span 上,这一轮聊了什么、答了什么在链路上就看不见。

拆到独立分支(fix/ai-persistence-deadline):会话持久化的 deadline 修复。它与可观察性无关 —— 原来的 persistence context 带整个 interaction 的 deadline,一次 interaction 跑得比它久(多次模型调用 + 工具调用),deadline 到期后工具结果、最终回答、turn 关闭全部失败,整个 turn 被中止,下一个提问就没有历史。改成每次写入各自带一个有界 deadline,且最终回答持久化失败时不再中断交互(答案已经产生了,不该因为存储不健康就瞒住用户)。4 个文件、190 行,含 3 个新用例。

没有进 PR(保留在本地工作区,未提交):agent.yaml / models.yaml / rag.yaml / tools.yaml / hooks.yaml 的模型与开关调整 —— 其中 models.yaml 的 base_url 被改成了一个实例专属的阿里云百炼地址(llm-5xrv4zbjodexxmlp.cn-beijing.maas.aliyuncs.com),提交上去会让所有其他用户的请求都打到那个实例上,所以整个配置文件都退回原状、只留在本地。

@ambiguous-pointer
ambiguous-pointer marked this pull request as ready for review November 2, 2026 09:11

@AlexStocks AlexStocks left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

结论

APPROVE,一条建议本轮修(GenAI 异常事件名与规范不符),其余为不阻塞项。

这个 PR 做的事情本身是对的:把 Agent 的执行过程映射到 GenAI 语义约定、把 reasoning part 补进 messages、把 capture_reasoning 做成独立于 capture_content 的正交轴,方向都没问题。其中两处细节质量很高:rewriteReasoningParts 先解码再判 type(strings.Contains(document, "reasoning") 早退会被 JSON 转义绕过,"\u0072easoning" 在字节层面不含这个词,CaptureNone 就形同虚设——这是真正的安全修复);truncateSemanticJSON 改为丢尾部元素而不是整份丢掉(避免「空列表被后端读成没有对话」的静默失真)。

下面是逐条意见,按优先级排列。


我在本地实际执行的验证

git checkout p1616
cd ai && go build ./...                          # OK
cd ai && go test ./component/hooks/... ./component/agent/...          # 全部 ok
cd ai && go test -race ./component/hooks/... ./component/agent/react/...  # 全部 ok(1m15s)
cd ai && go vet ./...                            # 无输出
cd ai && gofmt -l .                              # 23 个文件,全部在 component/rag、stub、test/e2e

关于 gofmt:这 23 个文件与 ai 分支上的既有状况一致(作者在 #1618 里已经说明过),本 PR 触及的 15 个 .go 文件全部 gofmt 干净,我逐个比对过。也就是说本 PR 没有加重这个问题,但反过来意味着「把 cd ai && go fmt ./... 加进 CI」这件事仍然被这 23 个文件挡着。

关于 CI:.github/workflows/ci.yml 与 riscv-build.yml 的触发分支只有 develop,本 PR 的 base 是 ai,所以 Go 的 build/vet/test 一次都没跑过;head d0bf0e1 上只有 SonarCloud 的两个 check。上面的本地结果是我这边唯一的编译与测试证据。这一点不是本 PR 的问题,但它决定了「本 PR 绿了」这句话在合并时的含义——建议合并前手动在 CI 或本地跑一遍两个模块。


🟡 建议本轮修:gen_ai.client.operation.exception 用在了规范明确排除的操作上

ai/component/hooks/tracing.go:52、:176

genAIOperation() 把 EventModelCallError/End 与 EventToolCallError/End 都纳入了 gen_ai.client.operation.exception。但 gen-ai-exceptions.md 对这个事件的定义是排他的:

This event represents an exception that occurred during a Generative AI client operation other than inference, embeddings, agent invocation, or response fetching ...
For inference operations, instrumentations SHOULD record gen_ai.client.inference.exception instead of this event.
For client agent invocation operations, instrumentations SHOULD record gen_ai.client.invoke_agent.exception instead.

而 execute-tool.md:857 与 client-inference.md:1365 分别定义了 gen_ai.execute_tool.exception 与 gen_ai.client.inference.exception,同样写明 The event name MUST be ...。

也就是说:

span 现在发的事件 规范要求
chat <model>(inference) gen_ai.client.operation.exception gen_ai.client.inference.exception
execute_tool <tool> gen_ai.client.operation.exception gen_ai.execute_tool.exception
invoke_agent ...(内部 agent) 不发 gen_ai.invoke_agent.exception

PR 描述里「gen-ai-exceptions.md:事件名 MUST 为此」这句是误读——那句 MUST 约束的是「这个事件本身叫什么」,不是「所有异常都用这个事件」。这两条恰好是本 PR 覆盖的全部两种操作,所以按规范实现的采集端(把 inference/tool 异常单独建视图的那类)在错误的 bucket 里找不到它们。这跟 PR 的核心诉求(「采集端按规范自己认」)是直接冲突的。

建议:genAIOperation 改成返回事件名而不是 bool,按 state.Event 分派:

func genAIExceptionName(event Event) string {
    switch event {
    case EventModelCallError, EventModelCallEnd: return "gen_ai.client.inference.exception"
    case EventToolCallError, EventToolCallEnd:   return "gen_ai.execute_tool.exception"
    }
    return ""
}

exceptionRecorder 的去重逻辑不用动(按 span key 去重仍然正确)。analyzer.go 那边的 genAIExceptionEvent 常量(#1618)要同步改成匹配多个名字,否则 #1618 的错误分类会读不到新名字。


🟡 exception.stacktrace 取的是 hook 自己的栈,不是出错点的栈

ai/component/hooks/tracing.go:218

func captureStackTrace() string {
	buffer := make([]byte, 2048)
	return string(buffer[:runtime.Stack(buffer, false)])
}

两个问题:

  1. 栈内容是常量。它在 hook 分发内部调用,每个错误的栈都是 recordGenAIException → newTracingHook.func1 → Manager.Emit → ...,跟真正出错的地方(模型调用超时、工具 panic)没有任何关系。注释里写「the same convention the OpenTelemetry Go SDK uses when it records an exception」——SDK 的 RecordError 是在错误发生的现场由调用方调用的,栈自然指向现场;这里是在 hook 边界补采,语义不同,注释会误导后来人把它当成有效证据。
  2. 2048 字节可能截断。runtime.Stack 在 buffer 不够时返回已写入的部分并截断最后一个 frame,结果是「看起来完整但最后一行是半截」——比不写更难排查。要保留就改用 debug.Stack()(按需扩容)。

建议:要么删掉这个属性(exception.stacktrace 在规范里是 Recommended 而非 Required,缺失不违规),要么在错误产生处用 errors.WithStack/自定义 error 带上栈,hook 只从 error 里取。按当前实现,每个错误 span 会稳定多出 ~2 KB 且信息量为零。


🟡 Manager.ReasoningPolicy() 没有生产消费者,且注释与实现相互矛盾

ai/component/hooks/manager.go:190

grep -rn "ReasoningPolicy" --include=*.go ai/ | grep -v _test.go 除定义处外没有命中——这个方法只有测试在用(TestManagerAppliesCaptureReasoningPolicy、TestComponentRegistersCaptureReasoningPolicy)。同时它的注释说:

The most permissive policy wins because every hook that captures payloads shares the same content

而 Emit 里的实现是逐 registration 应用策略(ApplyReasoningPolicy(..., reg.captureReasoning) / hookState.reasoningPolicy = reg.captureReasoning),两个 hook 声明不同策略时拿到的内容并不相同。所以这个方法一旦被接上去,会返回一个「比任何一个 hook 实际看到的都更宽松」的值。

建议:要么删掉(现在删零成本),要么把它变成「本 manager 对外承诺的最宽策略」并在注释里写清它不是任何一个 hook 的实际视图。留着不接、注释还写反,是最容易在下一个 PR 里被误用的状态。


🟡 capture_reasoning: none 会留下 {"role":"assistant","parts":[]}

ai/component/hooks/reasoning.go:156(filterReasoningElements)

过滤只从 parts 数组里摘元素,不判断摘完之后消息是否还剩下任何 part。因此一条只带 reasoning 的 assistant 消息会变成空 parts 消息:

[{"role":"user","parts":[{"type":"text","content":"hi"}]},
 {"role":"assistant","parts":[]}]

TestApplyReasoningPolicyIgnoresDocumentShape 把这个结果写成了断言(len(messages[1].Parts) != 0 → want 0),所以它是有意为之,但它带来的后果值得再想一遍:

  • 规范里 parts 是 message 的必填字段(models.py: ChatMessage.parts),空数组不是非法,但语义上是「一条什么都没说的助手消息」;Langfuse/OpenLIT 这类界面会渲染成一个空气泡;
  • 如果整条 trace 只有这一条 assistant 消息(例如模型这一轮只输出了 thinking),过滤后 trace 根上就是一条空内容,正好落在本 PR 想解决的那个「后端显示没有内容」的坑里;
  • 空消息还占着 4096 字节的截断预算。

建议:filterReasoningElements 之后对「parts 变空的消息」做一次收尾——整条消息丢掉,或补一个 {"type":"text","content":"[reasoning omitted]"} 占位。前者更干净,后者对「这里本来有思考」更诚实。两种都比空数组好。


💭 两处截断的「512」不是同一个 512

  • tracing.go:truncatedJSONStringLimit = 512 → truncateJSONStrings 用 typed[:limit] 切字节;
  • reasoning.go:truncatedReasoningLimit = 512 → 注释写 The limit counts characters,用 []rune 切字符。

同一个数字、两种含义,且 reasoning.go 的注释还说 It matches the limit used for the other captured JSON strings——对中文来说这等于「reasoning 保留 512 字,正文只保留 512 字节(约 170 字)」,差了 3 倍。建议要么统一成字节(与既有行为一致),要么统一成字符(与用户直觉一致),并把重复的常量收敛成一个。

💭 会话截断保留最早的几轮,丢掉最新的

tracing.go:truncateSemanticJSON 的新逻辑从数组尾部丢弃元素,注释的理由是「比整份丢掉好」。这个取舍在用户提问场景成立,但在 agent 场景里方向是反的:真正要看的是「这一轮模型拿到的最新工具返回是什么」,而它总在数组末尾。4096 字节 / 每串 512 字节,实际只留得下 8 条左右消息,最关键的尾巴全被砍掉。

可以考虑:优先丢 system 消息、或头部+尾部各保留若干条([前2条, "…省略N条…", 后4条]),至少保证最后一条 tool 结果在。这条不阻塞,但如果要在 README 里写「能看到这一轮聊了什么」,现在的实现只对短会话成立。

💭 两处行为破坏需要写进发布说明

  • span 名从 invoke_agent 变成 invoke_agent dubbo-admin-sre-agent:任何按 operation name 过滤的既有看板/告警查询会失效(Jaeger UI 的 operation 下拉、Grafana 的 operation_name= 过滤)。
  • 删除 agent.usage.total_tokens:既有按这个属性算成本的看板会归零。

两处改动方向都对(规范里确实没有 total token 属性,span 名也确实应该是 invoke_agent {name}),但这是对外契约变更,建议在 CHANGELOG 或 PR 描述里单列一条 migration note。另外 AgentName 是硬编码常量,多实例/多 agent 部署时所有 span 会报同一个名字——现在只有一个 agent 所以没问题,gen_ai.agent.name 又要求低基数,所以硬编码反而是对的,只是将来加第二个 agent 时得记着这里。


亮点

  • State.snapshotInputContent() 把策略应用放在 inputContent.snapshot() 之后、truncatedContentLimit 截断之前,这个顺序是对的:先摘掉 reasoning 再算预算,摘掉的内容真的省下了空间(README 里那张表也这么写的)。
  • filterReasoningParts 只依赖 parts + type 两个键,不绑定其余字段,正好抵抗 vLLM 把 reasoning_content 改名那类漂移。
  • 非 JSON 文档原样返回(rewriteReasoningParts 的两条 early return),把「解析失败不能丢数据」这条原则落到了代码里,而不是只写在注释里。
  • gen_ai.agent.name 只加在 agent 作用域的 span 上、gen_ai.agent.id 明确不加(测试里 assertNoSpanAttribute 钉住),对着规范抄得很细。
  • 新增 TestAgentSpanCarriesConversationAndAnswer 直接断言「trace 根上有 input/output」,而 Langfuse 的行为恰恰取决于这一点——测的是需求而不是实现。

Comment thread ai/component/hooks/tracing.go Resolved
Comment thread ai/component/hooks/tracing.go Resolved
Comment thread ai/component/hooks/manager.go Resolved
Comment thread ai/component/hooks/reasoning.go Resolved

@larry-zy larry-zy left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

补充审查已核对分支:ambiguous-pointer:feat/ai_otel_genai 的 head 为 d0bf0e1fa74734872170f772c6a8bb1780addb6f,目标 apache:ai 当前为 e6cef77666b6eb709867c92eba7c5a0fb8de0ec6。

在临时副本中合并最新 base 后,AI 模块的 go build ./...、go vet ./...、原有 go test ./... 和 hooks/react 的 race 检查均通过。下面四项是在该合并结果上用额外回归用例复现、且现有讨论尚未覆盖的问题。采集策略绕过项包含既有全局 provider 接线的问题,已在对应评论中注明归属。

Comment thread ai/component/hooks/component.go Resolved
Comment thread ai/component/hooks/manager.go Resolved
Comment thread ai/component/agent/react/steps.go Resolved
ambiguous-pointer and others added 2 commits November 16, 2026 13:02
The agent used to be a black box. What it called, which tools it used,
what it thought and what it answered could only be reconstructed from the
Admin console logs, and those logs have no session dimension, do not
record tool results and carry no causal structure. This makes the agent
emit a standard OTLP trace instead, so Langfuse, OpenLIT or any other
OpenTelemetry backend can pick it up without a line of adapter code.

The implementation follows the OpenTelemetry generative AI semantic
conventions:

- the agent-scoped spans carry gen_ai.agent.name, and the invoke_agent
  span is named "invoke_agent {gen_ai.agent.name}", so a backend
  recognises the trace as an agent trace;
- the model span is named "chat {model}" and carries
  gen_ai.request.model, gen_ai.provider.name and the token usage; the
  tool span is named "execute_tool {tool}" and carries gen_ai.tool.name;
- a failing span always carries a non-empty, low-cardinality error.type
  (falling back to _OTHER) and records a
  gen_ai.client.operation.exception event with the exception type, the
  message and the stack trace;
- gen_ai.conversation.id carries the session id, which is what Langfuse
  shows as its session;
- the private agent.usage.total_tokens attribute is gone: the
  conventions define an input and an output token count, and the total is
  their sum.

The thinking process used to be dropped on the floor, because converting
a model response into a message only handled the text, tool_call and
tool_call_response parts. A separate capture_reasoning switch keeps it
now, orthogonal to capture_content: a prompt and a chain of thought are
two different kinds of data with different risks, so one switch cannot
serve both. Both switches default to none, so no plain-text prompt
reaches a trace unless it is asked for.

The agent span carries the conversation and the final answer, because
most backends (Langfuse among them) read the trace input and output from
the root span, and a trace without them renders as "no input or output".

Two defects found while reviewing this change are fixed here as well. The
reasoning filter searched the raw document for the word "reasoning" and
returned early on a hit, so a JSON-escaped spelling of the type was
never decoded and the reasoning content reached the trace even with
capture_reasoning set to none. And the content truncation shortened the
strings first and then gave up when the document still did not fit,
replacing it with an empty list, which a backend reads as "there was no
conversation" even though the policy said "truncated".
…e with the pinned conventions

Addresses the review findings on the OTel GenAI observability work.

The agent span is the trace root, so it must carry the answer the user
actually received — and nothing else. The answer was assigned to the
interaction state before finish(), which persists it and streams it to the
user; when the persistence failed the interaction ended in an error and the
user never received the answer, while the root span still reported it as
the interaction output. A trace that shows a complete answer for an
interaction that failed to deliver it misleads exactly the investigation it
is supposed to support. The assignment now happens after finish() returns.

The exception event no longer carries exception.stacktrace. The hook only
observes the error message, so a stack captured at the hook boundary is the
same dispatch stack for every failure and says nothing about where the
failure happened; it also truncated mid-frame. The conventions list the
attribute as Recommended, so leaving it out stays within the specification.

ReasoningPolicy now says what it actually returns: the widest policy any
hook declares, not the view a single hook gets. Emit applies the policy per
registration, so two hooks that declare different policies see different
content, and the previous comment claimed the opposite.

A message whose only part was the removed reasoning is no longer left with
an empty parts array. The placeholder stands in for it: an empty array
reads as "the assistant said nothing", which a backend renders as a blank
bubble and — when the trace holds nothing else — as a trace with no
content at all, which is what the capture policy exists to prevent.

The two truncation limits are now one limit counted in bytes. The document
budget is a byte budget, so counting characters for the reasoning content
alone let a multi-byte text take up three times the room it was meant to
hold while claiming the same nominal limit.

The conventions the implementation follows are pinned at semconv-genai
commit 6fd0d76, where the GenAI exception has a single event name and the
inference exception uses it too. The conventions main branch split the
exception events after this branch was written; that split is unreleased
and marked breaking, so the pin stays and the documentation now says so.
The capture policies governed the spans the tracing hook owns and nothing
else. Three gaps let content reach a trace that the policies were meant to
keep out of it, and the reasoning capture had nothing to act on.

The reasoning policy no longer rewrites tool data. It applied to the
generic State.Input and State.Output, so the arguments of a tool call that
used the field names of a message lost their reasoning-looking elements and
the trace reported a call that never happened. The policy now applies to
the messages of a model and to nothing else.

The Genkit attributes are scrubbed at the export boundary. Genkit records
the request and the response of a model call on the span of its own action,
and those attributes never reach the Manager, so neither the content policy
nor the reasoning policy reached them. The exporter applies both, which is
what makes the documented promise that no content attribute is exported at
all hold for the whole trace.

The reasoning content of a response now reaches the message. An
OpenAI-compatible endpoint reports the thinking content in a
reasoning_content field that the adapter does not map onto a reasoning
part, so the field is read from the response body and added to the message
as a reasoning part. Without it a reasoning capture policy had nothing to
filter and the thinking content of a model never reached a trace.
@robocanic

Copy link
Copy Markdown
Contributor

感谢贡献!整体设计很清晰:将 Tracing Hook 对齐到了 OpenTelemetry GenAI 语义约定(semconv-genai@6fd0d76),补齐了 invoke_agent / chat / execute_tool Span 命名、gen_ai.* 属性、Token 聚合、根 Span 对话归档及分级内容采集策略;前两轮对异常事件去重(exceptionRecorder)和工具业务 JSON 免误伤(contentKindForEvent)的处理也很扎实。

结合最新提交(60a4a20)看了一下实现细节,新引入的 reasoning.go 与 exporter.go 还有几处关键问题建议合入前处理一下:


一、高优先级问题(P0 / P1)

1. [P0] reasoningModel.Register 注册的是未包装的 m.inner,运行期 reasoningModel.Generate 实际不会被调用

  • 位置:ai/component/models/component.go:215-217、ai/component/models/reasoning.go:138-150
  • 原因:
    genkit.RegisterAction(g, reasoningModel{inner: model}) 内部调用 action.Register(g.reg),而 reasoningModel.Register 直接转发给了 m.inner.Register(r),把未包装的原始 *ai.model(底层 ActionDef)注册进了 Genkit Registry,reasoningModel 结构体本身并未进入 Registry。
    运行期 ReActAgent 通过 ai.WithModelName(model) -> ai.LookupModel(r, opts.Model) 解析出来的是原始 m.inner:
    1. reasoningModel.Generate 在生产链路中永远不会执行,ctx 中也不会注入 reasoningCaptureKey{};
    2. 即使开启 capture_reasoning: full/truncated,实际运行中依然采不到 reasoning_content;
    3. captureReasoningMiddleware 每次请求仍会把响应体 io.ReadAll 读进内存,再因 req.Context() 里取不到 reasoningCaptureKey{} 而丢弃。
      (现有 reasoning_test.go 直接实例化 reasoningModel{...} 调用 .Generate(...),未走 RegisterAction + LookupModel 路径,所以单测没有暴露。)
  • 建议:改用 ai.NewModel(api.NewName(providerName, cfg.Key), &ai.ModelOptions{...}, func(ctx, req, cb) { ... })(或 genkit.DefineModel)把 reasoningCapture 注入与 PartReasoning 追加包进真正的 ActionDef 执行函数中再注册,并补充走 genkit.LookupModel 的单测。

2. [P1] 思考模型返回空正文(仅含 reasoning_content)时,resp.Text() 会把思维链当成最终回答发给用户,并绕过 capture_reasoning: none

  • 位置:ai/component/models/reasoning.go:164-169、ai/component/agent/react/steps.go:157, 180
  • 原因:
    在当前依赖的 github.com/firebase/genkit/go@v1.2.0 中,compat_oai 仅当 Message.Content != "" 时才追加 PartText(compat_oai/generate.go:425);而 ai.Message.Text()(ai/generate.go:840-842)有一条未检查 PartKind 的单元素快路径:
    if len(m.Content) == 1 {
        return m.Content[0].Text // 未检查 p.IsText(),会直接返回 PartReasoning.Text
    }
    一旦修好上面的注册问题,当思考模型(DeepSeek-R1 / QwQ / Qwen3 等)因 max_tokens 在思考阶段耗尽(finish_reason: "length",content: "")或偶发空正文且无 tool call 时,response.Message.Content 原本为空,追加 ai.NewReasoningPart(reasoning, nil) 后恰好 len(Content) == 1。此时 steps.go:180 的 answer := resp.Text() 会直接拿到整段原始 reasoning:
    1. 跳过空响应重试和 fallbackAnswer,直接把内部推理文本流式发给终端用户并存入 messageStore;
    2. EventInteractionEnd 通过 genAIAssistantMessages(interactionState.Answer) 将其作为普通 {"type":"text","content":"..."} 写入根 Span 的 gen_ai.output.messages,从而绕过 capture_reasoning: none。
  • 建议:在 react 层提取文本回答时不要直接依赖 resp.Text(),改为显式只拼接 part.IsText() 的分片(另外留意 compat_oai 的 concatenateContent 拼历史消息时同样不区分 PartKind,避免未来将含 PartReasoning 的原始 resp.Message 直接回传模型)。

3. [P1] contentScrubbingExporter 在 capture_content: truncated 下未截断 Genkit Span,且 scrubGenkitResponse 漏掉了非 ModelResponse 结构的输出

  • 位置:ai/component/hooks/exporter.go:79-103, 144-165
  • 原因:
    1. scrubAttributes 只在 CaptureNone 时丢弃 genkit:input / genkit:output;设为 CaptureTruncated 时没有执行 4096B / 512B 截断限制,导致每次 prompt.Execute 产生的 Genkit Span(prompt / generate / model)仍会全量导出完整系统提示词、历史上下文与全部工具 Schema,与 ai/component/hooks/README.md 中“truncated 限制每个 JSON 属性不超过 4096 字节、策略覆盖整条 trace”的说明不一致。
    2. scrubGenkitResponse 仅按 ai.ModelResponse(单数 "message" 字段)反序列化;而 Genkit ExecutablePrompt Span 的 genkit:output 是 *ai.GenerateActionOptions(复数 "messages" 字段),解析后 response.Message == nil 会直接原样放行,若其中带有 PartReasoning 会漏过 capture_reasoning 过滤。
  • 建议:在 CaptureTruncated 下对 genkit:input / genkit:output 同步执行截断(或评估在导出标准 gen_ai.* 属性时直接剥离冗余的 genkit:input/genkit:output);同时让 scrubGenkitResponse 兼容含 "messages" 数组的 payload。

二、中低优先级问题(P2 / P3)

  1. [P2] docs/ai-agent-observability.md 未随 60a4a20 同步更新(docs/ai-agent-observability.md:207-208, 216-217, 224-232):

    • 第 7 节“已知限制”仍写着“思考内容目前采不到”和“capture_content: none 时完整 trace(含 genkit 的 prompt/model span)里仍可能带用户输入与提示词”,第 8 节仍列为待办,第 9 节也漏掉了 ai/component/hooks/exporter.go 和 ai/component/models/reasoning.go,与最新代码及 ai/component/hooks/README.md 矛盾。
  2. [P2] captureReasoningMiddleware 吞掉读取错误及无谓缓冲(ai/component/models/reasoning.go:76-99, 108-129):

    • body, readErr := io.ReadAll(resp.Body) 若中途网络断开(readErr != nil),第 88-90 行用半截 bytes.NewReader(body) 替换 resp.Body 并返回 return resp, nil,下游只会看到 JSON unexpected EOF,掩盖了真实的传输层错误。
    • 同一个 OpenAICompatible client 同时服务于 Embedder(/embeddings 响应较大)和未开启捕获的请求,建议先检查 req.Context().Value(reasoningCaptureKey{}) 是否存在,再执行 io.ReadAll。
    • 第 81 行已限定 Content-Type 含 application/json(建议大小写不敏感匹配),SSE 流式响应已提前返回,reasoningContents 中的 Delta.ReasoningContent 分支目前是不可达代码。
  3. [P2] 交互在首轮组装消息前失败时,根 invoke_agent Span 会写出 gen_ai.input.messages = "[]"(ai/component/agent/react/react.go:210-212、hook_content.go:39-45):

    • 当 interactionState 已初始化但 ra.run 在 s.Conversation = messages(steps.go:151)前出错返回时,interactionState.Conversation 为 ([]*ai.Message)(nil),装入 any 后 input.([]*ai.Message) 为 true,convertGenAIMessages(nil, "") 返回非 nil 空切片并序列化为 "[]"。建议在 len(messages) == 0 时返回 nil 以省略该属性(与 genAIAssistantMessages("") 行为一致)。
  4. [P3] 小细节:

    • ai/component/hooks/exporter_test.go:73-77 调用了全局 otel.SetTracerProvider(provider) 并在 t.Cleanup 中 Shutdown,建议在 Cleanup 中恢复原有的 otel.GetTracerProvider(),避免影响同包后续测试。
    • ai/schema/json/hooks.schema.json:53-60, 129-136 中新增的两处 capture_reasoning 建议和 capture_content 一样补上 "default": "none"。

…he answer

The wrapper that adapts the reasoning content of a response was never the
model that entered the registry. genkit.RegisterAction calls the Register
method of the value it is given, and the wrapper forwarded that call to the
model it wraps, so the registry held the wrapped model and a lookup
resolved that one. The wrapper never ran. The reasoning content of a
response was therefore never captured, a reasoning capture policy had
nothing to filter, and the middleware read the body of every chat
completion into memory only to discard it.

The wrapper is now the model that enters the registry, with the adaptation
bound to its execution function, and it carries the options of the model it
wraps so that the registered model keeps the capabilities the adapter
declared for it.

The reasoning of a thinking model is a reasoning part, and genkit's
Message.Text() returns the text of a single part without looking at its
kind. A response that carried nothing but the reasoning would therefore
have been delivered to the user as the answer, and it would have bypassed
the capture policy that is meant to keep the reasoning out of the trace.
The answer of a response is now taken from the parts genkit treats as text,
so a response without an answer is empty and the reasoning stays where it
belongs.

The middleware reads the body of a response only when a capture is in
flight, so a request without one is no longer buffered.

The test of the registered model looks the model up by name, the way the
agent does. A test of the wrapper alone cannot see that the wrapper was not
the model the agent used.
…ng hook

The ai branch moved on while this PR was open: apache#1600, apache#1594, apache#1596 and
apache#1608 landed. The tracing hook is the place they meet, because apache#1594
enforces the sensitive data boundaries and this PR adds the graded
capture policies.

The merge keeps both sides:

- The content capture stays fixed to none, as apache#1594 requires. The schema
  constrains it and the validation rejects any other value, so no
  deployment can turn it on. The machinery that shortens a captured
  payload is kept for the controlled diagnostic channel that ADR 0002
  defers.
- The reasoning policy is a separate axis and keeps its own levels.
- The span strings, the error text on the standard exception event and
  the GenAI exception message now go through the sanitizer of apache#1594.
- The model call receives the ephemeral sanitized view of apache#1594, and the
  canonical messages are only used for the agent span.
- The reasoning capture middleware reports the transport error instead of
  handing a half-read body back, which hid the failure behind a JSON parse
  error downstream.
- An empty conversation is left out of the span instead of being exported
  as an empty list, which a backend reads as "there was no conversation".
- The Genkit content attributes are shortened on the export boundary too,
  so the budget of the truncated policy holds for the spans Genkit writes
  itself.
- The reasoning capture policy has a default in the schema, like the
  content policy, and the config loader renders it.
- The exporter test restores the global tracer provider.
- The observability document describes the reasoning adaptation and the
  export boundary.
The pinned semantic conventions describe the exception event for a
generative AI client operation, and a tool call is an operation of the
agent and not of a client. The tool span keeps the standard exception
event and the span status until the conventions give the tool call an
event of its own.
@sonarqubecloud

sonarqubecloud Bot commented Dec 2, 2026

Copy link
Copy Markdown

@ambiguous-pointer

Copy link
Copy Markdown
Contributor Author

结论

感谢这轮评审。P0 与最重的那条 P1 是一起修的 —— 这两条有因果关系,分开修会出事。其余逐条核实:多数属实并已修,两条按「保留机制、默认值不变」处理。

这一版同时并入了上游 ai 分支的四个 PR(#1600 JWT 认证、#1594 敏感数据边界、#1596 交互幂等与会话生命周期、#1608 快照与契约加固),合并提交是 862ff8b。下面的行号都指合并后的代码。

一、P0 与 P1 #2 一起修:前者掩盖了后者

P0 — reasoningModel 没有真正进入 registry

这条成立,而且比评审描述的更彻底。 原因链逐段在 genkit v1.2.0 源码中确认过:

  • genkit.RegisterAction(g, v) 的实现就是 v.Register(g.reg)(genkit/genkit.go:225),注册被转发给值自己;
  • 本 PR 的 reasoningModel.Register(r) 转发给了 m.inner.Register(r),进 registry 的是未包装的内层模型;
  • 运行期 ai.LookupModel(r, name) 用 core.ResolveActionFor[*ModelRequest, *ModelResponse, *ModelResponseChunk](r, api.ActionTypeModel, name) 取回的同样是内层模型。

所以 reasoningModel.Generate 在生产链路里从未被调用:ctx 里不会有 reasoningCaptureKey{},capture_reasoning: full/truncated 采不到任何东西;captureReasoningMiddleware 却每个响应体都 io.ReadAll 进内存再丢弃。现有单测直接实例化 reasoningModel{...} 调 .Generate(...),绕过了 RegisterAction + LookupModel,所以没有暴露。

修法:wrapper 改为用 ai.NewModel(name, &opts, m.generate) 把自己注册进 registry,捕获键注入与 PartReasoning 追加都发生在真正的 ActionDef 执行函数里;被包装模型的 ai.ModelOptions 一并传给 wrapper,注册出的模型保留 adapter 声明的能力位(ai/component/models/reasoning.go 的 Register / action(),以及 ai/component/models/component.go 传入 options)。genkit 的四个内置 middleware 内外各套一次,但对本配置全是 no-op 或幂等。

回归测试:TestTheRegisteredModelCarriesTheReasoning(ai/component/models/reasoning_test.go)走 RegisterAction + LookupModel 的真实路径,断言取回的模型确实带 reasoning part。把 Register 改回旧写法,这个用例会失败。

P1 #2 — 思维链被当成最终回答发给用户

这条同样成立,而且正是 P0 掩盖的结果 —— 这也是两条必须一起落地的原因。

ai.Message.Text()(genkit v1.2.0 ai/generate.go:834)在只有一个 part 时走快路径 return m.Content[0].Text,不检查 PartKind;多元素路径才会 p.IsText() || p.IsData()。而 reasoningModel.Generate 追加的是 ai.NewReasoningPart。

P0 未修时 reasoning part 根本不会被追加,所以这条不会触发;一旦只修 P0,只返回 reasoning_content 的思考模型就会产出一个 reasoning part,resp.Text() 把它当成答案发给用户,并且绕过 capture_reasoning: none。

修法:新增 ai/component/agent/react/answer.go 的 answerText(resp),只拼接 part.IsText() || part.IsData() 的分片;ai/component/agent/react/steps.go 的空响应判定与答案提取都改用它。回归测试 TestAnswerTextIgnoresTheReasoning / TestAnswerTextReturnsTheTextParts / TestAnswerTextOfAnEmptyResponse(ai/component/agent/react/answer_test.go)。

顺带确认了评审提到的另一半:agent 从不把 resp.Message 原样回传模型(ra.finish 用答案文本重建消息存进历史),所以历史里不会出现 reasoning part。

二、P1 #3 — 导出器

前半属实,已修。 contentScrubbingExporter 之前只按 reasoning 策略过滤,没有按预算截断 Genkit 写的 genkit:input / genkit:output。现在 ai/component/hooks/exporter.go 的 truncate 在 capture_content: truncated 下用与 hook 路径同一个 truncateSemanticJSON 和同一个预算截断。

后半是防御性分支。 genkit v1.2.0 把 genkit:output 写成 json.Marshal(ai.ModelResponse),不是 ModelResponse 形状的输出不会出现在这条路径上;scrubGenkitResponse 在解析失败时原样返回,正是为了「解析失败绝不丢内容」。

三、P2 与 P3

文档未同步(属实,已修)

docs/ai-agent-observability.md 第 7 节的「思考内容目前采不到」和第 8 节的两条待办已经过期:reasoning part 的来源已接上(ai/component/models/reasoning.go 的 middleware 读出响应里的 reasoning_content,reasoningModel 追加为 reasoning part),Genkit 自身的 span 由 ai/component/hooks/exporter.go 在导出边界处理。第 9 节的相关文件表补上了 exporter.go 与 models/reasoning.go。

middleware 吞掉读取错误与无谓缓冲(属实,已修)

  • 读取错误:之前 io.ReadAll 出错时用半截 body 替换 resp.Body 并返回 nil 错误,真实的传输层错误会被下游的 JSON unexpected EOF 掩盖。现在返回带包装的错误(ai/component/models/reasoning.go)。
  • 无谓缓冲:现在先检查 req.Context() 里有没有捕获键,没有就直接 next(req),不读 body。
  • Content-Type:改成大小写不敏感匹配。
  • Delta.ReasoningContent 分支保留:它覆盖以 chunk 形状的 JSON 应答的端点,删掉会让这类端点的思考内容被静默丢弃。

首轮失败时写出 gen_ai.input.messages = "[]"(属实,已修)

ai/component/agent/react/hook_content.go 的 convertGenAIMessages 在消息为空时返回 nil,属性整个省略,不再导出空列表。

两处 P3(属实,已修)

  • ai/component/hooks/exporter_test.go 现在在 cleanup 里恢复原来的全局 tracer provider。
  • ai/schema/json/hooks.schema.json 的两处 capture_reasoning 补上 "default": "none"。副作用是配置 loader 会把 capture_reasoning: none 渲染进配置,ai/config/test/hooks_config_test.go 的三处期望值相应更新 —— 与上游 capture_content 的既有行为一致。

四、合并上游带来的变化,需要一起看

上游 #1594 把 capture_content 固定为 none:schema 里是 "const": "none",配置成别的值启动即报错(ADR 0002 要求 span 保持 metadata-only,内容要走带授权与 TTL 的受控诊断通道)。

本 PR 保留了这套分级采集的机器(截断、reasoning 过滤),但配置层面仍然锁死 —— schema 的 const 与 validate() 都拦住了它。也就是说采集策略目前是休眠的,等受控诊断通道落地后再启用;上游的 sanitizer 同时接管了 span 字符串、标准异常事件文本与 GenAI 异常消息。

如果维护者希望采集策略现在就可用,那是与 #1594 的策略取舍,需要一起决定;本 PR 没有单方面放宽 const。

五、未验证项

评审提到的「各厂商真实端点对这些参数的接受情况」仍然无法验证(无凭证)。本轮新增的验证都在本地与 httptest 级别。

@robocanic robocanic left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

审查结论

整体方向正确:Span 命名、gen_ai.* 属性、error.type 兜底、provider 映射与规范对齐;capture_reasoning 与 capture_content 正交的设计清晰;rewriteReasoningParts 先解码再判 type(避免 JSON 转义绕过)、导出边界对 genkit:input/output 的兜底处理、answerText 不再把 reasoning 当答案交付,都是扎实的改动。我在 head 7609165 上通读了全部非测试代码,未发现 Critical 级别的问题,下面是两条建议合并前处理的 Important 项。

Critical

未发现。

Important

1. 文档、hooks.yaml 与 PR 描述宣称 capture_content 可配 truncated/full,但代码与 schema 会拒绝,运行时与文档契约相互矛盾

  • ai/component/hooks/component.go:105:validate() 对 capture_content != none 直接返回错误;ai/schema/json/hooks.schema.json 中该字段也是 const: "none"。
  • 但 ai/component/hooks/hooks.yaml:38(注释 none | truncated | full)、docs/ai-agent-observability.md:60(§3.1 配置示例)、§3.2 的开关矩阵与「建议」表(开发环境 truncated/full)、§5 调试速查(多处「需开 capture_content」)以及 PR 描述的表格,都在指导用户开启内容采集。照做会在启动时直接报错;只有 §7「内容不采集」一行说明了它被固定为 none。
  • 直接后果:在当前可配置的取值下,capture_reasoning: truncated|full 没有任何可观察效果(内容属性全部不发),PR 标题/描述里「思考过程可见、输入输出可见」的核心卖点在生产配置下不可达;reasoning.go、exporter.go 的 truncated/full 分支、contentAttributes 的内容路径都只能靠单测覆盖,无法端到端验证。此外 PR 描述称异常事件带 exception.stacktrace,而代码(tracing.go recordGenAIException)有意不记录。
  • 建议:统一口径。把 hooks.yaml 注释、文档 §3.1/§3.2/§5 与 PR 描述改成「capture_content 当前固定为 none,capture_reasoning 暂无外部可见效果,待受控诊断通道(ADR 0002)落地后生效」,并在 PR 描述中如实说明这点,避免使用者和后续 reviewer 误判功能已可用。

2. reasoningModel 与 captureReasoningMiddleware 对所有模型调用无条件生效,即便 capture_reasoning: none(默认且当前唯一有效的取值)也有额外开销和暴露面

  • ai/component/models/component.go:220、:271;ai/component/models/reasoning.go:81、:188:每次 generate 都会向 ctx 注入 reasoningCapture,因此中间件对每一个 application/json 响应都执行 io.ReadAll + json.Unmarshal 解析 reasoning_content,随后把 reasoning 以 ReasoningPart 追加到 response.Message.Content 里——无论后面是否有任何策略会用到它。
  • 影响:① 默认配置下每次模型调用多一次完整响应体缓冲与解析,却不产生任何可观察输出;② 完整的 thinking 文本被常驻在所有 ModelResponse.Message 上,之后任何新增的、会序列化/持久化/回传 resp.Message 的调用点(包括 RAG 的 query rewrite/hyde/intent 等同样走这些已注册模型的路径)都会默认携带 reasoning,只能依赖每个消费方自觉过滤(answerText 就是为此而加的补丁)。
  • 建议:让 registerModel/createModelPlugin 只在 hooks 配置的 capture_reasoning != none 时才包装模型并安装中间件(或至少让 reasoningModel.generate 在策略为 none 时跳过注入),默认路径保持与改动前完全一致;并补一个「策略为 none 时响应体不被缓冲、Message 不含 ReasoningPart」的测试。

其它说明(不阻塞)

  • 上一轮评审提到的 Go CI 不会在 base 为 ai 的 PR 上触发,仍然成立;合并前请在本地跑 cd ai && go build ./... && go test -race ./component/hooks/... ./component/agent/react/... ./component/models/... 作为唯一的编译与测试证据。

总体评估

可以合并:需先修复上述两条 Important(至少统一文档/配置契约,并为 reasoning 包装器加上策略开关)。

核心实现质量较高,且 Critical 级问题未发现;但文档与代码在 capture_content 上的契约矛盾会直接误导使用者,且默认路径上的无条件响应体缓冲与 reasoning 常驻是可以低成本消除的风险。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants