標準に従ってスパンに名前を付ける

読了まで約40 分。8 節に5 例を収録。

第2026.11.2版 2026年11月23日時点で例が通過 80 例中 80 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.2)から翻訳した。 原文を読む

Labs

この章を実際に手を動かして学ぶ

すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。約 30 秒で開く。

すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。Labs が実行環境を用意する: 月40 時間。

Labで開く、新しいタブで開く

利用時間を確認しています…

Lab を確認しています…

自分のマシンで、無料: 書籍のノートブックをダウンロード、そのコードとデータを GitHub から取得する。

この章を終えると、アシスタントのトレースに含まれる各スパンに、OpenTelemetry の GenAI 規約がそのステップに対して求める名前、種別、属性を与えられるようになる。また、どのソフトウェアがそのスパンを生成したか、名前がどのスキーマバージョンに従っているかを示せるようになる。さらに、スパンがレジストリから外れたときに失敗するチェックを実行できるようになる。

Ambrewick のオンコールエンジニアは、本書がトレースを構築する対象のアシスタントを運用している(1 件のメッセージ、1 件のトレース)。彼らは、そのトレースを自分たちがすでに運用しているツールで扱いたいと考えている。それらのツールが知っている語彙は一つだけであり、モデル呼び出し、検索、ツール実行、エージェントのターンに対して規約が与える名前である。第 1 章の名前は、そこでは何の意味も持たない。この章で構築するチェックであるバリデータは、各スパンをレジストリの規則と照合する。デバイスに関する質問で検索を含むメッセージ 809 に対して実行すると、4 個のスパンから 4 件の指摘が出る。指摘はスパンごとに 1 件であり、いずれも、そのスパンには既知のスパン種別がないと述べている。SDK はどの名前も受け付けるため、SDK はこれらの指摘を一つも出さなかった。そこでこの章では、各スパンに標準の名前と種別を与え、誰がそれを生成したかを記録し、名前を正しく保つチェックを構築する。続く第 3 章では、クライアントライブラリのスパンをこれらの名前に照らして測定する。

Development 版の標準

バックエンドは、スパンに関する問い合わせを名前で処理する。今週のモデル呼び出しにどれだけ時間がかかったかという問いは、どのスパンがモデル呼び出しであるかについてすべてのバックエンドが合意している場合にのみ、一つの答えを持つ。標準とは、その合意のことである。セマンティック規約とは、スパン、属性、メトリクスに対して公開された名前、型、意味の取り決めであり、どのバックエンドも同じ名前を同じように読み取れるようにするものである。ここでの標準は、OpenTelemetry の GenAI セマンティック規約である。

GenAI の名前は、当初 OpenTelemetry のコアのセマンティック規約リポジトリに置かれていた。そのリポジトリはリリース 1.42.0 で gen_ai プレフィックスの名前を非推奨とし、名前は独立したリポジトリへ移った(変更履歴)。本書は、そのリポジトリの最初の単独リリースである GenAI 規約のバージョン 0.1.0 に従う(変更履歴)。

規約には二つの形式がある。人が読むためのページと、プログラムが読めるレジストリである。レジストリは、スパンの種類、その kind、属性を記述した YAML モデルである。本書の検証ツールは、固定されたバージョンのレジストリを読む。したがって、検証ツールが確認する名前は、レジストリに載っている名前である。

GenAI 規約のバージョン 0.1.0 のすべてのページは Development であり、その名前はどのリリースでも変更される可能性がある。仕様は自らの構成要素について Development を定義しており、そのステータスのページは、そうした構成要素について次のように述べている。「The component MAY be removed without prior notice. The component SHOULD NOT be used in production.」(ステータスのページ)。GenAI のページも同じステータスを持ち、その変更履歴には名前の変更が示されている。最初の単独リリースでは、推論スパンの種類の名前が gen_ai.inference.client から gen_ai.client.inference に変更された。本書の名前はそのリリースに従っているため、後のリリースで名前が変更される可能性がある。

実践ルール: 公開するすべての名前の横に、規約のバージョンを固定して記載すること。Development の名前の上に構築したダッシュボードには、名前が変更されたときに実行される検査が必要である。

この部分はまだ翻訳されていないため、英語で表示している。

Span types for each step

