Orchestrating Multi-Agent Collaboration and Communication Patterns in MetaGPT

MetaGPT implements a plug-and-play multi-agent framework where a Team hosts Roles that interact through a shared Environment, using message routing and reaction cycles to coordinate complex workflows.

MetaGPT provides a structured approach to orchestrating multi-agent collaboration and communication patterns through its core abstraction layers. The framework isolates agent definition, group orchestration, and message transport into distinct components that work together to enable sophisticated multi-agent workflows. Understanding these patterns is essential for building reliable agent teams that can execute complex software engineering tasks.

Core Architecture: Team, Role, and Environment

MetaGPT organizes multi-agent systems around three primary concerns, each handled by a dedicated class:

Concern Core Class Responsibilities
Agent Definition Role (metagpt/roles/role.py) Encapsulates an agent's persona, goal, actions, memory, and reaction strategy (React, By-Order, or Plan-And-Act).
Group Orchestration Team (metagpt/team.py) Holds the collection of roles, manages budget investment, launches projects, and drives the execution loop via run.
Message Transport Environment (metagpt/environment/base_env.py) Registers roles, distributes Message objects, tracks global history, and archives project state.

Agent Definition with Role

The Role class serves as the fundamental building block for agents. Each role maintains a private MessageQueue (rc.msg_buffer) and short-term memory (rc.memory) that stores recent observations. Roles declare their capabilities by registering Action subclasses via set_actions(), and define their interests through the _watch() method, which filters incoming messages by their source type.

Group Orchestration with Team

The Team class acts as the conductor for multi-agent workflows. It maintains a registry of hired roles and manages the execution budget through an investment model. The run_project() method injects the initial user requirement into the environment as a Message, while the main run() loop coordinates round-based execution until completion or budget exhaustion.

Message Transport with Environment

The Environment provides the shared communication bus for all agents. It maintains a registry of active roles and handles message routing through publish_message(). The environment tracks global message history and provides archival capabilities for post-execution analysis.

The React Cycle: How Agents Observe, Think, and Act

MetaGPT implements a standardized reaction cycle within the Role class that enables agents to process information and take action. The run() method in metagpt/roles/role.py executes this cycle up to rc.max_react_loop times (defaulting to 1) per activation.

Observation and Memory

The cycle begins with observation. The role pulls new messages from its private MessageQueue (rc.msg_buffer) and filters them according to its watch list (rc.watch). Only messages matching the watch criteria are stored in short-term memory (rc.memory). This filtering mechanism ensures agents only process relevant information, reducing noise and computational overhead.

Thinking Strategies

The thinking phase depends on the role's react_mode setting:

  • React Mode (REACT): The role uses LLM prompting to select the next action dynamically based on current memory context. The _think() method generates reasoning about which action to take.
  • By-Order Mode (BY_ORDER): The role executes registered actions sequentially without LLM deliberation, useful for deterministic workflows.
  • Plan-And-Act Mode (PLAN_AND_ACT): The role first constructs a task plan using the Planner component, then executes actions according to that plan, enabling complex multi-step reasoning.

Action Execution

In the action phase, the role executes the chosen Action subclass. The action receives context from memory and returns an ActionOutput or Message. This result is written back into the role's memory and published to the environment for other agents to observe. The _act() method handles this execution and publication logic.

Source: Role._react, Role._think, Role._act in metagpt/roles/role.py.

Message Routing and Communication Patterns

MetaGPT's communication system relies on the Message class (metagpt/schema.py) which carries routing metadata including send_to, cause_by, and sent_from fields. The Environment class manages message distribution through sophisticated routing logic.

Directed Messaging

When a role calls publish_message(), the Environment iterates over all registered roles and delivers the message only to those whose address set matches the routing tag (is_send_to). This enables targeted communication where specific agents receive specific messages based on their identifiers or roles.

Broadcast Patterns

The framework supports broadcast communication through special routing constants:

  • Broadcast to All: Using MESSAGE_ROUTE_TO_ALL (represented as {"All"}) sends messages to all registered agents.
  • Self-Routing: When a message is addressed to the sender itself (MESSAGE_ROUTE_TO_SELF), the framework rewrites the routing set to include the sender's identifier, enabling self-feedback loops and iterative refinement.

