按标准为 span 命名

阅读约 43分钟,8节中含5个示例。

版次 2026.11.2 示例于 2026年11月23日 通过 80个示例中有80个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.2。 阅读原文

实验室

通过动手实践学习本章

完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。

完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。

正在查找您的 Lab…

在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。

读完本章,你可以为助手追踪记录中的每个 span 指定 OpenTelemetry 的 GenAI 约定对其步骤所要求的名称、类型和属性。你可以说明某个 span 由哪个软件生成,其名称遵循哪个模式版本,还可以运行一项检查,在 span 偏离注册表时报告失败。

Ambrewick 的值班工程师运行着本书为其构建追踪记录的助手(一条消息,一条追踪),他们希望这些追踪记录能进入自己已在使用的工具。这些工具只认一套词汇:约定为模型调用、检索、工具运行和智能体的一轮交互所给出的名称。第 1 章的名称在这些工具里没有任何意义。验证器是本章要构建的检查,它把每个 span 与注册表的规则作比较。对消息 809(一个带有检索的设备问题)运行时,它的 4 个 span 产生了 4 条发现,每个 span 一条,每条都指出该 span 没有已知的 span 类型。SDK 没有报告其中任何一条,因为 SDK 接受任何名称。因此,本章为每个 span 指定标准的名称和类型,记录它由谁生成,并构建保证名称正确的检查。随后第 3 章将以这些名称为尺度,衡量一个客户端库生成的 span。

Development 版本下的标准

后端按名称回答关于某个 span 的问题。比如“本周模型调用耗时多久”这样的问题,只有在所有后端对哪些 span 是模型调用达成一致时,才会有唯一的答案,而标准就是这种一致。语义约定(semantic convention)是对 span、属性或指标公开发布的名称、类型和含义,使任何后端都以相同方式解读同一个名称。这里的标准是 OpenTelemetry 的 GenAI 语义约定。

GenAI 的名称最初位于 OpenTelemetry 的核心语义约定仓库。该仓库在 1.42.0 版本中弃用了以 gen_ai 为前缀的名称,这些名称随后迁移到了一个独立的仓库(变更日志)。本书遵循该仓库的首个独立发布版本,即 GenAI 约定 0.1.0 版(变更日志)。

约定有两种形式:供人阅读的页面,以及注册表(registry)。注册表是一个 YAML 模型,描述 span 类型、它们的种类和属性,程序可以读取。本书的校验器读取固定版本的注册表,因此它检查的名称就是注册表所列出的名称。

GenAI 约定 0.1.0 版的每一个页面都处于 Development 状态:其中的名称在任何发布版本中都可能变化。规范为自身的组件定义了 Development,其状态页面对这类组件的说明是:“The component MAY be removed without prior notice. The component SHOULD NOT be used in production.”(状态页面)。GenAI 页面带有相同的状态,其变更日志也显示了名称的变动。首个独立发布版本把推理 span类型的名称从 gen_ai.inference.client 改为 gen_ai.client.inference。本书中的名称遵循该发布版本,因此后续版本可能会对它们重命名。

**工作准则:**在你发布的每个名称旁标明约定的版本。基于 Development 名称构建的仪表盘,需要一项在名称变化时运行的检查。

各步骤的 span 类型

注册表把 span 分为若干 span 类型,每种类型都有名称模式、一个 span kind 和必需的属性。第 1 章的各个步骤归入其中四种。推理 span 是对生成式模型的一次客户端调用的 span,模型或者回答提示,或者请求调用工具。检索 span 是应用的检索步骤运行一次的 span,该步骤返回与查询相关的文档。工具执行 span 是一个工具运行一次的 span,以该工具命名。智能体调用 span 是一次智能体调用的 span。本书的智能体运行在助手的进程内,所以它的 span 属于进程内类型,这一类型也涵盖工作流。远程智能体的 span 是它自己类型的 CLIENT span。路由步骤和回答步骤是模型调用,检索步骤是一次搜索,工具运行就是工具的运行,而每条消息的根 span 对应一次智能体运行。

