
In Part 1 we logged every turn of the agent loop. In Part 2 we fixed the tools so the model picks the right one. This part is about the bug that costs real money: the agent that never stops.
It shows up in three ways. The agent repeats the same tool call over and over. A long conversation outgrows the context window and the run falls over halfway. Or the run is technically fine but takes so many turns that nobody waits for it. All three come from the same missing piece: a loop that has no idea when to quit.
Put a ceiling on every loop
Here is the loop from Part 1, with the one thing it was missing:
const MAX_TURNS = 20;
const MAX_TOKENS_BUDGET = 200_000;
let turns = 0;
let spent = 0;
while (true) {
if (turns++ >= MAX_TURNS) return finish("turn_limit", messages);
if (spent >= MAX_TOKENS_BUDGET) return finish("token_budget", messages);
const response = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
system: SYSTEM_PROMPT,
tools,
messages,
});
spent += response.usage.input_tokens + response.usage.output_tokens;
// ...handle stop_reason and tool calls as before
}Pick numbers from your traces, not from instinct. Look at your normal runs, take the longest successful one, and set the limit at about double. The limit is not meant to trigger often. It exists so that the day something goes wrong costs you 20 turns, not 20,000.
When a limit trips, don't throw. Return a result that says why you stopped and what was done so far, and hand it to a person or a retry queue. A run that stops cleanly with a reason is debuggable. A run that crashes is not.
Spot a loop from the trace
A looping agent has a very particular trace. The same tool, the same input, the same result, turn after turn:
turn 4 tool_use get_order {"order_number":"48213"} -> is_error: "No order with number 48213"
turn 5 tool_use get_order {"order_number":"48213"} -> is_error: "No order with number 48213"
turn 6 tool_use get_order {"order_number":"48213"} -> is_error: "No order with number 48213"The model isn't stupid. It was told to look the order up, the lookup failed, and nothing in the error told it to do something different. (This is why Part 2 insisted that errors say what to try next.)
You can detect this in code. Keep a fingerprint of each tool call (name plus input, serialised the same way each time) and count repeats:
import { createHash } from "node:crypto";
const seen = new Map<string, number>();
const MAX_REPEATS = 2;
function fingerprint(name: string, input: unknown): string {
return createHash("sha256").update(name + JSON.stringify(input)).digest("hex");
}
function repeatedTooOften(name: string, input: unknown): boolean {
const key = fingerprint(name, input);
const count = (seen.get(key) ?? 0) + 1;
seen.set(key, count);
return count > MAX_REPEATS;
}When it trips, don't just kill the run. Tell the model what is happening in the tool result, which is the one place it is guaranteed to read:
if (repeatedTooOften(block.name, block.input)) {
results.push({
type: "tool_result",
tool_use_id: block.id,
is_error: true,
content:
"You have made this exact call several times with the same result. " +
"Do not call it again. Either try a different approach or tell the customer " +
"you can't complete this and offer to pass it to the team.",
});
continue;
}If the same fingerprint trips twice in one run, stop the run and escalate. Two nudges is generous.
Context windows fill up quietly
Every turn adds to messages: the model's reply, your tool results, the next reply. Tool results are the big part. One get_order returning a full order with line items and history can be thousands of tokens, and the model sees all of it again on every later turn.
You can watch it happen. Log the input tokens per turn from Part 1's trace:
turn 1 input_tokens 2,140
turn 5 input_tokens 14,880
turn 12 input_tokens 61,300
turn 19 input_tokens 148,900A steady climb like this means every turn costs more than the last, and eventually the request fails. Three fixes, in order of how often they help:
1. Make tool results smaller. Return what the model needs, not everything you have. get_order should return status, carrier and tracking number, not the customer's whole address history. Add parameters such as fields or limit when a tool can return a lot. This is the cheapest fix and usually the biggest.
2. Clear old tool results. Once the model has used a result, it rarely needs the raw version again. Replace old tool results with a one-line stub:
const KEEP_LAST = 4;
function trimOldToolResults(messages: Anthropic.MessageParam[]) {
const resultIdx = messages.flatMap((m, i) =>
m.role === "user" && Array.isArray(m.content) && m.content.some((b) => b.type === "tool_result") ? [i] : [],
);
for (const i of resultIdx.slice(0, -KEEP_LAST)) {
const content = messages[i].content as Anthropic.ToolResultBlockParam[];
messages[i].content = content.map((b) =>
b.type === "tool_result" ? { ...b, content: "[result removed to save space]" } : b,
);
}
}Keep the tool_use blocks and the tool_result blocks paired, as Part 1 showed. You are changing what is inside a result, not removing the result.
3. Summarise and restart. For runs that are genuinely long, ask the model to write a short summary of what has been done and what is left, then start a fresh conversation containing only the system prompt, the original task and that summary. Store the summary somewhere you can read it, because you will want to see what got lost.
Anthropic's API also has features that do some of this for you, such as clearing old tool results and compacting long conversations. They change over time, so check the current docs. Whichever you use, keep logging input_tokens per turn so you can see whether it is working.
Check you are really done
Many agents loop because they have no way to know they have finished. "Handle this support ticket" is not something a model can verify. "Reply to the customer, then call close_ticket" is.
Give every run an explicit finish:
- A finish tool. Add a
finishtool with a structured input such as{ outcome: "resolved" | "escalated", summary: string }. The run ends when it is called, and the summary is your log line. - A checkable end state. If the task is "update the CRM record", the finish check is reading the record back, in code, not asking the model whether it worked.
- A stop condition in the prompt. "When you have answered the customer's question, stop. Do not ask follow-up questions unless information is missing."
for (const block of response.content) {
if (block.type === "tool_use" && block.name === "finish") {
return finish(block.input.outcome, messages, block.input.summary);
}
}A run that ends because the model called finish is a success you can count. A run that ends because of turn_limit is a bug you can find, because you can search your logs for that reason.
Long runs should survive a crash
If a run takes ten minutes and the process restarts at minute nine, you don't want to begin again. Save the messages array after every turn (a row per run in your database is enough), and make resuming a matter of loading it:
await db.runs.update(runId, { messages, turns, spent, status: "running" });Two warnings. First, any tool with side effects needs to be safe to run twice, because a resumed run may repeat the last tool call. That is the idempotency problem from our automations series, and the same fixes apply. Second, never resume a run that is half-way through a tool call without checking whether the call happened. Record the tool_use id before running the tool and the result after, so you can tell.
Cost is a bug report
Runaway agents are first noticed in the bill. Add three numbers to every run record: turns, tokens in and out, and finish reason. Then make two dashboards, or even just two queries:
- Runs by finish reason. If
turn_limitis more than a few percent of runs, your tools or prompt have a problem. Read those traces first. - Tokens per run, p50 and p95. A p95 many times higher than the median is your loop-and-bloat bucket. Open the five most expensive runs and read them.
Set a per-run and a per-day spending alert. The point isn't to be perfect. The point is that an infinite loop is caught in an hour, not at the end of the month.
Checklist
When an agent won't stop:
- Put a turn limit and a token budget on every loop. Base them on real traces.
- Return a result with a finish reason when a limit trips. Never crash.
- Fingerprint tool calls, and tell the model when it is repeating itself.
- Log
input_tokensper turn and watch for the climb. - Shrink tool results first, then clear old ones, then summarise and restart.
- Give every run an explicit finish: a
finishtool or a checkable end state. - Save
messagesafter each turn so a long run can resume. - Track turns, tokens and finish reason per run. Read the most expensive runs weekly.
If you'd rather have someone build and debug this alongside you, that's what we do at Zaitics: AI agents and automations for small teams, with the logging, limits and tests already in place.


