Sub topic 10
Structuring an Agent Run as a Trace
This chapter assumes you can write Python context managers and have a tracer provider configured, as covered in the SDK setup chapter. It also assumes you know what spans, attributes and parent-child context are. Here you will decide what the span tree for one agent run should look like, and then build it.
Why structure matters
An agent run is not a single call. It is a loop. The agent asks a model what to do, runs a tool, feeds the result back, and repeats until it can answer. If every model call and tool call becomes an unrelated trace, you cannot answer basic questions. Which user request caused this call? How many iterations did the run take? Which step was slow?
The fix is to make the whole run one trace with a single root span. Every model call, tool call and retrieval step becomes a descendant of that root. One trace ID then identifies one agent run.
The shape of the tree
A useful agent trace has three levels:
- A root span for the whole run, with operation
invoke_agent. - Optionally, one span per loop iteration, so you can see how many turns the agent took.
- Leaf spans for each model call (
chat), tool call (execute_tool) and retrieval step.
The iteration level is a design choice, not a requirement of the GenAI semantic conventions. Without it, the tree is flat: the root has many children ordered by start time. That works for short runs. For runs with many turns, the iteration span groups related work and makes a runaway loop obvious, because you see dozens of iteration spans instead of a long unlabeled list.
Naming and attributes
The GenAI semantic conventions give each span a name and a gen_ai.operation.name attribute. Use these consistently.
| Span | Name pattern | Key attributes |
|---|---|---|
| Agent run | `invoke_agent {agent name}` | `gen_ai.operation.name=invoke_agent`, `gen_ai.agent.name` |
| Model call | `chat {model}` | `gen_ai.operation.name=chat`, `gen_ai.request.model` |
| Tool call | `execute_tool {tool name}` | `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name` |
Keep span names low in cardinality. Put the agent name, model name and tool name in the name, but never user IDs, order IDs or question text. High-cardinality names make grouping and searching in a backend nearly useless. Put variable values in attributes instead.
Span kind also matters. A model call that goes over the network to a provider is SpanKind.CLIENT. The agent run itself is in-process work, so the default INTERNAL kind is a good fit for the root and iteration spans. If your agent runs as a separate service that other services call, SpanKind.SERVER or a remote-agent client span may be more accurate.
Building the tree in code
The parent-child relationship comes from context. When you use start_as_current_span, the new span becomes the current span for the duration of the with block. Any span started inside the block takes it as its parent automatically. You do not pass parents by hand.
The example below runs a small agent loop. A scripted fake model asks for a tool on the first turn and answers on the second. The code runs as shown and prints the spans to the console, so you do not need a Collector.
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
ConsoleSpanExporter,
SimpleSpanProcessor,
)
from opentelemetry.trace import SpanKind, Status, StatusCode
provider = TracerProvider(resource=Resource.create({"service.name": "support-agent"}))
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support_agent")
MAX_ITERATIONS = 5
def fake_model(history):
# Scripted stand-in for a real LLM: ask for a tool first, then answer.
if not any(m["role"] == "tool" for m in history):
return {"action": "tool", "tool": "search_orders", "args": {"customer_id": "c-42"}}
return {"action": "answer", "text": "You have one open order, A-1001."}
def search_orders(customer_id):
with tracer.start_as_current_span("execute_tool search_orders") as span:
span.set_attribute("gen_ai.operation.name", "execute_tool")
span.set_attribute("gen_ai.tool.name", "search_orders")
return [{"id": "A-1001", "customer": customer_id}]
TOOLS = {"search_orders": search_orders}
def run_agent(question):
with tracer.start_as_current_span("invoke_agent support-agent") as root:
root.set_attribute("gen_ai.operation.name", "invoke_agent")
root.set_attribute("gen_ai.agent.name", "support-agent")
history = [{"role": "user", "content": question}]
for i in range(1, MAX_ITERATIONS + 1):
with tracer.start_as_current_span("agent.iteration") as turn:
turn.set_attribute("agent.iteration", i)
with tracer.start_as_current_span(
"chat example-model", kind=SpanKind.CLIENT
) as chat:
chat.set_attribute("gen_ai.operation.name", "chat")
chat.set_attribute("gen_ai.request.model", "example-model")
decision = fake_model(history)
if decision["action"] == "answer":
root.set_attribute("agent.iterations", i)
return decision["text"]
result = TOOLS[decision["tool"]](**decision["args"])
history.append({"role": "tool", "content": str(result)})
root.set_attribute("agent.iterations", MAX_ITERATIONS)
root.set_status(Status(StatusCode.ERROR, "max iterations reached"))
return "Sorry, I could not finish."
print(run_agent("Where is my order?"))Notice three details. The agent.iteration and agent.iterations attributes are custom, so they use a namespace of your own rather than gen_ai.. The root span records the final iteration count, so you can filter for expensive runs without opening child spans. And the loop cap sets an error status on the root when it is hit, so runaway loops show up as failed traces.
Edge cases and common mistakes
- Broken parents in threads and async tasks. Context lives in a
contextvarsvariable. Code run withasynciotasks inherits it, but plainthreading.Threadand many thread pools do not. A tool run in a worker thread then starts a new root trace. Capture the context withcontext.get_current()and attach it in the worker withcontext.attach(), or usecontextvars.copy_context().run(...). - Spans that never end. If you call
start_spanwithout awithblock and forgetspan.end(), the span is never exported. Prefer the context manager. - Streaming responses. A streamed model call finishes after the function returns. Keep the span open until the stream is exhausted, or the duration will show only time to first byte.
- Parallel tool calls. When a model requests several tools at once, create sibling spans under the same parent. They overlap in time, and the trace view shows them side by side.
- Failure placement. Record an exception on the span where it happened. Set the root to
ERRORonly if the run as a whole failed. A tool that fails and is retried successfully should not mark the run as failed. - Long-lived agents. For a chat session spanning many user turns, one trace per turn is usually better than one trace per session. A trace that stays open for hours is hard to sample and view. Link turns together with a shared session attribute instead.
Checking the result
Run the example and look at the console output. Every span should carry the same trace_id. The chat and execute_tool spans should have a parent_id equal to the span_id of an agent.iteration span. The iteration spans should have the invoke_agent span as their parent. The root span has no parent. If a span shows a different trace_id, its context was lost somewhere, usually at a thread boundary.
Exercise
In the example, a developer moves search_orders into a ThreadPoolExecutor.submit call. The tool span now appears as a separate trace with its own trace ID. Why does this happen, and how do you fix it?
Show answer
The current span is stored in context variables, and a worker thread started by the pool does not inherit the caller's context. With no active parent, the tool span becomes a new root. Fix it by capturing the context before submitting, for example ctx = contextvars.copycontext(), and running the function with ctx.run(searchorders, customerid) inside the worker. You can also use opentelemetry.context.getcurrent() and attach it in the worker, detaching it in a finally block.
Exercise
Why does the example set the root span to ERROR when the iteration cap is reached, and why is a retried tool failure treated differently?
Show answer
Hitting the cap means the run did not produce an answer, so the run as a whole failed and the root should show that. A tool failure that a retry recovers from does not change the run's outcome. The exception belongs on the failed tool span, while the root stays unset or OK.