Span 类型 名称模式 Kind 操作名称
推理 {operation} {model} CLIENT,进程内时为 INTERNAL chat
检索 {operation} INTERNAL retrieval
工具执行 execute_tool {tool} INTERNAL execute_tool
智能体调用 invoke_agent {agent} 进程内为 INTERNAL;远程智能体为 CLIENT invoke_agent
inference-span-names.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通过
"""Print the span name each step gets from the assistant, beside the registry's pattern for that span type. The names arethe spans', the patterns are the registry's, and each assert checks one span's name against its pattern.The point rests on the four name lines: the inference, tool and agent names from message 11159 (a route, an answer, atool call and a second answer), and the retrieval name from message 809."""from lib.assistant import Assistantfrom lib.bm25 import Retrieverfrom lib.case import load_articles, load_messages, load_tool_durationsfrom lib.clock import VirtualClockfrom lib.dayrun import DAY, RECORDING, RELEASEfrom lib.export import spans_to_rowsfrom lib.genai import REGISTRY_VERSION, SCHEMA_URL, SPAN_OPERATIONS, SPAN_TYPESfrom lib.ids import SequentialIdsfrom lib.replay import Replay, ReplayContactsfrom lib.tools import Toolsfrom lib.tracing import make_providerfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterreplay = Replay(RECORDING)retriever, tools = Retriever(load_articles(), RELEASE.top_k), Tools(load_tool_durations(), ReplayContacts(replay))rows = {}for message in (m for m in load_messages(DAY) if m.message_id in ("809", "11159")):    clock, exporter = VirtualClock(DAY, start_ns=message.arrival_ns), InMemorySpanExporter()  # one exporter per message    tracer = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", clock, SequentialIds(),                           exporter, SCHEMA_URL).get_tracer("ambrewick.assistant", schema_url=SCHEMA_URL)    Assistant(replay, retriever, tools, clock, tracer, RELEASE).handle(message)    rows[message.message_id] = spans_to_rows(exporter)agent = next(row for row in rows["11159"] if row["parent_span_id"] is None)  # the root is the agent's invocationinference = next(row for row in rows["11159"] if row["attributes"].get("gen_ai.operation.name") == "chat")tool = next(row for row in rows["11159"] if row["attributes"].get("gen_ai.operation.name") == "execute_tool")retrieval = next(row for row in rows["809"] if row["attributes"].get("gen_ai.operation.name") == "retrieval")print("GenAI conventions version:", REGISTRY_VERSION)print("inference span name:", inference["name"])print("retrieval span name:", retrieval["name"])print("tool span name:", tool["name"])print("agent span name:", agent["name"])print("inference provider name:", inference["attributes"]["gen_ai.provider.name"])print("inference prompt name:", inference["attributes"]["gen_ai.prompt.name"])print("inference prompt version:", inference["attributes"]["gen_ai.prompt.version"])# Model spans are `{operation} {model}`, retrieval is its operation alone, tools are `execute_tool {tool}`, the agent is# `invoke_agent {agent}`. Each assert checks one span against its pattern.assert inference["name"] == f"chat {RELEASE.model}" and retrieval["name"] == "retrieval"assert tool["name"] == f"execute_tool {tool['attributes']['gen_ai.tool.name']}"assert agent["name"] == f"invoke_agent {agent['attributes']['gen_ai.agent.name']}"for span_type in sorted(SPAN_OPERATIONS):  # the operation names the registry defines, per span type    print(f"operation names, {span_type}:", ", ".join(SPAN_OPERATIONS[span_type]))for span_type in sorted(SPAN_TYPES):  # the attributes the validator requires, per span type    print(f"required attributes, {span_type}:", len(SPAN_TYPES[span_type]["required"]))
输出python inference-span-names.py
GenAI conventions version: 0.1.0
inference span name: chat qwen3-4b-instruct-2507
retrieval span name: retrieval
tool span name: execute_tool remove_item
agent span name: invoke_agent ambrewick-assistant
inference provider name: openai
inference prompt name: ambrewick.route
inference prompt version: p1
operation names, gen_ai.client.inference: chat, generate_content, realtime_inference, text_completion
operation names, gen_ai.execute_tool: execute_tool
operation names, gen_ai.invoke_agent.internal: invoke_agent
operation names, gen_ai.retrieval: retrieval
required attributes, gen_ai.client.inference: 2
required attributes, gen_ai.execute_tool: 2
required attributes, gen_ai.invoke_agent.internal: 1
required attributes, gen_ai.retrieval: 1
required attributes, mcp.client: 1
required attributes, mcp.server: 1
练习 2.1

用模型名而不是提供方来命名模型 span

+10 项证明

第 42 行用提供方属性而不是模型来命名模型 span。请修改第 42 行,使模型 span 按其注册表模式进行检查,并使用本次运行所用的模型。

print("inference prompt version:", inference["attributes"]["gen_ai.prompt.version"])# Model spans are `{operation} {model}`, retrieval is its operation alone, tools are `execute_tool {tool}`, the agent is# `invoke_agent {agent}`. Each assert checks one span against its pattern.assert tool["name"] == f"execute_tool {tool['attributes']['gen_ai.tool.name']}"assert agent["name"] == f"invoke_agent {agent['attributes']['gen_ai.agent.name']}"for span_type in sorted(SPAN_OPERATIONS):  # the operation names the registry defines, per span type
运行于 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3
练习 2.2

编写工具名称和智能体名称的检查

+10 项证明

