클라이언트 라이브러리가 호출을 계측하게 하기

읽는 데 약 33분, 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장에서는 모델 스팬을 직접 작성했다. 2장 "표준이 쓰는 방식으로 스팬 이름 짓기"에서는 그 스팬에 표준의 이름을 붙였다. 이 장에서는 라이브러리가 그 스팬을 대신 작성할 수 있는지, 그리고 라이브러리가 만든 스팬이 어디에서 달라지는지를 묻는다.

앰브루익의 어시스턴트는 openai 클라이언트 라이브러리를 통해 모델을 호출한다. 이 라이브러리에는 클라이언트를 감싸서 호출마다 스팬을 기록하는 패키지가 있다. 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.

패키지가 내보내는 것

패키지는 호출마다 스팬을 하나씩 기록하며, 스팬의 이름은 작업과 모델을 따라 짓는다. 출력에는 그 스팬의 속성 이름이 정렬된 순서로 나열된다. 이 책이 읽는 속성은 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 클라이언트에 대해 이 책의 자체 스팬에 부여한 값과 같다.

이 책의 자체 스팬과 다른 점이 그 목록에 하나 드러나는데, 바로 콘텐츠다. 콘텐츠 캡처가 꺼져 있으므로 프롬프트나 응답을 담은 속성은 없다. 캡처 스위치에서 그 스위치가 무엇이며 기본값이 무엇인지 설명한다. 패키지는 클라이언트의 기본 URL에서 server.port를 가져오며, 포트가 암묵적이거나 443이면 이를 생략한다(1.3b0의 opentelemetry/instrumentation/genai/openai/utils.py).

호출은 두 가지 메트릭을 만들고, 출력에는 그 이름, 단위, 포인트 수가 나온다. 초 단위의 gen_ai.client.operation.duration에는 1개의 데이터 포인트가 있다. 토큰 단위의 gen_ai.client.token.usage에는 2개의 데이터 포인트가 있으며, 하나는 입력용이고 하나는 출력용이다. 포인트는 gen_ai.token.type로 나뉘는데, 이는 이전 규약에서 그 구분을 부르던 이름이다. 이 이름은 opentelemetry-semantic-conventions 0.66b2에서 여전히 사용 중단된 상수로 남아 있으며, v0.1.0에서 두 개의 토큰 히스토그램으로 대체되었다. 이 장에서 "메트릭"과 "히스토그램"은 패키지의 계측기만 가리킨다. 6장에서 두 용어를 모두 정의한다.

스트리밍 호출은 계측기 두 개, 즉 gen_ai.client.operation.time_to_first_chunk와 gen_ai.client.operation.time_per_output_chunk, 그리고 스팬 속성 하나, 즉 gen_ai.response.time_to_first_chunk를 더 추가한다. 이 장의 예제는 스트리밍하지 않으므로 출력에 이 중 어느 것도 나오지 않는다. 이름 표에는 스트림 이름 세 개가 모두 들어 있는데, 생성기가 자신이 만든 스트리밍 응답에서 관찰한 것이다. 이는 직접 만든 스팬과 계측된 스팬의 비교에서 설명한다.

이 장은 각 계측기의 이름, 단위, 포인트 수만 출력하고 값은 출력하지 않는데, 이유는 하나다. 패키지는 스팬 시간을 스크립트가 패치한 시계에서 가져오지만, 지속 시간과 청크 계측기는 패치가 미치지 않는 단조 타이머를 읽는다. 따라서 그 값은 기록하는 기계의 실제 측정 시간이며 실행할 때마다 바뀐다. 토큰 값은 응답의 사용량이므로 고정되어 있고, 모든 계측기가 같은 방식으로 출력되도록 개수로 출력한다.

작업 규칙: 패키지의 스팬과 계측기는 테스트에서 개수를 세고, 각 이름, 단위, 포인트 수는 출력에서 읽는다. 테스트가 타이머를 통제하지 못하는 계측기의 값은 단언하지 않는다. 개수는 매 실행에서 유지되지만 값은 그렇지 않기 때문이다.

직접 만든 스팬과 계측된 스팬 비교

2장에서는 이 책의 스팬을 레지스트리와 대조해 검사했으며, 이 절에서는 같은 방식으로 패키지를 측정한다. 이름은 패키지의 출력에서 관찰한 것이다. v0.1.0과의 대응은 이 책의 판단이며, 생성기 examples/data/genai/build_names_map.py에 한 번 작성되어 레지스트리와 대조해 검사된다. 출력은 기록된 호출, 스트림이 추가하는 이름을 얻으려고 생성기가 만든 스트리밍 응답, 이벤트의 이름을 알려 주는 콘텐츠 이벤트를 켠 호출에서 얻었다. 항목 하나는 실행이 아니라 패키지의 소스에서 가져왔다. 바로 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개는 다르다. 다른 다섯 개에는 각각 v0.1.0에서 무엇이 되었는지가 함께 출력된다.

