讓用戶端函式庫為呼叫加上埋點

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

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

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

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

Labs

透過實作學習本章

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

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

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

正在檢查您的時數…

正在尋找您的 Lab…

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

讀完本章後,你能讀懂官方 OpenAI 埋點在一次聊天呼叫中寫出的內容,說明其中哪些名稱與本書所採用的 GenAI 慣例版本 0.1.0 不同,並指出決定是否記錄提示與回覆的變數及其預設值。第 1 章以手寫方式建立了模型 span。第 2 章〈依標準的方式命名 span〉為這些 span 採用了標準的名稱。本章要探討的是:函式庫能否代為寫出這些 span,以及它寫出的 span 在哪些地方有所不同。

Ambrewick 的助理透過 openai 用戶端函式庫呼叫其模型,而這個函式庫有一些套件可以包裝用戶端,並為每次呼叫寫出一個 span。在第 1 章中,只有模型呼叫是有記錄時間的步驟,因此,若有套件能正確寫出這些 span,本書就能省下大部分手工建立的 span。若套件寫出的內容不同,則本章之後各章的每個查詢都會受到影響,因為那些章節要讀取這些名稱。問題相當具體:對於一次真實的呼叫,這個套件會輸出什麼?它與本書手寫的內容又有哪些差異?

此部分尚未翻譯,因此以英文呈現。

A call through the client

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

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.

套件會輸出什麼

這個套件對每次呼叫寫入一個 span,span 以操作與模型命名,輸出則依排序列出該 span 上的屬性名稱。本書會讀取的屬性有 gen_ai.operation.name、gen_ai.provider.name、gen_ai.request.model、gen_ai.response.model、gen_ai.response.finish_reasons、gen_ai.usage.input_tokens、gen_ai.usage.output_tokens、server.address 與 server.port。provider 的值是 openai,也就是第 2 章為本書自有 span 針對 openai 用戶端所給的值。

從這份清單可以看出與本書自有 span 的一項差異:內容。沒有任何屬性存放提示詞或回覆,因為內容擷取是關閉的。擷取開關說明該開關是什麼,以及它的預設值。套件從用戶端的基底 URL 取得 server.port,若該連接埠是隱含的或是 443,則省略不記(opentelemetry/instrumentation/genai/openai/utils.py,版本 1.3b0)。

這次呼叫會產生兩個指標,輸出列出它們的名稱、單位與資料點數量。gen_ai.client.operation.duration 以秒為單位,有 1 個資料點。gen_ai.client.token.usage 以 token 為單位,有 2 個資料點,一個對應輸入,一個對應輸出。這些資料點以 gen_ai.token.type 區分,這是較舊慣例對此區分所用的名稱。它在 opentelemetry-semantic-conventions 0.66b2 中仍是已棄用的常數,而 v0.1.0 以兩個 token 直方圖取代了它。在本章中,「指標」與「直方圖」僅指該套件的量測工具。第 6 章會定義這兩者。

串流呼叫會再增加兩個量測工具 gen_ai.client.operation.time_to_first_chunk 與 gen_ai.client.operation.time_per_output_chunk,以及一個 span 屬性 gen_ai.response.time_to_first_chunk。本章的範例不使用串流,因此輸出不會印出其中任何一項。名稱表收錄了這三個串流名稱,它們是產生器從自己建構的串流回覆中觀察到的,如手工建立的 span 與已插入檢測的 span 對照所說明。

本章只印出每個量測工具的名稱、單位與資料點數量,而不印出任何數值,原因只有一個。套件的 span 時間取自腳本所修補的時鐘,但它的持續時間與區塊量測工具讀取的是單調計時器,修補並不會影響到它。因此這些值是錄製機器的真實計時,每次執行都會改變。token 的值是固定的,因為它們是回覆的用量,並且以數量形式印出,使每個量測工具的印出方式一致。

**實用原則:**在測試中計算套件的 span 與量測工具的數量,並從其輸出讀取每個名稱、單位與資料點數量。不要對計時器不受測試控制的量測工具斷言數值,因為數量在每次執行都成立,而數值並非如此。

手工建立的 span 與插裝產生的 span 之比較