在示例中,第 43 行和第 44 行是空白的。请编写两条断言,分别对照注册表中的命名模式,检查工具跨度的名称和智能体跨度的名称,使用属性 gen_ai.tool.name 和 gen_ai.agent.name。

# Model spans are `{operation} {model}`, retrieval is its operation alone, tools are `execute_tool {tool}`, the agent is# `invoke_agent {agent}`. Each assert checks one span against its pattern.assert inference["name"] == f"chat {RELEASE.model}" and retrieval["name"] == "retrieval"for span_type in sorted(SPAN_OPERATIONS):  # the operation names the registry defines, per span type    print(f"operation names, {span_type}:", ", ".join(SPAN_OPERATIONS[span_type]))for span_type in sorted(SPAN_TYPES):  # the attributes the validator requires, per span type
运行于 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3
练习 2.3

为什么检索跨度的名称中没有索引

+10 项证明

该示例打印出“retrieval span name: retrieval”,尽管搜索是针对知识库运行的。下列哪一项能解释名称中为何没有索引?

为什么检索跨度的名称中没有索引:选出正确的解释
运行于 Python 3.13.16

模型 span 的变化最大。它的名称由操作、一个空格和模型名称组成,因此读者浏览追踪时可以看出每次调用由哪个模型作答。消息 11159 是一个带一次工具调用的列表请求,它的第一次模型调用名为 chat qwen3-4b-instruct-2507。注册表为推理 span 上的 gen_ai.operation.name 给出了一份众所周知的取值列表,列表之外也可以使用自定义值(注册表属性)。验证器通过本书自建的映射把每个值对应到一种 span 类型,该映射给推理类型的值是 chat, generate_content, realtime_inference, text_completion。助手在每次调用中写入的是 chat。该示例针对本次运行所用的操作和模型,断言模型 span 的名称,并根据工具 span 和智能体 span 携带的属性构造工具名称和智能体名称,因此任何一处出现偏差,运行都会失败。

检索 span 仅以其操作命名,即 retrieval。注册表的模式没有为被搜索的索引留出位置,所以知识库的名称不出现在 span 名称中。工具运行以其工具命名,即 execute_tool remove_item,这是消息 11159 中删除一个条目的列表工具的那次运行。根 span 命名为 invoke_agent ambrewick-assistant,它取代了第 1 章的 message span。我们保留 invoke_agent 而不用 invoke_workflow,因为由模型选择路由,并决定是否调用工具。模型通过工具调用来驱动控制流,这正是注册表中智能体类型所描述的情形。

注册表留有余地的一个属性是提供方。在本书中,推理 span 的 gen_ai.provider.name 取值为 openai,这个取值出自我们的判断。注册表中该属性的众所周知取值不包含 llama.cpp,列表中没有的提供方可以采用自定义值(注册表)。该属性的通用说明写道,它“SHOULD be set based on the instrumentation's best knowledge and may differ from the actual upstream provider”(客户端推理)。我们记录 openai,是因为 Ambrewick 的客户端以 OpenAI 的 API 与其端点通信,而官方软件包为该调用记录的是 openai,第 3 章会展示这一点。模型以其他方式提供服务的读者,应按同一规则选择取值,并说明这一点。

在助手产生的 span 中,回退 span 是唯一一个注册表没有给出名称的。本书保留它,验证器会标记它,而验证一节说明了为什么这个标记是正确的结果。

**工作准则:**按注册表的模式为每个 span 命名,而不是按产生它的函数命名,操作名称取自注册表中众所周知的取值。对于你所运行的内容,若注册表没有给出取值,就使用客户端及其官方插桩会写入的值,并说明这是一种判断。

span 的类型取决于进程

span 的类型说明其工作在何处运行:CLIENT 表示从进程发出的调用,SERVER 表示接收到的调用,INTERNAL 表示进程内部的工作(另有 PRODUCER 和 CONSUMER 两种,标记交给队列的工作)。模型调用是其中最难判断的情形。注册表写道:“当被插桩的 GenAI 系统通常运行在与其客户端不同的进程中,或者 GenAI 调用通过 HTTP 等已插桩的协议发生时,建议使用 CLIENT 类型”(client inference)。端点之后的模型要通过离开助手所在进程的调用来访问,因此它的 span 是 CLIENT。注册表也允许对运行在同一进程内的模型使用 INTERNAL,所以类型才需要判断。本书用 span 自身可以体现的一项检验来应用这条规则:调用是否指明了服务器。指明服务器的调用是 CLIENT,没有指明服务器的调用可以是 INTERNAL。

