LangChain max_iterations: Preventing Runaway Agents
max_iterations is a parameter on LangChain's AgentExecutor that limits how many reasoning steps the agent can take. Without it, the agent can loop indefinitely — calling tools, reasoning, and calling more tools until the context window is exhausted or the API rate limit is hit.
AgentExecutor Configuration
from langchain.agents import AgentExecutor
# No bounds set - dangerous in production!
executor = AgentExecutor.from_agent_and_tools(
agent=agent,
tools=tools,
verbose=True
)from langchain.agents import AgentExecutor
executor = AgentExecutor.from_agent_and_tools(
agent=agent,
tools=tools,
verbose=True,
max_iterations=10,
max_execution_time=60, # 60 second timeout
early_stopping_method="generate"
)Frequently Asked Questions
What happens if max_iterations is not set on AgentExecutor?
Without max_iterations, AgentExecutor will continue its think-act-observe cycle indefinitely. Each cycle makes an LLM API call. In production, this means unbounded API costs and potential service disruption until the context window (typically 4K-128K tokens) is exhausted.
What should I set max_iterations to?
Depends on your use case. For simple Q&A agents: 5-10. For research agents with multiple tools: 15-25. For complex multi-step workflows: 25-50. Always pair with max_execution_time as a secondary safeguard. Start low and increase based on observed needs.
What is max_execution_time in LangChain?
max_execution_time (in seconds) is a time-based bound complementing max_iterations. It catches cases where individual iterations are slow (e.g., tools making external API calls). Set both: max_iterations=10, max_execution_time=60.
What is early_stopping_method in LangChain?
When max_iterations is reached, early_stopping_method controls behavior: "force" immediately stops and returns, "generate" makes one final LLM call to generate a summary response. Use "generate" for user-facing agents.
How Inkog Detects This
Inkog identifies AgentExecutor instantiations without max_iterations or max_execution_time parameters. It also detects when these values are set unreasonably high (e.g., max_iterations=1000) which provides no practical protection.
npx -y @inkog-io/cli scan .