Sub topic 18
GenAI metrics alongside traces
This chapter assumes you have finished the SDK setup chapter. You should be comfortable with a TracerProvider, a Resource, and a span around a model call. You should also know what a counter and a histogram are in general terms.
Traces show what happened in one request. Metrics show how the whole system behaves over time. For an LLM application you need both, and the GenAI semantic conventions define a small set of metrics that match the span attributes you already record.
Why traces are not enough
A trace answers "why was this one request slow?" It does not cheaply answer "what is the 95th percentile latency of model calls this week?" or "how many output tokens did we spend per hour?" Answering those from traces means querying every span, and sampling makes the counts wrong. If you keep only 10% of traces, a token total computed from spans is about 10% of the real number.
Metrics are aggregated inside your process before export. They cost almost nothing per request, they are not affected by trace sampling, and they stay small as traffic grows.
| Question | Best signal |
|---|---|
| Why did request 8f2c take 40 seconds? | Trace |
| What is p95 model latency by model? | Metric |
| How many tokens did we use today? | Metric |
| Which tool call failed inside this agent run? | Trace |
| Did error rate rise after the deploy? | Metric |
The standard GenAI client metrics
The GenAI conventions define two metrics that a client (your application) records for each model call.
| Metric name | Instrument | Unit | What it records |
|---|---|---|---|
| `gen_ai.client.token.usage` | Histogram | `{token}` | Tokens used per call, split by `gen_ai.token.type` (`input` or `output`) |
| `gen_ai.client.operation.duration` | Histogram | `s` | Wall-clock duration of the call, in seconds |
Both use the same attributes as the matching span:
gen_ai.operation.name, for examplechat.gen_ai.provider.name, which names the provider. Older versions of the conventions called thisgen_ai.system, so check which one your libraries emit.gen_ai.request.modelandgen_ai.response.model.error.type, set only when the call failed.
The conventions also define server-side metrics such as gen_ai.server.request.duration and gen_ai.server.time_to_first_token. These are for people who run the model server. A normal application records only the two client metrics.
The conventions for GenAI are still marked as in development, so names can change between releases. Pin your instrumentation library versions and check the current specification when you upgrade.
Setting up the meter provider
Metrics use a parallel pipeline to traces. A MeterProvider plays the role of the TracerProvider, and a metric reader plays the role of the span processor. The reader collects aggregated values on an interval and hands them to an exporter.
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
from opentelemetry.sdk.resources import Resource
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
resource = Resource.create({"service.name": "support-agent"})
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint="http://localhost:4318/v1/metrics"),
export_interval_millis=15000,
)
# Default histogram buckets suit millisecond web latencies, not LLM calls
# that take seconds. Replace them for the duration metric.
duration_view = View(
instrument_name="gen_ai.client.operation.duration",
aggregation=ExplicitBucketHistogramAggregation(
boundaries=[0.25, 0.5, 1, 2, 4, 8, 16, 32, 64]
),
)
token_view = View(
instrument_name="gen_ai.client.token.usage",
aggregation=ExplicitBucketHistogramAggregation(
boundaries=[1, 4, 16, 64, 256, 1024, 4096, 16384, 65536]
),
)
provider = MeterProvider(
resource=resource,
metric_readers=[reader],
views=[duration_view, token_view],
)
metrics.set_meter_provider(provider)
meter = metrics.get_meter("support_agent")
duration_histogram = meter.create_histogram(
"gen_ai.client.operation.duration",
unit="s",
description="GenAI operation duration",
)
token_histogram = meter.create_histogram(
"gen_ai.client.token.usage",
unit="{token}",
description="Number of input and output tokens used",
)Use the same service.name here as in your tracer resource. That shared value is what lets a dashboard line up metrics and traces for one service.
The View objects matter. A histogram counts values into buckets, and percentiles are estimated from those buckets. If every call lands in one bucket, your p95 is meaningless.
Recording metrics next to the span
Record the metric in the same function that creates the span. Both then see the same outcome, and you compute the attributes once.
import time
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
tracer = trace.get_tracer("support_agent")
def call_model(messages):
# Stand-in for a real LLM client call.
return {"text": "Hello!", "input_tokens": 12, "output_tokens": 3}
def traced_chat(messages, model="example-model"):
attrs = {
"gen_ai.operation.name": "chat",
"gen_ai.provider.name": "example-provider",
"gen_ai.request.model": model,
}
start = time.perf_counter()
with tracer.start_as_current_span(f"chat {model}", kind=SpanKind.CLIENT) as span:
for key, value in attrs.items():
span.set_attribute(key, value)
try:
result = call_model(messages)
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, str(exc)))
span.set_attribute("error.type", type(exc).__qualname__)
duration_histogram.record(
time.perf_counter() - start,
{**attrs, "error.type": type(exc).__qualname__},
)
raise
span.set_attribute("gen_ai.usage.input_tokens", result["input_tokens"])
span.set_attribute("gen_ai.usage.output_tokens", result["output_tokens"])
duration_histogram.record(time.perf_counter() - start, attrs)
token_histogram.record(
result["input_tokens"], {**attrs, "gen_ai.token.type": "input"}
)
token_histogram.record(
result["output_tokens"], {**attrs, "gen_ai.token.type": "output"}
)
return result["text"]This code needs the metrics setup from the previous block to run first, because it uses duration_histogram and token_histogram. Failed calls still record a duration, tagged with error.type. If you skip this, a dashboard of latency will hide your slowest failures, such as timeouts.
Keeping attribute cardinality low
Every distinct combination of attribute values creates a separate time series. Metrics are cheap only while that count stays small.
Safe metric attributes have a small, fixed set of values: operation name, provider, model name, and error type. Use type(exc).__qualname__ for error.type, not the exception message, because messages often contain unique IDs.
Connecting the signals in the Collector
The Collector handles metrics through a separate pipeline from traces. Extend the earlier configuration with a metrics pipeline that reuses the same receiver.
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
batch: {}
exporters:
debug:
verbosity: detailed
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [debug]
metrics:
receivers: [otlp]
processors: [batch]
exporters: [debug]Using metrics and traces together
A practical workflow goes from metric to trace:
- An alert fires because p95 of
gen_ai.client.operation.durationfor one model exceeds its limit. - You filter the dashboard by
gen_ai.request.modelanderror.typeto see whether the cause is slow successes or failures. - You open traces for the same service and time window, filtered to that model, and look for the slow span.
Some SDKs and backends support exemplars, which attach a trace ID to a histogram bucket. If yours does, you can jump from a slow bucket straight to a trace. Without exemplars, the shared service.name, model name, and time window are your join keys.
Common mistakes
- Wrong units. The duration metric is in seconds, not milliseconds. Recording
1250instead of1.25pushes everything into the top bucket. - Counting tokens twice. If an auto-instrumentation library already emits
gen_ai.client.token.usage, adding your own recording doubles every total. Check the library's output first. - Computing cost from sampled spans. Use the token metric for totals and multiply by your price table in the dashboard.
- Short-lived processes. The periodic reader exports every interval, so a script that exits sooner loses its data. Call
provider.shutdown()before exit to flush it.
Exercise
Your team sums gen_ai.usage.input_tokens from spans to report daily token spend, and the trace sampler keeps 20% of traces. The report shows far less spend than the provider's invoice. Why, and which signal should you use instead?
Show answer
The sampler drops 80% of traces, so span-based sums cover only about a fifth of real usage. Metrics are aggregated in the process before sampling applies, so gen_ai.client.token.usage (split by gen_ai.token.type) counts every call. Use that metric for spend reports and keep traces for debugging individual requests.
Exercise
A colleague adds user.id as an attribute on gen_ai.client.token.usage to chart tokens per user. What problem does this cause, and what is a better design?
Show answer
Each user ID creates its own time series, so the series count grows with your user base. That can overload the metrics backend and raise its cost. Keep the metric attributes to low-cardinality values such as model and token type. Put user.id on the span, or on a log or span-derived analysis, and look at the heaviest users from there.