span-kinds-by-process.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通过
"""Give one model call two kinds: CLIENT when the model sits behind an endpoint, as the trace shows it, and INTERNALwhen the same assistant runs the model in process. Then run the validator on both.The point rests on the two model-call kind lines and on the zero findings: the registry allows INTERNAL for anin-process model (it says MAY), and the validator accepts it when the call names no server. An endpoint span markedINTERNAL is flagged, because it names one."""from lib.dayrun import DAY, RECORDING, run_day_tracedfrom lib.genai import REGISTRY_VERSION, validatefrom lib.replay import Replayclass InProcess:    """The recorded model, run as if it shared the assistant's process: the same answers, and no endpoint."""    in_process = True    def __init__(self, replay):        self._replay = replay    def reply(self, request):        return self._replay.reply(request)rows = run_day_traced(DAY, ["809"], live=False).spans  # a devices message: a route and an answer call, behind an endpointlocal = run_day_traced(DAY, ["809"], backend=InProcess(Replay(RECORDING)), live=False).spans  # the same model in processendpoint = next(row for row in rows if row["name"].startswith("chat "))in_process = next(row for row in local if row["name"].startswith("chat "))retrieval = next(row for row in rows if row["name"] == "retrieval")root = next(row for row in rows if row["parent_span_id"] is None)marked = dict(endpoint, kind="INTERNAL")  # the endpoint's span, wrongly marked as in processprint("GenAI conventions version:", REGISTRY_VERSION)print("model call kind, behind an endpoint:", endpoint["kind"])print("model call kind, in process:", in_process["kind"])address, port = endpoint["attributes"]["server.address"], endpoint["attributes"]["server.port"]print("server the endpoint span names:", f"{address}:{port}")print("findings on the in-process span:", len(validate(in_process)))print("findings on the endpoint span marked INTERNAL:", len(validate(marked)))print("retrieval span kind:", retrieval["kind"])print("agent span kind:", root["kind"])assert validate(endpoint) == [] and validate(in_process) == []  # both kinds are the registry'sassert "server.address" not in in_process["attributes"]  # an in-process model names no serverassert len(validate(marked)) == 1 and "kind is INTERNAL" in validate(marked)[0]assert validate(retrieval) == [] and validate(root) == []  # INTERNAL is the registry's kind for these two types
输出python span-kinds-by-process.py
GenAI conventions version: 0.1.0
model call kind, behind an endpoint: CLIENT
model call kind, in process: INTERNAL
server the endpoint span names: localhost:8000
findings on the in-process span: 0
findings on the endpoint span marked INTERNAL: 1
retrieval span kind: INTERNAL
agent span kind: INTERNAL

把消息 809 的模型调用以两种方式各运行一次,可以看到这条规则的作用。消息 809 是一个关于设备的问题,包含一次路由调用和一次回答调用。在端点之后,span 的类型是 CLIENT;同样的调用在进程内运行,则得到 INTERNAL。端点的 span 指明了服务器,进程内的 span 没有指明。验证器对进程内的 span 报告 0 条发现,示例对此作了断言。若把端点的 span 标记为 INTERNAL,它仍然指明服务器,验证器对它报告 1 条发现。示例断言这条发现的文本会指明类型 kind is INTERNAL,并且只打印其数量。这条发现正是该规则所要避免的错误。

本书中的 dev-day 追踪全部是 CLIENT,因为所记录的模型调用都是通过端点提供的。进程内的情形是由助手自己的代码调用同一个模型,本书只在这个示例中运行它。读者若把模型移入进程,应预期类型随之改变;若 span 仍然指明服务器,则应预期验证器会指出这一点。

检索 span 和智能体 span 都是 INTERNAL,示例对二者分别作了断言,因为它们的工作在助手内部运行。打印出的类型中,检索 span 为 INTERNAL,智能体 span 为 INTERNAL。注册表给出了这两种类型(registry),验证器会对其进行检查。

工作准则: 只要调用发往服务器,即使该服务器在同一台机器上,也应为模型 span 设置 CLIENT。只有当模型运行在你的进程中且 span 没有指明服务器时,才设置 INTERNAL,并让验证器检查你设置的每一个类型。

这部分尚未翻译,因此以英文显示。

Which attributes a span must carry

A name tells a backend what a span is. The requirement level tells it which attributes that span must carry. A requirement level says when an attribute must appear: required, conditionally required, recommended or opt-in (requirement levels). A required attribute appears on every span of its type. A conditionally required one appears when its condition holds, and the registry writes the condition beside it. A recommended attribute says what a good span carries, and an opt-in one appears only when something switches it on.

The registry also says which attributes each span type must carry. The book's module, lib.genai, holds every requirement level from the registry, so the requirement levels and kinds that the validator checks are the registry's, not a list someone typed. The validator checks the kind and the required attributes, and nothing else, so a span can pass it and still lack what the registry asks for in a conditional case. The validator's counts, as the inference-span-names example prints them, show how many each span type requires: 2 on an inference span, 2 on a tool-execution span, 1 on the retrieval span and 1 on the agent span. Its required attributes are its operation name and its provider name, so the provider judgement is not optional. A span without either one fails the check.

