Python AI agent tracing can build a parent-child execution timeline by recording each operation as a span and linking nested spans to their parent. The resulting trace shows what ran, in what order, how long it took, and where tool calls or model requests fit within an agent run.
What a Parent-Child Trace Shows
An AI agent run is rarely one function call. It may accept a task, plan steps, call a language model, choose a tool, wait for the tool, pass its result back to the model, and produce a response. A trace represents this work as related operations rather than as a flat list of log messages.
- Trace: the collection of recorded work for one request or workflow execution.
- Span: a timed operation, such as the whole agent run, a model request, or a tool invocation.
- Parent-child relationship: a link indicating that one span was started as part of another span.
A timeline view commonly displays spans as horizontal bars on a shared time axis. A parent agent span can contain child spans for planning, model calls, and tools. The nesting helps answer both “what happened?” and “which part took the time?” A trace is not automatically a perfect record of every event: its detail depends on what the application instruments and what the tracing system collects.
How to Create the Timeline in Python
There are two practical approaches: use a tracing library with explicit parent-child spans, or use a framework’s tracing integration and export its traces to a compatible viewer. OpenTelemetry is a vendor-neutral instrumentation model often used for distributed traces. Its Python API lets code create spans and set attributes; an exporter sends the data to a collector or tracing backend. Exact setup depends on the chosen exporter and destination, so the code below focuses on the span relationships.
With an OpenTelemetry tracer available, the basic pattern is:
from opentelemetry import trace
tracer = trace.get_tracer("agent_app")
def run_agent(task):
with tracer.start_as_current_span("agent.run") as parent:
parent.set_attribute("agent.task_type", "question")
plan = make_plan(task)
result = call_tool(plan[0])
return summarize(task, result)
def call_tool(command):
with tracer.start_as_current_span("tool.call"):
return execute(command)
When a span is current, a span started within its context is normally associated with that parent. The agent span therefore acts as the parent, and the tool span becomes its descendant. Add similar spans around model requests, planning, retrieval, and other meaningful boundaries. For asynchronous Python code, use the library’s context-aware instrumentation and keep work inside the relevant span context; context propagation across threads, queues, or separate services may need explicit support.
To see a timeline, configure a span processor and exporter, then inspect the exported trace in a backend that supports hierarchical traces. Creating spans alone does not guarantee a visible chart: spans must be recorded, exported, received, and displayed. Follow the documentation for the selected OpenTelemetry SDK, exporter, collector, and backend rather than assuming a particular endpoint or configuration works everywhere.
Choose Useful Span Boundaries and Attributes
Make spans correspond to operations a developer might investigate. A span for every tiny helper function can overwhelm the view, while one span for the entire run hides the cause of delays. A useful starting structure is:
agent.runas the top-level operation.agent.planfor planning or routing.model.requestfor each model interaction.tool.callfor each tool execution, with the tool category recorded as an attribute.agent.finalizefor assembling the final answer, if that work is substantial.
Attributes add searchable context, such as a workflow name, tool type, attempt number, or outcome. Prefer stable, low-cardinality values: a tool name like search is generally more useful for grouping than a unique task ID. Put unique identifiers in trace or span context where appropriate, not in attributes intended for aggregation.
Record errors through the tracing API’s supported exception or status mechanisms, and include a clear outcome when a call fails or is cancelled. A failed child span can then be located within the parent workflow. Avoid treating an error message as a substitute for structured status and exception recording.
Keep Trace Data Safe and Manageable
Agent traces can capture sensitive material if prompts, tool arguments, or returned documents are recorded. Do not attach entire prompts, credentials, personal data, or confidential tool output by default. Prefer redacted summaries, categories, lengths, and status fields. Apply access controls and retention rules at the tracing destination, and check what automatic instrumentation records before enabling it in a production environment.
Tracing also has a cost in storage, network traffic, and runtime work. Sampling can reduce volume, but may omit individual runs; choose a policy that still captures the failures and slow paths you need to investigate. Keep high-volume or large payload data out of span attributes. Avoid logging the same full content in both application logs and traces without a clear need.
Common Timeline Problems
- Every span appears as a root: the child was started outside the parent’s active context, context was lost across an async or service boundary, or the backend did not receive the parent identifier.
- Nothing appears in the viewer: check that spans are sampled and ended, a processor and exporter are configured, and the collector or destination is reachable.
- Durations look wrong: verify spans use the tracing SDK’s timing, and remember that concurrent child spans can overlap. Their durations do not necessarily add up to the parent’s duration.
- The trace is hard to read: reduce low-value spans, use consistent names, and add a small set of useful attributes.
- Tool work is missing: instrument the tool wrapper or service itself. A parent agent span cannot show internal work that was never recorded or propagated.
A trace also differs from a log. Logs are individual records, while spans describe timed operations and their relationships. They complement one another: a span can link to relevant logs, and logs can include trace context, but neither format automatically replaces the other.
Framework Instrumentation or Manual Spans?
Framework integrations can save time by creating spans around common agent actions, such as model calls and tool executions. Their coverage and attribute conventions vary, so inspect the emitted trace and confirm that the parent-child relationships match the application’s actual control flow. Manual spans provide precise boundaries and work well for custom orchestration, but require consistent instrumentation and maintenance.
A combined approach is often effective: use supported framework instrumentation for standard operations, then add a small number of manual spans around application-specific stages. Avoid wrapping the same operation twice unless the extra nesting provides useful information. For a small script, basic structured logging may be enough; choose tracing when understanding timing, nested work, or cross-service execution matters.
Frequently Asked Questions
Can Python tracing show a complete AI agent run?
It can show all work that has been instrumented and successfully exported. Uninstrumented library internals, external services without context propagation, and unsampled runs may not appear.
Does a child span have to finish before its parent?
In a well-formed trace, a parent operation usually encloses the work it starts. Concurrent tasks can overlap, but the parent should remain active for the relevant work and the tracing system must preserve context correctly.
Why does my tool call show as a separate trace?
The tool may be running in a separate process or service without trace context propagation, or its span may have been created without the current parent context. Check instrumentation and propagation at that boundary.
Should prompts and tool outputs go into spans?
Not by default. They may contain sensitive information and can create large traces. Record only what is necessary, redact carefully, and verify destination access and retention settings.
Can traces tell me exactly why an agent made a decision?
They can show recorded inputs, operations, timing, and outcomes, but they do not prove the model’s internal reasoning. Use concise, safe application events to explain observable decisions rather than treating a timeline as a complete account of model internals.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Secure Boot Battlefield 6 ASUS: Fix & Enable Guide
- Best Tech Websites to Follow for Pros & Beginners
- Second Wind Quest Walkthrough: Where Winds Meet6.00 min/km
- Enshrouded Weapon Upgrade Guide: How to Improve Gear5.00 min/km
- Connect Phone to Controller for Cloud Gaming
- Python Search Highlighting: Snippets & Matches