How to Fix 'agent infinite loop' in LangChain (Python)
If you’re seeing agent infinite loop in LangChain, it usually means the agent kept calling tools or re-planning without ever reaching a final answer. In practice, this shows up when the agent has no valid exit path, keeps getting bad tool outputs, or is configured to allow too many iterations.
This is almost always a control-flow problem, not a model problem.
The Most Common Cause
The #1 cause is a tool that returns something the agent cannot use to finish, combined with an agent prompt that keeps encouraging more tool use. In LangChain Python, this often appears as:
- •
AgentExecutorhittingmax_iterations - •
OutputParserException - •repeated
Action:/Observation:cycles - •logs showing the same tool being called over and over
Here’s the broken pattern:
| Broken | Fixed |
|---|---|
| Tool returns unstructured text that never helps the agent answer | Tool returns structured, bounded output |
| Agent has no clear stop condition | Agent can produce a final answer after one tool call |
# BROKEN
from langchain.agents import initialize_agent, AgentType
from langchain.tools import Tool
from langchain_openai import ChatOpenAI
def lookup_customer(query: str) -> str:
# Returns noisy text that encourages more reasoning
return f"Customer found. Raw record: {query}. Try searching again if unsure."
tools = [
Tool(
name="lookup_customer",
func=lookup_customer,
description="Look up customer data"
)
]
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
max_iterations=10,
)
print(agent.run("Find customer 123 and summarize their status"))
# FIXED
from langchain.agents import initialize_agent, AgentType
from langchain.tools import Tool
from langchain_openai import ChatOpenAI
def lookup_customer(query: str) -> str:
# Return compact, final-useful data only
return "customer_id=123,status=active,risk=low,last_contact=2024-10-12"
tools = [
Tool(
name="lookup_customer",
func=lookup_customer,
description="Return one-line customer summary in key=value format"
)
]
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
max_iterations=3,
)
print(agent.run("Find customer 123 and summarize their status"))
The key fix is not “add more iterations.” It’s making the tool output useful enough that the LLM can stop.
Other Possible Causes
1) The tool description is too vague
If the model does not know when to use the tool, it may keep trying different paths.
# BAD
Tool(
name="policy_search",
func=policy_search,
description="Search policies"
)
# GOOD
Tool(
name="policy_search",
func=policy_search,
description="Use once to fetch a policy by exact policy_id. Do not use for general questions."
)
2) Your prompt encourages endless reasoning
A prompt like “keep searching until you are fully certain” is a loop generator.
# BAD prompt fragment
"""
You must continue using tools until you are completely certain.
Never answer unless every detail is verified.
"""
# GOOD prompt fragment
"""
Use at most one tool call per question unless new evidence appears.
If the tool result is sufficient, provide a final answer.
"""
3) The model cannot parse your tool output
This often happens with malformed JSON or inconsistent formatting. You may see OutputParserException or repeated retries.
# BAD: invalid JSON-ish output
return "{status: active, risk: low}"
# GOOD: valid JSON string or structured dict depending on your setup
return '{"status":"active","risk":"low"}'
If you’re using structured tools or function calling, keep outputs deterministic and schema-aligned.
4) max_iterations is masking a deeper bug
A higher limit does not fix a loop; it just delays failure. You’ll often see:
- •
Agent stopped due to iteration limit or time limit.
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
max_iterations=25, # hides the issue longer
)
Lowering it during debugging makes the loop obvious faster.
How to Debug It
- •
Turn on verbose tracing
- •Set
verbose=TrueonAgentExecutor. - •Watch whether the same tool is called repeatedly with similar inputs.
- •If you see repeated
Action:lines with no meaningful change, you have a loop.
- •Set
- •
Inspect the exact failure mode
- •If you see
OutputParserException, your model output format is breaking parsing. - •If you see
Agent stopped due to iteration limit or time limit, your agent never reached a final answer. - •If you see repeated tool calls with similar arguments, your prompt/tool design is causing recursion-like behavior.
- •If you see
- •
Log raw tool input/output
- •Print every tool argument and response.
- •Look for empty strings, vague text, malformed JSON, or responses that ask the agent to “search again.”
def lookup_customer(query: str) -> str:
print("TOOL INPUT:", query)
result = "customer_id=123,status=active,risk=low"
print("TOOL OUTPUT:", result)
return result
- •Reduce the problem
- •Remove all but one tool.
- •Use a minimal prompt.
- •Set
max_iterations=2. - •If the loop disappears, add components back one by one until it returns.
Prevention
- •Keep tool outputs short, structured, and directly useful for the final answer.
- •Write tool descriptions with explicit usage boundaries: what it does and when not to call it.
- •Add guardrails in prompts:
- •maximum number of tool calls
- •when to stop and answer
- •what counts as sufficient evidence
If you’re building production agents for banking or insurance workflows, treat infinite loops as a design bug. Fix them at the agent contract level: better tools, tighter prompts, lower iteration ceilings during testing, and strict output schemas.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit