クライアントライブラリにコール計装を任せる

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

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

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

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

Labs

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

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

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

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

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

Lab を確認しています…

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

この章を終えると、次の三つができるようになる。OpenAI 公式の計装が 1 回のチャット呼び出しに対して書き出す内容を読むこと。その名前のうち、本書が従う GenAI 規約のバージョン 0.1.0 と異なるものを挙げること。プロンプトと応答を記録するかどうかを決める変数を、そのデフォルト値とともに答えること。第 1 章ではモデルのスパンを手作業で書いた。第 2 章「標準に従ってスパンに名前を付ける」では、それらのスパンに標準の名前を与えた。この章では、ライブラリがそれらのスパンを代わりに書けるかどうかと、ライブラリのスパンがどこで異なるかを問う。

Ambrewick のアシスタントは、openai クライアントライブラリを通じてモデルを呼び出している。このライブラリには、クライアントをラップして呼び出しごとにスパンを書くパッケージがある。第 1 章で時間が記録されているステップはモデル呼び出しだけだった。したがって、それらを正しく書くパッケージがあれば、本書が手作業で作るスパンの大部分は不要になる。一方、異なる書き方をするパッケージは、この章より後の章のすべてのクエリを変えてしまう。それらの章は名前を読むからである。問いは具体的である。実際の 1 回の呼び出しについて、パッケージは何を出力し、本書が手作業で書く内容とどこが異なるのか。

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

A call through the client

There are two ways to get a span for a model call. Manual instrumentation is spans your code makes; automatic instrumentation collects telemetry with no change to the application's source code. Chapter 1 used the first kind. This section uses an instrumentation library. An instrumentation library is a package that makes the telemetry for another library's calls: one call in the start-up code installs it, and the zero-code agent, opentelemetry-instrument, loads the same package with no change to the calls.

instrumented-chat-call.py Python 3.13.16 · httpx 0.28.1 · mcp 2.3.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 合格
"""One chat call through the openai client, instrumented by the official package and answered from the recording. Thepoint rests on three printed facts: the call makes one client span, named for its operation and model; that span is achild of the message's span; and it holds the usage the reply reported. The metrics are named and counted here, nevervalued, since their durations use real time."""from lib.http_replay import client, route_body    # lib first: threads and seeds are fixed before anything elseimport opentelemetry.sdk.trace as sdk_tracefrom opentelemetry.instrumentation.genai.openai import OpenAIInstrumentorfrom opentelemetry.sdk.metrics import MeterProviderfrom opentelemetry.sdk.metrics.export import InMemoryMetricReaderfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterfrom lib.assistant import RELEASESfrom lib.case import load_messagesfrom lib.clock import VirtualClockfrom lib.ids import SequentialIdsfrom lib.names_map import name_mapfrom lib.report import fmt_intfrom lib.tracing import make_providerclock = VirtualClock("2026-12-07")# The SDK reads span times from its trace module's time_ns, so patching that name gives every span, the package's included,# virtual times.sdk_trace.time_ns = lambda: clock.advance(1_000_000)exporter, reader = InMemorySpanExporter(), InMemoryMetricReader()provider = make_provider("ambrewick-assistant", RELEASES["r0"].service_version, "example", clock, SequentialIds(),                         exporter, "https://opentelemetry.io/schemas/1.45.0")OpenAIInstrumentor().instrument(tracer_provider=provider, meter_provider=MeterProvider(metric_readers=[reader]))with provider.get_tracer("ambrewick-assistant").start_as_current_span("invoke_agent ambrewick-assistant"):    reply = client().chat.completions.create(**route_body(load_messages("2026-12-07")[0]))call, root = exporter.get_finished_spans()                  # the call ends before the message's span doesmetrics = reader.get_metrics_data().resource_metrics[0].scope_metrics[0].metricsprint("spans in the trace:", len(exporter.get_finished_spans()))print("instrumented span, name:", call.name)print("instrumented span, kind:", call.kind.name)print("instrumented span, scope schema URL:", call.instrumentation_scope.schema_url)print("attributes on the span:", ", ".join(sorted(call.attributes)))print("gen_ai.provider.name on the span:", call.attributes["gen_ai.provider.name"])print("server.address on the span:", call.attributes["server.address"])print("server.port on the span:", call.attributes["server.port"])print("input count on the span:", fmt_int(call.attributes["gen_ai.usage.input_tokens"]))print("output count on the span:", fmt_int(call.attributes["gen_ai.usage.output_tokens"]))for metric in metrics: print(f"metric {metric.name}, unit {metric.unit.strip('{}')}, data points: {len(metric.data.data_points)}")types = {p.attributes["gen_ai.token.type"] for m in metrics if m.name == "gen_ai.client.token.usage" for p in m.data.data_points}print("token types on the usage metric:", ", ".join(sorted(types)))# The call is a child of the message's span, and its usage is the reply's. Every name it makes is in the table.assert call.parent.span_id == root.context.span_idassert (call.attributes["gen_ai.usage.input_tokens"], call.attributes["gen_ai.usage.output_tokens"]) == (    reply.usage.prompt_tokens, reply.usage.completion_tokens)assert {m.name for m in metrics} | set(call.attributes) | {"gen_ai.token.type"} <= set(name_map())
出力python instrumented-chat-call.py
spans in the trace: 2
instrumented span, name: chat qwen3-4b-instruct-2507
instrumented span, kind: CLIENT
instrumented span, scope schema URL: https://opentelemetry.io/schemas/1.37.0
attributes on the span: gen_ai.operation.name, gen_ai.provider.name, gen_ai.request.max_tokens, gen_ai.request.model, gen_ai.request.seed, gen_ai.request.temperature, gen_ai.response.finish_reasons, gen_ai.response.id, gen_ai.response.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, server.address, server.port
gen_ai.provider.name on the span: openai
server.address on the span: localhost
server.port on the span: 8000
input count on the span: 142
output count on the span: 6
metric gen_ai.client.operation.duration, unit s, data points: 1
metric gen_ai.client.token.usage, unit token, data points: 2
token types on the usage metric: input, output

