0PricingLogin
AI Agents · Lesson

Detecting and Breaking Infinite Loops

Max iterations guards, repeated-action detection, and loop circuit breakers.

The Infinite Loop Threat

An agent in an infinite loop burns tokens, blocks resources, and produces no useful output. In production, this translates directly to money wasted and user frustration.

Three mechanisms work together to prevent infinite loops: max iteration limits, repeated action detection, and timeouts.

Guard 1: Max Iterations Limit

The simplest and most important guard is a hard step limit. Every agent loop must have one. When the limit is reached, the agent either returns its best current answer or an explicit failure message.

MAX_ITERATIONS = 20

def run_agent(query: str) -> dict:
    history = []

    for step in range(1, MAX_ITERATIONS + 1):
        action = decide_action(query, history)

        if action['type'] == 'final_answer':
            return {'status': 'ok', 'answer': action['answer'], 'steps': step}

        result = execute_tool(action['tool'], action['args'])
        history.append({'step': step, 'tool': action['tool'], 'result': result})

    # Hard stop — max iterations reached
    return {
        'status': 'max_iterations_reached',
        'answer': None,
        'steps': MAX_ITERATIONS
    }

All lessons in this course

  1. Common Agent Loop Failures
  2. Trace Logging for Agent Steps
  3. Detecting and Breaking Infinite Loops
  4. Step-Through Debugging Techniques
← Back to AI Agents