依標準為 span 命名

閱讀約 44 分鐘,8 節 中共有 5 個範例。

版次 2026.11.2 範例於 2026年11 月 23 通過測試 80 個範例中有 80 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.2。 閱讀原文

Labs

透過實作學習本章

完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。約 30 秒內開啟。

完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。由 Labs 為你執行:每月 40 小時。

在 Lab 中開啟,於新分頁開啟

正在檢查您的時數…

正在尋找您的 Lab…

於您自己的電腦,免費: 下載本書的筆記本,連同其程式碼與資料,皆取自 GitHub。

讀完本章後,你可以為助理追蹤(trace)中的每個 span,依 OpenTelemetry 的 GenAI 慣例,賦予其對應步驟所預期的名稱、種類與屬性。你可以說明是哪個軟體產生了該 span,以及其名稱遵循哪一個結構描述版本,也可以執行一項檢查,在 span 偏離登錄表(registry)時使檢查失敗。

Ambrewick 的值班工程師負責運作這個助理,本書所建構的追蹤即來自該助理(一則訊息,一條追蹤)。他們希望這些追蹤能進入自己已在使用的工具。這些工具只認得一套詞彙:慣例為模型呼叫、檢索、工具執行與代理人一輪回應所訂的名稱。第 1 章的名稱在那些工具中毫無意義。驗證器(validator)是本章要建構的檢查,它會將每個 span 與登錄表的規則比對。對訊息 809(一個含有檢索的裝置問題)執行驗證器時,其 4 個 span 產生 4 項發現,每個 span 一項,且每項都指出該 span 沒有已知的 span 類型。SDK 並未對任何一項提出錯誤,因為 SDK 接受任何名稱。因此,本章為每個 span 賦予標準的名稱與種類,記錄其產生者,並建構一項檢查,確保名稱維持正確。接著第 3 章會以這些名稱來衡量某個用戶端函式庫的 span。

處於 Development 階段的標準

後端是依名稱來回答有關 span 的問題。像是「本週模型呼叫花了多少時間」這類問題,只有在所有後端都認同哪些 span 是模型呼叫時,才會有唯一的答案,而標準就是這種共識。語意慣例(semantic convention)是針對 span、屬性或指標(metric)所公布的名稱、型別與意義,讓任何後端都能以相同方式解讀同一個名稱。這裡的標準是 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 類型

登錄表(registry)將 span 分成數種 span 類型,每種類型都有名稱模式、一種 span kind,以及它所要求的屬性。第 1 章的各個步驟可歸入其中四種。推論 span(inference span)是一次用戶端呼叫生成式模型的 span,該模型會回答提示,或要求呼叫工具。檢索 span(retrieval span)是應用程式的檢索步驟執行一次的 span,該步驟會回傳與查詢相關的文件。工具執行 span(tool-execution span)是一個工具執行一次的 span,以該工具命名。代理程式呼叫 span(agent-invocation 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 行是空白的。請撰寫兩個 assert,依據各自的登錄表模式,分別檢查工具 span 的名稱與代理 span 的名稱,並使用屬性 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

為什麼 retrieval span 的名稱不含索引

+10 則證明

範例印出「retrieval span name: retrieval」,儘管搜尋是針對知識庫執行的。下列哪一項能說明名稱中為何沒有索引?

為什麼 retrieval span 的名稱不含索引:選出正確的說明
在 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 與其端點通訊,而官方套件(official package)對該次呼叫記錄的也是 openai,第 3 章會說明。若讀者的模型以其他方式提供服務,應依同樣的規則選擇,並說明這一點。

在助理產生的 span 中,後備 span(fallback span)是登錄表唯一沒有命名的一個。本書保留它,驗證器會標記它,而驗證一節說明了為何這個標記是正確的結果。

實用原則: 每個 span 都依登錄表的模式命名,而不是依產生它的函式命名,並從登錄表的已知值中取得操作名稱。若登錄表對你所執行的某項內容沒有提供值,就使用用戶端及其官方埋點(instrumentation)會寫入的值,並說明這是一項判斷。

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.

跨度由誰產生

跨度說明了它量測的內容,另有兩處說明是誰進行量測:資源與儀器化範圍。儀器化範圍指出產生跨度的程式單元,通常是一個儀器化函式庫,在這裡則是助理自己的模組。綱要網址指向一份已發布的遙測綱要,也就是語意慣例的某個版本,遙測資料即遵循該版本。正文不直接寫出任何綱要網址,這裡的每一個網址都由其範例印出。

資源帶有三個由本書自行設定的屬性。service.name的值是ambrewick-assistant。service.version的值是1.0.0,它標示發行版本,第 10 章會讀取它,依發行版本拆分追蹤。service.instance.id的值是dev-day-replay。重播會自行設定執行個體識別碼,因此重新執行時會指向同一個執行個體,各次執行的追蹤便能互相比較。程序重新啟動後,只有事先設定過識別碼,才會保留原本的執行個體識別碼;若要用查詢跟隨同一個執行個體跨越重新啟動,識別碼就必須維持不變。

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 上執行

本章中綱要網址有所變動,範例會印出兩個值。第 1 章的資源寫的是https://opentelemetry.io/schemas/1.44.0。那是所固定版本的語意慣例套件所含的最新綱要,即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 時並未發布自己的綱要網址。核心在 1.42.0 淘汰了其gen_ai.*名稱,因為這些名稱已移到各自的儲存庫。因此,戳記說明的是資源的service.*名稱依循哪一個核心版本,而 GenAI 的版本則隨驗證一併記錄,即0.1.0。本書產生的模組從登錄庫的資訊清單取得該網址,範例並斷言 SDK 的常數中不含此網址。這些常數停在它們自己的版本。在service.*屬性中,該網址所指的版本只淘汰了service.peer.name與service.peer.namespace(變更記錄),所以資源所設定的那三個屬性,無論採用哪個網址,意義都相同。

改名後的跨度,其儀器化範圍是ambrewick.assistant,綱要網址與資源的相同,範例也對此加以斷言。官方的用戶端函式庫則會寫入它自己的範圍。

**實用原則:**請自行在資源上設定service.name與service.version,並讓service.instance.id取得該執行個體獨有的值,如正式環境一節所述。接著,把你的慣例所依賴的核心版本之綱要網址交給追蹤器,該網址應取自登錄庫的資訊清單,而不是 SDK 的常數,因為常數可能落後於慣例。請把 GenAI 慣例的版本固定在驗證工具旁,因為在 v0.1.0 時它們沒有綱要網址可供蓋上戳記。

依登錄表驗證

名稱是對登錄表(registry)所作的主張,而驗證器讓這項主張可以被檢驗。它會從 gen_ai.operation.name 找出每個 span 的類型;若是 MCP span,則從其方法(method)找出。MCP 是 Model Context Protocol,也就是工具伺服器所使用的協定。接著驗證器會依登錄表的規則,檢查該 span 的種類(kind)與必要屬性。找不到類型的 span 會得到一則說明此事的發現,而每則發現都會指出所屬的 span,因此輸出讀起來就是一份待修正的清單。

驗證器無法為第 1 章的 span命名,因為這些 span 沒有 gen_ai.operation.name,而這正是它用來找出 span 類型的屬性。訊息 809 的 4 個 span 分別是 message、route、retrieve 與 answer,檢查會為每一個印出一則發現:no known span type for this row。這則發現已說明原因。根 span 改名之後,message 會變成 invoke_agent ambrewick-assistant,該 span 便依其自身的類型接受檢查。

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 章的 span 沒有型別

+10 則證明

訊息 809 上的每個 span 都印出「no known span type for this row」。哪一項敘述說明了原因?

為什麼第 1 章的 span 沒有型別:選出正確的說明
在 Python 3.13.16 上執行

改名後,這些 span 通過檢查。在全部 20 則 dev-day 訊息中,本範例檢查了 74 個 span,在登錄表有定義的 span 上發現 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

驗證器確實會標記其他 span。這 6 則備援回覆各有一個 ambrewick.fallback span,檢查標記了全部 6 個,每個都附上 no known span type。這是正確的結果,並非這些慣例的失敗。登錄表定義的是它所列出的類型,不在其中的 span 就沒有類型。本書自己的 span 與屬性位於 ambrewick. 命名空間,那是本書的命名空間,而命名規則要求名稱置於某個命名空間之下(命名規則)。一則指出 span 不在登錄表內的發現,說明的就是該 span 屬於本書自己。每一個標記都被斷言必須是這則發現而非其他,因此若有登錄表內的 span 多出標記,執行就會失敗。

實用原則: 登錄表 span 上的發現,視為缺陷。自己命名空間內 span 上的發現,視為登錄表給出的答覆:這個 span 是你自己的。

為正式環境中的 span 命名

這裡的驗證器是在範例內,對已記錄的 span 執行。在正式環境中,同樣的檢查必須對服務實際匯出的 span 執行,而有三件事會讓它悄悄失效。第四件事則決定執行個體 ID 是否有意義。我們建議在正式環境中使用 Development 名稱,但須已鎖定版本並經過驗證,因為升級後驗證器的第一次執行,會顯示哪些內容有所變動。

第一件事是名稱的內容。規範要求 span 名稱必須是該類 span 的「最通用的字串」,並指出 get_account/42 這類名稱過於具體(span API)。模型 span 的名稱帶有模型,取自一份簡短的固定清單,這樣已足夠通用。若名稱由使用者 ID 組成,每位使用者就會產生一個新名稱,而登錄庫的模式中沒有容納這種名稱的空間。審查者若在 span 名稱中看到識別碼,無論驗證器怎麼說,都應將其視為缺陷。

第二件事是 SDK。它不會阻止錯誤的名稱。第 1 章的粗略名稱原封不動地通過了,拼錯的登錄庫名稱也會如此。只有驗證器會讀取登錄庫,因此匯出 span 卻不執行驗證器的管線,完全沒有檢查。我們建議在匯出 span 的管線中執行驗證器,而不只是在測試中執行。

第三件事是升級。Development 名稱可能在任何版本中變更,而升級後驗證器的第一次執行,會列出有哪些內容變動。更改鎖定版本之前請先閱讀該清單,並在與版本相同的 pull request 中修改名稱。另一個寫入較舊名稱的套件所產生的 span,也可能送到同一個後端。後端若同時存有那些 span 和本書的 span,就會在同一個步驟上看到兩套詞彙。

第四件事是執行個體 ID。service.namespace、service.name 與 service.instance.id 這個三元組必須全域唯一(服務登錄庫)。SDK 的預設做法是在每個行程中產生新的隨機 UUID。在正式環境中,請保留該隨機 UUID,或從對執行個體唯一的 ID 衍生出 UUIDv5,且絕不要讓多個副本共用同一個值。重播時使用的固定執行個體 ID 對重播而言是正確的,但不應照抄。

新增 span 時,請先寫登錄庫類型,再寫名稱,最後寫種類。我們建議採用這個順序,因為類型決定了名稱的模式與種類。

實用原則: 在匯出 span 的管線中執行驗證器,並在有發現時讓建置失敗。在檢查旁邊鎖定慣例的版本,並在升級之前閱讀變更紀錄。

本章的決定

登錄表會變動,名稱也會隨之變動。本章所確定的,是本書的 span 依循哪一個版本,以及一項在 span 不再依循該版本時提出回報的檢查。以下每一項選擇,都是本書其餘部分所仰賴的,而每一項只要能斷言,就有一個範例加以斷言。

  • 本書的名稱依循 GenAI conventions 0.1.0,而且由於登錄表處於 Development 階段,版本會固定在驗證器旁邊。
  • 檢索 span 僅以其操作命名,即 retrieval,因為登錄表的模式中沒有容納其他內容的位置。
  • provider 的值為 openai。這是我們的判斷,並與登錄表的指引並列引用;驗證器無法檢查這一點,因為登錄表中沒有可供 llama.cpp 比對的值。
  • 助理的提示詞有名稱,也有版本,因此推論 span 會帶有 gen_ai.prompt.name 與 gen_ai.prompt.version,登錄表將後者列為條件式必要。
  • 模型 span 的種類依循程序而定:在伺服器之後為 CLIENT,只有在同一程序內且該 span 未指名伺服器時才為 INTERNAL。
  • 本書的資源與追蹤器所帶的 schema URL,是登錄表所依賴之核心版本的 schema URL,而不是 SDK 最新的常數。
  • 驗證器會將登錄表中 span 上的發現回報為缺陷;本書自己的備援 span 則有各自的發現,這些發現不屬於缺陷。

本章,於本版次中

版次 2026.11.2範例於 2026年11 月 23 通過測試5 of 5 個範例 in this chapter pass

譯自英文書,版次 2026.11.2。

開始 Labs

本書仍可免費閱讀。

查看價格

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 2 章,共 12 章: 依標準為 span 命名

  1. 處於 Development 階段的標準
  2. 各步驟的 span 類型
  3. Span 的種類取決於程序
  4. Which attributes a span must carry
  5. 跨度由誰產生
  6. 依登錄表驗證
  7. 為正式環境中的 span 命名
  8. 本章的決定

返回頂端所有章節