第2026.11.2版でopenai 3.56.0 から 3.57.0 へから更新された。

The run sends one route request through the openai client: the route call for the dev day's first message, which load_messages(...)[0] replays. The client does not reach a model. Its HTTP exchange is a recording, served by the mock transport of httpx from lib/http_replay.py. The transport answers every request, so no socket opens even though the URL names the model server. The recorded server sends usage only on a non-streamed reply, so the recording keeps that reply, and a span takes its token counts from usage. The run also patches the time_ns in the SDK's trace module, which the package's spans take their times from, so the call's span gets the virtual times the replay gives. Replay and the virtual clock explains the rest. The package's duration metrics are not patched, and what the package emits says why.

The trace holds 2 spans: the message's root, invoke_agent ambrewick-assistant, and the call. The package marks the call CLIENT, as the book marks its own model calls, because the model runs behind a server. The call's span is named chat qwen3-4b-instruct-2507, the operation followed by the model, which is the registry's pattern for an inference span.

The call's usage reads 142 input tokens and 6 output tokens. These are the usage counts the llama-cpp-python server reported in its reply, which the package copied onto the span. They are not the book's recorded counts, which re-tokenize the prompt. The attribute's name, gen_ai.usage.input_tokens, says what the value counts, not where it came from.

The book's code makes only the root; the package makes the call's span inside it. The script asserts that the call's parent is the root, and that its two usage counts equal the reply's, so a change in either fails the run.

Working rule: Wrap the client once, at start-up, and make your own spans only for work the library cannot see, such as the message's root, its tool calls and its fallback reply. When no package wraps a client, or the one that does writes names the table can't map, make the call's span by hand, as chapter 1 did. Then check the call's parent in a test, as the script does, because the parent is what places the call in its message's trace.

パッケージが出力するもの

このパッケージは、呼び出しごとに1つのスパンを書き出す。スパンの名前は操作とモデルから付けられ、出力にはそのスパンの属性名が並べ替えた順に一覧される。本書が読むのは gen_ai.operation.name、gen_ai.provider.name、gen_ai.request.model、gen_ai.response.model、gen_ai.response.finish_reasons、gen_ai.usage.input_tokens、gen_ai.usage.output_tokens、server.address、server.port である。プロバイダの値は openai である。これは、第2章が openai クライアントについて本書独自のスパンに与えた値と同じである。

本書独自のスパンとの違いが1つ、この一覧に表れている。内容である。プロンプトも応答も保持する属性はない。内容の取得が無効になっているからである。このスイッチが何であり、既定値が何かについては、取得スイッチで述べている。このパッケージは、クライアントのベース URL から server.port を取り出す。ポートが暗黙の場合や443の場合は、その属性を省く(1.3b0 では opentelemetry/instrumentation/genai/openai/utils.py)。

この呼び出しは2つのメトリクスを作り、出力にはその名前、単位、データポイント数が示される。秒単位の gen_ai.client.operation.duration のデータポイントは 1 個である。トークン単位の gen_ai.client.token.usage のデータポイントは 2 個で、入力用と出力用が1つずつある。ポイントは gen_ai.token.type で分けられる。これは、以前の規約でこの区分に使われていた名前である。opentelemetry-semantic-conventions 0.66b2 では今も非推奨の定数として残っており、v0.1.0 でこれが2つのトークンヒストグラムに置き換えられた。この章で「メトリクス」と「ヒストグラム」は、パッケージの計測器だけを指す。どちらも第6章で定義する。

ストリーミングの呼び出しでは、計測器が gen_ai.client.operation.time_to_first_chunk と gen_ai.client.operation.time_per_output_chunk の2つ、スパン属性が gen_ai.response.time_to_first_chunk の1つ加わる。この章の例はストリーミングを行わないので、出力にはこれらのどれも現れない。名前の表には3つのストリーム名がすべて載っている。これらは、ジェネレーターが組み立てたストリーム応答から観測したものである。その経緯は、手作りのスパンと計装されたスパンの比較で説明している。

この章が各計測器の名前、単位、データポイント数だけを出力し、値を出力しないのには理由がある。パッケージはスパンの時刻を、スクリプトがパッチを当てた時計から取る。しかし、所要時間とチャンクの計測器は単調増加タイマーを読み、パッチはこれに届かない。したがって、それらの値は記録を行ったマシンの実際の所要時間であり、実行のたびに変わる。トークンの値は応答の使用量なので固定されている。すべての計測器を同じ形式で出力するため、トークンの値も件数として出力している。

実践ルール: パッケージのスパンと計測器の数をテストで数え、各名前、単位、データポイント数を出力から読み取る。タイマーをテストで制御できない計測器の値は、アサートしてはならない。件数は実行のたびに成り立つが、値は成り立たないからである。