第 2 章依註冊表檢查了本書自己的 span,本節以同樣的方式衡量該套件。這些名稱是從套件的輸出中觀察得到的,與 v0.1.0 之間的對應則是本書的判斷,已一次寫在產生器 examples/data/genai/build_names_map.py 中,並依註冊表檢查過。輸出來自三個來源:已錄製的呼叫、由產生器為串流新增的名稱而建構的串流回覆,以及開啟內容事件的呼叫,後者提供了事件的名稱。有一個項目來自套件的原始碼,而非來自實際執行:gen_ai.usage.cache_read.input_tokens。套件只有在回覆帶有已快取的提示 token 時才會寫入它,而已錄製的回覆都沒有這類 token。

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 個不同。五個不同的名稱,每一個都附上它在 v0.1.0 中改成了什麼。

五項差異中有四項出現在指標方面。註冊表的指標檔案指出,推論不應(SHOULD NOT)回報 gen_ai.client.operation.duration,並將推論耗時命名為 gen_ai.client.inference.duration。token 指標是分歧的一項:套件寫入的是一個帶有 gen_ai.token.type 資料點屬性的直方圖,而註冊表則有兩個直方圖,分別對應輸入與輸出。第五項 gen_ai.token.type 是較早的慣例為這種區分所取的名稱,v0.1.0 已將它換成兩個 token 直方圖,因此依註冊表所寫的查詢無法用它選出套件的輸入資料點。

由於第 2 章已依註冊表檢查過本書自己的 span,此表中的每一處落差都屬於該套件。第 6 章與第 7 章在讀取套件的輸出時,用的就是這張表。最先用到它的是第 6 章的 totals-from-metrics-not-spans 與第 7 章的 time-to-first-chunk。

實用原則: 維護一張套件所發出名稱的表,由其輸出產生並依註冊表檢查,然後透過它來讀取該套件的資料。對表中沒有的名稱發出查詢,應當在測試中失敗,就像本書的範例那樣,而不是在正式環境中什麼也沒回傳。請在套件版本變更時重新產生這張表,而不是等到圖表沒了動靜才做。

三個名為 openai 的套件

三個名為 openai 的套件都能為用戶端加上檢測(instrumentation),它們在名稱與內容處理上各有不同。依 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 慣例,沒有選擇加入的機制,也沒有指明版本。頁面並未指名慣例的版本,但檢測範圍(scope)所標記的是 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 的套件將其 span 命名為 openai.chat,而不是以操作與模型命名,並且預設把提示(prompt)與補全內容(completion)寫入 span 中。它的開關是 TRACELOOP_TRACE_CONTENT,除非有人將其設為 false,否則一直保持開啟。除了 true、1、yes 或 on 之外,任何值都會將它關閉,而情境值(context value)override_enable_content_tracing 則會再次將它開啟。這與 OpenTelemetry 套件的做法正好相反,也是本章最重要的差異。若團隊將 Traceloop 的套件加入一個會把私人文字送往模型的服務,其遙測資料所含的內容就已改變,而團隊並未為此設定任何變數。

本書採用第一個套件。它是固定檔所記錄的套件,其名稱與登錄表一致,僅有前面的一節所述的五項差異。只有在後端僅能讀取較舊名稱時,我們才會選擇第二個套件;只有在需要該專案自行定義的名稱時,才會選擇第三個。無論選哪一個,都須依所固定的版本讀取其內容開關,並且除非有人為了明確說明的目的而開啟,否則應關閉內容擷取。

實用原則: 請依你所固定的版本,從各檢測套件自己的原始碼或文件讀取其內容開關與預設值,不要只依規格判斷。各套件的預設值不同,因此服務一旦加入第二個套件,其遙測資料所能包含的內容就會改變。

內容擷取開關

內容擷取是插裝(instrumentation)用來記錄提示詞與回覆本身的開關,若未設定,預設為關閉,即 NO_CONTENT。第一個套件的預設值是 NO_CONTENT,第二個套件的預設值是 false;Traceloop 的 0.63.1 wheel 則會將它開啟(Three packages called openai)。

GenAI conventions v0.1.0 的 spans 頁面規定,這個開關 MUST 命名為 OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT,而第一個套件違反了這項 MUST。它讀取的是另一個變數 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT,並且完全不讀取規範所用的名稱。下一次執行會顯示這樣做的後果。它先將規範的名稱設為 SPAN_ONLY 並進行一次呼叫,接著以套件自己的名稱做相同的事作為對照,並計算每次呼叫的 span 所含的內容屬性數量。

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 行將套件的變數設為一個不是模式的值,並在某個標籤下印出模式。請修改這兩行,使套件變數保存小寫的模式名稱,並讓該行以標籤 '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 上執行

重點在於兩個數量之間的差異:使用規範的名稱時,內容屬性有 0 個,而使用套件自己的名稱時則有 2 個,而且沒有任何訊息回報這項差異。團隊若設定了規範的名稱,得到的輸出會與完全沒有設定時相同,而這正是需要防範的失敗。它悄然發生,看起來像是成功,直到有人要查看某個提示詞卻發現一筆也沒有。

這個套件會解析四個值:NO_CONTENT、SPAN_ONLY、EVENT_ONLY 與 SPAN_AND_EVENT。套件在 1.3b0 的原始碼(opentelemetry/util/genai/utils.py)會先將值轉為大寫,再比對模式,因此比對時不分大小寫。對於其他任何值,它會記錄一則警告並回傳 NO_CONTENT。輸出顯示了這兩種退回行為。套件的變數未設定時,模式為 NO_CONTENT。值不是任何模式時,則為 NO_CONTENT。

第 12 章的 What leaks when capture is on 說明了四種模式各自會寫入與洩漏什麼。這裡有一次呼叫會記錄內容作為對照,而該範例只會印出其 span 含有多少個內容屬性。本章其他所有範例都在關閉擷取的情況下執行,本書也會一直保持關閉,直到第 12 章為了明確說明的目的才將它開啟。

第二個開關 OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK 可以將內容上傳到檔案,並寫入指向這些檔案的參照。套件將這些參照寫成 gen_ai.input.messages_ref 與 gen_ai.output.messages_ref,這是登錄表(registry)中的名稱;只有插裝的 docstring 以點號拼寫它們。本章沒有任何一次執行會產生這兩者,因為這個 hook 還需要設定 OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH,而這裡沒有任何一次執行設定它。第 12 章會介紹這個 hook。

實用原則: 依套件自己的原始碼所讀取的名稱,在你所固定的版本上設定該套件的內容變數,並以測試檢查這項設定:測試要斷言,當且僅當變數指定的是會記錄內容的模式時,span 才含有內容。對於尚未指明擷取目的的任何服務,請保持內容擷取關閉,並檢視該服務所載入的每個套件的預設值。

另外兩種命名方案

另有兩種命名方案描述的事實與 GenAI 慣例相同:一是 Arize 發布的 OpenInference,它自有 openinference-instrumentation-openai 套件,是用戶端的第四個套件;另一是 OpenLLMetry,也就是 Traceloop 套件背後的專案。我們說明這兩者,是為了讓讀者遇到它們的名稱時,知道這些名稱代表什麼。本書不採用其中任何一種。

OpenInference 的模組在其鎖定版本 0.1.46 中,以自己的常數來命名模型、供應商、token 數量、span 種類與訊息。指令碼會讀取這些常數,並把每一個常數與同一事實的 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 名稱並列印出,執行時也會對照名稱表檢查每一組配對,因此若某個常數在下一次鎖定版本時移動,執行就會失敗。讀者最先遇到的是 token 數量的配對:llm.token_count.prompt 對應 gen_ai.usage.input_tokens,llm.token_count.completion 對應 gen_ai.usage.output_tokens。

指令碼會斷言每個 GenAI 名稱都是本書名稱表所收錄的名稱,因此若對應中出現表內沒有的名稱,執行就會失敗。OpenInference 的 span 種類在 GenAI 中沒有專屬的屬性。輸出記錄了模型呼叫在 OpenInference 中是 LLM,而在 GenAI 名稱中,由操作名稱承載相同的意義,其值為 chat。它的 OpenAI 供應商值是 openai,與第一個 OpenTelemetry 套件為 openai 用戶端寫入的字串相同。

OpenLLMetry 的名稱來自 opentelemetry-semantic-conventions-ai,版本為 0.5.1,發布於 2026 年 3 月 26 日,Traceloop 的 0.63.1 套件使用這個版本。關於這些解讀的注意事項,請見三個名為 openai 的套件。OpenLLMetry 有四個名稱,在登錄表中有功能相同的名稱:gen_ai.client.operation.duration 對應 gen_ai.client.inference.duration,gen_ai.client.token.usage 對應輸入與輸出的直方圖,gen_ai.usage.cache_creation.input_tokens 對應 gen_ai.usage.cache_write.input_tokens,gen_ai.usage.reasoning_tokens 對應 gen_ai.usage.reasoning.output_tokens。

