Lesson 67.7 · 7 of 9 · 5 min read · Reviewed 24 Nov 2026
OpenTelemetry for LLM and agent traces
By the end, you can
- Explain how OpenTelemetry carries LLM and agent traces from your code to a backend.
- Name model and tool spans with the generative AI semantic conventions.
Lesson 67.1 described tracesTrace: A record of everything that happened during one request or agent run, as a tree of timed steps. and spans. OpenTelemetryOpenTelemetry: An open standard and toolkit for collecting traces, metrics and logs from software. (often shortened to OTel) is the open standard most teams use to produce them. It is not a product: it is a set of APIs, SDKs and a wire format that many tools understand.
The moving parts
| Part | What it does |
|---|---|
| API and SDK | Your code starts and ends spans and sets attributes |
| Instrumentation | Libraries that create spans for you, for example around an HTTP client or a model SDK |
| Exporter | Sends finished spans out, usually over OTLP (the OpenTelemetry protocol) |
| Collector (optional) | A separate process that receives, filters, redacts, samples and forwards telemetry |
| Backend | Where you view and query traces: an open-source tool, an APM product, or an LLM tracing tool |
Because every part speaks the same format, you can change the backend without rewriting your instrumentation.
Names that line up: the GenAI conventions
OpenTelemetry publishes semantic conventions: agreed names for common attributes. The generative AI set covers model calls, tool calls and agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. steps. A few you will see often:
| Attribute | Meaning |
|---|---|
gen_ai.operation.name |
The kind of operation, such as chat, execute_tool or invoke_agent |
gen_ai.request.model |
The model id you asked for |
gen_ai.response.model |
The model id that actually answered |
gen_ai.usage.input_tokens |
Input tokens for this call |
gen_ai.usage.output_tokens |
Output tokens for this call |
The conventions are still marked as in development, so some names have changed between versions. Pick a version, note it in your code, and check the spec when you upgrade.
A worked example
Here is a model span created by hand with the Python API. Instrumentation libraries do the same thing for you.
from opentelemetry import trace
tracer = trace.get_tracer("support-agent")
def call_model(model_id, messages):
with tracer.start_as_current_span(f"chat {model_id}") as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.request.model", model_id)
resp = client.messages.create(model=model_id, max_tokens=500, messages=messages)
span.set_attribute("gen_ai.usage.input_tokens", resp.usage.input_tokens)
span.set_attribute("gen_ai.usage.output_tokens", resp.usage.output_tokens)
return resp
Wrap each tool call in its own span the same way. Because the spans are created inside the agent run’s span, they nest under it automatically.
Crossing service boundaries
An agent often calls tools that live elsewhere: an internal API, an MCPModel Context Protocol (MCP): An open protocol that standardises how AI applications connect to tools, data and prompts through servers. server, a subagentSubagent: A separate agent instance, with its own context and instructions, that a main agent delegates a task to. service. OpenTelemetry passes trace context (the trace id and parent span id) in request headers, using the W3C traceparent format. If the other service extracts that context, its spans join your trace. If not, you get two unrelated traces and lose the story.
Prompt text is opt-in
The conventions treat prompt and completion content as optional and sensitive. Many instrumentation libraries leave it out unless you turn it on. If you do capture it, redactRedaction: Removing or masking sensitive data, such as PII or secrets, before it is stored, logged or sent. first (67.3), or route content through a Collector that strips it before it reaches a third-party backend.
Common mistakes
- Inventing your own names like
llm_modelandtokens_in. Dashboards and tools then can’t line them up. - Dropping context at the tool boundary, so tool spans float in their own traces.
- SamplingSampling: Choosing the next token from the model’s probability distribution, rather than always taking the most likely one. at the start of a request only. You may throw away the rare failing run. A Collector can do tail sampling: decide after the trace ends, and keep every error.
- Capturing full content by default and sending it to a backend in another region (70.4).
Key points
- OpenTelemetry is a vendor-neutral standard: your code creates spans, an exporter sends them over OTLP, and any compatible backend can show them.
- The generative AI semantic conventions give shared names for model calls, tool calls and agent steps, such as gen_ai.request.model and gen_ai.usage.input_tokens.
- Propagate trace context to tools and other services so a whole agent run lands in one trace.
- Prompt and response text is opt-in; the conventions are still evolving, so pin the version you follow.
Propagate trace context across a tool call
Use the W3C traceparent header so a tool in another service joins the agent's trace.
You will have: inject() and extract() functions and a span list that forms one trace with GenAI attribute names.
Steps
- Run the starter: it reports 2 traces, because the tool span starts its own.
- Write inject() to build a traceparent header from the current span.
- Write extract() to read it back in the tool service.
- Run again and check the tool span's parent is the agent run span.
- Compare the attribute names with the OpenTelemetry GenAI conventions.
Done when
- traces: 1 is printed.
- The execute_tool span has the invoke_agent span as its parent.
- Spans use gen_ai.* attribute names, not invented ones.
Open in the Playground No API key needed.
Starter code (Python)
# Propagate trace context to a tool service so the whole run lands in one trace.
import random
rng = random.Random(7)
SPANS = []
def new_id(nbytes):
return "".join(f"{rng.randrange(256):02x}" for _ in range(nbytes))
def start_span(name, parent=None, attrs=None):
span = {"name": name, "trace_id": parent["trace_id"] if parent else new_id(16), "span_id": new_id(8),
"parent_id": parent["span_id"] if parent else None, "attrs": attrs or {}}
SPANS.append(span)
return span
def inject(span):
"""W3C trace context: version-traceid-spanid-flags."""
# TODO: return {"traceparent": "00-<trace id>-<span id>-01"} for this span
return {}
def extract(headers):
# TODO: split headers["traceparent"] on "-" and return {"trace_id": ..., "span_id": ...}
return None
def tool_service(headers, order_id):
"""Runs in another service. It only sees the request headers."""
parent = extract(headers)
start_span("execute_tool lookup_order", parent, {"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "lookup_order"})
return {"order_id": order_id, "status": "shipped"}
run = start_span("invoke_agent support", None, {"gen_ai.operation.name": "invoke_agent"})
start_span("chat claude-x", run, {"gen_ai.operation.name": "chat", "gen_ai.request.model": "claude-x",
"gen_ai.usage.input_tokens": 2310, "gen_ai.usage.output_tokens": 180})
tool_service(inject(run), "1120")
for s in SPANS:
print(f"{s['trace_id'][:8]} {s['name']:<28} parent={s['parent_id'] or '-'} {s['attrs'].get('gen_ai.operation.name')}")
print("traces:", len({s["trace_id"] for s in SPANS}))
Show a solution
# Propagate trace context to a tool service so the whole run lands in one trace.
import random
rng = random.Random(7)
SPANS = []
def new_id(nbytes):
return "".join(f"{rng.randrange(256):02x}" for _ in range(nbytes))
def start_span(name, parent=None, attrs=None):
span = {"name": name, "trace_id": parent["trace_id"] if parent else new_id(16), "span_id": new_id(8),
"parent_id": parent["span_id"] if parent else None, "attrs": attrs or {}}
SPANS.append(span)
return span
def inject(span):
"""W3C trace context: version-traceid-spanid-flags."""
return {"traceparent": f"00-{span['trace_id']}-{span['span_id']}-01"}
def extract(headers):
parts = headers.get("traceparent", "").split("-")
if len(parts) != 4:
return None
return {"trace_id": parts[1], "span_id": parts[2]}
def tool_service(headers, order_id):
"""Runs in another service. It only sees the request headers."""
parent = extract(headers)
start_span("execute_tool lookup_order", parent, {"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "lookup_order"})
return {"order_id": order_id, "status": "shipped"}
run = start_span("invoke_agent support", None, {"gen_ai.operation.name": "invoke_agent"})
start_span("chat claude-x", run, {"gen_ai.operation.name": "chat", "gen_ai.request.model": "claude-x",
"gen_ai.usage.input_tokens": 2310, "gen_ai.usage.output_tokens": 180})
tool_service(inject(run), "1120")
for s in SPANS:
print(f"{s['trace_id'][:8]} {s['name']:<28} parent={s['parent_id'] or '-'} {s['attrs'].get('gen_ai.operation.name')}")
print("traces:", len({s["trace_id"] for s in SPANS}))