The registry sorts spans into span types, and each type has a name pattern, a span kind and the attributes it requires. Chapter 1's steps fall into four of them. An inference span is the span of one client call to a generative model that answers the prompt or asks for a tool call. A retrieval span is the span of one run of the application's retrieval step, which returns the documents relevant to a query. A tool-execution span is the span of one run of a tool, named for the tool. An agent-invocation span is the span of one invocation of an agent. The book's agent runs in the assistant's process, so its span is the in-process type, which also covers workflows. A remote agent's span is a CLIENT span of its own type. The route and answer steps are model calls, the retrieve step is a search, the tool runs are tool runs, and each message's root is one agent run.

Span type Name pattern Kind Operation name
Inference {operation} {model} CLIENT, or INTERNAL in process chat
Retrieval {operation} INTERNAL retrieval
Tool execution execute_tool {tool} INTERNAL execute_tool
Agent invocation invoke_agent {agent} INTERNAL in process; CLIENT for a remote agent 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

モデルスパンの名前にはプロバイダではなくモデルを使う

+10 件の検証

42行目は、モデルスパンの名前をモデルではなくプロバイダ属性から作っている。42行目を修正し、モデルスパンが、そのレジストリのパターンに対して、実行で使われたモデルを用いて照合されるようにせよ。

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 を使い、ツールスパンの名前とエージェントスパンの名前を、それぞれのレジストリパターンと照合する assert を 2 つ書く。

# 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 で実行される

The model span changes most. Its name is the operation, a space, and the model's name, so a reader scanning a trace sees which model answered each call. Message 11159, a lists request with one tool call, has its first model call named chat qwen3-4b-instruct-2507. The registry gives one list of well-known values for gen_ai.operation.name on an inference span, and a custom value MAY be used beyond it (registry attributes). The validator maps each value to a span type through a map the book makes, and that map gives the inference type chat, generate_content, realtime_inference, text_completion. The assistant writes chat for each of its calls. The example asserts the model span's name against the operation and the model the run used, and it builds the tool and agent names from the attributes their spans carry, so a drift in either one fails the run.

The retrieval span is named by its operation alone, retrieval. The registry's pattern leaves no room for the index it searched, so the knowledge base's name stays out of the span name. A tool run is named for its tool, execute_tool remove_item, the run of the list tool that removed an item in message 11159. The root is named invoke_agent ambrewick-assistant, and it replaces chapter 1's message span. We keep invoke_agent rather than invoke_workflow, because the model chooses the route and whether to call a tool. The model drives the control flow through tool calls, which is the case the registry's agent type describes.

One attribute the registry leaves open is the provider. In the book, the inference span's gen_ai.provider.name is openai, and that value is our judgement. The registry's well-known values for the attribute include no value for llama.cpp, and a provider the list lacks may take a custom value (registry). The attribute's general note says it "SHOULD be set based on the instrumentation's best knowledge and may differ from the actual upstream provider" (client inference). We record openai because Ambrewick's client speaks OpenAI's API to its endpoint, and the official package records openai for that call, as chapter 3 shows. A reader whose model is served another way should choose by the same rule and say so.

Of the spans the assistant makes, the fallback span is the only one the registry does not name. The book keeps it, the validator flags it, and the validation section says why that flag is the right answer.

Working rule: Name each span from its registry pattern, not from the function that made it, and take the operation name from the registry's well-known values. Where the registry gives no value for something you run, use the value the client and its official instrumentation would write, and say that it's a judgement.

スパンの種別はプロセスに従う

スパンの種別は、その処理がどこで実行されたかを示す。プロセスの外へ出る呼び出しには CLIENT、受け取る呼び出しには SERVER、プロセス内部の処理には INTERNAL を用いる(このほかに PRODUCER と CONSUMER があり、キューに渡される処理を表す)。難しいのはモデル呼び出しの場合である。レジストリには次のようにある。「計装対象の GenAI システムが通常はクライアントとは別のプロセスで動作する場合、または GenAI 呼び出しが HTTP などの計装済みプロトコルを介して行われる場合は、CLIENT 種別を用いることを推奨する」(client inference)。エンドポイントの背後にあるモデルへは、アシスタントのプロセスの外へ出る呼び出しで到達するため、そのスパンは CLIENT になる。レジストリは、同じプロセス内で動作するモデルに INTERNAL を用いることも認めており、そのため種別の決定には判断が伴う。本書は、スパン自体が示せる検証、すなわちその呼び出しがサーバーを名指ししているかどうかで、この規則を適用する。サーバーを名指しする呼び出しは 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 は、ルート呼び出しと回答呼び出しを持つ devices の質問である。エンドポイントの背後では、スパンの種別は CLIENT であり、同じ呼び出しをプロセス内で実行すると INTERNAL になる。エンドポイントのスパンはサーバーを名指ししており、プロセス内のスパンは何も名指ししていない。バリデータは、プロセス内のスパンについて 0 件の指摘を報告する。この件数は例の中でアサートされている。エンドポイントのスパンを INTERNAL とした場合でも、そのスパンはサーバーを名指ししたままであり、バリデータはそれについて 1 件の指摘を報告する。指摘の文面には種別 kind is INTERNAL が含まれることがアサートされており、出力されるのは件数のみである。この指摘が、規則によって防ごうとしている不具合である。

