By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The tool loop leaves an ordered record behind: the model's tool_calls, one ToolMessage per call keyed by tool_call_id, and finally a plain answer. That record is the observable contract of the agent, and reading it well is the difference between patching a symptom and fixing a cause.
This lab puts one broken trace on the table. The customer asked where order ORD-4521 is. The model made a wrong first call, the tool rejected it, the loop recovered on a second attempt, and the final answer happens to be right - a run that looks fine from the outside and still needs a fix. Your job is to find the first wrong decision, name whether the tool or the prompt owns it, and leave a test behind.
The snippet defines the broken trace, a repaired version of the same run, and a diagnose helper that checks four invariants: argument formats, structured tool errors, matching call and result ids, and an answer grounded in a tool result. Run it to see what the trace analyst would report.
"""Read a tool-call trace the way a debugger reads a stack."""
import re
BROKEN_TRACE = [
{
"role": "ai",
"tool_calls": [
{
"name": "lookup_order",
"args": {"order_id": "4521"},
"id": "call_1",
}
],
},
{
"role": "tool",
"tool_call_id": "call_1",
"content": {"ok": False, "error": "invalid_order_id"},
},
{
"role": "ai",
"tool_calls": [
{
"name": "lookup_order",
"args": {"order_id": "ORD-4521"},
"id": "call_2",
}
],
},
{
"role": "tool",
"tool_call_id": "call_2",
"content": {
"ok": True,
"order_id": "ORD-4521",
"status": "in_transit",
},
},
{"role": "ai", "text": "Order ORD-4521 is in transit."},
]
FIXED_TRACE = [
{
"role": "ai",
"tool_calls": [
{
"name": "lookup_order",
"args": {"order_id": "ORD-4521"},
"id": "call_1",
}
],
},
{
"role": "tool",
"tool_call_id": "call_1",
"content": {
"ok": True,
"order_id": "ORD-4521",
"status": "in_transit",
},
},
{"role": "ai", "text": "Order ORD-4521 is in transit."},
]
ORDER_ID = re.compile(r"^ORD-\d{4}$")
def diagnose(trace):
findings = []
call_ids, result_ids = set(), set()
for message in trace:
for call in message.get("tool_calls", []):
call_ids.add(call["id"])
args = call["args"]
if call["name"] == "lookup_order" and not ORDER_ID.match(
args.get("order_id", "")
):
findings.append(
f"call {call['id']}: order_id "
f"{args.get('order_id')!r} does not match ORD-####"
)
if message["role"] == "tool":
result_ids.add(message["tool_call_id"])
if message["content"].get("ok") is False:
findings.append(
f"result {message['tool_call_id']}: tool returned "
f"{message['content']['error']!r}"
)
missing = call_ids - result_ids
if missing:
findings.append(f"unmatched tool calls: {sorted(missing)}")
if "in transit" not in trace[-1].get("text", ""):
findings.append("final answer is not grounded in the tool result")
return findings
for label, trace in (("broken", BROKEN_TRACE), ("fixed", FIXED_TRACE)):
print(f"{label} trace:")
findings = diagnose(trace)
if not findings:
print("- no findings")
for finding in findings:
print("-", finding)The first line is the bug: the model passed '4521' where the contract says ORD-4521, so the tool validated and returned invalid_order_id. The second call is the same run recovering; the final answer is grounded. That is why a trace review starts at the first wrong message instead of at the sentence the customer complained about - the visible error is the last consequence of the run, not its cause.
The repaired trace makes the same request with the corrected format and produces no findings. Both traces are fixtures now: the broken one documents the bug, and the fixed one documents the behaviour the test suite should pin.
Most trace reviews follow the same shape. Read the symptom the customer or the dashboard reported, find the message where the run first went wrong, then decide whether the tool or the prompt was missing information. This table is the decision tree; adapt the rows to the tools in front of you.
| Symptom | Trace evidence | Root cause | Fix in tool or prompt | Test that catches it |
|---|---|---|---|---|
| Tool rejects real orders | AI call has order_id: '4521'; result is invalid_order_id | Docstring never shows the format and the schema has no pattern | Tool: add a format example and a pattern; prompt: state the id format once | Schema test accepts ORD-4521, rejects 4521 |
| Wrong tool chosen | Order-status question calls search_docs instead of lookup_order | Tool names and descriptions overlap, so no description says when to use it | Tool: describe when to use lookup_order; prompt: add a routing line for order status | Scripted trajectory test asserts lookup_order |
| Answer claims a write | Final AI text says 'refund issued'; no queue_for_approval call in the trace | The prompt rewards a confident answer and has no evidence rule | Prompt: answer only from tool results; tool: the queue returns a pending record | Grounded-answer case: no refund claim without a pending record |
| Unmatched call and result | An AI tool_call_id has no matching ToolMessage; the next request is rejected | A hand-written loop dropped a failed call instead of appending an error result | Code: one ToolMessage per call id, failures included | Unit test asserts the call-id set equals the result-id set |
| Model repeats a failing call | Two AI calls with identical arguments; both results are invalid_order_id | No recovery instruction in the prompt and no repeat guard in the loop | Prompt: after one validation error ask a clarifying question; code: repeat guard plus step cap | Scripted trajectory test stops after one retry |
| Another customer's order appears | The call's order_id does not belong to the ticket | The tool trusted the model; the prompt let text choose the argument | Tool: validate ownership against the ticket; prompt: use only the thread's order id | Security test: cross-ticket argument is rejected |
A trace points at a cause, and the cause belongs to exactly one layer. Use this order; it mirrors the authority model the whole path builds on.
The lab's deliverable is not a better sentence; it is a test file. These are the four invariants the diagnose helper checks, and each one is a plain assertion over a stored trace.
tool_calls entry has exactly one ToolMessage with the same tool_call_id, and failures are results too.4521 fails before the tool is even called in the fixed version.Key takeaways
A trace is the observable contract of the loop: AI tool calls, ToolMessage results keyed by tool_call_id, then the answer.
Diagnose the first wrong decision, not the final sentence; the answer is where a cause becomes visible.
A missing format or when-to-use clause is a tool fix; a wrong choice made with correct information is a prompt fix.
Properties neither tool nor prompt can guarantee - ownership, write authority, PII - need code controls and tests.
Convert every failing trace into a regression fixture that asserts id matching, argument formats, write evidence and grounding.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.