LLM Observability with OpenTelemetry
An HTTP service is healthy when its requests are fast and return 200. An LLM call can be fast, return 200 and still be wrong in ways no status code shows: an answer cut off at its token budget, a prompt cache that silently stopped hitting, a retry storm that tripled the bill, a new prompt version that made answers worse. Observability for LLM systems means recording enough on every call to see those things.
This post covers what to record and where. It follows the OpenTelemetry GenAI semantic conventions, whose first standalone release came less than two weeks before I wrote this, tests the claims against a running OpenTelemetry SDK, and adds what we learned keeping LLM services observable in production. The experiments ran against a local fake of the Claude Messages API, except where a number comes from 26 real calls measured for the previous post on prompt caching. One finding changed my code halfway through: the Anthropic SDK now traces itself.
In short
- Use three kinds of record for three questions: traces for one call in detail, metrics for totals and rates, and content with evaluation scores, opt-in and stored apart, for quality.
- Count cost from metrics, never from sampled traces. With traces sampled at 10 per cent, a simulated cost total landed between 93 and 107 per cent of the truth in nine repeats out of ten, and nine in ten failed calls were missing from the sample.
- Normalise token counts. Anthropic's
input_tokensexcludes cached tokens; on 26 measured calls, pricing it alone gave $0.025 against a true $0.486. - Check what already emits spans. Since version 1.14.0 the Anthropic Python SDK creates one for every call, so a hand-written GenAI span counts every token twice.
Three kinds of record
| Question | Where the answer lives |
|---|---|
| Why was this job slow, and what did its calls do? | Trace: one span per step and per call, with attributes |
| What did we spend this week, per model and per step? | Metrics: token counters, never sampled |
| Are errors, truncations or latency rising? | Metrics: rates and histograms, with alerts |
| Did the new prompt version make answers worse? | Evaluation scores, attached to traces by prompt version |
| What exactly did the model see and say? | Content, captured on purpose, with its own access rules |
Google's SRE book names "latency, traffic, errors, and saturation" as the four golden signals. They still apply. LLM calls add two of their own: cost, which varies by orders of magnitude from one call to the next, and quality, which no status code reports.
The conventions, and how fast they move
OpenTelemetry's GenAI semantic conventions say what to call things, so that any backend can read the telemetry. A model call is an inference span named {gen_ai.operation.name} {gen_ai.request.model}, such as chat claude-sonnet-5-5, of kind CLIENT. It carries the provider, the requested and the returned model, the output budget (gen_ai.request.max_tokens), the finish reasons, the response id, token usage, time to the first chunk for a stream, and error.type on failure. Token usage and duration also go to metrics: gen_ai.client.inference.duration and a counter per token type, gen_ai.client.inference.usage.input_tokens and its siblings. One rule matters more than it looks: when a request is retried, the span "SHOULD cover the duration of the logical operation with all retries."
The names are still moving. Every attribute is marked Development. In 2026 the conventions left the main semantic-conventions repository for their own, and v0.1.0, its first release, on 21 November, renamed gen_ai.usage.cache_creation.input_tokens to gen_ai.usage.cache_write.input_tokens and replaced the gen_ai.client.token.usage histogram with per-type counters and histograms. The Python package of convention constants, opentelemetry-semantic-conventions 0.66b3, still ships the old names. Keep the names your code emits in one module, and expect to change them.
Your SDK may already trace
Since version 1.14.0, released on 14 October, the Anthropic Python SDK creates spans itself. Its changelog says: "If your app registers a global tracer provider, the SDK will create spans with it after upgrading". Its source describes one CLIENT span per call, "with every retry and the reading of the stream it returns", which is what the conventions ask. Two details differ from them: the span is named anthropic.messages.create rather than the operation and the model, and the stop reason is recorded as anthropic.message.stop_reason rather than gen_ai.response.finish_reasons. It records metadata only unless content capture is turned on, sends trace context with each request unless told not to, and is switched off with ANTHROPIC_OPEN_TELEMETRY=false. The documentation marks it beta: "the SDK options and the span schema can change in ways that break your code". It emits no metrics.
I found this out in a test. My first wrapper made its own GenAI span for each call, and the test exporter showed two: mine and the SDK's, each with 7,862 input tokens.
The conventions warn about exactly this: "Don't sum gen_ai.usage.* over all spans without filtering by operation name. The same tokens can be reported on multiple types of spans". Agent frameworks, gateways and SDKs can each report the same call. So the wrapper now leaves the call span to the SDK and adds what the SDK cannot know: a span for the pipeline step, which names the prompt and its version, and the metrics. The SDK's span nests under it:
For other providers, or older SDKs, instrumentation libraries fill the same role: OpenTelemetry's own opentelemetry-instrumentation-openai-v2 and the OpenLLMetry project's opentelemetry-instrumentation-anthropic among them. Whatever creates the call span, there should be exactly one per call.
Counting tokens correctly
Providers disagree about what "input tokens" means. Anthropic reports the cache apart: input_tokens is only the uncached part, with cache_read_input_tokens and cache_creation_input_tokens beside it. OpenAI reports a total and the cached part inside it. The conventions pick the total ("This value SHOULD include cached tokens"), and their Anthropic page gives the sum to compute. Langfuse, which reads these attributes, subtracts the cache reads and writes again to price each part.
With a working cache the difference is large. Here are the 26 calls from the caching post, priced three ways at Claude Sonnet 5.5's prices: $2 per million input tokens, $2.50 for a five-minute cache write, $4 for a one-hour write (7,785 of the written tokens), $0.10 for a cache read and $10 for output.
Pricing input_tokens as the provider reports it missed 95 per cent of the cost, because almost all the input was cache writes and reads. Pricing the convention's gross count at the base rate overstated it by half. Only a price per token type gets it right. In production we normalised every provider's usage to one definition at the client, gross input with the cache counts beside it, and fed the observability backend the uncached input separately, so it could price cached tokens apart.
Three more lessons from the same work:
- Record usage on failed and cancelled calls. A call that fails after a reply, because its answer was truncated, refused or still invalid after its re-asks, has spent tokens. So has a call cancelled between a reply and its retry. If usage is recorded only on success, that spend disappears from every dashboard. We attach the summed usage to the error and to the span.
- Count requests, not just calls. One logical call can send several HTTP requests: retries, and re-asks when structured output fails validation. Recording the request count per call is what makes a retry storm visible before the invoice does.
- Read usage from the API, never from the model. An output schema once asked the model itself to report its token usage in the answer. The model can only guess at that number, and producing it costs output tokens. Usage comes from the response's
usageobject.
Cost needs metrics, not sampled traces
At volume, traces are sampled; keeping one in ten is common. Metrics are not, and the conventions say to prefer them: use the token metrics "whenever possible. They aren't affected by trace sampling." To see what sampling does to a cost estimate, I generated 10,000 calls with a heavy tail: 2 per cent are large documents carrying 20 per cent of the cost, and 35 calls fail. I sampled them at 10 per cent with the SDK's TraceIdRatioBased sampler and also counted tokens on a metric. The sampler kept 1,016 spans. Scaling their tokens up missed the true total by 2.1 per cent; the counter matched it exactly. Repeating the 10 per cent sample 2,000 times shows the spread:
The estimate is unbiased but noisy: 90 per cent of the repeats fell between 0.933 and 1.073 of the true total, and only 76 per cent within 5 per cent of it. Failures fare worse. Of 35 failed calls, the sample kept 3.4 on average and none at all in 58 repeats. A head sampler decides before the call has failed. A tail sampler decides after the trace has finished, so it can keep every error and every slow trace. The OpenTelemetry Collector's tail sampling processor does this, at a price: "All spans for a given trace MUST be received by the same collector instance".
Here is a policy that keeps every failed trace, every slow one, every one that hit the output budget, and a tenth of the rest. The thresholds are examples. A trace is kept when any policy says keep. I ran it in otelcol-contrib 0.166.0, with decision_wait shortened to 2 seconds, and sent it 400 single-span traces: it kept all 10 failed, all 10 slow and all 10 truncated ones, and 35 of the 370 others.
# Checked in otelcol-contrib 0.166.0: all errors, slow and truncated traces kept, about a tenth of the rest.
processors:
tail_sampling:
decision_wait: 60s # longer than your slowest trace, retries included
num_traces: 50000
policies:
- name: errors
type: status_code
status_code: {status_codes: [ERROR]}
- name: slow
type: latency
latency: {threshold_ms: 30000}
- name: truncated # not an error, but the answer was cut off
type: string_attribute
string_attribute: {key: anthropic.message.stop_reason, values: [max_tokens]}
- name: rest
type: probabilistic
probabilistic: {sampling_percentage: 10}
Set decision_wait above the longest trace you expect, or the processor decides before the slow call has finished. A long step with several retries is the case to size it for.
Cost then comes from the counters. This function sums them per model and prices each token type separately, with the input counter reduced by the cached parts because the conventions define it as a total. It uses the prices above, with one gap that its comment explains: the convention's single cache-write counter cannot tell a five-minute write from a dearer one-hour write.
"""Cost per model from the unsampled token counters, priced per token type."""
from collections import defaultdict
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
# USD per million tokens. Prices are data, so a price change is a one-line edit. The convention has one cache-write
# counter; one-hour writes cost more, so if you use them, also count
# usage.cache_creation.ephemeral_1h_input_tokens on a counter of your own.
PRICES = {"claude-sonnet-5-5": {"uncached": 2.0, "cache_write": 2.5, "cache_read": 0.10, "output": 10.0}}
PREFIX = "gen_ai.client.inference.usage."
def cost_by_model(reader: InMemoryMetricReader, prices: dict[str, dict[str, float]]) -> dict[str, float]:
"""Sum the counters per model, then price each token type. Input is gross, so subtract the cached parts."""
totals: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
for rm in reader.get_metrics_data().resource_metrics:
for sm in rm.scope_metrics:
for m in sm.metrics:
if m.name.startswith(PREFIX):
for p in m.data.data_points:
totals[p.attributes["gen_ai.request.model"]][m.name.removeprefix(PREFIX)] += p.value
cost = {}
for model, t in totals.items():
price = prices[model]
read, write = t["cache_read.input_tokens"], t["cache_write.input_tokens"]
cost[model] = (
(t["input_tokens"] - read - write) * price["uncached"] + write * price["cache_write"]
+ read * price["cache_read"] + t["output_tokens"] * price["output"]
) / 1e6
return cost
For a dashboard, the same arithmetic belongs in the metrics backend, one query term per token type. A function like this one is still useful for a nightly check that the dashboard and the invoice agree.
What every call should say
| Record | Attribute | Why |
|---|---|---|
| Model requested and served | gen_ai.request.model, gen_ai.response.model | An alias or a fallback can serve a different model |
| Output budget and why it stopped | gen_ai.request.max_tokens, finish reason | Together they show how close answers come to truncation |
| Usage, with the cache | gen_ai.usage.* | Cost, and whether the cache is working |
| Time to first chunk | gen_ai.response.time_to_first_chunk | What a streaming user waits for; it includes retries |
| Prompt and version | gen_ai.prompt.name, gen_ai.prompt.version | Ties quality changes to prompt changes |
| Where it went | server.address, region, the model id sent | Routing and data residency, checked rather than assumed |
| The provider's request id | anthropic.request.id, the SDK's own attribute | The only key the provider's support can look up |
| How it failed | error.type, status code, retryable or not | Separates throttling from bugs |
Two rows came from production gaps. When a call misbehaved, we could not match it to the provider's logs or tell which region served it until every span recorded the route, the endpoint and the request id. And truncations were invisible until every span recorded the output budget it was sent with and the finish reason it got back, so that output tokens could be read against the budget.
Attributes on spans can be as specific as you like. Labels on metrics cannot: every distinct combination becomes its own time series. Keep metric labels to a few bounded values, such as model, operation, pipeline step and error type, and leave request ids, user ids and document names to the spans.
Attribute values are a contract
An attribute value of None looks harmless. We once set a prompt version that was sometimes None and flooded the logs with warnings. I checked what the OpenTelemetry Python SDK does with it, setting None on 1,000 spans:
| SDK version | Warnings logged | Spans that keep the attribute |
|---|---|---|
| 1.34.0, 1.39.0, 1.42.0, 1.44.0 | 1,000 | 0 |
| 1.45.3 | 0 | 1,000, with the value None |
Up to 1.44.0, every call logged "Invalid type NoneType for attribute 'gen_ai.prompt.version' value" and dropped the attribute. Version 1.45.3 keeps the attribute with the value None and logs nothing. Neither tells you which prompt ran. Set an attribute only when you have its value, and test the telemetry like any other output, as the next section does.
Content: off by default, on purpose
Prompts and outputs are the most useful telemetry and the most dangerous. The conventions say instrumentations "SHOULD NOT capture them by default", and describe three levels: record nothing, record content on the spans, which suits pre-production, or store it externally and record references, "recommended in production environments where telemetry volume is a concern or sensitive data needs to be handled securely". The Anthropic SDK follows this: its content_mode defaults to metadata_only.
In production we drew the line in two more places. Error details that travel into a workflow engine's history carry the provider, model, status, request id and retry verdict, never message text, because that history is kept and widely readable. And binary inputs, images and PDFs, are never traced, only counted. When content must be kept for debugging or evaluation, pseudonymising it first keeps personal data out of the trace store.
Quality is a signal too
Latency and errors say whether the system works; they say nothing about whether the answers are good. Quality needs its own records, attached to the same traces:
- Cheap signals on every call: the share of answers that fail schema validation, need a re-ask, are refused or end at
max_tokens. Each is a counter labelled by step, and by prompt version while there are only a few versions, and a jump after a deploy is a regression found in minutes. - Scores on a sample: automated checks, or a model grading a sample of traces against a rubric, stored as scores on those traces so they can be compared by prompt version. The post on validating LLM extraction describes checks of this kind.
- Human feedback: corrections and ratings, linked to the trace that produced the answer.
Tools such as Langfuse store scores, prompt versions and traces together; Langfuse accepts OpenTelemetry directly at /api/public/otel, over HTTP only. The useful property is the link: a score that cannot be traced to a prompt version and a model cannot explain a regression.
A small layer on top of the SDK's span
This is the wrapper the experiments used. It opens a span for the pipeline step, lets the SDK trace the call beneath it, and records the convention's metrics, on failure too, with whatever usage the stream had reported before it ended. It labels errors as the SDK's span does, so the two can be joined. The token counters carry gen_ai.token.modality, which the conventions require, as unknown, because Anthropic does not split usage by modality. A stream that ended early raises, as the previous post recommends, rather than returning an empty answer.
"""What to add around a traced Claude call: a step span that names the prompt, and unsampled token metrics.
The Anthropic SDK (1.14.0 and later) already emits one CLIENT span per call, with usage, model and request id.
"""
import time
import anthropic
from opentelemetry import metrics, trace
tracer = trace.get_tracer("llm-app")
meter = metrics.get_meter("llm-app")
# Names from semantic-conventions-genai v0.1.0. They are still in development, so they live in one place.
TOKENS = {k: meter.create_counter(f"gen_ai.client.inference.usage.{k}", unit="{token}")
for k in ("input_tokens", "output_tokens", "cache_read.input_tokens", "cache_write.input_tokens")}
DURATION = meter.create_histogram("gen_ai.client.inference.duration", unit="s",
explicit_bucket_boundaries_advisory=[0.01, 0.025, 0.05, 0.1, 0.25, 0.5,
1, 2.5, 5, 10, 30, 60])
TRUNCATED = meter.create_counter("app.llm.truncated", unit="{call}")
class IncompleteStream(ConnectionError):
"""The stream ended before message_stop; the SDK returns a message with stop_reason None and no error."""
def token_counts(usage) -> dict[str, int]:
"""Anthropic's input_tokens excludes cached tokens; the convention's input_tokens includes them."""
read = usage.cache_read_input_tokens or 0
write = usage.cache_creation_input_tokens or 0
return {"input_tokens": usage.input_tokens + read + write, "output_tokens": usage.output_tokens or 0,
"cache_read.input_tokens": read, "cache_write.input_tokens": write}
def spent(stream):
"""The usage a stream had reported when it ended: message_start carries the input, deltas the output."""
try:
return stream.current_message_snapshot.usage
except (AssertionError, AttributeError): # no response yet, or no message_start
return None
def error_type(e: BaseException) -> str:
"""As the SDK labels its own span, so the two can be joined: the error type, else the status, else a class."""
if isinstance(e, anthropic.APITimeoutError):
return "client_timeout_error"
if isinstance(e, anthropic.APIConnectionError):
return "connection_error"
if isinstance(e, anthropic.APIStatusError) and (e.type or e.status_code >= 400):
return str(e.type or e.status_code) # an error event inside a stream has status 200
return type(e).__name__
def run_step(client: anthropic.Anthropic, step: str, prompt_name: str, prompt_version: str,
**params) -> anthropic.types.Message:
"""One pipeline step: a span the SDK's call span nests under, and metrics that sampling cannot thin."""
labels = {"gen_ai.operation.name": "chat", "gen_ai.provider.name": "anthropic",
"gen_ai.request.model": params["model"], "app.step": step} # few values each: safe as labels
with tracer.start_as_current_span(step, attributes={"app.step": step, "gen_ai.prompt.name": prompt_name,
"gen_ai.prompt.version": prompt_version}):
start, stream, message = time.monotonic(), None, None
try:
with client.messages.stream(**params) as stream:
message = stream.get_final_message()
if message.stop_reason is None: # cut short: fail loudly, not with an empty answer
raise IncompleteStream("stream closed before message_stop")
if message.stop_reason == "max_tokens":
TRUNCATED.add(1, labels)
return message
except BaseException as e: # cancellation included: its tokens were spent too
labels["error.type"] = error_type(e)
raise
finally:
DURATION.record(time.monotonic() - start, labels)
usage = message.usage if message is not None else spent(stream)
for name, value in (token_counts(usage).items() if usage else ()):
if value: # Anthropic does not split usage by modality
TOKENS[name].add(value, {**labels, "gen_ai.token.modality": "unknown"})
Against the fake server, three calls produced the records you would hope for. A cached call counted 7,862 input tokens, 7,841 of them cache reads. A stream cut after its first event raised IncompleteStream and still counted the 12 input and 1 output tokens it had reported. A throttled call recorded a duration labelled rate_limit_error, the same label as the SDK's span, and no tokens. A review of my first version found two gaps these cases cover: it counted tokens only on success, and it labelled the throttled call 429 while the SDK's span said rate_limit_error.
It is cheap. Against a stub client, the step span and metrics cost 56 microseconds per call. Against the local fake server, the SDK's own tracing added about 0.25 milliseconds per call (1,618 against 1,368 microseconds, the median of seven interleaved runs). An earlier run on the same shared machine measured 38 microseconds and 0.13 milliseconds, so read these as orders of magnitude. A real call takes about a second, so together that is a few hundredths of a per cent.
Testing the telemetry
The double span and the None attribute were both found by reading exported spans. Put that reading in a test. The in-memory span exporter and metric reader are in the SDK, so a test needs no collector and no network beyond a fake API. This one, run with pytest, checks that a call produces one call span under its step, that a failed call still counts its tokens, and that the cost function matches a hand calculation. It passes against the SDK versions installed here, 2.16.0 of the Anthropic package and 1.45.3 of OpenTelemetry. A module fixture makes the two calls once, so each test can also run on its own.
"""Tests for the telemetry itself: run a call against the fake API and read back what was recorded."""
import anthropic
import pytest
from opentelemetry import metrics, trace
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
# Providers first: genai_otel creates its tracer and meters on import.
exporter, reader = InMemorySpanExporter(), InMemoryMetricReader()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
trace.set_tracer_provider(provider)
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))
import genai_otel # noqa: E402
from fake_api import serve # noqa: E402
from llm_cost import PRICES, cost_by_model # noqa: E402
PARAMS = dict(model="claude-sonnet-5-5", max_tokens=1024, messages=[{"role": "user", "content": "hi"}])
@pytest.fixture(scope="module")
def recorded() -> list:
"""One cached call and one cut stream, recorded once for every test in this file."""
serve(8767)
client = anthropic.Anthropic(api_key="test", base_url="http://127.0.0.1:8767", max_retries=0)
exporter.clear()
genai_otel.run_step(client, "summarise", "summarise-contract", "7",
extra_headers={"x-scenario": "cached"}, **PARAMS)
with pytest.raises(genai_otel.IncompleteStream):
genai_otel.run_step(client, "summarise", "summarise-contract", "7",
extra_headers={"x-scenario": "cut"}, **PARAMS)
return exporter.get_finished_spans()
def counter(name: str, **labels: str) -> int:
"""The summed value of one counter over the points whose labels match."""
total = 0
for rm in reader.get_metrics_data().resource_metrics:
for sm in rm.scope_metrics:
for m in sm.metrics:
if m.name == name:
total += sum(p.value for p in m.data.data_points
if all(p.attributes.get(k) == v for k, v in labels.items()))
return total
def test_one_call_span_under_the_step(recorded):
step, call = recorded[1], recorded[0] # a child span finishes before its parent
assert (step.name, call.name) == ("summarise", "anthropic.messages.create")
assert call.parent.span_id == step.context.span_id
assert step.attributes["gen_ai.prompt.version"] == "7"
assert call.attributes["gen_ai.usage.input_tokens"] == 7862 # gross: 21 new + 7,841 cache reads
assert call.attributes["gen_ai.usage.cache_read.input_tokens"] == 7841
assert call.attributes["gen_ai.request.max_tokens"] == 1024
assert call.attributes["anthropic.request.id"].startswith("req_")
def test_failed_call_still_counts_its_tokens(recorded):
assert counter("gen_ai.client.inference.usage.input_tokens", **{"error.type": "IncompleteStream"}) == 12
def test_cost_is_priced_per_token_type(recorded):
# Both calls: 33 uncached input (21 + 12), 7,841 cache reads, 3 output (2 + 1).
expected = (33 * 2.0 + 7841 * 0.10 + 3 * 10.0) / 1e6
assert cost_by_model(reader, PRICES)["claude-sonnet-5-5"] == pytest.approx(expected)
Dashboards and alerts
| Panel | From | Alert when |
|---|---|---|
| Cost per day, per model and step | Token counters times prices | Above budget, or a step's share jumps |
| Cache hit share | Cache reads over all input | It falls after a deploy |
| Error rate by type | Duration histogram, with error.type | rate_limit_error and overloaded_error rise: lower concurrency; invalid_request_error rises: a bug |
| Latency and time to first chunk | Histograms, 95th percentile | Above the service objective |
| Truncation and re-ask rates | Counters by step, such as app.llm.truncated | They rise after a prompt or model change |
| Requests per call | Request count | Above a level you choose, such as 1.2 requests per call |
A checklist
- One inference span per call, covering its retries; check what your SDK and frameworks already emit before adding your own.
- A step span above it, naming the prompt and its version.
- Token counters and a duration histogram, unsampled; compute cost from them, per token type.
- Normalise usage to one definition, with cache reads and writes beside the total.
- Usage recorded on failed and cancelled calls, and a request count per call.
- Output budget, finish reason, model served, route and request id on every call.
- Tail sampling that keeps every error, every slow trace and every truncation.
- Bounded metric labels; nothing per request or per user.
- Content off by default; when on, stored apart, with its own access rules.
- Quality counters on every call and scores on a sample, linked to prompt versions.
- Attribute names in one module, pinned to a version of the conventions, and a test that reads the exported spans and metrics.
Sources
- OpenTelemetry GenAI semantic conventions, release v0.1.0: client inference, token metrics, spans and content capture, Anthropic
- Claude: OpenTelemetry in the SDKs and the Anthropic Python SDK changelog (version 2.16.0 tested here)
- OpenTelemetry Python SDK (1.34.0 to 1.45.3 tested here)
- OpenTelemetry Collector: tail sampling processor
- Langfuse: OpenTelemetry and token and cost tracking
- Google SRE book: Monitoring Distributed Systems
- opentelemetry-instrumentation-openai-v2 and OpenLLMetry