Agent Tracing and OpenTelemetry
A trace turns "the agent did something odd" into an ordered, timed record you can inspect.
Give every run a trace with nested spans for agent invocations, model calls, retrievals, tool calls and approvals. Use OpenTelemetry so data can move between tools, propagate context across agents and services, follow the GenAI naming conventions while pinning versions, and record message content only by deliberate choice.
What you will learn: traces, spans, events and links, a span hierarchy for single and multi-agent systems, context propagation, the GenAI conventions, a collector pipeline and how to choose tracing tools.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and What to Measure: Metrics, Dashboards and SLOs.
The Python example ran in November 2026 with Python 3.13 and opentelemetry-sdk==1.45.0. The GenAI semantic conventions were marked Development and may change. The collector configuration is an illustration that was not run.
Runs, traces, spans and events
| Term | Meaning | Agent example |
|---|---|---|
| Run | One execution of a task, in your product's language | "Resolve this ticket" |
| Trace | All the connected work for one operation, sharing a trace ID | The run across agent, tools and services |
| Span | One timed step with a name, parent, attributes and status | A tool call |
| Event | Something that happened at a moment | A guardrail blocked a call |
| Attribute | A named value on a span or event | Model name, token count |
| Link | A reference to another trace or span that is not a parent | A batch job that serves many requests |
| Resource | What produced the data | Service name, version, environment |
A run and a trace are often one to one, but not always. A task that waits two days for approval is better recorded as several traces that share a run ID and link to each other.
What a good trace looks like
Create a span when a step can fail on its own, takes meaningful time, costs money, crosses a boundary or changes something. A span for every small function adds noise.
Why OpenTelemetry?
OpenTelemetry is an open, vendor-neutral project for generating and transporting traces, metrics and logs. Your code uses its API, an SDK processes the data and an exporter sends it, usually with the OpenTelemetry Protocol (OTLP), to a collector or a backend. Changing backend then means changing configuration more than code.
GenAI semantic conventions
Semantic conventions are agreed names, so that tools can understand your data. In June 2026 the generative AI conventions moved into their own repository. Everything shown below was in Development status when checked.
| Operation name | Span name pattern | Notes from the conventions |
|---|---|---|
invoke_agent | invoke_agent {agent name} | In-process span kind is internal; a separate client span covers calls to remote agents |
invoke_workflow | invoke_workflow {name} | When the application, not the model, defines the control flow |
create_agent | create_agent {agent name} | Mostly for remote agent services; client span |
plan | plan {agent name} | A planning phase; internal span |
chat | chat {model} | A model request |
execute_tool | execute_tool {tool name} | One tool execution |
retrieval | retrieval {data source} | A search step |
| Attribute | Holds |
|---|---|
gen_ai.agent.name, gen_ai.agent.version | Which agent and release |
gen_ai.conversation.id | Conversation, when an identifier is available |
gen_ai.provider.name | Provider |
gen_ai.request.model | Requested model |
gen_ai.usage.input_tokens, gen_ai.usage.output_tokens | Token counts |
gen_ai.tool.name, gen_ai.tool.call.id | Tool and call identity |
error.type | Class of failure |
gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions | Content: opt-in, because it may be sensitive |
Put your own fields under your own prefix, such as app.policy.decision or app.run.id, so they never collide with future standard names. Pin the instrumentation version, and test that dashboards still work before upgrading.
A runnable example
The program records a support run that hands work to a billing worker. The handoff passes only a message with headers, as a queue would, and the worker runs after the first span has ended. inject writes the trace context into the headers and extract reads it on the other side.
"""Nested agent spans, with the trace carried across a handoff."""
from opentelemetry import trace
from opentelemetry.propagate import extract, inject
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import SpanKind, Status, StatusCode
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("demo-agent", "1.0.0")
def step(operation, target, kind=SpanKind.INTERNAL, **attrs):
"""Start a span named '<operation> <target>' with GenAI attributes."""
span_attrs = {"gen_ai.operation.name": operation, **attrs}
return tracer.start_as_current_span(f"{operation} {target}", kind=kind,
attributes=span_attrs)
def billing_worker(message):
"""Runs elsewhere: it only receives the message and its headers."""
context = extract(message["headers"])
with tracer.start_as_current_span("invoke_agent billing", context=context,
attributes={"gen_ai.operation.name": "invoke_agent",
"gen_ai.agent.name": "billing"}):
with step("execute_tool", "invoice.read",
**{"gen_ai.tool.name": "invoice.read"}) as span:
span.set_attribute("error.type", "timeout")
span.set_status(Status(StatusCode.ERROR, "timeout"))
with step("invoke_agent", "support",
**{"gen_ai.agent.name": "support", "app.agent.version": "2.4.0"}):
with step("plan", "support", **{"gen_ai.agent.name": "support"}):
with step("chat", "example-model", SpanKind.CLIENT,
**{"gen_ai.request.model": "example-model",
"gen_ai.usage.input_tokens": 820,
"gen_ai.usage.output_tokens": 96}):
pass
with step("execute_tool", "order.read", **{"gen_ai.tool.name": "order.read"}):
pass
headers = {}
inject(headers) # writes the W3C traceparent header
message = {"headers": headers, "task": "check invoice"}
billing_worker(message) # later, outside the first agent's context
spans = sorted(exporter.get_finished_spans(), key=lambda s: s.start_time)
by_parent = {}
for s in spans:
by_parent.setdefault(s.parent.span_id if s.parent else None, []).append(s)
def show(parent=None, depth=0):
for s in by_parent.get(parent, []):
error = s.attributes.get("error.type")
print(" " * depth + f"{s.name} [{s.kind.name}]" + (f" error={error}" if error else ""))
show(s.context.span_id, depth + 1)
show()
print("Traces:", len({s.context.trace_id for s in spans}), "| spans:", len(spans))
version, trace_id, parent_id, flags = headers["traceparent"].split("-")
print("traceparent parts:", len(version), len(trace_id), len(parent_id), len(flags))
Output:
invoke_agent support [INTERNAL]
plan support [INTERNAL]
chat example-model [CLIENT]
execute_tool order.read [INTERNAL]
invoke_agent billing [INTERNAL]
execute_tool invoice.read [INTERNAL] error=timeout
Traces: 1 | spans: 6
traceparent parts: 2 32 16 2
Six spans form one trace even though the worker received nothing but text headers. The traceparent header from the W3C Trace Context standard carries a version, a 32-character trace ID, a 16-character parent span ID and flags. The failing tool is visible at the exact level where it happened.
Remove the context=context argument and run again. The billing spans start a new, unconnected trace, which is the most common fault in multi-agent tracing.
Propagation across boundaries
| Boundary | How to carry context |
|---|---|
| HTTP or gRPC call | Standard headers, usually added by instrumentation |
| Message queue | Message headers; consider a link instead of a parent for delayed work |
| Threads and async tasks | Make sure the current context follows the task |
| MCP tool server | Follow the MCP conventions your libraries support, and test that the server joins the trace |
| Remote agent (A2A or other) | Send context if the other side is trusted to receive it; record your client span either way |
| Long pause for a person | Save the run ID and context with the state; link the resumed trace |
Do not accept trace context, or "baggage" values carried with it, as proof of identity or permission. Outside callers can send anything. Do not put personal data or secrets in baggage, which travels to every downstream service. Decide at your edge whether to continue an incoming trace or start a new one with a link.
Multi-agent hierarchies
- Supervisor and workers: worker invocations are children of the supervisor's span; parallel workers appear as overlapping siblings.
- Handoff: record who handed what to whom, with the reason and a hash or identifier of the state passed (Handoffs, Routing, Shared State and Communication).
- Debate or group chat: add a round number so repeated turns are distinguishable.
- Fan-in: a step that combines several branches can link to all of them.
- Background work: give it its own trace linked to the request that caused it.
Record on every agent span its name, version, the user or service it acts for as a pseudonymous identifier, the delegation depth and the stop reason. With those, you can find all runs where depth exceeded two, or where one version ended on a step limit.
Traces, metrics and logs together
Each signal answers a different question, and they work best when they share identifiers.
| Signal | Answers | Agent use |
|---|---|---|
| Metrics | How often, how much, how slow? | Success rate, tokens, cost, tool errors, alerts |
| Traces | What happened in this run? | Order, timing and parentage of steps |
| Logs and events | What was said at this moment? | Policy decisions, warnings, exceptions |
Write the trace ID into application logs, and link dashboards to example traces. Then an alert leads to affected runs in two clicks. Keep high-cardinality values such as run or user identifiers on spans and out of metric labels, where each new value creates a new time series.
Design attributes for the questions you ask
| Question | Attributes needed |
|---|---|
| Which release got worse? | Agent version, model, index or data version |
| Which tool is failing for whom? | Tool name, error type, tenant identifier |
| Why did runs end early? | Stop reason, step count, budget used |
| What did policy block? | Rule identifier, decision, tool |
| Where did time go? | Complete child spans, queue and approval waits |
| What did this answer rely on? | Document identifiers and versions from retrieval |
Write the questions first, then check that a sample trace can answer each one. Fields that serve no question are cost and risk without benefit. Keep names and units consistent across teams, and publish a short attribute dictionary that code review can check.
Automatic and manual instrumentation
Instrumentation libraries can create spans for model clients, HTTP calls and some frameworks with little code. They do not know your business steps, policy decisions or outcome. Start with automatic spans, then add manual spans for agent invocations, tools, approvals and handoffs. Check for duplicates when a framework and a client library both instrument the same call, since doubled spans inflate token totals.
A collector pipeline
A collector sits between applications and storage. It is a good place to drop fields, sample and route, so that every service follows the same rules. This illustrative configuration shows the shape.
receivers:
otlp:
protocols:
grpc: {endpoint: "0.0.0.0:4317"} # restrict with network rules and TLS
processors:
memory_limiter: {check_interval: 1s, limit_mib: 512}
attributes/drop_content:
actions:
- {key: gen_ai.input.messages, action: delete}
- {key: gen_ai.output.messages, action: delete}
- {key: gen_ai.system_instructions, action: delete}
batch: {}
exporters:
otlphttp: {endpoint: "https://telemetry.example.internal"}
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/drop_content, batch]
exporters: [otlphttp]
Content can also appear in events, logs and other attribute names, so a short deny list is not enough. Prefer not capturing it, and see Safe Logging, Sampling and Retention for allow lists. Check which components your collector distribution includes.
Check your instrumentation
Treat telemetry as a feature with tests. An in-memory exporter, as above, lets a unit test assert that:
- one run produces one trace with a single root;
- every tool call has a span with a name and status;
- failures set an error type;
- no content attribute appears when capture is off;
- context survives the queue and the remote call.
In production, watch for dropped spans, exporter errors and traces with missing parents. Export should be asynchronous, and an unavailable backend should not stop the agent. Records that must never be lost, such as approvals, belong in a durable audit store, not only in sampled traces (Transparency, Accountability and Audit Evidence). The Lab: Evaluation Harness and Tracing lab practices this end to end.
Open-source tools and platforms
| Kind | Examples | Strength | Watch for |
|---|---|---|---|
| Collection | OpenTelemetry Collector | Vendor-neutral processing and routing | You operate it |
| General tracing | Jaeger, Grafana Tempo | Service-wide traces | Little built-in evaluation of model quality |
| Metrics and dashboards | Prometheus, Grafana | Alerting and long-term trends | Not a trace store by itself |
| LLM-focused tools | Langfuse, Arize Phoenix, MLflow Tracing | Prompt views, datasets and scoring | Differing support for the conventions and differing licenses |
| Commercial observability suites | Many vendors | Managed operation and broad integration | Cost by volume and data location |
Product features change quickly, so compare against your own needs rather than a list. License terms vary too: some projects use permissive licenses, while others are source-available with limits on hosting them as a service.
Questions for a trial
- Does it accept OTLP and understand current GenAI names?
- Can it show a deep multi-agent trace clearly and search by your attributes?
- Can you redact before data leaves your network?
- Who can see content, and is access logged?
- Can you set retention by type and delete on request?
- Can failed runs become evaluation cases?
- What does your real volume cost, and how do you export your data?
Common mistakes
| Mistake | Better approach |
|---|---|
| One log line per run | Nested spans for each meaningful step |
| Lost context at queues and handoffs | Inject and extract, then test it |
| IDs or user text in span names | Keep names low-cardinality; put detail in attributes |
| Capturing all content by default | Opt in for specific needs with controls |
| Marking handled failures as success | Record error type and final outcome separately |
| Upgrading conventions blindly | Pin, test dashboards, then upgrade |
Tracing checklist
- Each run has an identifier that users and support can quote.
- Agent, model, retrieval, tool and approval steps are spans.
- Context crosses every service and agent boundary you control.
- Agent version and stop reason are recorded.
- Content capture is off unless deliberately enabled.
- Instrumentation has automated tests.
- Export failures do not break the agent.
- Convention and library versions are pinned.
Frequently asked questions
Do I need OpenTelemetry if my framework has its own tracing?
Not strictly, but check whether it can export OpenTelemetry data so agent traces can join those of your other services.
Should the model's reasoning be a span?
Record the planning step and its timing, and treat any generated reasoning text as optional, sensitive content.
How much does tracing slow an agent?
Asynchronous export usually adds little compared with model calls, but measure it in your own system.
Are the GenAI conventions stable?
They were marked as in development when this page was written, so expect changes and pin versions.
References and further reading
- OpenTelemetry: traces: spans, context and links.
- GenAI semantic conventions: the current definitions.
- GenAI observability with OpenTelemetry: an official walk-through.
- W3C Trace Context: the traceparent header.
- OpenTelemetry Collector: pipelines and components.
Next steps
Safe Logging, Sampling and Retention
Decide what to keep and for how long.
Debugging Agents, RAG and Handoffs
Use traces to find causes.
Tool Testing and Observability
Instrument tools in detail.