다섯 가지 차이 가운데 네 가지는 메트릭에 있다. 레지스트리의 메트릭 파일은 추론에 대해 gen_ai.client.operation.duration을 보고해서는 안 되며(SHOULD NOT), 추론 소요 시간의 이름은 gen_ai.client.inference.duration이라고 밝힌다. 토큰 메트릭은 둘로 갈라지는 경우다. 패키지는 gen_ai.token.type 데이터 포인트 속성을 가진 히스토그램 하나를 쓰지만, 레지스트리에는 입력용과 출력용 히스토그램 두 개가 있다. 다섯 번째인 gen_ai.token.type은 이전 규약이 이 구분에 붙인 이름이다. v0.1.0은 이를 두 토큰 히스토그램으로 대체했으므로, 레지스트리를 보고 작성한 쿼리는 이 이름으로 패키지의 입력 포인트를 선택할 수 없다.

2장에서 이 책의 스팬을 레지스트리와 대조해 검사했으므로, 이 표의 모든 차이는 패키지에 속한다. 이 표는 6장과 7장에서 패키지의 출력을 읽을 때 사용한다. 처음 쓰이는 곳은 6장의 totals-from-metrics-not-spans와 7장의 time-to-first-chunk이다.

작업 규칙: 패키지가 내보내는 이름의 표를 하나 두고, 이를 패키지의 출력에서 생성해 레지스트리와 대조해 검사한 뒤, 패키지의 데이터는 그 표를 통해 읽는다. 표에 없는 이름을 조회하는 쿼리는 운영 환경에서 아무것도 반환하지 않는 대신, 이 책의 예제가 실패하듯 테스트에서 실패해야 한다. 표는 차트가 조용해질 때가 아니라 패키지의 버전이 바뀔 때 다시 생성한다.

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에서 실행된다

출력에는 각 패키지의 프로젝트, 이름 짓기 방식, 콘텐츠 스위치와 그 기본값이 나온다. 또 각 패키지에 대해 이 내용이 설치된 소스에서 나왔는지 휠을 읽은 결과인지도 표시한다. 스크립트는 스위치를 읽는 모듈인 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 규약을 무조건 사용한다고 밝힌다. 페이지는 규약 버전을 밝히지 않지만, 스코프에는 이 책의 1.45.0과 나란히 https://opentelemetry.io/schemas/1.37.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이고 두 번째 패키지의 기본값은 false이다. Traceloop의 0.63.1 wheel은 이 스위치를 켠다(Three packages called openai).

GenAI 규약 v0.1.0의 스팬 문서는 이 스위치의 이름이 반드시 OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT여야 한다(MUST)고 규정하는데, 첫 번째 패키지는 이 MUST를 따르지 않는다. 이 패키지는 다른 변수인 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT를 읽으며, 명세의 이름은 어디에서도 읽지 않는다. 다음 실행은 그 결과를 보여 준다. 명세의 이름을 SPAN_ONLY로 설정하고 호출을 한 번 수행한다. 이어서 대조군으로 패키지 자체의 이름을 사용해 같은 작업을 수행하고, 각 호출의 스팬이 가진 콘텐츠 속성의 수를 센다.

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은 네 가지 모드가 각각 무엇을 기록하고 무엇을 유출하는지 설명한다. 여기서는 대조군으로 한 번의 호출이 콘텐츠를 기록하며, 그 예제는 스팬이 가진 콘텐츠 속성의 수만 출력한다. 이 장의 다른 모든 예제는 캡처를 끈 상태로 실행되며, 12장에서 명시된 목적을 위해 켜기 전까지 이 책은 캡처를 꺼 둔다.

두 번째 스위치인 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 패키지를 따로 가지고 있다. 다른 하나는 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일에 공개된 opentelemetry-semantic-conventions-ai 0.5.1 버전에서 가져온 것이며, 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를 기록한 스팬을 찾지 못하므로, 합계가 적게 나오는데도 이를 알려 주는 오류는 나타나지 않는다.

작업 규칙: 각 체계의 이름을 레지스트리의 이름에 한 번만 대응시키되, 코드 안의 표로 작성한다. 표에 없는 이름이 나오면 위의 매핑 예제처럼 실행을 실패시킨다. 서비스의 스팬에 쓸 체계는 첫 스팬을 보내기 전에 하나로 정하고, 다른 체계의 이름은 그 트레이스에 넣지 않는다.

운영 환경에서 발생하는 문제