Opt-in attributes are the ones to watch for privacy. The message contents of a model call are opt-in, so the book's spans carry none of them unless a switch asks for them, and chapter 3 says what that switch does.

Conditional requirements are the ones the validator does not read. gen_ai.prompt.version is conditionally required on the inference span when the span carries gen_ai.prompt.name and a version is available. gen_ai.prompt.name is conditionally required when a named prompt template is used (registry). The assistant's prompts are named and versioned, so its inference spans carry both: ambrewick.route and p1 on the route call in message 11159. Chapter 10 queries that pair to tell releases apart. The validator reads only required attributes, so it would not report a span that lacks either one, and a gap in a conditional attribute is a gap it will not report.

Working rule: Read a span's requirement levels before you read its name. A missing required attribute is a defect in the span. A missing conditionally required attribute is a defect only when its condition holds, so read the condition in the registry before you file it.

谁生成了这个跨度

跨度说明它测量了什么,另有两处说明是谁测量的:资源和插桩作用域。插桩作用域给生成跨度的代码单元命名,通常是一个插桩库,这里则是助手自己的模块。模式 URL 指向一份已发布的遥测模式,即遥测数据所遵循的某个语义约定版本。正文从不直接写出模式 URL,这里的每一个 URL 都由对应的示例打印出来。

资源带有三个由本书自行设置的属性。service.name 的值是 ambrewick-assistant。service.version 的值是 1.0.0,它标记发布版本,第 10 章会读取它,以便按版本拆分追踪。service.instance.id 的值是 dev-day-replay。重放会自行设置实例 ID,因此重新运行时指向同一个实例,其追踪可以在各次运行之间比较。进程重启后,只有事先设置过实例 ID,它才会保持不变;若要用查询跟踪同一个实例跨越重启的过程,就需要这个 ID 保持不变。

resource-and-schema.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通过
"""Print the resource and the instrumentation scope of the renamed spans, with the schema URL each one carries, besidechapter 1's stamp.The point rests on the schema lines: chapter 1's resource said 1.44.0, the renamed spans say 1.45.0, and the SDK'sconstants have no 1.45.0 schema, which the assert checks. The book takes that URL from the registry's manifest(genai.SCHEMA_URL), and make_provider puts it on the tracer as well as the resource."""from lib.dayrun import RELEASEfrom lib.genai import SCHEMA_URLfrom lib.ids import SequentialIdsfrom lib.tracing import make_provider, spanfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterfrom opentelemetry.semconv.schemas import SchemasCHAPTER_1_SCHEMA = "https://opentelemetry.io/schemas/1.44.0"def version_key(url):    """Sort key for a schema URL: its version as numbers, so 1.9 sorts before 1.44."""    return tuple(int(part) for part in url.rsplit("/", 1)[1].split("."))exporter = InMemorySpanExporter()provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", None, SequentialIds(),                         exporter)tracer = provider.get_tracer("ambrewick.assistant")  # no schema given: the tracer carries the provider'sspan(tracer, "resource probe", 1, 2)  # one ended span, so the scope's schema can be read from itscope = exporter.get_finished_spans()[0].instrumentation_scopechapter_1 = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", None, SequentialIds(),                          InMemorySpanExporter(), CHAPTER_1_SCHEMA)  # the resource chapter 1 built, read back from itknown = {schema.value for schema in Schemas}  # what opentelemetry-semantic-conventions 0.66b2 can stampprint("chapter 1's resource schema URL:", chapter_1.resource.schema_url)print("renamed spans' resource schema URL:", provider.resource.schema_url)print("renamed spans' scope schema URL:", scope.schema_url)print("instrumentation scope name:", scope.name)print("highest schema in the SDK's constants:", max(known, key=version_key))print("service.name:", provider.resource.attributes["service.name"])print("service.version:", provider.resource.attributes["service.version"])print("service.instance.id:", provider.resource.attributes["service.instance.id"])assert SCHEMA_URL not in known  # the constants stop at 1.44.0, so the book takes its 1.45.0 from the registryassert provider.resource.schema_url == scope.schema_url == SCHEMA_URLassert provider.resource.attributes["service.instance.id"] == "dev-day-replay"  # set, not drawn at random
输出python resource-and-schema.py
chapter 1's resource schema URL: https://opentelemetry.io/schemas/1.44.0
renamed spans' resource schema URL: https://opentelemetry.io/schemas/1.45.0
renamed spans' scope schema URL: https://opentelemetry.io/schemas/1.45.0
instrumentation scope name: ambrewick.assistant
highest schema in the SDK's constants: https://opentelemetry.io/schemas/1.44.0
service.name: ambrewick-assistant
service.version: 1.0.0
service.instance.id: dev-day-replay
练习 2.4

为什么模式 URL 取自注册表

