AutoGen Tutorial (Python): debugging agent loops for intermediate developers
This tutorial shows you how to debug AutoGen agent loops in Python by making the loop visible, bounded, and testable. You need this when agents keep repeating themselves, fail to terminate, or silently drift into useless back-and-forth without producing a final answer.
What You'll Need
- •Python 3.10+
- •
pyautogeninstalled - •An OpenAI API key exported as
OPENAI_API_KEY - •A terminal or shell for running the script
- •Basic familiarity with
AssistantAgent,UserProxyAgent, andinitiate_chat
Step-by-Step
- •Start with a minimal loop you can reproduce.
If you cannot reproduce the bad behavior in a tiny script, you cannot debug it reliably.
import os
import autogen
config_list = [
{
"model": "gpt-4o-mini",
"api_key": os.environ["OPENAI_API_KEY"],
}
]
llm_config = {
"config_list": config_list,
"temperature": 0,
}
assistant = autogen.AssistantAgent(
name="assistant",
llm_config=llm_config,
)
user = autogen.UserProxyAgent(
name="user",
human_input_mode="NEVER",
max_consecutive_auto_reply=5,
code_execution_config=False,
)
user.initiate_chat(
assistant,
message="Explain why agent loops happen in AutoGen and give one fix.",
)
- •Add explicit termination rules.
Most looping issues come from vague prompts and no stopping condition. Make the assistant know exactly when to stop.
assistant = autogen.AssistantAgent(
name="assistant",
llm_config=llm_config,
system_message=(
"You are a debugging assistant. "
"Answer directly and stop after one complete response. "
"If the task is solved, end with 'DONE'."
),
)
user = autogen.UserProxyAgent(
name="user",
human_input_mode="NEVER",
max_consecutive_auto_reply=3,
code_execution_config=False,
)
result = user.initiate_chat(
assistant,
message="Give me three reasons an AutoGen agent may loop forever.",
)
print(result)
- •Inspect every turn with a custom reply hook.
When loops happen, you want to see what each agent received and sent before they repeat the same pattern.
def log_messages(recipient, messages, sender, config):
last = messages[-1]
print("\n--- DEBUG TURN ---")
print("From:", sender.name)
print("To:", recipient.name)
print("Content:", last.get("content", "")[:500])
return False, None
assistant.register_reply([autogen.Agent, None], log_messages)
user.initiate_chat(
assistant,
message="Trace this conversation and show where repetition starts.",
)
- •Put a hard ceiling on conversation length.
Even good prompts can fail under edge cases, so enforce a maximum number of turns in code instead of trusting the model to behave.
chat_result = user.initiate_chat(
assistant,
message="Find the root cause of an infinite AutoGen loop.",
)
print("Conversation finished.")
print("Summary object:", chat_result)
if hasattr(chat_result, "chat_history"):
print("Turns:", len(chat_result.chat_history))
- •Reduce the problem to a deterministic test case.
Once you have logging and limits, isolate the exact prompt that causes repetition and run it repeatedly while changing one variable at a time.
test_prompts = [
"Explain one cause of looping in AutoGen.",
"Explain one cause of looping in AutoGen and stop.",
]
for prompt in test_prompts:
print("\n=== TEST PROMPT ===")
print(prompt)
user.initiate_chat(assistant, message=prompt)
Testing It
Run the script and watch for repeated assistant responses, identical phrasing across turns, or conversations that exceed your expected turn count. If your termination rule works, the assistant should end with a clear final response instead of asking follow-up questions forever.
A good test is to compare behavior before and after adding max_consecutive_auto_reply, a strict system message, and logging. If the loop still happens, your issue is usually in tool execution, missing termination criteria, or a second agent re-injecting the same task.
Next Steps
- •Add structured termination checks using message content rules like
"DONE"or JSON status fields. - •Learn how to debug tool-calling loops caused by repeated function failures.
- •Build a reusable chat wrapper that logs turns, enforces limits, and stores transcripts for regression tests.
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