For LLM observability with OpenTelemetry, instrument every model call, tool call and agent invocation as spans that follow the OpenTelemetry GenAI semantic conventions: chat {model}, execute_ and invoke_, with gen_ai.* attributes for provider, model, token usage and finish reasons. Keep prompts and completions off the span by default. Capture them only through an opt-in path that sends content to a separate store with its own access controls. Work out cost at query time from token counts and a price table with effective dates, not inside the app. Link evaluations back to the exact span with gen_ events. The conventions are still marked Development, so pin your instrumentation versions and expect renames.
The rest of this post covers what the conventions define today, a reference span tree for an agent run, the cost maths most teams get wrong, how to handle content and PII, which backends to use, and a telemetry contract you can adopt as it stands.
01What are the OpenTelemetry GenAI semantic conventions, and are they stable?
They are a shared vocabulary for GenAI telemetry: span names, attribute keys, metrics and events. Any OTLP backend can read them without a vendor SDK. They cover model inference, embeddings, retrieval, memory operations, tool execution, agents and workflows, plus MCP. There are provider-specific pages for Anthropic, OpenAI, AWS Bedrock and Azure AI Inference.
They are not stable. Every GenAI page and almost every gen_ai.* attribute is marked Development. The history explains why you should pin versions:
| Date | Release | What changed |
|---|---|---|
| Aug 2025 | semconv v1.37.0 | gen_ renamed to gen_. Per-message events (gen_, gen_…) replaced by gen_, gen_ and gen_. |
| Jun 2026 | semconv v1.42.0 | All GenAI, OpenAI and MCP conventions moved to the dedicated semantic-conventions-genai repository. The copies in the core repo are deprecated. |
| Unreleased (at the time of writing) | semantic-conventions-genai main |
The gen_ histogram (and its gen_ attribute) is replaced by separate gen_ counters and per-operation histograms. Per-modality token attributes are added. |
The instrumentation libraries moved too. In Python, the official GenAI instrumentations now live in opentelemetry-python-genai. opentelemetry-instrumentation-openai-v2 is deprecated in favour of opentelemetry-instrumentation-genai-openai, which the deprecation notice says "contains breaking changes". Older instrumentations used OTEL_ to switch from the v1.36 shapes to the newer ones. If any of your services are still on the older packages, check that flag.
Our position: adopt them anyway. Instrumentation that is mostly standard and occasionally renamed costs far less than an LLM vendor's proprietary SDK spread through your codebase. You handle the renames centrally in the Collector, as shown later in this post.
02What an agent run looks like as a trace
The conventions define three span families that matter for agents. All of the names below come from the model spans and agent spans specs:
| Span | Name format | Kind | Key attributes |
|---|---|---|---|
| Inference | {gen_, e.g. chat claude-… |
CLIENT (INTERNAL for in-process models) |
gen_, gen_, gen_, gen_, gen_, gen_ |
| Tool execution | execute_ |
INTERNAL |
gen_, gen_, gen_, opt-in gen_ / .result |
| Agent | invoke_ |
CLIENT for remote agents, INTERNAL for in-process |
gen_, gen_, gen_, gen_ |
There are also invoke_, plan, create_, retrieval, embeddings and a family of memory operations. Most teams need only the three above.
Here is one turn of an illustrative support-triage agent, with the HTTP, database and MCP spans your existing instrumentation already produces:
POST /v1/tickets/{id}/triage SERVER http
└─ invoke_agent support-triage INTERNAL conversation.id=conv_81f…
├─ chat <model> CLIENT in=18,204 (cache_read=16,010) out=412
├─ execute_tool search_orders INTERNAL tool.call.id=toolu_01…
│ └─ SELECT orders CLIENT db
├─ chat <model> CLIENT in=19,030 (cache_read=18,204) out=96
├─ execute_tool issue_refund INTERNAL
│ └─ tools/call issue_refund CLIENT mcp ──► server span in MCP process
└─ chat <model> CLIENT finish_reasons=["stop"]Three things make this trace useful, not just pretty.
- The tool span sits between the two model calls it connects. When the second
chatcall goes wrong, you can see the exact tool result that went into it. You can also see the database query that produced that result. - Token usage lives on each inference span, so you can add it up per agent, per tool loop and per tenant.
- The MCP hop is one trace, not two. The MCP conventions inject W3C
traceparent/tracestateinto the JSON-RPC request'sparams._, unprefixed, as defined by SEP-414. This matters because one MCP request can span several HTTP requests, and one streamable HTTP response can carry several MCP messages. HTTP-level propagation alone gives you the wrong parent.meta
If distributed tracing itself is new territory for your team, read Anatomy of a request: one click traced through CDN, WAF, load balancer, app and database first. Everything here sits on top of it.
03How to instrument an LLM agent with OpenTelemetry
Split the work in two. Use the official instrumentations for the provider SDK calls, because they handle streaming, retries and the provider's token-field quirks. Write the agent and tool spans by hand, because only your agent harness knows where an agent starts and what a tool is.
Provider calls: use the official instrumentation
pip install opentelemetry-sdk opentelemetry-exporter-otlp \
opentelemetry-instrumentation-genai-anthropicfrom opentelemetry.instrumentation.genai.anthropic import AnthropicInstrumentor
AnthropicInstrumentor().instrument() # every client.messages.create() now emits a chat spanEquivalent packages exist for OpenAI, Google GenAI, Bedrock, LangChain, LlamaIndex, the OpenAI Agents SDK, the Claude Agent SDK and others. Check the repository listing for the current set. Every one of them is pre-1.0 (1.3b0.dev on main at the time of writing). Pin exact versions.
Agent and tool spans: write them yourself
import os
from opentelemetry import trace
from opentelemetry.trace import SpanKind
tracer = trace.get_tracer("acme.support_agent", "2026.06.1")
AGENT = "support-triage"
MODEL = os.environ["AGENT_MODEL"] # exact provider model id; keep it in config
def run_agent(client, messages, tools, conversation_id: str):
with tracer.start_as_current_span(
f"invoke_agent {AGENT}",
kind=SpanKind.INTERNAL,
attributes={
# Set at creation time: samplers can only see attributes present at start.
"gen_ai.operation.name": "invoke_agent",
"gen_ai.agent.name": AGENT,
"gen_ai.agent.version": "2026-06-26",
"gen_ai.provider.name": "anthropic",
"gen_ai.conversation.id": conversation_id,
},
):
for step in range(MAX_STEPS):
resp = client.messages.create( # auto-instrumented chat span
model=MODEL, max_tokens=2048, messages=messages, tools=TOOL_SCHEMAS,
)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
return resp
results = [run_tool(block) for block in resp.content if block.type == "tool_use"]
messages.append({"role": "user", "content": results})
raise StepBudgetExceeded(AGENT, MAX_STEPS)
def run_tool(call):
with tracer.start_as_current_span(
f"execute_tool {call.name}",
kind=SpanKind.INTERNAL,
attributes={
"gen_ai.operation.name": "execute_tool",
"gen_ai.tool.name": call.name,
"gen_ai.tool.call.id": call.id,
"gen_ai.tool.type": "function",
"gen_ai.agent.name": AGENT,
},
) as span:
try:
output = TOOLS[call.name](**call.input)
return {"type": "tool_result", "tool_use_id": call.id, "content": output}
except Exception as exc:
# start_as_current_span records the exception and sets ERROR status for us;
# error.type is the low-cardinality class the spec asks for.
span.set_attribute("error.type", type(exc).__qualname__)
raiseTwo details that are easy to miss:
- Set sampling-relevant attributes at span creation. The spec lists
gen_,ai. operation. name gen_,ai. provider. name gen_,ai. request. model gen_andai. tool. name gen_as attributes that "SHOULD be provided at span creation time". A head sampler never sees anything you add later.ai. agent. name - Don't invent a
gen_. The spec says plainly that a new UUID, the trace ID or a hash of the content "SHOULD NOT be used as a fallback". Use the conversation or thread ID your application already stores, or leave it unset.ai. conversation. id
The step budget in that loop is not decoration. Our post Agent failure modes in production: loops, drift, tool misuse and recovery explains why. Traces are how you find the right value for MAX_STEPS.
04Token and cost attribution: where most dashboards are wrong
gen_ai.usage.input_tokens includes cached tokens
The convention defines gen_ as the total input, including cache reads and cache writes. gen_ and gen_ are subsets of that total. Reasoning tokens (gen_) are likewise a subset of gen_.
Providers don't all report usage this way. Anthropic's API reports input_ excluding cached tokens, so the Anthropic page of the convention requires instrumentation to compute input_. OpenAI maps cache reads from usage..
So if you price gen_ at the base input rate, you over-count cached traffic badly. Here is a worked example.
Worked example (illustrative, list prices from Anthropic's pricing page at the time of writing (check the page, they change often), Claude Sonnet 5.5: $2/MTok input, $2.50/MTok 5-minute cache write, $0.20/MTok cache read, $10/MTok output). Assume one agent run makes 12 inference calls. Each call has 20,000 input tokens (16,000 cache read, 2,000 cache write, 2,000 uncached) and 800 output tokens.
| Line | Per call | Cost per call |
|---|---|---|
| Uncached input | 2,000 × $2 / 1M | $0.0040 |
| Cache write (5 min) | 2,000 × $2.50 / 1M | $0.0050 |
| Cache read | 16,000 × $0.20 / 1M | $0.0032 |
| Output | 800 × $10 / 1M | $0.0080 |
| Correct total | $0.0202 → $0.242 per run | |
Naive: input_ × base rate + output |
20,000 × $2/1M + $0.008 | $0.0480 → $0.576 per run |
The naive number is 2.4× too high. It also hides the thing you most need to see: whether prompt caching is working at all.
Compute cost at query time, not in the app
We don't stamp a cost attribute on spans. Prices change, and pricing modifiers stack: batch discounts, data-residency multipliers (Anthropic charges 1.1× for US-only inference on 4.6+ models), fast modes, and 5-minute versus 1-hour cache-write rates. A cost written into a span at emit time stays wrong for ever once any of those change. A versioned price table joined at query time can be corrected after the fact.
The convention has no cost attribute in any case. Some backends accept their own (Langfuse reads gen_ or langfuse.), but treat that as a display convenience, not your system of record.
-- Postgres-flavoured; adapt to your span store (ClickHouse, BigQuery, etc.).
-- model_prices: one row per (model, price component) with valid_from / valid_to.
WITH calls AS (
SELECT trace_id, span_id, start_time,
attrs->>'gen_ai.response.model' AS model,
(attrs->>'gen_ai.usage.input_tokens')::bigint AS in_total,
COALESCE((attrs->>'gen_ai.usage.cache_read.input_tokens')::bigint, 0) AS in_cache_read,
COALESCE((attrs->>'gen_ai.usage.cache_write.input_tokens')::bigint, 0) AS in_cache_write,
(attrs->>'gen_ai.usage.output_tokens')::bigint AS out_total,
attrs->>'app.tenant_id' AS tenant
FROM spans
WHERE attrs->>'gen_ai.operation.name' IN ('chat', 'generate_content', 'text_completion')
)
SELECT c.tenant,
date_trunc('day', c.start_time) AS day,
SUM( (c.in_total - c.in_cache_read - c.in_cache_write) * p.input_usd_per_mtok
+ c.in_cache_read * p.cache_read_usd_per_mtok
+ c.in_cache_write * p.cache_write_usd_per_mtok
+ c.out_total * p.output_usd_per_mtok ) / 1e6 AS cost_usd
FROM calls c
JOIN model_prices p
ON c.model = p.model
AND c.start_time >= p.valid_from
AND (p.valid_to IS NULL OR c.start_time < p.valid_to)
GROUP BY 1, 2;Use gen_ (the model that actually answered), not gen_ (what you asked for, which may be an alias). Add your own attributes for anything the convention can't express yet: app., app.feature, app. (batch, fast, residency). The convention also doesn't separate 5-minute from 1-hour cache writes. If you use both, record the split yourself from Anthropic's usage. and usage..
Compare models by cost per successful task, not tokens per call. Tokenisers differ. Anthropic notes that Claude 4.7 and later produce "approximately 30% more tokens for the same text" than earlier models, so token counts alone mislead across model generations.
Metrics for alerting, traces for attribution
If you tail-sample traces, trace-derived totals will under-count. Alert on metrics recorded before sampling. On main, the convention defines monotonic counters (gen_, …output_, …cache_, …cache_, …reasoning.) for totals, and histograms (gen_ / …output_) for p95/p99 outliers only. Be aware of drift here: the Python opentelemetry-util-genai 1.2b0 package (24 Sept 2026) still records the older gen_ histogram. Check what your instrumentation emits before you build dashboards on it. Never put user, conversation or trace IDs on metric attributes. That is a cardinality bill, as covered in OpenTelemetry without the bill: sampling, cardinality and when to leave Datadog.
05How to capture prompts and completions safely (PII)
The convention's default is the right one: instrumentations SHOULD NOT capture instructions, inputs or outputs unless you opt in. It then describes three patterns:
- Don't record content (default).
- Record content on span attributes (
gen_,ai. input. messages gen_,ai. output. messages gen_). The spec suggests this for cases where "privacy regulations do not apply or the telemetry storage complies with them, for example, in pre-production environments."ai. system_ instructions - Upload content to external storage and record references on the span. The spec recommends this for production.
In the Python instrumentations, OTEL_ takes NO_CONTENT (default), SPAN_ONLY, EVENT_ONLY or SPAN_. Pattern 3 is a completion hook: OTEL_ plus OTEL_ set to any fsspec URI (gs://…, s3://…). The built-in hook writes the content out and records a reference attribute such as gen_ on the span. The spec still lists a common reference format as a TODO, so expect this to change.
What we'd do in production:
- Pattern 3, with your own hook. It should redact before upload, write to a bucket in the right region with its own IAM, encryption and retention, and key objects by tenant and conversation. Then a GDPR erasure request becomes "delete this prefix", not "rewrite a trace backend's immutable storage". The spec says the hook runs regardless of the span sampling decision, so you keep complete content for evals even when you sample traces heavily.
- Treat tool arguments and results as more sensitive than prompts.
gen_is often a raw database row or API payload, and it carries data the user never typed. It is opt-in for good reason.ai. tool. call. result - Treat system instructions as IP, not PII. They are low-risk for privacy and high-risk competitively. Keep them out of any backend your vendors' support staff can open.
- Pseudonymise user IDs with a keyed HMAC, not a plain hash. A SHA-256 of an email address can be reversed with a dictionary of known emails.
- Keep a Collector-side safety net, below, for when someone flips
SPAN_on in production by mistake.AND_ EVENT
Prompt content is also an attack surface. Anything an attacker can inject into a prompt will end up in your traces and your eval datasets. See Securing AI agents: prompt injection, tool permissions and least privilege for MCP.
06Reference asset: the LLM telemetry contract
This is the policy we'd put in a repo and enforce in review and in the Collector. It says, for each signal, what you record, where it goes and who can read it.
Attribute policy
| Attribute / signal | Record? | Where it goes | Class | Notes |
|---|---|---|---|---|
gen_, gen_, gen_, server. |
Always, at span start | All backends | Operational | Needed by samplers |
gen_, gen_, gen_ |
Always | All backends | Operational | response.id is your fallback join key to evals |
gen_ (all token counts) |
Always | All backends | Operational | Cost is derived at query time |
gen_, max_tokens, reasoning. |
Always | All backends | Operational | Essential when you diff behaviour between versions |
gen_, gen_ |
Always, when templated | All backends | Operational | The column you group eval scores by |
gen_, gen_, gen_, gen_ |
Always | All backends | Operational | |
gen_ |
When your app has one | All backends | Pseudonymous | Never synthesise one |
app., app.feature, app. (HMAC) |
Always | All backends | Pseudonymous | Not on metrics |
gen_, gen_ |
Prod: via hook only | Restricted content store | Personal data | Reference attribute on the span |
gen_, gen_ |
Prod: via hook only, per-tool allowlist | Restricted content store | Personal / confidential | Default deny |
gen_, gen_ |
Store by prompt version, not per call | Prompt registry | Confidential | Per-call capture is redundant and costly |
gen_ |
No | – | Personal data | Usually the PII itself |
gen_, gen_, …time_ |
Always, pre-sampling | Metrics backend | Operational | Attributes: provider, model, operation, error.type only |
gen_ events |
Always | LLM backend + warehouse | Operational | Parented to the evaluated span |
Collector config: one pipeline per audience
The same OTLP stream feeds two pipelines. General APM gets metadata with all content stripped, plus a regex PII sweep. A restricted LLM backend gets the PII-swept stream. A transform fixes mixed instrumentation versions on the way through.
receivers:
otlp:
protocols:
grpc: { endpoint: 0.0.0.0:4317 }
http: { endpoint: 0.0.0.0:4318 }
processors:
memory_limiter:
check_interval: 1s
limit_percentage: 80
spike_limit_percentage: 20
# Normalise pre-v1.37 instrumentation still emitting gen_ai.system.
transform/genai_compat:
trace_statements:
- context: span
statements:
- set(attributes["gen_ai.provider.name"], attributes["gen_ai.system"]) where attributes["gen_ai.provider.name"] == nil and attributes["gen_ai.system"] != nil
- delete_key(attributes, "gen_ai.system")
# Content never reaches general-purpose APM.
attributes/strip_genai_content:
actions:
- { key: gen_ai.input.messages, action: delete }
- { key: gen_ai.output.messages, action: delete }
- { key: gen_ai.system_instructions, action: delete }
- { key: gen_ai.tool.definitions, action: delete }
- { key: gen_ai.tool.call.arguments, action: delete }
- { key: gen_ai.tool.call.result, action: delete }
- { pattern: '^gen_ai\.prompt\.variable\..+', action: delete }
# Safety net for anything that slipped through (RE2 syntax).
redaction/pii:
allow_all_keys: true
blocked_values:
- '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}' # email
- '\b4[0-9]{12}(?:[0-9]{3})?\b' # Visa PAN
- '\b5[1-5][0-9]{14}\b' # Mastercard PAN
summary: info
batch: {}
exporters:
otlphttp/apm:
endpoint: https://otlp.apm.example.internal
otlphttp/llm:
endpoint: https://langfuse.example.internal/api/public/otel
headers:
Authorization: "Basic ${env:LANGFUSE_BASIC_AUTH}"
service:
pipelines:
traces/apm:
receivers: [otlp]
processors: [memory_limiter, transform/genai_compat, attributes/strip_genai_content, redaction/pii, batch]
exporters: [otlphttp/apm]
traces/llm:
receivers: [otlp]
processors: [memory_limiter, transform/genai_compat, redaction/pii, batch]
exporters: [otlphttp/llm]
logs/apm: # gen_ai.client.inference.operation.details events carry content too
receivers: [otlp]
processors: [memory_limiter, attributes/strip_genai_content, redaction/pii, batch]
exporters: [otlphttp/apm]The redaction processor is Beta for traces and Alpha for logs. Regex redaction is a backstop, not a privacy programme. It will miss names, addresses and anything paraphrased. The real control is not capturing content in the first place.
Readiness checklist
- Every provider SDK call produces a
chat/generate_span withcontent gen_populated, including cache splits.ai. usage. * - Every tool call produces an
execute_span that is a child of the agent span, including tools run in thread pools or queues.tool - Agent spans carry
gen_and a version you can map to a deploy.ai. agent. name - MCP clients and servers propagate context through
params._.meta - Content capture is
NO_CONTENTin production, and a hook writes to a restricted store with retention set. - Cost comes from a dated price table, and finance agrees with it to within a few per cent of the invoice.
- Token and latency alerts run on pre-sampling metrics.
- The trace ID and the evaluated span ID are stored with every user feedback record and eval result.
- Instrumentation versions are pinned, and someone owns reading the semantic-conventions-genai changelog.
07Linking traces to evals
Observability tells you what happened. LLM evals tell you whether it was any good. They are only useful together if every score can be traced back to the exact span it judged, and from there to the prompt version, model, tool results and retrieved context behind it.
The convention defines a gen_ event for this. It "SHOULD be parented to GenAI operation span being evaluated when possible", with gen_ as the fallback join key. Its attributes are gen_, gen_, gen_ and gen_.
Evals usually run asynchronously, minutes or hours after the trace has closed. So store the IDs when the response is produced, then re-create the parent context later:
from opentelemetry import trace
from opentelemetry._logs import get_logger, LogRecord
from opentelemetry.trace import NonRecordingSpan, SpanContext, TraceFlags
eval_logger = get_logger("acme.evals")
# At response time, persist alongside the answer:
# ctx = trace.get_current_span().get_span_context()
# trace_id_hex, span_id_hex = format(ctx.trace_id, "032x"), format(ctx.span_id, "016x")
def record_eval(trace_id_hex: str, span_id_hex: str, name: str,
score: float, label: str, explanation: str) -> None:
parent = SpanContext(
trace_id=int(trace_id_hex, 16),
span_id=int(span_id_hex, 16),
is_remote=True,
trace_flags=TraceFlags(TraceFlags.SAMPLED),
)
eval_logger.emit(LogRecord(
event_name="gen_ai.evaluation.result",
context=trace.set_span_in_context(NonRecordingSpan(parent)),
attributes={
"gen_ai.evaluation.name": name, # e.g. "groundedness"
"gen_ai.evaluation.score.value": score,
"gen_ai.evaluation.score.label": label, # e.g. "pass" / "fail"
"gen_ai.evaluation.explanation": explanation,
},
))We ran this against opentelemetry-api and opentelemetry-sdk 1.45.1, and the emitted record carried the parent's trace and span IDs. The Python logs API is still underscore-prefixed (opentelemetry._), so pin your version.
Most LLM backends also have a native score API keyed on trace and observation IDs. Langfuse's Python SDK, for example, has create_. Use the native API if it is your only consumer. Emit the OTel event if scores must also reach your warehouse or APM. For traces ingested over OTLP, Langfuse stores the OTel trace and span IDs as hex and uses them as its trace and observation IDs, so the 32-hex and 16-hex strings persisted above work as trace_id and observation_.
Three loops, one join key:
- Offline evals in CI run your dataset through the instrumented app. Each case gets a trace, so a regression comes with a debuggable trace attached, and trajectory evals for agents have the full path to check, not just the final answer.
- Online evals score a sample of production spans asynchronously. Don't draw that sample from your tail-sampled traces. Tail sampling keeps errors and slow requests on purpose, so an eval set built from it shows a quality problem that isn't there. Draw a separate uniform sample, from the content store where the completion hook writes regardless of sampling.
- Human feedback (thumbs, edits, escalations) arrives with the trace ID your API returned to the client. Store it next to the feedback row.
Group every score by gen_ + gen_ + gen_ + gen_. That is how "the new prompt is better" becomes a query, not an opinion.
08Langfuse vs Phoenix vs Datadog vs a plain OTel backend
Because the instrumentation is standard, choosing a backend is reversible. That is the main reason to instrument this way.
| Backend | Native schema | Reads gen_ai.* over OTLP? |
Hosting / licence | Strengths | Watch out for |
|---|---|---|---|---|---|
| Langfuse | Own (traces, observations, scores) | Yes. Maps gen_ai.*, OpenInference and langfuse.* attributes at / |
Cloud, or self-host. Core MIT, ee/ directories separately licensed (LICENSE) |
Prompt management, datasets, scores and cost views in one place | Cloud billing is per unit, and units = traces + observations + scores (docs), so span-heavy agents add up |
| Arize Phoenix | OpenInference | Yes. Converts gen_ai.* spans to OpenInference at ingest (source) |
Self-host (pip, Docker, Helm). Elastic License 2.0 | Strong eval tooling, quick to run locally | ELv2 restricts offering it as a managed service. Where attributes conflict, OpenInference wins over gen_ai.* |
| Datadog | Own | Yes. OTel GenAI conventions 1.37+ or OpenInference, with header dd-otlp-source= |
SaaS | Sits next to your existing APM, logs and RUM | Its docs note a 3–5 minute delay before traces appear. Content goes to a third party |
| Tempo, Jaeger, Honeycomb, ClickHouse | Generic OTel | Stores them as ordinary attributes | Any | Cheapest, and joins with the rest of your telemetry | No message rendering, prompt management or eval UI. You build the views yourself |
On the instrumentation side, community options such as OpenLLMetry and the OpenInference instrumentors cover frameworks the official packages don't yet. Check which convention version and attribute names a given release emits before you mix them with the official packages in one fleet.
What we'd do by default: official OTel instrumentation, plus hand-written agent and tool spans. One Collector tier, configured as above. Content-stripped spans to whatever APM you already run. Full traces to a self-hosted Langfuse or Phoenix in your own cloud account, with the content store alongside. Go SaaS for the LLM backend only once you've decided you're comfortable with the content leaving your boundary.
Worked sizing example for Langfuse Cloud (illustrative). Assume 100,000 agent runs a month. Each run is one trace with 40 observations (chat, tool and retrieval spans) and one score, so 42 units per run and 4.2M units a month. The pricing page lists, at the time of writing, Core at $29/month with 100k units included, then $8 per 100k units, falling to $7 per 100k between 1M and 10M. That gives $29 + (900k × $8/100k = $72) + (3.2M × $7/100k = $224), about $325 a month. Halve the spans per run and the bill roughly halves. That is a reason to keep instrumentation deliberate, not to stop tracing.
09Failure modes we plan for
- Double-counted cache tokens. Covered above. Test it: run one cached call and check the numbers against the provider's usage response.
- Spans that never end. If a client disconnects halfway through a stream and your code never drains or closes the iterator, the inference span leaks. The spec says a stream that ends early should report
errorinfinish_. Wrap streaming inreasons try/finally. - Orphaned tool spans. Python's
Threaddoes not carryPool Executor contextvarsinto worker threads, and queues drop context entirely. Usecontextvars.or the threading instrumentation for pools. Injectcopy_ context(). run(... ) traceparentinto job payloads for queues. - Hours-long agent runs as one trace. Tail samplers buffer for
decision_(30 seconds by default in the tail sampling processor), and backends cap trace duration and span count. Make each turn or task its own trace. Tie them together withwait gen_and span links. Context engineering for long-running agents covers where those turn boundaries naturally fall.ai. conversation. id - Oversized attributes. Message arrays can exceed backend attribute limits. A blunt truncation leaves invalid JSON behind. The spec allows truncating individual message contents "preserving JSON structure". Better still, use the hook.
- Retries hidden inside one span. By spec, the inference span covers the whole logical operation, retries included. So a slow span may be backoff, not a slow model. Keep HTTP client instrumentation on so the retries appear as child spans.
- Mixed convention versions. One service emits
gen_, anotherai. system gen_, and dashboards quietly split in two. Normalise in the Collector, as above, and alert on the presence of deprecated keys.ai. provider. name
10How this crosses into the rest of the stack
LLM observability is rarely only an AI-team problem. The Collector tiers, sampling and retention belong to Cloud & DevOps. The content store's region, IAM, encryption and erasure path are Security and Data. The price table and per-tenant cost model end up in finance's reporting. The trace ID returned to the client and stored with feedback is a Software API decision. Which features deserve online evals at all is a Strategy call. Teams that design all of this in one place get traces they can actually use. Teams that don't tend to find, a quarter later, that the prompts were in the APM vendor's backend all along.
11When you probably don't need this yet
If you have one LLM call behind one feature, at modest volume, log the provider's usage object and the response ID with your normal request logs and stop there. The provider's console will tell you what you spend. Full GenAI tracing pays off once you have tool loops, multiple models, multiple tenants to bill, or a quality question you can't answer without seeing the inputs. For most teams building agents, that happens in the first month.
12FAQ
Are the OpenTelemetry GenAI semantic conventions stable?
No. At the time of writing, they are marked Development. They moved out of the core semantic-conventions repository in v1.42.0 (June 2026) into semantic-conventions-genai, which had not cut a tagged release at the time of writing. Expect renames. Pin instrumentation versions and normalise attribute names in the Collector.
What is the difference between OpenInference and the OTel GenAI conventions?
Both are attribute schemas carried over OTLP. OpenInference came out of Arize and is Phoenix's native format (input.value, llm.). The GenAI conventions are the OpenTelemetry project's standard (gen_ai.*). Phoenix, Langfuse and Datadog now ingest both. For new work we'd emit gen_ai.*, because it is the vendor-neutral one.
Should I log full prompts and completions in my traces? Not in production traces. Keep content capture off and use a completion hook to write content to a separate store with its own access controls, region and retention. Leave a reference on the span. Inline capture is fine in development and staging, where the data is synthetic or the backend is approved for it.
How do I trace tool calls that go through MCP?
Use MCP client and server instrumentation that injects traceparent and tracestate into the request's params._, as the GenAI MCP conventions and SEP-414 specify. The MCP server span then becomes a child of the client span, whatever the transport. If you are building your own MCP server, add this propagation from the start. Tools you run in-process still need an execute_ span from your own code.
How do I attribute LLM cost per customer?
Put a tenant attribute on the agent or request span, keep gen_ on every inference span, and join against a dated price table at query time. Price uncached input, cache reads, cache writes and output separately. Never price gen_ as a single figure. Don't put tenant IDs on metrics.
Does tracing add latency to LLM calls?
Not in any way you'll notice, if you configure it properly. Spans are exported asynchronously by the batch span processor, and model calls take hundreds of milliseconds to seconds. The real risks are synchronous content uploads in a completion hook and unbounded export queues under memory pressure. Make uploads asynchronous and keep memory_ in the Collector.