+10 项证明

输出为重命名后的跨度(span)给出了一个模式 URL,它比 SDK 常量中最高的那个更新。为什么该示例从注册表的清单中取得这个 URL,而不是从这些常量中取得?

为什么模式 URL 取自注册表:选出正确的解释
运行于 Python 3.13.16

模式 URL 在本章中发生了变化,示例会打印出前后两个值。第 1 章的资源使用的是 https://opentelemetry.io/schemas/1.44.0。那是被固定版本的 semantic-conventions 包所含的最新模式 0.66b2,其最高模式为 https://opentelemetry.io/schemas/1.44.0。第 1 章的命名没有遵循任何约定,所以那个戳记并没有描述本书跨度所表达的任何内容。重命名后的跨度加盖的是 https://opentelemetry.io/schemas/1.45.0,这是 GenAI 约定 v0.1.0 所依赖的核心语义约定版本。GenAI 约定在 v0.1.0 时并不发布自己的模式 URL。核心约定在 1.42.0 中弃用了其 gen_ai.* 名称,因为它们已迁入各自的仓库。因此,戳记说明的是资源的 service.* 名称遵循哪一个核心版本,而 GenAI 的版本则随校验一并给出,即 0.1.0。本书生成的模块从注册表的清单中取得该 URL,示例则断言 SDK 的常量中不包含它。这些常量止于它们自身的版本。在 service.* 属性中,该 URL 所指的版本只弃用了 service.peer.name 和 service.peer.namespace(变更日志),所以资源所设置的那三个属性在两个 URL 下含义相同。

重命名后的跨度,其插桩作用域是 ambrewick.assistant,模式 URL 与资源的相同,示例对此做了断言。官方客户端库则写入它自己的作用域。

工作准则: 请自行在资源上设置 service.name 和 service.version,并为 service.instance.id 赋予每个实例唯一的值,生产环境一节对此有说明。然后,把你的约定所依赖的核心版本的模式 URL 交给追踪器,该 URL 应取自注册表的清单,而不是 SDK 的常量,因为后者可能落后于约定。请把 GenAI 约定的版本与校验器一并固定,因为在 v0.1.0 时它们没有可供加盖的模式 URL。

对照注册表进行验证

名称是对注册表作出的一项声明,而验证器使这项声明可以被检验。它从 gen_ai.operation.name 中找出每个跨度的类型;对于 MCP 跨度,则从其方法中找出。MCP 是 Model Context Protocol,即工具服务器所使用的协议。随后,验证器依据注册表的规则检查该跨度的种类和必需属性。若找不到某个跨度的类型,它会给出一条说明此事的发现项,而且每条发现项都会指明所属的跨度,因此输出读起来就是一份待修复的清单。

验证器无法为第 1 章的跨度命名,因为这些跨度不带 gen_ai.operation.name,而验证器正是读取这个属性来确定跨度的类型。消息 809 的 4 个跨度分别是 message、route、retrieve 和 answer,检查为每个跨度各输出一条发现项:no known span type for this row。这条发现项给出了原因。根节点改名之后,message 变为 invoke_agent ambrewick-assistant,该跨度便按其自身的类型接受检查。

validate-the-spans.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通过
"""Run the validator over chapter 1's rough spans for message 809: every span fails, because none names a registry spantype.The point rests on the count of findings, one per span, and on the text of each: "no known span type" means the spancarries neither `gen_ai.operation.name` nor an MCP method, which is how the validator finds a registry span's type."""from lib.dayrun import RELEASE, run_dev_dayfrom lib.export import spans_to_rowsfrom lib.genai import REGISTRY_VERSION, validatefrom lib.ids import SequentialIdsfrom lib.report import fmt_intfrom lib.tracing import make_provider, spanfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter# Chapter 1 stamped this schema; kept so the spans are the ones chapter 1 printed.CHAPTER_1_SCHEMA = "https://opentelemetry.io/schemas/1.44.0"(run,) = run_dev_day(["809"])  # message 809: a route call, a retrieval, and an answer calloutcome = run.outcomeexporter = InMemorySpanExporter()provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),                         exporter, CHAPTER_1_SCHEMA)tracer = provider.get_tracer("ambrewick.assistant")# Chapter 1's names: the root is the message, each step is named by its step, and no kind is set (INTERNAL).root = span(tracer, "message", run.arrived_ns, run.replied_ns,            attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})for step in outcome.steps:    attributes = {"ambrewick.step": step.step}    if step.step in ("route", "answer"):  # model calls carry their token counts, under the book's own keys        attributes |= {"ambrewick.tokens.input": step.prompt_tokens, "ambrewick.tokens.cached": step.cached_tokens,                       "ambrewick.tokens.output": step.completion_tokens}    span(tracer, step.step, step.start_ns, step.end_ns, parent=root, attributes=attributes)rows = spans_to_rows(exporter)  # sorted by (trace, start, span), so the findings print in the same order every runfindings = [finding for row in rows for finding in validate(row)]print("GenAI conventions version:", REGISTRY_VERSION)print("spans checked:", fmt_int(len(rows)))for finding in findings:    print("finding:", finding)print("findings, no known span type:", fmt_int(sum("no known span type" in finding for finding in findings)))print("findings, all:", fmt_int(len(findings)))assert all(len(validate(row)) == 1 for row in rows)  # each span fails once, and only once
输出python validate-the-spans.py
GenAI conventions version: 0.1.0
spans checked: 4
finding: message: no known span type for this row
finding: route: no known span type for this row
finding: retrieve: no known span type for this row
finding: answer: no known span type for this row
findings, no known span type: 4
findings, all: 4
练习 2.5

