Building Autonomous AI Agents · Module 2 · Memory, Scratchpads & Context Windows
Detecting and Breaking Infinite Loops
5 min read · lesson 4 of 6
One of the most common failure modes of autonomous agents is getting stuck in repetitive loops: repeatedly searching for the same failing query or calling the same failing tool. Robust production systems must have hard programmatic loop breakers.
The Loop Breaker Pattern
- Max Iterations Cap: Always enforce a hard ceiling (e.g. 10 or 15 iterations maximum) regardless of what the LLM desires.
- Action Fingerprinting: Hash the combination of `tool_name + JSON.stringify(args)`. If the exact same hash occurs 3 times consecutively, intervene immediately.
- Nudge Prompt: When a loop is detected, inject a system message: 'Warning: You have repeated this exact action without new progress. Choose a different approach or report your blocker to the user.'
const historyHashes = new Set<string>();
for (let step = 0; step < MAX_STEPS; step++) {
const action = await getNextAction();
const hash = `${action.tool}:${JSON.stringify(action.args)}`;
if (historyHashes.has(hash)) {
injectSystemMessage('Loop detected! Do not repeat previous actions.');
}
historyHashes.add(hash);
}Practice
Draft a system prompt directive that explicitly instructs the agent how to proceed when it receives a loop warning.