Agents filter incoming broadcasts through their watch lists, ensuring they only react to relevant message types regardless of the routing method.

Source: Environment.publish_message in metagpt/environment/base_env.py.

Team Execution Loop

The Team class orchestrates the overall execution flow through its run method in metagpt/team.py. This method implements the main coordination loop that drives multi-agent collaboration.

async def run(self, n_round=3, idea="", send_to="", auto_archive=True):
    if idea:
        self.run_project(idea, send_to)
    while n_round > 0:
        if self.env.is_idle:
            break
        self._check_balance()
        await self.env.run()       # parallel role.run() for all active agents

        n_round -= 1
    self.env.archive(auto_archive)
    return self.env.history

The execution flow follows these steps:

  1. Project Initialization: If an idea is provided, run_project injects the initial user requirement as a Message into the environment.
  2. Round-Based Execution: The loop continues for n_round iterations or until the environment becomes idle (all agents finished).
  3. Budget Monitoring: _check_balance verifies that the cost manager hasn't exceeded the allocated investment, aborting execution if funds are depleted.
  4. Parallel Scheduling: env.run() schedules all non-idle roles concurrently using asyncio.gather, enabling parallel collaboration while preserving deterministic ordering within each role's react loop.
  5. Archival: Upon completion, the environment archives the project history for later analysis.

Common Collaboration Patterns in MetaGPT

MetaGPT supports several distinct collaboration patterns that can be combined to build complex workflows:

Pattern Implementation Example
Sequential Hand-off Roles watch for messages from specific predecessors using _watch(). Creates a pipeline where each agent handles a specific phase. SimpleCoder → SimpleTester → SimpleReviewer in the custom multi-agent example.
Broadcast & Selective Consumption Roles broadcast to MESSAGE_ROUTE_TO_ALL; recipients filter by watch list. Enables pub-sub architectures. Agents listening for high-level objectives while ignoring implementation details.
Parallel Exploration Multiple roles with independent watch sets run concurrently in the same round. Each generates alternative solutions. Engineer, Architect, and DataAnalyst working on design tasks simultaneously.
Dynamic Plan-and-Act Using react_mode == PLAN_AND_ACT, roles construct task graphs with the Planner component before execution. ProjectManager planning subtasks before delegating to specialist roles.

Memory and State Management

MetaGPT implements a tiered memory system that enables agents to maintain context across interactions:

Short-term memory (rc.memory) stores recent messages for the current reasoning step. During the _think phase, roles query this memory using self.rc.memory.get() to retrieve relevant context for decision-making. Important items can be extracted via self.rc.important_memory for prioritized processing.

Long-term memory (RoleZeroLongTermMemory in metagpt/memory/role_zero_memory.py) provides optional persistence across projects. This enables agents to retain knowledge from previous executions and apply learned patterns to new tasks.

The memory system integrates with the react cycle, ensuring that agents have access to historical context when selecting actions or generating plans.

Source: RoleContext.memory definition in metagpt/roles/role.py.

Building a Custom Multi-Agent Team

The following example demonstrates how to construct a three-agent pipeline using MetaGPT's collaboration primitives:


# examples/build_customized_multi_agents.py

import fire
from metagpt.actions import Action, UserRequirement
from metagpt.logs import logger
from metagpt.roles import Role
from metagpt.schema import Message
from metagpt.team import Team

class SimpleWriteCode(Action):
    PROMPT_TEMPLATE = """
    Write a python function that can {instruction}.
    Return ```python your_code_here ``` with NO other texts,
    your code:
    """
    async def run(self, instruction: str):
        rsp = await self._aask(self.PROMPT_TEMPLATE.format(instruction=instruction))
        return rsp.split("```python")[1].split("```")[0].strip()

class SimpleCoder(Role):
    name = "Alice"
    profile = "SimpleCoder"
    def __init__(self, **kw):
        super().__init__(**kw)
        self._watch([UserRequirement])
        self.set_actions([SimpleWriteCode])