为什么第 1 章的跨度没有类型

+10 项证明

消息 809 上的每个跨度都输出“no known span type for this row”。哪一条陈述给出了原因?

为什么第 1 章的跨度没有类型:选出正确的解释
运行于 Python 3.13.16

改名之后,这些跨度通过了检查。在全部 20 条开发日消息中,该示例共检查了 74 个跨度,在注册表所定义的任何跨度上发现的问题数为 0。一条断言把这个数目固定为零,因此,若某项改动破坏了名称,运行会失败,而不是打印出一个新的数字。

validate-the-renamed-spans.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通过
"""Run the validator over every span of the dev day's twenty messages: no finding on any span the registry defines, andone on each of the book's own fallback spans, which the registry does not define.The point rests on the line "findings on registry spans: 0", which is asserted, and on the fallback count, whichequals the fallback replies."""from lib.assistant import Assistantfrom lib.bm25 import Retrieverfrom lib.case import load_articles, load_messages, load_tool_durationsfrom lib.clock import VirtualClockfrom lib.dayrun import DAY, RECORDING, RELEASEfrom lib.export import spans_to_rowsfrom lib.genai import REGISTRY_VERSION, SCHEMA_URL, validatefrom lib.ids import SequentialIdsfrom lib.replay import Replay, ReplayContactsfrom lib.report import fmt_intfrom lib.tools import Toolsfrom lib.tracing import make_providerfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterfrom collections import Counterreplay = Replay(RECORDING)retriever, tools = Retriever(load_articles(), RELEASE.top_k), Tools(load_tool_durations(), ReplayContacts(replay))messages, fallback_replies, rows = load_messages(DAY), 0, []for message in messages:  # arrival order, as the replay needs; each message gets its own clock, exporter and trace    clock = VirtualClock(DAY, start_ns=message.arrival_ns)    exporter = InMemorySpanExporter()  # one per message, so each message's IDs start from 1    tracer = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", clock, SequentialIds(),                           exporter, SCHEMA_URL).get_tracer("ambrewick.assistant", schema_url=SCHEMA_URL)    fallback_replies += Assistant(replay, retriever, tools, clock, tracer, RELEASE).handle(message).source == "fallback"    rows += spans_to_rows(exporter)book = [row for row in rows if row["name"] == "ambrewick.fallback"]# The book's own fallback span is not a registry span, so it is checked apart from the others.registry_findings = [finding for row in rows if row["name"] != "ambrewick.fallback" for finding in validate(row)]book_findings = [finding for row in book for finding in validate(row)]# A span with no gen_ai.operation.name is counted under its own name, which is how the fallback span appears.operations = Counter(row["attributes"].get("gen_ai.operation.name", row["name"]) for row in rows)print("GenAI conventions version:", REGISTRY_VERSION)print("messages:", fmt_int(len(messages)))print("spans checked:", fmt_int(len(rows)))for operation in sorted(operations):    print(f"spans, {operation}:", fmt_int(operations[operation]))print("findings on registry spans:", fmt_int(len(registry_findings)))print("fallback replies:", fmt_int(fallback_replies))print("findings on the book's fallback span:", fmt_int(len(book_findings)))assert not registry_findings  # zero findings on every span the registry definesassert len(book_findings) == len(book) == fallback_replies  # one per fallback span, and each span is a fallback replyassert all("no known span type" in finding for finding in book_findings)
输出python validate-the-renamed-spans.py
GenAI conventions version: 0.1.0
messages: 20
spans checked: 74
spans, ambrewick.fallback: 6
spans, chat: 37
spans, execute_tool: 3
spans, invoke_agent: 20
spans, retrieval: 8
findings on registry spans: 0
fallback replies: 6
findings on the book's fallback span: 6

