patterntypescriptMajor
AI agent loops need a maximum step limit to prevent infinite execution
Viewed 0 times
ai-agentloop-detectionmax-iterationstool-usesafetystep-limit
Problem
LLM-based agents that iteratively call tools and re-prompt can get stuck in loops — repeatedly calling the same tool, oscillating between two states, or making incremental progress that never converges. Without a step limit the agent runs indefinitely consuming tokens and credits.
Solution
Implement a hard maximum iteration count (e.g., 20 steps) as an outer loop guard. Track which tools were called with which arguments and detect repeated calls as a loop signal. Provide the agent with an explicit 'task_complete' or 'give_up' tool it can call when it cannot make progress.
Why
LLMs lack persistent awareness of their loop state. They operate purely on context — if the context doesn't make the loop condition obvious, the model will not detect it. External loop control is mandatory.
Gotchas
- The step limit should be configurable per task type — simple tasks need few steps, complex ones more
- When the step limit is hit, return a partial result rather than an error — partial progress is valuable
- Log all agent steps for debugging — agent failures are hard to diagnose without a trace
Code Snippets
Agent loop with step limit
const MAX_STEPS = 20;
let steps = 0;
while (steps < MAX_STEPS) {
const response = await llm.chat(messages);
if (!response.tool_calls?.length) break; // natural completion
messages.push(response);
for (const tc of response.tool_calls) {
const result = await executeTool(tc);
messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result) });
}
steps++;
}
if (steps >= MAX_STEPS) console.warn('Agent hit step limit');Context
Building autonomous AI agents that use tools in a loop
Revisions (0)
No revisions yet.