本書の dev-day のトレースはすべて CLIENT である。記録されたモデル呼び出しが、エンドポイントを介して処理されたためである。プロセス内のケースは、同じモデルをアシスタント自身のコードから呼び出すものであり、本書ではこの例の中でのみ実行する。モデルをプロセス内へ移す読者は、それに伴って種別が変わることを想定すべきであり、スパンがなおサーバーを名指ししている場合には、バリデータがそれを指摘することを想定すべきである。

検索スパンとエージェントスパンはどちらも INTERNAL である。どちらの処理もアシスタントの内部で実行されるためで、例の中でそれぞれについてアサートされている。出力される種別は、検索スパンが INTERNAL、エージェントスパンが INTERNAL である。レジストリは両方の種別を定めており(registry)、バリデータがそれらを検査する。

実践ルール: 呼び出しがサーバーへ向かう場合は、同じマシン上のサーバーであっても、モデルのスパンに CLIENT を与える。INTERNAL を与えるのは、モデルが自分のプロセス内で動作し、かつスパンがサーバーを名指ししない場合に限る。設定した各種別は、バリデータに検査させる。

スパンが持たなければならない属性

名前は、スパンが何であるかをバックエンドに伝える。要件レベルは、そのスパンがどの属性を持たなければならないかを伝える。要件レベルは、属性がいつ現れなければならないかを定めるものであり、必須、条件付き必須、推奨、オプトインの四つがある(要件レベル)。必須属性は、その種類のすべてのスパンに現れる。条件付き必須の属性は、条件が成り立つときに現れ、レジストリは条件を属性の横に記している。推奨属性は、良いスパンが何を持つかを示し、オプトインの属性は、何かがそれを有効にしたときにだけ現れる。

レジストリは、各スパンの種類がどの属性を持たなければならないかも定めている。本書のモジュール lib.genai はレジストリのすべての要件レベルを保持している。したがって、バリデータが検査する要件レベルと種類は、誰かが手で入力した一覧ではなく、レジストリのものである。バリデータが検査するのは種類と必須属性だけである。そのため、スパンはバリデータを通過しても、条件付きの場合にレジストリが求める属性を欠いていることがある。inference-span-names の例が出力するバリデータの件数は、各スパンの種類が要求する数を示している。推論スパンでは 2、ツール実行スパンでは 2、検索スパンでは 1、エージェントスパンでは 1 である。その必須属性は操作名とプロバイダ名であり、したがってプロバイダの判断は省略できない。どちらか一方でも欠くスパンは、検査に失敗する。

プライバシーの観点で注意すべきなのは、オプトインの属性である。モデル呼び出しのメッセージ内容はオプトインであるため、本書のスパンは、スイッチで求めない限りそれらを一切持たない。そのスイッチが何をするかは第3章で述べる。

バリデータが読まないのは、条件付きの要件である。gen_ai.prompt.version は、スパンが gen_ai.prompt.name を持ち、かつバージョンが利用できる場合に、推論スパンで条件付き必須となる。gen_ai.prompt.name は、名前付きのプロンプトテンプレートを使う場合に条件付き必須となる(レジストリ)。アシスタントのプロンプトには名前とバージョンが付いているため、その推論スパンは両方を持つ。メッセージ 11159 のルート呼び出しでは ambrewick.route と p1 がそれである。第10章では、このペアを問い合わせてリリースを区別する。バリデータは必須属性だけを読むので、どちらかを欠くスパンがあっても報告しない。条件付き属性の欠落は、バリデータが報告しない欠落である。