验证器确实会标记其他跨度。6 条回退回复各有一个 ambrewick.fallback 跨度,检查标记了其中全部 6 个,每个都附有 no known span type。这是正确的,并不表示约定失败。注册表定义了它所列出的类型,而不在其中的跨度没有类型。本书自己的跨度和属性位于 ambrewick. 命名空间,这是本书自己的命名空间,而命名规则要求名称置于某个命名空间之下(命名规则)。一条表明某个跨度在注册表之外的发现项,说明的是该跨度属于本书自己。每个标记都被断言为这一种发现项而非其他,因此,若某个注册表跨度新增了标记,运行就会失败。

**工作准则:**把注册表跨度上的发现项视为缺陷。把你自己命名空间中跨度上的发现项视为注册表给出的答复:该跨度是你自己的。

为生产环境中的 span 命名

本章的验证器作用于示例中记录下来的 span。在生产环境中,同样的检查必须作用于服务实际导出的 span,而有三件事会让检查悄无声息地失效。第四件事则决定实例 ID 是否有意义。我们建议在生产环境中使用 Development 名称,前提是它已被固定并经过验证,因为升级后验证器的首次运行会显示哪些内容发生了变化。

第一件事是名称的内容。规范要求 span 名称是其所属 span 类别中"最通用的字符串",并指出 get_account/42 过于具体(span API)。模型 span 的名称带有模型名,取自一份简短的固定列表,这已足够通用。若名称由用户 ID 构成,则每个用户都会产生一个新名称,而注册表的模式中容不下这样的名称。审阅者若在 span 名称中看到标识符,无论验证器如何判定,都应将其视为缺陷。

第二件事是 SDK。它不会阻止错误的名称。第 1 章中那些粗糙的名称原样通过了,拼错的注册表名称同样会通过。只有验证器会读取注册表,因此导出 span 却不运行验证器的流水线,根本没有任何检查。我们建议在导出 span 的流水线中运行验证器,而不仅仅是在测试中运行。

第三件事是升级。Development 名称可能在任何一次发布中改变,升级后验证器的首次运行会列出哪些内容发生了变化。在更改固定版本之前先阅读这份列表,并在同一个拉取请求中随版本一并修改名称。另一个写入旧名称的包所产生的 span 也可能到达同一个后端。后端中若同时存有这些 span 和本书的 span,同一个步骤就会出现两套词汇。

第四件事是实例 ID。service.namespace、service.name 和 service.instance.id 三元组必须全局唯一(服务注册表)。SDK 的默认做法是在每个进程中生成新的随机 UUID。在生产环境中,请保留这个随机 UUID,或者由实例独有的 ID 派生出 UUIDv5,并且绝不要在多个副本之间共用同一个值。回放中固定的实例 ID 对回放而言是正确的,但不应照搬。

添加 span 时,先写其注册表类型,再写名称,最后写种类。我们建议采用这一顺序,因为类型决定了名称的模式和种类。

工作准则: 在导出 span 的流水线中运行验证器,出现任何发现即让构建失败。将约定的版本与检查固定在一起,升级之前先阅读变更日志。

本章的决定

注册表会变动,名称也会随之变动。本章确定的是本书的各个 span 遵循哪个版本,以及一项在它们不再遵循该版本时给出报告的检查。下面的每项选择都是本书其余部分所依赖的,而且凡是能够断言的,都有一个示例对其加以断言。

  • 本书的名称遵循 GenAI 约定 0.1.0,并且该版本固定在验证器旁边,因为该注册表处于 Development 状态。
  • 检索 span 仅以其操作命名,即 retrieval,因为注册表的模式没有为其他任何内容留出位置。
  • 提供方的取值为 openai。这是我们自己的判断,并与注册表的指引并列引用,验证器无法对其进行检查,因为注册表中没有可供 llama.cpp 比对的取值。
  • 助手的提示词都有名称和版本,因此推理 span 带有 gen_ai.prompt.name 和 gen_ai.prompt.version,注册表将后者规定为有条件必需。
  • 模型 span 的类型取决于进程:位于服务器之后时为 CLIENT,仅在进程内部、且该 span 未指明服务器时才为 INTERNAL。
  • 本书的资源和追踪器携带的是注册表所依赖的核心发行版的模式 URL,而不是 SDK 中最新的常量。
  • 验证器将注册表 span 上的发现报告为缺陷,而本书自己的回退 span 有各自的发现,这些发现不属于缺陷。

本章,在本版次中

版次 2026.11.2示例于 2026年11月23日 通过5 of 5个示例 in this chapter pass

译自英文版图书,版次 2026.11.2。

开始实验室

图书始终免费阅读。

查看价格

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 2 章,共 12 章: 按标准为 span 命名

  1. Development 版本下的标准
  2. 各步骤的 span 类型
  3. span 的类型取决于进程
  4. Which attributes a span must carry
  5. 谁生成了这个跨度
  6. 对照注册表进行验证
  7. 为生产环境中的 span 命名
  8. 本章的决定

返回顶部全部章节