手作りのスパンと計装済みスパンの比較

第2章では本書自身のスパンをレジストリと照合した。本節では、同じ方法でパッケージを測定する。名前はパッケージの出力から観測したものである。v0.1.0 との対応づけは本書の判断であり、ジェネレータ examples/data/genai/build_names_map.py に一度だけ記述し、レジストリと照合してある。出力は、記録した呼び出し、ストリームが加える名前のためにジェネレータが組み立てたストリーミング応答、そしてイベント名を得るためにコンテンツイベントを有効にした呼び出しから得た。1件だけは、実行ではなくパッケージのソースから得ている。gen_ai.usage.cache_read.input_tokens である。パッケージはこれを、応答にキャッシュ済みのプロンプトトークンが含まれる場合にのみ書き込むが、記録した応答にはそれが含まれない。

diff-hand-and-instrumented.py Python 3.13.16 · numpy 2.5.5 合格
"""The names the official package emits, set against the GenAI conventions v0.1.0 names this book uses. The table isexamples/lib/names_map.py, which examples/data/genai/build_names_map.py writes by running the package on the recordedcall, on a streamed reply it constructs (for the names a stream adds) and on a call with content events on (for theevent's name). The point rests onthe last printed count: five names differ from v0.1.0, and each one is named here. instrumented-chat-call checks thatthe names a live call makes are in the same table."""from lib.names_map import REGISTRY_VERSION, name_map          # lib first: threads and seeds are fixed before anything elsefrom importlib.metadata import versiontable = name_map()def status(name, targets):    """Same when the name is its own v0.1.0 name, or the chat span's type; the two named exceptions get their own    labels, and the rest are renamed, split or absent."""    if targets == (name,) or (name == "chat {model}" and targets == ("gen_ai.client.inference",)):        return "same"    if name == "gen_ai.client.operation.duration":        return "wrong instrument for inference"    if name == "gen_ai.token.type":        return "replaced by the two token histograms"    if not targets:        return "no v0.1.0 name"    return "split into two" if len(targets) == 2 else "renamed"statuses = {name: status(name, targets) for name, targets in table.items()}print("registry version:", REGISTRY_VERSION)print("package version:", version("opentelemetry-instrumentation-genai-openai"))print("names the package emits, in the table:", len(table))print("names the same in v0.1.0:", sum(value == "same" for value in statuses.values()))for name in sorted(table):    if statuses[name] != "same":        print(f"{statuses[name]}, {name}:", " and ".join(table[name]) or "none")print("names that differ from v0.1.0:", sum(value != "same" for value in statuses.values()))assert {name for name, value in statuses.items() if value != "same"} == {    "gen_ai.client.operation.duration", "gen_ai.client.token.usage", "gen_ai.client.operation.time_to_first_chunk",    "gen_ai.client.operation.time_per_output_chunk", "gen_ai.token.type"}
出力python diff-hand-and-instrumented.py
registry version: 0.1.0
package version: 1.3b0
names the package emits, in the table: 25
names the same in v0.1.0: 20
wrong instrument for inference, gen_ai.client.operation.duration: gen_ai.client.inference.duration
renamed, gen_ai.client.operation.time_per_output_chunk: gen_ai.client.inference.time_per_output_chunk
renamed, gen_ai.client.operation.time_to_first_chunk: gen_ai.client.inference.time_to_first_chunk
split into two, gen_ai.client.token.usage: gen_ai.client.inference.operation.input_tokens and gen_ai.client.inference.operation.output_tokens
replaced by the two token histograms, gen_ai.token.type: none
names that differ from v0.1.0: 5
演習 3.1

削除された名前が none と出力される理由

+10 件の検証

出力では、gen_ai.token.type の行は none で終わっているが、gen_ai.client.token.usage の行には二つの名前が列挙されている。none は何によって説明されるか。

削除された名前が none と出力される理由:正しい説明を選ぶ
Python 3.13.16 で実行される

表には、パッケージが出力する名前が 25 個ある。そのうち 20 個は v0.1.0 と同じであり、5 個が異なる。異なる5個は、それぞれ v0.1.0 で何になったかとともに示してある。

5個の相違のうち4個はメトリクスにある。レジストリのメトリクスファイルには、推論に対して gen_ai.client.operation.duration を報告してはならない(SHOULD NOT)と書かれており、推論の所要時間の名前は gen_ai.client.inference.duration とされている。分かれ方が特徴的なのはトークンのメトリクスである。パッケージは gen_ai.token.type というデータポイント属性を持つ1つのヒストグラムを書くが、レジストリには入力用と出力用の2つのヒストグラムがある。5個目の gen_ai.token.type は、この分割に対して以前の規約が与えていた名前であり、v0.1.0 では2つのトークンヒストグラムに置き換えられた。そのため、レジストリに基づいて書いたクエリでは、この名前でパッケージの入力ポイントを選択できない。

第2章で本書自身のスパンをレジストリと照合したので、この表にある相違はすべてパッケージ側に属する。この表は、第6章と第7章でパッケージの出力を読むときに使うものである。最初の使用箇所は、第6章の totals-from-metrics-not-spans と第7章の time-to-first-chunk である。

