LLM Observability with OpenTelemetry: A Practical Guide

An LLM agent can fail without a single 5xx: it loops through tools, burns its token budget or quietly gets a new model snapshot. LLM observability makes each of those steps visible. Here you will trace a tool-calling agent with the OpenTelemetry GenAI conventions, redact and tail-sample in the Collector, and chart cost per request, tokens per second and error rate.
How LLM observability with OpenTelemetry fits together
The agent emits one span per step. One OpenTelemetry Collector then uses those spans twice: it turns all of them into Prometheus metrics, and it redacts and samples them before storing traces in Tempo.
Metrics are counted before sampling, so cost stays exact when you keep a tenth of the traces. You need Python 3.10+, an Anthropic API key, Docker and an OTLP-capable Tempo or Jaeger.
What to capture for every LLM call
When the agent is wrong or expensive, a trace must show which step, model and prompt were involved, and the tokens used. The GenAI semantic conventions name these fields:
| Signal | Recorded as | Answers |
|---|---|---|
| Tokens | gen_ai.usage.input_tokens, gen_ai.usage.output_tokens | Cost? |
| Latency per step | Duration of each chat and execute_tool span | Slow step? |
| Tool calls | execute_tool spans, gen_ai.tool.name | Looping? |
| Cost | Tokens times price, in PromQL | On budget? |
| Model | gen_ai.request.model, gen_ai.response.model | Snapshot changed? |
| Prompt version | gen_ai.prompt.name, gen_ai.prompt.version | Prompt regressed? |
Prompt and response text is missing on purpose: message content is opt-in because it often holds customer data.
Instrumenting an agent with the GenAI conventions
The example is an incident-triage agent, modelled on a Slack bot I built that investigates incidents using documentation search, metric plugins and log APIs. Each model call becomes a CLIENT span named after the operation and model. Save this as agent.py:
import sys, anthropic
from opentelemetry import trace
from tools import TOOLS, IMPL
tracer, client = trace.get_tracer("triage-agent"), anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"
PROMPT = {"gen_ai.prompt.name": "triage", "gen_ai.prompt.version": "v7"}
def chat(messages):
with tracer.start_as_current_span(f"chat {MODEL}", kind=trace.SpanKind.CLIENT, attributes={
"gen_ai.operation.name": "chat", "gen_ai.provider.name": "anthropic",
"gen_ai.request.model": MODEL, **PROMPT}) as span:
r = client.messages.create(model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages)
span.set_attributes({"gen_ai.response.model": r.model,
"gen_ai.usage.input_tokens": r.usage.input_tokens,
"gen_ai.usage.output_tokens": r.usage.output_tokens})
return r
tools.py holds your tool schemas and a dict of functions; stubs that return canned strings will do. The prompt name and version go on every chat span, so a bad prompt edit shows up as a label. The response model records the snapshot actually served.
Next, the agent loop. One invoke_agent span wraps the request and each tool call gets an execute_tool span:
def tool(c):
with tracer.start_as_current_span(f"execute_tool {c.name}", attributes={
"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": c.name,
"gen_ai.tool.call.id": c.id}):
return {"type": "tool_result", "tool_use_id": c.id, "content": str(IMPL[c.name](**c.input))}
def triage(question):
with tracer.start_as_current_span("invoke_agent triage", attributes={
"gen_ai.operation.name": "invoke_agent", "gen_ai.agent.name": "triage"}):
messages = [{"role": "user", "content": question}]
for _ in range(6): # step budget
r = chat(messages)
if r.stop_reason != "tool_use":
return r.content[0].text
messages.append({"role": "assistant", "content": r.content})
messages.append({"role": "user", "content": [tool(c) for c in r.content if c.type == "tool_use"]})
raise RuntimeError("step budget exhausted")
print(triage(sys.argv[1]))
The six-step budget is an LLMOps guardrail: a confused agent stops instead of looping on your bill. Tool arguments and results stay off spans. If a call raises, the SDK records the exception and marks the span ERROR.
Prefer automatic chat spans? opentelemetry-python-genai ships Anthropic and OpenAI instrumentations; its README warns that anthropic 2.x and newer emits its own spans, so keep one source; the run step below disables the SDK's. The waterfall shows one request:
The second chat call is slow and expensive because the tool results joined its context; that growth per step drives agent cost. On a 30M+ active-series stack I ran, Grafana Tempo tracing helped cut MTTR by up to 80%.
Collector: PII redaction, tail sampling, token metrics
Agent traffic needs its own settings: runs last a minute, prompts may contain emails or keys, and token totals must stay exact when traces are dropped. Save the first half of otel.yaml:
receivers:
otlp: {protocols: {grpc: {endpoint: "0.0.0.0:4317"}}}
processors:
redaction:
allow_all_keys: true # false would drop every unlisted attribute
blocked_values: ["[\\w.+-]+@[\\w-]+\\.[\\w.]+", "sk-[\\w-]{20,}"] # emails, API keys
tail_sampling:
decision_wait: 120s # outlast the slowest agent run
policies:
- {name: errors, type: status_code, status_code: {status_codes: [ERROR]}}
- {name: slow, type: latency, latency: {threshold_ms: 20000}}
- {name: costly, type: numeric_attribute,
numeric_attribute: {key: gen_ai.usage.input_tokens, min_value: 30000}}
- {name: baseline, type: probabilistic, probabilistic: {sampling_percentage: 10}}
delta_to_cumulative: {}
The redaction processor masks matching values as ****. The tail sampler keeps a trace when any policy votes for it; my guide to trace sampling covers the trade-offs. The flowchart shows the decision:
If decision_wait is shorter than a run, late spans miss the decision. Running several replicas? A load-balancing exporter keyed on trace ID must route each trace to one instance. Now append the metrics half:
connectors:
span_metrics: # all spans, before sampling
namespace: llm
histogram: {unit: s, explicit: {buckets: [1s, 2s, 5s, 10s, 30s, 60s]}}
dimensions: [{name: gen_ai.request.model}, {name: gen_ai.prompt.version}]
sum:
spans:
llm.tokens.input:
source_attribute: gen_ai.usage.input_tokens
attributes: &dims [{key: gen_ai.request.model}, {key: gen_ai.prompt.version}]
llm.tokens.output:
source_attribute: gen_ai.usage.output_tokens
attributes: *dims
exporters:
otlp_grpc/tempo: {endpoint: "tempo:4317", tls: {insecure: true}}
prometheus: {endpoint: "0.0.0.0:8889"}
service:
pipelines:
traces/metrics: {receivers: [otlp], exporters: [span_metrics, sum]}
traces: {receivers: [otlp], processors: [redaction, tail_sampling], exporters: [otlp_grpc/tempo]}
metrics: {receivers: [span_metrics, sum], processors: [delta_to_cumulative], exporters: [prometheus]}
Both trace pipelines share the receiver, so metrics see every span while Tempo gets a sample. The sum connector emits delta counters, which delta_to_cumulative converts for Prometheus. Older configs say spanmetrics and otlp: both were renamed and remain deprecated aliases. On Kubernetes, the OpenTelemetry Operator can run this config.
Run it and verify
Start the Collector, then run the agent under opentelemetry-instrument, which configures the SDK from environment variables and exports to localhost:4317 by default:
pip install anthropic opentelemetry-distro opentelemetry-exporter-otlp
docker run -d --name otelcol -p 4317:4317 -p 8889:8889 \
-v "$PWD/otel.yaml:/etc/otelcol-contrib/config.yaml" otel/opentelemetry-collector-contrib:0.166.0
export OTEL_SERVICE_NAME=triage-agent OTEL_METRICS_EXPORTER=none OTEL_LOGS_EXPORTER=none ANTHROPIC_OPEN_TELEMETRY=false
opentelemetry-instrument python agent.py "Why is checkout failing?"
sleep 60; curl -s localhost:8889/metrics | grep '^llm_tokens'
# llm_tokens_input_total{gen_ai_prompt_version="v7",gen_ai_request_model="claude-sonnet-5-5",...} 5270
You should see the agent's answer, then a token counter like the last line (value illustrative). Span metrics flush every 60 seconds, so wait a minute. If nothing appears, docker logs otelcol shows an unknown component or a busy port. Traces reach Tempo after the two-minute decision wait.
Dashboards: cost per request, tokens per second, error rate
With tokens in Prometheus, four panels answer the first questions people ask. Prices are illustrative; use your provider's rate card:
# Cost per request, USD (illustrative $3 / $15 per 1M tokens)
(sum(rate(llm_tokens_input_total[5m])) * 3e-6 + sum(rate(llm_tokens_output_total[5m])) * 15e-6)
/ sum(rate(llm_calls_total{span_name="invoke_agent triage"}[5m]))
# Output tokens per second
sum(rate(llm_tokens_output_total[5m])) / sum(rate(llm_duration_seconds_sum{span_name=~"chat .*"}[5m]))
# Error rate
(sum(rate(llm_calls_total{span_name=~"chat .*", status_code="STATUS_CODE_ERROR"}[5m])) or vector(0))
/ sum(rate(llm_calls_total{span_name=~"chat .*"}[5m]))
# p95 latency per step
histogram_quantile(0.95, sum by (le, span_name) (rate(llm_duration_seconds_bucket[5m])))
Cost divides spend by agent calls, so it is per user request. Falling tokens per second usually means provider load or a bigger model. The or vector(0) shows zero instead of an empty error panel. Empty results? Check label names on /metrics: dots become underscores.
Put a latency SLO on agent p95, and ticket on cost jumps after model or prompt changes. An LLM can draft more PromQL for review.
Common pitfalls
- High-cardinality labels. Keep conversation and user IDs on spans, never as metric dimensions. Trimming labels with the Collector and vector.dev is how I cut one metrics bill by up to 50%.
- Counting after sampling. Metrics built behind the tail sampler undercount cost by the sampling rate.
- Capturing content by default. Keep message content opt-in, redacted and on short retention.
- Trusting convention names. The GenAI conventions are still in Development, and v0.1.0 of the new repository renamed the token metrics. Metrics derived from span attributes survive that. Some instrumentations emit the newest names only with
OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental.
Key takeaways
- Give every step a span (agent, chat, tool), with tokens, model and prompt version on chat spans.
- Count metrics from all spans before tail sampling, then keep traces with errors, long runs or heavy token use.
- Once tokens are metrics, cost, speed and error rate are one PromQL query each.
Related articles

RAG over Post-Mortems: Learn from Every Incident
Index post-mortems, Slack timelines and tickets in one Chroma collection, ask 'have we seen this before?' during an incident, and cluster contributing factors with HDBSCAN to decide which reliability work to fund.

RAG in Production: Evals, Observability, Cost, Freshness
Take a runbook RAG bot from demo to production: gate changes on recall@k and faithfulness evals, trace retrieval and generation with OpenTelemetry, set latency and groundedness SLOs, and cut cost with caching and incremental re-indexing.

AI Agents for SRE: Agentic Ops for Routine Work, Safely
Which SRE chores can an AI agent take on today? A task matrix, a read-only MCP server in Python, one scoped write behind human approval, an audit log, and a trust ladder for promoting agents safely.