让客户端库为调用生成观测数据
阅读约 54分钟,8节中含5个示例。
实验室
通过动手实践学习本章
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。
在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。
在本书所用版本上运行你的代码
学完本章,你将能够读懂官方 OpenAI 观测插桩为一次对话调用写出的内容,指出其中哪些名称与本书所遵循的 GenAI 约定版本 0.1.0 不一致,并说出决定提示词和回复是否被记录的那个变量及其默认值。第 1 章手工编写了模型 span。第 2 章"按标准的方式命名 span"为这些 span 采用了标准的名称。本章要问的是,能否由库来写这些 span,以及库写出的 span 在哪些地方不同。
Ambrewick 的助手通过 openai 客户端库调用其模型,而该库有一些包可以封装客户端,并为每次调用写一个 span。在第 1 章中,只有模型调用的步骤带有记录下来的时间,因此,如果某个包能正确写出这些调用,本书就可以省去相当一部分手工编写的 span。如果某个包写出的内容不同,则本章之后各章中的每一条查询都会受到影响,因为这些章节要读取这些名称。问题是具体的:对于一次真实的调用,这个包会输出什么,它与本书手工编写的内容有何不同?
这部分尚未翻译,因此以英文显示。
A call through the client
There are two ways to get a span for a model call. Manual instrumentation is spans your code makes; automatic instrumentation collects telemetry with no change to the application's source code. Chapter 1 used the first kind. This section uses an instrumentation library. An instrumentation library is a package that makes the telemetry for another library's calls: one call in the start-up code installs it, and the zero-code agent, opentelemetry-instrument, loads the same package with no change to the calls.
1"""One chat call through the openai client, instrumented by the official package and answered from the recording. The2point rests on three printed facts: the call makes one client span, named for its operation and model; that span is a3child of the message's span; and it holds the usage the reply reported. The metrics are named and counted here, never4valued, since their durations use real time."""5from lib.http_replay import client, route_body # lib first: threads and seeds are fixed before anything else67import opentelemetry.sdk.trace as sdk_trace8from opentelemetry.instrumentation.genai.openai import OpenAIInstrumentor9from opentelemetry.sdk.metrics import MeterProvider10from opentelemetry.sdk.metrics.export import InMemoryMetricReader11from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1213from lib.assistant import RELEASES14from lib.case import load_messages15from lib.clock import VirtualClock16from lib.ids import SequentialIds17from lib.names_map import name_map18from lib.report import fmt_int19from lib.tracing import make_provider2021clock = VirtualClock("2026-12-07")22# The SDK reads span times from its trace module's time_ns, so patching that name gives every span, the package's included,23# virtual times.24sdk_trace.time_ns = lambda: clock.advance(1_000_000)25exporter, reader = InMemorySpanExporter(), InMemoryMetricReader()26provider = make_provider("ambrewick-assistant", RELEASES["r0"].service_version, "example", clock, SequentialIds(),27 exporter, "https://opentelemetry.io/schemas/1.45.0")28OpenAIInstrumentor().instrument(tracer_provider=provider, meter_provider=MeterProvider(metric_readers=[reader]))2930with provider.get_tracer("ambrewick-assistant").start_as_current_span("invoke_agent ambrewick-assistant"):31 reply = client().chat.completions.create(**route_body(load_messages("2026-12-07")[0]))3233call, root = exporter.get_finished_spans() # the call ends before the message's span does34metrics = reader.get_metrics_data().resource_metrics[0].scope_metrics[0].metrics35print("spans in the trace:", len(exporter.get_finished_spans()))36print("instrumented span, name:", call.name)37print("instrumented span, kind:", call.kind.name)38print("instrumented span, scope schema URL:", call.instrumentation_scope.schema_url)39print("attributes on the span:", ", ".join(sorted(call.attributes)))40print("gen_ai.provider.name on the span:", call.attributes["gen_ai.provider.name"])41print("server.address on the span:", call.attributes["server.address"])42print("server.port on the span:", call.attributes["server.port"])43print("input count on the span:", fmt_int(call.attributes["gen_ai.usage.input_tokens"]))44print("output count on the span:", fmt_int(call.attributes["gen_ai.usage.output_tokens"]))45for metric in metrics: print(f"metric {metric.name}, unit {metric.unit.strip('{}')}, data points: {len(metric.data.data_points)}")46types = {p.attributes["gen_ai.token.type"] for m in metrics if m.name == "gen_ai.client.token.usage" for p in m.data.data_points}47print("token types on the usage metric:", ", ".join(sorted(types)))48# The call is a child of the message's span, and its usage is the reply's. Every name it makes is in the table.49assert call.parent.span_id == root.context.span_id50assert (call.attributes["gen_ai.usage.input_tokens"], call.attributes["gen_ai.usage.output_tokens"]) == (51 reply.usage.prompt_tokens, reply.usage.completion_tokens)52assert {m.name for m in metrics} | set(call.attributes) | {"gen_ai.token.type"} <= set(name_map())
python instrumented-chat-call.pyspans in the trace: 2
instrumented span, name: chat qwen3-4b-instruct-2507
instrumented span, kind: CLIENT
instrumented span, scope schema URL: https://opentelemetry.io/schemas/1.37.0
attributes on the span: gen_ai.operation.name, gen_ai.provider.name, gen_ai.request.max_tokens, gen_ai.request.model, gen_ai.request.seed, gen_ai.request.temperature, gen_ai.response.finish_reasons, gen_ai.response.id, gen_ai.response.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, server.address, server.port
gen_ai.provider.name on the span: openai
server.address on the span: localhost
server.port on the span: 8000
input count on the span: 142
output count on the span: 6
metric gen_ai.client.operation.duration, unit s, data points: 1
metric gen_ai.client.token.usage, unit token, data points: 2
token types on the usage metric: input, output
自第 2026.11.2 版起由 openai3.56.0至3.57.0 更新。
The run sends one route request through the openai client: the route call for the dev day's first message, which load_messages(...)[0] replays. The client does not reach a model. Its HTTP exchange is a recording, served by the mock transport of httpx from lib/http_replay.py. The transport answers every request, so no socket opens even though the URL names the model server. The recorded server sends usage only on a non-streamed reply, so the recording keeps that reply, and a span takes its token counts from usage. The run also patches the time_ns in the SDK's trace module, which the package's spans take their times from, so the call's span gets the virtual times the replay gives. Replay and the virtual clock explains the rest. The package's duration metrics are not patched, and what the package emits says why.
The trace holds 2 spans: the message's root, invoke_agent ambrewick-assistant, and the call. The package marks the call CLIENT, as the book marks its own model calls, because the model runs behind a server. The call's span is named chat qwen3-4b-instruct-2507, the operation followed by the model, which is the registry's pattern for an inference span.
The call's usage reads 142 input tokens and 6 output tokens. These are the usage counts the llama-cpp-python server reported in its reply, which the package copied onto the span. They are not the book's recorded counts, which re-tokenize the prompt. The attribute's name, gen_ai.usage.input_tokens, says what the value counts, not where it came from.
The book's code makes only the root; the package makes the call's span inside it. The script asserts that the call's parent is the root, and that its two usage counts equal the reply's, so a change in either fails the run.
Working rule: Wrap the client once, at start-up, and make your own spans only for work the library cannot see, such as the message's root, its tool calls and its fallback reply. When no package wraps a client, or the one that does writes names the table can't map, make the call's span by hand, as chapter 1 did. Then check the call's parent in a test, as the script does, because the parent is what places the call in its message's trace.
该包输出的内容
该包为每次调用写入一个 span,span 以操作和模型命名,输出按排序后的顺序列出该 span 上的属性名称。本书读取的属性有 gen_ai.operation.name、gen_ai.provider.name、gen_ai.request.model、gen_ai.response.model、gen_ai.response.finish_reasons、gen_ai.usage.input_tokens、gen_ai.usage.output_tokens、server.address 和 server.port。提供方的值为 openai,这正是第 2 章为本书自有的 span 在 openai 客户端上给出的值。
这份列表中显示出与本书自有 span 的一处差异:内容。没有任何属性保存提示词或回复,因为内容捕获处于关闭状态。捕获开关说明了该开关是什么,以及它的默认值。该包从客户端的基础 URL 中取得 server.port,当端口为隐含端口或为 443 时则省略它(在 1.3b0 中见 opentelemetry/instrumentation/genai/openai/utils.py)。
该调用生成两个指标,输出给出了它们的名称、单位和数据点数量。gen_ai.client.operation.duration 以秒为单位,有 1 个数据点。gen_ai.client.token.usage 以 token 为单位,有 2 个数据点,输入和输出各一个。这些数据点按 gen_ai.token.type 拆分,这是旧版约定对这种拆分的称呼。在 opentelemetry-semantic-conventions 0.66b2 中,它仍是一个已弃用的常量,v0.1.0 用两个 token 直方图取代了它。在本章中,“指标”和“直方图”仅指该包的 instrument。第 6 章对这两者都有定义。
流式调用会增加两个 instrument,即 gen_ai.client.operation.time_to_first_chunk 和 gen_ai.client.operation.time_per_output_chunk,以及一个 span 属性 gen_ai.response.time_to_first_chunk。本章的示例不使用流式传输,因此其输出不会打印其中任何一项。名称表列出了全部三个流式名称,它们是生成器从其构建的流式回复中观察到的,详见手工构造的 span 与插桩 span 的对照。
本章打印每个 instrument 的名称、单位和数据点数量,而不打印任何值,原因只有一个。该包的 span 时间取自脚本打过补丁的时钟,但它的时长和数据块 instrument 读取的是单调计时器,补丁对其不起作用。因此这些值是录制机器的真实耗时,每次运行都会变化。token 的值是固定的,因为它们就是回复的用量,并且以计数形式打印,使每个 instrument 的打印方式一致。
工作准则: 在测试中统计一个包的 span 和 instrument 的数量,并从其输出中读取每个名称、单位和数据点数量。不要对测试无法控制其计时器的 instrument 断言某个值,因为数量在每次运行中都成立,而值则不然。
手工编写的 span 与插桩生成的 span 对照
第 2 章已将本书自己的 span 与注册表逐一核对,本节用同样的方法衡量该软件包。这些名称取自软件包的输出,而它们与 v0.1.0 的对应关系是本书的判断:该判断只在生成器 examples/data/genai/build_names_map.py 中写了一次,并已与注册表核对。输出来自三处:一次已记录的调用;一段由生成器构造的流式回复,用来得到流式调用额外产生的名称;以及一次开启内容事件的调用,由它得到事件的名称。有一个条目来自软件包的源代码,而不是来自某次运行:gen_ai.usage.cache_read.input_tokens。只有当回复带有已缓存的提示词 token 时,软件包才会写入它,而已记录的回复都不带这类 token。
1"""The names the official package emits, set against the GenAI conventions v0.1.0 names this book uses. The table is2examples/lib/names_map.py, which examples/data/genai/build_names_map.py writes by running the package on the recorded3call, on a streamed reply it constructs (for the names a stream adds) and on a call with content events on (for the4event's name). The point rests on5the last printed count: five names differ from v0.1.0, and each one is named here. instrumented-chat-call checks that6the names a live call makes are in the same table."""7from lib.names_map import REGISTRY_VERSION, name_map # lib first: threads and seeds are fixed before anything else8from importlib.metadata import version910table = name_map()111213def status(name, targets):14 """Same when the name is its own v0.1.0 name, or the chat span's type; the two named exceptions get their own15 labels, and the rest are renamed, split or absent."""16 if targets == (name,) or (name == "chat {model}" and targets == ("gen_ai.client.inference",)):17 return "same"18 if name == "gen_ai.client.operation.duration":19 return "wrong instrument for inference"20 if name == "gen_ai.token.type":21 return "replaced by the two token histograms"22 if not targets:23 return "no v0.1.0 name"24 return "split into two" if len(targets) == 2 else "renamed"252627statuses = {name: status(name, targets) for name, targets in table.items()}28print("registry version:", REGISTRY_VERSION)29print("package version:", version("opentelemetry-instrumentation-genai-openai"))30print("names the package emits, in the table:", len(table))31print("names the same in v0.1.0:", sum(value == "same" for value in statuses.values()))32for name in sorted(table):33 if statuses[name] != "same":34 print(f"{statuses[name]}, {name}:", " and ".join(table[name]) or "none")35print("names that differ from v0.1.0:", sum(value != "same" for value in statuses.values()))36assert {name for name, value in statuses.items() if value != "same"} == {37 "gen_ai.client.operation.duration", "gen_ai.client.token.usage", "gen_ai.client.operation.time_to_first_chunk",38 "gen_ai.client.operation.time_per_output_chunk", "gen_ai.token.type"}
python diff-hand-and-instrumented.pyregistry version: 0.1.0
package version: 1.3b0
names the package emits, in the table: 25
names the same in v0.1.0: 20
wrong instrument for inference, gen_ai.client.operation.duration: gen_ai.client.inference.duration
renamed, gen_ai.client.operation.time_per_output_chunk: gen_ai.client.inference.time_per_output_chunk
renamed, gen_ai.client.operation.time_to_first_chunk: gen_ai.client.inference.time_to_first_chunk
split into two, gen_ai.client.token.usage: gen_ai.client.inference.operation.input_tokens and gen_ai.client.inference.operation.output_tokens
replaced by the two token histograms, gen_ai.token.type: none
names that differ from v0.1.0: 5
为什么被移除的名称会输出 none
+10 项证明来自手工编写的 span 与插桩生成的 span 对照,第 3 章再读一遍
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
输出中 gen_ai.token.type 所在的行以 none 结尾,而 gen_ai.client.token.usage 所在的行列出了两个名称。none 该如何解释?
原理何在
该表收录了软件包输出的 25 个名称。其中 20 个与 v0.1.0 相同,5 个不同。在不同的五个名称中,每一个都附有它在 v0.1.0 中变成的名称。
五处差异中有四处出现在指标里。注册表的指标文件规定,推理场景 SHOULD NOT 上报 gen_ai.client.operation.duration,并将推理时长命名为 gen_ai.client.inference.duration。token 指标是出现拆分的那一个:软件包写出的是一个带有 gen_ai.token.type 数据点属性的直方图,而注册表中有两个直方图,分别对应输入和输出。第五处是 gen_ai.token.type,这是旧版约定为这种拆分所用的名称,v0.1.0 用两个 token 直方图取代了它,因此依据注册表写成的查询无法用它选出软件包的输入数据点。
由于第 2 章已将本书自己的 span 与注册表核对过,此表中的每一处差异都属于该软件包。第 6 章和第 7 章在读取软件包的输出时使用的就是这张表。最先用到它的是第 6 章的 totals-from-metrics-not-spans 和第 7 章的 time-to-first-chunk。
工作准则: 维护一张软件包所输出名称的表,由其输出生成,并与注册表核对,通过它来读取该软件包的数据。查询表中没有的名称时,应当在测试中失败,就像本书的示例那样失败,而不是在生产环境中返回空结果。应在软件包版本变化时重新生成该表,而不是等到图表没有数据时才这样做。
这部分尚未翻译,因此以英文显示。
Three packages called openai
Three packages called openai instrument the client, and they differ on names and on content. Their names, as PyPI spells them, are opentelemetry-instrumentation-genai-openai, opentelemetry-instrumentation-openai-v2 and opentelemetry-instrumentation-openai. The first two are OpenTelemetry's. The third is Traceloop's. Only the first is installed here, at the version the pins hold. The other two are neither installed nor pinned, so this section reads their published wheels, at the versions and dates the table gives, and does not run them. Their versions are written as text for that reason: the pins file does not hold them, and no example prints them.
1"""Three packages called openai instrument the client, and they disagree on names and on content. Two are OpenTelemetry's2and differ in naming scheme; the third is Traceloop's and captures content by default. Only the first is installed in the3pinned environment, so the point rests on that one: its version is printed, and the module that reads its content switch4names the switch the table gives. The other two are not importable here, so their names and defaults are the source5readings the chapter cites, printed as wheel readings and not as runs."""6import lib # lib first: threads and seeds are fixed before anything else78import importlib.util9from importlib.metadata import version1011# Name as PyPI spells it; the module it imports; its project; the naming its source gives; its content switch and that12# switch's default, both from the source reading in notes/research/client-library-instrumentation.md (S2, S6, S7).13PACKAGES = (14 ("opentelemetry-instrumentation-genai-openai", "opentelemetry.instrumentation.genai.openai", "OpenTelemetry",15 "GenAI conventions, latest experimental, unconditionally", "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",16 "NO_CONTENT"),17 ("opentelemetry-instrumentation-openai-v2", "opentelemetry.instrumentation.openai_v2", "OpenTelemetry",18 "GenAI conventions v1.30.0 unless the experimental opt-in is set", "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",19 "false"),20 ("opentelemetry-instrumentation-openai", "opentelemetry.instrumentation.openai", "Traceloop",21 "its own names, from opentelemetry-semantic-conventions-ai 0.5.1", "TRACELOOP_TRACE_CONTENT", "true"),22)23installed = [row for row in PACKAGES if importlib.util.find_spec(row[1]) is not None]24assert [row[0] for row in installed] == ["opentelemetry-instrumentation-genai-openai"]25source = importlib.util.find_spec("opentelemetry.util.genai.utils").origin26assert installed[0][4] in open(source, encoding="utf-8").read() # the module that reads the switch names it2728print("packages importable in this environment:", len(installed))29print("installed version:", version(installed[0][0]))30for name, module, project, naming, switch, default in PACKAGES:31 print(f"{name}, evidence:", "installed source" if name == installed[0][0] else "wheel reading")32 print(f"{name}, project:", project)33 print(f"{name}, naming:", naming)34 print(f"{name}, content switch:", switch)35 print(f"{name}, content switch default:", default)
python three-openai-packages.pypackages importable in this environment: 1
installed version: 1.3b0
opentelemetry-instrumentation-genai-openai, evidence: installed source
opentelemetry-instrumentation-genai-openai, project: OpenTelemetry
opentelemetry-instrumentation-genai-openai, naming: GenAI conventions, latest experimental, unconditionally
opentelemetry-instrumentation-genai-openai, content switch: OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT
opentelemetry-instrumentation-genai-openai, content switch default: NO_CONTENT
opentelemetry-instrumentation-openai-v2, evidence: wheel reading
opentelemetry-instrumentation-openai-v2, project: OpenTelemetry
opentelemetry-instrumentation-openai-v2, naming: GenAI conventions v1.30.0 unless the experimental opt-in is set
opentelemetry-instrumentation-openai-v2, content switch: OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT
opentelemetry-instrumentation-openai-v2, content switch default: false
opentelemetry-instrumentation-openai, evidence: wheel reading
opentelemetry-instrumentation-openai, project: Traceloop
opentelemetry-instrumentation-openai, naming: its own names, from opentelemetry-semantic-conventions-ai 0.5.1
opentelemetry-instrumentation-openai, content switch: TRACELOOP_TRACE_CONTENT
opentelemetry-instrumentation-openai, content switch default: true
更正 Traceloop 内容开关的默认值
+10 项证明来自Three packages called openai,第 3 章再读一遍
建立在 span 的基础上,参见第1章,“一条消息,一条追踪”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 21 行把 Traceloop 包的内容开关默认值写成了错误的值。请修改该行,使其中打印的默认值与本节为该包给出的默认值一致。
原理何在
两个默认值为何不同
+10 项证明来自Three packages called openai,第 3 章再读一遍
建立在 semantic convention 的基础上,参见第2章,“Development 版本下的标准”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
输出中 Traceloop 一行的内容开关默认值为 true,而第一个包的默认值为 NO_CONTENT。这两个默认值为什么不同?
原理何在
The output gives each package's project, its naming, its content switch and that switch's default, and it says for each package whether those lines come from the installed source or from a wheel reading. The script checks that opentelemetry.util.genai.utils, the module that reads the switch, names the first package's switch.
| Package, version and date | Project | Names | Content switch, default |
|---|---|---|---|
opentelemetry-instrumentation-genai-openai, 1.3b0, 23 October 2026 |
OpenTelemetry | GenAI conventions, experimental set | OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT, NO_CONTENT |
opentelemetry-instrumentation-openai-v2, 2.4b0, 1 May 2026 |
OpenTelemetry | GenAI conventions v1.30.0, unless opted in | OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT, false |
opentelemetry-instrumentation-openai, 0.63.1, 16 November 2026 |
Traceloop | its own names, from opentelemetry-semantic-conventions-ai 0.5.1 |
TRACELOOP_TRACE_CONTENT, true |
The first package's page calls its version a pre-release, and its description says, "The latest experimental features may introduce breaking changes in future releases." The page also says that it uses the experimental GenAI conventions unconditionally, with no opt-in and no version named. The page names no conventions version, but the scope stamps https://opentelemetry.io/schemas/1.37.0, beside the book's 1.45.0. The table names no version of the conventions for the first package, because the package states none, and the earlier section measures it against v0.1.0, the version the book follows.
The second package keeps the older naming by default, and its switch has two meanings. On its legacy path the variable takes true, and the default is false. On its experimental path the variable takes span_only, event_only or span_and_event. Which meaning applies depends on the experimental opt-in, so a team reads the package's version and its opt-in together before it sets the variable. Both OpenTelemetry packages read the same variable, with different values, so a team that moves from the second and keeps true gets NO_CONTENT from the first, with only a warning in the log.
Traceloop's package names its span openai.chat, not the operation and the model, and it writes prompts and completions into the span by default. Its switch is TRACELOOP_TRACE_CONTENT, and it stays on unless someone sets it to false. Any value other than true, 1, yes or on turns it off, and a context value, override_enable_content_tracing, turns it back on. That is the reverse of the OpenTelemetry package, and it is the difference that matters most in this chapter. A team that adds Traceloop's package to a service that sends private text to a model has changed what its telemetry holds, and it has not set any variable to do so.
For this book we use the first package. It is the one the pins hold, and its names are the registry's, bar the five differences in the earlier section. We would choose the second only for a backend that reads its older names and nothing else, and the third only for the names its own project defines. Either choice needs its content switch read at the version pinned, with content capture off unless someone turned it on for a stated purpose.
Working rule: Read each instrumentation package's content switch and its default from that package's own source or documentation at the version you pin, and not from the spec alone. The defaults differ between packages, so a service that adds a second package changes what its telemetry can hold.
内容捕获开关
内容捕获是插桩用来记录提示词和回复本身的开关,除非另行设置,否则它处于关闭状态,即 NO_CONTENT。第一个包的默认值是 NO_CONTENT,第二个包的默认值是 false;Traceloop 的 0.63.1 wheel 则默认将其打开(Three packages called openai)。
GenAI 约定 v0.1.0 的 spans 页面规定,该开关必须(MUST)命名为 OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT,而第一个包违背了这条 MUST。它读取的是另一个变量 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT,并且在任何地方都不读取规范中的名称。下面的运行展示了这会造成什么后果。它先把规范中的名称设为 SPAN_ONLY 并发起一次调用;然后作为对照,用包自己的名称做同样的事,并统计每次调用的 span 所含的内容属性数量。
1"""The content switch: whether the official package's span holds the prompt and the reply. The package reads one variable,2and the spec's name for the same switch is read nowhere in the package. The point rests on three counts. With the spec's3name set to SPAN_ONLY, one call's span holds no content. With the package's own name set to SPAN_ONLY, a control call's4span holds two, so the count can rise and the package does read its name. And the package's parser gives NO_CONTENT when5its variable is unset and when it holds a value that is not a mode. The control records content for one call, and this6example prints only how many content attributes that span holds, never their values."""7import lib # lib first: threads and seeds are fixed before anything else89import os1011import opentelemetry.sdk.trace as sdk_trace12from opentelemetry.instrumentation.genai.openai import OpenAIInstrumentor13from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter14from opentelemetry.util.genai.utils import ContentCapturingMode, get_content_capturing_mode1516from lib.assistant import RELEASES17from lib.case import load_messages18from lib.clock import VirtualClock19from lib.http_replay import client, route_body20from lib.ids import SequentialIds21from lib.tracing import make_provider2223PACKAGE_VARIABLE = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"24SPEC_VARIABLE = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT"25print("the package reads:", PACKAGE_VARIABLE, "| the spec's name for the switch:", SPEC_VARIABLE)26print("values the package parses:", ", ".join(mode.name for mode in ContentCapturingMode))27os.environ.pop(PACKAGE_VARIABLE, None)28print("mode, package variable unset:", get_content_capturing_mode().name)29os.environ[PACKAGE_VARIABLE] = "not a mode" # the parser logs this and falls back, it does not raise30print("mode, value that is not a mode:", get_content_capturing_mode().name)31os.environ.pop(PACKAGE_VARIABLE)323334# Instrument afresh with the variable set to SPAN_ONLY, make one call, and print how many content attributes its span35# holds. The package reads its mode when it is instrumented, so the variable is set before that and removed after.36def content_attributes(variable: str, label: str, expected: int) -> None:37 os.environ[variable] = "SPAN_ONLY"38 clock = VirtualClock("2026-12-07")39 sdk_trace.time_ns = lambda: clock.advance(1_000_000) # virtual span times, as in instrumented-chat-call40 exporter = InMemorySpanExporter()41 provider = make_provider("ambrewick-assistant", RELEASES["r0"].service_version, "example", clock, SequentialIds(),42 exporter, "https://opentelemetry.io/schemas/1.45.0")43 instrumentor = OpenAIInstrumentor()44 instrumentor.instrument(tracer_provider=provider)45 client().chat.completions.create(**route_body(load_messages("2026-12-07")[0]))46 instrumentor.uninstrument()47 os.environ.pop(variable)48 call = exporter.get_finished_spans()[0]49 count = len([key for key in call.attributes if key.startswith(("gen_ai.input.messages", "gen_ai.output.messages"))])50 print(f"content attributes on the span, {label}:", count)51 assert count == expected525354content_attributes(SPEC_VARIABLE, "spec variable set", 0) # set, and read by nothing in the package55content_attributes(PACKAGE_VARIABLE, "package variable set", 2) # the control: the package's own name, one call
python capture-switch-names.pythe package reads: OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT | the spec's name for the switch: OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT
values the package parses: NO_CONTENT, SPAN_ONLY, EVENT_ONLY, SPAN_AND_EVENT
mode, package variable unset: NO_CONTENT
mode, value that is not a mode: NO_CONTENT
content attributes on the span, spec variable set: 0
content attributes on the span, package variable set: 2
自第 2026.11.2 版起由 openai3.56.0至3.57.0 更新。
让包读取小写的模式名称
+10 项证明第 29 行和第 30 行把包的变量设置为一个不是模式的值,并在某个标签下打印该模式。请修改这两行,使包的变量保存一个小写的模式名称,并使该行在标签 'mode, lower-case value:' 下打印,从而让示例打印出所示的输出。
原理何在
为什么规范中的名称不产生内容
+10 项证明输出显示,使用规范中的名称发起的调用包含 0 个内容属性,而使用包自身名称发起的调用包含 2 个。下列哪一项能解释第一个结果?
原理何在
关键在于两个计数之间的差异:使用规范中的名称时,内容属性为 0 个,而使用包自己的名称时为 2 个,并且没有任何信息报告这一差异。设置了规范名称的团队得到的输出,与完全没有设置时相同,这正是需要防范的故障。它悄无声息,看上去像是成功了,直到有人要查看某条提示词却发现一条也没有。
该包解析四个取值:NO_CONTENT、SPAN_ONLY、EVENT_ONLY 和 SPAN_AND_EVENT。该包在 1.3b0 的源码(opentelemetry/util/genai/utils.py)会先把取值转换为大写再匹配模式,因此匹配时不区分字母大小写。对于其他任何取值,它会记录一条警告并返回 NO_CONTENT。输出显示了这两种回退情形。包的变量未设置时,模式为 NO_CONTENT。取值不是模式时,模式为 NO_CONTENT。
第 12 章的捕获开启时泄露什么说明了四种模式各自写入和泄露的内容。这里有一次调用把内容记录下来作为对照,该示例只打印其 span 所含内容属性的数量。本章其他所有示例都在捕获关闭的状态下运行,本书一直保持关闭,直到第 12 章为了明确说明的目的才将其打开。
第二个开关 OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK 可以把内容上传到文件,并写入指向这些文件的引用。该包把这些引用写成 gen_ai.input.messages_ref 和 gen_ai.output.messages_ref,这是注册表中的名称;只有插桩的 docstring 把它们拼写成带点号的形式。本章没有任何运行会输出这两者,因为该钩子还需要设置 OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH,而这里没有任何运行设置它。第 12 章会介绍这个钩子。
工作准则: 按照包自身源码所读取的名称,在你锁定的版本上设置该包的内容变量,并用一项测试检查这个设置:测试断言,当且仅当变量指定了会记录内容的模式时,span 才包含内容。对于尚未说明捕获目的的服务,保持内容捕获关闭,并查明服务所加载的每个包的默认值。
另外两种命名方案
另有两种命名方案描述的事实与 GenAI 约定相同:一是 Arize 发布的 OpenInference,它自带 openinference-instrumentation-openai 包,是客户端的第四个包;二是 OpenLLMetry,即 Traceloop 那个包背后的项目。我们对两者都做说明,以便读者遇到它们的名称时知道其含义。本书不输出这两种名称。
OpenInference 的模块在其固定版本 0.1.46 中,用自己的常量来命名模型、提供方、词元计数、span 类型和消息。脚本读取这些常量,并把每个常量与同一事实对应的 GenAI 名称放在一起设置。
1"""OpenInference, a naming scheme the book does not emit, at its pinned version. Its module names the facts a model call2carries (the model, the provider, the token counts, the span kind, the messages) in its own words. The point rests on3the table: each name is one the pinned module defines, and each maps to a GenAI conventions name the book's registry or4its name table holds. The mapping is written here by hand, and checked against both."""5import lib # lib first: threads and seeds are fixed before anything else67from importlib.metadata import version89from openinference.semconv.trace import OpenInferenceLLMSystemValues, OpenInferenceSpanKindValues, SpanAttributes1011from lib import genai12from lib.names_map import NAMES1314# OpenInference's constant and the GenAI name for the same fact. OpenInference's span kind has no GenAI attribute: the15# operation name carries the same meaning, chat for a model call.16MAPPING = (17 (SpanAttributes.LLM_MODEL_NAME, "gen_ai.request.model"),18 (SpanAttributes.LLM_SYSTEM, "gen_ai.provider.name"),19 (SpanAttributes.LLM_TOKEN_COUNT_PROMPT, "gen_ai.usage.input_tokens"),20 (SpanAttributes.LLM_TOKEN_COUNT_COMPLETION, "gen_ai.usage.output_tokens"),21 (SpanAttributes.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ, "gen_ai.usage.cache_read.input_tokens"),22 (SpanAttributes.OPENINFERENCE_SPAN_KIND, "gen_ai.operation.name"),23 (SpanAttributes.LLM_INPUT_MESSAGES, "gen_ai.input.messages"),24 (SpanAttributes.LLM_OUTPUT_MESSAGES, "gen_ai.output.messages"),25)26known = set(genai.ATTR) | {name for names in NAMES.values() for name in names}27print("openinference-semantic-conventions version:", version("openinference-semantic-conventions"))28for openinference, conventions in MAPPING:29 print(f"{openinference} -> {conventions}")30 assert conventions in known31print("span kind for a model call:", OpenInferenceSpanKindValues.LLM.value)32print(f"{SpanAttributes.LLM_SYSTEM} for an OpenAI client:", OpenInferenceLLMSystemValues.OPENAI.value)
python openinference-mapping.pyopeninference-semantic-conventions version: 0.1.46
llm.model_name -> gen_ai.request.model
llm.system -> gen_ai.provider.name
llm.token_count.prompt -> gen_ai.usage.input_tokens
llm.token_count.completion -> gen_ai.usage.output_tokens
llm.token_count.prompt_details.cache_read -> gen_ai.usage.cache_read.input_tokens
openinference.span.kind -> gen_ai.operation.name
llm.input_messages -> gen_ai.input.messages
llm.output_messages -> gen_ai.output.messages
span kind for a model call: LLM
llm.system for an OpenAI client: openai
该示例把每个 OpenInference 名称与对应的 GenAI 名称并排打印,运行时还会对照名称表检查每一对,因此,如果某个常量在下次更新固定版本时发生变动,运行就会失败。词元计数是读者最先遇到的几组对应:llm.token_count.prompt 对应 gen_ai.usage.input_tokens,llm.token_count.completion 对应 gen_ai.usage.output_tokens。
脚本断言每个 GenAI 名称都在本书的名称表中,因此,如果某个映射指向了表中不存在的名称,运行就会失败。OpenInference 的 span 类型在 GenAI 中没有对应的专属属性。输出记录了一次模型调用在 OpenInference 中是 LLM,而在 GenAI 名称中,由操作名称承载同样的含义,即 chat。其 OpenAI 提供方的取值是 openai,与第一个 OpenTelemetry 包为 openai 客户端写入的字符串相同。
OpenLLMetry 的名称来自 opentelemetry-semantic-conventions-ai,版本为 0.5.1,发布于 2026 年 3 月 26 日,Traceloop 的 0.63.1 包使用该版本。关于这些读数的注意事项见三个名为 openai 的包。OpenLLMetry 的名称中有四个在注册表里有承担相同作用的名称:gen_ai.client.operation.duration 对应 gen_ai.client.inference.duration,gen_ai.client.token.usage 对应输入与输出两个直方图,gen_ai.usage.cache_creation.input_tokens 对应 gen_ai.usage.cache_write.input_tokens,gen_ai.usage.reasoning_tokens 对应 gen_ai.usage.reasoning.output_tokens。
我们建议全书统一使用 OpenTelemetry 的名称。第 5 章其他方案的做法所述的后端表示它们接收这些名称,每项说法在该处都附有版本和日期。只有当你运行的后端只读取另一种方案、不读取其他方案时,才因这一理由选择那种方案。不要在同一条 trace 中混用方案。查询 gen_ai.usage.input_tokens 时,找不到写入 llm.token_count.prompt 的 span,因此合计结果会偏小,而且没有任何错误提示。
工作准则: 把每种方案的名称一次性映射到注册表的名称上,映射写成代码中的一张表,表中没有的名称一律使运行失败,上面的映射示例就是这样做的。在发送第一个 span 之前,为一项服务的 span 选定一种方案,并让其他方案的名称不进入它的 trace。
生产环境中的问题
该包在生产环境中会出现四类问题。
- 预发布版本。 第一个包处于预发布版本,其页面警告说,它的实验性功能可能在不另行通知的情况下变更。固定版本只锁定一个版本。升级的团队会采用下一个版本写出的任何名称,因此必须重新生成名称表,并且当运行遇到表中没有的名称时必须失败。
- 开关放错位置。 规范中的名称对该包不起任何作用,而且没有任何错误提示。相反的错误更为严重。团队若加入 Traceloop 的包却什么都不设置,就等于打开了提示内容的捕获,因为在其 0.63.1 的 wheel 中,该包的默认值是开启,而且即使变量为
false,上下文覆盖仍可以将其重新打开。 - 仪表盘使用注册表中的名称。 若图表从该包读取
gen_ai.client.inference.duration,将查不到任何数据点,因为该包写出的是gen_ai.client.operation.duration。前面的一节列出了每个不同的名称。 - 同一客户端上有两个包。 若服务为同一个客户端加载了第二个插桩包,则每次调用的 span 可能会以两套名称各写入一次。此处没有任何示例同时加载两个包,因此没有演示这一情形;按每次调用统计 span 数量的测试可以将其显现出来。
本章做出的决定
软件包使用的名称会落后于标准,下面每项选择都说明了本书如何应对这一点:
- 模型调用由固定在 1.3b0 版本的 OpenTelemetry 软件包封装,本书自己的 span 只封装该软件包看不到的工作。
- 该软件包写法与注册表不同的五个名称,在一张生成的表中一次性完成映射,本书其余部分都通过这张表来读取该软件包的输出。
- 本章的所有示例中,内容捕获均处于关闭状态,只有一个对照示例除外:它为一次调用记录内容,并且只打印内容的数量。第 12 章会有意将其开启,并说明它会泄露什么。
- 指标只按名称、单位和数据点数量打印,从不按值打印,因为其中的时长仪表使用的是真实时间。
- 本书使用 OpenTelemetry 的名称,因为第 5 章中的后端都声明可以接收这些名称,所以更换后端只需要修改设置,而不必修改 span。
- 三个软件包的名称均按原样给出,只运行第一个。另外两个是对 wheel 包的读取,如关于三个软件包的一节所述。
工作准则: 将插桩软件包固定在确切的版本,根据它自身的输出生成其名称表,并先在该版本的源代码中查看它的内容开关,再信任 span 中所保存的内容。软件包一旦更改其名称或默认值,你的追踪数据所保存的内容也会随之改变,而它的版本及其作用域的 schema URL 就是你能得到的变化信号。
本章,在本版次中
版次 2026.11.2示例于 2026年11月23日 通过5 of 5个示例 in this chapter pass
译自英文版图书,版次 2026.11.2。