実践ルール: パッケージが出力する名前の表を1つ保持する。表はパッケージの出力から生成してレジストリと照合し、パッケージのデータはこの表を通して読む。表にない名前に対するクエリは、本書の例と同様にテストで失敗させ、本番で何も返さない状態にしてはならない。表は、グラフが静かになったときではなく、パッケージのバージョンが変わったときに再生成する。

openai という名前の三つのパッケージ

openai という名前を持ち、クライアントを計装するパッケージは三つある。これらは名前と内容(コンテンツ)の扱いが異なる。PyPI での表記による名前は、opentelemetry-instrumentation-genai-openai、opentelemetry-instrumentation-openai-v2、opentelemetry-instrumentation-openai である。最初の二つは OpenTelemetry のパッケージであり、三つ目は Traceloop のパッケージである。ここでインストールしているのは最初の一つだけで、バージョンはピン留めファイルが保持するものである。残りの二つはインストールもピン留めもしていない。そのため本節では、表に示すバージョンと日付の公開済み wheel を読み、実行はしない。これらのバージョンを文章として書くのは、そのためである。ピン留めファイルはそれらを保持せず、どの例も出力しない。

three-openai-packages.py Python 3.13.16 · 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 合格
"""Three packages called openai instrument the client, and they disagree on names and on content. Two are OpenTelemetry'sand differ in naming scheme; the third is Traceloop's and captures content by default. Only the first is installed in thepinned environment, so the point rests on that one: its version is printed, and the module that reads its content switchnames the switch the table gives. The other two are not importable here, so their names and defaults are the sourcereadings the chapter cites, printed as wheel readings and not as runs."""import lib  # lib first: threads and seeds are fixed before anything elseimport importlib.utilfrom importlib.metadata import version# Name as PyPI spells it; the module it imports; its project; the naming its source gives; its content switch and that# switch's default, both from the source reading in notes/research/client-library-instrumentation.md (S2, S6, S7).PACKAGES = (    ("opentelemetry-instrumentation-genai-openai", "opentelemetry.instrumentation.genai.openai", "OpenTelemetry",     "GenAI conventions, latest experimental, unconditionally", "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",     "NO_CONTENT"),    ("opentelemetry-instrumentation-openai-v2", "opentelemetry.instrumentation.openai_v2", "OpenTelemetry",     "GenAI conventions v1.30.0 unless the experimental opt-in is set", "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",     "false"),    ("opentelemetry-instrumentation-openai", "opentelemetry.instrumentation.openai", "Traceloop",     "its own names, from opentelemetry-semantic-conventions-ai 0.5.1", "TRACELOOP_TRACE_CONTENT", "true"),)installed = [row for row in PACKAGES if importlib.util.find_spec(row[1]) is not None]assert [row[0] for row in installed] == ["opentelemetry-instrumentation-genai-openai"]source = importlib.util.find_spec("opentelemetry.util.genai.utils").originassert installed[0][4] in open(source, encoding="utf-8").read()     # the module that reads the switch names itprint("packages importable in this environment:", len(installed))print("installed version:", version(installed[0][0]))for name, module, project, naming, switch, default in PACKAGES:    print(f"{name}, evidence:", "installed source" if name == installed[0][0] else "wheel reading")    print(f"{name}, project:", project)    print(f"{name}, naming:", naming)    print(f"{name}, content switch:", switch)    print(f"{name}, content switch default:", default)
出力python three-openai-packages.py
packages importable in this environment: 1
installed version: 1.3b0
opentelemetry-instrumentation-genai-openai, evidence: installed source
opentelemetry-instrumentation-genai-openai, project: OpenTelemetry
opentelemetry-instrumentation-genai-openai, naming: GenAI conventions, latest experimental, unconditionally
opentelemetry-instrumentation-genai-openai, content switch: OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT
opentelemetry-instrumentation-genai-openai, content switch default: NO_CONTENT
opentelemetry-instrumentation-openai-v2, evidence: wheel reading
opentelemetry-instrumentation-openai-v2, project: OpenTelemetry
opentelemetry-instrumentation-openai-v2, naming: GenAI conventions v1.30.0 unless the experimental opt-in is set
opentelemetry-instrumentation-openai-v2, content switch: OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT
opentelemetry-instrumentation-openai-v2, content switch default: false
opentelemetry-instrumentation-openai, evidence: wheel reading
opentelemetry-instrumentation-openai, project: Traceloop
opentelemetry-instrumentation-openai, naming: its own names, from opentelemetry-semantic-conventions-ai 0.5.1
opentelemetry-instrumentation-openai, content switch: TRACELOOP_TRACE_CONTENT
opentelemetry-instrumentation-openai, content switch default: true
演習 3.2

Traceloop のコンテンツ既定値を修正する

+10 件の検証

21行目は、Traceloop のパッケージにおけるコンテンツスイッチの既定値を誤った値で示している。表示されている既定値が、この節でそのパッケージについて示している値になるように、その行を修正する。

     "GenAI conventions v1.30.0 unless the experimental opt-in is set", "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",     "false"),    ("opentelemetry-instrumentation-openai", "opentelemetry.instrumentation.openai", "Traceloop",)installed = [row for row in PACKAGES if importlib.util.find_spec(row[1]) is not None]assert [row[0] for row in installed] == ["opentelemetry-instrumentation-genai-openai"]
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 で実行される
演習 3.3

二つのデフォルト値が異なる理由

+10 件の検証