class SimpleWriteTest(Action):
    PROMPT_TEMPLATE = """
    Context: {context}
    Write {k} unit tests using pytest for the given function.
    Return ```python your_code_here ``` with NO other texts,
    your code:
    """
    async def run(self, context: str, k: int = 3):
        rsp = await self._aask(self.PROMPT_TEMPLATE.format(context=context, k=k))
        return rsp.split("```python")[1].split("```")[0].strip()

class SimpleTester(Role):
    name = "Bob"
    profile = "SimpleTester"
    def __init__(self, **kw):
        super().__init__(**kw)
        self._watch([SimpleWriteCode])
        self.set_actions([SimpleWriteTest])

class SimpleWriteReview(Action):
    PROMPT_TEMPLATE = """Context: {context}
    Review the test cases and provide one critical comment:"""
    async def run(self, context: str):
        return await self._aask(self.PROMPT_TEMPLATE.format(context=context))

class SimpleReviewer(Role):
    name = "Charlie"
    profile = "SimpleReviewer"
    def __init__(self, **kw):
        super().__init__(**kw)
        self._watch([SimpleWriteTest])
        self.set_actions([SimpleWriteReview])

async def main(
    idea: str = "write a function that calculates the product of a list",
    investment: float = 3.0,
    n_round: int = 5,
    add_human: bool = False,
):
    team = Team()
    team.hire([SimpleCoder(), SimpleTester(), SimpleReviewer(is_human=add_human)])
    team.invest(investment)
    team.run_project(idea)
    await team.run(n_round=n_round)

if __name__ == "__main__":
    fire.Fire(main)

This example illustrates three key collaboration primitives:

  • Watch lists (self._watch([...])) form a directed collaboration graph, ensuring agents only react to relevant message types.
  • Action registration (self.set_actions([...])) determines each role's capabilities and available tools.
  • Team orchestration handles the execution loop, budget management, and message distribution across all agents.

Source: examples/build_customized_multi_agents.py in the MetaGPT repository.

Summary

MetaGPT provides a robust framework for orchestrating multi-agent collaboration and communication patterns through three core abstractions:

  • Role (metagpt/roles/role.py) encapsulates agent behavior, memory, and reaction strategies (React, By-Order, Plan-And-Act).
  • Team (metagpt/team.py) manages the execution loop, parallel scheduling, and budget constraints across multiple roles.
  • Environment (metagpt/environment/base_env.py) handles message routing, role registration, and shared state management.

The framework supports diverse collaboration patterns including sequential pipelines, broadcast messaging, parallel exploration, and dynamic planning through configurable watch lists and reaction modes.

Frequently Asked Questions

How does MetaGPT handle message routing between agents?

MetaGPT routes messages through the Environment class in metagpt/environment/base_env.py. When a role calls publish_message(), the environment iterates over registered roles and delivers the message only to agents whose address set matches the send_to field. The framework supports directed messaging to specific roles, broadcasting to MESSAGE_ROUTE_TO_ALL, and self-routing via MESSAGE_ROUTE_TO_SELF for feedback loops.

What are the different reaction modes available in MetaGPT?

MetaGPT supports three reaction modes defined in metagpt/roles/role.py: React (dynamic LLM-based action selection), By-Order (sequential execution of registered actions), and Plan-And-Act (construction of a task plan before execution). The mode is set via set_react_mode() and determines how the _think() method selects actions during the react cycle.

How does the Team execution loop manage parallel agent execution?

The Team.run() method in metagpt/team.py executes agents concurrently using asyncio.gather via env.run(). In each round, the environment schedules all non-idle roles to run their react loops simultaneously. This parallel execution enables multiple agents to work on different aspects of a problem concurrently, while the round-based structure ensures synchronization points between iterations. The loop continues until n_round completes or the environment becomes idle.

Can agents in MetaGPT communicate across different projects or sessions?

By default, agents operate within the scope of a single Team execution and Environment instance. However, MetaGPT provides RoleZeroLongTermMemory in metagpt/memory/role_zero_memory.py for persisting knowledge across sessions. For cross-project communication, developers must implement custom solutions that serialize agent states or use shared memory stores, as the standard Environment resets between distinct Team instantiations unless explicitly configured otherwise.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →