Sub topic 18
GenAI metrics alongside traces
This chapter assumes you have the SDK set up from earlier chapters and know how to record token usage on a span.
Why add metrics
A trace describes one request in detail. A metric summarizes many requests as numbers over time. Traces answer "why was this request slow?" Metrics answer "is latency getting worse, and how many tokens did we spend this hour?"
Sampling is the main reason to keep both. If you sample 10% of traces, counting spans undercounts traffic and cost. Metrics are recorded for every call, so totals stay accurate.
The standard instruments
The GenAI semantic conventions define client-side histograms. A histogram stores the distribution of values, so you can compute percentiles.
| Metric | Unit | Meaning |
|---|---|---|
| `gen_ai.client.operation.duration` | `s` | Time for one model call |
| `gen_ai.client.token.usage` | `{token}` | Tokens per call, split by `gen_ai.token.type` (`input` or `output`) |
These conventions are still evolving, so check the current specification for exact names and required attributes.
Recording metrics in Python
Metrics use a separate provider from traces. This example exports to the same Collector over OTLP/HTTP.
import time
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint="http://localhost:4318/v1/metrics"),
export_interval_millis=15000,
)
metrics.set_meter_provider(
MeterProvider(
resource=Resource.create({"service.name": "support-agent"}),
metric_readers=[reader],
)
)
meter = metrics.get_meter("support_agent")
duration = meter.create_histogram(
"gen_ai.client.operation.duration", unit="s",
description="GenAI client operation duration",
)
token_usage = meter.create_histogram(
"gen_ai.client.token.usage", unit="{token}",
description="Tokens used per GenAI operation",
)
def record_chat(model, input_tokens, output_tokens, seconds, error_type=None):
attrs = {"gen_ai.operation.name": "chat", "gen_ai.request.model": model}
if error_type:
attrs["error.type"] = error_type
duration.record(seconds, attrs)
token_usage.record(input_tokens, {**attrs, "gen_ai.token.type": "input"})
token_usage.record(output_tokens, {**attrs, "gen_ai.token.type": "output"})
start = time.perf_counter()
# ... call the model here ...
record_chat("example-model", 12, 3, time.perf_counter() - start)Use the same values you put on the span. Reuse the token counts and attribute names so a dashboard and a trace agree.
Add a metrics pipeline
The Collector configuration from earlier needs a second pipeline. Add this under service.pipelines, and keep the traces pipeline as it is:
metrics:
receivers: [otlp]
processors: [batch]
exporters: [debug]Keep attributes low-cardinality
Every unique combination of attribute values creates a separate time series. Model name, operation name, and error type are safe. Never put user IDs, trace IDs, or prompt text on a metric. Those values belong on spans, where each record is stored once.
Exercise
Your traces are sampled at 5%. A dashboard built from span counts shows 1,000 chat calls per hour. Why might this be wrong, and which instrument gives the correct total?
Show answer
Only sampled requests produce stored spans, so span counts undercount real traffic. The gen_ai.client.operation.duration histogram is recorded on every call, and its count gives the real number of calls. The sum of gen_ai.client.token.usage gives total tokens.