出力では、Traceloop の行のコンテンツスイッチのデフォルトは true であり、最初のパッケージのデフォルトは NO_CONTENT である。この二つのデフォルトはなぜ異なるのか。

二つのデフォルト値が異なる理由:正しい説明を選ぶ
Python 3.13.16 で実行される

出力には、各パッケージのプロジェクト、命名、内容の切り替えとその既定値が示される。さらに、それらの行がインストール済みのソースから得たものか、wheel を読んで得たものかも、パッケージごとに示される。スクリプトは、切り替えを読むモジュールである opentelemetry.util.genai.utils が、最初のパッケージの切り替えを名指ししていることを検査する。

パッケージ、バージョン、日付 プロジェクト 命名 内容の切り替えと既定値
opentelemetry-instrumentation-genai-openai、1.3b0、2026年10月23日 OpenTelemetry GenAI 規約、実験的なセット OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT、NO_CONTENT
opentelemetry-instrumentation-openai-v2、2.4b0、2026年5月1日 OpenTelemetry オプトインしない限り GenAI 規約 v1.30.0 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT、false
opentelemetry-instrumentation-openai、0.63.1、2026年11月16日 Traceloop 独自の名前(opentelemetry-semantic-conventions-ai 0.5.1 に由来) TRACELOOP_TRACE_CONTENT、true

最初のパッケージのページは、そのバージョンをプレリリースと呼び、説明には "The latest experimental features may introduce breaking changes in future releases." とある。ページはまた、オプトインもバージョン指定もなく、実験的な GenAI 規約を無条件に使うと述べている。ページは規約のバージョンを示していないが、スコープは https://opentelemetry.io/schemas/1.37.0 を刻印しており、これは本書の 1.45.0 と並ぶ。最初のパッケージについて表が規約のバージョンを示さないのは、パッケージ自身が何も述べていないからである。前の節では、本書が従うバージョンである v0.1.0 に照らしてこのパッケージを測定している。

二つ目のパッケージは、既定では古い命名を保ち、その切り替えには二つの意味がある。従来の経路では、変数は true を取り、既定値は false である。実験的な経路では、変数は span_only、event_only、span_and_event を取る。どちらの意味が適用されるかは実験的なオプトインに依存する。そのためチームは、変数を設定する前に、パッケージのバージョンとオプトインをあわせて確認する。二つの OpenTelemetry パッケージは同じ変数を異なる値で読むので、二つ目から移行して true を維持したチームは、最初のパッケージから NO_CONTENT を得ることになり、ログに警告が出るだけである。

Traceloop のパッケージは、スパンに操作とモデルではなく openai.chat という名前を付け、既定でプロンプトと応答をスパンに書き込む。その切り替えは TRACELOOP_TRACE_CONTENT であり、false に設定されない限りオンのままである。true、1、yes、on 以外の値はすべてオフにし、コンテキスト値 override_enable_content_tracing が再びオンにする。これは OpenTelemetry のパッケージとは逆であり、本章で最も重要な違いである。非公開のテキストをモデルに送るサービスに Traceloop のパッケージを追加したチームは、テレメトリが保持する内容を変えたことになるが、そのために変数を一つも設定していない。

本書では最初のパッケージを用いる。ピン留めが保持するのはこれであり、その名前は、前の節の五つの違いを除いて、レジストリの名前である。二つ目を選ぶのは、古い名前だけを読むバックエンドの場合に限り、三つ目を選ぶのは、そのプロジェクトが定義する名前が必要な場合に限る。どちらを選ぶ場合も、ピン留めしたバージョンで内容の切り替えを読む必要があり、明示した目的のために誰かがオンにしない限り、内容の取得はオフにしておく。

実践ルール: 各計装パッケージの内容の切り替えとその既定値は、仕様だけではなく、ピン留めしたバージョンのそのパッケージ自身のソースまたはドキュメントから読むこと。既定値はパッケージごとに異なるので、二つ目のパッケージを追加したサービスは、テレメトリが保持しうる内容を変えることになる。

キャプチャスイッチ

コンテンツキャプチャとは、プロンプトと応答そのものを記録するための、インストルメンテーションのスイッチである。設定しない限りオフであり、その値は NO_CONTENT である。最初のパッケージの既定値は NO_CONTENT で、2番目のパッケージの既定値は false である。Traceloop の 0.63.1 の wheel はこれをオンにする(Three packages called openai)。

GenAI 規約 v0.1.0 の spans のページは、このスイッチの名前を OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT としなければならない(MUST)と定めている。最初のパッケージはこの MUST から外れている。このパッケージが読むのは別の変数 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT であり、仕様の名前はどこでも読まない。次の実行は、その結果を示す。仕様の名前を SPAN_ONLY に設定して1回呼び出しを行う。続いて、対照として、パッケージ自身の名前で同じことを行い、それぞれの呼び出しのスパンが保持するコンテンツ属性の数を数える。

capture-switch-names.py Python 3.13.16 · httpx 0.28.1 · mcp 2.3.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 合格
"""The content switch: whether the official package's span holds the prompt and the reply. The package reads one variable,and the spec's name for the same switch is read nowhere in the package. The point rests on three counts. With the spec'sname set to SPAN_ONLY, one call's span holds no content. With the package's own name set to SPAN_ONLY, a control call'sspan holds two, so the count can rise and the package does read its name. And the package's parser gives NO_CONTENT whenits variable is unset and when it holds a value that is not a mode. The control records content for one call, and thisexample prints only how many content attributes that span holds, never their values."""import lib  # lib first: threads and seeds are fixed before anything elseimport osimport opentelemetry.sdk.trace as sdk_tracefrom opentelemetry.instrumentation.genai.openai import OpenAIInstrumentorfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterfrom opentelemetry.util.genai.utils import ContentCapturingMode, get_content_capturing_modefrom lib.assistant import RELEASESfrom lib.case import load_messagesfrom lib.clock import VirtualClockfrom lib.http_replay import client, route_bodyfrom lib.ids import SequentialIdsfrom lib.tracing import make_providerPACKAGE_VARIABLE = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"SPEC_VARIABLE = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT"print("the package reads:", PACKAGE_VARIABLE, "| the spec's name for the switch:", SPEC_VARIABLE)print("values the package parses:", ", ".join(mode.name for mode in ContentCapturingMode))os.environ.pop(PACKAGE_VARIABLE, None)print("mode, package variable unset:", get_content_capturing_mode().name)os.environ[PACKAGE_VARIABLE] = "not a mode"                   # the parser logs this and falls back, it does not raiseprint("mode, value that is not a mode:", get_content_capturing_mode().name)os.environ.pop(PACKAGE_VARIABLE)# Instrument afresh with the variable set to SPAN_ONLY, make one call, and print how many content attributes its span# holds. The package reads its mode when it is instrumented, so the variable is set before that and removed after.def content_attributes(variable: str, label: str, expected: int) -> None:    os.environ[variable] = "SPAN_ONLY"    clock = VirtualClock("2026-12-07")    sdk_trace.time_ns = lambda: clock.advance(1_000_000)      # virtual span times, as in instrumented-chat-call    exporter = InMemorySpanExporter()    provider = make_provider("ambrewick-assistant", RELEASES["r0"].service_version, "example", clock, SequentialIds(),                             exporter, "https://opentelemetry.io/schemas/1.45.0")    instrumentor = OpenAIInstrumentor()    instrumentor.instrument(tracer_provider=provider)    client().chat.completions.create(**route_body(load_messages("2026-12-07")[0]))    instrumentor.uninstrument()    os.environ.pop(variable)    call = exporter.get_finished_spans()[0]    count = len([key for key in call.attributes if key.startswith(("gen_ai.input.messages", "gen_ai.output.messages"))])    print(f"content attributes on the span, {label}:", count)    assert count == expectedcontent_attributes(SPEC_VARIABLE, "spec variable set", 0)     # set, and read by nothing in the packagecontent_attributes(PACKAGE_VARIABLE, "package variable set", 2)   # the control: the package's own name, one call
出力python capture-switch-names.py
the package reads: OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT | the spec's name for the switch: OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT
values the package parses: NO_CONTENT, SPAN_ONLY, EVENT_ONLY, SPAN_AND_EVENT
mode, package variable unset: NO_CONTENT
mode, value that is not a mode: NO_CONTENT
content attributes on the span, spec variable set: 0
content attributes on the span, package variable set: 2

第2026.11.2版でopenai 3.56.0 から 3.57.0 へから更新された。

演習 3.4

パッケージに小文字のモード名を読み取らせる

+10 件の検証

29行目と30行目は、パッケージの変数にモードではない値を設定し、そのモードをラベル付きで出力している。この2行を変更し、パッケージの変数が小文字のモード名を保持するようにして、行をラベル 'mode, lower-case value:' の下に出力させる。これにより、この例は示された出力を表示する。

print("values the package parses:", ", ".join(mode.name for mode in ContentCapturingMode))os.environ.pop(PACKAGE_VARIABLE, None)print("mode, package variable unset:", get_content_capturing_mode().name)os.environ.pop(PACKAGE_VARIABLE)

得られるべき出力

the package reads: OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT | the spec's name for the switch: OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT
values the package parses: NO_CONTENT, SPAN_ONLY, EVENT_ONLY, SPAN_AND_EVENT
mode, package variable unset: NO_CONTENT
mode, lower-case value: SPAN_ONLY
content attributes on the span, spec variable set: 0
content attributes on the span, package variable set: 2
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 で実行される
演習 3.5

仕様の名前ではコンテンツが得られない理由

+10 件の検証

出力を見ると、仕様の名前で行った呼び出しではコンテンツ属性が 0 個であり、パッケージ自身の名前で行った呼び出しでは 2 個である。最初の結果を説明するのはどれか。

仕様の名前ではコンテンツが得られない理由:正しい説明を選ぶ
Python 3.13.16 で実行される

要点は2つの数の差である。仕様の名前ではコンテンツ属性が 0 個になり、パッケージ自身の名前では 2 個になる。この差を報告するものは何もない。仕様の名前を設定したチームが得るのは、何も設定しなかった場合と同じ出力であり、これが防ぐべき失敗である。この失敗は表に現れず、プロンプトを求められて1件も見つからないときまで、成功しているように見える。

このパッケージが解釈する値は、NO_CONTENT、SPAN_ONLY、EVENT_ONLY、SPAN_AND_EVENT の4つである。1.3b0 のパッケージのソース(opentelemetry/util/genai/utils.py)は、モードと照合する前に値を大文字に変換するので、照合では大文字と小文字が区別されない。それ以外の値の場合は、警告をログに出して NO_CONTENT を返す。出力は2つのフォールバックの両方を示している。パッケージの変数が未設定のとき、モードは NO_CONTENT である。モードではない値のときは NO_CONTENT である。

