Repository navigation
feat(ai): make the agent observable through OTel GenAI conventions - #1616
ambiguous-pointer wants to merge 7 commits into
Conversation
4180a8a to
3899b5b
Compare
修一个 reasoning 策略的绕过(来自 #1618 的评审意见)#1618 的评审指出 本 PR 才是这段代码的归属地(#1618 那边已经把 改法:去掉原始文本的字符串早退,一律先解码再判定 type 判别符。解码后的比较本来就认得转义形式,所以 回归用例 已验证这个用例确实能抓到问题:把解码顺序改回旧写法,它会失败,报错里被转义的 reasoning part 原样保留。
|
本 PR 的范围收敛按「只保留单纯的 GenAI OTel 可观察性」的要求,把工作区里混在一起的东西拆开了。 留在本 PR(现已并入本 PR 的单个提交
动机:多数后端(Langfuse 就是)从 trace 的根 span 上取 Input / Output,根上没有这两条属性时 trace 会渲染成「no input or output」;之前消息只写在模型 span 上,这一轮聊了什么、答了什么在链路上就看不见。 拆到独立分支( 没有进 PR(保留在本地工作区,未提交): |
df77d49 to
d0bf0e1
Compare
AlexStocks
left a comment
There was a problem hiding this comment.
结论
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 recordgen_ai.client.inference.exceptioninstead of this event.
For client agent invocation operations, instrumentations SHOULD recordgen_ai.client.invoke_agent.exceptioninstead.
而 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)])
}两个问题:
- 栈内容是常量。它在 hook 分发内部调用,每个错误的栈都是
recordGenAIException → newTracingHook.func1 → Manager.Emit → ...,跟真正出错的地方(模型调用超时、工具 panic)没有任何关系。注释里写「the same convention the OpenTelemetry Go SDK uses when it records an exception」——SDK 的RecordError是在错误发生的现场由调用方调用的,栈自然指向现场;这里是在 hook 边界补采,语义不同,注释会误导后来人把它当成有效证据。 - 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 的行为恰恰取决于这一点——测的是需求而不是实现。
larry-zy
left a comment
There was a problem hiding this comment.
补充审查已核对分支:ambiguous-pointer:feat/ai_otel_genai 的 head 为 d0bf0e1fa74734872170f772c6a8bb1780addb6f,目标 apache:ai 当前为 e6cef77666b6eb709867c92eba7c5a0fb8de0ec6。
在临时副本中合并最新 base 后,AI 模块的 go build ./...、go vet ./...、原有 go test ./... 和 hooks/react 的 race 检查均通过。下面四项是在该合并结果上用额外回归用例复现、且现有讨论尚未覆盖的问题。采集策略绕过项包含既有全局 provider 接线的问题,已在对应评论中注明归属。
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.
d0bf0e1 to
8396005
Compare
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.
|
感谢贡献!整体设计很清晰:将 Tracing Hook 对齐到了 OpenTelemetry GenAI 语义约定( 结合最新提交( 一、高优先级问题(P0 / P1)1. [P0]
|
…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.
|
结论感谢这轮评审。P0 与最重的那条 P1 是一起修的 —— 这两条有因果关系,分开修会出事。其余逐条核实:多数属实并已修,两条按「保留机制、默认值不变」处理。 这一版同时并入了上游 一、P0 与 P1 #2 一起修:前者掩盖了后者P0 —
|
robocanic
left a comment
There was a problem hiding this comment.
审查结论
整体方向正确: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.gorecordGenAIException)有意不记录。 - 建议:统一口径。把
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 常驻是可以低成本消除的风险。



概要
把 Dubbo Admin 的 AI 助手变成可观测、可调试的对象——不翻 console 日志,就能看清它是怎么跑的:怎么发起调用、调了哪些 tools、思考过程是什么、输入输出长什么样。
做法是让 Agent 的执行过程符合 OpenTelemetry generative AI 语义约定,导出标准 OTLP。结果是采集端的可视化直接可用,Langfuse / OpenLIT / 任何 OTel 后端都能认出来,不需要写任何一行适配代码。
采集端能看到什么
OpenLIT —— 链路树被原生重建,Agent 被识别为 Coding Agent:
Langfuse —— 会话、模型用量、token 全部对上,
sessionId直接来自gen_ai.conversation.id:上面两张图不是设计稿,是实测——在本地统一收集点(OTel Collector → Langfuse / OpenLIT / Greptime)上跑真实的 Agent 交互导出来的。
为什么是「可观测性 + 采集端配合」,而不是别的
Agent 此前是个黑盒。它跑完一次会话,中间调了哪些工具、模型返回了什么、有没有走降级、思考过程是什么,只能翻 Admin 的 console 日志。而 console 日志有两个根本缺陷:
这三件事不是「补几个日志字段」能解决的——它们需要一个带会话维度、带因果结构、能被通用工具消费的数据模型。OTel 的 GenAI 语义约定正好给了这个模型:把 Agent 的执行过程表达成规范的 trace,导出 OTLP,后端按规范自己认。
为什么不用私有的
ai.model.*命名空间:短期省事,但代价是后端认不出来——每个平台都要写一层适配,而适配层永远追不上规范演进。(规范没有定义的内部信息——交互 id、迭代序号、阶段、降级与兜底——仍然用agent.*前缀,它们不参与后端对 Agent 的识别。)上面两张截图里 OpenLIT 把它显示成 Coding Agent、Langfuse 把它映射成 Session,全是因为我们发的是规范属性。改了什么
1. 对齐语义约定(
ai/component/hooks/tracing.go)gen_ai.agent.namegen_ai.invoke_agent.internal上是 Conditionally Requiredinvoke_agent {gen_ai.agent.name}invoke_agent {name}error.type,兜底_OTHERerror.type会直接毁掉它的基数gen_ai.client.operation.exception事件,带exception.type/exception.message/exception.stacktracegen-ai-exceptions.md:事件名 MUST 为此exception事件保留——Dubbo RPC 链路里全是传统异常,读它们是分析器的基本盘gen_ai.provider.name映射到规范的 well-known 值gemini→gcp.gemini(依据是 base_url 为generativelanguage.googleapis.com,而规范对gcp.gemini的描述正是 "Also known as the AI Studio API")agent.usage.total_tokensprovider 映射不做过滤:规范原文允许自定义值("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_contentcapture_reasoningnonetruncated/fullnonetruncated/fulltruncatedtruncated/fullfull为什么拆成两个开关:它们是两类不同的风险。提示词与工具入参/返回值是业务数据(可能含用户标识、订单信息);思考过程是另一类内容,敏感度与用途都不同。合成一个开关,就没法做到「开发期要盯思考过程、生产期要把它藏起来」的同时不误开业务数据。
两个开关默认都是
none—— 默认情况下链路里不存在任何明文提示词,这是刻意的隐私保护,也让「在共享环境里打开采集」是安全的。3. 文档
docs/ai-agent-observability.md—— 属性与后端字段的映射表、怎么开采集、调试速查表(我想知道 X → 去哪看)、已验证结果、已知限制。ai/component/hooks/README.md—— 配置项说明。调试速查(节选)
gen_ai.conversation.id(Langfuse 里就是 Session ID)gen_ai.tool.name+ span 名execute_tool <tool>gen_ai.tool.call.arguments/.result(需开capture_content)type: "reasoning"part(需开capture_reasoning)error.type+gen_ai.client.operation.exception事件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 无缺失:Client(规范要求),失败的工具 span 状态为Error;gen_ai.provider.name = gcp.gemini(映射生效)、gen_ai.agent.name = dubbo-admin-sre-agent;gen_ai.client.operation.exception事件(异常事件按 span 去重);{"type":"reasoning"},符合规范;sessionId来自gen_ai.conversation.id,模型用量面板显示gemini-pro / 192 tokens。两个与本改动无关、但排查时值得知道的事实:
tail_sampling(常见策略:错误必留、慢链路必留、其余按百分比),没有错误且不够慢的链路会被按概率丢弃。此时「某段时间没有失败链路」这个结论并不可靠。已知限制
trace.EventOption也无法在包外实现。当前用 span status = Error 兜底none。看不到提示词与思考过程是默认行为,不是故障truncated下的长对话保留前几轮gen_ai.response.model未上报gen_ai.request.model:genkit 的ModelResponse与ModelRequest都不带模型名,要拿到实际服务的模型得侵入 OpenAI 兼容插件去解析原始响应关联
6fd0d76,全部文档 Status 为 Development)