You ask an internal assistant a question and wait almost four seconds for the answer. The backend log gives you that same single number and nothing else. Open the trace for the same request, and you see that the document-search tool took 2.42 seconds. Now you have a specific place to start.
This article explains what a trace is, how to read one for an AI agent, and how to produce one yourself with a short Python script. You only need basic Python and a terminal.
What a trace is, in plain words
Think of ordering food for delivery. The app says “40 minutes”, but you want to know where the time went. Was the restaurant slow to cook? Did the courier wait outside? Was the road blocked? A receipt with a time stamp for each stage would answer that.
A trace is that receipt for one request in your software. It records every step the request went through, when each step started and how long it took.
Each step in a trace is a span. A span has a name, a start time, an end time and a parent. The parent is the step that called it. Spans nest, so a trace looks like a tree.
A span can also carry attributes. An attribute is a key-value pair with extra facts, such as which model was called or how many tokens it used.
OpenTelemetry (often shortened to OTel) is an open-source project that defines how to create traces and send them to monitoring tools. Because it is a shared standard, the same trace can be viewed in many different backends.
Why an AI agent needs a trace
An AI agent is a program that calls a language model, lets the model choose a tool (a function your code exposes, such as “search the docs”), runs that tool, and then calls the model again with the result. One user question can therefore turn into several model calls and several tool calls.
If you only log the total time, you cannot tell which of these steps is slow. You might spend a day tuning prompts when the real delay is a search service that retries after a timeout.
OpenTelemetry has semantic conventions for this. Semantic conventions are agreed names for spans and attributes, so that every tool and library labels the same thing the same way. The GenAI conventions describe an agent run like this:
- an
invoke_agentspan for the whole agent run; - a
chatspan for each call to the model; - an
execute_toolspan for each tool call.
OpenTelemetry’s GenAI observability walkthrough shows this structure with a top-level invoke_agent span and child spans for each model and tool call.
Read the trace in the order things ran
In our example, the agent calls the model to build a search query, runs a document-search tool, and calls the model again to write the answer. The durations below are illustrative. They were not measured on a real system.
invoke_agent document_assistant 3800 ms
├─ chat 620 ms
├─ execute_tool search_docs 2420 ms
└─ chat 710 ms
Read it from top to bottom. The whole run took 3.8 seconds. Document search took 2.42 of those seconds. The two model calls together took about 1.3 seconds.
So the next measurement belongs inside search_docs. If that span records only a total, add child spans (spans whose parent is search_docs) for the index query and for fetching the documents. Also record when each retry happens.
You may then find that the query itself takes a few hundred milliseconds. Most of the time could be a wait after a failed call. In that case, look at the first failure and the delay between attempts.
Shortening the model’s answer would mostly affect the final chat span. It would not fix the search delay.
When tools run in parallel
Some agents run several tools at the same time. Then you cannot simply add the durations. Two spans that each last two seconds can overlap for the full two seconds, so the user waits two seconds, not four.
Look at the start and end times on the timeline instead. If the agent needs every result before it can answer, start with the tool that finishes last.
Emit the spans yourself
Some agent frameworks already create these spans for you through an instrumentation library, which is code that records telemetry automatically. If yours does not, you can create the spans by hand with the OpenTelemetry SDK. The SDK (software development kit) is the library that actually builds spans and passes them on.
The SDK hands finished spans to an exporter. An exporter decides where spans go. In this example, it prints them to the console. In production, you would usually send them to a collector, a separate OpenTelemetry service that receives telemetry and forwards it to your monitoring backend.
The script below uses stand-ins instead of a real model and a real search service. Each stand-in just sleeps (time.sleep) and uses fixed token counts. This lets you run it without an API key. In a real agent, take the token counts from the provider’s response.
Step 1: create a virtual environment
Run this in a terminal, in an empty folder:
python3 -m venv .venv
This creates a .venv folder with its own Python, so the packages you install do not affect the rest of your system. Nothing is printed when it succeeds.
Step 2: install the SDK
.venv/bin/pip install opentelemetry-sdk
This installs opentelemetry-sdk and its dependency opentelemetry-api. On Windows, the path is .venv\Scripts\pip instead of .venv/bin/pip.
Step 3: save the script
Save this as trace_agent.py in the same folder:
import time
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, ConsoleSpanExporter
from opentelemetry.trace import SpanKind
def one_line(span):
ms = (span.end_time - span.start_time) / 1e6
attrs = {k: v for k, v in span.attributes.items() if k.startswith("gen_ai.")}
return f"{span.name:<28} {ms:6.0f} ms {attrs}\n"
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter(formatter=one_line)))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("document-assistant")
def chat(model, input_tokens, output_tokens, seconds):
# Stand-in for the real model call; record the counts the provider returns.
with tracer.start_as_current_span(f"chat {model}", kind=SpanKind.CLIENT) as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.provider.name", "openai")
span.set_attribute("gen_ai.request.model", model)
time.sleep(seconds)
span.set_attribute("gen_ai.usage.input_tokens", input_tokens)
span.set_attribute("gen_ai.usage.output_tokens", output_tokens)
def search_docs(call_id, query):
with tracer.start_as_current_span("execute_tool search_docs") as span:
span.set_attribute("gen_ai.operation.name", "execute_tool")
span.set_attribute("gen_ai.tool.name", "search_docs")
span.set_attribute("gen_ai.tool.call.id", call_id) # id supplied by the model
# The query string stays out of the span unless content capture is enabled.
time.sleep(0.3)
return ["doc-17", "doc-42"]
with tracer.start_as_current_span("invoke_agent document_assistant") as agent:
agent.set_attribute("gen_ai.operation.name", "invoke_agent")
agent.set_attribute("gen_ai.agent.name", "document_assistant")
chat("example-model", 812, 46, 0.1)
search_docs("call_01", "VPN setup for contractors")
chat("example-model", 2140, 180, 0.15)
What the parts do:
TracerProvideris the central object that creates tracers and holds the export setup.SimpleSpanProcessorpasses each span to the exporter as soon as the span ends.ConsoleSpanExporter(formatter=one_line)prints each span. The smallone_linefunction keeps only the span name, the duration and thegen_ai.*attributes, so the output fits on one line.- Each
with tracer.start_as_current_span(...)block is one span. A span opened inside another block becomes its child.
Step 4: run it
.venv/bin/python trace_agent.py
Run with opentelemetry-sdk 1.45.2 on Python 3.13, it printed:
chat example-model 105 ms {'gen_ai.operation.name': 'chat', 'gen_ai.provider.name': 'openai', 'gen_ai.request.model': 'example-model', 'gen_ai.usage.input_tokens': 812, 'gen_ai.usage.output_tokens': 46}
execute_tool search_docs 305 ms {'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': 'search_docs', 'gen_ai.tool.call.id': 'call_01'}
chat example-model 154 ms {'gen_ai.operation.name': 'chat', 'gen_ai.provider.name': 'openai', 'gen_ai.request.model': 'example-model', 'gen_ai.usage.input_tokens': 2140, 'gen_ai.usage.output_tokens': 180}
invoke_agent document_assistant 565 ms {'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': 'document_assistant'}
Your milliseconds will differ slightly, because time.sleep is not exact.
Step 5: read the output
Child spans end before their parent, so the invoke_agent span prints last. Its 565 ms covers the three steps inside it.
The names and kinds follow the conventions. invoke_agent {gen_ai.agent.name} and execute_tool {gen_ai.tool.name} are INTERNAL spans, meaning work done inside your process. chat {gen_ai.request.model} is a CLIENT span, meaning a call out to another service.
gen_ai.tool.call.id is the identifier the model gives a tool call. Set it only when the model or provider actually supplied one.
To send spans to a local collector instead of the console, replace the console exporter with an OTLP exporter. OTLP is the OpenTelemetry Protocol, the standard format collectors accept.
The GenAI attributes are still marked Development, so names can change between releases. Agent spans, execute_tool spans, inference spans
Keep content out unless you opt in
To investigate the slow search, you need the tool name, the call id, the outcome, the number of attempts and the duration. For model calls, the model name and the token counts reported by the provider help you compare runs. You do not need the text of the prompt.
The conventions treat prompts, model outputs and tool inputs and outputs as sensitive. These attributes are Opt-In, and instrumentations should not record them by default:
gen_ai.input.messagesandgen_ai.output.messages;gen_ai.system_instructions;gen_ai.tool.call.argumentsandgen_ai.tool.call.result.
When an instrumentation offers an environment variable to turn this on, the variable must be named OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT. Its values are NO_CONTENT (the default), SPAN_ONLY, EVENT_ONLY and SPAN_AND_EVENT. Check that your instrumentation supports it before relying on the name. Turn content on only where your monitoring backend is approved to hold that data. Content capture configuration
If the final chat span produces structured output that your code then validates, a rejected answer and its retry show up as extra chat spans in the same trace. Validating LLM output after it passes the JSON Schema covers that step. If search_docs runs on a remote MCP server, what stateless MCP changes for server deployment covers the server side.
Common mistakes
- Adding up parallel spans. Overlapping spans do not add up. Read start and end times on the timeline.
- Putting prompts or documents in attributes “just for debugging”. That sends internal data to the monitoring system. Use the opt-in switch on purpose, not by accident.
- Inventing a tool call id. If the model did not supply one, leave
gen_ai.tool.call.idunset. - Comparing different workloads. A faster p95 on easier questions proves nothing. The p95 is the duration that 95% of requests stay under.
- Treating attribute names as permanent. They are still in Development. Check the conventions when you upgrade.
- Keeping the console exporter in a real service. It is for learning and local tests. Send spans to a collector or backend instead.
Check the telemetry and compare releases
Before trusting dashboards built on these spans, check that the attributes match the conventions.
OpenTelemetry’s post on agent-generated GenAI instrumentation describes Weaver’s weaver registry live-check. Weaver is an OpenTelemetry tool for working with semantic conventions. Live-check starts an OTLP listener, receives telemetry from a running instrumentation and compares it with the semantic-convention registry. It exits with a non-zero code when it finds a violation, such as a missing attribute or a wrong type. OpenTelemetry on agent-generated instrumentation and live-check
After a fix, rerun the same set of questions. Compare the p95 of search_docs with the p95 of the whole request, before and after the change. If the tool gets faster and users still wait, open a slow trace to see which step now takes the time.
Conclusion
A trace with invoke_agent, chat and execute_tool spans shows whether time goes to the model or to a tool. Add detail only inside the span you are investigating. Record names, ids, durations and token counts by default, and keep message content behind the explicit opt-in. Check the spans against the conventions, and compare the same workload before and after each change.