実践ルール: スパンの名前を読む前に、そのスパンの要件レベルを読むこと。必須属性の欠落は、スパンの欠陥である。条件付き必須属性の欠落は、その条件が成り立つときにだけ欠陥となる。したがって、報告する前にレジストリで条件を確認すること。

スパンを作ったのは誰か

スパンは何を計測したかを示し、誰が計測したかは別の二つの場所が示す。リソースとインストルメンテーションスコープである。インストルメンテーションスコープは、スパンを作ったコードの単位に名前を付けるものであり、通常はインストルメンテーションライブラリを指す。ここではアシスタント自身のモジュールである。スキーマ URL は、公開されたテレメトリスキーマ、すなわちテレメトリが従うセマンティック規約のリリースに名前を付ける。本文ではスキーマ URL を直接記さない。ここに示す URL はいずれも、対応する例が出力したものである。

リソースには、本書が自ら設定する三つの属性がある。service.name は ambrewick-assistant である。service.version は 1.0.0 であり、リリースを示す。第10章では、これを読んでトレースをリリースごとに分割する。service.instance.id は dev-day-replay である。リプレイはインスタンス ID を自ら設定するため、再実行しても同じインスタンスの名前が使われ、実行ごとにトレースを比較できる。再起動するプロセスがインスタンス 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 件の検証

出力では、名前を変更したスパンに、SDK の定数の中で最も新しいものよりも新しいスキーマ URL が付与されている。この例が、その URL を定数からではなくレジストリのマニフェストから取得しているのはなぜか。

スキーマ URL をレジストリから取得する理由:正しい説明を選ぶ
Python 3.13.16 で実行される

本章ではスキーマ URL が変わった。例は両方の値を出力する。第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 の時点では独自のスキーマ URL を公開していない。コアは、gen_ai.* の名前が独自のリポジトリに移された 1.42.0 で、それらを非推奨とした。したがってスタンプが示すのは、リソースの service.* の名前がどのコアのリリースに従うかであり、GenAI のバージョンは検証と並べて 0.1.0 として持ち回る。本書の生成モジュールはこの URL をレジストリのマニフェストから取得し、例は SDK の定数にこの URL が含まれないことをアサートする。定数は、その SDK 自身のリリースで止まっている。service.* 属性のうち、この URL が指すリリースが非推奨とするのは service.peer.name と service.peer.namespace だけである(変更履歴)。そのため、リソースが設定する三つの属性は、どちらの URL でも同じ意味に読める。

名前を改めたスパンのインストルメンテーションスコープは ambrewick.assistant であり、そのスキーマ URL はリソースのものと同じである。例はこれをアサートする。公式クライアントライブラリは独自のスコープを書き込む。

実践ルール: リソースには service.name と service.version を自分で設定し、service.instance.id にはインスタンスごとに一意の値を与える。これは本番環境の節で説明するとおりである。そのうえで、トレーサーには、依存するコアのリリースのスキーマ 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 であり、検査はそれぞれに 1 件ずつ指摘を出力する。その内容は 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 件の問題を見つける。1 つのアサーションがこの件数を 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. に置かれる。命名規則も、名前を名前空間の中に置くよう求めている(命名規則)。スパンがレジストリの外にあるという指摘は、そのスパンが本書独自のものであることを示している。各指摘はこの指摘であって他のものではないことがアサートされるので、レジストリのスパンに指摘が付けば、実行は失敗する。

実践ルール: レジストリのスパンに対する指摘は、欠陥として読む。自分の名前空間のスパンに対する指摘は、そのスパンが自分のものであるというレジストリの回答として読む。

本番環境でスパンに名前を付ける

ここでの検証器は、例の中で記録済みのスパンに対して動作する。本番環境では、サービスが実際にエクスポートするスパンに対して同じ検査を実行する必要がある。ただし、この検査が気づかれないまま失敗する原因が三つある。さらに四つ目の原因が、インスタンス ID に意味があるかどうかを左右する。本番環境で Development の名前を使うことを推奨するのは、その名前が固定され、かつ検証されている場合である。アップグレード後の検証器の初回実行が、何が変わったかを示すからである。

