11A.1 Tracing and Observability for LLM Applications
A classic web service fails loudly: a 500, a timeout, a stack trace. An LLM feature fails quietly — it returns HTTP 200 with a fluent, confident, wrong answer; it burns twelve times the expected tokens on a retry loop; it leaks a customer's invoice into a log line shipped to a third-party dashboard. None of the tools you already know catch that, because none of them were built for a system whose outputs are non-deterministic, whose inputs are natural language, whose unit of cost is a token, and whose "correct" is a judgement call rather than an exception. This lesson is the complete engineering reference for making LLM systems observable: what to record at every layer, how to structure it as traces, spans and attributes, how to instrument with OpenTelemetry and the GenAI semantic conventions, how to choose between instrumentation strategies and observability platforms, how to keep telemetry itself safe, and how to debug production incidents from traces. It builds the tracing core of the module's running project, llm_service, and hands the metrics, dashboards and alerting to 11A.2.
What you'll learn
- Why LLM observability is a different discipline from classic APM: non-determinism, prompts as code, token-priced calls, multi-step chains and agents, quality failures that aren't errors, and sensitive content inside telemetry
- The observability stack for LLM apps: traces, metrics and logs plus evals and user feedback as the fourth leg — and which problems each one actually solves
- Exactly what to capture per model call and per request: the full field list, mapped onto the token, cost and logging conventions from 03.7 and 03.10
- Span taxonomies for plain calls, RAG pipelines and agents — what the root span is, which stages deserve their own spans, and which fields belong on each
- OpenTelemetry for GenAI, completely: the pipeline (SDK → span processors → exporters → collector → backend), the current status of the GenAI semantic conventions, manual instrumentation of a real client, context propagation across async code and service boundaries, and head vs tail sampling
- What a well-formed GenAI span looks like: the
gen_ai.operation.namevalues, span names and kinds, requirement levels, normalised token usage, content capture modes, and the trace shape of tool, single-agent, multi-agent and hand-off runs, with a mini tracer and a linter you can run offline (3.7 to 3.13) - Auto-instrumentation: the official
opentelemetry-instrumentation-genai-*packages, Traceloop/OpenLLMetry, OpenInference, provider-native tracing, and what each is good for as of November 2026 - The instrumentation trade-off: proxy-based (Helicone-style), SDK-wrapper-based, and OTel-based — lock-in, completeness, latency overhead and failure modes
- How to build a telemetry exporter that can never break a request: fail-open, bounded queue, timeouts, dropping under pressure — full code
- The observability platform landscape as of November 2026: Langfuse, LangSmith, Arize Phoenix, Pydantic Logfire, Datadog Agent Observability, Helicone, Braintrust, W&B Weave, OpenLIT, Opik, and the APM vendors' LLM features — with a verified comparison table and a decision flow
- How to send spans to Langfuse and Arize Phoenix over OTLP (endpoints, headers, protocols), how OpenInference differs from the GenAI conventions, how to choose between tools by constraints, and how DeepEval span types line up with GenAI operations so one trace serves monitoring and evaluation (5.5 to 5.11)
- Sessions, users and conversations: grouping traces into sessions, attaching feedback, annotation workflows, turning production traces into eval datasets, and replaying a trace locally
- Privacy-safe telemetry: what never to log, redaction before export, content capture as opt-in, retention, access control, hashed identifiers, regional storage and DPAs
- Cost attribution: tracing tokens to features, tenants and prompt versions; unit economics (cost per request, per user, per resolved ticket); budgets and anomaly detection
- A debugging playbook for the failures that only traces reveal — slow requests, wrong answers, tool loops, retry storms, cost spikes — and a complete trace viewer/CLI you can run today
What you don't need
- API keys. Every part has something concrete you can do without one: pure-Python tracing, a JSONL trace store, a viewer and summariser that run on files you generate yourself, mock-server instrumentation, and reading outputs you supply. The provider- and platform-facing samples are labelled illustrative.
- A running observability backend. Parts that show Langfuse, Phoenix or OTel Collector setups are reference code you can run later; the concepts and the data model are the deliverable.
- Metrics, dashboards, SLOs and alerting design. 11A.2 owns those; this lesson produces the traces and cost records they consume and shows where the boundary falls.
- Security architecture. Module 12 owns threat modelling, guardrails and data-protection policy; this lesson covers only what telemetry itself must not leak.
Setup
The pure-local parts of this lesson need nothing but Python 3.11+ and the standard library. The instrumentation parts use the module's provider SDKs plus OpenTelemetry packages. Lessons 03.1–03.11 share one project folder, llm-apis; the Modules 11A to 11C running project is llm_service (a FastAPI app built across those modules — this lesson adds its tracing layer). Create it once:
uv init llm-service --bare --python 3.13 && cd llm-serviceThen add the packages this lesson uses (package names only; this space moves monthly, so you get whatever is newest when you install):
# OTel core: SDK, OTLP HTTP exporter (traces/metrics/logs over http/protobuf, port 4318)
uv add opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
# Official GenAI auto-instrumentation (BETA as of Nov 2026 — see 3.4)
uv add opentelemetry-instrumentation-genai-openai \
opentelemetry-instrumentation-genai-anthropic
# Optional: one observability platform SDK per part that uses it
uv add langfuse arize-phoenix \
openinference-instrumentation-openai \
traceloop-sdk logfireThe samples were written and checked against opentelemetry-sdk and opentelemetry-exporter-otlp-proto-http 1.45.2, the beta opentelemetry-instrumentation-genai-openai and -anthropic 1.3b0, langfuse 5.2.0, arize-phoenix 21.0.0, openinference-instrumentation-openai 0.1.69, traceloop-sdk 0.62.4 and logfire 5.5.0, all as of November 2026. A plain install gives you the newest release of each. The GenAI instrumentation packages are beta and the OpenTelemetry GenAI attribute names are still in development, so if a span attribute or an instrumentor class differs from the lesson, check that package's release notes (3.4 says more); the stdlib tracer built in this lesson is unaffected.
The .env file holds keys and backend endpoints where used:
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=... # optional
OPENROUTER_API_KEY=... # optional gateway
# Where telemetry goes (examples in Parts 3 and 5)
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
LANGFUSE_PUBLIC_KEY=...
LANGFUSE_SECRET_KEY=...
LANGFUSE_BASE_URL=https://cloud.langfuse.com # or your self-hosted URL
PHOENIX_ENDPOINT=http://localhost:6006 # read by this lesson's code in 5.4; Phoenix's own register() helper reads PHOENIX_COLLECTOR_ENDPOINT (see 5.6)Samples that call a hosted provider are labelled illustrative; samples marked "run for real" use only the standard library and produce real output you can reproduce.
What you must be able to do after this lesson#
- Explain why error rate and latency cannot detect a wrong answer that returns HTTP 200
- List the fields to capture per model call, including model_requested versus model_resolved and the token columns
- Design a span tree for a plain call, a RAG request and an agent run
- Build a telemetry exporter that is fail-open, with a bounded queue and timeouts
- Name what must never be logged by default and the safe alternative for each
- Turn a production trace into an eval case and compute cost per resolved outcome
- Pick the first query to run for a slow, wrong, looping, retry-storm or cost-spike trace
Why this matters for an AI engineer#
Every row of this table is a promise an earlier lesson made to this one — and a production failure waiting to happen:
| You'll hear... | You'll understand it after... |
|---|---|
| "The bot gave a wrong answer yesterday — can you find the exact request?" | Part 2: what to capture |
| "Why is this trace 40 seconds? Which stage was slow?" | 2.4 Span taxonomy, Part 9 |
| "We're sending full prompts to the observability vendor — is that OK?" | Part 7: privacy-safe telemetry |
| "The eval score dropped but nobody changed the prompt." | 6.3 Traces become eval cases |
| "Which feature is costing us money this month?" | Part 8: cost attribution |
| "Langfuse or LangSmith or just Datadog?" | Part 5: platforms |
| "Why does the sub-agent show up inside the tool span?" / "Is that span kind CLIENT or INTERNAL?" | 3.7 span kinds, 3.11 trace shapes |
"Is input_tokens with or without the cache?" |
3.10 normalising token usage |
| "Just point the OTLP exporter at Langfuse (or Phoenix)." | 5.6 sending spans over OTLP |
| "Can the same trace feed our monitoring and our evals?" | 5.11 DeepEval spans and GenAI spans |
| "The OTel GenAI conventions keep changing — should we build on them?" | 3.2 The conventions' status |
| "Telemetry added 300ms to every request." | 4.2 The safe exporter |
| "The agent looped nine times before the budget stopped it." | 9.1 The debugging playbook |
| "Users rate answers thumbs-down — where does that feedback go?" | Part 6: sessions and feedback |
Part 1: Why LLM observability is a different discipline#
1.1 What classic APM assumes — and why each assumption breaks#
Application performance monitoring (APM) matured on systems with three properties LLM applications don't have:
| APM assumption | Why it breaks for LLM apps |
|---|---|
| Deterministic behaviour. Same input → same output, so a replay reproduces the bug | Sampling parameters, provider-side model updates and non-deterministic decoding mean the same request can produce different answers. You can't "re-run prod" — you can only inspect what happened |
| Errors are exceptions. A failure throws, returns 5xx, or trips a health check | The most expensive failures return HTTP 200 with plausible wrong text (03.8, Part 10 catalogues 200s that aren't successes). A wrong answer, a refusal, a truncated reply and a safety block are all "successful" HTTP responses |
| Latency is milliseconds and CPU-bound. A span of 40ms is an eternity; p99 is the tail | One model call takes seconds to minutes; a RAG request fans out to an embedder, a vector store, a reranker and the model; an agent run can make dozens of sequential calls. Inter-token latency, time-to-first-token and queueing behind provider rate limits all matter |
| Payloads are small and structured. Logging a request body is cheap | Prompts and completions are large, semi-structured, and frequently contain PII, secrets and licensed documents. Telemetry volume is dominated by content, which is exactly what you can least afford to leak |
| Cost is infrastructure. You pay for CPU-hours; a request's marginal cost is ~0 | Every call has a metered cost in tokens, priced differently by token type (uncached input, cached reads/writes, output, reasoning) and by provider and tier. Cost is a first-class telemetry field, not an invoice line item |
| One request = one service hop. Traces follow HTTP calls between your services | The interesting "hops" are often inside one process: retrieve → rerank → generate → tool → generate. And provider-side retries, fallbacks and prompt caching are invisible unless you record them |
| Quality = correctness of code. If the code ran, it worked | The model can follow your code perfectly and still produce a bad answer. Quality is an eval question (Module 10A), and the signals that approximate it online — feedback, judges, citation coverage, abstention rates — are telemetry of a different kind |
1.2 What actually goes wrong in production#
The failure gallery below is not hypothetical — each row is a real incident pattern, and each one is invisible to classic monitoring:
| Failure | What the dashboards show | What the trace reveals |
|---|---|---|
| Wrong answer from stale retrieval | 200 OK, latency normal | The retrieve span returned chunks from a superseded index version; index_version attribute differs from expected |
| Silent quality regression after a provider model update | Error rate flat | model_resolved attribute changed (gpt-6-luna → gpt-6-luna-2026-09-22 snapshot); eval-linked traces show the score drop |
| Cost spike | Bill arrives at month end | One feature's uncached_input_tokens p95 tripled after a prompt edit removed the cacheable prefix; prefix fingerprint changed |
| Agent tool loop | Request "succeeds" slowly | Nine tool_call spans with identical arguments; steps counter and policy_decision attributes show the loop |
| Retry storm amplifying an outage | Your error rate looks worse than the provider's | attempts attribute > 1 on every span; child spans show exponential backoff colliding across tenants |
| PII in telemetry | Nobody notices until a breach report | gen_ai.input.messages content attribute shipped user emails to a SaaS backend with a 30-day retention |
| Truncated answers billed as success | Finish-reason mix shifts | finish_reason=max_output_tokens on 12% of calls — paid-for answers users can't use (03.7, 5.1) |
| Cardinality bomb in attributes | Dashboards fine; the backend bill and UI crawl | user_hash, request_id and query text recorded as span attribute values — millions of distinct values; the backend's attribute index and your invoice explode |
| Orphaned spans from broken async context | "Traces look weird", trees won't render | asyncio.create_task called outside the with span() block → child spans arrive with no parent_span_id (or a stale trace_id); the backend shows flat orphan roots |
The common thread: every one of these is a telemetry problem before it's an engineering problem. You cannot fix what you cannot see, and for LLM systems "see" means more than status codes and durations.
1.3 The observability stack: three pillars plus a fourth leg#
Classic observability rests on three pillars — metrics (aggregated numbers over time), logs (discrete events), and traces (causal trees of work). LLM systems need all three and a fourth:
flowchart TB
subgraph pillars ["The observability stack for LLM apps"]
T["TRACES<br/>one request end-to-end:<br/>spans, attributes, timing, cost"]
M["METRICS<br/>rates, percentiles, token & cost counters"]
L["LOGS<br/>structured events, audit trail, debug detail"]
E["EVALS + FEEDBACK<br/>quality signals: judges, golden sets,<br/>thumbs up/down, review queues"]
end
T --> Q["Answers: WHERE did it break,<br/>WHAT did it cost, HOW slow"]
M --> Q
L --> Q
E --> Q2["Answers: WAS it good,<br/>IS it getting worse"]| Pillar | Answers | Owns it in this module |
|---|---|---|
| Traces | Where did time go? Which stage failed? What did the model see and emit? What did it cost? | This lesson (data model, instrumentation, platforms) |
| Metrics | How is the service doing now? Error rate, p95 latency, tokens/sec, cost/day, cache hit rate | 11A.2 |
| Logs | What exactly happened at this instant? Audit and compliance records | 03.10 built the logging kit; this lesson extends it into traces |
| Evals + feedback | Was the answer good? Is quality drifting? Which real failures become test cases? | Module 10A owns eval methodology; this lesson covers the production feedback loop |
The fourth leg matters because the other three measure operations, not quality. A trace can show a perfectly executed pipeline that produced a hallucinated answer. Evals and feedback are how quality enters the observability picture — and Module 10A showed the key convergence: a production trace is a candidate eval case, and an eval failure is a trace you can inspect (07.9 makes the same point for RAG).
1.4 What "observability" means here, precisely#
Observability is the property of a system where you can answer new questions about its behaviour from the telemetry it emits — questions you didn't anticipate when you wrote the instrumentation. It's the opposite of monitoring, which answers only the questions you pre-defined ("is error rate > 1%?"). The practical test: when a user reports "the invoice extractor gave a wrong total yesterday at 14:32", can you reconstruct that exact request — its prompt version, retrieved chunks, model snapshot, token counts and output — from telemetry alone? If yes, the system is observable. Everything in this lesson exists to make that answer yes.
Part 2: The observability data model — what to capture#
2.1 The primitives: traces, spans, attributes, events, resources#
Everything in this lesson is built from five nouns. Learn them once and every platform and library below is just a different rendering of the same model:
| Primitive | What it is | LLM example |
|---|---|---|
| Trace | One end-to-end unit of work — one user request, one agent run, one batch job. Has a trace_id |
POST /ask for ticket #4471; one invoice-extraction job |
| Span | One timed operation inside a trace, with a start, an end, a name, a status and attributes. Spans nest into a tree | retrieve, rerank, generate, tool_call:lookup_order |
| Attribute | A key-value pair on a span (or resource): gen_ai.request.model="gpt-6-luna", feature="support-bot" |
The fields of 2.2 and 2.3 |
| Event | A point-in-time marker on a span (no duration): "first token received", "retry attempt 2", "user stopped reading" | ttft moment, finish_reason determination |
| Resource | Attributes describing the thing emitting telemetry — service name, version, environment, SDK versions | service.name="llm_service", service.version="1.4.2", deployment.environment="prod" |
Two properties matter more than the definitions:
- The trace is the unit of debugging. One request → one trace → a tree of spans you can read top-down. When 07.10's
PipelineTraceserialises to JSON, that is a trace record — this lesson generalises it beyond RAG. - Attributes are where the cost and quality live. A span's duration tells you when; its attributes tell you what it was for: which model, which prompt version, which tenant, how many tokens, what it cost, whether it was retried. Design attributes like a schema, because every dashboard, alert and eval join keys off them.
2.2 What to capture per LLM call#
One model call produces one span (or one log record, before you have tracing). These fields come straight from conventions already established in this module — do not invent new names:
| Field | Source / convention | Answers |
|---|---|---|
trace_id, span_id, parent_span_id |
Your tracing layer (W3C trace context) | "Show me the whole request" / "which stage spawned this call" |
provider, api |
Adapter (03.11) | "OpenAI Responses or Anthropic Messages? Which quirks apply?" |
model_requested, model_resolved |
Request config + response model/model_version |
"Did an alias move? Did a fallback fire? Which snapshot served?" |
request_id |
Provider response ID (x-request-id, request-id, x-generation-id, Gemini response_id) |
"What do we tell provider support?" |
prompt_name, prompt_version, prompt_sha256 |
04.10's PromptSpec | "Which prompt produced this? Did the text change without a version bump?" |
params |
Generation config actually sent (max tokens, reasoning effort, structured-output schema id) | "What settings produced this output?" |
input_summary, output_summary |
Lengths, hashes, redacted excerpts — never raw content by default (2.6) | "Same prompt as before? Roughly how big?" |
uncached_input_tokens, cached_input_tokens, cache_write_tokens, total_input_tokens, output_tokens, reasoning_tokens |
The module convention (03.7, 3.1, 03.10, 4.1) | "What did it consume? Is caching working? What did reasoning cost?" |
cost_usd, cost_source, price_version |
03.7's cost_calc.price() |
"What did this call cost, and who priced it?" |
latency_ms, ttft_ms, tpot_ms (time per output token) |
Your clock; TTFT only for streams (03.3, Part 12) | "Slow model or slow network? Did the user see tokens quickly?" |
finish_reason, status |
Provider's stop signal; ok/truncated/blocked/error:<Name> |
"Did it finish, get cut off, refuse, or fail?" |
attempts, error_class, error_status, retry_after_ms |
Your retry wrapper (03.8) | "Were retries hiding failures? What failed?" |
tool_calls |
Names + argument hashes (count and names always; args redacted) | "What actions did it propose?" |
retrieval (for RAG) |
hit_count, top_score, index_version, chunk_ids (hashed or scoped) |
"What grounded the answer?" (07.11, 5.1) |
eval_score, feedback |
Module 10A judges, user thumbs | "Was it good?" — attached post-hoc to the trace |
feature, tenant_hash, user_hash, session_id |
Call site + keyed hashes (03.2, 10.3, 03.7, 5.1) | "Which feature/tenant/user drove this?" |
feature_flags, experiment_id, variant |
Your flag system | "Which code path and which A/B arm?" |
sdk_versions |
importlib.metadata |
"Which client versions were running when it broke?" |
The token columns follow the module convention exactly — uncached_input_tokens is what bills at the plain input rate; output_tokens includes reasoning tokens, with reasoning_tokens recorded separately as the informational subset. Mixing conventions across providers is the classic cost-dashboard bug: OpenAI's input_tokens, Anthropic's input_tokens and Gemini's prompt_token_count mean three different things (03.10, 4.1 explains the mapping). Log all six columns; you cannot reconstruct a missing one later.
Usage also reports billable events that are not token columns — web_searches, grounding_searches and per-modality input counts (modality_input), plus the price modifiers tier, geo and regional (03.11, 03.7). They stay out of the six-column schema; when a feature bills them, record them as their own span attributes (llm.web_searches, llm.grounding_searches) — 03.7's cost log already carries the same fields.
Attribute design rules — attributes are indexed and billed by the backend, so treat their values like a schema, not a junk drawer:
- Bounded value sets for anything you'll group, filter or alert on.
feature,finish_reason,outcome,providertake a handful of values — perfect attributes.user_hash,request_id,session_id, query text and prompt excerpts take millions — they belong in logs/events or the content store, never as high-cardinality attribute values (the 1.2 gallery shows the failure). - Redact before you set. An attribute is written the moment
set_attributesruns; there is no "we'll scrub it downstream". Hash or truncate anything identifying (Part 7). - Names are API. Every dashboard, alert and eval join keys off them; renaming
cost_usdtocostsilently empties every panel built on it. Version names (v1) rather than rename when the meaning changes. - Stable across services. The same key must mean the same thing on every span and every service that shares a trace — that's what makes cross-service queries possible (3.6).
2.3 What to capture per request#
A request (one user action, one API call to your service) is the root span. Its attributes are the join keys that make per-request debugging possible:
| Field | Why it's on the root span |
|---|---|
request_id (yours) |
The ID you return to the client and log on every line — the first thing support asks for |
route, method, status_code |
Which endpoint; did it succeed at the HTTP layer |
user_hash, tenant_hash, session_id |
Keyed hashes (HMAC, purpose-scoped — see Part 7), never raw IDs |
feature, experiment_id, variant |
Cost and quality attribution (Part 8) |
prompt_name, prompt_version |
The deployed prompt artefact (04.10) |
total_cost_usd, total_tokens, total_latency_ms |
Rolled up from child spans — the per-request bill and duration |
outcome |
ok, abstained, refused, degraded, error — the business-level result, which no provider reports |
degraded, fallback_used, cache_hit |
Silent quality/cost changes: a fallback answer is "successful" but different |
feedback (post-hoc) |
Thumbs/comment attached after the fact — see Part 6 |
The discipline that makes this work: put the same attribute names on every span at every layer. feature, tenant_hash, prompt_version and model_resolved on the root span and propagated to child spans means any aggregation — "cost by feature", "p95 by tenant", "error rate by prompt version" — works without joins. This is also why 03.11's hook model carries a tags dict on CallContext: validated, scrubbed metadata that flows to every hook for exactly this purpose.
2.4 Span taxonomy for RAG pipelines and agents#
A plain chat call needs one span. A RAG pipeline or agent run needs a tree. The taxonomy below is what 07.11, 5.1 established for RAG and 08A.14, 3.2 for agents — use these names so traces from different features compare cleanly:
flowchart TD
R["root: POST /ask (request span)<br/>feature=docs_qa · tenant_hash=9f2c · outcome=pending"]
R --> A1["authz + scope<br/>2ms · status=ok"]
R --> A2["query_plan<br/>340ms · 410 tok · model=gpt-6-luna"]
A2 --> A3["retrieve<br/>180ms · 24 hits · top_score=0.81 · index=v14"]
A3 --> A4["rerank<br/>95ms · top-8 kept"]
A4 --> A5["sufficiency check<br/>210ms · pass=1"]
A5 --> A6["generate (LLM call)<br/>2.4s · ttft=380ms · in=5.8k out=84 tok · $0.0006"]
A6 --> A7["cite + verify<br/>140ms · 2 citations ok"]
A7 --> A8["cost rollup + log<br/>total=$0.0007 · outcome=ok"]
R2["root: agent run (ticket #4471)<br/>feature=support-agent · steps_budget=12"]
R2 --> B1["model_call #1<br/>in=4.2k · tool_call=lookup_order"]
B1 --> B2["tool:lookup_order<br/>12ms · ok · args_hash=ab12"]
B2 --> B3["model_call #2<br/>in=5.1k · tool_call=issue_refund"]
B3 --> B4["approval gate<br/>pending→approved · 41s · by=ana"]
B4 --> B5["tool:issue_refund<br/>380ms · ok · $84.50"]
B5 --> B6["model_call #3<br/>final answer · 610 tok out"]Naming rules that keep this sane:
- Root span = the request or the run. For a synchronous API call it's the HTTP handler; for an agent it's the run (
agent_run/run); for a batch job it's the job. Everything else nests under it. gen_ai.*attributes on model-call spans; your own names on everything else. The GenAI conventions (3.2) standardisegen_ai.operation.name,gen_ai.request.model,gen_ai.usage.*etc. for the model call itself — butretrieve,rerank,sufficiency,approvalare your stages. 07.11's advice is exactly right: aretrievespan you defined beats a convention that changed under you.- Tool calls are child spans of the model call that proposed them (or siblings under a
toolsgroup — pick one and be consistent; child-of-model-call is what 08A.14's tracer does and it answers "which model call caused this action?"). - Every span gets the request's join keys (
feature,tenant_hash,user_hash,session_id,prompt_version) so any slice of the tree aggregates correctly. - Content is opt-in per span kind. 07.11's table is the model: timings, counts, scores, cost — always; question text, answer text, retrieved chunk text — only in the access-controlled store. Apply the same split to agents: tool names and arg hashes always; arg values only when redacted and scoped.
2.5 Multi-turn conversations and sessions#
A chat feature doesn't produce one trace per message — it produces one trace per turn, and the turns belong together. Two identifiers handle this:
session_id/conversation_id: your stable ID for the conversation (the 03.2 conversation store's ID). Every turn's root span carries it, so "show me this user's whole conversation" is a query, not an archaeology project.turn_index/parent_turn_id: ordering within the session. Useful when a bad answer in turn 5 was caused by context assembled in turn 3.
Sessions are also where feedback attaches: a thumbs-down on turn 5 links to that turn's trace, and ideally propagates a "session health" flag to sibling traces for review sampling (Part 6).
2.6 The JSONL trace record schema#
Before any platform enters the picture, your traces should land in a format you own: JSON Lines — one JSON object per span, append-only, trivially shippable to any log pipeline, queryable with jq or the viewer in Part 9. This is the same choice 03.7 made for cost records ("JSON Lines to a file here; a log pipeline in production") and 03.10 made for call logs. One record per span, in two parts: a fixed envelope (the OTel primitives — ids, name, kind, timing, status) and an attrs object holding everything else, exactly where OTel keeps span attributes:
{"trace_id":"tr_9f2c1ab04d","span_id":"s_031","parent_span_id":"s_001","name":"generate","kind":"llm","start_ms":812.4,"duration_ms":2410.2,"status":"ok","ts":"2026-11-04T15:26:32.711Z","attrs":{"feature":"docs_qa","tenant_hash":"a1b2c3","user_hash":"d4e5f6","session_id":"conv_88","model_requested":"gpt-6-luna","model_resolved":"gpt-6-luna-2026-09-22","provider":"openai","api":"responses","request_id":"req_8f2c51d0a7","prompt_name":"docs-qa.answer","prompt_version":"1.4.2","prompt_sha256":"9f2c1ab0","uncached_input_tokens":5800,"cached_input_tokens":1200,"cache_write_tokens":0,"total_input_tokens":7000,"output_tokens":84,"reasoning_tokens":0,"cost_usd":0.000634,"cost_source":"computed","price_version":"2026-11-04","latency_ms":2410,"ttft_ms":380,"finish_reason":"stop","attempts":1,"gen_ai.operation.name":"chat","sdk":"openai==3.42.1","env":"prod"}}That record is a generate span carrying the full per-call field set from 2.2; the demo traces in Part 9 emit the same shape with a representative subset of attributes. Design rules for the schema:
- Envelope +
attrs, mirroring OTel. The envelope fields are the primitives every tool needs (trace_id/span_id/parent_span_idrebuild the tree,start_ms/duration_ms/status/tsmeasure it); everything else is an attribute inattrs— the same split OTel makes between span identity and span attributes, so a JSONL record and an OTLP span carry the same information. - Every span's
attrscarries the request's join keys (repeatfeature,tenant_hash,user_hash,session_id,prompt_versionon children) so any slice aggregates without a join — the viewer's--byreads them straight off the records. - Separate
model_requestedfrommodel_resolved,cost_usdfromcost_source(computed/provider/unknown— unknown isnull, never0), andprompt_versionfromprompt_sha256(the hash catches unversioned edits, 04.10, 4.1). These are allattrskeys. - Content fields are namespaced inside
attrsand off by default:content.input_excerpt,content.output_excerpt,content.redacted=true— present only when capture is enabled (Part 7). - Timestamps in UTC ISO-8601 plus a monotonic
start_ms/duration_msfor precise durations (wall-clock for correlation, monotonic for measurement).
Part 3: OpenTelemetry for GenAI#
Deep-dive
3.1 The OpenTelemetry pipeline#
OpenTelemetry (OTel) is the vendor-neutral, CNCF-standard way to produce and ship telemetry. You don't need a platform to use it — OTel is a pipeline, and the platform is just where the pipeline ends:
flowchart LR
subgraph app ["Your service (llm_service)"]
CODE["Application code<br/>manual spans + auto-instrumentation"]
SDK["OTel SDK<br/>TracerProvider, span processors,<br/>samplers, resource"]
EXP["OTLP exporter<br/>HTTP :4318 / gRPC :4317"]
CODE --> SDK --> EXP
end
EXP -->|"OTLP (protobuf/JSON)"| COL["OTel Collector<br/>receives, batches, samples,<br/>redacts, routes"]
COL --> BE["Backend<br/>Phoenix, Langfuse, Datadog,<br/>Jaeger, your own store"]The pieces, in the order data flows:
| Piece | What it does | Python package |
|---|---|---|
API (opentelemetry-api) |
The interfaces your code and libraries call: trace.get_tracer(), span context, propagators. No-op until a SDK is configured |
opentelemetry-api |
SDK (opentelemetry-sdk) |
The real implementation: TracerProvider, span processors, samplers, Resource, context managers |
opentelemetry-sdk |
| Instrumentations | Libraries that automatically wrap SDK calls (provider SDKs, frameworks, HTTP clients) and create spans | opentelemetry-instrumentation-* |
| Exporters | Ship finished spans somewhere: OTLP (the standard wire format), console, in-memory (for tests) | opentelemetry-exporter-otlp-proto-http |
| Collector (optional but recommended) | A separate process that receives OTLP, batches, samples, redacts, retries and fans out to one or more backends | otel/opentelemetry-collector (Docker) |
| Backend | Stores and renders traces: Phoenix, Langfuse, Datadog, Grafana Tempo, Jaeger, or your own JSONL store | — |
Why this indirection matters: your code emits OTel, not a vendor's format. Switch backends by changing an endpoint, not by rewriting instrumentation. The GenAI semantic conventions (3.2) are what make gen_ai.request.model mean the same thing in Phoenix, Datadog and Langfuse — when they stabilise.
3.2 The GenAI semantic conventions and their status#
The GenAI semantic conventions are OTel's agreed attribute names for LLM telemetry: gen_ai.provider.name, gen_ai.operation.name, gen_ai.request.model, gen_ai.response.model, gen_ai.response.id, gen_ai.response.finish_reasons, token usage under gen_ai.usage.* (input_tokens, output_tokens, cache_read.input_tokens, cache_write.input_tokens, reasoning.output_tokens, plus per-modality text./audio./image. variants), and opt-in content attributes gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions (03.10, 4.7 lists the core set; the anthropic SDK already emits them).
The usage attributes line up with this module's token convention: the conventions say gen_ai.usage.input_tokens should include cached tokens (cache reads and writes are subsets of it), and gen_ai.usage.reasoning.output_tokens is a subset of gen_ai.usage.output_tokens — the same "total input, output includes reasoning" shape as 2.2's table, so set_usage() below can fill them directly. (As of November 2026 the spec's own attribute tables, in the docs/gen-ai/client-inference.md file of the repo below, are the place to check these names.)
Their status as of November 2026 — verified against the repositories — is the single most important volatile fact in this lesson:
- The conventions moved to a dedicated repository,
open-telemetry/semantic-conventions-genai(created May 2026). The mainsemantic-conventionsrepo's v1.42.0 release (June 12, 2026) deprecated everygen_ai.*definition and moved it there. - Every GenAI-specific surface is still at Development stability — attribute names can change without a deprecation window. The new repo has no releases or tags as of November 2026; you follow a commit or dated snapshot. Its pinned
semantic-conventionsdependency is already at v1.45.0 (the core repo's latest, published 2 November 2026; read from the new repo'smodel/manifest.yaml), so the GenAI names track the newest conventions — not the deprecated v1.42.0 set. - Content capture is governed by an environment variable whose name differs between the two official sources (checked 9 November 2026): the released Python instrumentation packages (
1.3b0) readOTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT, while the conventions repo'sdocs/gen-ai/gen-ai-spans.mdsays a variable, if provided, MUST be namedOTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT. Use the name in the README of the instrumentation you actually install; the examples below use the Python one. It takesNO_CONTENT(the default — capture nothing),SPAN_ONLY,EVENT_ONLYorSPAN_AND_EVENT;OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimentalgates the newest attribute shapes and modes. The default matters enormously for PII (Part 7) — and note the failure mode: setting a misspelled variable name is a silent no-op, so you believe capture is configured one way while the default (no content) is what you actually get. - The Python instrumentation lives in a separate monorepo,
open-telemetry/opentelemetry-python-genai, publishingopentelemetry-instrumentation-genai-*packages —openai,anthropic,google-genai,openai-agentsand others (names vary per library; the instrumentation index in that repo is the source of truth) — at1.3b0, explicitly beta as of October 2026. They continue the olderopentelemetry-instrumentation-openai-v2line.
What the conventions cover beyond one model call (as of November 2026, from the repository's docs/gen-ai/ pages, all Development status): gen_ai.operation.name is not only chat/generate_content/embeddings — the agent pages define create_agent, invoke_agent (an agent driven by LLM tool-call control flow), invoke_workflow (application-defined control flow such as a graph), plan and execute_tool, with span names of the form {operation} {gen_ai.agent.name} and agent attributes gen_ai.agent.name (low-cardinality, human-readable), gen_ai.agent.id (provider-assigned, for hosted agents), gen_ai.agent.description and gen_ai.agent.version. So the agent-run root span and tool spans of 2.4 can carry gen_ai.operation.name = "invoke_agent" / "execute_tool" and keep your own tool.* attributes beside them. The metric side defines gen_ai.client.operation.duration (a histogram, in seconds) for callers (but on 1 December 2026 its page says not to report it for model, tool or agent operations; 3.13 has the details), and gen_ai.server.request.duration, gen_ai.server.time_to_first_token and gen_ai.server.time_per_output_token for the model server — the ones that matter when you run your own model server (11C.6); the token-usage metrics live on a separate page of the repo, so look names up there rather than copying them from a blog. The conventions' span-level gen_ai.provider.name has well-known values (openai, anthropic, gcp.gemini, gcp.vertex_ai, aws.bedrock, azure.ai.openai, mistral, ollama and more): note gcp.gemini for the Gemini API, not google or gemini, and keep OpenRouter as your own value (openrouter) because it is a gateway, not a model vendor — that is a design choice, not a convention rule.
3.3 Manual instrumentation with the OTel Python SDK#
Auto-instrumentation (3.4) covers the provider call itself, but your pipeline stages (retrieve, rerank, sufficiency, approval, tool_call) are yours to instrument. The pattern is always the same: get a tracer, start a span, set attributes, let it end.
This file is llm_service/telemetry.py — the tracing core of the running project. It wraps the OTel SDK in a small API the rest of the service uses, and works with or without an OTLP exporter configured:
# llm_service/telemetry.py — the service's tracing facade over the OTel Python SDK.
# Manual spans for pipeline stages + model calls; attributes follow the GenAI
# semantic conventions where they exist and our own names elsewhere.
from __future__ import annotations
import os
from contextlib import contextmanager
from typing import Any, Iterator, Mapping
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
BatchSpanProcessor,
ConsoleSpanExporter,
SimpleSpanProcessor,
)
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
from opentelemetry.trace import Status, StatusCode
SERVICE_NAME = os.environ.get("OTEL_SERVICE_NAME", "llm_service")
ENV = os.environ.get("APP_ENV", "dev")
# GenAI attribute names (Development-status conventions, Nov 2026 — names may shift;
# keep them behind this module so a rename is a one-file change).
GENAI = {
"provider": "gen_ai.provider.name",
"operation": "gen_ai.operation.name",
"request_model": "gen_ai.request.model",
"response_model": "gen_ai.response.model",
"response_id": "gen_ai.response.id",
"finish_reasons": "gen_ai.response.finish_reasons",
"usage_input": "gen_ai.usage.input_tokens",
"usage_output": "gen_ai.usage.output_tokens",
"usage_cache_read": "gen_ai.usage.cache_read.input_tokens",
"usage_cache_write": "gen_ai.usage.cache_write.input_tokens",
"usage_reasoning": "gen_ai.usage.reasoning.output_tokens",
# Content attributes exist but are OPT-IN via
# OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT
# (NO_CONTENT default; SPAN_ONLY / EVENT_ONLY / SPAN_AND_EVENT to opt in).
"input_messages": "gen_ai.input.messages",
"output_messages": "gen_ai.output.messages",
}
def configure_tracing(*, otlp_endpoint: str | None = None,
sample_ratio: float = 1.0) -> TracerProvider:
"""Set up the global TracerProvider once at startup.
otlp_endpoint: e.g. http://localhost:4318 (OTLP HTTP). None -> console only
(useful in dev; production always exports).
sample_ratio: fraction of *root* traces to keep (head sampling; see 3.5).
"""
resource = Resource.create({
"service.name": SERVICE_NAME,
"service.version": os.environ.get("SERVICE_VERSION", "0.0.0"),
"deployment.environment": ENV,
})
provider = TracerProvider(
resource=resource,
# ParentBased: respect the upstream sampling decision if there is one,
# else apply our ratio to root spans.
sampler=ParentBased(root=TraceIdRatioBased(sample_ratio)),
)
if otlp_endpoint:
# OTLPSpanExporter reads OTEL_EXPORTER_OTLP_ENDPOINT (+_TRACES_ENDPOINT,
# _HEADERS) itself; we pass it explicitly so the code is self-documenting.
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
OTLPSpanExporter,
)
provider.add_span_processor(BatchSpanProcessor(
OTLPSpanExporter(endpoint=f"{otlp_endpoint}/v1/traces"),
# Bounded queue + timeouts are defaults that matter: see 4.2.
))
else:
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
return provider
_SPAN_KINDS = {
"internal": trace.SpanKind.INTERNAL,
"server": trace.SpanKind.SERVER,
"client": trace.SpanKind.CLIENT,
"producer": trace.SpanKind.PRODUCER,
"consumer": trace.SpanKind.CONSUMER,
}
@contextmanager
def span(name: str, *, kind: str = "internal",
attributes: Mapping[str, Any] | None = None,
record_exception: bool = True) -> Iterator[trace.Span]:
"""Start a child span of whatever is current, set attributes, mark errors.
kind: "internal" (default), "server" (root request), "client" (outbound call
to a provider/tool), "producer"/"consumer" for queues. OTel span kinds.
"""
tracer = trace.get_tracer(SERVICE_NAME)
attrs = {}
for k, v in (attributes or {}).items():
a = _attr(v)
if a is not None: # None means "omit this attribute"
attrs[k] = a # (OTel attribute values can't be None)
with tracer.start_as_current_span(
name, kind=_SPAN_KINDS[kind], attributes=attrs or None) as sp:
try:
yield sp
except Exception as exc:
if record_exception:
sp.record_exception(exc)
sp.set_status(Status(StatusCode.ERROR, type(exc).__name__))
raise
def _attr(v: Any) -> Any:
"""Coerce attribute values to OTel-supported types (str, bool, int, float,
sequences of those). None means "omit the attribute"; anything else is
stringified — never let a dict or object reach set_attributes (it raises
and would break the request)."""
if v is None:
return None
if isinstance(v, (str, bool, int, float)):
return v
if isinstance(v, (list, tuple)) and all(
isinstance(x, (str, bool, int, float)) for x in v):
return list(v)
return str(v)[:500] # bounded: an attribute is not a payload store
def genai_span_attributes(*, provider: str, operation: str, model: str,
**extra: Any) -> dict[str, Any]:
"""Build the gen_ai.* attribute set for a model-call span."""
attrs = {
GENAI["provider"]: provider,
GENAI["operation"]: operation, # "chat", "generate_content", "text_completion"
GENAI["request_model"]: model,
}
attrs.update(extra)
return attrs
def set_usage(span_obj: trace.Span, *, input_tokens: int, output_tokens: int,
cache_read: int = 0,
cache_write: int | Mapping[str, int] | None = None,
reasoning: int = 0) -> None:
"""Attach token usage to a model-call span.
Uses the module's token convention mapped onto gen_ai.usage.* names:
input = total prompt tokens; output = completion tokens (incl. reasoning).
cache_read is the cache-read count; cache_write takes either a total or
03.11's Usage.cache_write_tokens ({lifetime: tokens}): the total goes to
the convention's gen_ai.usage.cache_write.input_tokens, and each lifetime
gets our own llm.usage.cache_write_<lifetime>_tokens attribute.
reasoning is the informational subset of output_tokens
(gen_ai.usage.reasoning.output_tokens). These are the six token columns
of 2.2's table - capture all of them.
"""
attrs: dict[str, Any] = {
GENAI["usage_input"]: input_tokens,
GENAI["usage_output"]: output_tokens,
GENAI["usage_cache_read"]: cache_read,
GENAI["usage_reasoning"]: reasoning,
}
if cache_write is not None:
if isinstance(cache_write, Mapping):
attrs[GENAI["usage_cache_write"]] = sum(cache_write.values())
for lifetime, n in cache_write.items():
attrs[f"llm.usage.cache_write_{lifetime}_tokens"] = n
else:
attrs[GENAI["usage_cache_write"]] = cache_write
span_obj.set_attributes(attrs)
def set_cost(span_obj: trace.Span, cost_usd: float | None,
source: str = "computed") -> None:
"""Attach cost. cost_usd=None means unknown — never write 0 for unknown."""
if cost_usd is not None:
span_obj.set_attributes({"llm.cost_usd": cost_usd,
"llm.cost_source": source})
def current_trace_id() -> str | None:
"""The W3C trace id of the current span, hex, or None if not tracing."""
ctx = trace.get_current_span().get_span_context()
if ctx and ctx.trace_id:
return format(ctx.trace_id, "032x")
return None
def inject_context(headers: dict[str, str]) -> dict[str, str]:
"""Propagate trace context into outbound HTTP headers (traceparent/tracestate).
Call before an HTTP request to a provider or downstream service so the
remote span becomes a child of this one. For the provider SDKs, prefer the
SDKs' own propagation (openai sends traceparent when configured; anthropic's
open_telemetry option does it automatically — see 3.4).
"""
from opentelemetry.propagate import inject
inject(headers)
return headersThe span() context manager is deliberately tiny: it is the only place spans are created for pipeline stages, so attribute hygiene (the _attr coercion that stops a dict from crashing set_attributes) lives in one spot. Now instrument a pipeline stage and a model call:
# llm_service/pipeline.py (excerpt) — using telemetry.py's facade.
# A RAG-style request: authz -> retrieve -> rerank -> generate -> cite.
# llm_client is 03.11's LLMClient; Request/Response are its types.
# build_scope/retriever/reranker/messages_for/build_cited_answer/
# classify_outcome are illustrative glue, not module API.
from provider_agnostic.types import Request
from llm_service.telemetry import span, genai_span_attributes, set_usage, set_cost
async def answer_question(req, principal):
with span("request", kind="server",
attributes={"http.route": "/ask", "feature": "docs_qa",
"tenant_hash": req.tenant_hash,
"user_hash": req.user_hash,
"session_id": req.session_id}) as root:
with span("authz_scope", attributes={"policy": "acl_filter"}):
scope = build_scope(principal) # sync, fast
with span("retrieve", kind="client",
attributes={"retrieval.backend": "hybrid",
"retrieval.index_version": req.index_version}) as sp:
hits = await retriever.search(req.query, scope) # embed + vector + BM25
sp.set_attributes({"retrieval.hit_count": len(hits),
"retrieval.top_score": hits[0].score if hits else 0.0})
with span("rerank", kind="client",
attributes={"rerank.top_n": 8}) as sp:
chunks = await reranker.rerank(req.query, hits[:50])
sp.set_attributes({"rerank.kept": len(chunks)})
# The model call: a gen_ai.* span, child of `request`.
with span("generate", kind="client",
attributes=genai_span_attributes(
provider="openai", operation="chat",
model=req.model,
**{"llm.feature": "docs_qa",
"llm.prompt_version": req.prompt_version})) as gen:
resp = await llm_client.acomplete(
Request(model=req.model,
messages=messages_for(chunks, req)))
usage = resp.usage # Usage | None — None means unknown, never 0
if usage is not None:
set_usage(gen,
input_tokens=usage.total_input_tokens,
output_tokens=usage.output_tokens,
cache_read=usage.cached_input_tokens,
cache_write=usage.cache_write_tokens,
reasoning=usage.reasoning_tokens)
if resp.cost is not None: # Cost | None: .usd may itself be None
set_cost(gen, resp.cost.usd, resp.cost.source)
gen.set_attributes({
"gen_ai.response.model": resp.resolved_model or req.model,
"gen_ai.response.id": resp.request_id,
"gen_ai.response.finish_reasons": [resp.finish_reason.value],
})
with span("cite_verify", attributes={"citations.expected": True}):
answer = build_cited_answer(resp.text, chunks)
# Roll totals onto the root span for per-request dashboards.
# Unknown cost stays unset — never write 0 for "we couldn't price it"
# (03.7's rule, and set_cost's contract).
if resp.cost is not None and resp.cost.usd is not None:
root.set_attributes({"llm.total_cost_usd": resp.cost.usd})
if usage is not None:
root.set_attributes(
{"llm.total_input_tokens": usage.total_input_tokens})
root.set_attributes({"outcome": classify_outcome(resp)}) # same key the collector policy in 3.5 matches
return answer3.4 Auto-instrumentation: what exists#
Manual spans cover your stages. For the provider SDK call itself you have three options, in increasing order of coverage:
| Approach | What it instruments | Status as of Nov 2026 | Use when |
|---|---|---|---|
Official GenAI instrumentations (opentelemetry-instrumentation-genai-{lib}) |
openai, anthropic, google-genai, openai-agents, etc. — one span per API call with gen_ai.* attributes and token metrics |
Beta (1.3b0, Oct 2026); continues openai-v2 line |
You want standard OTel spans with minimal code; accept beta |
Traceloop / OpenLLMetry (traceloop-sdk) |
Dozens of instrumentations: openai, anthropic, google-generativeai, litellm, langchain, llamaindex, mcp, vector DBs, plus @workflow/@task decorators and entity mapping |
Active (0.62.4, Sep 2026), Apache-2.0 |
Broadest coverage; you want decorators for custom stages; OTel underneath so any backend works |
OpenInference (Arize) (openinference-instrumentation-*) |
openai, anthropic, google-genai, openai-agents, langchain, litellm, ollama, mistralai, bedrock, guardrails, instructor… — spans in OpenInference semconv | Active (e.g. openinference-instrumentation-openai 0.1.69), Apache-2.0 |
You're using Phoenix/Arize AX — native format, no translation |
| Provider-native | anthropic SDK's built-in open_telemetry option (03.10, 4.7); OpenAI Agents SDK tracing; LangChain/LangGraph callbacks |
anthropic option is beta; Agents SDK tracing on by default |
You already use those SDKs/frameworks |
OpenLIT (openlit) |
openlit.init() auto-instruments 50+ providers/frameworks/vector DBs/GPUs and exports OTel traces+metrics to any OTLP backend or the OpenLIT platform (self-host, Apache-2.0) |
Active; the plan's named option | You want one-line instrumentation plus an optional self-hosted platform |
The list of released official packages, with their versions as of 1 December 2026, is in 3.13.
A minimal auto-instrumentation setup (illustrative — needs a key and a running backend):
# Auto-instrument the openai SDK before creating clients.
# Official GenAI instrumentation (beta) — emits gen_ai.* spans:
from opentelemetry.instrumentation.genai.openai import OpenAIInstrumentor
OpenAIInstrumentor().instrument()
# Or Traceloop/OpenLLMetry — broader coverage, decorators for your stages:
# from traceloop.sdk import Traceloop
# Traceloop.init(app_name="llm_service", disable_batch=True) # disable_batch in dev
# @task(name="retrieve") / @workflow(name="answer_question")
# Or OpenInference for Phoenix:
# from openinference.instrumentation.openai import OpenAIInstrumentor
# OpenAIInstrumentor().instrument()
# Then configure the tracer provider (3.3) BEFORE instrumenting, so spans have
# somewhere to go. Order matters: provider -> instrumentors -> clients.3.5 Sampling: head vs tail#
Traces cost money to store and your backend bills by volume. Sampling decides which traces to keep:
| Strategy | How it works | Keeps | Loses |
|---|---|---|---|
| Head sampling | Decide at trace start (e.g. parentbased_traceidratio 10%) |
A random 10% of all requests, uniformly | Nothing systematically — but also keeps 10% of the boring ones and may drop the one interesting error |
| Tail sampling | Buffer the whole trace, decide at the end based on outcome | All errors, all slow traces, all high-cost traces, plus a random baseline | Requires the collector or backend to hold complete traces before deciding — more infrastructure |
For LLM apps tail sampling is usually right: the traces you most need are the rare bad ones (errors, finish_reason=max_tokens, outcome=degraded, cost outliers, low eval scores), and they're exactly what head sampling drops 90% of the time. OTel's collector has a tail_sampling processor for this; some backends (Datadog, Phoenix Cloud) offer it as a feature. A pragmatic middle ground used in production: head-sample everything at a low ratio (1–10%) for baseline metrics, and always-sample errors and flagged sessions via a tail_sampling policy or a second "important traces" stream.
This is what that collector config actually looks like — reference YAML for otelcol (adjust processor names/versions to your collector release; the policy types shown — status_code, latency, string_attribute, probabilistic — are the stable set):
# otel-collector-config.yaml — OTLP in, redact + tail-sample, OTLP out.
receivers:
otlp:
protocols:
grpc: {endpoint: 0.0.0.0:4317}
http: {endpoint: 0.0.0.0:4318}
processors:
# Redact BEFORE export: content-bearing gen_ai attributes never leave the
# cluster (Part 7's "redact at write time" rule, enforced a second time here).
attributes/redact-content:
actions:
- {key: gen_ai.input.messages, action: delete}
- {key: gen_ai.output.messages, action: delete}
- {key: gen_ai.system_instructions, action: delete}
# Buffer whole traces, then decide: keep the interesting, sample the rest.
tail_sampling:
decision_wait: 10s
num_traces: 50000
expected_new_traces_per_sec: 100
policies:
- name: errors
type: status_code
status_code: {status_codes: [ERROR]}
- name: slow # LLM calls legitimately take seconds;
type: latency # 10s catches the pathological tail
latency: {threshold_ms: 10000}
- name: degraded # business outcome, not just span status
type: string_attribute
string_attribute: {key: outcome, values: [degraded, error]}
- name: baseline # keep a random slice for healthy trends
type: probabilistic
probabilistic: {sampling_percentage: 5}
exporters:
otlphttp:
endpoint: https://traces.example.com # Phoenix, Datadog, Langfuse, ...
service:
pipelines:
traces:
receivers: [otlp]
processors: [attributes/redact-content, tail_sampling]
exporters: [otlphttp]Two operational facts about tail_sampling that bite in production: all spans of a trace must reach the same collector instance (otherwise each replica sees a partial trace and decides on incomplete data), so a fleet of collectors needs a trace-ID-aware load-balancing tier in front (the collector's loadbalancing exporter, routing by trace ID); and the buffer is memory — num_traces × average trace size is your collector's RAM budget, which is why LLM traces with large content attributes are best redacted or truncated before the sampler, as above.
Two ordering details matter: redaction runs before sampling so policies can't accidentally match on content attributes, and decision_wait trades decision quality for latency — the collector holds each trace ~10s before shipping it, which is fine for traces (they're not on the request path) but is one more reason telemetry must stay async and fail-open.
3.6 Context propagation across async and services#
Trace context travels via W3C Trace Context — the traceparent and tracestate HTTP headers (and the traceparent/tracestate/baggage keys in MCP _meta, which 08E.1 noted is the seam for joining MCP calls into the same trace). Three rules:
- Within a process:
start_as_current_spannests automatically;contextvarscarry it acrossawaitpoints. Createasyncio.Tasks inside the span or passcontext=trace.get_current(). - Across your own services: inject
traceparentinto outbound requests (inject_contextintelemetry.py, or the framework's instrumentation) and extract on the server side. FastAPI/Starlette OTel instrumentation does this automatically. - To the provider: the provider sees your
traceparentheader but won't continue your trace — their spans are a separate trace on their side. What you get back isrequest_id/response.id, which you record as an attribute so support can correlate. (Anthropic'sopen_telemetryoption propagates context to Anthropic for their-side tracing; OpenAI's Agents SDK does similar for agent sessions.)
3.7 Operations, span names and span kinds#
3.2 told you where the GenAI conventions live and how unstable they are. Subsections 3.7 to 3.13 show what a well-formed GenAI span and trace look like, and build a small tracer and a linter around those rules with the standard library only. Every name below was checked on 1 December 2026 against the pages in docs/gen-ai/ of the conventions repository. Every one of those pages is at Development status, so open the page again before you build a dashboard on a name.
Every GenAI span says what kind of work it did with the attribute gen_ai.operation.name. The conventions list 21 well-known values. These are the ones you will meet in almost every agent trace:
| Value | What it is |
|---|---|
chat |
A chat-style model call (messages in, message out). The usual one |
text_completion |
A legacy completion-style call |
generate_content |
A call to an API such as Gemini's generate_content |
embeddings |
An embedding call |
retrieval |
A search over a vector store, an index or another retriever |
execute_tool |
Running a tool the model asked for |
create_agent |
Creating an agent (typically on a hosted agent service) |
invoke_agent |
Running an agent whose control flow is driven by the LLM through tool calls |
invoke_workflow |
Running application-defined control flow, such as a graph or a fixed pipeline |
plan |
A planning step by an agent |
The rest are invoke_runner (the pattern invoke_{framework_entrypoint} for framework entry points), realtime_inference, fetch_response, user_speech, and the memory operations create_memory, search_memory, update_memory, upsert_memory, delete_memory, create_memory_store and delete_memory_store. This is the same set that the DeepEval mapping in 5.11 uses.
Span names follow a pattern, so any backend can group them:
| Operation | Span name | Kind |
|---|---|---|
| Model call | {gen_ai.operation.name} {gen_ai.request.model}, such as chat gpt-6-luna |
CLIENT by default |
| Tool execution | execute_tool {gen_ai.tool.name} |
INTERNAL |
| Retrieval | retrieval |
INTERNAL |
| Agent run in your process | invoke_agent {gen_ai.agent.name}, such as invoke_agent support_agent (just the operation if there is no agent name) |
INTERNAL |
| Agent run on a remote agent service | invoke_agent {gen_ai.agent.name} |
CLIENT |
| Agent creation | create_agent {gen_ai.agent.name} |
CLIENT |
| Planning | plan {gen_ai.agent.name} |
INTERNAL |
Span kinds. A span has a kind that says what role it played. OTel defines INTERNAL, CLIENT, SERVER, PRODUCER and CONSUMER, and GenAI uses two of them. CLIENT means your code called something outside the process and waited: a model call to a hosted provider, or a call to a remote agent service. INTERNAL means work inside your own process: tool execution, retrieval and an agent that runs in your process. The inference page says CLIENT is the default, INTERNAL may be used for a model that runs in the same process, and CLIENT is recommended when the model is in another process or the call goes over a protocol such as HTTP. Kind matters because backends use it to draw service maps and to separate client latency from server latency.
Requirement levels are how a standard says "how much do I have to do?". Each attribute on a page carries one:
| Level | Meaning |
|---|---|
| Required | Always set it |
| Conditionally required | Set it when the condition holds (for example error.type only if the operation failed) |
| Recommended | Set it when you can |
| Opt-in | Do not set it by default; the user must turn it on. Used for anything sensitive |
For a model call, gen_ai.operation.name and gen_ai.provider.name are Required, gen_ai.request.model is Conditionally Required ("if available"), token usage is Recommended, and prompts and answers are Opt-in. For a tool span, gen_ai.operation.name and gen_ai.tool.name are Required, and gen_ai.tool.call.arguments and gen_ai.tool.call.result are Opt-in.
3.8 Attributes and requirement levels#
The attributes you will set every day, from the pages checked on 1 December 2026. The list is not exhaustive: the pages also define more request parameters (gen_ai.request.temperature, top_p, max_tokens, seed and others).
| Group | Attribute | Level and meaning |
|---|---|---|
| Model call | gen_ai.operation.name |
Required: chat, embeddings and so on |
gen_ai.provider.name |
Required: openai, anthropic, aws.bedrock and others |
|
gen_ai.request.model |
Conditionally required: the model you asked for | |
gen_ai.response.model |
Recommended: the model that actually answered (can be a dated snapshot) | |
gen_ai.response.id |
Recommended: the provider's response id | |
gen_ai.response.finish_reasons |
Recommended: one entry per generation | |
gen_ai.request.stream |
Set only on streaming requests | |
gen_ai.response.time_to_first_chunk |
Recommended for streaming: time to the first token | |
| Usage | gen_ai.usage.input_tokens, gen_ai.usage.output_tokens |
Recommended: totals (see 3.10) |
gen_ai.usage.cache_read.input_tokens, gen_ai.usage.cache_write.input_tokens |
Recommended when non-zero: subsets of the input total | |
gen_ai.usage.reasoning.output_tokens |
Recommended when non-zero: a subset of the output total | |
| Conversation | gen_ai.conversation.id |
Conditionally required only if you have a real id. The page says not to fall back to a UUID, a trace id or a content hash |
| Tool | gen_ai.tool.name |
Required on tool spans |
gen_ai.tool.call.id |
Only if the model or the provider supplied one | |
gen_ai.tool.description, gen_ai.tool.type |
Recommended | |
| Agent | gen_ai.agent.name, gen_ai.agent.id, gen_ai.agent.description, gen_ai.agent.version |
Set when available; name is low-cardinality and human readable |
| Retrieval | gen_ai.retrieval.top_k |
Recommended: documents requested |
| Prompt template | gen_ai.prompt.name, gen_ai.prompt.version |
When you use a named prompt template |
| Errors | error.type |
Conditionally required when the operation failed. Use _OTHER if you cannot classify it |
The per-call fields of 2.2 map onto these like this: provider to gen_ai.provider.name, model_requested to gen_ai.request.model, model_resolved to gen_ai.response.model, request_id to gen_ai.response.id, finish_reason to gen_ai.response.finish_reasons, prompt_name and prompt_version to gen_ai.prompt.name and gen_ai.prompt.version, total_input_tokens to gen_ai.usage.input_tokens, cached_input_tokens to cache_read.input_tokens, cache_write_tokens to cache_write.input_tokens, and reasoning_tokens to reasoning.output_tokens. uncached_input_tokens has no attribute of its own: it is the input total minus the cache subsets. Fields such as feature, tenant_hash and outcome stay your own names.
The opt-in (content) attributes. These are the most useful attributes for debugging and the most dangerous for privacy, so the conventions mark them Opt-in:
gen_ai.input.messages,gen_ai.output.messages,gen_ai.system_instructionsgen_ai.tool.definitionsgen_ai.tool.call.arguments,gen_ai.tool.call.resultgen_ai.retrieval.query.text,gen_ai.retrieval.documentsgen_ai.prompt.variables
The spans page says instrumentations "SHOULD NOT capture them by default, but SHOULD provide an option for users to opt in". For content that is too big or too sensitive for a span, the conventions define _ref attributes (such as gen_ai.input.messages_ref) that point to external storage, with upload settings such as OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH. Reference URIs must not embed credentials. 3.2 has the variable name, its four values and the two-spellings warning; 3.9 lets you watch each value work.
3.9 A mini tracer that emits OTel-shaped spans#
You do not need the SDK installed to see what the conventions produce. 03.12 recorded spans with names we made up. This tracer records the same data model as OpenTelemetry (traceId, spanId, parentSpanId, kind, attributes, events, status) with the GenAI names from 3.7 and 3.8. It is not the SDK: it has no exporters or processors, and it uses a simulated clock so durations are easy to read. It also reads the content-capture variable the way the conventions describe. For comparison, here is the real SDK for one span, shown as illustrative and not run (the OTel SDK is not installed where this lesson was checked; the classes follow the Python instrumentation page on opentelemetry.io, and SpanKind comes from the API itself):
# otel_sdk_sketch.py (illustrative, not run: needs `opentelemetry-sdk`)
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
from opentelemetry.trace import SpanKind, Status, StatusCode
provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support-service")
with tracer.start_as_current_span("chat gpt-6-luna", kind=SpanKind.CLIENT) as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.provider.name", "openai")
span.set_attribute("gen_ai.request.model", "gpt-6-luna")
try:
... # call the model here
span.set_attribute("gen_ai.usage.input_tokens", 120)
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR))
span.set_attribute("error.type", type(exc).__name__)
raiseThe telemetry.py facade in 3.3 wraps exactly these calls. Here is the stdlib version. Save it as genai_trace.py:
# genai_trace.py (standard library only)
"""A mini tracer that emits OpenTelemetry-shaped spans using the GenAI attribute names.
It is NOT the OpenTelemetry SDK. It has the same data model (trace id, span id, parent,
kind, attributes, events, status) so you can see exactly what the SDK would record.
The clock is simulated so durations are easy to read; real code uses time.time_ns().
"""
import contextlib
import contextvars
import json
import os
import uuid
CAPTURE_ENV = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT" # name from the conventions repo (checked 2026-12-01)
_current = contextvars.ContextVar("current_span", default=None)
class Span:
def __init__(self, tracer, name, kind, trace_id, parent_id, start_ns, attributes):
self.tracer = tracer
self.data = {
"traceId": trace_id, "spanId": uuid.uuid4().hex[:16], "parentSpanId": parent_id,
"name": name, "kind": kind, "startTimeUnixNano": start_ns, "endTimeUnixNano": None,
"attributes": dict(attributes), "events": [], "status": {"code": "UNSET"},
}
def set_attribute(self, key, value):
self.data["attributes"][key] = value
def add_event(self, name, attributes=None):
self.data["events"].append({"name": name, "timeUnixNano": self.tracer.now_ns,
"attributes": attributes or {}})
def set_content(self, key, value):
"""Opt-in content (prompts, outputs, tool arguments). Dropped unless the mode allows it."""
mode = self.tracer.capture_mode
if mode in ("SPAN_ONLY", "SPAN_AND_EVENT"):
self.data["attributes"][key] = json.dumps(value)
if mode in ("EVENT_ONLY", "SPAN_AND_EVENT"):
self.add_event("gen_ai.client.inference.operation.details", {key: json.dumps(value)})
def set_error(self, exc):
# Only the exception CLASS is kept: messages can quote the user's input.
self.data["status"] = {"code": "ERROR", "message": type(exc).__name__}
self.data["attributes"]["error.type"] = type(exc).__name__
self.add_event("exception", {"exception.type": type(exc).__name__})
class Tracer:
def __init__(self, service_name):
self.resource = {"service.name": service_name}
self.scope = {"name": "demo.genai.minitracer"}
mode = os.environ.get(CAPTURE_ENV, "NO_CONTENT").upper()
# The spec says unrecognised values fall back to NO_CONTENT.
self.capture_mode = mode if mode in ("NO_CONTENT", "SPAN_ONLY", "EVENT_ONLY", "SPAN_AND_EVENT") else "NO_CONTENT"
self.now_ns = 1_700_000_000_000_000_000
self.spans = []
self.order = {} # span id -> creation number, to print parents before children
def advance(self, ms):
self.now_ns += int(ms * 1_000_000)
def in_order(self):
return sorted(self.spans, key=lambda s: self.order[s["spanId"]])
@contextlib.contextmanager
def start_span(self, name, kind="INTERNAL", attributes=None):
parent = _current.get()
trace_id = parent.data["traceId"] if parent else uuid.uuid4().hex
span = Span(self, name, kind, trace_id, parent.data["spanId"] if parent else None,
self.now_ns, attributes or {})
self.order[span.data["spanId"]] = len(self.order)
token = _current.set(span)
try:
yield span
except Exception as exc:
span.set_error(exc)
raise
finally:
span.data["endTimeUnixNano"] = self.now_ns
_current.reset(token)
self.spans.append(span.data)
# --- helpers that apply the GenAI naming rules ----------------------------------
def chat(tracer, provider, model, in_tok, out_tok, finish, ms, messages=None, reply=None, **extra):
with tracer.start_span(f"chat {model}", "CLIENT", {
"gen_ai.operation.name": "chat", "gen_ai.provider.name": provider,
"gen_ai.request.model": model, **extra}) as s:
if messages is not None:
s.set_content("gen_ai.input.messages", messages)
tracer.advance(ms)
s.set_attribute("gen_ai.response.model", model)
s.set_attribute("gen_ai.usage.input_tokens", in_tok)
s.set_attribute("gen_ai.usage.output_tokens", out_tok)
s.set_attribute("gen_ai.response.finish_reasons", [finish])
if reply is not None:
s.set_content("gen_ai.output.messages", reply)
@contextlib.contextmanager
def execute_tool(tracer, tool_name, ms, arguments=None, result=None, agent=None, **extra):
attrs = {"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": tool_name, **extra}
if agent:
attrs["gen_ai.agent.name"] = agent
with tracer.start_span(f"execute_tool {tool_name}", "INTERNAL", attrs) as s:
if arguments is not None:
s.set_content("gen_ai.tool.call.arguments", arguments)
tracer.advance(ms)
if result is not None:
s.set_content("gen_ai.tool.call.result", result)
yield s
def retrieval(tracer, ms, top_k, query=None):
with tracer.start_span("retrieval", "INTERNAL", {
"gen_ai.operation.name": "retrieval", "gen_ai.retrieval.top_k": top_k}) as s:
if query is not None:
s.set_content("gen_ai.retrieval.query.text", query)
tracer.advance(ms)
def invoke_agent(tracer, name, operation="invoke_agent"):
return tracer.start_span(f"{operation} {name}", "INTERNAL",
{"gen_ai.operation.name": operation, "gen_ai.agent.name": name})Read the helpers at the bottom. Each one applies a naming rule from 3.7: the span name of a model call is chat {model}, a tool call is execute_tool {tool name}, an agent run is invoke_agent {agent name}.
Content capture, in action. The same call under six settings of the variable (one in lower case, one nonsense value). The tracer follows the conventions' variable name, OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT; the released Python packages may read the ..._CAPTURE_MESSAGE_CONTENT spelling instead (3.2).
# content_modes.py (standard library only)
"""Same call, four values of OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT: what lands where."""
import os
import genai_trace as g
for mode in ("NO_CONTENT", "SPAN_ONLY", "EVENT_ONLY", "SPAN_AND_EVENT", "span_only", "nonsense"):
os.environ[g.CAPTURE_ENV] = mode
t = g.Tracer("support-service")
g.chat(t, "openai", "demo-model-b", 120, 18, "stop", 300,
messages=[{"role": "user", "content": "my email is ana@example.com"}])
s = t.spans[0]
on_span = [k for k in s["attributes"] if k == "gen_ai.input.messages"]
print(f"{mode:<15} -> effective={t.capture_mode:<14} content on span: {bool(on_span)!s:<5} "
f"content events: {len(s['events'])}")NO_CONTENT -> effective=NO_CONTENT content on span: False content events: 0
SPAN_ONLY -> effective=SPAN_ONLY content on span: True content events: 0
EVENT_ONLY -> effective=EVENT_ONLY content on span: False content events: 1
SPAN_AND_EVENT -> effective=SPAN_AND_EVENT content on span: True content events: 1
span_only -> effective=SPAN_ONLY content on span: True content events: 0
nonsense -> effective=NO_CONTENT content on span: False content events: 0Case-insensitive values work, and a value the code does not recognise falls back to NO_CONTENT, as the spec says.
3.10 Normalising token usage across providers#
The conventions say gen_ai.usage.input_tokens includes cached tokens, and gen_ai.usage.output_tokens includes reasoning tokens. Cache reads, cache writes and reasoning tokens are subsets, reported separately only when non-zero.
The providers do not report usage the same way. OpenAI's input_tokens already includes cached tokens. Anthropic's input_tokens counts only the tokens after the last cache breakpoint, with cache reads and writes in separate fields (03.7 has the table and the sources). Copy Anthropic's number straight into gen_ai.usage.input_tokens and you under-count. This function does the normalisation for both providers, for the same logical call (2,000 input tokens, 1,500 of them a cache hit):
# usage_mapping.py (standard library only)
"""Turn each provider's usage object into the GenAI usage attributes.
Convention: gen_ai.usage.input_tokens INCLUDES cached tokens; cache reads and writes are subsets of it.
OpenAI already reports it that way. Anthropic's input_tokens EXCLUDES cache reads and writes, so we add them.
"""
def openai_usage(u):
out = {"gen_ai.usage.input_tokens": u["input_tokens"],
"gen_ai.usage.output_tokens": u["output_tokens"]}
cached = u.get("input_tokens_details", {}).get("cached_tokens", 0)
reasoning = u.get("output_tokens_details", {}).get("reasoning_tokens", 0)
if cached:
out["gen_ai.usage.cache_read.input_tokens"] = cached
if reasoning:
out["gen_ai.usage.reasoning.output_tokens"] = reasoning
return out
def anthropic_usage(u):
read = u.get("cache_read_input_tokens", 0)
write = u.get("cache_creation_input_tokens", 0)
out = {"gen_ai.usage.input_tokens": u["input_tokens"] + read + write, # normalise: total input
"gen_ai.usage.output_tokens": u["output_tokens"]}
if read:
out["gen_ai.usage.cache_read.input_tokens"] = read
if write:
out["gen_ai.usage.cache_write.input_tokens"] = write
return out
# Same logical call: 2,000 prompt tokens of which 1,500 were a cache hit; 120 output tokens.
openai_obj = {"input_tokens": 2000, "input_tokens_details": {"cached_tokens": 1500},
"output_tokens": 120, "output_tokens_details": {"reasoning_tokens": 0}}
anthropic_obj = {"input_tokens": 500, "cache_read_input_tokens": 1500, "cache_creation_input_tokens": 0,
"output_tokens": 120}
a, b = openai_usage(openai_obj), anthropic_usage(anthropic_obj)
print("openai :", a)
print("anthropic:", b)
assert a == b, "the two providers should normalise to the same attributes"
assert a["gen_ai.usage.cache_read.input_tokens"] <= a["gen_ai.usage.input_tokens"]
print("same attributes, same meaning")openai : {'gen_ai.usage.input_tokens': 2000, 'gen_ai.usage.output_tokens': 120, 'gen_ai.usage.cache_read.input_tokens': 1500}
anthropic: {'gen_ai.usage.input_tokens': 2000, 'gen_ai.usage.output_tokens': 120, 'gen_ai.usage.cache_read.input_tokens': 1500}
same attributes, same meaningBoth providers end at the same attributes with the same meaning. That is the point of a convention. Use it when you build the attributes from a raw usage object. The Anthropic SDK's own OpenTelemetry spans already include cache tokens in gen_ai.usage.input_tokens (08A.14, 3.6), so do not add them again there. The raw field names are the ones documented in 03.7; check the SDK reference if they have changed.
3.11 Trace shapes: model, tool, retrieval and agent runs#
One model call is a single chat span (kind CLIENT) with the attributes of 3.8 and, if you capture content, the opt-in message attributes. For streaming, add gen_ai.request.stream and gen_ai.response.time_to_first_chunk. If the call is retried, record each attempt as its own span so a retry storm is visible (the attempt count is your own attribute).
A tool call and a retrieval. A tool call is an execute_tool {tool name} span, kind INTERNAL, sitting beside the model calls it belongs to. The model's decision to call a tool is part of the chat span that came before; the running of the tool is the execute_tool span. A retrieval is a retrieval span (kind INTERNAL) with gen_ai.retrieval.top_k; the query text and the documents are opt-in. Your own stages (rerank, citation check) have no standard operation name: give them your own span names and attributes, as 2.4 argues, and do not invent gen_ai.* names for them.
A single-agent run is one invoke_agent span for the run, and inside it one chat and one execute_tool per step, in order. The span count in the tree equals the step count in the loop (08A.2), which makes loop problems obvious: a stuck agent shows up as a long ladder of identical execute_tool spans. Tools that run in parallel overlap in time and are siblings. If your code defines the flow instead (a fixed graph where the model fills in blanks), the operation is invoke_workflow, and the agent steps inside it may still be invoke_agent spans. The invoke_agent span sits under a root span for your own request (POST /ask) that carries your own attributes (feature, prompt version, session id, see 2.3).
A multi-agent run nests: when one agent calls another, the second agent's whole run happens inside the first agent's step. Four scenarios follow. Save this file as genai_demo.py next to genai_trace.py:
# genai_demo.py (standard library only)
import json
import genai_trace as g
def single_agent(t):
with g.invoke_agent(t, "support_agent"):
g.retrieval(t, 40, top_k=3, query="refund policy for late orders")
g.chat(t, "anthropic", "demo-model-a", 900, 40, "tool_use", 800,
messages=[{"role": "user", "content": "Where is order A17?"}],
reply=[{"role": "assistant", "content": "calling get_order"}])
with g.execute_tool(t, "get_order", 25, arguments={"order_id": "A17"},
result={"status": "shipped"}, agent="support_agent"):
pass
g.chat(t, "anthropic", "demo-model-a", 1010, 22, "end_turn", 500)
def multi_agent(t):
with g.invoke_agent(t, "orchestrator"):
g.chat(t, "openai", "demo-model-b", 700, 30, "tool_calls", 600)
# The orchestrator calls a sub-agent *as a tool*; the spec has a refinement for exactly this.
with g.execute_tool(t, "ask_billing_agent", 0, agent="orchestrator",
**{"gen_ai.transfer.mode": "return_to_caller",
"gen_ai.transfer.target.name": "billing_agent"}):
with g.invoke_agent(t, "billing_agent"):
g.chat(t, "openai", "demo-model-b", 500, 25, "tool_calls", 450)
with g.execute_tool(t, "lookup_invoice", 60, agent="billing_agent"):
pass
g.chat(t, "openai", "demo-model-b", 640, 35, "stop", 520)
g.chat(t, "openai", "demo-model-b", 900, 60, "stop", 700)
def handoff(t):
# Your code defines the flow (router, then billing), so the root is an invoke_workflow span.
with g.invoke_agent(t, "support_flow", operation="invoke_workflow"):
with g.invoke_agent(t, "router"):
g.chat(t, "openai", "demo-model-b", 300, 12, "tool_calls", 250)
# A hand-off: the router passes control on and does not wait for the answer.
with g.execute_tool(t, "transfer_to_billing", 0, agent="router",
**{"gen_ai.transfer.mode": "pass_control",
"gen_ai.transfer.target.name": "billing_agent"}):
pass
# Here the target agent is a SIBLING of the router's span. Some frameworks nest it
# under the transfer tool span instead; both shapes are valid (see 3.10).
with g.invoke_agent(t, "billing_agent"):
g.chat(t, "openai", "demo-model-b", 450, 40, "stop", 500)
def failing_tool(t):
with g.invoke_agent(t, "billing_agent"):
g.chat(t, "openai", "demo-model-b", 500, 25, "tool_calls", 450)
try:
with g.execute_tool(t, "lookup_invoice", 3000, agent="billing_agent"):
raise TimeoutError("upstream billing API timed out")
except TimeoutError:
pass # the agent catches it and answers without the tool
g.chat(t, "openai", "demo-model-b", 560, 30, "stop", 400)
def print_tree(tracer):
by_parent = {}
for s in tracer.in_order():
by_parent.setdefault(s["parentSpanId"], []).append(s)
def walk(pid, depth):
for s in by_parent.get(pid, []):
ms = (s["endTimeUnixNano"] - s["startTimeUnixNano"]) / 1e6
flag = " ERROR " + s["attributes"]["error.type"] if s["status"]["code"] == "ERROR" else ""
print(f"{' ' * depth}{s['name']:<32} {s['kind']:<9} {ms:>6.0f} ms{flag}")
walk(s["spanId"], depth + 1)
walk(None, 0)
if __name__ == "__main__":
t1 = g.Tracer("support-service")
single_agent(t1)
print("capture mode:", t1.capture_mode)
print_tree(t1)
print()
t2 = g.Tracer("support-service")
multi_agent(t2)
print_tree(t2)
print()
t3 = g.Tracer("support-service")
handoff(t3)
print_tree(t3)
print()
t4 = g.Tracer("support-service")
failing_tool(t4)
print_tree(t4)
print("\none raw span, as exported:")
print(json.dumps([s for s in t1.spans if s["name"].startswith("chat")][0], indent=2))capture mode: NO_CONTENT
invoke_agent support_agent INTERNAL 1365 ms
retrieval INTERNAL 40 ms
chat demo-model-a CLIENT 800 ms
execute_tool get_order INTERNAL 25 ms
chat demo-model-a CLIENT 500 ms
invoke_agent orchestrator INTERNAL 2330 ms
chat demo-model-b CLIENT 600 ms
execute_tool ask_billing_agent INTERNAL 1030 ms
invoke_agent billing_agent INTERNAL 1030 ms
chat demo-model-b CLIENT 450 ms
execute_tool lookup_invoice INTERNAL 60 ms
chat demo-model-b CLIENT 520 ms
chat demo-model-b CLIENT 700 ms
invoke_workflow support_flow INTERNAL 750 ms
invoke_agent router INTERNAL 250 ms
chat demo-model-b CLIENT 250 ms
execute_tool transfer_to_billing INTERNAL 0 ms
invoke_agent billing_agent INTERNAL 500 ms
chat demo-model-b CLIENT 500 ms
invoke_agent billing_agent INTERNAL 3850 ms
chat demo-model-b CLIENT 450 ms
execute_tool lookup_invoice INTERNAL 3000 ms ERROR TimeoutError
chat demo-model-b CLIENT 400 ms
one raw span, as exported:
{
"traceId": "bae93ca083724a5792ff9aebc09ee7ad",
"spanId": "e3da40f288df4e84",
"parentSpanId": "8747a3adba0d40d5",
"name": "chat demo-model-a",
"kind": "CLIENT",
"startTimeUnixNano": 1700000000040000000,
"endTimeUnixNano": 1700000000840000000,
"attributes": {
"gen_ai.operation.name": "chat",
"gen_ai.provider.name": "anthropic",
"gen_ai.request.model": "demo-model-a",
"gen_ai.response.model": "demo-model-a",
"gen_ai.usage.input_tokens": 900,
"gen_ai.usage.output_tokens": 40,
"gen_ai.response.finish_reasons": [
"tool_use"
]
},
"events": [],
"status": {
"code": "UNSET"
}
}Read the second tree, the multi-agent run:
- Nesting comes from context propagation. The sub-agent runs while the tool span is current, so its
invoke_agentspan becomes the tool span's child. Nothing special is needed in your code while the call stays in one process and task. Across services, send thetraceparentheader so the remote agent continues the trace (3.6). - The tool span times the whole delegation.
execute_tool ask_billing_agenttook 1030 ms because the sub-agent ran inside it. To see where the time went, read the sub-tree. - Each agent keeps its own step counts. The orchestrator made 2 model calls and 1 tool call, and so did the billing agent. A rollup per agent tells you which agent is expensive.
Agent as a tool. The execute-tool page has a refinement for tool calls that hand work or control to another agent. Instrumentation should use it for such calls and should not report additional spans for the transfer. It adds two attributes, gen_ai.transfer.mode (well-known values pass_control and return_to_caller) and gen_ai.transfer.target.name. In the multi-agent run the call to the billing agent is return_to_caller: the orchestrator waits and resumes.
Hand-offs. In a hand-off, agent A passes the conversation to agent B and does not take it back. Mark that execute_tool span pass_control and name the target (third tree). B's invoke_agent span is then a sibling or a child of that tool span, depending on the framework. The pages read for this lesson give no hierarchy rule for multi-agent runs (not found in gen-ai-spans.md or gen-ai-agent-spans.md on 1 December 2026), so check your framework's instrumentation and keep the nesting consistent across your services.
Links. An OTel span can carry links to other spans. Use a link when work is related but not nested, for example a background job started by an agent step. This is general OTel practice and not a GenAI rule.
Errors. When a step fails, set the span status to ERROR, set error.type to the exception class or a short category (_OTHER if unknown), and record the exception as an event. Keep the class only: exception messages can quote user input, so treat them with the same care as content (Part 7). The fourth tree shows a caught error: the tool span ends ERROR, while the agent span stays UNSET because the agent handled it and answered anyway. If the agent re-raised, its span would end ERROR too.
3.12 A linter for the conventions#
Rules that live only in prose get broken in the next refactor. This script is a linter that checks a span list against the rules of 3.7 to 3.10: required attributes present, span names in the right pattern, the right span kind, content absent when capture is off, a cache count never above the input total, errors carrying error.type, and parents that exist and contain their children in time. It also rolls up the model calls and tool calls made directly inside each agent span (this lesson's own definition, for illustration). Save it as check_spans.py:
# check_spans.py (standard library only)
"""Lint spans against the GenAI conventions as this lesson summarises them (checked 2026-12-01)."""
import genai_trace as g
from genai_demo import failing_tool, handoff, multi_agent, single_agent
REQUIRED = { # operation -> (required attributes, expected kind(s))
"chat": ({"gen_ai.provider.name"}, {"CLIENT", "INTERNAL"}),
"execute_tool": ({"gen_ai.tool.name"}, {"INTERNAL"}),
"invoke_agent": (set(), {"INTERNAL", "CLIENT"}),
"invoke_workflow": (set(), {"INTERNAL"}),
"retrieval": (set(), {"INTERNAL"}),
}
CONTENT_ATTRS = {"gen_ai.input.messages", "gen_ai.output.messages", "gen_ai.system_instructions",
"gen_ai.tool.call.arguments", "gen_ai.tool.call.result",
"gen_ai.retrieval.query.text", "gen_ai.tool.definitions"}
def lint(spans, capture_mode="NO_CONTENT"):
problems, ids = [], {s["spanId"]: s for s in spans}
for s in spans:
a, name = s["attributes"], s["name"]
op = a.get("gen_ai.operation.name")
if op not in REQUIRED:
problems.append(f"{name}: unknown or missing gen_ai.operation.name {op!r}")
continue
need, kinds = REQUIRED[op]
for key in sorted(need - a.keys()):
problems.append(f"{name}: missing required attribute {key}")
if s["kind"] not in kinds:
problems.append(f"{name}: kind {s['kind']} not expected for {op}")
if op == "chat" and name != f"chat {a.get('gen_ai.request.model')}":
problems.append(f"{name}: span name should be 'chat {{gen_ai.request.model}}'")
if op == "execute_tool" and name != f"execute_tool {a.get('gen_ai.tool.name')}":
problems.append(f"{name}: span name should be 'execute_tool {{gen_ai.tool.name}}'")
if a.get("gen_ai.usage.cache_read.input_tokens", 0) > a.get("gen_ai.usage.input_tokens", 0):
problems.append(f"{name}: cache_read tokens exceed the input total (input_tokens must include them)")
if s["status"]["code"] == "ERROR" and "error.type" not in a:
problems.append(f"{name}: error status without error.type")
if capture_mode == "NO_CONTENT" and CONTENT_ATTRS & a.keys():
problems.append(f"{name}: content attribute present although capture mode is NO_CONTENT")
if s["parentSpanId"] and s["parentSpanId"] not in ids:
problems.append(f"{name}: parent {s['parentSpanId']} was never exported (orphan)")
elif s["parentSpanId"]:
p = ids[s["parentSpanId"]]
if not (p["startTimeUnixNano"] <= s["startTimeUnixNano"] and s["endTimeUnixNano"] <= p["endTimeUnixNano"]):
problems.append(f"{name}: not inside its parent's time range")
return problems
def rollup(spans):
"""Calls made directly inside each invoke_agent span (this lesson's definition, not the spec's)."""
out = {}
for s in spans:
if s["attributes"].get("gen_ai.operation.name") == "invoke_agent":
kids = [c for c in spans if c["parentSpanId"] == s["spanId"]]
ops = [c["attributes"].get("gen_ai.operation.name") for c in kids]
out[s["attributes"]["gen_ai.agent.name"]] = {"inference_calls": ops.count("chat"),
"tool_calls": ops.count("execute_tool")}
return out
if __name__ == "__main__":
for label, fn in (("single-agent", single_agent), ("multi-agent", multi_agent),
("hand-off", handoff), ("failing tool", failing_tool)):
t = g.Tracer("support-service")
fn(t)
print(f"{label:<13}-> {len(t.spans)} spans, {len(lint(t.spans))} problems; {rollup(t.spans)}")
print("\nSeeded mistakes:")
t = g.Tracer("support-service")
with g.invoke_agent(t, "demo_agent"):
with t.start_span("chat demo-model", "CLIENT", # no provider name
{"gen_ai.operation.name": "chat", "gen_ai.request.model": "demo-model"}):
pass
with t.start_span("tool get_order", "CLIENT", # wrong name and kind
{"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "get_order"}):
pass
with t.start_span("execute_tool lookup", "INTERNAL", # content leaked, mode is NO_CONTENT
{"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "lookup",
"gen_ai.tool.call.arguments": '{"email": "ana@example.com"}'}):
pass
with t.start_span("chat demo-model", "CLIENT", {"gen_ai.operation.name": "chat",
"gen_ai.provider.name": "openai", "gen_ai.request.model": "demo-model"}) as s:
s.data["status"] = {"code": "ERROR"} # error without error.type
with t.start_span("chat demo-model", "CLIENT", {"gen_ai.operation.name": "chat",
"gen_ai.provider.name": "anthropic", "gen_ai.request.model": "demo-model",
"gen_ai.usage.input_tokens": 500, # the Anthropic mistake: cache
"gen_ai.usage.cache_read.input_tokens": 1500}): # not added to the total
pass
for p in lint(t.spans):
print(" -", p)single-agent -> 5 spans, 0 problems; {'support_agent': {'inference_calls': 2, 'tool_calls': 1}}
multi-agent -> 8 spans, 0 problems; {'billing_agent': {'inference_calls': 2, 'tool_calls': 1}, 'orchestrator': {'inference_calls': 2, 'tool_calls': 1}}
hand-off -> 6 spans, 0 problems; {'router': {'inference_calls': 1, 'tool_calls': 1}, 'billing_agent': {'inference_calls': 1, 'tool_calls': 0}}
failing tool -> 4 spans, 0 problems; {'billing_agent': {'inference_calls': 2, 'tool_calls': 1}}
Seeded mistakes:
- chat demo-model: missing required attribute gen_ai.provider.name
- tool get_order: kind CLIENT not expected for execute_tool
- tool get_order: span name should be 'execute_tool {gen_ai.tool.name}'
- execute_tool lookup: content attribute present although capture mode is NO_CONTENT
- chat demo-model: error status without error.type
- chat demo-model: cache_read tokens exceed the input total (input_tokens must include them)The four real runs are clean, and each seeded mistake is caught by the rule written for it. Notice the mistakes the linter does not know about: it checks the shape of spans, not whether the numbers are true.
Use it as an evaluation. Two things can be wrong with telemetry: it can break the conventions, and the trace can be poor evidence for grading. The lint pass rate measures the first. For the second, check completeness: for each agent run, does the tree hold one chat span per model call and one execute_tool span per tool call? A missing span means a metric that reads the trajectory scores a different run than the one that happened (10A.7, 10.4 adapts spans into a trajectory). A tiny eval design:
- Inputs: ten recorded runs from your agent (single-agent and multi-agent), plus three runs you broke on purpose (a tool span with the wrong kind, a
chatspan with no provider, a run where the tool span was lost). - Metric: lint pass rate per run, plus "step count from the loop equals step count from the spans".
- Pass rule: all ten real runs have zero lint problems and equal step counts, and all three broken runs are flagged. Run it in CI, so a change to your instrumentation cannot silently change what your dashboards and evals read.
3.13 GenAI metrics, the opt-in switch and instrumentation packages#
Metrics. Traces describe single requests. Metrics are numbers aggregated over time, and the conventions define a set for GenAI (all Development, checked 1 December 2026):
| Metric | Type, unit | Meaning |
|---|---|---|
gen_ai.client.inference.duration |
histogram, seconds | Duration of a model call as seen by the caller (defined on the client inference page) |
gen_ai.client.operation.duration |
histogram, seconds | See the warning below |
gen_ai.server.request.duration |
histogram, seconds | Server-side request duration, when you run the model server |
gen_ai.server.time_to_first_token |
histogram, seconds | Server-side time to first token |
gen_ai.server.time_per_output_token |
histogram, seconds | Server-side decode time per output token |
gen_ai.invoke_agent.duration |
histogram, seconds | Duration of an in-process agent invocation |
gen_ai.invoke_agent.inference_calls |
histogram, {inference_call} |
Model calls per agent invocation |
gen_ai.invoke_agent.tool_calls |
histogram, {tool_call} |
Client-side tool calls per agent invocation |
The client inference page also defines gen_ai.client.inference.time_to_first_chunk and gen_ai.client.inference.time_per_output_chunk. A separate page defines token counters such as gen_ai.client.inference.usage.input_tokens and ...output_tokens, split by gen_ai.token.modality (text, image, audio, unknown).
The agent metrics are worth noticing: invoke_agent.inference_calls and invoke_agent.tool_calls count the steps in a run. That is the number you want for "how many steps did the agent take?" and for spotting loops. The rollup() in 3.12 computes the same idea from the span tree. The spec defines the metrics by name and unit; the pages read for this lesson did not give a precise rule for counting calls made by nested agents, so check the metrics page before you rely on an exact definition.
The opt-in switch. OpenTelemetry uses the environment variable OTEL_SEMCONV_STABILITY_OPT_IN to let users opt in to newer semantic conventions in instrumentations that support it. For GenAI the value reported in OTel's own text and in Datadog's documentation is gen_ai_latest_experimental, which makes an instrumentation emit the newest experimental GenAI conventions instead of the old ones. This is only partly verified: the conventions repository's docs/gen-ai pages and the Python GenAI monorepo README do not mention the variable (unverified as of 2026-12-01). What to do:
- Whether a package reads the variable, and what it does when the variable is unset, is package-specific. Read that package's README.
- If you want the newest names, set the variable in the environment of the process that does the instrumenting, before the instrumentation loads.
- If a dashboard suddenly shows different attribute names after an upgrade, check this variable and the package version before anything else.
Instrumentation packages. 3.4 compares the approaches. The detail, from the README of open-telemetry/opentelemetry-python-genai on 1 December 2026: released packages exist for openai, anthropic, google-genai, openai-agents, langchain, llama-index, bedrock, dspy, agno, portkey, qwen-agent, qwenpaw and smolagents; claude-agent-sdk, crewai, ollama and weaviate-client are unreleased placeholders. Most released packages are at 1.3b0 (smolagents at 1.2b0); the b marks a beta pre-release (reading b0 as beta is an inference, the README does not use the word). Names follow opentelemetry-instrumentation-genai-{library}, except the Google one, which is opentelemetry-instrumentation-google-genai.
Part 4: Instrumentation strategies and the safe exporter#
4.1 Proxy-based vs SDK-based vs OTel-based#
Three ways to get telemetry out of an LLM app, with real trade-offs:
| Strategy | How it works | Completeness | Latency overhead | Failure modes | Lock-in |
|---|---|---|---|---|---|
| Proxy/gateway (Helicone-style, or a LiteLLM/Portkey gateway — 11C.3 owns gateways) | Point base_url at a proxy; it logs every request/response |
High for provider calls; blind to your stages (retrieve, rerank, policy) | One extra network hop per call; the proxy is a new dependency in the hot path | Proxy down = requests fail (unless fail-open configured); proxy sees full content | High: traces live in the proxy's format/backend |
SDK wrapper / hooks (03.11's Hook model, LangSmith @traceable, Logfire decorators) |
Your code calls the wrapper; it emits spans/logs around each call | Good for model calls and annotated functions; you instrument stages yourself | ~zero (in-process) | Wrapper bugs can break calls (mitigated by fail-open observers, 03.11, Part 9) | Medium: proprietary span format unless it emits OTel |
| OpenTelemetry | Manual spans + auto-instrumentation → OTLP → any backend | Highest: your stages and provider calls in one trace model | ~zero in-process; export is async/batched | Exporter/backend down = lost spans (must be fail-open) | Lowest: OTel is the standard; backends are interchangeable |
The honest answer for most teams: OTel-based instrumentation, with SDK wrappers where they add convenience. Proxy-based tracing is the fastest way to see your provider calls (one base_url change) and is worth it for a quick audit or a gateway you're already running — but it can't see inside your pipeline, it adds a hop, and it concentrates your prompts in a third party. SDK wrappers are fine for small projects; at scale you want the vendor-neutral model so you can change backends without rewriting instrumentation.
4.2 The safe exporter: fail-open, bounded and fast#
The OTel SDK's BatchSpanProcessor already batches and exports on a background thread — but for the JSONL trace store (and for understanding the pattern), here is the whole thing: llm_service/tracekit.py, pure stdlib so it runs anywhere, no SDK and no services. The design rules:
emit()isput_nowaitor drop — never blocks the request thread- bounded queue; on overflow, drop and count the loss (visible, not silent)
- exporter thread swallows sink exceptions — a dead backend loses spans, not requests
flush()/close()for shutdown and tests- an idle queue never kills the worker — this is the subtle one:
queue.get(timeout=...)raisesqueue.Emptyon inactivity, and the naive reading treats that like the shutdown sentinel and exits. Here the timeout is just a flush tick; only the_STOPsentinel ends the loop, so the exporter survives any idle gap
# llm_service/tracekit.py — the module's pure-Python trace core (stdlib only).
# One TraceRecord per span, written as JSON Lines. SafeExporter ships records to a
# sink on a background thread with a bounded queue: telemetry can never block or
# break a request (fail-open by design — see lesson 11A.1, Part 4).
from __future__ import annotations
import json
import queue
import sys
import threading
import time
import uuid
from contextlib import contextmanager
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Callable, Iterator
@dataclass
class TraceRecord:
"""One span as one JSON object. Envelope + attrs, mirroring OTel: the tree
is rebuilt by parent_span_id; join keys are repeated inside attrs on every
record so any slice aggregates without a join."""
trace_id: str
span_id: str
parent_span_id: str | None
name: str
kind: str # request | stage | llm | tool | retrieval | ...
start_ms: float # ms on a monotonic clock, relative to trace start
duration_ms: float
status: str # ok | error | unset
ts: str
attrs: dict[str, Any] = field(default_factory=dict)
def new_ids() -> tuple[str, str]:
return f"tr_{uuid.uuid4().hex[:12]}", f"s_{uuid.uuid4().hex[:8]}"
class TraceStore:
"""Append-only JSONL writer. One file per day keeps files manageable."""
def __init__(self, path: str | Path):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
self._lock = threading.Lock()
def write(self, record: TraceRecord) -> None:
self.write_all([record])
def write_all(self, records: list[TraceRecord]) -> None:
with self._lock, self.path.open("a", encoding="utf-8") as fh:
for record in records:
fh.write(json.dumps(asdict(record),
separators=(",", ":")) + "\n")
@staticmethod
def read(path: str | Path) -> list[TraceRecord]:
out = []
for line in Path(path).read_text(encoding="utf-8").splitlines():
if line.strip():
d = json.loads(line)
out.append(TraceRecord(**d))
return out
_FLUSH = object() # sentinel: ship whatever is buffered, keep running
_STOP = object() # sentinel: ship the remainder, then exit
class SafeExporter:
"""Ships TraceRecords to a sink on a daemon thread.
Guarantees (the whole point of Part 4):
* emit() NEVER blocks meaningfully and NEVER raises — put_nowait or drop.
* A dead sink cannot kill the worker thread or the request: every
exception inside _run is swallowed after one warning.
* The queue is bounded; under sustained overload we drop NEWEST records
(keep the oldest — early spans carry the request context) and count
drops so loss is visible, not silent.
* An idle queue does NOT kill the worker: get(timeout=...) raising
queue.Empty just means "time to flush", never "time to exit". Only the
_STOP sentinel ends the loop, so the exporter survives any idle gap.
"""
def __init__(self, sink: Callable[[list[TraceRecord]], None], *,
maxsize: int = 10_000, batch: int = 100,
flush_interval_s: float = 1.0):
self._sink = sink
self._q: queue.Queue[TraceRecord | object] = queue.Queue(maxsize=maxsize)
self._batch = batch
self._flush_s = flush_interval_s
self.dropped = 0
self.exported = 0
self._thread = threading.Thread(target=self._run, daemon=True,
name="safe-exporter")
self._thread.start()
def emit(self, record: TraceRecord) -> None:
try:
self._q.put_nowait(record)
except queue.Full:
self.dropped += 1 # fail-open: drop, count, never raise
def flush(self, timeout: float = 5.0) -> None:
"""Best-effort: ask the worker to ship its buffer, then wait for the
queue to drain. Not a guarantee — close() is the real shutdown path."""
try:
self._q.put_nowait(_FLUSH)
except queue.Full:
pass
deadline = time.monotonic() + timeout
while time.monotonic() < deadline and not self._q.empty():
time.sleep(0.01)
def close(self) -> None:
try:
self._q.put_nowait(_STOP) # sentinel: worker ships & exits
except queue.Full:
pass # daemon thread; process exit reaps it
self._thread.join(timeout=5.0)
def _ship(self, buf: list[TraceRecord]) -> None:
try:
self._sink(buf)
self.exported += len(buf)
except Exception:
# Fail-open: telemetry must never break the app.
# One warning, then keep going — a dead backend
# means lost spans, not lost requests.
print("telemetry export failed (spans dropped)", file=sys.stderr)
def _run(self) -> None:
buf: list[TraceRecord] = []
last = time.monotonic()
while True:
try:
item = self._q.get(timeout=self._flush_s)
except queue.Empty:
item = _FLUSH # idle tick: flush if due, KEEP RUNNING
if item is _STOP:
self._ship(buf)
return
if item is not _FLUSH:
buf.append(item)
if buf and (item is _FLUSH or len(buf) >= self._batch or
time.monotonic() - last >= self._flush_s):
self._ship(buf)
buf.clear()
last = time.monotonic()
class Tracer:
"""Minimal span/trace recorder producing TraceRecords for a SafeExporter
or a TraceStore. ~the shape of OTel but dependency-free, so the data model
is testable with no SDK installed."""
def __init__(self, sink: Callable[[TraceRecord], None], *,
service: str = "llm_service", env: str = "dev"):
self._sink = sink
self.service, self.env = service, env
self._local = threading.local()
@contextmanager
def span(self, name: str, kind: str = "stage",
attrs: dict[str, Any] | None = None) -> Iterator[dict]:
"""One span. Inside it, the yielded dict IS the record's attrs —
mutate it before exit to add attributes discovered mid-span."""
trace_id, span_id = getattr(self._local, "trace_id", None), None
if trace_id is None:
trace_id, span_id = new_ids()
parent_id = None
else:
span_id = f"s_{uuid.uuid4().hex[:8]}"
parent_id = self._local.span_id
sp = {"trace_id": trace_id, "span_id": span_id,
"parent_span_id": parent_id, "name": name, "kind": kind,
"attrs": dict(attrs or {})}
outer = getattr(self._local, "span_id", None)
self._local.trace_id, self._local.span_id = trace_id, span_id
start = time.monotonic()
t0 = time.time()
try:
yield sp.setdefault("attrs", {})
status = "ok"
except BaseException: # incl. KeyboardInterrupt: `status` must
status = "error" # always be set before the finally block
raise
finally:
dur = (time.monotonic() - start) * 1000
rec = TraceRecord(
trace_id=trace_id, span_id=span_id,
parent_span_id=parent_id, name=name, kind=kind,
# start_ms is relative to the request's t0 (RequestCtx);
# with no request scope the `start` default gives 0.0.
start_ms=(start - getattr(self._local, "t0", start)) * 1000,
duration_ms=dur, status=status,
ts=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(t0)),
attrs=sp.get("attrs", {}))
# restore parent context
self._local.span_id = outer
if outer is None:
self._local.trace_id = None
self._sink(rec)
def begin_request(self, name: str, attrs: dict[str, Any]) -> "RequestCtx":
return RequestCtx(self, name, attrs)
class RequestCtx:
"""Explicit request scope: sets the trace root and monotonic t0 so child
spans get correct parent ids and relative timings. Use as a context
manager around one request."""
_UNSET = object() # sentinel: "no t0 was set before this request"
def __init__(self, tracer: Tracer, name: str, attrs: dict[str, Any]):
self.tracer, self.name, self.attrs = tracer, name, attrs
self._cm = None
self._prev_t0 = self._UNSET
def __enter__(self):
# Stamp t0 BEFORE entering the root span: span() computes
# start_ms = span_start - t0 when the span exits, so setting it
# first keeps the root's start_ms ~0 instead of slightly negative.
local = self.tracer._local
self._prev_t0 = getattr(local, "t0", self._UNSET)
local.t0 = time.monotonic()
try:
self._cm = self.tracer.span(self.name, kind="request",
attrs=self.attrs)
self._attrs = self._cm.__enter__()
except Exception:
self._restore_t0()
raise
return self
def __exit__(self, *exc):
try:
return self._cm.__exit__(*exc)
finally:
self._restore_t0()
def _restore_t0(self) -> None:
# Restore the previous t0 — or remove ours entirely. NEVER store
# None: getattr(local, "t0", start) only uses its default when the
# attribute is ABSENT, so a stored None makes `start - t0` raise
# TypeError in the next standalone span on this thread.
local = self.tracer._local
if self._prev_t0 is self._UNSET:
del local.t0
else:
local.t0 = self._prev_t0And the driver that produces the demo traces — llm_service/demo.py, also complete:
# llm_service/demo.py — generate sample JSONL traces exercising every path,
# then show the SafeExporter and the viewer working on real files. Stdlib only.
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from tracekit import SafeExporter, TraceStore, Tracer
HERE = Path(__file__).parent
OUT = HERE / "traces_sample.jsonl"
# Join keys repeat on EVERY span (lesson 2.6) so any slice aggregates
# without a join — the viewer's --by reads them off the records.
JOIN = {"tenant_hash": "t_9f2c", "user_hash": "u_77ab",
"session_id": "conv_12", "prompt_version": "1.4.2"}
# gpt-6-luna standard-tier list prices, 03.7 prices.yaml version 2026-11-04:
# $0.10 / 1M uncached input, $0.01 / 1M cached reads, $0.50 / 1M output.
def cost_usd(uncached: int, cached: int, out: int) -> float:
return (uncached * 0.10 + cached * 0.01 + out * 0.50) / 1_000_000
# A fake "pipeline": root request -> retrieve -> generate(llm) -> cite.
def fake_pipeline(tracer: Tracer, feature: str, *, uncached: int, cached: int,
out: int, model: str = "gpt-6-luna",
resolved: str = "gpt-6-luna-2026-09-22",
fail_stage: str | None = None):
with tracer.begin_request("POST /ask",
{**JOIN, "feature": feature}) as req:
# The root span's attributes are written when the `with` block exits,
# on success AND on failure. A line placed after the stages never runs
# when a stage raises, so the outcome is set in try/except/else: the
# failing request still records outcome="error" before re-raising.
try:
with tracer.span("retrieve", kind="retrieval",
attrs={**JOIN, "feature": feature,
"hit_count": 24, "top_score": 0.81,
"index_version": "v14"}):
time.sleep(0.001)
with tracer.span("generate", kind="llm",
attrs={**JOIN, "feature": feature,
"model_requested": model,
"model_resolved": resolved,
"provider": "openai",
"uncached_input_tokens": uncached,
"cached_input_tokens": cached,
"total_input_tokens": uncached + cached,
"output_tokens": out,
"cost_usd": cost_usd(uncached, cached, out),
"cost_source": "computed",
"price_version": "2026-11-04",
"finish_reason": "stop"}):
if fail_stage == "generate":
raise RuntimeError("provider 529")
time.sleep(0.002)
with tracer.span("cite_verify", kind="stage",
attrs={**JOIN, "feature": feature,
"citations.ok": 2}):
pass
except Exception:
req._attrs["outcome"] = "error"
req._attrs["error_class"] = "ServerError" # 529 -> ServerError
raise # the caller still sees it
else:
req._attrs["outcome"] = "ok"
def main() -> None:
store = TraceStore(OUT)
exporter = SafeExporter(store.write_all, maxsize=100, batch=10)
tracer = Tracer(exporter.emit)
# 3 healthy docs_qa requests (varying sizes), 1 support-agent run
# (bigger context -> an agent's worth of tokens), 1 failing request.
for uncached, cached, out in ((5800, 1200, 84), (6100, 1500, 92),
(5400, 900, 77)):
fake_pipeline(tracer, "docs_qa", uncached=uncached, cached=cached,
out=out)
fake_pipeline(tracer, "support-agent", uncached=26000, cached=6000,
out=540)
try:
fake_pipeline(tracer, "docs_qa", uncached=5800, cached=1200,
out=84, fail_stage="generate")
except RuntimeError:
pass
exporter.flush(2.0)
exporter.close()
print(f"wrote {OUT.name} exported={exporter.exported} dropped={exporter.dropped}")
if __name__ == "__main__":
main()Run for real — demo.py drives a fake pipeline through Tracer → SafeExporter → TraceStore (JSONL), including one failing request:
$ python demo.py
Output:
wrote traces_sample.jsonl exported=19 dropped=0Layout and running. This lesson's snippets are files inside the llm_service package folder of the llm-service project from Setup: telemetry.py (the OTel facade), pipeline.py, tracekit.py, demo.py and trace_view.py (9.2). tracekit.py, demo.py and trace_view.py are pure standard library — demo.py puts its own folder on sys.path so from tracekit import ... works, and trace_view.py is self-contained. telemetry.py and pipeline.py additionally need the OTel packages above and provider_agnostic — copy that package folder from the 03.11 project (agnostic-client) into llm-service/, the same arrangement 11A.2 uses. llm_service/ needs no __init__.py (Python 3 namespace packages), though adding one does no harm. From the repo root: cd llm-service/llm_service && python demo.py writes traces_sample.jsonl next to demo.py, then python trace_view.py traces_sample.jsonl inspects it (--summary, --errors, --by feature; every flag is in the file's header comment).
The same pattern applies to the OTel path: BatchSpanProcessor uses a bounded queue (max_queue_size, max_export_batch_size, schedule_delay_millis, export_timeout_millis — all settable) and drops on overflow. The lesson: the exporter is the least important part; the guarantee that it can never hurt you is the feature. If you self-host and your collector is down for an hour, you lose an hour of traces — the service keeps serving.
Part 5: Observability platforms#
Reference
5.1 The categories, and what "platform" means here#
An observability platform for LLM apps does four jobs: ingest traces (and often logs/metrics), store them queryably, render them for debugging (trace trees, sessions, datasets), and increasingly evaluate (scores, judges, datasets, prompt management). The market splits into categories that matter for the decision:
| Category | Examples (Nov 2026) | Ingest model | Best for |
|---|---|---|---|
| Open-source, OTel-native | Arize Phoenix, Langfuse (self-host), Opik | OTLP / SDK | Self-hosting, data residency, no per-seat cost |
| Open-source core + cloud | Langfuse Cloud, Phoenix Cloud/AX | OTLP / SDK | OSS flexibility with managed hosting |
| Commercial, eval-first | LangSmith, Braintrust | Proprietary SDK (LangSmith), OTel (Braintrust) | Tight eval→trace→dataset loops |
| Commercial, OTel-native APM | Pydantic Logfire, Datadog Agent Observability, W&B Weave | OTLP / vendor SDK | Whole-app observability, existing APM investment |
| Proxy/gateway logging | Helicone (see status note), gateway built-ins | HTTP proxy | Zero-code audit; limited depth |
5.2 The landscape as of November 2026#
Verified against official pages and PyPI. Prices and plans change monthly — treat the pricing column as a snapshot, not a quote.
| Platform | Licence / deployment | OTel support | Prompt mgmt | Evals/datasets | Cost tracking | Pricing shape (Nov 2026) |
|---|---|---|---|---|---|---|
| Langfuse | MIT core; owned by ClickHouse since January 2026 (stays open source, Cloud continues); cloud + self-host (Postgres+Redis+ClickHouse+S3) | Yes — the Python SDK (v5 since October 2026; v4 before) is OTel-based; OTLP ingest is real-time | Yes (prompt versions, labels) | Yes — datasets, experiments, LLM-as-judge | Yes — usage/cost dashboards | OSS free self-host; cloud tiers by volume |
| LangSmith | Proprietary; cloud (self-host Enterprise only) | Partial — LangChain-native tracing, OTLP export for sessions | Via LangChain hub | Deepest — trace→dataset→eval workflow | Yes | Developer free (1 seat, 5k base traces/mo); Plus $39/seat/mo (10k base traces); base traces kept 14 days, extended 180 days; overage pay-as-you-go (langchain.com/pricing, 8 Nov 2026) |
| Arize Phoenix | Elastic-2.0 (source-available); phoenix serve local, cloud/AX |
Yes — OpenInference semconv, OTLP native | Yes | Yes — evals, datasets, experiments, prompt replay | Via span attributes | Free self-host; AX commercial |
| Pydantic Logfire | MIT SDK; platform closed (self-host = enterprise licence) | Yes — OTel-native, SQL over spans | Via Pydantic AI/prompt features | Evaluations on spans | Yes — LLM cost as span attributes | Personal free 10M records/mo; Team $49/mo; $2/M overage |
| Datadog Agent Observability | Proprietary SaaS | Vendor SDKs (Python/Node/Java) emit OTel-compatible spans | No | Evaluators on spans | Yes — billed per LLM span | Consumption; free tier 40K LLM spans/mo, Pro from $160/mo (annual) incl. 100K; only LLM-kind spans bill; 15-day retention |
| Helicone | Apache-2.0 proxy; cloud + self-host | Proxy logging, not OTel-native | Yes | Datasets/evals (basic) | Yes — per-request cost | ⚠️ Acquired by Mintlify in March 2026 and put into maintenance mode (security fixes, bug fixes and new model names, no new features). Helicone's own repository and site banner now say it is no longer part of Mintlify and is part of Experiential Labs (commit of 11 November 2026); the new owner's plans are not yet published, so verify current status before relying on it. Self-host still works; don't start new projects on it |
| Braintrust | Proprietary; managed + BYOC/self-host data plane (enterprise) | Yes | Yes | Yes — eval-first: experiments, scoring, CI gates | Yes | Free tier; usage-based |
| W&B Weave | Proprietary; inside W&B | Yes | Partial | Yes — evals/tracking | Yes | Included with W&B plans |
| OpenLIT | Open-source OTel-native instrumentation | Yes — emits OTel | No | No (tracing only) | Via attributes | OSS |
| Opik (Comet) | Apache-2.0; cloud + self-host (full backend free) | SDK-based; OTel-compatible | Yes | Yes — evals, online eval, agent opt | Yes | OSS free self-host; cloud tiers |
5.3 A decision flow#
flowchart TD
Q1{"Self-host / data residency<br/>required?"} -->|Yes| Q2{"Have k8s + ClickHouse<br/>ops capacity?"}
Q1 -->|No| Q3{"Already on Datadog / W&B /<br/>LangChain ecosystem?"}
Q2 -->|Yes| LF["Langfuse self-host<br/>(MIT, OTel-native, full loop)"]
Q2 -->|No| PH["Phoenix self-host<br/>(single binary, ELv2)"]
Q3 -->|Datadog| DD["Datadog Agent Observability"]
Q3 -->|W&B| WB["W&B Weave"]
Q3 -->|LangChain-heavy| LS["LangSmith"]
Q3 -->|None| Q4{"Eval-driven dev<br/>or ops-driven?"}
Q4 -->|Eval-first| BT["Braintrust or Langfuse Cloud"]
Q4 -->|Ops/APM| LF2["Logfire or Langfuse Cloud"]The axes that actually decide it: self-host vs cloud, OTel-native vs proprietary, evals built-in vs bring-your-own, price shape (per-span vs per-seat vs per-record), and existing ecosystem. If you emit OTel, Phoenix or Logfire are the path of least resistance; if you want the whole prompt→trace→eval loop in one OSS product, Langfuse.
5.4 Minimal integrations — two of them#
Langfuse (Python SDK v5, OTel-based) — illustrative; needs LANGFUSE_PUBLIC_KEY/SECRET_KEY/BASE_URL. Version note, checked on Langfuse's docs in November 2026: Python SDK v5 (first released 14 October 2026) is the current major; it needs Langfuse Cloud or a self-hosted server v4.59.0 or newer, so a self-hosted v3 server must stay on SDK v4. For that case install langfuse==4.18.0, the last 4.x; this is the one exact pin kept in this lesson, because it is a compatibility constraint and not a preference. The snippet below uses only get_client, the @observe decorator and update_current_span; all three appear in Langfuse's current Python SDK docs (the instrumentation page documents from langfuse import observe with @observe(), name and as_type; the page does not label which SDK version introduced it, so if it errors on your version check that page). The v4 → v5 upgrade guide lists what was removed (mostly score and dataset-run helpers).
# pip install langfuse — OpenTelemetry-based since v4.
# (Upgrade deliberately: read the changelog before moving to a new SDK major.)
from langfuse import get_client, observe
langfuse = get_client() # reads env keys; call once at startup
@observe(name="generate") # emits an OTel span -> Langfuse trace
def generate(client, req): # client: 03.11's LLMClient; req: its Request
resp = client.complete(req)
langfuse.update_current_span(
metadata={"model_resolved": resp.resolved_model,
"feature": "docs_qa",
"cost_usd": resp.cost.usd if resp.cost else None,
"cost_source": resp.cost.source if resp.cost else "unknown"})
return resp.textArize Phoenix — self-host the UI, send OTLP spans to it. Illustrative:
pip install arize-phoenix opentelemetry-sdk opentelemetry-exporter-otlp
phoenix serve # UI + OTLP collector on http://localhost:6006# Point the OTel exporter at Phoenix's OTLP endpoint. Phoenix deliberately
# does NOT use the OTLP-standard HTTP port: it serves OTLP/HTTP on :6006 at
# /v1/traces (and OTLP/gRPC on :4317; Phoenix configuration docs, checked 12 November 2026) — `phoenix serve --help` for overrides.
import os
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import BatchSpanProcessor
endpoint = os.environ["PHOENIX_ENDPOINT"].rstrip("/") # http://localhost:6006
exporter = OTLPSpanExporter(endpoint=f"{endpoint}/v1/traces",
headers={}) # no auth on local phoenix
provider.add_span_processor(BatchSpanProcessor(exporter))
# `provider` is the TracerProvider returned by configure_tracing() (3.3).
# Then instrument as in Part 3 — Phoenix renders the same spans.5.5 to 5.11 go deeper: self-hosting, the OTLP endpoints and headers of each, OpenInference, choosing by constraints and the DeepEval span mapping.
Both ingest standard OTel spans; the difference is the backend and the SDK ergonomics. Langfuse adds prompt management/datasets/evals in one product; Phoenix is lighter and evals-focused with an Elastic-2.0 licence.
5.5 Where traces live: self-hosted or cloud#
A span can hold the user's question, retrieved documents, tool arguments and the answer. If content capture is on, a trace store is a second copy of your sensitive data, readable by anyone with access to the dashboard. So the first question about a backend is where the data lives, before features. 7.3 is the checklist for region, retention, access and DPAs; this subsection compares the two ways to run a backend.
| Self-hosted | Cloud service | |
|---|---|---|
| Where data lives | Your own infrastructure and region | The vendor's, in the region you pick (if offered) |
| Effort | You run, upgrade, back up and secure it | The vendor does |
| Cost shape | Your infrastructure and people | Usage or seat pricing |
| Control | Full, including network isolation | Vendor policies and your contract |
| Good for | Strict data-residency or no-data-leaves-us rules | Small teams, a fast start |
Langfuse (checked 1 December 2026 against its self-hosting and OpenTelemetry pages): you can use Langfuse Cloud or self-host. Some enterprise features need a licence key when self-hosted. The self-hosted stack has four stateful parts, plus the web and worker containers: Postgres for transactional data, ClickHouse for observability data (traces, observations and scores), Redis or Valkey for the queue and cache, and S3-compatible blob storage for raw events and attachments. Each major release can raise the minimum ClickHouse version, so read the release notes before you upgrade. The cloud has regional endpoints (host names in 5.6), and the OTel endpoint on a self-hosted server needs version 3.22.0 or later.
Arize Phoenix is open source with a local mode (phoenix serve) that needs no account, plus a hosted option. 5.2 records its licence as Elastic-2.0 (checked November 2026). The Arize docs site refused automated access on 1 December 2026, so Phoenix Cloud's regions and any licence change are unverified as of 2026-12-01.
5.6 Sending spans over OTLP: Langfuse and Phoenix#
OTLP is the OpenTelemetry protocol for sending telemetry. It comes in flavours: OTLP/HTTP with protobuf bodies (the usual), OTLP/HTTP with JSON bodies, and OTLP/gRPC. For traces, an HTTP exporter sends a POST to {endpoint}/v1/traces with an ExportTraceServiceRequest: a list of resourceSpans, each holding the resource and a list of scopeSpans with the spans. Which flavours a backend accepts is part of the choice.
Langfuse (its OpenTelemetry page, checked 1 December 2026):
- Endpoints: EU
https://cloud.langfuse.com/api/public/otel, UShttps://us.cloud.langfuse.com/api/public/otel, Japanhttps://jp.cloud.langfuse.com/api/public/otel, HIPAAhttps://hipaa.cloud.langfuse.com/api/public/otel, and a local self-hosted server athttp://localhost:3000/api/public/otel. Append/v1/tracesfor the traces-specific path. - Authentication: HTTP Basic auth with your public and secret key:
Authorization: Basic <base64(public_key:secret_key)>. - A header for real-time data:
x-langfuse-ingestion-version: 4makes directly sent OTel data appear in real time on the v4 data model. Without it, data can be delayed by up to 10 minutes. - Protocols: OTLP over HTTP, both protobuf and JSON. gRPC is not supported (the page says "not supported yet").
- Attributes it understands: OTel GenAI attributes (such as
gen_ai.request.model,gen_ai.usage.*andgen_ai.conversation.id, which becomes the session id), its ownlangfuse.*attributes (such aslangfuse.session.idandlangfuse.user.id), OpenInference'sinput.valueandoutput.value, and some others. Attributes it does not map are kept undermetadata.attributes.
Arize Phoenix (the arize-phoenix-otel page on PyPI, version 0.17.3 of 6 November 2026; the Arize docs site itself was not reachable, so the port details below come from the lesson's earlier check in 5.4 and are partly unverified as of 2026-12-01):
- A local
phoenix serveaccepts OTLP/HTTP (protobuf) on port 6006 at/v1/tracesand OTLP/gRPC on port 4317. Local Phoenix needs no authentication; a key is needed only when authentication is enabled. - The Python helper
phoenix.otel.register()sets up a tracer provider. Its settings come from the environment variablesPHOENIX_COLLECTOR_ENDPOINT,PHOENIX_PROJECT_NAME,PHOENIX_API_KEYandPHOENIX_CLIENT_HEADERS. - The helper picks the transport from the endpoint. A URL with no path is treated as gRPC on port 4317. A URL with a path (such as
/v1/traces) or a Phoenix Cloud URL uses HTTP. If gRPC is blocked, for example behind a proxy, passprotocol="http/protobuf".
5.7 A dry run: what the request looks like#
This code takes the multi-agent trace from 3.11, converts it to the OTLP/JSON body shape, and builds the requests for Langfuse and Phoenix. It sends nothing. The keys are placeholders (pk-lf-EXAMPLE, sk-lf-EXAMPLE); never put real keys in code or in a lesson. Save it as otlp_dryrun.py next to genai_trace.py and genai_demo.py:
# otlp_dryrun.py (standard library only; builds the requests but sends NOTHING)
"""Show exactly what an OTLP/HTTP export of our spans would look like, per backend."""
import base64
import json
import genai_trace as g
from genai_demo import multi_agent
KIND = {"INTERNAL": 1, "SERVER": 2, "CLIENT": 3}
STATUS = {"UNSET": 0, "OK": 1, "ERROR": 2}
def any_value(v):
if isinstance(v, bool):
return {"boolValue": v}
if isinstance(v, int):
return {"intValue": str(v)} # OTLP/JSON writes 64-bit integers as strings
if isinstance(v, float):
return {"doubleValue": v}
if isinstance(v, list):
return {"arrayValue": {"values": [any_value(x) for x in v]}}
return {"stringValue": str(v)}
def attrs(d):
return [{"key": k, "value": any_value(v)} for k, v in d.items()]
def otlp_json(tracer):
spans = []
for s in tracer.spans:
spans.append({
"traceId": s["traceId"], "spanId": s["spanId"],
**({"parentSpanId": s["parentSpanId"]} if s["parentSpanId"] else {}),
"name": s["name"], "kind": KIND[s["kind"]],
"startTimeUnixNano": str(s["startTimeUnixNano"]), "endTimeUnixNano": str(s["endTimeUnixNano"]),
"attributes": attrs(s["attributes"]), "status": {"code": STATUS[s["status"]["code"]]}})
return {"resourceSpans": [{"resource": {"attributes": attrs(tracer.resource)},
"scopeSpans": [{"scope": tracer.scope, "spans": spans}]}]}
def langfuse_request(body, host="https://cloud.langfuse.com", public_key="pk-lf-EXAMPLE", secret_key="sk-lf-EXAMPLE"):
token = base64.b64encode(f"{public_key}:{secret_key}".encode()).decode()
return {"method": "POST", "url": f"{host}/api/public/otel/v1/traces",
"headers": {"Authorization": f"Basic {token}", "Content-Type": "application/json",
"x-langfuse-ingestion-version": "4"},
"body_bytes": len(json.dumps(body))}
def phoenix_request(base="http://localhost:6006"):
# A real exporter sends protobuf here (the SDK does the encoding); local Phoenix needs no auth header.
return {"method": "POST", "url": f"{base}/v1/traces",
"headers": {"Content-Type": "application/x-protobuf"}, "body": "<protobuf bytes from the SDK>"}
if __name__ == "__main__":
t = g.Tracer("support-service")
multi_agent(t)
body = otlp_json(t)
print("Langfuse (dry run):")
print(json.dumps(langfuse_request(body), indent=2))
print("\nPhoenix local (dry run):")
print(json.dumps(phoenix_request(), indent=2))
first = dict(body["resourceSpans"][0]["scopeSpans"][0]["spans"][0])
first["attributes"] = first["attributes"][:2] + ["... more attributes ..."]
print("\nfirst span in the OTLP/JSON body (attributes shortened):")
print(json.dumps(first))Langfuse (dry run):
{
"method": "POST",
"url": "https://cloud.langfuse.com/api/public/otel/v1/traces",
"headers": {
"Authorization": "Basic cGstbGYtRVhBTVBMRTpzay1sZi1FWEFNUExF",
"Content-Type": "application/json",
"x-langfuse-ingestion-version": "4"
},
"body_bytes": 5479
}
Phoenix local (dry run):
{
"method": "POST",
"url": "http://localhost:6006/v1/traces",
"headers": {
"Content-Type": "application/x-protobuf"
},
"body": "<protobuf bytes from the SDK>"
}
first span in the OTLP/JSON body (attributes shortened):
{"traceId": "e8d6c9cdc1d642d48f849b784dc77805", "spanId": "1fc7fb7cc845424c", "parentSpanId": "36f68e1f4e17484f", "name": "chat demo-model-b", "kind": 3, "startTimeUnixNano": "1700000000000000000", "endTimeUnixNano": "1700000000600000000", "attributes": [{"key": "gen_ai.operation.name", "value": {"stringValue": "chat"}}, {"key": "gen_ai.provider.name", "value": {"stringValue": "openai"}}, "... more attributes ..."], "status": {"code": 0}}(The trace and span ids differ on every run.) Notice what is there. The Authorization header is the Base64 of public:secret. That is encoding, not encryption, which is why you only ever send it over HTTPS. Span ids are hex strings, and 64-bit numbers such as timestamps travel as strings in JSON. The Phoenix request is protobuf in practice, so the code only shows the headers; real exporters do the encoding for you.
5.8 Real exporter configuration (illustrative)#
With the real OpenTelemetry SDK the configuration is a few lines. The Langfuse variant uses the standard OTel environment variables, which the OTLP HTTP exporter reads (the Langfuse page lists the same variables). Not run; placeholders only.
# .env (never commit this file; keys shown as placeholders)
OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.langfuse.com/api/public/otel
# AUTH_STRING = base64 of "<public key>:<secret key>"; Langfuse's docs show `echo -n "pk:sk" | base64`
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic <AUTH_STRING>,x-langfuse-ingestion-version=4"# langfuse_otlp.py (illustrative, not run: needs opentelemetry-sdk and opentelemetry-exporter-otlp-proto-http)
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
provider = TracerProvider()
# With no arguments the HTTP exporter reads OTEL_EXPORTER_OTLP_ENDPOINT / OTEL_EXPORTER_OTLP_HEADERS
# and appends /v1/traces itself (standard OTel behaviour).
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)For Phoenix, the OpenInference instrumentation packages' own quickstarts build the provider by hand and point the exporter at local Phoenix. The two primary providers (illustrative, not run: each needs a key and phoenix serve running locally):
# phoenix_openai.py (illustrative, not run: needs OPENAI_API_KEY and `phoenix serve`)
from openinference.instrumentation.openai import OpenAIInstrumentor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk import trace as trace_sdk
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
tracer_provider = trace_sdk.TracerProvider()
tracer_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter("http://127.0.0.1:6006/v1/traces")))
OpenAIInstrumentor().instrument(tracer_provider=tracer_provider) # instrument BEFORE creating the client
from openai import OpenAI
client = OpenAI()
client.responses.create(model="gpt-6-luna", input="Where is order A17?") # this call now produces a span# phoenix_anthropic.py (illustrative, not run: needs ANTHROPIC_API_KEY and `phoenix serve`)
from openinference.instrumentation.anthropic import AnthropicInstrumentor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk import trace as trace_sdk
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
tracer_provider = trace_sdk.TracerProvider()
tracer_provider.add_span_processor(
SimpleSpanProcessor(OTLPSpanExporter("http://127.0.0.1:6006/v1/traces")))
AnthropicInstrumentor().instrument(tracer_provider=tracer_provider)
from anthropic import Anthropic
client = Anthropic()
client.messages.create(model="claude-haiku-5-5", max_tokens=200,
messages=[{"role": "user", "content": "Where is order A17?"}])SimpleSpanProcessor exports every span immediately, which is good for a demo and wrong for production; use BatchSpanProcessor there, and see 4.2 for a fail-open exporter. Because both tools take OTLP, one provider can export to both at once by adding two span processors (each exporter takes its own endpoint and headers), which is a cheap way to compare them on your own traffic.
5.9 OpenInference and the GenAI conventions#
OpenInference is a set of semantic conventions and instrumentation libraries from Arize for LLM applications, built on OpenTelemetry. Phoenix uses it natively. It predates the OTel GenAI conventions and uses different names. The span kind is an attribute, openinference.span.kind. The Arize docs list the values (found by search on 1 December 2026; sources differ a little in how many they list) as LLM, TOOL, AGENT, CHAIN, RETRIEVER, EMBEDDING, RERANKER, GUARDRAIL, EVALUATOR, PROMPT, DECISION and UNKNOWN. So there are two vocabularies for the same facts:
| Fact | OTel GenAI | OpenInference |
|---|---|---|
| What kind of step | gen_ai.operation.name (chat, execute_tool, ...) |
openinference.span.kind (LLM, TOOL, ...) |
| Model | gen_ai.request.model |
llm.model_name |
| Input tokens | gen_ai.usage.input_tokens |
llm.token_count.prompt |
| Output tokens | gen_ai.usage.output_tokens |
llm.token_count.completion |
| Tool name | gen_ai.tool.name |
tool.name |
| Content | opt-in gen_ai.input.messages and others |
input.value, output.value |
Backends accept more than one vocabulary. Langfuse maps GenAI attributes, its own langfuse.* attributes and OpenInference-style input.value and output.value. The practical rule: emit the vocabulary your instrumentation produces, and check on the backend's page which attributes it understands. If something you care about (cost, session id) shows up under "metadata" and not in a dedicated column, the backend did not recognise the name.
You can also translate in your own code. This function renames the four facts above, and the table it prints runs it over the multi-agent trace. The mapping from gen_ai.operation.name to a span kind is a conceptual correspondence written for this lesson, not an official table. Save it as map_spans.py:
# map_spans.py (standard library only)
"""Map GenAI operations to DeepEval span types and OpenInference span kinds (concept table, no DeepEval import)."""
import genai_trace as g
from genai_demo import multi_agent
# gen_ai.operation.name -> (DeepEval span type, OpenInference span kind)
MAPPING = {
"invoke_agent": ("agent", "AGENT"),
"invoke_workflow": ("agent", "CHAIN"),
"chat": ("llm", "LLM"),
"text_completion": ("llm", "LLM"),
"generate_content": ("llm", "LLM"),
"retrieval": ("retriever", "RETRIEVER"),
"execute_tool": ("tool", "TOOL"),
"embeddings": ("custom", "EMBEDDING"),
"plan": ("custom", "CHAIN"),
}
def to_openinference(span):
a = span["attributes"]
op = a.get("gen_ai.operation.name")
out = {"openinference.span.kind": MAPPING.get(op, ("custom", "UNKNOWN"))[1]}
renames = {"gen_ai.request.model": "llm.model_name",
"gen_ai.usage.input_tokens": "llm.token_count.prompt",
"gen_ai.usage.output_tokens": "llm.token_count.completion",
"gen_ai.tool.name": "tool.name"}
for src, dst in renames.items():
if src in a:
out[dst] = a[src]
return out
if __name__ == "__main__":
t = g.Tracer("support-service")
multi_agent(t)
print(f"{'span name':<32} {'gen_ai.operation.name':<14} {'DeepEval type':<14} OpenInference attributes")
for s in t.in_order():
op = s["attributes"]["gen_ai.operation.name"]
de = MAPPING.get(op, ("custom",))[0]
print(f"{s['name']:<32} {op:<14} {de:<14} {to_openinference(s)}")span name gen_ai.operation.name DeepEval type OpenInference attributes
invoke_agent orchestrator invoke_agent agent {'openinference.span.kind': 'AGENT'}
chat demo-model-b chat llm {'openinference.span.kind': 'LLM', 'llm.model_name': 'demo-model-b', 'llm.token_count.prompt': 700, 'llm.token_count.completion': 30}
execute_tool ask_billing_agent execute_tool tool {'openinference.span.kind': 'TOOL', 'tool.name': 'ask_billing_agent'}
invoke_agent billing_agent invoke_agent agent {'openinference.span.kind': 'AGENT'}
chat demo-model-b chat llm {'openinference.span.kind': 'LLM', 'llm.model_name': 'demo-model-b', 'llm.token_count.prompt': 500, 'llm.token_count.completion': 25}
execute_tool lookup_invoice execute_tool tool {'openinference.span.kind': 'TOOL', 'tool.name': 'lookup_invoice'}
chat demo-model-b chat llm {'openinference.span.kind': 'LLM', 'llm.model_name': 'demo-model-b', 'llm.token_count.prompt': 640, 'llm.token_count.completion': 35}
chat demo-model-b chat llm {'openinference.span.kind': 'LLM', 'llm.model_name': 'demo-model-b', 'llm.token_count.prompt': 900, 'llm.token_count.completion': 60}Each row shows the GenAI operation, a DeepEval span type (5.11) and the OpenInference attributes it would carry. The OpenInference output keeps only attributes it has a name for: invoke_agent spans get a kind but no model, because an agent span has none.
5.10 Choosing a tool: constraints first#
5.3 gives a flow. Here are the same constraints as questions, plus a way to settle a tie. Do not start from features.
- Can the data leave your environment? If not, self-host (Langfuse or Phoenix) or mask before export. If yes for some environments, decide per environment.
- Do you have people to run it? Langfuse self-hosting means four stateful services. Phoenix local is a single process. If nobody can operate ClickHouse, use a cloud service or Phoenix.
- What do you already emit? OTLP with GenAI attributes works with Langfuse directly. OpenInference instrumentation works natively with Phoenix. A mismatch costs you a translation layer (5.9).
- Do you need the eval loop in the same place? Datasets, scores and judges exist in all of these. How well they fit your workflow (6.3) is worth a one-day trial.
- What does it cost at your volume? Prices and plans change monthly; read the pricing page at decision time.
- How easy is it to leave? If your instrumentation is OTLP and your datasets export to JSONL, leaving is a configuration change. If a backend's proprietary SDK is woven through your code, leaving is a project.
A cheap way to decide is a two-backend trial: export the same spans to two tools for a week (two span processors, or a collector with two exporters) and ask five engineers to debug the same real incident in each, giving each group only the trace, not the logs. LangSmith and Braintrust, the commercial contrast cases in the 5.2 table, are the same question with a different answer to number 6; 11A.5, Part 2 teaches LangSmith.
5.11 DeepEval spans and GenAI spans: one trace for monitoring and evaluation#
An evaluation framework wants to score steps: "was this tool call correct?", "was the retrieved context relevant?". A monitoring backend wants the same steps as spans. If both describe a step with compatible vocabulary, you instrument once: the trace that ran in production can be exported and scored, instead of building a second set of test-only instrumentation. This subsection is the tracing side of that idea. 10B.5, 1.3 owns scoring spans with DeepEval and holds the full mapping table; no DeepEval code appears here.
The correspondence. DeepEval labels a span with a type: agent, llm, retriever, tool or custom (the default). The GenAI conventions label it with gen_ai.operation.name. The nearest match:
| DeepEval span type | Nearest GenAI operation | Span name pattern | Span kind | What carries across |
|---|---|---|---|---|
agent |
invoke_agent (LLM drives the loop) or invoke_workflow (your code defines the flow) |
invoke_agent {agent name} |
INTERNAL (CLIENT for a remote agent service) |
agent name; the available tools map loosely to the opt-in tool definitions |
llm |
chat (also generate_content, text_completion) |
chat {model} |
CLIENT |
provider, model, input and output tokens |
retriever |
retrieval |
retrieval |
INTERNAL |
top_k; query text and documents are opt-in |
tool |
execute_tool |
execute_tool {tool name} |
INTERNAL |
tool name; arguments and result are opt-in |
custom |
no standard operation | your own | any | your own name and attributes |
The MAPPING in 5.9 applies the same rule in code: invoke_agent becomes agent, chat becomes llm, execute_tool becomes tool, retrieval becomes retriever, and everything else, such as embeddings or plan, becomes custom.
What a trace needs so it can also be scored. Scoring needs content that monitoring may deliberately omit. Plan for the gap on purpose:
| A metric wants... | The GenAI span carries it as... | Default in production |
|---|---|---|
| The user's input and the final answer | gen_ai.input.messages, gen_ai.output.messages (opt-in) |
Off, by the privacy default |
| Retrieved context | gen_ai.retrieval.documents (opt-in) |
Off |
| Tool arguments and results | gen_ai.tool.call.arguments, gen_ai.tool.call.result (opt-in) |
Off |
| The path taken | The tree: invoke_agent > chat / execute_tool |
On: it is structure, not content |
| Cost and token counts | gen_ai.usage.* |
On |
So a production trace with content capture off supports structural scoring (did the agent call the right tool in the right order? how many steps?) but not content scoring (was the answer faithful to the context?). You can check which metrics a trace supports with a few lines. Save this as scorability.py:
# scorability.py (standard library only)
"""Which metrics can a trace support? Structure survives NO_CONTENT; text needs content capture."""
import os
import genai_trace as g
from genai_demo import single_agent
NEEDS = { # metric -> attributes that must appear on at least one span
"step count": {"gen_ai.operation.name"},
"cost per task": {"gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens"},
"right tool, right order": {"gen_ai.tool.name"},
"tool argument check": {"gen_ai.tool.call.arguments"},
"answer vs question": {"gen_ai.input.messages", "gen_ai.output.messages"},
}
for mode in ("NO_CONTENT", "SPAN_ONLY"):
os.environ[g.CAPTURE_ENV] = mode
t = g.Tracer("support-service")
single_agent(t)
seen = set().union(*(s["attributes"].keys() for s in t.spans))
print(f"capture mode {mode}")
for metric, need in NEEDS.items():
print(f" {metric:<24} {'can score' if need <= seen else 'CANNOT score (missing ' + ', '.join(sorted(need - seen)) + ')'}")capture mode NO_CONTENT
step count can score
cost per task can score
right tool, right order can score
tool argument check CANNOT score (missing gen_ai.tool.call.arguments)
answer vs question CANNOT score (missing gen_ai.input.messages, gen_ai.output.messages)
capture mode SPAN_ONLY
step count can score
cost per task can score
right tool, right order can score
tool argument check can score
answer vs question can scoreTo score content, either turn capture on for a sampled, access-controlled slice (with consent), or re-run the inputs in an evaluation environment where content is recorded.
Three ways one trace can serve both:
- Instrument for monitoring; adapt for evaluation. Export production spans to JSONL, convert them to a trajectory and grade offline. 10A.7, 10.4 is the framework-neutral version, and it works whatever produced the spans.
- Let the evaluation framework consume your instrumentation. 10B.5 notes that DeepEval has hooks for OpenInference instrumentors, so spans from a framework that already emits them can feed an eval. Read its limits before you plan on it.
- Turn traces into datasets. The trace's input and tool path become a test case that any framework (or none) can run (6.3).
Honest limits (from 10B.5's "Going deeper" note on DeepEval 4.3.6): there is no supported setting to export DeepEval's own spans to your collector, because the Confident AI endpoint setting changes the URL but keeps Confident authentication semantics; and when DeepEval joins your application's tracer provider, its processors coexist with yours but its own spans are not automatically exported through your exporters. So treat DeepEval tracing as evaluation infrastructure and your OTel pipeline as monitoring infrastructure. The mapping keeps them compatible: they share names and attributes, and each keeps its own export path. An evaluation should still work in a pull request with no key and no network.
Evaluate the plumbing too. Three things are worth measuring when you send spans to a backend: round-trip fidelity (does a span survive export and import without losing what you need?), mapping coverage (what fraction of your spans get a recognised operation or span kind?) and scorability (what fraction of traces carry the fields your metrics need?). A tiny design: take 20 recorded runs exported as OTLP/JSON and the same 20 fetched back from the backend's API. Compare the fields you care about (model, token counts, tool names, parent ids, session id). Pass when every structural field survives (ids, parent ids, names, kinds), at least 95% of spans map to a known type in your mapping function, and every attribute that lands under "metadata" instead of a dedicated field is listed and accepted or fixed on purpose.
Part 6: Sessions, users, conversations and feedback#
Deep-dive
6.1 Grouping traces into sessions#
A chat feature produces one trace per turn; the session is the conversation. Carry session_id (your conversation-store ID from 03.2) on every root span and the platform groups turns automatically — Langfuse "sessions", LangSmith "threads", Phoenix "sessions" all key off a metadata/session attribute. Add turn_index for ordering and parent_turn_id when a turn references an earlier one.
6.2 User feedback attached to traces#
Thumbs-up/down and comments are post-hoc span updates, not new spans:
- The feedback endpoint looks up the trace by
trace_id/span_id(the IDs you returned or logged), writes afeedbackscore/event onto that span (Langfusescore, Phoenixspan.log_feedback-style API, or your own JSONLfeedback.jsonljoined bytrace_id), and optionally flags the whole session for review. - 07.11, 6.1 built the
/feedbackendpoint for the docs Q&A service — the same pattern generalises: capturetrace_idat answer time, accept feedback against it later. - Sampling for review: don't read every trace. Sample ~1% uniformly plus 100% of anomalies (errors,
outcome=degraded, low feedback, high cost, injection-scan hits) into a human review queue — 07.11, 5.4 states the policy; Part 9 shows how to find the anomalies.
6.3 From trace to eval case#
The convergence 07.9 names: a production trace is a candidate eval case; an eval failure is a trace you can inspect. The flows:
- Trace → dataset: a bad or interesting production trace (with its input, retrieved context, output and scores) is exported as an eval example — Module 10A's
evalkitdataset schema (10A.2) is the target format. For agent traces, 10A.7, 10.4 shows the adapter that turns a recorded run into a gradableTrajectory. Platforms automate this: Langfuse datasets-from-traces, Phoenix datasets, Braintrust "log → dataset". - Eval → trace: a failing eval case links back to the trace that produced it, so "why did the judge score this 2/5" is answerable by inspecting the spans.
- Annotation workflows: human reviewers label traces (thumbs, categories, "which stage failed") — the labels feed both eval datasets and the failure taxonomy (07.10, 08A.14, Part 4). Online evaluation (judges/scorers run on sampled production traffic) is 10A.9's subject; this lesson supplies the traces it scores.
6.4 Replay and debug locally#
To debug a trace you don't want prod access: export the trace's spans to JSONL and replay it through the viewer (Part 9) or through a local pipeline with a fake provider (03.10's mock servers, 03.11's FakeResponses). The trace record is deliberately self-contained (input hashes, params, retrieved IDs, outputs) so a local replay needs no prod credentials.
Part 7: Privacy-safe telemetry#
Telemetry is a data-leak vector of its own: traces contain prompts (user PII), tool args (order IDs, emails), retrieved chunks (documents the user may not be allowed to see) and outputs. 07.11, 2.3.3 and 08A.14, 3.5 state the rules; this part is the operational checklist.
7.1 What never goes into telemetry by default#
| Never log | Why | Instead |
|---|---|---|
| Prompts and completions (raw) | PII, trade secrets, credentials users paste, licensed documents | Length, SHA-256 hash, redacted/sampled excerpt behind a flag (03.10, 4.5) |
| API keys, auth headers, session tokens | Obvious leak via "log the request" helpers | Allow-listed headers only |
| Raw user IDs, emails | Logs/traces read by more people than the DB | Keyed HMAC hash, purpose-scoped (USER_ID_PEPPER, purposes "logs-v1"/"llm-abuse-v1" — 03.2, 10.3, 03.7, 5.1) |
| Tool args/results (raw) | Often exactly what the user asked about | Tool name + arg hash + result status/size |
| Retrieved chunk text, embeddings | Documents the user may not be permitted to see; embeddings can leak content (07.11, 2.3.4) | chunk_ids (scoped), hit_count, top_score |
| Provider error message bodies | Can quote your input back | Error class, status, type/code only |
| Images, PDFs, base64 | Megabytes per span; a copy of the user's file | Size, media type, hash |
7.2 Redaction before export, not after#
The order matters: redact at write time, in your span attributes, before the exporter sees them. A pipeline that redacts later still has raw data in transit, in the collector, and in backups. Reuse 03.10's redact.py and 03.11's RedactHook pattern lists (API-key shapes, bearer tokens, JWTs, password= pairs, emails, card-like digit runs) — keep them under test, one test per shape. For telemetry specifically, prefer hashing over masking for identifiers (stable joins without reversible content) and allow-list attributes (only known-safe fields are set; an unknown field can't leak by being new). And add a second redaction layer in the collector — the attributes/transform processor deleting gen_ai.input.messages/gen_ai.output.messages/gen_ai.system_instructions before export, as in 3.5's config: defence in depth, so a code path that forgets to redact still can't leak.
7.3 Access control, retention, region and DPAs#
- Access control: who can read traces can read your users' prompts. Scope trace-store access like database access; separate the audit log (content-free, long retention) from the debug log (content-optional, short retention, access-controlled) — different stores, different audiences (07.11, 5.3).
- Retention: set it deliberately (30–90 days typical for traces; eval datasets built from traces get scrubbed before they leave prod). Know your vendor's default — SaaS backends have their own retention, and "we'll delete it later" isn't a control.
- Regional storage / residency: if tenants have data-residency requirements (02.9, Part 9), the trace backend must honour them — pick a region-pinned deployment or self-host; verify the vendor's data-processing terms (DPA) covers trace content, not just API payloads.
- PII detection at the boundary: 05.5, Part 8 (Presidio etc.) can scan span attributes before export for tenants under stricter regimes; Module 12 owns the full data-protection treatment.
Part 8: Cost attribution and unit economics#
Deep-dive
8.1 Tracing tokens to features, tenants and prompts#
The cost record (03.7, 5.1) already carries feature, customer (keyed hash), model, served_model, token columns and cost_usd. The trace adds the missing dimension: which stage spent it. A generate span's cost is the model bill; a retrieve span's cost is embedding+vector-DB; an agent run's cost is the sum over its model_call and tool spans — and attributing model cost to the tool that triggered it (walk parents) shows which tools drive spend (08A.14, 3.4).
The attribution keys that must be on every span from day one: feature, tenant_hash, user_hash, session_id, prompt_name, prompt_version, model_requested, model_resolved, experiment_id/variant. Missing any one makes a question unanswerable later — "cost by prompt version" is impossible if prompt_version wasn't recorded.
8.2 Unit economics#
Per-request cost is the building block; the numbers that matter:
| Metric | Formula | What it tells you |
|---|---|---|
| Cost per request | sum(cost_usd) / count(traces) by feature |
The bill per call, averaged |
| Cost per user/session | sum(cost_usd) grouped by user_hash/session_id |
Who drives spend; free-tier viability |
| Cost per resolved outcome | sum(cost_usd) / count(outcome=ok) — retries, refusals and failures still bill |
The real cost of a success (09.10's cost-per-task makes the same point) |
| Cost per stage | sum(cost_usd) by span.kind/name |
Where the money goes inside a pipeline |
| Cache-adjusted cost | (uncached×input_price + cached×cache_price + output×output_price) per call |
Whether prompt caching is actually saving (11B.3 owns strategy) |
Worked example (illustrative arithmetic, prices from 03.7's table, gpt-6.1-terra standard tier — $1.00/1M uncached input, $0.05/1M cached reads, $5.00/1M output, prices.yaml version 2026-11-04): a docs_qa request with total_input_tokens=7000 (5800 uncached + 1200 cached), output_tokens=84 → 5800×1.00e-6 + 1200×0.05e-6 + 84×5.00e-6 = 0.0058 + 0.00006 + 0.00042 ≈ $0.0063. If caching were off, the same call costs 7000×1.00e-6 + 84×5e-6 ≈ $0.0074 — the 1200 cached tokens saved ~$0.0011 (~15%). At 10k requests/day that's ~$11/day or ~$340/month — the kind of arithmetic that justifies caching work. (The same request on gpt-6-luna — $0.10/$0.01/$0.50 per 1M — costs ≈$0.0006: the ratio is what matters, and cheap models make caching less urgent but not free.)
8.3 Budgets and anomaly detection#
Tracing produces the data; 11A.2 turns it into alerts. The hand-off: emit per-request cost and token counters as metrics (counters/histograms, not just span attributes), tag them by feature/tenant_hash, and alert on relative anomalies — cost_per_request > 3× trailing-7d-median, uncached_input_tokens p95 tripling after a prompt change, attempts>1 rate spiking (retry storm), model_resolved distribution shifting (silent provider update). 11B.1 owns the optimisation playbook; 11A.2 owns the alert rules. This lesson's job is ensuring the attributes exist to compute them.
Part 9: Debugging with traces#
9.1 The playbook: five failures traces reveal#
| Symptom | First query | What the trace shows | Fix lives in |
|---|---|---|---|
| Slow request | --summary p95 by route, then --trace the slowest |
Which span dominates: retrieve (vector store), generate (TTFT vs total), tool_call (external API), or attempts>1 (retries) |
Stage-specific: index tuning, model tier, timeout, retry policy |
| Wrong answer | Find trace by request_id/time → --trace |
retrieve hit_count/top_score (bad retrieval?), prompt_version (regression?), model_resolved (provider update?), finish_reason (truncated?) |
07.10's taxonomy, 08A.14's failure modes |
| Tool loop | --errors or filter kind=tool repeated names |
Same tool_call span ×N with identical args_hash; steps counter; missing policy_decision=deny |
08A.14's budgets/loop detection |
| Retry storm | Count attempts>1 spans; check error_class |
Every span attempts=3+, error_class=RateLimit; provider 429s amplified by your retries |
03.8's retry budgets, 11C.3 |
| Cost spike | --by feature cost, then --by model_resolved |
One feature's uncached_input_tokens up (prompt edit broke cache prefix?), attempts up (retries billing), or model_resolved changed to a pricier snapshot |
11B.1, 11B.3 |
The universal first step: reproduce from the trace, not from memory. 07.10's oracle-context test ("is the answer even in the corpus?") is the RAG-specific version; the general version is "does the trace contain enough to attribute the failure to a stage?" If not, that's a telemetry gap — add the attribute, don't guess.
9.2 Building a trace viewer/CLI#
You don't need a platform to start. llm_service/trace_view.py reads the JSONL trace store and answers the debugging questions above — pure stdlib, runs on exported traces with no services. Here is the complete file:
# llm_service/trace_view.py — read JSONL traces and answer debugging questions.
#
# Pure stdlib. Usage:
# python trace_view.py traces.jsonl # list traces, newest first
# python trace_view.py traces.jsonl --trace tr_abc # render one trace tree
# python trace_view.py traces.jsonl --errors # only failed traces
# python trace_view.py traces.jsonl --by feature # aggregate by attribute
# python trace_view.py traces.jsonl --summary # service-level stats
from __future__ import annotations
import argparse
import json
import statistics
from collections import defaultdict
from pathlib import Path
# Attributes worth printing per span. Join keys (feature, tenant_hash, ...)
# repeat on every record by design (lesson 2.6) — they're for --by queries,
# not for reading the tree, so they're not in this list.
SHOW_ATTRS = ("model_resolved", "finish_reason",
"cost_usd", "uncached_input_tokens", "cached_input_tokens",
"output_tokens", "ttft_ms", "attempts", "hit_count",
"tool_name", "error_class", "outcome")
def load(path: str) -> list[dict]:
return [json.loads(l) for l in Path(path).read_text().splitlines() if l.strip()]
def group_by_trace(records: list[dict]) -> dict[str, list[dict]]:
traces: dict[str, list[dict]] = defaultdict(list)
for r in records:
traces[r["trace_id"]].append(r)
for spans in traces.values():
spans.sort(key=lambda r: r["start_ms"])
return traces
def trace_summary(spans: list[dict]) -> dict:
root = next((s for s in spans if not s["parent_span_id"]), spans[0])
return {
"trace_id": root["trace_id"],
"name": root["name"],
"spans": len(spans),
"duration_ms": max(s["start_ms"] + s["duration_ms"] for s in spans)
- min(s["start_ms"] for s in spans),
"cost": sum(s["attrs"].get("cost_usd") or 0 for s in spans),
"errors": sum(1 for s in spans if s["status"] == "error"),
"ts": root["ts"],
}
def render_tree(spans: list[dict]) -> str:
by_parent: dict[str | None, list[dict]] = defaultdict(list)
for s in spans:
by_parent[s["parent_span_id"]].append(s)
lines = []
def walk(span: dict, depth: int):
a = span["attrs"]
bits = " ".join(f"{k}={a[k]}" for k in SHOW_ATTRS if k in a)
flag = " ✗" if span["status"] == "error" else ""
lines.append(f"{' ' * depth}{span['name']} [{span['kind']}] "
f"{span['duration_ms']:.0f}ms{flag} {bits}")
for ch in by_parent.get(span["span_id"], []):
walk(ch, depth + 1)
roots = by_parent.get(None, [])
for r in roots or spans[:1]:
walk(r, 0)
return "\n".join(lines)
def cmd_list(traces: dict[str, list[dict]], only_errors: bool):
rows = []
for tid, spans in traces.items():
s = trace_summary(spans)
if only_errors and s["errors"] == 0:
continue
rows.append(s)
rows.sort(key=lambda r: r["ts"], reverse=True)
for r in rows[:25]:
print(f"{r['ts']} {r['trace_id']} {r['name']:<22} "
f"{r['spans']:>2} spans {r['duration_ms']:>8.0f}ms "
f"${r['cost']:.4f} errors={r['errors']}")
if not rows:
print("(no traces)")
def cmd_by(traces: dict[str, list[dict]], key: str):
agg: dict[str, dict] = defaultdict(
lambda: {"n": 0, "cost": 0.0, "errors": 0, "dur": []})
for spans in traces.values():
# The attribute may live on any span — model_resolved sits on the
# generate span, feature repeats on all of them. Collect the distinct
# values; "+" joins them when a trace used more than one (e.g. an
# agent run that fell back to a second model mid-trace).
vals = {str(s["attrs"][key]) for s in spans if key in s["attrs"]}
k = "+".join(sorted(vals)) if vals else "<none>"
s = trace_summary(spans)
a = agg[k]
a["n"] += 1
a["cost"] += s["cost"]
a["errors"] += s["errors"]
a["dur"].append(s["duration_ms"])
print(f"{'value':<24} {'traces':>7} {'errors':>7} {'cost_usd':>10} {'p50_ms':>9} {'p95_ms':>9}")
for k, a in sorted(agg.items(), key=lambda kv: -kv[1]["cost"]):
d = sorted(a["dur"])
p50 = statistics.median(d) if d else 0
p95 = d[min(len(d) - 1, int(len(d) * 0.95))] if d else 0
print(f"{k:<24} {a['n']:>7} {a['errors']:>7} {a['cost']:>10.4f} "
f"{p50:>9.0f} {p95:>9.0f}")
def cmd_summary(traces: dict[str, list[dict]]):
durs, costs, errs, toks = [], 0.0, 0, 0
for spans in traces.values():
s = trace_summary(spans)
durs.append(s["duration_ms"])
costs += s["cost"]
errs += s["errors"]
toks += sum(sp["attrs"].get("output_tokens") or 0 for sp in spans)
durs.sort()
n = len(durs)
print(f"traces={n} errors={errs} cost=${costs:.4f} "
f"output_tokens={toks}")
if n:
print(f"duration_ms p50={statistics.median(durs):.0f} "
f"p95={durs[min(n - 1, int(n * 0.95))]:.0f} "
f"max={durs[-1]:.0f}")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("file")
ap.add_argument("--trace")
ap.add_argument("--errors", action="store_true")
ap.add_argument("--by")
ap.add_argument("--summary", action="store_true")
args = ap.parse_args()
traces = group_by_trace(load(args.file))
if args.trace:
spans = traces.get(args.trace)
print(render_tree(spans) if spans else f"no trace {args.trace}")
elif args.by:
cmd_by(traces, args.by)
elif args.summary:
cmd_summary(traces)
else:
cmd_list(traces, args.errors)
if __name__ == "__main__":
main()Output on the demo traces (real: the standard-library code above, run for real) — demo.py (Part 4) generated 5 traces: 3 healthy docs_qa, 1 support-agent, and 1 failing docs_qa (4 docs_qa total):
$ python trace_view.py traces_sample.jsonl --by feature
Output:
value traces errors cost_usd p50_ms p95_ms
support-agent 1 0 0.0029 4 4
docs_qa 4 2 0.0025 4 4
$ python trace_view.py traces_sample.jsonl --by outcome
Output:
value traces errors cost_usd p50_ms p95_ms
ok 4 0 0.0048 4 4
error 1 2 0.0006 1 1
$ python trace_view.py traces_sample.jsonl --errors
Output:
2026-11-09T06:20:53Z tr_60f2365ff50b POST /ask 3 spans 1ms $0.0006 errors=2
$ python trace_view.py traces_sample.jsonl --trace tr_60f2365ff50b
Output:
POST /ask [request] 1ms ✗ error_class=ServerError outcome=error
retrieve [retrieval] 1ms hit_count=24
generate [llm] 0ms ✗ model_resolved=gpt-6-luna-2026-09-22 finish_reason=stop cost_usd=0.000634 uncached_input_tokens=5800 cached_input_tokens=1200 output_tokens=84Three things to read off this output. The failing trace carries outcome=error and error_class=ServerError on its root span, so --by outcome and the collector's outcome policy (3.5) can find it without looking at span status. errors=2 counts spans: the generate span that raised and the root span the exception propagated through. And --by feature shows docs_qa with 4 traces and 2 error spans because one failing request produces two error spans, not two failing requests. Timings and the trace id differ on every run; the token counts and costs do not.
Commands: --trace <id> (tree), --errors (failed only), --by <attr> (aggregate cost/p50/p95 — the attribute can live on any span, and + joins multiple values), --summary (service stats), or no flag (list traces newest-first). This is the same idea as 07.10's trace_view.py — a dependency-free renderer over exported trace data — generalised from one PipelineTrace document to a JSONL span store with tree and aggregation views.
9.3 Decision table: which debugging tool when#
| You have | Use |
|---|---|
A request_id/trace_id from a user report |
Platform trace view or trace_view.py --trace |
| "It's slow" with no specific request | --summary/--by route p95 → drill into slowest trace |
| "Answers seem worse" | Filter prompt_version/model_resolved changes; check eval-linked traces (10A.9) |
| Agent misbehaviour | --trace the run; look for repeated tool_call spans, missing policy_decision, high steps |
| Cost anomaly | --by feature/--by model_resolved; check attempts and uncached_input_tokens |
| No trace exists for the failure | Telemetry gap — add the span/attribute; the failure is unobservable by definition |
What this means for you#
You now own the observability data model and the instrumentation to fill it. The durable takeaways: instrument once, in OTel, with your own attribute names for your stages and gen_ai.* for model calls; keep content out of telemetry by default; make export fail-open; and choose the backend last. The llm_service tracing layer (telemetry.py for OTel, tracekit.py/trace_view.py for the dependency-free JSONL path) is the foundation 11A.2 turns into dashboards and alerts, 11B.3–11C.3 measure for cost/latency/reliability, and 11C.2 gates releases on. If you remember one thing: a trace that can't answer "what did it see, what did it cost, and was it any good?" isn't observability — it's logging.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Logging every prompt is the simplest observability" | It's the simplest liability. Content in telemetry is a breach vector; hash/length/redacted-excerpt gives you 90% of the debugging value at 0% of the risk |
| "OTel GenAI conventions are stable now" | They're all Development status in a repo with no releases (Nov 2026); names can change. Keep them behind a mapping layer |
| "Auto-instrumentation covers observability" | It covers the provider call only. Your stages, feature/tenant/prompt attributes and business outcome are yours to add |
| "Sampling 10% is fine" | Head sampling drops the rare bad traces you most need; tail-sample errors/high-cost/degraded, head-sample baseline |
| "The proxy gives full observability" | It sees provider calls only — blind to retrieve/rerank/policy stages, adds a hop, concentrates prompts in a third party |
| "Traces are only for debugging" | They're the substrate for evals (trace→dataset), cost attribution, feedback and alerting — the whole Module 10A and 11A loop runs on them |
| "Telemetry overhead is negligible" | It is if export is async/batched/fail-open. Synchronous export or unbounded queues turn observability into latency and outages |
| "A 200 response means success" | For LLMs, 200 + wrong answer / truncated / refused / degraded are all 'successful' HTTP — outcome and finish_reason attributes are the truth |
| "Turn content capture on so traces are useful" | Content capture is opt-in on purpose: the default is no content, and turning it on is a data-governance decision (3.8, Part 7) |
| "A multi-agent system needs a different tracing system" | It needs the same spans, nested: each agent's run is an invoke_agent span inside the step that called it (3.11) |
"One gen_ai.usage.input_tokens means the same thing across providers" |
Only after normalisation: OpenAI's number includes cached tokens, Anthropic's does not (3.10) |
| "Open source means our trace data is safe" | It means you can run it yourself; safety comes from how you secure and configure it (5.5) |
| "The OTLP endpoint is the same everywhere" | Paths, ports, auth headers and accepted protocols (HTTP vs gRPC, protobuf vs JSON) differ per backend (5.6) |
| "A trace with no content can still be scored fully" | Structure can be scored; content needs capture or a re-run (5.11) |
Key takeaways#
- LLM observability = traces + metrics + logs + evals/feedback; traces are the unit that answers "where, what, how much, how good".
- Capture per call: model requested/resolved, provider/api, prompt name/version/hash, params, token columns (module convention), cost, latency/TTFT, finish_reason, attempts, tool calls, retrieval stats, feature/tenant/user/session hashes, eval/feedback.
- Span taxonomy: root = request/run; stages = retrieve/rerank/generate/tool/guardrail; model calls carry
gen_ai.*; content is opt-in. Attributes are a schema: bounded value sets, join keys repeated on every span, redact before set — never raw IDs or query text as values. - OTel pipeline: API → SDK → processors → OTLP exporter → collector → backend. GenAI conventions are Development-status — map attribute names behind your own layer.
- Auto-instrument: official
opentelemetry-instrumentation-genai-*(beta), Traceloop/OpenLLMetry, OpenInference, provider-native (anthropicSDK'sopen_telemetry). - Sampling: tail-sample errors/cost/degraded; head-sample baseline;
ParentBasedkeeps traces whole. - Platforms (Nov 2026): Langfuse (MIT, ClickHouse-owned, v5 OTel SDK), Phoenix (ELv2,
phoenix serve), Logfire (OTel-native, record-priced), Datadog Agent Observability, LangSmith, Braintrust, Weave, Opik; Helicone was put into maintenance mode by Mintlify and now says it is part of Experiential Labs. - Privacy: redact before export, hash identifiers, content capture opt-in/scoped, access control + retention + region + DPA.
- Cost: attribute tokens to feature/tenant/prompt/stage; unit economics = cost per request/user/resolved outcome; anomalies are relative.
- Debugging: reproduce from the trace; the five failures (slow, wrong, loop, retry storm, cost spike) each have a first query.
- Telemetry must be fail-open: bounded queue, async export, drop-and-count on overflow.
- GenAI spans: every one has
gen_ai.operation.name(chat,execute_tool,invoke_agent,invoke_workflow,retrievaland others) and a name of the form{operation} {model, tool or agent name}. Model calls areCLIENTby default; tools, retrieval and in-process agents areINTERNAL. - Input tokens include cached tokens and cache and reasoning counts are subsets, so normalise each provider's usage object. A sub-agent's
invoke_agentspan nests inside the tool span that called it; hand-offs and agent-as-a-tool calls carrygen_ai.transfer.*attributes. - Lint your spans against the conventions in CI, and keep the lint rules next to the mapping layer.
- Send spans to Langfuse (HTTP only, Basic auth,
x-langfuse-ingestion-version: 4) or Phoenix (HTTP on 6006, gRPC on 4317) over OTLP. Choose the backend by constraints (data location, who runs it, what you already emit, the exit cost), and consider a two-backend trial. - DeepEval span types correspond to GenAI operations by idea, not by promise. Structure survives with content capture off; scoring content needs capture, with consent, or a re-run.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Trace / span / attribute / event / resource | The OTel primitives: one end-to-end unit, one timed operation, key-values on it, point markers, and the emitter's identity |
| GenAI semantic conventions | OTel's gen_ai.* attribute names for LLM telemetry; all Development status as of Nov 2026 |
| OTLP | OpenTelemetry Protocol — the wire format (HTTP :4318 / gRPC :4317) exporters use to reach a collector/backend |
| Span processor / exporter / sampler | SDK components that filter, batch and ship spans; ParentBased/TraceIdRatioBased decide what to keep |
| Head vs tail sampling | Decide at trace start vs buffer-then-decide on outcome; tail keeps the rare bad traces |
| Auto-instrumentation | Libraries that wrap provider SDKs/frameworks to emit spans without manual code |
| OpenInference | Arize's semantic conventions + openinference-instrumentation-* packages (Apache-2.0) |
| OpenLLMetry / traceloop-sdk | Traceloop's OTel-based instrumentation set + decorators (Apache-2.0, v0.62.4) |
| Session / trajectory | A conversation's grouped traces / an agent run's ordered step sequence (the span tree viewed as a list) |
| Trace-to-dataset / trace-to-eval-case | Exporting a production trace as an eval example; the trace↔eval convergence |
| Content capture | Opt-in gen_ai.input/output.messages attributes holding prompt/completion text — off by default |
| Keyed hash (HMAC user hash) | Pseudonymous user/tenant ID for telemetry joins without reversible PII (USER_ID_PEPPER) |
| Fail-open exporter | Telemetry that drops/buffers rather than blocks or raises — observability can't cause outages |
| Unit economics (cost per resolved outcome) | Cost divided by successful results, not calls — retries/refusals/failures still bill |
| Trace viewer / JSONL trace store | The dependency-free debugging path: spans as JSON Lines + a CLI that renders trees and aggregates |
| Attribute cardinality | The number of distinct values an attribute takes; unbounded values (IDs, query text) break backend indexing and billing — keep attribute values to bounded sets |
gen_ai.operation.name |
The attribute saying what a GenAI span is: chat, execute_tool, invoke_agent, invoke_workflow, retrieval and so on |
| Span kind | The role of a span: INTERNAL, CLIENT, SERVER, PRODUCER, CONSUMER. GenAI uses CLIENT for model calls and remote agents, INTERNAL for tools, retrieval and in-process agents |
| Requirement level | Required, conditionally required, recommended or opt-in: how much a convention asks of you for an attribute |
| Opt-in attribute | An attribute that is off by default, used for sensitive content such as prompts and tool arguments |
OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT |
The variable named by the conventions for choosing whether content goes on spans, events, both or neither |
invoke_agent / invoke_workflow |
Operations for an agent driven by the LLM, and for application-defined control flow |
| Agent as a tool | A tool call that hands work to another agent, marked with gen_ai.transfer.mode and gen_ai.transfer.target.name |
| Span link | A reference from one span to another that is related but not its parent, such as a background job started by an agent step |
| Mapping layer | One place in your code that holds attribute names, so a rename is a small change |
| Span linter | A check that spans follow the conventions: required attributes, names, kinds, no content when capture is off |
| Self-hosting / data residency | Running the backend yourself so data stays on your infrastructure / a rule that data stays in a region |
| Score (backend) | A number or label attached to a trace or span by a human, a rule or a judge |
| Span type (DeepEval) | A label (agent, llm, retriever, tool, custom) that corresponds loosely to a GenAI operation |
openinference.span.kind |
OpenInference's attribute for the kind of step (LLM, TOOL, AGENT, RETRIEVER and others) |
Exercises#
- Instrument the 03.11 client. Add a
TracingHook(aHooksubclass) toprovider_agnostic's hook list that emits a span perattempt()andafter()withmodel,cost_usd,finish_reasonattributes. Run the contract suite with a fake provider and confirm spans nest under a request span. - Build a trace summariser. Extend
trace_view.pywith--by model_resolvedand--by prompt_version. What new debugging question does each answer? - Trace→eval case.
demo.py(Part 4) writestraces_sample.jsonlwith one failingdocs_qatrace — find it withtrace_view.py --errors, take that trace, write it as anevalkitexample (10A.2), and score it: the trace is the input, the eval is the verdict. - Privacy audit. Given a span with
gen_ai.input.messagespopulated, write the redaction that strips emails/cards before export, and a test proving the raw value never reaches the sink. - Cost attribution. Using
--by featureon a week of traces, compute cost per resolved outcome for two features and explain which has the worse ratio and why. - Sampling policy. Write a
tail_sampling-style filter: keep traces wherestatus=errorORcost_usd > p95ORoutcome=degraded, plus 5% of the rest. Test it on the demo traces. - A retrieval-augmented step. Extend
single_agentingenai_demo.pyso the retrieval comes before the firstchatand the secondchathas agen_ai.prompt.versionattribute. Run the linter from 3.12. - Parallel tools and a lost span. Make the agent call two tools at the same time (start the second span before advancing the simulated clock). What should the parent-child structure be? Then delete one tool span from the list and say which of the 3.12 completeness checks catches it.
- Third provider shape. Write a
usage_mappingfunction for a usage object withprompt_tokens,completion_tokensandprompt_tokens_details.cached_tokens(the Chat Completions names). Use 03.7 to check which counts include which, and add a seeded mistake to the linter. - Dual export and the mapping. With the real SDK, configure two span processors so one trace goes to local Phoenix and, with placeholder keys, to the Langfuse EU endpoint. Then add
invoke_workflow(toCHAINand DeepEvalagent),embeddings(toEMBEDDING) andgen_ai.conversation.id(tosession.id) tomap_spans.py. - Scorability audit. Take a trace from
genai_demo.pyand list which of these metrics could be computed with content capture off: tool-call correctness, step count, answer faithfulness, retrieval relevance, cost per task.
Hints for the exercises
- 03.11's
Hookhasbefore,attempt,after,errorandabandoned;CallContext.call_idis the key you share between them. Start the request span inbefore()and keep it in a dict keyed byctx.call_id; add eachAttempt(model_key,n,ok,error_type,latency_ms,cost_usd) as a span event or child span; end the span inafter()orerror()and pop it from the dict, so nothing leaks. Hooks run on the caller's thread (or the event loop), so keep the work tiny and wrap it intry/except— a tracing hook is an observer and must never break the call. A child span nests under the request span only while the request span is current (opentelemetry.trace.use_span(span)); with the in-memory exporter from the OTel SDK you can assert onparentids in a test. - No code change is needed:
--byreads any attribute from any span, so both flags already work.--by model_resolvedanswers "did a snapshot change and what does each snapshot cost and how slow is it?";--by prompt_versionanswers "did the cost, error rate or latency shift with a prompt release?". The demo writes a single value for each, so edit the loops indemo.py(a secondresolved=and a secondJOIN["prompt_version"]) to see two rows. - The demo trace carries only hashes, counts and costs, no prompt text (by design: Part 7). So the example's
inputscan hold what the trace knows (feature,prompt_version,index_version) plus a placeholderquery; useprovenance.source="production-log"andpii_reviewed=False, and tag itfailure_stage="generate". The point of the exercise is the gap you hit: to turn a trace into a gradable case you need the input, which is exactly what content capture (opt-in) or the access-controlled store provides. - Test the redactor on the shapes of 7.2 one by one (email, API-key shape, card-like digit run), then add a sink that records what it receives and assert none of the raw values appear in it. Redact before
set_attributes, not in the sink. - Cost per resolved outcome is
sum(cost_usd) / count(outcome=ok). On the demo tracesdocs_qacosts about $0.0025 over 4 traces, but only 3 resolved, so it is about $0.00084 per resolved answer against $0.00063 per request. The gap (about a third) comes from the failed request, whose span still carries a cost in the demo (a real 5xx usually bills nothing, but refusals, truncated answers and calls that produced tokens before failing do). With a week of real traces, the feature with more retries, refusals or truncations shows the bigger gap. - Compute per-trace cost with
trace_summary()fromtrace_view.py. On five demo traces the viewer's p95 formula returns the maximum, socost > p95(strictly greater) keeps nothing extra; that is a small-sample effect, not a bug. Use>=, or a fixed threshold, for the demo, and remember the filter must see the whole trace before it decides, which is why the real one lives in the collector. - Pass
**{"gen_ai.prompt.version": "v7"}through theextraargument ofchat. The linter should report zero problems. - Both
execute_toolspans are children of the sameinvoke_agentspan (or of thechatthat asked for them) and each must lie inside its parent's time range. A deleted tool span makes the "oneexecute_toolper tool call" completeness check fail, because the loop says two tool calls and the tree shows one. prompt_tokensalready includes cached tokens, asinput_tokensdoes for Responses. Port the assertion fromusage_mapping.pyintolint()for the seeded mistake.OTLPSpanExportertakesendpointandheaders, so each exporter can have its own instead of the shared environment variables. Keep the mapping in one dictionary.- Structure and usage survive (step count, cost per task, right tool in the right order); anything that reads text does not (answer faithfulness, retrieval relevance).
scorability.pyshows the pattern.
Check yourself#
- Why can't classic APM metrics (error rate, latency) detect a wrong-but-200 LLM answer?Because a wrong answer returns HTTP 200 with no exception — error rate and latency look normal. You need content/quality signals (
outcome,finish_reason, eval scores, feedback) that APM doesn't capture. - What are the four legs of LLM observability, and which does this lesson own?Traces, metrics, logs, and evals+feedback. This lesson owns traces (data model, instrumentation, platforms); 11A.2 owns metrics/dashboards/alerts; 03.10 owns logs; Module 10A owns eval methodology.
- Why record both
model_requestedandmodel_resolved? When do they differ, and what does each tell you?They can differ when an alias moves, a router picks another model, or a fallback fires — the response names the served snapshot.model_requestedis what you asked for;model_resolvedis what actually served (and priced) the call. - What does the module's token convention require you to log, and why can't you reconstruct a missing column?
uncached_input_tokens,cached_input_tokens,cache_write_tokens,total_input_tokens,output_tokens(incl. reasoning),reasoning_tokens. Providers report overlapping/different subsets; you can't reconstruct which tokens were cached vs written after the fact. - What's the difference between head and tail sampling, and which suits LLM traces?Head decides at trace start (random %); tail buffers the whole trace and decides on outcome (keep errors/slow/expensive). LLM traces need tail sampling because the rare bad traces are the ones you most need.
- As of November 2026, what's the stability status of the OTel GenAI conventions and where do they live?All Development status, no releases, in
open-telemetry/semantic-conventions-genai— names can change; keep them behind a mapping layer. - Which three auto-instrumentation options exist for the
openaiSDK, and their trade-offs?Officialopentelemetry-instrumentation-genai-openai(beta, standardgen_ai.*), Traceloop/OpenLLMetry (broad coverage, decorators), OpenInference (Arize/Phoenix native). Trade-offs: beta vs breadth vs ecosystem. - Why must telemetry export be fail-open, and what does the safe exporter guarantee?Because a tracing failure inside the request path becomes an outage. The safe exporter guarantees: emit never blocks/raises, bounded queue drops-and-counts on overflow, sink exceptions are swallowed after one warning.
- What's the difference between a trace, a session and a trajectory?Trace = one request/run's span tree; session = a conversation's grouped traces; trajectory = the agent run's ordered step sequence (span tree as a list for replay/eval).
- Name three things that must never go into telemetry by default and the safe alternative for each.Raw prompts/completions (→ hash/length/redacted excerpt), raw user IDs/emails (→ keyed HMAC hash), tool args/results (→ name + arg hash + status). Also retrieved chunk text and provider error bodies.
- How does a production trace become an eval case?Export the trace's input/context/output/scores as an evalkit dataset example; the eval scores it. The trace is the candidate case, the eval is the verdict — they converge.
- What's the formula for cost per resolved outcome, and why does it differ from cost per request?
sum(cost_usd) / count(outcome=ok)— because retries, refusals, truncations and failures still bill; cost per request hides the cost of failures. - For the five debugging scenarios (slow, wrong, loop, retry storm, cost spike), what's the first query for each?Slow →
--summary/--by routep95 then slowest--trace; wrong → find trace, check retrieve/prompt_version/model_resolved/finish_reason; loop → repeated tool_call spans + steps counter; retry storm →attempts>1count + error_class; cost spike →--by feature/model_resolved+ uncached_input_tokens/attempts. - Why is Helicone a risky choice for a new project as of November 2026?Acquired by Mintlify in March 2026 and moved to maintenance mode (Mintlify's announcement: security updates, bug fixes and new models only). Helicone's own repository (
Helicone/helicone, commit of 11 November 2026) shows its site banner changing from "no longer part of Mintlify" to "now part of Experiential Labs", with "details to come soon" for signed-out visitors. The product's future is uncertain, so don't start new projects on it. - What
gen_ai.operation.namevalues do an agent run, a tool call and a model call use, and what are their span names and kinds?An agent run isinvoke_agent(span nameinvoke_agent {agent name}, kindINTERNAL, orCLIENTfor a remote agent service). A tool call isexecute_tool(execute_tool {tool name},INTERNAL). A model call ischat(chat {model},CLIENTby default). - How do you make Anthropic's and OpenAI's usage objects produce the same
gen_ai.usage.*attributes?Makegen_ai.usage.input_tokensthe total input including cached tokens, and report cache reads and writes as subsets. OpenAI'sinput_tokensalready is the total. For Anthropic addcache_read_input_tokensandcache_creation_input_tokenstoinput_tokens. - In a multi-agent run where an orchestrator calls a sub-agent as a tool, where does the sub-agent's
invoke_agentspan sit, and what doesgen_ai.transfer.modeadd?Inside theexecute_toolspan that called it, because the sub-agent runs while that span is current.gen_ai.transfer.modemarks the call asreturn_to_caller(the caller waits) orpass_control(a hand-off), andgen_ai.transfer.target.namenames the target; instrumentation should not add extra spans for the transfer. - How do you authenticate to Langfuse's OTLP endpoint, which protocols does it accept, and what does
x-langfuse-ingestion-version: 4do?HTTP Basic auth:Authorization: Basicplus the Base64 ofpublic_key:secret_key. It accepts OTLP over HTTP (protobuf and JSON) and not gRPC. The header makes directly sent OTel data appear in real time on the v4 data model instead of up to 10 minutes late. - What does Phoenix's
register()do with an endpoint that has no path, and with one that has a path?The Python helper treats a URL with no path as gRPC on port 4317 and a URL with a path (or a Phoenix Cloud URL) as HTTP. It accepts an explicitprotocol="http/protobuf"for networks where gRPC is blocked. - Why can a production trace with content capture off be scored for tool use but not for faithfulness?Tool use is a property of span structure and names, which are always recorded. Faithfulness needs the retrieved context and the answer text, which are opt-in content attributes and are off by default.
Further resources#
- OpenTelemetry docs: opentelemetry.io/docs — traces, SDK, exporters, collector, sampling
- GenAI semantic conventions: github.com/open-telemetry/semantic-conventions-genai (Development status — check before relying on names)
- Python GenAI instrumentation: github.com/open-telemetry/opentelemetry-python-genai (beta packages)
- Langfuse: langfuse.com/docs — OTel-based Python SDK (v5), self-hosting
- Arize Phoenix / OpenInference: arize.com/docs/phoenix and openinference.dev
- Traceloop/OpenLLMetry: github.com/traceloop/openllmetry
- Pydantic Logfire: pydantic.dev/logfire and pricing
- Datadog Agent Observability: docs.datadoghq.com/llm_observability
- LangSmith: docs.langchain.com/langsmith
- Opik: comet.com/docs/opik
- Helicone status: mintlify.com/blog/mintlify-acquires-helicone and the
Helicone/heliconerepository (the ownership banner) - GenAI conventions pages used in 3.7 to 3.13: docs/gen-ai/ (operations, execute tool, agent spans, metrics)
- Langfuse OpenTelemetry integration: langfuse.com/integrations/native/opentelemetry (endpoints, headers, mapped attributes) and self-hosting
- arize-phoenix-otel: pypi.org/project/arize-phoenix-otel (
register()and its environment variables) - OTLP specification: opentelemetry.io/docs/specs/otlp
- OpenTelemetry Python instrumentation: opentelemetry.io/docs/languages/python/instrumentation
- Earlier in this path: 03.7 cost/caching, 03.10 logging/debugging, 03.11 provider-agnostic client, 07.10 RAG debugging, 07.11 production RAG, 08A.14 reliable agents, 04.10 prompt versioning, Module 10A evaluation
← Module 10B: Eval Frameworks | Module 11A overview | 11A.2 — Metrics, Dashboards, SLOs and Alerting →