Most teams we talk to already trace their agents and spend hundreds or thousands of dollars a month on tools like Langfuse, LangSmith, or Braintrust, but get little value from their traces.
For most companies, trace storage has become an endless bucket of long, badly formed JSONs, with way too much information to make sense of. Most teams never read their traces and don't use them for much beyond playing bug whack-a-mole when someone complains: asking Claude to "investigate" and hoping the fix worked.
We talk about recursive loops, AGI, self-healing workflows. But the first blocker to improving your AI system is accepting that your traces are probably shit, and that if you can't make sense of them, an LLM judge won't either.
This guide tells you how to fix that, so your traces actually help you improve your agents.
TL;DR of what your traces should have to be useful:
- One task per trace, with every step nested under one root span, the IDs that connect it to the traces before and after it, and the metadata you will filter by (customer, user, environment).
- Each model call's full prompt and response, with the model and token counts, and the instructions the agent ran with, as text.
- Every tool call's input and output, including empty results and failures.
- For retrieval, every chunk returned in full, which ones were kept, and the final prompt.
- The agent's final answer, as structured fields.
- Which version produced it: the commit, whether the code had uncommitted changes, and a hash of each prompt.
- Any feedback or user signals.
1. How to structure your traces
1.1 Give each task its own trace
One trace should hold one thing your agent did: answer a question, write a report, handle a ticket, make a code change.
In a chat, that means one trace per message: the user's message and everything the agent did to reply. The whole conversation is linked through session.id (see 1.3), not crammed into a single trace.
The classic mistake is the opposite: tracing a whole batch job as one trace. Your nightly job processes 200 tickets and you get one giant trace with 200 answers in it. Good luck finding the one a customer complained about, or getting a judge to grade it. Start a new trace per ticket and tag it with the batch it came from.
1.2 Put every step of that task under the same root span
The opposite mistake is a trace that's too small: each model call sent as its own trace. That's what most telemetry setups do out of the box: they record every call to the model, but not the searches, tool calls and other steps around it.
Every model call, search and tool call the agent makes for a task should sit under one root span instead. Otherwise one report becomes a dozen loose traces, each holding just a prompt and a response. You can't see which search fed which prompt, and when the final answer is wrong, the real mistake is usually a few steps earlier, in a trace nobody opens.
The fix: open a root span when the task starts and run the work inside its context, so the model calls your telemetry already records attach to it. If the work moves to a background job or another service, pass the trace context along (the W3C traceparent header) so those steps join the same trace.
1.3 Record the ids that connect traces to each other
Tag every trace with the ids of what it belongs to: the conversation, report, ticket or workflow run.
A task is often wrong because of something that happened earlier. Your agent gets a work-permit question wrong, but the real mistake was two turns back, when it misread the traveler's nationality. With the turns connected, you can open the traces before and after the one you're looking at, in order.
Put the broadest id, usually the conversation or workflow run, in session.id. Most tracing tools use it to group traces into a sequence. Add the others as your own attributes. Use the ids your system already has, not something built from the data, so the same thing always gets the same id.
If the work is still the same task, keep it in the same trace (1.2). If it's a new task, such as a workflow step handing its result to the next, start a new trace and add an OpenTelemetry span link from it to the one that started it. Then you can follow the chain from either end, even across services.
1.4 Tag each trace with the metadata you will filter by
Most questions you'll ask aren't about one trace. Is it worse for one customer? Did it break after Tuesday's deploy? Are test runs polluting production numbers? Each needs a field to filter on, and you can't add one to old traces after the fact.
Start with these, then add your own:
| What it records | Example attribute | Why you want it |
|---|---|---|
| The conversation or workflow it belongs to | session.id = trip-4812 |
Open the traces that came before and after it, in order |
| Your own ids for what it worked on | app.report_id = rpt_2291 |
Find every attempt at the same report, ticket or booking |
| Which agent produced it | service.name = travel-assistant |
Keep agents apart when several send to the same place |
| Where it ran | deployment.environment.name = production |
Keep staging and test runs out of production numbers |
| Which code version ran | service.version = 3f9c2e1… (the commit) |
Split traces into before and after a change |
| Which prompt version ran | app.prompt_hash = a1b2c3d4e5f6 |
Catch prompt changes that shipped without a deploy |
| The customer or account | app.customer_id = northwind |
See whether one customer gets worse answers than the rest |
| The user | user.id = u_8841 |
Follow up on a bad answer, and count distinct people affected |
Fields that are the same for a whole deployment (service, version, environment) go on the OpenTelemetry resource, so every span gets them. Fields about the task (customer, user) go on the root span of every trace about it, including retries and feedback.
The fields that matter most are usually specific to your product: the kind of request, the template or workflow that ran, the customer's plan, the language of the conversation. Ask which groups you'd compare if your error rate went up, and record a field for each. They cost almost nothing to send.
1.5 Put the request and answer on the root, and the detail on each step
The root span holds what came in and what went out. Each child span holds the full detail of its own step.
Most tracing tools show a trace's input and output from its root. Leave the root empty and the trace looks empty in your list, even when every step inside is full.
Put big content on the step that produced it, once. If a parent needs to refer to its children, point to them (a result's id, source and score) instead of copying the text again.
Put token counts only on the model-call spans. Tracing tools add usage up across a trace, so a total on the parent counts everything twice.
2. What to record inside each trace
2.1 Record each model call: what went in, what came out, and what it cost
Your agent usually calls the model more than once per task: once to decide what to look up, again to write the reply. Record each call as its own span, with:
- the full prompt as sent;
- the full response;
- the model and the token counts.
The prompt as sent matters most. It isn't the prompt in your code: your code fills in the user's question, adds search results and may cut long context first. Only the recorded prompt shows what the model actually saw: whether the search results made it in, whether a value came through empty, whether something got cut.
The model and token counts tell you what each call cost, so you can put the cost of an answer next to whether it was right, and spot the expensive steps that don't change anything.
Use the OpenTelemetry GenAI attributes for the model and tokens, so your tracing tool can read them and work out the cost:
{
"name": "chat",
"attributes": {
"gen_ai.request.model": "claude-sonnet-4-6",
"gen_ai.usage.input_tokens": 3120,
"gen_ai.usage.output_tokens": 210,
"input.value": "System: You are a travel assistant... User: Do I need a visa for two weeks in Japan? I have a UK passport. Search results: ...",
"output.value": "Yes. You'll need to apply for a tourist visa before you travel."
}
}
2.2 Record the instructions as text
Put the full instructions the agent ran with on the span that used them: the system prompt, plus any rules, policy or template it was told to follow.
A label like prompt v6 isn't enough. Whoever's grading has to go find the instructions somewhere else and hope the copy they found matches what ran.
2.3 Trace every tool call, with its input and its output
Every tool call (web search, database lookup, page read, MCP tool, API call) gets its own span, with what went in and what came back.
The output is the part people skip, and it's the part you need when something's wrong. Say a travel assistant tells a UK traveler they need a visa for Japan. They don't: British passport holders get 90 days visa-free. Either the search never found that rule, or it found it and the agent ignored it. One is a search problem, the other a prompt problem, and only the search results tell you which.
Input goes in input.value, output in output.value:
{
"name": "web_search",
"attributes": {
"input.value": "Japan visa UK passport tourist",
"output.value": "[{\"title\": \"Japan tourist visa application\", ...}, {\"title\": \"Japan entry requirements\", \"url\": \"gov.uk/foreign-travel-advice/japan\", ...}]",
"output.value.truncated": false
}
}
2.4 For retrieval (RAG), record every chunk in full
If your agent answers from documents it looks up, record four things for each answer:
- the query the retriever actually ran, including any rewritten versions;
- every chunk it returned, in full, with its source, id and score;
- which chunks were kept after reranking or filtering;
- the final prompt sent to the model.
A RAG answer can go wrong in three places, and each needs a different fix. Say an employee asks your internal assistant how many days of leave they get. The handbook says 25, the assistant says 20:
| What happened | What you'd see in the trace | What to fix |
|---|---|---|
| The search never found the leave policy | None of the search results is the leave policy | The search |
| The search found it, but it was left out of what the model was given | The leave policy is in the search results, but not in the prompt | Which results get passed to the model |
| The model was given the leave policy and still said 20 | The leave policy is in the prompt, and the answer says 20 | The prompt or the model |
If the trace only has the question and the answer, all three look the same.
Keep chunks whole, even when the list is long. A short excerpt can cut off exactly the sentence that answers the question. If the list is too big for one span, split it across child spans instead of dropping chunks.
2.5 Record empty results and failures explicitly
A search that found nothing should still record an empty list. Otherwise "found nothing" and "didn't record anything" look identical.
Same for failures: a tool error, a timeout or a budget that ran out mid-run should mark the span as failed, with the reason. Watch out for tools that fail inside a successful response, like an HTTP 200 whose body says the search failed.
2.6 Store the agent's final answer as structured fields
Record what the agent finally returns (the reply, the report, the decision it hands to the next system) on the root span, as fields rather than one block of prose: the decision, the text the user sees, and each claim with a pointer to what backs it.
Here's the wrong visa answer stored that way:
{
"decision": "visa_required",
"reply": "Yes. You'll need to apply for a tourist visa before you travel.",
"claims": [
{
"claim": "UK passport holders need a tourist visa for Japan",
"evidence": "web_search result 1 (visa-service.example.com)"
}
]
}
That changes what a judge can do. Instead of asking "is this answer good?", it can check one claim against one piece of evidence: does result 1, a visa application page, say UK passport holders need a visa? It doesn't, so the claim fails. That's a much narrower question, and much easier to get right.
Also copy the decision onto the root span as its own attribute (app.decision = visa_required). Tracing tools filter on attributes, not on fields buried in a JSON output, so that's what lets you pull up every visa_required answer from last week.
3. How to tell whether the agent is improving
3.1 Record which version ran
Every trace should say exactly which version of your agent produced it. Otherwise you can't tell whether a change made things better or worse.
An agent changes in three ways, so you need three fields:
The code changes. Send the commit as service.version, from CI or your deploy script:
OTEL_RESOURCE_ATTRIBUTES=service.version=$(git rev-parse HEAD)
Someone runs it locally with uncommitted edits. Add a flag for that, so those runs aren't mistaken for the commit.
A prompt changes without a deploy, because it lives in a config file or a prompt manager. Add a short hash of each prompt and rules file, such as the first 12 characters of a SHA-256. Labels like prompt v6 get bumped by hand, so two traces with the same label can still have run different text. The hash tells you.
3.2 Add human feedback to the trace
When a person reacts to an answer (a thumbs-down, an edit, a reviewer's approval, a customer's reply), add it as a short span with the same ids as the answer's trace, holding the decision and the reason.
These are your ground truth. They're what you check an LLM judge against before you trust it, and what you count to see whether the agent is actually getting better.
Edits are especially useful: the difference between the two texts shows exactly what the person fixed.
4. How to keep it affordable and safe
4.1 Keep traces small by cutting repetition, not evidence
Record content in full. When traces get too big, cut what's repeated, not what's unique.
Most of the size is the same content recorded again and again: the same system prompt on every model call, the same document passed to several steps. Record it once with a hash, and have every other span point to it by that hash. Only do this if your tracing tool can show the full content from the reference, or a judge loses what it needs to grade.
For the rare field that's still enormous, like a whole uploaded document, set a size cap and flag it when it's hit (output.value.truncated), so whoever reads it knows they're only seeing part of it.
Size your export batches too. Once spans carry full documents, the default batch of hundreds of spans can be too big to send. If one trace is too large to keep, skip it and log it rather than failing the whole export.
4.2 Never let tracing break the agent
Wrap your tracing code so an error in it gets logged and ignored, never thrown into the agent.
The code that builds your traces runs inside the agent: turning search results into text, hashing a prompt, attaching the answer. If it throws and nothing catches it, the agent fails with it. Someone asking about a visa gets an error instead of an answer, because one search result couldn't be turned into JSON.
try:
span.set_attribute("output.value", json.dumps(results))
except Exception:
log.warning("tracing: could not record search results", exc_info=True)
Sending traces is safe as long as it happens in the background. Use OpenTelemetry's BatchSpanProcessor, which exports on a separate thread, not the simple processor, which exports on the agent's own thread. And set an export timeout.
Losing a trace leaves a small gap in your data. Failing a user's request is a lot worse.
4.3 Remove secrets and personal data before they leave your app
Strip secrets and personal data from your spans before they're exported. Full prompts, tool results and documents all end up in your tracing backend, including:
- secrets, such as API keys, tokens and credentials that end up in a tool's config or a request header;
- personal data you don't need to grade the answer, such as emails, phone numbers, and passport or account numbers.
Do it in one place, such as a span processor that runs on every span before export, so no new tool can skip it. Replace each removed value with a placeholder like [email], so you can still see something was there. If something can't be cleaned safely, such as a whole uploaded document, record a description and a hash instead.
How Glassray helps
Glassray reads traces like the ones in this guide and tells you where your agent goes wrong and whether your fixes worked. It does three things with them:
- It finds the problems. It reads every run, groups the runs that went wrong in the same way into one issue, and posts it to Slack.
- It keeps checking for them. When you confirm an issue, it becomes an evaluator that checks every new trace for it.
- It tests fixes before you ship. It proposes a fix and runs it against your past traces to see whether it holds.
You can send traces over OpenTelemetry, or connect the Langfuse or LangSmith project you already use.
If you would rather not set this up yourself, we can do it for you. Our engineers work in your codebase alongside your team: we add the tracing described here, build evaluators for the failures that matter to your users, and work on the fixes until they hold in production. Talk to a founder or join the waitlist.