MaxIterationsExceeded
llama_index.agent.max_iterations.MaxIterationsExceeded
Stack trace
llama_index.agent.max_iterations.MaxIterationsExceeded: Agent exceeded max iterations of 5
File "/app/llama_index/agent/agent.py", line 210, in run
raise MaxIterationsExceeded("Agent exceeded max iterations of 5") Why it happens
LlamaIndex agents run iterative reasoning loops to process queries. If the agent's stopping criteria are never met or the agent keeps generating new tasks indefinitely, it hits the max iterations limit to prevent infinite loops. This error signals that the agent logic or prompt is not converging.
Detection
Monitor agent run loops and catch MaxIterationsExceeded exceptions to log the iteration count and intermediate outputs, helping identify why the agent failed to stop.
Causes & fixes
Agent prompt or logic causes repeated cycles without reaching a stopping condition
Refine the prompt or agent logic to include clear stopping criteria or maximum steps to ensure convergence.
Max iterations parameter is set too low for the complexity of the task
Increase the max_iterations parameter in the agent configuration to allow more reasoning steps.
Agent is stuck due to ambiguous or conflicting instructions in the prompt
Simplify and clarify the prompt instructions to avoid ambiguous loops and ensure the agent can decide to stop.
Code: broken vs fixed
from llama_index import LLMPredictor, ServiceContext, GPTVectorStoreIndex, Agent
agent = Agent(max_iterations=5) # Too low max iterations
response = agent.run("Explain the process in detail") # This line raises MaxIterationsExceeded
print(response) import os
from llama_index import LLMPredictor, ServiceContext, GPTVectorStoreIndex, Agent
os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY') # Use env var for API key
agent = Agent(max_iterations=10) # Increased max iterations to allow more steps
response = agent.run("Explain the process in detail with clear stopping criteria") # Fixed prompt and config
print(response) # Should complete without error Workaround
Catch MaxIterationsExceeded in a try/except block, log the partial outputs, and optionally retry with a higher max_iterations or a simplified prompt.
Prevention
Design agent prompts with explicit stopping criteria and set a reasonable max_iterations limit based on task complexity to avoid infinite loops.