12章の What leaks when capture is on では、4つのモードのそれぞれが何を書き込み、何が漏れるのかを述べる。ここでは対照として1回の呼び出しでコンテンツを記録するが、その例が出力するのは、スパンが保持するコンテンツ属性の数だけである。この章の他のすべての例はキャプチャをオフにして実行する。本書は、12章が明示した目的のためにオンにするまで、キャプチャをオフのままにする。

2つ目のスイッチ OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK は、コンテンツをファイルにアップロードし、そのファイルへの参照を書き込むことができる。パッケージはこれらの参照を gen_ai.input.messages_ref と gen_ai.output.messages_ref として書き込む。これらはレジストリの名前であり、ドット区切りで綴っているのはインストルメンテーションの docstring だけである。この章のどの実行も、どちらも出力しない。フックには OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH の設定も必要であり、ここではどの実行もそれを設定していないからである。フックは12章で扱う。

実践ルール: パッケージのコンテンツ変数は、固定したバージョンでそのパッケージ自身のソースが読む名前で設定する。その設定はテストで確認し、変数が記録を行うモードを指しているとき、かつそのときに限りスパンがコンテンツを保持することを、そのテストで検証する。目的を定めていないサービスでは、コンテンツキャプチャをオフのままにする。また、サービスが読み込むすべてのパッケージの既定値を確認する。

ほかの二つの命名体系

GenAI 規約と同じ事実を記述する命名体系が、ほかに二つある。一つは Arize が公開する OpenInference であり、クライアント用の第四のパッケージとして独自の openinference-instrumentation-openai パッケージを持つ(OpenInference)。もう一つは Traceloop のパッケージの基になっているプロジェクトの OpenLLMetry である。両者の名前に出会った読者が、それが何を表すかを分かるように、ここで両方を説明する。本書はどちらも出力しない。

OpenInference のモジュールは、固定されたバージョン 0.1.46 において、モデル、プロバイダ、トークン数、スパン種別、メッセージを、それぞれ独自の定数で命名している。スクリプトはそれらの定数を読み取り、同じ事実を表す GenAI の名前の横に一つずつ設定する。

openinference-mapping.py Python 3.13.16 · numpy 2.5.5 · openinference-semantic-conventions 0.1.46 合格
"""OpenInference, a naming scheme the book does not emit, at its pinned version. Its module names the facts a model callcarries (the model, the provider, the token counts, the span kind, the messages) in its own words. The point rests onthe table: each name is one the pinned module defines, and each maps to a GenAI conventions name the book's registry orits name table holds. The mapping is written here by hand, and checked against both."""import lib  # lib first: threads and seeds are fixed before anything elsefrom importlib.metadata import versionfrom openinference.semconv.trace import OpenInferenceLLMSystemValues, OpenInferenceSpanKindValues, SpanAttributesfrom lib import genaifrom lib.names_map import NAMES# OpenInference's constant and the GenAI name for the same fact. OpenInference's span kind has no GenAI attribute: the# operation name carries the same meaning, chat for a model call.MAPPING = (    (SpanAttributes.LLM_MODEL_NAME, "gen_ai.request.model"),    (SpanAttributes.LLM_SYSTEM, "gen_ai.provider.name"),    (SpanAttributes.LLM_TOKEN_COUNT_PROMPT, "gen_ai.usage.input_tokens"),    (SpanAttributes.LLM_TOKEN_COUNT_COMPLETION, "gen_ai.usage.output_tokens"),    (SpanAttributes.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ, "gen_ai.usage.cache_read.input_tokens"),    (SpanAttributes.OPENINFERENCE_SPAN_KIND, "gen_ai.operation.name"),    (SpanAttributes.LLM_INPUT_MESSAGES, "gen_ai.input.messages"),    (SpanAttributes.LLM_OUTPUT_MESSAGES, "gen_ai.output.messages"),)known = set(genai.ATTR) | {name for names in NAMES.values() for name in names}print("openinference-semantic-conventions version:", version("openinference-semantic-conventions"))for openinference, conventions in MAPPING:    print(f"{openinference} -> {conventions}")    assert conventions in knownprint("span kind for a model call:", OpenInferenceSpanKindValues.LLM.value)print(f"{SpanAttributes.LLM_SYSTEM} for an OpenAI client:", OpenInferenceLLMSystemValues.OPENAI.value)
出力python openinference-mapping.py
openinference-semantic-conventions version: 0.1.46
llm.model_name -> gen_ai.request.model
llm.system -> gen_ai.provider.name
llm.token_count.prompt -> gen_ai.usage.input_tokens
llm.token_count.completion -> gen_ai.usage.output_tokens
llm.token_count.prompt_details.cache_read -> gen_ai.usage.cache_read.input_tokens
openinference.span.kind -> gen_ai.operation.name
llm.input_messages -> gen_ai.input.messages
llm.output_messages -> gen_ai.output.messages
span kind for a model call: LLM
llm.system for an OpenAI client: openai

この例は各 OpenInference の名前を対応する GenAI の名前の横に出力し、実行時にすべての組を名前表と照合する。そのため、次にバージョンを固定し直したときに移動する定数があれば、実行は失敗する。読者が最初に目にする組はトークン数であり、llm.token_count.prompt は gen_ai.usage.input_tokens に、llm.token_count.completion は gen_ai.usage.output_tokens に対応する。

