How to Fix 'agent infinite loop' in AutoGen (Python)
What the error means
agent infinite loop in AutoGen usually means your agent conversation never reaches a stopping condition, so the framework keeps routing messages forever. In practice, this shows up when AssistantAgent, UserProxyAgent, or a custom agent keeps replying without a termination signal, especially in initiate_chat() or group chat flows.
You’ll often see this after a few back-and-forth turns, then the run never ends until you kill the process or hit a max-iteration guard.
The Most Common Cause
The #1 cause is a missing or broken termination condition. In AutoGen, if your assistant keeps generating a response and your user proxy keeps auto-replying, you have created an endless loop.
Here’s the wrong pattern and the right pattern side by side:
| Broken pattern | Fixed pattern |
|---|---|
No termination check in is_termination_msg | Explicit stop condition on both sides |
human_input_mode="NEVER" with no exit token | Stop when the assistant emits "TERMINATE" |
| Unlimited auto-replies | Bounded max_consecutive_auto_reply |
# WRONG: no reliable stop condition
from autogen import AssistantAgent, UserProxyAgent
assistant = AssistantAgent(
name="assistant",
llm_config={"config_list": [{"model": "gpt-4o-mini"}]},
)
user_proxy = UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
code_execution_config=False,
)
user_proxy.initiate_chat(
assistant,
message="Summarize this policy document."
)
# RIGHT: explicit termination handling
from autogen import AssistantAgent, UserProxyAgent
def is_termination_msg(msg):
content = msg.get("content", "")
return isinstance(content, str) and content.strip().endswith("TERMINATE")
assistant = AssistantAgent(
name="assistant",
llm_config={"config_list": [{"model": "gpt-4o-mini"}]},
)
user_proxy = UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=5,
is_termination_msg=is_termination_msg,
code_execution_config=False,
)
user_proxy.initiate_chat(
assistant,
message="Summarize this policy document. End with TERMINATE."
)
If you’re using AutoGen’s standard chat loop, the assistant must know how to end. If you’re using a tool-calling setup, make sure tool results don’t keep re-triggering the same prompt without ever producing a terminal answer.
Other Possible Causes
1) Your system prompt encourages endless refinement
A common trap is asking the model to “keep improving until perfect” with no exit rule.
llm_config = {
"config_list": [{"model": "gpt-4o-mini"}],
}
assistant = AssistantAgent(
name="assistant",
system_message=(
"Keep revising the answer until it is perfect. "
"Do not stop unless you are fully satisfied."
),
llm_config=llm_config,
)
Fix it by adding an explicit completion rule:
assistant = AssistantAgent(
name="assistant",
system_message=(
"Answer once. If complete, end with TERMINATE. "
"Do not continue refining after that."
),
llm_config=llm_config,
)
2) GroupChat speaker selection keeps selecting the same agent
In GroupChat, a bad speaker_selection_method can bounce messages between agents forever.
from autogen import GroupChat, GroupChatManager
groupchat = GroupChat(
agents=[agent_a, agent_b],
messages=[],
speaker_selection_method="round_robin", # can loop if neither agent terminates
)
manager = GroupChatManager(groupchat=groupchat, llm_config=llm_config)
Fix by adding termination checks and limiting rounds:
groupchat = GroupChat(
agents=[agent_a, agent_b],
messages=[],
max_round=6,
)
manager = GroupChatManager(groupchat=groupchat, llm_config=llm_config)
3) Tool execution returns output that re-triggers the same request
This happens when an agent calls a tool, receives output, then asks for the same tool again because your prompt doesn’t distinguish “done” from “need more data”.
assistant = AssistantAgent(
name="assistant",
llm_config=llm_config,
)
user_proxy = UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
code_execution_config={"work_dir": "coding"},
)
A better pattern is to constrain tool usage and define completion clearly:
assistant = AssistantAgent(
name="assistant",
system_message="Use tools only once per task. Return final answer after tool output.",
llm_config=llm_config,
)
4) Your custom reply function always returns a response
If you override reply logic and never return None, AutoGen assumes there is always another message to send.
def reply_func(recipient, messages=None, sender=None, config=None):
return {"content": "Working on it..."} # never stops
Fix it by returning None when done:
def reply_func(recipient, messages=None, sender=None, config=None):
last = messages[-1]["content"]
if "TERMINATE" in last:
return None
return {"content": "Final answer. TERMINATE"}
How to Debug It
- •
Check whether termination is actually reachable
- •Search for
is_termination_msg,"TERMINATE", or equivalent stop logic. - •If you don’t have one, that’s likely your bug.
- •Search for
- •
Print every turn
- •Log sender name, recipient name, and message content.
- •You want to see whether the same two agents are repeating the same intent.
- •
Reduce to two agents
- •Remove tools, group chat managers, retrieval layers, and custom reply hooks.
- •If the loop disappears in a minimal setup, add pieces back one at a time.
- •
Inspect auto-reply settings
- •Look at
human_input_mode,max_consecutive_auto_reply, and any customreply_func. - •A common failure mode is
human_input_mode="NEVER"plus unlimited auto responses.
- •Look at
Prevention
- •Always define an explicit end condition:
- •Use
"TERMINATE"or a structured final message.
- •Use
- •Put hard limits on conversation length:
- •Set
max_consecutive_auto_replyandmax_round.
- •Set
- •Make prompts state completion rules:
- •“Answer once and stop” beats “keep iterating until perfect.”
If you want production-safe AutoGen flows in Python, treat termination as part of your protocol design. The model will not guess when your workflow is done unless you make that rule unambiguous.
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