MaxIterationsReached
langchain.agents.agent.MaxIterationsReached
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
agent.run(input)
File "/usr/local/lib/python3.9/site-packages/langchain/agents/agent.py", line 210, in run
raise MaxIterationsReached(f"Agent stopped after {self.max_iterations} iterations.")
langchain.agents.agent.MaxIterationsReached: Agent stopped after 15 iterations. Why it happens
LangChain agents run in a loop to iteratively call tools or LLMs until a stopping condition is met. If the agent does not reach a conclusion within the configured max_iterations, it raises MaxIterationsReached to avoid infinite loops caused by ambiguous prompts or logic errors.
Detection
Monitor agent execution time and iteration count; catch MaxIterationsReached exceptions to log the input and intermediate steps causing the loop to exceed limits before failure.
Causes & fixes
The agent prompt or logic causes it to cycle without reaching a stopping condition.
Refine the prompt or tool outputs to ensure the agent can reach a final answer within fewer iterations.
max_iterations parameter is set too low for the complexity of the task.
Increase the max_iterations parameter when creating the agent to allow more steps before stopping.
Agent tools or callbacks produce outputs that confuse the agent, causing repeated loops.
Validate and sanitize tool outputs and intermediate agent steps to prevent loops caused by unexpected responses.
Code: broken vs fixed
from langchain.agents import initialize_agent, Tool
from langchain.llms import OpenAI
llm = OpenAI(temperature=0)
tools = [Tool(name="Search", func=lambda x: "irrelevant output")]
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", max_iterations=3)
# This will raise MaxIterationsReached if the agent loops too long
agent.run("Find the capital of France") import os
from langchain.agents import initialize_agent, Tool
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(temperature=0, model="gpt-4o-mini", openai_api_key=os.environ["OPENAI_API_KEY"])
tools = [Tool(name="Search", func=lambda x: "Paris is the capital of France")]
# Increased max_iterations to 10 to allow more steps
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", max_iterations=10)
result = agent.run("Find the capital of France")
print(result) # Should complete without MaxIterationsReached Workaround
Catch MaxIterationsReached exception around agent.run(), log intermediate steps, and retry with a higher max_iterations or simplified prompt.
Prevention
Design agent prompts and tools to produce clear stopping signals and set max_iterations sufficiently high for task complexity to avoid infinite loops.