Infinite Loop in AI Agents

An infinite loop in an AI agent occurs when the agent enters an unbounded cycle of LLM calls, tool invocations, or state transitions that never terminates. Common causes include missing max_iterations on AgentExecutor, cycles in LangGraph StateGraphs, and LLM-controlled exit conditions that never evaluate to false.

CRITICAL SeverityLLM04: Model Denial of Service

AgentExecutor Without Bounds

Vulnerable
python
# Missing iteration bounds - runs until context limit
agent_executor = AgentExecutor.from_agent_and_tools(
    agent=agent,
    tools=tools,
    verbose=True
    # No max_iterations set!
    # No max_execution_time set!
)
result = agent_executor.run("Analyze this data...")
Secure
python
# Bounded execution with safety guards
agent_executor = AgentExecutor.from_agent_and_tools(
    agent=agent,
    tools=tools,
    verbose=True,
    max_iterations=10,
    max_execution_time=30,  # seconds
    early_stopping_method="generate"
)

Frequently Asked Questions

What causes infinite loops in AI agents?

Common causes include: missing max_iterations on LangChain AgentExecutor, cycles in LangGraph StateGraphs without termination conditions, CrewAI delegation loops between agents, and LLM-controlled exit conditions where the model decides when to stop but never does.

How do you detect infinite loops in AI agents before deployment?

Static analysis tools like Inkog trace the control flow graph of your agent code and identify loops without deterministic termination guards. This includes missing max_iterations parameters, cycles in graph-based agents, and recursive tool calling patterns.

What is the cost impact of an AI agent infinite loop?

A single runaway agent loop can consume thousands of dollars in API costs within minutes. Each loop iteration makes an LLM call ($0.01-0.10 per call), and without bounds, costs escalate until the context window limit or API rate limit is hit.

How do you fix an infinite loop in LangChain AgentExecutor?

Set max_iterations and max_execution_time parameters: AgentExecutor(agent=agent, tools=tools, max_iterations=10, max_execution_time=30). This ensures the agent stops after a bounded number of steps or seconds.

How Inkog Detects This

Inkog traces the control flow graph of your agent code and identifies LoopNodes without deterministic termination guards. It checks for missing max_iterations on AgentExecutor, cycles in LangGraph StateGraphs, and recursive agent delegation patterns.

bash
npx -y @inkog-io/cli scan .

Scan for Infinite Loops

Scan your AI agents for vulnerabilities. Free for developers.

Start Free Scan