
Here is a bug you will meet sooner or later. A customer asks your support agent where their order is. The agent replies, politely and confidently, that it shipped yesterday. It didn't. The order is still sitting in the warehouse.
You open the logs and find one line: the customer's question and the agent's answer. Nothing in between. Did the agent call lookup_order? Did it call it with the wrong ID? Did the tool return an error that the model glossed over? Did it skip the tool and guess?
You can't tell. And if you can't tell, you can't fix it. You end up tweaking the system prompt and hoping.
This series is about debugging AI agents properly. Part 1 is the foundation everything else rests on: understanding the loop your agent runs, and logging every turn of it so that when something goes wrong you can read exactly what happened.
An agent is a loop, not a single call
A chatbot is one request and one response. An agent is a loop. You send the model a conversation and a list of tools. The model either answers, or asks you to run one or more tools. You run them, append the results to the conversation, and send it back. Repeat until the model stops asking.

In code, with the Anthropic TypeScript SDK, the bare loop looks like this:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: "Where is order 48213?" },
];
while (true) {
const response = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
tools,
messages,
});
// Keep the whole assistant turn, tool_use blocks included.
messages.push({ role: "assistant", content: response.content });
if (response.stop_reason !== "tool_use") break;
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type !== "tool_use") continue;
results.push({
type: "tool_result",
tool_use_id: block.id,
content: await runTool(block.name, block.input),
});
}
messages.push({ role: "user", content: results });
}Three things in this loop matter for debugging:
stop_reasontells you why the model stopped this turn. It is the single most useful field in the response, and most logs never record it.response.contentis a list of blocks, not a string. A turn can contain text, atool_useblock, severaltool_useblocks, or a mix. If you only log the text, you lose the tool calls, which is where most agent bugs live.messagesgrows every turn. By turn five, the model is reading a conversation you never wrote by hand. When it does something odd, the cause is usually somewhere in that history.
The stop reasons you need to know
Every response ends with a stop_reason. These are the ones you will see in practice:
end_turn: the model finished and has given its answer.tool_use: the model wants you to run tools and send the results back.max_tokens: the response hit yourmax_tokenscap and was cut off mid-thought. This is a silent killer: the text looks finished but isn't, or a tool call is half-written.pause_turn: a server-side tool needs another round. Append the assistant turn and send the request again.refusal: the model declined. The response carries astop_detailsobject with more information.
The bare loop above treats everything that isn't tool_use as "done". That is exactly the kind of shortcut that turns a max_tokens cut-off into a confident half-answer shown to a customer. We'll fix it below.
Log one line per turn
The fix for "I can't see what happened" is boring and it works: write one structured log line for every turn of the loop. JSON Lines (one JSON object per line) is ideal. It is easy to append, easy to grep, and easy to load into anything.
Here is a small tracer. It records the turn number, the stop reason, every tool call with its input, every tool result, token usage and how long the call took.
import { appendFileSync } from "node:fs";
type TraceEvent = Record<string, unknown>;
export function createTracer(runId: string, file = `traces/${runId}.jsonl`) {
return (event: TraceEvent) => {
appendFileSync(
file,
JSON.stringify({ run: runId, at: new Date().toISOString(), ...event }) + "\n",
);
};
}
// Tool results can be huge (a whole web page, a big DB row).
// Keep enough to debug, not enough to fill your disk.
export const clip = (s: string, n = 2000) =>
s.length > n ? `${s.slice(0, n)}… [${s.length - n} more chars]` : s;Now wire it into the loop. While we are here, we fix the two gaps in the bare version: a hard cap on turns, and explicit handling of every stop reason.
import { randomUUID } from "node:crypto";
const MAX_TURNS = 10;
export async function runAgent(userInput: string) {
const runId = randomUUID();
const trace = createTracer(runId);
const messages: Anthropic.MessageParam[] = [{ role: "user", content: userInput }];
trace({ type: "start", input: userInput });
for (let turn = 1; turn <= MAX_TURNS; turn++) {
const started = Date.now();
const response = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
tools,
messages,
});
trace({
type: "model",
turn,
ms: Date.now() - started,
stop_reason: response.stop_reason,
usage: response.usage,
text: response.content.flatMap((b) => (b.type === "text" ? [b.text] : [])),
tool_calls: response.content.flatMap((b) =>
b.type === "tool_use" ? [{ id: b.id, name: b.name, input: b.input }] : [],
),
});
messages.push({ role: "assistant", content: response.content });
switch (response.stop_reason) {
case "end_turn":
trace({ type: "done", turn });
return { runId, messages };
case "pause_turn":
continue;
case "tool_use":
break;
default:
// max_tokens, refusal, or anything new: never pass it off as an answer.
trace({ type: "stopped", turn, reason: response.stop_reason });
throw new Error(`Run ${runId} stopped: ${response.stop_reason}`);
}
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type !== "tool_use") continue;
const t0 = Date.now();
try {
const output = await runTool(block.name, block.input);
trace({ type: "tool", turn, id: block.id, name: block.name, ms: Date.now() - t0, output: clip(output) });
results.push({ type: "tool_result", tool_use_id: block.id, content: output });
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
trace({ type: "tool_error", turn, id: block.id, name: block.name, error: message });
results.push({ type: "tool_result", tool_use_id: block.id, content: message, is_error: true });
}
}
messages.push({ role: "user", content: results });
}
trace({ type: "gave_up", turns: MAX_TURNS });
throw new Error(`Run ${runId} hit MAX_TURNS`);
}A few choices in there are worth calling out.
Every run gets an ID. When a customer complains, you want to go from their conversation to the exact trace file in one step. Put the run ID in your app logs and your support tooling.
Tool errors become data, not crashes. If runTool throws, we send the error back to the model as a tool_result with is_error: true. The model can often recover: retry with a corrected input, try a different tool, or tell the user plainly that it couldn't look the order up. If you let the exception kill the loop, the user gets nothing and you get a stack trace with no context.
max_tokens and refusal are treated as failures. Don't show a cut-off answer to a user as if it were complete. Fail loudly, and the trace tells you which one it was.
There is a turn cap. An agent that keeps calling tools forever is a real failure mode (we'll dig into why in a later part). Ten turns is plenty for most support and ops agents. If yours genuinely needs more, raise it on purpose, not by accident.
Reading a trace
Here is the trace for the shipping bug from the top of this post, trimmed a little:
{"run":"7f3c…","type":"start","input":"Where is order 48213?"}
{"run":"7f3c…","type":"model","turn":1,"stop_reason":"tool_use","tool_calls":[{"id":"toolu_01","name":"search_orders","input":{"query":"48213"}}]}
{"run":"7f3c…","type":"tool","turn":1,"name":"search_orders","output":"[{\"id\":\"48123\",\"status\":\"shipped\"}]"}
{"run":"7f3c…","type":"model","turn":2,"stop_reason":"end_turn","text":["Good news! Order 48213 shipped yesterday."]}
{"run":"7f3c…","type":"done","turn":2}Now the bug is obvious, and it isn't a "hallucination" at all. The model did call a tool. It called search_orders, a fuzzy search, instead of an exact lookup. The search returned a different order, 48123, with two digits swapped. The model read "shipped" and reported it.
Without the trace, you would have spent an afternoon rewording the system prompt ("NEVER make up order statuses!"). With it, you can see that the fix belongs in the tools: give the model an exact get_order tool, and make the search tool's description say clearly that it is fuzzy. That is the subject of Part 2.
When you read a trace, ask these five questions in order:
- Did the model call a tool at all? If not, it answered from its own knowledge or from earlier in the conversation.
- Which tool, with what input? Wrong tool and wrong arguments are the most common agent bugs by far.
- What did the tool actually return? Check it with your own eyes. Empty lists, error pages and the wrong record all look fine to a model that is trying to be helpful.
- What was the last thing the model saw before it answered? That is usually the tool result from the previous turn.
- Why did it stop?
end_turnmeans it thought it was done. Anything else means it was interrupted.
Bugs the trace catches in minutes
These are the loop bugs we see most often. Every one of them is invisible in a "question in, answer out" log and obvious in a turn-by-turn trace.
1. Appending text instead of content
// Wrong: throws away the tool_use blocks
messages.push({ role: "assistant", content: textOf(response) });
// Right: keep every block the model returned
messages.push({ role: "assistant", content: response.content });If you only keep the text, the next request contains tool_result blocks that point at tool_use IDs the API has never seen in the conversation. The API rejects the request with a 400. Always push response.content as is.
2. A tool call with no result
Every tool_use block needs a matching tool_result with the same tool_use_id in the very next user message. It is easy to break this when a tool is skipped ("we don't support that yet") or when an exception escapes. Even a skipped tool must send something back:
results.push({
type: "tool_result",
tool_use_id: block.id,
content: `Tool "${block.name}" is not available in this deployment.`,
is_error: true,
});
3. Splitting parallel results across messages
Models can ask for several tools in a single turn. When they do, all the results go back in one user message, as in the diagram above. If you send each result as its own message, the conversation stops being well formed, and over time the model learns from its own history that parallel calls don't work and stops making them. Your agent gets slower and you won't know why.
4. Truncated turns
If your trace shows stop_reason: "max_tokens", the turn was cut off. The usual cause is a max_tokens value copied from an old example (1024 is a common culprit), which is fine for a one-line answer and far too small for an agent that writes long tool inputs or reasons before acting. Raise it. For long outputs, use streaming so the request doesn't time out on the HTTP side.
5. The endless loop
The trace shows turn after turn of the same tool with the same input. The model keeps asking, the tool keeps returning something the model doesn't find useful, and nobody stops it. The turn cap stops the bleeding. The real fix is usually a better tool result: if a search finds nothing, say "No orders match 48213" instead of returning []. Models handle a clear sentence much better than an empty array.
Make failures replayable
The last piece is the one that saves the most time. When a run fails, save the full messages array next to the trace. Then you can replay the exact turn that went wrong, as many times as you like, without poking at production:
import { readFileSync, writeFileSync } from "node:fs";
export function saveConversation(runId: string, messages: Anthropic.MessageParam[]) {
writeFileSync(`traces/${runId}.messages.json`, JSON.stringify(messages, null, 2));
}
// replay.ts: re-run the model on a saved conversation, up to a given turn
const [runId, upTo] = process.argv.slice(2);
const saved: Anthropic.MessageParam[] = JSON.parse(
readFileSync(`traces/${runId}.messages.json`, "utf8"),
);
// Keep everything before the assistant turn you want to reproduce.
const history = saved.slice(0, Number(upTo));
const response = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
tools,
messages: history,
});
console.dir(response.content, { depth: null });Now "the agent did something weird yesterday" turns into a repeatable test case. Change a tool description, replay, and see whether the behaviour changes. Run it a few times, because model output varies between runs. A fix that works one time in five isn't a fix.
Checklist
Before you debug anything else in an agent, make sure the loop gives you this:
- One JSON line per model turn, with
stop_reason, tool calls and their inputs, text and usage. - One line per tool execution, with the (clipped) output or the error.
- A run ID that links a user's conversation to its trace.
- Every
stop_reasonhandled explicitly, withmax_tokensandrefusaltreated as failures. - A hard cap on turns.
- Tool errors sent back to the model as
is_errorresults, not thrown. - Failed conversations saved and replayable.
It is maybe sixty lines of code. It turns "the AI did something weird" into a trace you can read in two minutes.
Next in this series: the shipping bug wasn't really a model problem. It was a tool problem. Part 2 is about why agents call the wrong tool, or no tool at all, and how to design tool names, descriptions, schemas and error messages so they pick the right one.