スクリプトは、各 GenAI の名前が本書の名前表に含まれていることを表明する。したがって、存在しない名前を指す対応付けがあれば、実行は失敗する。OpenInference のスパン種別に当たる GenAI の属性は単独では存在しない。出力は、モデル呼び出しが OpenInference では LLM であることを記録し、GenAI の名前では操作名が同じ意味を chat として担う。OpenAI のプロバイダ値は openai であり、これは最初の OpenTelemetry パッケージが openai クライアントに対して書き込む文字列と同じである。

OpenLLMetry の名前は、2026 年 3 月 26 日にリリースされたバージョン 0.5.1 の opentelemetry-semantic-conventions-ai に由来し、Traceloop の 0.63.1 パッケージがこれを使う。これらの読み取りに関する注意は、openai という名の三つのパッケージにある。OpenLLMetry の名前のうち四つには、同じ役割を果たすレジストリの名前がある。gen_ai.client.operation.duration に対するレジストリの名前は gen_ai.client.inference.duration、入力と出力のヒストグラムに対する gen_ai.client.token.usage、gen_ai.usage.cache_creation.input_tokens に対する gen_ai.usage.cache_write.input_tokens、gen_ai.usage.reasoning_tokens に対する gen_ai.usage.reasoning.output_tokens である。

本書では全体を通じて OpenTelemetry の名前を推奨する。第 5 章ほかの事例で説明するバックエンドは、これらの名前を取り込むとしており、それぞれの主張にはバージョンと日付を添えて示してある。別の体系を選ぶのは、運用中のバックエンドがその体系しか読み取らない場合に限る。一つのトレースに複数の体系を混在させてはならない。gen_ai.usage.input_tokens を対象にしたクエリは llm.token_count.prompt を書き込むスパンを見つけられず、合計は少なく出るが、それを知らせるエラーは出ない。

実践ルール: 各体系の名前をレジストリの名前へ対応付ける作業は、コード内の表として一度だけ行い、表にない名前があれば実行を失敗させる。上の対応付けの例がそうしている。サービスのスパンに使う体系は、最初のスパンを送信する前に一つ選び、ほかの体系の名前をそのトレースに入れない。

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

What goes wrong in production

Four things go wrong with the package in production.

  • The pre-release. The first package is at a pre-release version, and its page warns that its experimental features may change without notice. The pin holds one version. A team that upgrades takes whatever names the next release writes, so the name table must be regenerated, and the run must fail on a name it does not hold.
  • The switch in the wrong place. The spec's name does nothing with this package, and no error says so. The opposite mistake is worse. A team that adds Traceloop's package and sets nothing has turned prompt capture on, because that package's default is on, in its 0.63.1 wheel, and a context override can turn it back on even when the variable is false.
  • Dashboards on the registry's names. A chart that reads gen_ai.client.inference.duration from this package finds no points, since the package writes gen_ai.client.operation.duration. The earlier section lists each name that differs.
  • Two packages on one client. A service that loads a second instrumentation package for the same client may write each call's span twice, under two sets of names. No example here loads two, so this is not shown; a test that counts spans per call would show it.

この章で行った決定

パッケージの命名は標準に遅れる。以下の各決定は、本書がその遅れとどのように付き合うかを示している。

  • モデル呼び出しは 1.3b0 に固定した OpenTelemetry のパッケージでラップし、本書独自のスパンは、そのパッケージが見ることのできない処理だけをラップする。
  • パッケージがレジストリとは異なる形で書き出す五つの名前は、生成した対応表で一度だけ対応付ける。本書のそれ以降の部分は、その表を通してパッケージの出力を読む。
  • この章のすべての例で、コンテンツの取得は無効にしてある。例外は一つの対照例だけで、これは一回の呼び出しについてコンテンツを記録し、その件数だけを出力する。第12章ではこれを意図して有効にし、何が漏れるかを述べる。
  • メトリクスは名前、単位、データ点の数で出力し、値では出力しない。期間を測る計器が実時間を使うためである。
  • 本書が OpenTelemetry の名前を使うのは、第5章のバックエンドが取り込めると述べている名前だからである。そのため、バックエンドを変更することは、スパンの変更ではなく設定の変更で済む。
  • 三つのパッケージ名は正確に示すが、実行するのは最初の一つだけである。残りの二つは、三つのパッケージについての節で説明するとおり、wheel の読み取りによるものである。

実践ルール: インストルメンテーションのパッケージは正確なバージョンに固定し、その名前の対応表はパッケージ自身の出力から生成し、スパンが保持するコンテンツを信頼する前に、そのバージョンのソースからコンテンツの切り替えを読むこと。パッケージが名前や既定値を変えると、トレースに保持される内容が変わる。それを知らせる手がかりとなるのが、パッケージのバージョンと、そのスコープのスキーマ URL である。

この版における本章

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

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

Labs を開始

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

料金を見る

この節を引用する

形式

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

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

このページの内容

全12章中の第3章: クライアントライブラリにコール計装を任せる

  1. A call through the client
  2. パッケージが出力するもの
  3. 手作りのスパンと計装済みスパンの比較
  4. openai という名前の三つのパッケージ
  5. キャプチャスイッチ
  6. ほかの二つの命名体系
  7. What goes wrong in production
  8. この章で行った決定

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