Lesson 67.6 · 6 of 9 · 4 min read · Reviewed 24 Nov 2026
Worked example: usage fields, request ids and OpenTelemetry
By the end, you can
- Read usage and request ids from Claude API responses.
- Turn on OpenTelemetry for Claude Code.
Usage on every response
A Messages APIMessages API: The chat API endpoint that takes a list of messages and returns the next assistant message. response includes a usage object like this:
"usage": {
"input_tokens": 2310,
"output_tokens": 180,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 1950
}
Put these numbers on the model span. Cached reads and cache writes are priced differently from plain input, so keep them separate when computing cost. The pricing page has current rates. For streamingStreaming: Receiving a response as a series of server-sent events while it is generated, instead of waiting for the whole reply., the final counts arrive in the closing events of the stream.
Request ids
Every response carries a request id in its headers, and the official SDKs expose it on the response object. Log it on the span. When you report a problem, the request id lets support find that exact call.
Errors are data too
Record the error type (for example rate_limit_error or overloaded_error) and status code on the span. Chapter 69 uses these to drive retries and alerts.
Claude Code telemetry
Claude Code can export metrics and events through OpenTelemetryOpenTelemetry: An open standard and toolkit for collecting traces, metrics and logs from software., configured with environment variables, for example:
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
It reports things like sessions, tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. use, cost estimates, and tool decisions. Prompt text is not included by default. Check the monitoring docs for the current list of metrics and the opt-in setting for prompts.
On other providers
Every API returns token counts, under different names. OpenAI reports input and output tokensOutput tokens: The tokens the model generates in its reply, including any tool calls and thinking. with details for cached input and reasoning tokens. Gemini’s usageMetadata reports prompt, candidate, thought and cached-content token counts. Map them onto the OpenTelemetry GenAI names (67.7) at the edge so dashboards and cost reports work across providers.
Key points
- Each Messages API response includes a usage object with input, output and cache token counts.
- Each response has a request id; log it so you and Anthropic support can find a specific call.
- Claude Code can export metrics and events with OpenTelemetry; prompt text is left out unless you opt in.
Record usage and ids on spans
Turn a Messages API response into a model span with exact token counts, ids and cost.
You will have: A model_span() function that prints every field needed for cost and support lookups.
Steps
- Run the starter against the simulated API: the span has only the model id.
- Copy input and output tokens from the usage object.
- Add cache read and cache write tokens as separate fields.
- Add the message id and request id, and an error branch that keeps the request id.
- Compute cost in illustrative credits from the four counts.
Done when
- The span prints gen_ai.usage.input_tokens and gen_ai.usage.output_tokens.
- Cache reads and writes are separate fields.
- cost_credits is computed from the usage numbers, not guessed.
Open in the Playground No API key needed.
Starter code (Python)
# Put exact usage numbers and ids on a model span, then cost it in illustrative credits.
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"
# Illustrative credits per 1,000 tokens. Look up real prices on the pricing page.
RATES = {"input": 1.0, "output": 5.0, "cache_read": 0.1, "cache_write": 1.25}
def model_span(resp, model):
span = {"gen_ai.request.model": model, "status": "ok"}
# TODO: copy input and output tokens from resp.usage onto the span
# TODO: keep cache reads (cache_read_input_tokens) and writes (cache_creation_input_tokens) separate
# TODO: add resp.id, and a request id if the response exposes one
# TODO: compute span["cost_credits"] from the four token counts and RATES
return span
try:
resp = client.messages.create(model=MODEL, max_tokens=200,
messages=[{"role": "user", "content": "In one sentence, what is a trace?"}])
span = model_span(resp, MODEL)
except anthropic.APIStatusError as e:
# TODO: record the status code and e.request_id on an error span
span = {"gen_ai.request.model": MODEL, "status": "error"}
for k, v in span.items():
print(f"{k:<28} {v}")
Show a solution
# Put exact usage numbers and ids on a model span, then cost it in illustrative credits.
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"
# Illustrative credits per 1,000 tokens. Look up real prices on the pricing page.
RATES = {"input": 1.0, "output": 5.0, "cache_read": 0.1, "cache_write": 1.25}
def model_span(resp, model):
u = resp.usage
span = {
"gen_ai.request.model": model,
"gen_ai.usage.input_tokens": u.input_tokens,
"gen_ai.usage.output_tokens": u.output_tokens,
"cache_read_tokens": getattr(u, "cache_read_input_tokens", 0) or 0,
"cache_write_tokens": getattr(u, "cache_creation_input_tokens", 0) or 0,
"message_id": resp.id,
"request_id": getattr(resp, "_request_id", None) or "(read it from the response headers)",
"status": "ok",
}
span["cost_credits"] = round((span["gen_ai.usage.input_tokens"] * RATES["input"]
+ span["gen_ai.usage.output_tokens"] * RATES["output"]
+ span["cache_read_tokens"] * RATES["cache_read"]
+ span["cache_write_tokens"] * RATES["cache_write"]) / 1000, 4)
return span
try:
resp = client.messages.create(model=MODEL, max_tokens=200,
messages=[{"role": "user", "content": "In one sentence, what is a trace?"}])
span = model_span(resp, MODEL)
except anthropic.APIStatusError as e:
span = {"gen_ai.request.model": MODEL, "status": "error", "status_code": e.status_code, "request_id": e.request_id}
for k, v in span.items():
print(f"{k:<28} {v}")
Do it Watch usage numbers on a streamed reply in the Playground. No API key needed.