Orchestrating several LLM agents that negotiate a task beats cramming every role into a single prompt. This autogen groupchat tutorial multiple agents shows how to stand up a working GroupChat with a coding assistant, a reviewer, and a user proxy that executes generated code. You’ll get runnable Python, the exact message flow to expect, and the knobs that matter in production.
Prerequisites
- Python 3.10 or newer.
pip install pyautogen(theautogenpackage, version 0.2.x).- An OpenAI-compatible API key. If you point AutoGen at n4n.ai’s single OpenAI-compatible endpoint, you get automatic fallback across 240+ models when a provider is rate-limited, without changing the code below.
Create a virtual environment and install:
python -m venv .venv
source .venv/bin/activate
pip install pyautogen
Set your key in the environment:
export OPENAI_API_KEY="sk-..."
LLM configuration
AutoGen agents take an llm_config dict that mirrors the OpenAI client params. Use a cheap model for the manager and a stronger one for the coder to save tokens.
import os
llm_config = {
"model": "gpt-4o-mini",
"api_key": os.environ["OPENAI_API_KEY"],
"temperature": 0.2,
# "base_url": "https://api.n4n.ai/v1", # uncomment to route through a gateway
}
If you use a gateway, keep the same dict shape. AutoGen forwards the request as an OpenAI chat completion, so any compliant endpoint works.
Define the agents
We need three participants: a UserProxyAgent that runs code, a coder assistant, and a reviewer assistant. The user proxy never asks for human input in this demo.
from autogen import AssistantAgent, UserProxyAgent
user = UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=10,
code_execution_config={"work_dir": "tmp", "use_docker": False},
)
coder = AssistantAgent(
name="coder",
llm_config=llm_config,
system_message="You are a senior Python engineer. Write concise, correct code. Reply with code blocks only when implementation is needed.",
)
reviewer = AssistantAgent(
name="reviewer",
llm_config=llm_config,
system_message="You are a strict code reviewer. Check for bugs, edge cases, and style. Approve or request changes succinctly.",
)
The code_execution_config tells the proxy to write files to tmp/ and run them locally. Disable Docker only for trusted, sandboxed dev boxes.
Build the GroupChat and Manager
A GroupChat holds the agent list and message history. A GroupChatManager uses an LLM to pick the next speaker when speaker_selection_method="auto".
from autogen import GroupChat, GroupChatManager
groupchat = GroupChat(
agents=[user, coder, reviewer],
messages=[],
max_round=12,
speaker_selection_method="auto",
)
manager = GroupChatManager(
groupchat=groupchat,
llm_config=llm_config,
)
max_round caps the total speaker turns. Without it, a chatty group can loop.
Run a task
Kick off the conversation by sending a message to the manager through the user proxy.
result = user.initiate_chat(
manager,
message="Write a script that prints all prime numbers under 50, then run it.",
)
Expected early output (abridged):
user_proxy (to chat_manager):
Write a script that prints all prime numbers under 50, then run it.
chat_manager (to coder):
Write a script that prints all prime numbers under 50, then run it.
coder (to chat_manager):
```python
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print([x for x in range(50) if is_prime(x)])
The manager then routes to `user_proxy`, which executes the block and posts stdout. The reviewer gets the next turn to critique.
user_proxy (to chat_manager):
exitcode: 0 (execution succeeded) Code output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
reviewer (to chat_manager):
Approved. Edge cases (0,1) handled correctly. Style is clean.
When the reviewer approves, the manager sees no pending action and the chat terminates after `max_round` or when a termination reply is detected. `result.token_count` gives total tokens spent.
## Control speaker selection
The default `"auto"` method asks the LLM to pick the next agent. For deterministic pipelines, use `"round_robin"`:
```python
groupchat = GroupChat(
agents=[user, coder, reviewer],
messages=[],
max_round=12,
speaker_selection_method="round_robin",
)
In this autogen groupchat tutorial multiple agents example, round-robin forces coder → user → reviewer in fixed order, which removes a model call for speaker selection.
For full programmatic control, subclass GroupChat and override select_speaker:
class MyGroupChat(GroupChat):
def select_speaker(self, last_speaker, selector):
if last_speaker == "coder":
return self.agents[0] # user_proxy
return self.agents[2] # reviewer
groupchat = MyGroupChat(
agents=[user, coder, reviewer],
messages=[],
max_round=12,
)
Stop conditions
AutoGen stops a group chat when max_round is hit or when any agent sends a message containing a termination string (default "TERMINATE"). Give the reviewer a system message that ends with If code is correct, reply "TERMINATE". and set allow_repeat_speaker=False to prevent loops.
reviewer = AssistantAgent(
name="reviewer",
llm_config=llm_config,
system_message="You are a strict code reviewer. If code is correct, reply 'TERMINATE'.",
)
Safe code execution
Running LLM-generated code is dangerous. In production:
- Set
use_docker=True(requires Docker daemon) or run in a locked-down VM. - Restrict
code_execution_configwithtimeout=30and avoid shared kernel state. - Filter which agents can trigger execution. Only the user proxy should hold
code_execution_config; assistants never get it.
user = UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
code_execution_config={
"work_dir": "tmp",
"use_docker": True,
"timeout": 30,
},
)
Common failure modes
Silent loops. If max_round is too high and no agent says TERMINATE, you burn tokens. Set it to twice the expected turns.
Wrong speaker picked. With speaker_selection_method="auto", the manager model may pick itself. Exclude the manager from agents—it is not a participant, only a coordinator.
Code exec errors swallowed. The user proxy prints exit code but continues. Check exitcode in the message and have the reviewer reject on non-zero.
Wrapping up
The pattern above is a minimal but real multi-agent pipeline: a generator, a critic, and an executor negotiating through a managed chat. Swap the coder for a planner and the reviewer for a tool-caller and you have a research agent. The autogen groupchat tutorial multiple agents approach scales to a dozen roles as long as you constrain rounds and execution.
Keep the manager model cheap, isolate code execution, and log speaker transitions. That’s the difference between a demo and a system you can ship.