我們建議本書全程採用 OpenTelemetry 的名稱。第 5 章其他系統的做法所描述的後端都表示會接收這些名稱,每項說法在該處都附有版本與日期。只有在你執行的後端只讀取某一種其他方案時,才基於該理由選擇那個方案。不要在同一條追蹤中混用方案。查詢 gen_ai.usage.input_tokens 時,找不到寫入 llm.token_count.prompt 的 span,總計會偏少,卻沒有錯誤提示。

實用原則: 把各方案的名稱一次對應到登錄表的名稱,並以程式碼中的表格實作,凡是表中沒有的名稱就讓執行失敗,如上述對應範例所做的那樣。在送出第一個 span 之前,為服務的 span 選定一種方案,並讓其他方案的名稱不進入其追蹤。

正式環境中會出什麼問題

這個套件在正式環境中會出現四種問題。

  • 預先發行版本。 第一個套件屬於預先發行版本,其頁面警告,實驗性功能可能在不另行通知的情況下變更。固定版本只會鎖定一個版本。若團隊升級,就會採用下一個版本所寫入的任何名稱,因此必須重新產生名稱對照表,而且遇到對照表中沒有的名稱時,執行必須失敗。
  • 開關設在錯誤的位置。 規格中的名稱對這個套件不起作用,也不會有任何錯誤訊息指出這一點。相反的錯誤更嚴重。若團隊加入 Traceloop 的套件卻什麼都不設定,就等於開啟了提示內容的擷取,因為該套件在其 0.63.1 wheel 中的預設值是開啟,而且即使變數為 false,情境覆寫(context override)仍可能將它重新開啟。
  • 儀表板依賴登錄表的名稱。 若圖表從這個套件讀取 gen_ai.client.inference.duration,就會找不到任何資料點,因為這個套件寫入的是 gen_ai.client.operation.duration。前一節列出了每個不同的名稱。
  • 同一個用戶端上有兩個套件。 若服務為同一個用戶端載入第二個插裝套件,每次呼叫的 span 可能會以兩組名稱各寫入一次。這裡沒有任何範例載入兩個套件,因此並未示範這種情況;以每次呼叫計算 span 數量的測試便能顯示這個問題。

本章所做的決定

套件使用的名稱會落後於標準,以下每項決定都說明本書如何因應:

  • 模型呼叫由固定在 1.3b0 版本的 OpenTelemetry 套件包裝,本書自己的 span 只包裝該套件看不到的工作。
  • 套件寫法與登錄表(registry)不同的五個名稱,只在一份產生出來的對照表中對應一次,本書其餘部分都透過這份對照表讀取套件的輸出。
  • 本章所有範例都關閉內容擷取,只有一個對照組例外:它記錄單次呼叫的內容,並且只印出內容的數量。第 12 章會刻意開啟內容擷取,並說明它會洩漏什麼。
  • 指標(metric)只印出名稱、單位與資料點數量,不印出數值,因為其時間長度儀器(duration instrument)使用的是真實時間。
  • 本書採用 OpenTelemetry 的名稱,因為第 5 章中的後端都表示可以擷取這些名稱,所以更換後端只需要更改設定,不必更改 span。
  • 三個套件名稱都會精確列出,但只執行第一個。另外兩個是對 wheel 的檢讀,如三個套件那一節所說明。

實用原則: 將檢測(instrumentation)套件固定在確切的版本,由它自己的輸出產生名稱對照表,並且在相信 span 所含的內容之前,先從該版本的原始碼讀取它的內容開關。套件若更改名稱或預設值,就會改變您的追蹤資料所含的內容,而它的版本與其範圍(scope)的 schema URL,就是您得知這類變更的訊號。

本章,於本版次中

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

譯自英文書,版次 2026.11.2。

開始 Labs

本書仍可免費閱讀。

查看價格

引用本節

格式

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

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

本頁內容

第 3 章,共 12 章: 讓用戶端函式庫為呼叫加上埋點

  1. A call through the client
  2. 套件會輸出什麼
  3. 手工建立的 span 與插裝產生的 span 之比較
  4. 三個名為 openai 的套件
  5. 內容擷取開關
  6. 另外兩種命名方案
  7. 正式環境中會出什麼問題
  8. 本章所做的決定

返回頂端所有章節