AI and machine learning · Advanced · 28 min
Trace LLM calls with OpenTelemetry
By Padding · Updated 18 Nov 2026
Python 3.15 · anthropic SDK 2.14.0 · opentelemetry-sdk 1.45.2 · OpenTelemetry Collector 0.166.0
You will have a Python app whose Claude calls, retries and tool runs appear as one OpenTelemetry trace with GenAI attributes, token and latency metrics, prompts kept out by default, and an export path from the console to an OpenTelemetry Collector.
On this page
When a feature built on a language model is slow or expensive, the first question is always the same: which call? A support assistant might make three model calls and run two tools for one user question, retry once after a rate limit, and spend most of its tokens on a system prompt nobody has looked at in months. Logs show pieces of that. A trace shows the whole question as one tree, with timings and token counts on each branch.
This tutorial builds that trace for a small currency assistant that calls Claude with one tool. You will:
- register OpenTelemetry tracer and meter providers, and see the span that the Anthropic Python SDK emits on its own for each request
- group every model call and tool run for one question under one parent span
- run your own retry loop so each attempt is a separate child span
- record token and latency histograms named after the OpenTelemetry GenAI semantic conventions
- keep prompts and replies out of telemetry by default, with a redacted opt-in
- export everything to the console first, then over OTLP to an OpenTelemetry Collector
Two things moved recently, and both shape the code. The GenAI semantic conventions now live in their own repository and had their first standalone release, v0.1.0, on 21 November 2026; every attribute and metric in them still has the status Development, so names can change. And the Anthropic Python SDK, including the 2.14.0 release used here, now emits its own spans, in beta. Pin both, as this tutorial does, and expect to rename things when you upgrade.
Every call goes to a local stub of the Messages API, so you need no API key and spend nothing. The token counts and timings you see are made up by the stub; the code and the attribute names are the same against the real API.
Step 1 · Create the project
Make a throwaway project and add the Anthropic SDK, the OpenTelemetry API and SDK, and the OTLP exporter that sends over HTTP. The versions are pinned exactly, because span and attribute names in both the SDK and the conventions can change between releases:
mkdir -p ~/llm-trace-demo
cd ~/llm-trace-demo
uv init --no-package
uv add "anthropic==2.14.0" "opentelemetry-api==1.45.2" "opentelemetry-sdk==1.45.2" \
"opentelemetry-exporter-otlp-proto-http==1.45.2"opentelemetry-api is what libraries call. It records nothing on its own: until your app installs opentelemetry-sdk and registers providers, every span and metric is a cheap no-op. That split is why the Anthropic SDK can depend on the API without forcing tracing on anyone.
Check it worked
uv run python -c "import anthropic, opentelemetry.sdk.version as v; print(anthropic.__version__, v.__version__)"The output is 2.14.0 1.45.2.
Step 2 · Start a stub of the Messages API
Create stub_server.py, a cut-down version of the stub from testing Claude API code offline. It answers POST /v1/messages in three ways: a plain greeting when the request has no tools, a tool_use block asking for convert_currency on the first turn, and a text answer once the request carries a tool_result. A second argument makes it refuse the first few requests with a 429 rate-limit error, so you can watch a retry later. It also prints the traceparent header of each request, which comes up in the next step:
cat > stub_server.py <<'PY'
"""A local stand-in for the Claude Messages API. Standard library only.
Usage: python stub_server.py [port] [busy]
The first <busy> requests get a 429 rate-limit error, so you can watch retries.
"""
import json
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8811
BUSY = int(sys.argv[2]) if len(sys.argv) > 2 else 0
state = {"requests": 0}
def message(msg_id, content, stop_reason, usage):
return {
"id": msg_id,
"type": "message",
"role": "assistant",
"model": "claude-opus-5-5",
"content": [{"type": "thinking", "thinking": "", "signature": "stub"}] + content,
"stop_reason": stop_reason,
"stop_sequence": None,
"usage": usage,
}
def answer(body):
if not body.get("tools"):
usage = {"input_tokens": 12, "output_tokens": 9}
return message("msg_stub_hello", [{"type": "text", "text": "Hello from the stub."}],
"end_turn", usage)
last = body["messages"][-1]["content"]
results = [b for b in last if isinstance(b, dict) and b.get("type") == "tool_result"]
if results:
text = f"50 US dollars is about {results[0]['content']} at today's rate."
usage = {"input_tokens": 96, "output_tokens": 41,
"cache_read_input_tokens": 512, "cache_creation_input_tokens": 0}
return message("msg_stub_answer", [{"type": "text", "text": text}], "end_turn", usage)
call = {"type": "tool_use", "id": "toolu_stub_01", "name": "convert_currency",
"input": {"amount": 50, "from_currency": "USD", "to_currency": "KES"}}
usage = {"input_tokens": 512, "output_tokens": 188,
"cache_read_input_tokens": 0, "cache_creation_input_tokens": 0}
return message("msg_stub_tool", [call], "tool_use", usage)
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
state["requests"] += 1
if state["requests"] <= BUSY:
error = {"type": "rate_limit_error", "message": "Rate limited by the stub."}
return self.reply(429, {"type": "error", "error": error}, {"retry-after": "1"})
self.reply(200, answer(body), {"request-id": f"req_stub_{state['requests']}"})
def reply(self, status, payload, headers):
data = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
for key, value in headers.items():
self.send_header(key, value)
self.end_headers()
self.wfile.write(data)
def log_request(self, code="-", size="-"):
traceparent = self.headers.get("traceparent", "none")
print(f"stub: {self.command} {self.path} -> {code} traceparent={traceparent}", flush=True)
print(f"Stub Messages API on http://127.0.0.1:{PORT} (first {BUSY} requests get 429)", flush=True)
ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
PYThe usage numbers are invented, but their shape is real: the second reply reports 512 tokens read from the prompt cache, the way the API does when the same long system prompt and tool list come back on the next turn.
Start the stub in a second terminal and leave it running:
cd ~/llm-trace-demo
uv run stub_server.py 8811Back in the first terminal, point the SDK at it for the rest of this session. stub-key is not a key; the SDK refuses to send a request without one, and the stub never checks it:
export ANTHROPIC_BASE_URL=http://127.0.0.1:8811
export ANTHROPIC_API_KEY=stub-key
curl -s "$ANTHROPIC_BASE_URL/v1/messages" -H "content-type: application/json" \
-d '{"model": "claude-opus-5-5", "max_tokens": 100, "messages": [{"role": "user", "content": "hi"}]}' \
| tee /tmp/hello.json
echo
grep -q "Hello from the stub" /tmp/hello.jsonCheck it worked
The second terminal prints Stub Messages API on http://127.0.0.1:8811 (first 0 requests get 429), then stub: POST /v1/messages -> 200 traceparent=none for the curl request. curl prints one line of JSON containing "Hello from the stub.". When you move to the real API later, unset ANTHROPIC_BASE_URL and load your real key from its private file, as in calling an LLM API from Python.
Step 3 · Register providers and see the SDK's own span
Create telemetry.py. It builds a tracer provider and a meter provider, both tagged with a service.name, and registers them globally. With APP_TELEMETRY unset it prints to the console, one JSON object per line so you can filter it with grep; with APP_TELEMETRY=otlp it sends over OTLP instead, which you use in the last step:
cat > telemetry.py <<'PY'
"""Set up OpenTelemetry tracing and metrics for this app."""
import os
from opentelemetry import metrics, trace
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import ConsoleMetricExporter, PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
def one_line(item):
return item.to_json(indent=None) + "\n"
def setup_telemetry(service_name):
resource = Resource.create({"service.name": service_name, "service.version": "0.1.0"})
if os.environ.get("APP_TELEMETRY", "console") == "otlp":
# Sends to OTEL_EXPORTER_OTLP_ENDPOINT (default http://localhost:4318)
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
span_exporter, metric_exporter = OTLPSpanExporter(), OTLPMetricExporter()
else:
span_exporter = ConsoleSpanExporter(formatter=one_line)
metric_exporter = ConsoleMetricExporter(formatter=one_line)
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(BatchSpanProcessor(span_exporter))
trace.set_tracer_provider(tracer_provider)
reader = PeriodicExportingMetricReader(metric_exporter, export_interval_millis=10_000)
meter_provider = MeterProvider(resource=resource, metric_readers=[reader])
metrics.set_meter_provider(meter_provider)
def shutdown():
# Flushes the last spans and metrics before the process exits.
tracer_provider.shutdown()
meter_provider.shutdown()
return shutdown
PYshutdown matters more than it looks. The batch processor holds spans in memory and sends them every few seconds; a short script that exits without calling it loses its last spans, which are usually the ones you wanted.
Now make one call with no tracing code of your own:
cat > hello.py <<'PY'
import anthropic
from telemetry import setup_telemetry
shutdown = setup_telemetry("fx-assistant")
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY and ANTHROPIC_BASE_URL
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=4000, # thinking counts towards this, so leave room for it
messages=[{"role": "user", "content": "Say hello."}],
)
print("stop_reason:", message.stop_reason, flush=True)
shutdown()
PY
uv run hello.py | tee hello.jsonl
grep -q '"name": "anthropic.messages.create"' hello.jsonl
grep -q '"gen_ai.request.model": "claude-opus-5-5"' hello.jsonl
grep -q '"gen_ai.usage.output_tokens": 9' hello.jsonlThe SDK emits one CLIENT span per request, named anthropic.messages.create, whenever a tracer provider is registered. It fills in the GenAI attributes for you: gen_ai.provider.name, gen_ai.operation.name (chat), gen_ai.request.model, gen_ai.request.max_tokens, gen_ai.response.id, gen_ai.response.model and the usage counts, plus HTTP attributes and the request-id header as anthropic.request.id. It also sends the span's trace context to the API in a traceparent header, so Anthropic's server-side spans can join your trace if you turn on API tracing for your organisation.
Check it worked
The output starts with stop_reason: end_turn, then one long JSON line for the span, with "name": "anthropic.messages.create", "kind": "SpanKind.CLIENT", "gen_ai.request.model": "claude-opus-5-5" and "gen_ai.usage.output_tokens": 9. In the second terminal the stub's log line now shows traceparent=00-...: the 32 hex characters after 00- are the same as the span's trace_id without its 0x. If you see no span, the provider was registered after the client made its call, or ANTHROPIC_OPEN_TELEMETRY is set to false.
Step 4 · Decide what may leave the process
Spans travel: to a Collector, to a vendor, into dashboards that more people can read than your production database. A prompt can hold a customer's email address, phone number or account details, and the conventions treat recording it as an explicit opt-in. The SDK agrees: its content_mode defaults to metadata_only, and only ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE=content adds prompts and replies to its spans, unredacted.
Leave the SDK in metadata_only. When you do need content to debug a bad answer, record it yourself, after redaction, behind the switch the conventions define: OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT, whose default is NO_CONTENT. Create privacy.py:
cat > privacy.py <<'PY'
"""Prompts and replies stay out of telemetry unless someone opts in."""
import os
import re
EMAIL = re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+")
PHONE = re.compile(r"\+?\d[\d -]{7,}\d")
MAX_CHARS = 500
def capture_content():
setting = os.environ.get("OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT", "NO_CONTENT")
return setting.upper() in ("SPAN_ONLY", "SPAN_AND_EVENT")
def redact(text):
text = PHONE.sub("[phone]", EMAIL.sub("[email]", str(text)))
return text if len(text) <= MAX_CHARS else text[:MAX_CHARS] + "[truncated]"
def redact_arguments(arguments):
return {k: redact(v) if isinstance(v, str) else v for k, v in arguments.items()}
def to_parts(content):
"""Turn Messages API content into the conventions' message parts."""
if isinstance(content, str):
return [{"type": "text", "content": redact(content)}]
parts = []
for block in content:
block = block if isinstance(block, dict) else block.model_dump()
if block["type"] == "text":
parts.append({"type": "text", "content": redact(block["text"])})
elif block["type"] == "tool_use":
parts.append({"type": "tool_call", "id": block["id"], "name": block["name"],
"arguments": redact_arguments(block["input"])})
elif block["type"] == "tool_result":
parts.append({"type": "tool_call_response", "id": block["tool_use_id"],
"response": redact(block["content"])})
return parts # thinking blocks are left out on purpose
PYto_parts turns Messages API content blocks into the message parts the conventions describe: text, tool_call and tool_call_response. Thinking blocks are dropped. The cap of 500 characters per part keeps one long document from blowing past a back end's attribute size limit.
Two regular expressions are a floor, not a privacy programme. They miss names, addresses and ID numbers, and phone formats vary by country. For real redaction, see redacting personal data before sending text to an LLM, and run the same redaction on telemetry.
Check it worked
uv run python -c "from privacy import redact, capture_content; print(capture_content(), redact('Call +254 712 345 678 or mail ama@example.com'))" | tee /tmp/redact.txt
grep -q "False Call \[phone\] or mail \[email\]" /tmp/redact.txtThe output is False Call [phone] or mail [email]: capture is off, and both details are replaced.
Step 5 · Put every call and tool run in one trace
The SDK's span covers one HTTP request. A user's question is bigger than that: here it is a model call that asks for a tool, the tool run, and a second model call that writes the answer. Create genai_trace.py with three things the SDK does not do for you:
call_claudeopens anllm_callspan and runs its own retry loop with SDK retries switched off, so each attempt becomes a separateanthropic.messages.createchild span. The conventions say the span for one logical model call should cover all its retries;llm_callis that span. It carries no token counts, so the SDK spans stay the single place to sum usage.- It records three histograms the SDK does not emit: duration, input tokens and output tokens per call, with the names and bucket boundaries from the conventions.
run_toolwraps a tool in anexecute_tool {name}span with the conventions' tool attributes.
cat > genai_trace.py <<'PY'
"""Spans and metrics around Claude calls, named after the GenAI semantic conventions v0.1.0."""
import json
import time
import anthropic
from opentelemetry import metrics, trace
from opentelemetry.trace import SpanKind
from privacy import capture_content, redact, redact_arguments, to_parts
tracer = trace.get_tracer("fx_assistant", "0.1.0")
meter = metrics.get_meter("fx_assistant", "0.1.0")
# Bucket boundaries recommended by the conventions.
SECONDS = [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60]
TOKENS = [4**n for n in range(14)] # 1, 4, 16 ... 67108864
inference_duration = meter.create_histogram(
"gen_ai.client.inference.duration", unit="s",
description="GenAI client inference operation duration.",
explicit_bucket_boundaries_advisory=SECONDS,
)
input_tokens = meter.create_histogram(
"gen_ai.client.inference.operation.input_tokens", unit="{token}",
description="Input tokens per inference operation, including cached tokens.",
explicit_bucket_boundaries_advisory=TOKENS,
)
output_tokens = meter.create_histogram(
"gen_ai.client.inference.operation.output_tokens", unit="{token}",
description="Output tokens per inference operation, including thinking tokens.",
explicit_bucket_boundaries_advisory=TOKENS,
)
def error_type(err):
"""The API's error type (rate_limit_error ...), else the exception class."""
return getattr(err, "type", None) or type(err).__name__
def call_claude(client, request, max_attempts=3):
"""One logical model call: an llm_call span around every attempt, plus metrics."""
client = client.with_options(max_retries=0) # this loop does the retrying
metric_attributes = {
"gen_ai.operation.name": "chat",
"gen_ai.provider.name": "anthropic",
"gen_ai.request.model": request["model"],
"server.address": client.base_url.host,
"server.port": client.base_url.port or 443,
}
started = time.perf_counter()
with tracer.start_as_current_span("llm_call") as span:
span.set_attribute("gen_ai.request.model", request["model"])
if capture_content():
span.set_attribute("gen_ai.input.messages", json.dumps(
[{"role": m["role"], "parts": to_parts(m["content"])} for m in request["messages"]]))
for attempt in range(1, max_attempts + 1):
span.set_attribute("app.llm.attempts", attempt)
try:
# The SDK adds one anthropic.messages.create span per attempt.
message = client.messages.create(**request)
break
except (anthropic.RateLimitError, anthropic.InternalServerError) as err:
span.add_event("retry", {"error.type": error_type(err), "attempt": attempt})
if attempt == max_attempts:
failed = {**metric_attributes, "error.type": error_type(err)}
inference_duration.record(time.perf_counter() - started, failed)
input_tokens.record(0, failed)
output_tokens.record(0, failed)
raise
time.sleep(min(float(err.response.headers.get("retry-after", 2**attempt)), 30))
if capture_content():
span.set_attribute("gen_ai.output.messages", json.dumps(
[{"role": "assistant", "parts": to_parts(message.content)}]))
usage = message.usage
# Anthropic's input_tokens leaves out cache reads and writes; the conventions count them.
total_input = (usage.input_tokens + (usage.cache_read_input_tokens or 0)
+ (usage.cache_creation_input_tokens or 0))
done = {**metric_attributes, "gen_ai.response.model": message.model}
inference_duration.record(time.perf_counter() - started, done)
input_tokens.record(total_input, done)
output_tokens.record(usage.output_tokens, done)
return message
def run_tool(block, functions):
"""Run one tool_use block in an execute_tool span."""
with tracer.start_as_current_span(
f"execute_tool {block.name}",
kind=SpanKind.INTERNAL,
attributes={
"gen_ai.operation.name": "execute_tool",
"gen_ai.tool.name": block.name,
"gen_ai.tool.call.id": block.id,
"gen_ai.tool.type": "function",
},
) as span:
result = functions[block.name](**block.input)
if capture_content():
span.set_attribute("gen_ai.tool.call.arguments", json.dumps(redact_arguments(block.input)))
span.set_attribute("gen_ai.tool.call.result", redact(result))
return result
PYPython's span attributes accept strings, numbers, booleans and lists of them, not nested objects, so the message lists go in as JSON strings. The SDK records its own content attributes the same way.
Now the app. answer opens an answer_question span, so everything inside it shares one trace ID. The loop stops after three model calls, and it handles a reply that hit max_tokens while still thinking, which has no text at all:
cat > app.py <<'PY'
"""A small currency assistant: one question, one tool, every step traced."""
import sys
import anthropic
from genai_trace import call_claude, run_tool, tracer
from telemetry import setup_telemetry
MODEL = "claude-opus-5-5"
MAX_TOKENS = 4000 # thinking counts towards this, so leave room for it
SYSTEM = "You convert currencies. Use the convert_currency tool for every rate."
RATES_PER_USD = {"USD": 1.0, "KES": 129.0, "NGN": 1550.0, "GHS": 15.4, "ZAR": 18.1}
TOOLS = [{
"name": "convert_currency",
"description": "Convert an amount between two currencies at today's rate.",
"input_schema": {
"type": "object",
"properties": {
"amount": {"type": "number"},
"from_currency": {"type": "string", "enum": list(RATES_PER_USD)},
"to_currency": {"type": "string", "enum": list(RATES_PER_USD)},
},
"required": ["amount", "from_currency", "to_currency"],
},
}]
def convert_currency(amount, from_currency, to_currency):
usd = amount / RATES_PER_USD[from_currency]
return f"{usd * RATES_PER_USD[to_currency]:,.2f} {to_currency}"
def answer(client, question):
messages = [{"role": "user", "content": question}]
with tracer.start_as_current_span("answer_question"):
for _ in range(3): # at most three model calls per question
message = call_claude(client, {"model": MODEL, "max_tokens": MAX_TOKENS,
"system": SYSTEM, "tools": TOOLS,
"messages": messages})
text = "".join(b.text for b in message.content if b.type == "text").strip()
if message.stop_reason == "max_tokens" and not text:
return "Stopped at max_tokens before answering; raise MAX_TOKENS."
if message.stop_reason != "tool_use":
return text
messages.append({"role": "assistant", "content": message.content})
results = [
{"type": "tool_result", "tool_use_id": block.id,
"content": run_tool(block, {"convert_currency": convert_currency})}
for block in message.content if block.type == "tool_use"
]
messages.append({"role": "user", "content": results})
return "No answer after three model calls."
if __name__ == "__main__":
shutdown = setup_telemetry("fx-assistant")
question = sys.argv[1] if len(sys.argv) > 1 else (
"Hi, this is ama@example.com. How much is 50 US dollars in Kenyan shillings?")
try:
print("ANSWER:", answer(anthropic.Anthropic(), question), flush=True)
finally:
shutdown()
PYgenai_trace asks for its tracer and meter at import, before setup_telemetry runs. That is fine: the OpenTelemetry API hands out proxies that start recording once a provider is registered.
The console output is long, so add summarise.py, which prints the spans as an indented tree and the last batch of metrics as a table:
cat > summarise.py <<'PY'
"""Print console-exporter output as a span tree and a metrics table."""
import json
import sys
spans, metric_batches = [], []
for line in open(sys.argv[1]):
if line.startswith("{"):
item = json.loads(line)
(metric_batches if "resource_metrics" in item else spans).append(item)
children = {}
for span in spans:
children.setdefault(span["parent_id"], []).append(span)
KEYS = ["http.response.status_code", "error.type", "gen_ai.usage.input_tokens",
"gen_ai.usage.output_tokens", "anthropic.message.stop_reason", "app.llm.attempts"]
def show(span, depth=0):
attrs = span["attributes"]
details = " ".join(f"{k.split('.')[-1]}={attrs[k]}" for k in KEYS if k in attrs)
print(f"{' ' * depth}{span['name']} {details}".rstrip())
for child in sorted(children.get(span["context"]["span_id"], []), key=lambda s: s["start_time"]):
show(child, depth + 1)
for root in children.get(None, []):
print("trace", root["context"]["trace_id"])
show(root, 1)
for batch in metric_batches[-1:]:
for resource in batch["resource_metrics"]:
for scope in resource["scope_metrics"]:
for metric in scope["metrics"]:
for point in metric["data"]["data_points"]:
print(f"{metric['name']} ({metric['unit']}): count={point['count']} "
f"sum={round(point['sum'], 3)} error={point['attributes'].get('error.type', '-')}")
PY
uv run app.py > run1.jsonl
uv run summarise.py run1.jsonl | tee tree1.txt
grep -q "ANSWER: 50 US dollars is about 6,450.00 KES" run1.jsonl
grep -q "execute_tool convert_currency" tree1.txt
test "$(grep -c 'anthropic.messages.create status_code=200' tree1.txt)" -eq 2Check it worked
The tree has one trace ID and this shape (your IDs differ):
trace 0x6476d438d58ac580202f20f61398f618
answer_question
llm_call attempts=1
anthropic.messages.create status_code=200 input_tokens=512 output_tokens=188 stop_reason=tool_use
execute_tool convert_currency
llm_call attempts=1
anthropic.messages.create status_code=200 input_tokens=608 output_tokens=41 stop_reason=end_turnLook at input_tokens=608 on the second call. The stub reported 96 input tokens and 512 cache reads; the SDK's span adds them, as the conventions ask, because cached tokens are still tokens the model read. run1.jsonl also starts with ANSWER: 50 US dollars is about 6,450.00 KES at today's rate.
Step 6 · Watch a retry become a child span
Restart the stub so it refuses the first request with a 429. In the second terminal, press Ctrl+C, then:
uv run stub_server.py 8811 1Ask the same question again:
uv run app.py > run2.jsonl
uv run summarise.py run2.jsonl | tee tree2.txt
grep -q "anthropic.messages.create status_code=429 type=rate_limit_error" tree2.txt
grep -q "llm_call attempts=2" tree2.txtThe first attempt fails, call_claude waits the one second the retry-after header asks for, and the second attempt succeeds. If you leave the SDK's own retries on instead (the default is two), you get one anthropic.messages.create span for the whole call with http.request.resend_count set and no span per attempt. That is less detail, but less code; pick one, never both, or every failure retries nine times.
Check it worked
The first llm_call now has two children:
llm_call attempts=2
anthropic.messages.create status_code=429 type=rate_limit_error
anthropic.messages.create status_code=200 input_tokens=512 output_tokens=188 stop_reason=tool_useThe failed attempt's span has status ERROR and error.type rate_limit_error, and the llm_call span has a retry event. The question still got its answer, and in a back end the one-second gap between the two child spans shows exactly where the time went.
Step 7 · Read the token and latency metrics
Traces answer "what happened to this question". Metrics answer "what is happening to all of them": they are cheap to keep for months and can drive alerts. The summary ends with the three histograms from the last run:
grep "gen_ai.client" tree2.txt
grep -q "gen_ai.client.inference.operation.input_tokens ({token}): count=2 sum=1120" tree2.txt
grep -q "gen_ai.client.inference.operation.output_tokens ({token}): count=2 sum=229" tree2.txtEach histogram counts one value per logical call, not per attempt, so the retry does not double the token counts. Their attributes are the model, provider, operation and server, all of which have a handful of values. Never add a user ID, question text or trace ID to a metric attribute: each new value creates a new time series, and the bill or the memory of your metrics store grows with your user count.
Check it worked
You see three lines like these (the duration includes the one-second retry wait):
gen_ai.client.inference.duration (s): count=2 sum=1.033 error=-
gen_ai.client.inference.operation.input_tokens ({token}): count=2 sum=1120 error=-
gen_ai.client.inference.operation.output_tokens ({token}): count=2 sum=229 error=-With the real API these numbers are what you multiply by your model's prices to see cost per question. Output tokens include thinking tokens, which on Opus 5.5 are often most of them. If your users write in Swahili, Yoruba or Amharic as well as English, the same question can use noticeably more tokens in one language than another; adding a low-cardinality app.language attribute to these histograms shows that difference directly.
Step 8 · Opt in to redacted prompt capture
Search the first run for the customer's email address and the question:
grep -c "example.com" run1.jsonl || true
grep -c "Kenyan" run1.jsonl || true
test "$(grep -c 'Kenyan' run1.jsonl)" -eq 0Both counts are 0: by default no prompt, reply or tool argument left the process. Now turn capture on for one run, as you would while debugging a bad answer:
OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT=SPAN_ONLY uv run app.py > run3.jsonl
grep -o '"gen_ai.input.messages": "[^}]*}' run3.jsonl | head -1
grep -q 'this is \[email\]' run3.jsonl
test "$(grep -c 'ama@example.com' run3.jsonl)" -eq 0The app's own spans gain gen_ai.input.messages, gen_ai.output.messages, gen_ai.tool.call.arguments and gen_ai.tool.call.result. The SDK's spans do not, because the SDK is still in metadata_only mode. Do not set ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE=content as well, or the same prompt goes out a second time without redaction.
Check it worked
The grep -o line prints something like "gen_ai.input.messages": "[{\"role\": \"user\", \"parts\": [{\"type\": \"text\", \"content\": \"Hi, this is [email]. How much is 50 US dollars in Kenyan shillings?\"}. The question is there; the email address is not. Keep the switch off in production and turn it on per deployment for a limited time; a person should still read a sample of captured spans to check the redaction catches what your users actually type.
Step 9 · Export over OTLP to a Collector
The console is for development. In production your app sends OTLP to an OpenTelemetry Collector, which batches, filters and forwards to whatever tracing back end you use. Download the Collector's core build into the project folder. It is about 43 MB, worth knowing on a metered connection. The script picks the right file for Linux or macOS on Intel or ARM:
cd ~/llm-trace-demo
OTELCOL_VERSION=0.166.0
os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$(uname -m)" in
x86_64) arch=amd64 ;;
aarch64 | arm64) arch=arm64 ;;
*) echo "No Collector build for $(uname -m) here"; false ;;
esac
curl -fsSLO "https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v${OTELCOL_VERSION}/otelcol_${OTELCOL_VERSION}_${os}_${arch}.tar.gz"
tar -xzf "otelcol_${OTELCOL_VERSION}_${os}_${arch}.tar.gz" otelcol
./otelcol --versionA binary downloaded by hand gets no security updates from your package manager. To upgrade, change OTELCOL_VERSION to the newest release on the opentelemetry-collector-releases page and run the block again. Running the Collector as a service with a full pipeline is covered in running the OpenTelemetry Collector as a telemetry pipeline.
Write a configuration that receives OTLP over HTTP on port 4318 and prints everything it gets with the debug exporter:
cat > collector.yaml <<'YAML'
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:4318
processors:
batch: {}
exporters:
debug:
verbosity: detailed
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [debug]
metrics:
receivers: [otlp]
processors: [batch]
exporters: [debug]
YAML
./otelcol validate --config collector.yaml && echo "collector.yaml is valid"Start it in a third terminal, and leave the stub running in the second:
cd ~/llm-trace-demo
./otelcol --config collector.yamlRun the app with OTLP export. Nothing in app.py changes; only the environment does:
APP_TELEMETRY=otlp OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 uv run app.pyTo send to a real back end, replace debug with an otlphttp exporter pointing at your vendor's endpoint, and keep its API token in an environment variable or a file the Collector reads, never in collector.yaml itself.
Check it worked
The app prints only ANSWER: 50 US dollars is about 6,450.00 KES at today's rate.; the spans no longer go to your terminal. In the Collector's terminal, a few seconds later, you see something like Name : anthropic.messages.create and Name : execute_tool convert_currency in the traces output, -> service.name: Str(fx-assistant) among the resource attributes, and gen_ai.client.inference.duration in the metrics output. Stop the Collector and the stub with Ctrl+C. When you have finished with the project, delete it:
cd ~
rm -rf ~/llm-trace-demoNext steps
- Add HTTP and web framework spans around this code, with sampling: trace a Python web app with OpenTelemetry.
- Build a real Collector pipeline that deletes sensitive attributes and keeps every error trace: run the OpenTelemetry Collector as a telemetry pipeline.
- Use the cache-read numbers from these spans to cut cost: cut LLM costs with prompt caching.
- Test the same code against fixtures for errors and odd replies: test Claude API code offline against a stub server.
Related tutorials
- Use MCP server tools from your own Claude appYou will connect a Python app to the stdio clinic-hours MCP server, hand an allowlisted set of its tools to Claude, pass every tool call through to the server with a tested bridge, and know when the API's MCP connector can do the connecting for you.
- Serve an MCP server over Streamable HTTP with authenticationYou will run an MCP server over Streamable HTTP on localhost that checks the Origin header, accepts only bearer tokens your token verifier knows, limits each tool to the right scope, and refuses calls without a token.
- Secure the MCP servers you build and the ones you installYou will harden a small clinic MCP server with a read-only database connection, a file allowlist, input limits and its own credential, prove each guard with pytest, and pin a server's tool list so a changed or poisoned tool is caught before you approve it.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials