Module 09 · Lesson 9.3
Tracing Tool Calls and Agent Decisions
On this page
- What you will learn
- What a trace is and why agents need one
- The trace event: what each line records
- Run ids and version labels
- What to record and what never to record
- Build a tracer and replay a run in Python
- Using a trace to find out what went wrong
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
A customer writes: "Your bot told me my bike was delivered, but it is still in the warehouse." You open the logs and find a single line: "reply sent". Nothing tells you which order was looked up, which tool returned what, or why the agent chose that answer. You cannot fix a problem you cannot see.
A trace solves this. It is a step-by-step record of one run, like the black box of an aircraft. In this lesson you learn what to put in a trace, what to keep out of it, and how to read a run back from its events. Most of it needs no coding. One short Python script builds a trace and prints a timeline.
What you will learn
- Explain what a trace is and how it differs from an ordinary log line.
- Write a trace event with the fields run id, step, kind, name, time, success and version.
- List what must never be recorded in a trace.
- Rebuild the timeline of a run from its events with Python.
Before you start
- The previous lesson, API Design, Background Jobs and Session Management.
- No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
What a trace is and why agents need one
A normal program does the same steps every time, so its code explains its behaviour. An agent chooses its own steps. The same question can lead to different tool calls on different days. To understand one particular run, you must have a record of that run.
- Trace
- The ordered record of everything one run did: each model call, tool call and check, with its outcome and time taken.
- Event
- One entry in a trace, such as "called search_help, took 35 ms, succeeded".
- Run id
- A unique label such as R-0001 that is stamped on every event of one run, so the events can be found and put back together.
- Observability
- How well you can understand what a system is doing from the outside, using the records it produces.
Think of a parcel tracking page. It does not say "delivered" and stop. It lists each stop with a time. If the parcel goes missing, you see where. A trace is a tracking page for one agent run.
Big systems use shared standards for traces. The OpenTelemetry project describes the general idea of traces and their parts. You do not need it for this course, but it is useful background if you later join a team that uses it.
The trace event: what each line records
In this module every event is one line of JSON in a file called traces.jsonl. Writing one object per line makes the file easy to add to and easy to read with simple tools.
{"run_id": "R-0001", "step": 1, "kind": "model", "name": "search_help", "ms": 120, "ok": true, "version": "v2"}One event. It is written on a single line in the real file.
| Field | Meaning | Example |
|---|---|---|
| run_id | Which run this event belongs to | R-0001 |
| step | The order inside the run, starting at 1 | 3 |
| kind | What type of step it was: model, tool or check | tool |
| name | Which tool, model step or check | search_help |
| ms | How long the step took, in milliseconds | 120 |
| ok | Whether the step worked | true |
| version | Which instructions and settings were active | v2 |
- model events are calls to the AI model.
- tool events are calls to your tools, such as lookup_order or search_help.
- check events are your own code checks, such as the grounding check from Module 4 or an output check.
Run ids and version labels
Create the run id as soon as a request arrives. Put it on every event, and return it to the client in the response, as in POST /ask. Now a customer's complaint can point to one run, and you can pull up its events with GET /runs/<run_id>.
The version field says which instructions, tools and model settings were active. Imagine answers got worse on Tuesday. If every event carries a version, you can see that the bad runs all came from v2. You will use this again in Versioning, Rollbacks and Production Operations.
- Use ids that cannot be mixed up between runs, even when two runs overlap.
- Use the same id in your logs, traces and API responses.
- If one request leads to a background job, store the run id with the job id. See API Design, Background Jobs and Session Management.
What to record and what never to record
A trace is useful because it is detailed. It is also dangerous for the same reason. Many people can read traces, and they are kept for a long time. Treat a trace as a place where private data can leak.
| Record | Never record |
|---|---|
| Run id, step number and version | API keys, passwords and tokens |
| The kind and name of each step | Full customer messages or full model replies, unless redacted |
| How long each step took | Email addresses, card numbers, home addresses |
| Whether each step succeeded | The whole instruction text on every event |
| Short error codes or reasons | Raw tool results that contain personal data |
If you do need some text to investigate, redact it first. Redacting means replacing sensitive parts with a safe marker, for example turning an email address into [email] before it is written. Data Privacy, Sensitive Information and Secure Logging shows a redaction function. The sample trace in this lesson avoids the question altogether: it stores only names and numbers.
Build a tracer and replay a run in Python
The script below creates a small Tracer class. It adds events with fixed, made-up millisecond values, so the output is the same each time. Then a timeline function rebuilds the run from the saved lines. The run is a Quillfeather help question where the grounding check failed once.
import json
class Tracer:
def __init__(self, run_id, version):
self.run_id = run_id
self.version = version
self.events = []
def add(self, kind, name, ms, ok=True):
event = {
"run_id": self.run_id,
"step": len(self.events) + 1,
"kind": kind,
"name": name,
"ms": ms,
"ok": ok,
"version": self.version,
}
self.events.append(event)
def lines(self):
return [json.dumps(e) for e in self.events]Part 1: the Tracer class. Standard library only.
def timeline(events):
total = sum(e["ms"] for e in events)
print("Run", events[0]["run_id"], events[0]["version"], "total", total, "ms")
for e in events:
mark = "ok" if e["ok"] else "FAIL"
print(" %d. %-5s %-11s %4d ms %s" % (e["step"], e["kind"], e["name"], e["ms"], mark))
t = Tracer("R-0001", "v2")
t.add("model", "ask_model", 820)
t.add("tool", "search_help", 35)
t.add("check", "grounding", 2, ok=False)
t.add("model", "ask_model", 640)
print(t.lines()[2])
timeline([json.loads(line) for line in t.lines()])Part 2: add this below part 1 in the same file.
What each part does
class Traceris a class, a bundle of data and functions that belong together. OneTracerobject records one run.__init__runs when you create the tracer. It stores the run id and version and starts with an empty list of events.add(...)builds one event dictionary. The step number is the current count plus one, so steps are always 1, 2, 3 and so on.ok=Trueis a default value. If you do not passok, the step is assumed to have worked.lines()turns each event into one line of JSON text. In a real service you would append each line totraces.jsonl.timeline(events)adds up the times and prints one row per step, with FAIL on any step that did not work.- The last line reads the JSON lines back into dictionaries first. That proves the run can be rebuilt from the saved text alone.
{"run_id": "R-0001", "step": 3, "kind": "check", "name": "grounding", "ms": 2, "ok": false, "version": "v2"}
Run R-0001 v2 total 1497 ms
1. model ask_model 820 ms ok
2. tool search_help 35 ms ok
3. check grounding 2 ms FAIL
4. model ask_model 640 ms okRead the timeline like a story. The model decided to search the help pages. The search worked. The grounding check failed, so the agent asked the model again, and the second try passed. Without the trace you would only know that the answer took about a second and a half.
Using a trace to find out what went wrong
When a customer complains, work in this order.
Step 1: Find the run id
Ask for it, or find it from the time and the order number in your records.
Step 2: Load all events with that run id
Sort them by step number. Check the version first.
Step 3: Look for the first step that is not ok
The first failure is usually the cause. Later failures are often only consequences.
Step 4: Check the decisions
Did the model pick the right tool? Did a check reject the answer? Was a step much slower than usual?
Step 5: Turn the finding into a test
Add the case to your evaluation dataset, so the same problem is caught next time. See Evaluation Datasets, Rubrics and Expected Behaviours.
Traces also feed the next lesson. When you add up many runs, you get numbers such as error rate and slow runs. That is Monitoring Quality, Failures, Latency and Cost.
Conclusion and your next step
A trace is the ordered record of one run. Each event holds a run id, step, kind, name, time, success flag and version. Record decisions and outcomes, redact or leave out anything personal, and you can rebuild any run later.
Your next step: list the steps of your own agent and decide which events it should write. Mark any field that could contain personal data. Then continue to Monitoring Quality, Failures, Latency and Cost, where you summarise many traces into numbers and alerts.
For more background, see The Tool-Calling Loop: Reference Diagram and AI-Assisted Debugging: A Scientific-Method Prompt Framework.
Common errors and how to fix them
You cannot tell which log lines belong to which run.
Why it happens: No run id is stamped on the events.
Fix: Create a run id when the request arrives and add it to every event and to the API response.
A customer's email address appears in the trace file.
Why it happens: Whole messages or tool results were written without redaction.
Fix: Record names and numbers only. If text is needed, redact it before writing, and remove the old lines.
Behaviour changed but you cannot say why.
Why it happens: Events carry no version label.
Fix: Add the version to every event, and change it whenever instructions, tools or model settings change.
The trace shows that the agent was slow, but not where.
Why it happens: Only the total time was recorded.
Fix: Record the time of each step, so you can see which one was slow.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Read a trace and find the cause
A customer asked, "Can I get a refund on QF-1044?" The agent replied that a refund was approved. Below is the trace. Find the first suspicious step and say what the trace tells you about the cause.
You will need
- Step 1: model, name ask_model, 700 ms, ok true
- Step 2: tool, name search_help, 30 ms, ok true
- Step 3: model, name ask_model, 650 ms, ok true
- Step 4: check, name policy_check, 1 ms, ok true
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- A trace of a correct answer might include a check that fails when a refund is promised.
- Names of retrieved page ids are safe to record. Customer text is not.
- Ask what a person could not tell from this trace.
Show a model answer
Every step reports ok, so nothing visibly failed. The agent never called request_return, yet it told the customer a refund was approved. That promise should have been caught by the policy check, which passed, so the check is too weak or missing the rule. The trace is also too thin to show which help pages were used, so add the ids of retrieved pages to the event name or a new field. Finally, add the question as an evaluation case that expects status needs_person or return_requested and no refund promise.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The same id on every event lets you group them. Encryption and speed are different jobs. A timestamp alone is tempting, but two runs can overlap and then their events mix.
Show the answer and explanation
Answer: B. A name and a duration describe the step without exposing anyone. The email is personal data and the key is a secret. Both could leak through anyone with access to the trace.
Show the answer and explanation
Answer: B. When behaviour changes, the version points to what changed. JSON has no such rule. Skipping the label is tempting, but without it you cannot compare runs before and after a change.
Frequently asked questions
What is the difference between a log and a trace?
A log is a general record of things that happened in a program, often one line at a time. A trace is a connected record of one run, with steps in order and a shared run id. Traces answer "what happened in this run?", logs answer "what is the program doing?".
Should I store the full prompt and reply in the trace?
Usually not. They can hold personal data and they make the files large. Record names, timings and outcomes. If you need text for debugging, store a redacted short version and limit who can read it.
How long should I keep traces?
Only as long as you need them to debug and monitor. The exact period depends on your organisation's policy and local rules, so check with whoever owns privacy there.
Do I need OpenTelemetry to trace an agent?
No. A simple JSON lines file is enough to start, as in this course. OpenTelemetry is a common standard that bigger teams use, so learning its ideas helps if you move to such a team.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Traces(opens in a new tab)
OpenTelemetry · Official documentation · General background on what a trace and its parts are. Not required for this course.
- Logging Cheat Sheet(opens in a new tab)
OWASP Foundation · Official documentation · What to log, and what to keep out of logs.
- LLM02:2025 Sensitive Information Disclosure(opens in a new tab)
OWASP Foundation · Official documentation · How sensitive data can leak from LLM applications.
- json: JSON encoder and decoder(opens in a new tab)
Python Software Foundation · Official documentation · The dumps and loads functions used in the example.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.