一つ目は名前の内容である。仕様は、スパン名がそのスパンの種類に対して「最も一般的な文字列」であることを求めており、get_account/42 は具体的すぎる例として挙げている(span API)。モデルスパンの名前には、短い固定リストの中から選んだモデルが入る。これは十分に一般的である。ユーザー ID から組み立てた名前はユーザーごとに新しい名前となるが、レジストリのパターンには識別子を入れる余地がない。スパン名に識別子が含まれているのをレビュアーが見つけた場合は、検証器の結果にかかわらず、それを欠陥として扱うべきである。

二つ目は SDK である。SDK は誤った名前を止めない。第 1 章の大まかな名前はそのまま通過したし、レジストリ名のつづりを誤った場合も同様に通過する。レジストリを読むのは検証器だけであり、検証器を実行せずにスパンをエクスポートするパイプラインには、検査がまったくないことになる。検証器はテストだけでなく、スパンをエクスポートするパイプラインでも実行することを推奨する。

三つ目はアップグレードである。Development の名前は、どのリリースでも変更されうる。アップグレード後の検証器の初回実行では、変わったものが一覧に出る。固定されたバージョンを変更する前にその一覧を読み、名前の変更はバージョンの変更と同じプルリクエストで行う。古い名前を書き出す別のパッケージのスパンが、同じバックエンドに届くこともある。それらと本書のスパンを保持するバックエンドでは、一つのステップに二つの語彙が現れる。

四つ目はインスタンス ID である。service.namespace、service.name、service.instance.id の三つ組は、グローバルに一意でなければならない(MUST)(service registry)。SDK の既定値は、プロセスごとに新しくランダムに生成される UUID である。本番環境ではそのランダムな UUID を使い続けるか、インスタンス固有の ID から UUIDv5 を導出する。一つの値を複数のレプリカで共有してはならない。リプレイで使う固定のインスタンス ID は、リプレイでは正しいが、そのまま真似るのは誤りである。

スパンを追加するときは、レジストリの種別、名前、種類の順に書く。この順序を推奨するのは、種別が名前のパターンと種類を決めるからである。

実践ルール: スパンをエクスポートするパイプラインで検証器を実行し、指摘があればビルドを失敗させる。規約のバージョンは検査と並べて固定し、そのバージョンを上げる前に変更履歴を読む。

この章で決めたこと

レジストリは変わっていくものであり、名前もそれに伴って変わる。この章で確定させるのは、本書のスパンがどのバージョンに従うかということと、スパンがそれに従わなくなったときに報告する検査である。以下の各項目は、本書の以降の部分が前提とする選択であり、例はそれぞれについて、検証できるものを表明している。

  • 本書の名前は GenAI conventions 0.1.0 に従う。レジストリは Development の段階にあるため、このバージョンはバリデータと並べて固定する。
  • 検索スパンは、操作名のみの retrieval と名付ける。レジストリのパターンには、それ以外のものを入れる場所がないためである。
  • プロバイダの値は openai とする。これは本書の判断であり、レジストリの指針を並べて引用してある。レジストリには llama.cpp と照合できる値がないため、バリデータはこれを検査できない。
  • アシスタントのプロンプトには名前とバージョンを付ける。そのため、推論スパンは gen_ai.prompt.name を gen_ai.prompt.version とともに持つ。レジストリは、この組を条件付きで必須としている。
  • モデルスパンの種別はプロセスの構成に従う。サーバの背後にある場合は CLIENT とし、スパンがサーバを名指ししない、プロセス内のみの場合に限って INTERNAL とする。
  • 本書のリソースとトレーサは、SDK の最新の定数ではなく、レジストリが依存するコアリリースのスキーマ URL を持つ。
  • バリデータは、レジストリ上のスパンに対する指摘を欠陥として報告する。本書独自のフォールバックのスパンには、それ専用の指摘を出すが、それらは欠陥ではない。

この版における本章

第2026.11.2版2026年11月23日時点で例が通過この章の5 例件のうち5件が合格

英語版の書籍(版2026.11.2)から翻訳した。

Labs を開始

書籍は引き続き無料で読める。

料金を見る

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全12章中の第2章: 標準に従ってスパンに名前を付ける

  1. Development 版の標準
  2. Span types for each step
  3. スパンの種別はプロセスに従う
  4. スパンが持たなければならない属性
  5. スパンを作ったのは誰か
  6. レジストリに対する検証
  7. 本番環境でスパンに名前を付ける
  8. この章で決めたこと

ページの先頭に戻るすべての章