운영 환경에서 이 패키지에는 네 가지 문제가 생긴다.

  • 프리릴리스. 첫 패키지는 프리릴리스 버전이며, 패키지 페이지는 실험적 기능이 예고 없이 바뀔 수 있다고 경고한다. 버전 고정은 한 버전만 유지한다. 업그레이드하는 팀은 다음 릴리스가 쓰는 이름을 그대로 받아들이게 되므로, 이름 표를 다시 생성해야 하고, 표에 없는 이름이 나오면 실행이 실패해야 한다.
  • 엉뚱한 곳에 둔 스위치. 명세에 있는 이름은 이 패키지에서 아무 효과가 없으며, 이를 알려 주는 오류도 없다. 반대의 실수는 더 나쁘다. Traceloop의 패키지를 추가하고 아무것도 설정하지 않은 팀은 프롬프트 캡처를 켠 셈이 된다. 그 패키지의 기본값이 0.63.1 wheel에서 켜짐이기 때문이며, 변수가 false여도 컨텍스트 재정의로 다시 켜질 수 있다.
  • 레지스트리의 이름에 기댄 대시보드. 이 패키지에서 gen_ai.client.inference.duration을(를) 읽는 차트에는 데이터 포인트가 없다. 이 패키지는 gen_ai.client.operation.duration을(를) 기록하기 때문이다. 앞선 절에 이름이 다른 항목이 모두 나와 있다.
  • 한 클라이언트에 패키지 둘. 같은 클라이언트에 대해 계측 패키지를 하나 더 로드하는 서비스는 각 호출의 스팬을 서로 다른 두 이름 체계로 두 번 기록할 수 있다. 이 책의 예제에는 둘을 로드하는 것이 없으므로 이 현상은 보이지 않는다. 호출당 스팬 수를 세는 테스트라면 이를 보여 줄 것이다.

이 장이 내린 결정

패키지가 쓰는 이름은 표준보다 늦게 따라가므로, 아래의 각 결정은 이 책이 그 차이를 어떻게 다루는지 밝힌다.

  • 모델 호출은 1.3b0에 고정한 OpenTelemetry 패키지가 감싸고, 이 책이 직접 만든 스팬은 패키지가 볼 수 없는 작업만 감싼다.
  • 패키지가 레지스트리와 다르게 쓰는 다섯 가지 이름은 생성된 표 하나에 한 번만 대응시키고, 책의 나머지 부분은 그 표를 거쳐 패키지의 출력을 읽는다.
  • 이 장의 모든 예제에서 콘텐츠 캡처는 꺼 둔다. 예외는 한 번의 호출에 대해서만 콘텐츠를 기록하고 그 개수만 출력하는 대조 예제 하나다. 12장에서는 의도적으로 이를 켜고, 무엇이 유출되는지 설명한다.
  • 메트릭은 이름, 단위, 포인트 수로만 출력하고 값은 출력하지 않는다. 지속 시간 계측기가 실제 시간을 사용하기 때문이다.
  • 이 책이 OpenTelemetry 이름을 사용하는 까닭은 5장의 백엔드들이 이 이름을 수집한다고 밝히고 있기 때문이며, 그래서 백엔드를 바꾸는 일은 스팬의 변경이 아니라 설정의 변경이 된다.
  • 세 패키지의 이름은 정확하게 제시하며, 그중 첫 번째만 실행한다. 나머지 둘은 세 패키지에 관한 절에서 설명하듯이 휠을 읽어 확인한 내용이다.

작업 규칙: 계측 패키지는 정확한 버전으로 고정하고, 이름 표는 그 패키지 자신의 출력에서 생성하며, 스팬에 담긴 콘텐츠를 신뢰하기 전에 해당 버전의 소스에서 콘텐츠 스위치를 읽어라. 패키지가 이름이나 기본값을 바꾸면 트레이스에 담기는 내용이 바뀌며, 패키지의 버전과 그 스코프의 스키마 URL이 바뀌었음을 알려 주는 신호가 된다.

이 판의 이 장

2026.11.2판예제 통과 2026년 11월 235 of 5개 예제 in this chapter pass

영어판 2026.11.2판을 번역한 것이다.

Labs 시작

도서는 계속 무료로 읽을 수 있다.

요금 보기

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 3장: 클라이언트 라이브러리가 호출을 계측하게 하기

  1. A call through the client
  2. 패키지가 내보내는 것
  3. 직접 만든 스팬과 계측된 스팬 비교
  4. openai라는 이름의 패키지 세 개
  5. 콘텐츠 캡처 스위치
  6. 다른 두 가지 이름 체계
  7. 운영 환경에서 발생하는 문제
  8. 이 장이 내린 결정

맨 위로 돌아가기전체 장