AutoGen: AgentChat, Teams, Termination and Tools Reference Guide
By DevShelfHub
AgentChat, Core, Extensions — agents, teams, termination, tools, and the modern v0.4+ async API. Covers AssistantAgent, RoundRobinGroupChat, SelectorGroupChat, and the autogen_ext model clients for OpenAI, Anthropic, and Ollama.
AutoGen 0.4 is a rewrite of the legacy 0.2 series — everything is async, the package
is split (autogen-core,
autogen-agentchat, autogen-ext),
and the import root is now autogen_agentchat (not
autogen). The old pyautogen
package on PyPI is 0.2.x. Names current as of May 2026.
install · extensions · studioSetup
bash
# v0.4+ layered packages — install what you need
pip install -U "autogen-agentchat" # high-level multi-agent API
pip install -U "autogen-core" # actor model primitives
pip install -U "autogen-ext[openai]" # provider extension (openai, anthropic, ollama, ...)
pip install -U "autogen-ext[docker]" # sandboxed code-execution
# Studio (visual builder, optional)
pip install -U "autogenstudio"
autogenstudio ui --port 8081
# env — pick the provider matching your extension
export OPENAI_API_KEY=sk-...
export ANTHROPIC_API_KEY=sk-...
where things liveCommon imports
High-level multi-agent API in autogen_agentchat. Provider clients +
extensions in autogen_ext.*. Lower-level actor model in
autogen_core.
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent, CodeExecutorAgent
Built-in agent classes.
from autogen_agentchat.teams import RoundRobinGroupChat, SelectorGroupChat, Swarm, MagenticOneGroupChat
Team patterns.
from autogen_agentchat.conditions import TextMentionTermination, MaxMessageTermination, ExternalTermination, TokenUsageTermination
Stop conditions.
from autogen_agentchat.messages import TextMessage, ToolCallSummaryMessage, HandoffMessage
Message classes.
from autogen_agentchat.ui import Console
Pretty-prints a run stream.
from autogen_ext.models.openai import OpenAIChatCompletionClient, AzureOpenAIChatCompletionClient
OpenAI / Azure client.
from autogen_ext.models.anthropic import AnthropicChatCompletionClient
Anthropic client.
from autogen_ext.models.ollama import OllamaChatCompletionClient
Local via Ollama.
from autogen_ext.tools.mcp import McpWorkbench, StdioServerParams
Wrap MCP servers as tools.
from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor
Sandboxed Python in Docker.
from autogen_core import CancellationToken, MessageContext, RoutedAgent, message_handler
Human-in-the-loop. input_func can be sync or async.
CodeExecutorAgent(name, code_executor=…)
Runs Python / shell from messages.
await agent.run(task="…")
One-shot. Returns TaskResult.
agent.run_stream(task="…")
Async iterator of events + messages.
await agent.on_messages(messages, ct)
Lower-level entry. Used inside teams.
python
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
def get_weather(city: str) -> str:
"""Look up current weather for a city."""
return f"{city}: 22 C, clear."
async def main() -> None:
model = OpenAIChatCompletionClient(model="gpt-4o-mini")
agent = AssistantAgent(
name="weather_bot",
model_client=model,
tools=[get_weather],
system_message="Use tools when the user asks about weather.",
reflect_on_tool_use=True,
)
# Console wraps run_stream and prints to stdout.
await Console(agent.run_stream(task="What's the weather in Paris?"))
await model.close()
asyncio.run(main())
multi-agent orchestrationTeams
RoundRobinGroupChat([a, b, c])
Speakers rotate. Predictable, cheap.
SelectorGroupChat([…], model_client=…)
An LLM picks the next speaker each turn.
SelectorGroupChat(…, selector_func=fn)
Override selection with custom code.
Swarm([…], …)
Agents pass control via HandoffMessage.
MagenticOneGroupChat([…], model_client=…)
Plan-track-replan orchestrator. Good for open-ended tasks.
team.run(task="…")
One-shot. Returns TaskResult.
team.run_stream(task="…")
Stream events while the team runs.
await Console(team.run_stream(…))
Pretty-print to stdout.
await team.reset()
Wipe state between runs.
await team.save_state() / load_state(state)
Persist + resume between processes.
python
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination, MaxMessageTermination
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
async def main() -> None:
model = OpenAIChatCompletionClient(model="gpt-4o-mini")
writer = AssistantAgent("writer", model, system_message="Draft concise posts.")
editor = AssistantAgent(
"editor", model,
system_message="Critique drafts. When the post is ready, reply with 'APPROVE'.",
)
termination = TextMentionTermination("APPROVE") | MaxMessageTermination(6)
team = RoundRobinGroupChat([writer, editor], termination_condition=termination)
await Console(team.run_stream(task="Write a 100-word post on vector databases."))
await model.close()
asyncio.run(main())
when to stopTermination
TextMentionTermination("APPROVE")
Stop when any message contains the string.
MaxMessageTermination(max_messages=10)
Hard cap on message count.
TokenUsageTermination(max_total_token=2000)
Cap by tokens.
ExternalTermination()
Triggered from outside via .set(). Useful for HITL.
SourceMatchTermination(["reviewer"])
Stop after a named agent speaks.
FunctionCallTermination(function_name=…)
Stop when a specific tool is called.
cond_a | cond_b
Combine with | (or) and & (and).
Always pin a termination condition. Teams without one will loop until they hit the model’s context cap —
expensive and confusing.
give agents capabilityTools
def fn(arg: int) -> str: …
Bare function works. Docstring + type hints are the schema.
async def fn(…) -> …:
Async tools are fine. Awaited inside agent loop.
FunctionTool(fn, description=…, name=…)
Wrap with explicit metadata when needed.
McpWorkbench(server_params=StdioServerParams(…))
Expose every tool from an MCP server.
workbench=McpWorkbench(…)
Pass to AssistantAgent(workbench=…) instead of tools.
tools=[a, b, c]
Multiple bare functions / FunctionTool / LangChain Tool objects.
Required for Docker / Jupyter executors before use.
CodeExecutorAgent("exec", code_executor=…)
Drop into a team as a code-runner participant.
research → write → reviewEnd-to-end · SelectorGroupChat team
Three agents, one shared model client, dynamic selector, terminate on “APPROVE”. Streams to the console.
python
# Research + write team with web tool, selector chat, and termination on approval.
import asyncio
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
from autogen_agentchat.teams import SelectorGroupChat
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
async def web_search(query: str) -> str:
"""Return summaries for the top N results."""
return f"[stub] results for: {query}"
async def main() -> None:
model = OpenAIChatCompletionClient(model="gpt-4o-mini")
researcher = AssistantAgent(
"researcher", model, tools=[web_search],
system_message="Find 3 primary sources. Cite each.",
)
writer = AssistantAgent(
"writer", model,
system_message="Turn research into a 200-word post. End drafts with 'DRAFT_READY'.",
)
reviewer = AssistantAgent(
"reviewer", model,
system_message="Approve or revise. When happy, reply 'APPROVE'.",
)
team = SelectorGroupChat(
participants=[researcher, writer, reviewer],
model_client=model,
termination_condition=TextMentionTermination("APPROVE"),
)
await Console(team.run_stream(task="Post on Postgres pgvector in 2026."))
await model.close()
asyncio.run(main())
Best practiceGood to know
Share a single model client across agents.
Build one OpenAIChatCompletionClient and pass it into each
AssistantAgent. Pools HTTP connections, simplifies close().
Stream with Console(team.run_stream(…)) during dev.
You see speaker selection, tool calls, and final output as they happen. Switch to
.run() for prod.
Use save_state / load_state for HITL.
Serialise the team between turns; pair with ExternalTermination to pause
for human input without holding the event loop.
Common trapsWatch out for
0.2 (pyautogen) vs 0.4 (autogen-agentchat) are different APIs.
Don’t mix tutorials. The 0.2 AssistantAgent + GroupChatManager
pattern does not work in 0.4. Default to 0.4+ for new work.
Always close model clients.
Otherwise the HTTP pool leaks and asyncio.run hangs at shutdown. Pattern:
try / finally: await model.close().
Don’t let agents pick endlessly.
A SelectorGroupChat with no termination + similar-goal agents will round-
robin politely until the wallet is empty. Pin MaxMessageTermination as a
backstop.
AutoGen is an open-source multi-agent framework built by Microsoft Research. Version 0.4+ is a full rewrite with an async-first design, split into autogen-core, autogen-agentchat, and autogen-ext packages. It lets you build teams of AI agents that collaborate to complete tasks.
How do I create an agent in AutoGen 0.4?
Create an AssistantAgent with a name, model_client, and optional tools list. The model_client can be any provider — OpenAI, Azure, Anthropic, or Ollama via autogen_ext. Add a system_message to define the agent's persona and capabilities.
What is the difference between AutoGen 0.2 and AutoGen 0.4?
AutoGen 0.4 is a complete rewrite. It is fully async, uses split packages (autogen-agentchat, autogen-core, autogen-ext), and replaces the old pyautogen package. The import root changed from autogen to autogen_agentchat, and the API is not backwards-compatible.
How do I build a multi-agent team in AutoGen?
Wrap agents in a RoundRobinGroupChat or SelectorGroupChat with a termination condition such as TextMentionTermination('TERMINATE') or MaxMessageTermination(10). Call await team.run(task='...') to start the conversation and await Console(team.run_stream(...)) to stream output.
What LLMs does AutoGen support?
AutoGen supports OpenAI (GPT-4o, GPT-4o-mini), Azure OpenAI, Anthropic Claude, and local models via Ollama — all through provider-specific client classes in autogen_ext.models. Each agent gets its own model_client, so a team can mix providers.
How does tool use work in AutoGen?
Define tools as Python functions decorated with @FunctionTool or pass a list of callables to AssistantAgent(tools=[...]). AutoGen automatically generates the JSON Schema from type hints and docstrings. The agent decides when to call tools and receives results automatically.