Agent Tracing and OpenTelemetry

A trace turns "the agent did something odd" into an ordered, timed record you can inspect.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Versions used

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.

Beginner The building blocks

Runs, traces, spans and events

TermMeaningAgent example
RunOne execution of a task, in your product's language"Resolve this ticket"
TraceAll the connected work for one operation, sharing a trace IDThe run across agent, tools and services
SpanOne timed step with a name, parent, attributes and statusA tool call
EventSomething that happened at a momentA guardrail blocked a call
AttributeA named value on a span or eventModel name, token count
LinkA reference to another trace or span that is not a parentA batch job that serves many requests
ResourceWhat produced the dataService 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

invoke_agent supportthe whole run
plan, chatdecide what to do
execute_tool order.readtimed, with status
invoke_agent billingchild run in another service
execute_tool invoice.readfailed: timeout
The boxes run in time order. A trace viewer indents each child under its parent.

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.

Intermediate Instrumenting agents

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.

Agent codeAPI and SDK
OTLPstandard transport
Collectorfilter, redact, sample
Backendstraces, metrics, logs

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 nameSpan name patternNotes from the conventions
invoke_agentinvoke_agent {agent name}In-process span kind is internal; a separate client span covers calls to remote agents
invoke_workflowinvoke_workflow {name}When the application, not the model, defines the control flow
create_agentcreate_agent {agent name}Mostly for remote agent services; client span
planplan {agent name}A planning phase; internal span
chatchat {model}A model request
execute_toolexecute_tool {tool name}One tool execution
retrievalretrieval {data source}A search step
AttributeHolds
gen_ai.agent.name, gen_ai.agent.versionWhich agent and release
gen_ai.conversation.idConversation, when an identifier is available
gen_ai.provider.nameProvider
gen_ai.request.modelRequested model
gen_ai.usage.input_tokens, gen_ai.usage.output_tokensToken counts
gen_ai.tool.name, gen_ai.tool.call.idTool and call identity
error.typeClass of failure
gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructionsContent: 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.

Try breaking it

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.

Expert Hierarchies, pipelines and tools

Propagation across boundaries

BoundaryHow to carry context
HTTP or gRPC callStandard headers, usually added by instrumentation
Message queueMessage headers; consider a link instead of a parent for delayed work
Threads and async tasksMake sure the current context follows the task
MCP tool serverFollow 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 personSave the run ID and context with the state; link the resumed trace
Trust boundaries

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.

SignalAnswersAgent use
MetricsHow often, how much, how slow?Success rate, tokens, cost, tool errors, alerts
TracesWhat happened in this run?Order, timing and parentage of steps
Logs and eventsWhat 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

QuestionAttributes 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

KindExamplesStrengthWatch for
CollectionOpenTelemetry CollectorVendor-neutral processing and routingYou operate it
General tracingJaeger, Grafana TempoService-wide tracesLittle built-in evaluation of model quality
Metrics and dashboardsPrometheus, GrafanaAlerting and long-term trendsNot a trace store by itself
LLM-focused toolsLangfuse, Arize Phoenix, MLflow TracingPrompt views, datasets and scoringDiffering support for the conventions and differing licenses
Commercial observability suitesMany vendorsManaged operation and broad integrationCost 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

  1. Does it accept OTLP and understand current GenAI names?
  2. Can it show a deep multi-agent trace clearly and search by your attributes?
  3. Can you redact before data leaves your network?
  4. Who can see content, and is access logged?
  5. Can you set retention by type and delete on request?
  6. Can failed runs become evaluation cases?
  7. What does your real volume cost, and how do you export your data?

Common mistakes

MistakeBetter approach
One log line per runNested spans for each meaningful step
Lost context at queues and handoffsInject and extract, then test it
IDs or user text in span namesKeep names low-cardinality; put detail in attributes
Capturing all content by defaultOpt in for specific needs with controls
Marking handled failures as successRecord error type and final outcome separately
Upgrading conventions blindlyPin, 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

Next steps