How to Fix 'agent infinite loop during development' in AutoGen (Python)
Opening
agent infinite loop during development usually means your AutoGen agents keep handing control back and forth without ever reaching a terminating condition. In practice, you’ll see this when AssistantAgent and UserProxyAgent keep generating replies, tool calls, or reflections with no clear stop signal.
This shows up most often during local testing when you wire up multi-agent chat, enable auto-reply, or forget to cap max_turns, max_consecutive_auto_reply, or termination logic.
The Most Common Cause
The #1 cause is missing termination conditions in a conversation that can keep generating replies forever.
A common broken pattern is: one agent responds, the other agent responds, and neither side ever produces a message that AutoGen treats as terminal. In AutoGen Python, this often looks like an AssistantAgent paired with a UserProxyAgent where the proxy auto-replies indefinitely.
Broken vs fixed pattern
| Broken | Fixed |
|---|---|
| No termination condition | Explicit stop condition |
| Unlimited auto-replies | Bounded turns / reply count |
| Tool call loop never ends | Tool result leads to final answer |
# BROKEN
from autogen import AssistantAgent, UserProxyAgent
assistant = AssistantAgent(
name="assistant",
llm_config={"config_list": [{"model": "gpt-4o-mini", "api_key": "YOUR_KEY"}]},
)
user_proxy = UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=50, # still too high if no termination exists
)
user_proxy.initiate_chat(
assistant,
message="Write a Python function to validate an IBAN.",
)
# FIXED
from autogen import AssistantAgent, UserProxyAgent
def is_termination_msg(msg):
content = msg.get("content", "") if isinstance(msg, dict) else str(msg)
return "TERMINATE" in content
assistant = AssistantAgent(
name="assistant",
llm_config={"config_list": [{"model": "gpt-4o-mini", "api_key": "YOUR_KEY"}]},
)
user_proxy = UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=5,
is_termination_msg=is_termination_msg,
)
user_proxy.initiate_chat(
assistant,
message="Write a Python function to validate an IBAN. End with TERMINATE when done.",
)
If you’re using GroupChat, the same problem happens when no speaker transition rule forces an end state. A chat with multiple agents and no exit condition will just keep cycling.
Other Possible Causes
1) human_input_mode="NEVER" with no exit path
If the agent can’t ask a human for confirmation and there’s no termination message, it will keep auto-responding.
# Problematic
UserProxyAgent(
name="proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=100,
)
Fix it by lowering the cap and adding is_termination_msg.
# Safer
UserProxyAgent(
name="proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=3,
is_termination_msg=lambda m: "DONE" in (m.get("content", "") if isinstance(m, dict) else ""),
)
2) Tool/function calling returns non-terminal output forever
This happens when the tool result triggers another tool call instead of producing a final answer.
# Example of a looping tool response pattern
def lookup_policy(policy_id: str):
return {"status": "ok", "next_action": "lookup_policy"} # bad: recursive instruction
Make tool output factual and terminal.
def lookup_policy(policy_id: str):
return {"policy_id": policy_id, "status": "active", "premium_due": False}
3) max_round or max_turns not set on group chat
With GroupChatManager, you need hard limits. Otherwise speaker selection can continue indefinitely.
from autogen import GroupChat, GroupChatManager
groupchat = GroupChat(
agents=[assistant, user_proxy],
messages=[],
speaker_selection_method="round_robin",
)
manager = GroupChatManager(groupchat=groupchat)
Add limits:
groupchat = GroupChat(
agents=[assistant, user_proxy],
messages=[],
speaker_selection_method="round_robin",
max_round=6,
)
4) The model keeps rephrasing instead of finishing
Some prompts encourage endless refinement: “improve,” “iterate,” “make it better,” without asking for a final deliverable.
message = "Keep improving this answer until it's perfect."
Use an explicit completion contract:
message = (
"Produce one final answer only. "
"Do not ask follow-up questions. "
'End with the word "TERMINATE".'
)
How to Debug It
- •
Inspect the last 10 messages
- •Look for repeated tool calls, repeated acknowledgements, or answers that never contain a terminal token like
TERMINATE. - •If you see the same intent bouncing between agents, you’ve found the loop.
- •Look for repeated tool calls, repeated acknowledgements, or answers that never contain a terminal token like
- •
Lower the turn limit
- •Set
max_consecutive_auto_reply=2ormax_round=4. - •If the loop stops earlier with a clearer error trace, your issue is missing termination logic rather than a broken API call.
- •Set
- •
Log every agent reply
- •Print message content before AutoGen passes control onward.
- •You want to catch patterns like:
- •“I’ll check that.”
- •“Let me verify.”
- •“Calling tool again.”
- •No final answer ever produced.
- •
Disable tools temporarily
- •Remove function calling and rerun.
- •If the loop disappears, your tool schema or tool output is causing recursive behavior.
Example debug hook:
def debug_message(msg):
print("ROLE:", msg.get("role"))
print("CONTENT:", msg.get("content"))
Prevention
- •Always define one hard stop:
- •
is_termination_msg - •
max_consecutive_auto_reply - •
max_round
- •
- •Make your system prompt explicit:
- •“Return one final answer.”
- •“Do not continue unless more input is required.”
- •Treat tool outputs as data, not instructions.
- •Never return
"next_action"fields that tell the agent to call itself again unless you really mean to orchestrate recursion.
- •Never return
If you’re building production workflows for banking or insurance, assume every agent will loop unless you prove otherwise. Add termination rules first, then add autonomy second.
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