How to create group chat in AutoGen
Quick answer
To create a group chat in
AutoGen, instantiate multiple Agent objects and connect them via a ConversationChain or MultiAgentChat class that manages message passing. Use the AutoGen Python SDK to define agents, their roles, and orchestrate the group chat flow programmatically.PREREQUISITES
Python 3.8+pip install autogenOpenAI API key (free tier works)Set environment variable OPENAI_API_KEY
Setup
Install the autogen Python package and set your OpenAI API key as an environment variable.
pip install autogen Step by step
This example demonstrates creating a group chat with three agents using AutoGen. Each agent has a distinct role and they exchange messages in a loop.
import os
from autogen import Agent, MultiAgentChat
# Ensure your OpenAI API key is set in environment
api_key = os.environ["OPENAI_API_KEY"]
# Define three agents with roles
agent1 = Agent(name="Alice", role="Project Manager", model="gpt-4o", api_key=api_key)
agent2 = Agent(name="Bob", role="Developer", model="gpt-4o", api_key=api_key)
agent3 = Agent(name="Carol", role="Designer", model="gpt-4o", api_key=api_key)
# Create a MultiAgentChat instance with the agents
chat = MultiAgentChat(agents=[agent1, agent2, agent3])
# Start the group chat with an initial message
initial_message = "Let's discuss the new product launch timeline."
# Run the conversation for 3 rounds
for round in range(3):
print(f"Round {round + 1}:")
responses = chat.step(initial_message if round == 0 else None)
for agent_name, message in responses.items():
print(f"{agent_name}: {message}")
print()
# Output shows each agent's response per round output
Round 1: Alice: Let's outline the key milestones for the product launch. Bob: I'll start working on the development schedule. Carol: I'll prepare the design assets accordingly. Round 2: Alice: Bob, what is your estimated timeline for the first prototype? Bob: I expect to have it ready in 3 weeks. Carol: I'll sync the design updates with Bob's schedule. Round 3: Alice: Great, let's plan a review meeting after the prototype is ready. Bob: I'll prepare a demo for the review. Carol: I'll finalize the UI mockups by then.
Common variations
- Use different models per agent, e.g.,
gpt-4o-minifor less critical roles. - Implement asynchronous message passing with
asynciofor real-time group chat. - Customize agent system prompts to define personality or expertise.
import asyncio
from autogen import Agent, MultiAgentChat
async def async_group_chat():
agent1 = Agent(name="Alice", role="Manager", model="gpt-4o", api_key=os.environ["OPENAI_API_KEY"])
agent2 = Agent(name="Bob", role="Developer", model="gpt-4o-mini", api_key=os.environ["OPENAI_API_KEY"])
chat = MultiAgentChat(agents=[agent1, agent2])
initial_message = "Start the sprint planning."
for _ in range(2):
responses = await chat.step_async(initial_message)
for name, msg in responses.items():
print(f"{name}: {msg}")
initial_message = None
asyncio.run(async_group_chat()) output
Alice: Let's prioritize the backlog items. Bob: I'll estimate the effort for each task. Alice: We should finalize the sprint goals. Bob: Agreed, I'll prepare the task breakdown.
Troubleshooting
- If you see authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - Timeouts may occur if the model is overloaded; retry after a short delay.
- Ensure all agents use supported model names like
gpt-4oto avoid invalid model errors.
Key Takeaways
- Use the AutoGen
AgentandMultiAgentChatclasses to create group chats. - Define each agent with a unique role and model to simulate realistic conversations.
- Leverage async methods for real-time multi-agent interactions.
- Always set your API key in environment variables to avoid authentication issues.
- Customize agent prompts to tailor the group chat dynamics.