intermediatearchitecturemetagptmulti-agentsopsoftware-factory

MetaGPT: Multi-Agent Software Factory

Product Manager to Architect to Engineer to QA role-based SOP-driven development, and comparison with CrewAI's role model.

MetaGPT: Multi-Agent Software Factory

MetaGPT takes a fundamentally different approach to multi-agent development than general-purpose frameworks like CrewAI or AutoGen. Instead of providing a blank canvas for agent collaboration, it simulates an entire software company with pre-defined roles, handoff protocols, and Standard Operating Procedures (SOPs). Published as the paper "Meta Programming for a Multi-Agent Collaborative Framework" and accepted at ICLR 2024, MetaGPT's core philosophy is captured in a single equation: Code = SOP(Team).

This article breaks down MetaGPT's role-based pipeline, its SOP-driven architecture, and how it compares to CrewAI's more flexible role model for loop engineering workflows.

The Five Roles: A Software Company in Code

MetaGPT defines five agent roles that mirror a real software organization. Each role consumes structured output from the previous role and produces its own artifact:

┌──────────────────────────────────────────────────────────────────┐
│                     MetaGPT SOP Pipeline                         │
│                                                                  │
│  User Prompt                                                     │
│      │                                                           │
│      ▼                                                           │
│  ┌─────────────┐    PRD     ┌─────────────┐    System Design    │
│  │  Product     │──────────►│  Architect   │─────────────────┐  │
│  │  Manager     │           │              │                  │  │
│  └─────────────┘           └─────────────┘                  │  │
│                                                         ▼  │  │
│  ┌─────────────┐    Test      ┌─────────────┐   Code      │  │
│  │  QA Engineer │◄───────────│  Engineer    │◄─────────────┘  │
│  │              │            │              │                    │
│  └─────────────┘            └─────────────┘                    │
│        │                            │                         │
│        └────────────────────────────┘                         │
│                     Fix Loop                                   │
│                                                                  │
└──────────────────────────────────────────────────────────────────┘

The Project Manager role (not shown in the primary pipeline) handles task allocation and timeline management. In practice, most users interact with MetaGPT through the PM-to-Engineer-to-QA path.

Role Responsibilities in Detail

RoleInputOutputKey SOP Behavior
Product ManagerOne-line user requirementStructured PRD with goals, user stories, constraintsExpands vague requirements into detailed specifications with acceptance criteria
ArchitectPRD documentSystem design with module decomposition, data models, API specsTranslates requirements into technical architecture with dependency graphs
Project ManagerSystem designTask allocation, timeline, file assignmentsBreaks architecture into discrete engineering tasks
EngineerTask + system designSource code files, runnable implementationWrites code against the architecture spec, one file per task
QA EngineerCode + PRD requirementsTest cases, test results, bug reportsValidates implementation against original requirements, triggers fix loops

The critical insight from the ICLR 2024 paper is that each role produces structured artifacts, not free-form text. The PM produces a PRD with specific fields; the Architect produces system design documents with explicit module boundaries and data flow diagrams. This structure is what enables reliable handoffs between agents.

SOP-Driven Development: The Core Mechanism

MetaGPT's SOPs are not just prompts -- they are codified workflows that enforce how information flows between roles. The framework materializes SOPs as Python classes with explicit publish_message and put_message communication protocols.

How SOPs Work

In a traditional multi-agent system, agents communicate through free-form conversation. MetaGPT replaces this with structured message passing:

Role A (PM)
  │
  ├── Writes structured PRD to shared workspace
  │   └── PRD stored as Message with schema validation
  │
  └── Calls self._publish_message(
          role="Architect",
          cause_by="WritePRD",
          intent="design_system",
          content=prd_document
      )

Role B (Architect)
  │
  ├── Watches for messages where role == self and intent matches
  │
  └── Calls self._react() → writes system design to workspace

This publish/subscribe pattern ensures that every handoff is auditable and type-safe. The shared workspace acts as the single source of truth, similar to a Git repository in a real team.

Running MetaGPT: A Minimal Example

# Install MetaGPT
pip install metagpt

# Configure LLM API key
export OPENAI_API_KEY="sk-xxx"

# Run the full software company pipeline
python -m metagpt "Build a CLI tool that converts CSV to JSON"

That single command triggers the entire PM-to-Architect-to-Engineer-to-QA pipeline. MetaGPT creates a workspace directory containing:

workspace/
├── docs/
│   ├── prd.md              # Product requirements (from PM)
│   └── system_design.md    # Architecture spec (from Architect)
├── tests/
│   └── test_csv_to_json.py # Test cases (from QA)
└── src/
    └── csv_to_json.py      # Source code (from Engineer)

Customizing the Team with Per-Role LLM Configuration

MetaGPT supports assigning different LLMs to different roles, which maps directly to the model tiering strategy used in loop engineering:

# config2.yaml — Per-action LLM configuration
llm:
  default:
    model: "claude-sonnet-4"
    api_type: "openai"

  action:
    WritePRD:
      model: "claude-opus-4"      # Complex reasoning for requirements
    WriteDesign:
      model: "claude-opus-4"      # Deep architectural thinking
    WriteCode:
      model: "claude-sonnet-4"    # General-purpose coding
    WriteCodeReview:
      model: "claude-sonnet-4"    # Review needs strong capability
    RunCode:
      model: "claude-haiku-4.5"   # Fast execution verification
    QATest:
      model: "claude-sonnet-4"    # Test writing

This tiered approach mirrors the Claude model tiering pattern: Opus for complex reasoning (requirements, architecture), Sonnet for implementation, and Haiku for fast verification tasks.

The Publish/Subscribe Architecture

MetaGPT's internal communication uses a message bus pattern. Each role subscribes to specific message types and reacts only when relevant:

┌─────────────────────────────────────────────────┐
│              MetaGPT Message Bus                  │
│                                                   │
│  PM.publish(WritePRD, intent="design")            │
│       │                                           │
│       ├──► Architect.watch(WritePRD)              │
│       │       └── React: WriteDesign             │
│       │           │                               │
│       │           ├──► Engineer.watch(WriteDesign)│
│       │           │       └── React: WriteCode   │
│       │           │           │                   │
│       │           │           ├──► QA.watch(Code) │
│       │           │           │    └── QATest     │
│       │           │           │                   │
│       │           │           └──► QA.watch(Code) │
│       │           │                └── RunCode   │
│       │           │                    │          │
│       │           │                    └──► Fix  │
│       │           │                        Loop   │
│       │           │                                │
│       │           └──► ProjectManager.watch(Design)│
│       │                   └── WriteTasks          │
│       │                                           │
│       └──► (no other subscribers)                │
│                                                   │
└─────────────────────────────────────────────────┘

The fix loop between Engineer and QA is where the loop engineering pattern emerges. If QA finds issues, it publishes a message back to the Engineer, who rewrites code and re-publishes. This continues until QA passes all checks or a maximum retry count is reached.

Custom Roles: Extending the Software Factory

While MetaGPT ships with five pre-built roles, the framework allows defining custom roles by subclassing Role and defining custom Action sequences:

from metagpt.roles import Role
from metagpt.actions import Action

class Researcher(Action):
    async def run(self, topic: str) -> str:
        """Research the topic and return findings."""
        prompt = f"Research {topic} and provide a technical summary"
        return await self._aask(prompt)

class TechnicalWriter(Role):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._init_actions([Researcher])

    async def _think(self) -> bool:
        """Determine if action should proceed."""
        return True

The Role base class handles message watching, publishing, and the SOP lifecycle. Custom roles plug into the same message bus as the built-in roles.

MetaGPT vs. CrewAI: Role Model Comparison

Both MetaGPT and CrewAI organize agents around roles, but their design philosophies diverge sharply. MetaGPT optimizes for software development simulation; CrewAI optimizes for general-purpose role-based collaboration.

Architecture Comparison

DimensionMetaGPTCrewAI
Core metaphorSoftware company with SOPsFlexible team with tasks
RolesPre-built (PM, Architect, Engineer, QA)Fully custom (define any role)
CommunicationStructured publish/subscribe message busAgent-to-agent delegation and chat
Output formatEnforced structured artifacts (PRD, design docs, code)Flexible output (depends on task definition)
WorkflowFixed pipeline (PM → Architect → Engineer → QA)Custom workflows (sequential, hierarchical, consensual)
Task modelSOP-driven: each role has a fixed set of actionsTask-driven: roles receive arbitrary tasks
Learning curveModerate — domain-specific, opinionatedLower — intuitive role-based mental model
Best forEnd-to-end software generation from requirementsBusiness process automation, research pipelines
Paper/AcademicICLR 2024, arXiv 2308.00352No formal paper, community-driven
GitHubFoundationAgents/MetaGPTjoaomdmoura/crewAI

Workflow Flexibility

MetaGPT Workflow (Fixed Pipeline):
  Requirement → PRD → Design → Code → Tests → (Fix Loop)
       │                                              │
       └──────────────────────────────────────────────┘
                     Single predetermined path

CrewAI Workflow (Flexible):
  Task A ──► Task B ──► Task C     (sequential)
     │          │
     └──► Task D ◄─┘              (hierarchical with delegation)
                │
                ▼
         Task E                    (consensual: multiple agents vote)

MetaGPT's fixed pipeline is a strength when you want reliable, repeatable software generation. CrewAI's flexible workflow is better when your agent collaboration doesn't fit a linear pipeline.

Structured Output: The Key Differentiator

MetaGPT's most distinctive feature is its insistence on structured artifacts at every pipeline stage. The ICLR 2024 paper demonstrates that this structuring dramatically reduces hallucination and inconsistency compared to free-form multi-agent collaboration:

MetaGPT PRD Structure (enforced):
┌──────────────────────────────────────┐
│ # Project Name                        │
│ ## Goals                              │
│   1. [Specific, measurable goal]     │
│   2. [Specific, measurable goal]     │
│ ## User Stories                       │
│   - As a [user], I want [feature]     │
│     so that [benefit]                 │
│ ## Requirements                       │
│   - REQ-001: [requirement text]      │
│   - REQ-002: [requirement text]      │
│ ## Constraints                        │
│   - [Technical constraint]           │
│ ## Success Criteria                   │
│   - [Measurable acceptance test]     │
└──────────────────────────────────────┘

CrewAI Output (flexible):
  Whatever the role's task description produces.
  Structure depends entirely on prompt engineering.

When CrewAI produces structured output, it is because the developer manually enforced it through prompt engineering and output parsing. MetaGPT enforces it at the framework level.

When to Choose MetaGPT vs. CrewAI

Do you need end-to-end software generation from a requirement?
├─ YES
│   Is the pipeline linear (PM → Architect → Code → QA)?
│   ├─ YES → MetaGPT (purpose-built for this)
│   └─ NO → CrewAI with custom sequential tasks
└─ NO
    Do you need multiple agent roles collaborating on non-software tasks?
    ├─ YES → CrewAI (general-purpose role model)
    └─ NO
        Are you building a domain-specific multi-agent system?
        ├─ YES → MetaGPT (extensible with custom roles)
        └─ NO → Evaluate LangGraph or AutoGen

MetaGPT in Loop Engineering

MetaGPT's pipeline maps naturally to the loop engineering paradigm. Each role-to-role handoff is a loop iteration, and the QA-to-Engineer fix loop is an explicit inner loop:

Outer Loop: Pipeline Stages

Loop 1: PM writes PRD
  ├── Verify: PRD covers all requirements?
  └── Pass → Next loop

Loop 2: Architect designs system
  ├── Verify: Design satisfies PRD constraints?
  └── Pass → Next loop

Loop 3: Engineer implements code
  ├── Verify: Code matches design?
  └── Pass → Next loop

Loop 4: QA validates
  ├── Verify: All tests pass?
  │   ├── FAIL → Return to Loop 3 (inner fix loop)
  │   └── PASS → Done

Inner Loop: The QA Fix Cycle

The QA-to-Engineer feedback loop is where MetaGPT most clearly demonstrates loop engineering principles. The maximum number of fix iterations is configurable, preventing infinite loops:

# Conceptual fix loop configuration
class SoftwareCompany:
    def __init__(self):
        self.max_fix_iterations = 3   # Quality gate: max 3 fix rounds
        self.n_bugs_fixed = 0

    async def run(self):
        while self.n_bugs_fixed < self.max_fix_iterations:
            code = await engineer.write_code(design)
            result = await qa.run_tests(code)
            if result.all_passed:
                break
            bugs = result.failed_tests
            await engineer.fix_bugs(bugs)
            self.n_bugs_fixed += 1

Combining MetaGPT with Other Tools

MetaGPT does not need to run in isolation. Its structured artifacts integrate well with tools from the broader loop engineering ecosystem:

IntegrationPatternBenefit
MetaGPT + Claude CodeUse MetaGPT to generate initial project structure, then Claude Code for iterative refinementSOP-driven scaffolding + interactive agent loop
MetaGPT + AiderMetaGPT generates code, Aider applies model tiering for fixesCombine SOP pipeline with cost-optimized editing
MetaGPT + GitHub ActionsMetaGPT runs in CI to generate code for issues, PRs auto-createdAutonomous issue-to-PR pipeline
MetaGPT PRD onlyRun only the PM role to generate structured PRDs for human teamsLightweight use case without full code generation

Running MetaGPT with Local Models

For teams that want to avoid API costs, MetaGPT supports local LLMs through Ollama integration:

# Start Ollama with a code-capable model
ollama serve
ollama pull deepseek-coder-v2

# Configure MetaGPT to use local model
cat > ~/.metagpt/config2.yaml << 'EOF'
llm:
  default:
    model: "deepseek-coder-v2"
    api_type: "ollama"
    base_url: "http://localhost:11434"
EOF

# Run the pipeline
python -m metagpt "Build a REST API for a todo app"

This approach is documented in IBM's tutorial on multi-agent PRD automation using MetaGPT with DeepSeek and Ollama, demonstrating that the SOP pipeline works with any sufficiently capable code model.

Limitations and Practical Considerations

MetaGPT's structured approach has trade-offs that matter for production loop engineering:

LimitationImpactMitigation
Fixed pipelineCannot easily express non-linear workflowsUse CrewAI for complex workflow topologies
Token costFull pipeline generates large artifacts (PRD + design + code + tests)Run individual roles instead of full pipeline
Context limitsLong PRDs may exceed smaller model context windowsUse Claude Opus (200K) or break requirements into smaller chunks
Quality varianceGenerated code may need significant human reviewUse MetaGPT for scaffolding, not final output
DebuggingMulti-role pipelines are harder to debug than single-agent loopsInspect the workspace artifacts at each stage

The token cost issue is particularly relevant. Running the full five-role pipeline with GPT-4 class models can consume 30-50K tokens for a moderate feature requirement. Per-action model tiering (Opus for PRD/design, Sonnet for code, Haiku for test execution) helps control this.

Quick Reference: MetaGPT Setup

# 1. Install
pip install metagpt

# 2. Configure API keys
export OPENAI_API_KEY="sk-xxx"

# 3. Full pipeline (all roles)
python -m metagpt "Build a URL shortener with analytics"

# 4. Single role only
python -c "
from metagpt.roles import ProductManager
pm = ProductManager()
prd = pm.run('Build a URL shortener with analytics')
print(prd)
"

# 5. Custom team
python -c "
from metagpt.team import Team
team = Team()
team.hire([
    ProductManager(),
    Architect(),
    Engineer(n_borg=3),   # 3 parallel engineers
    QaEngineer()
])
team.run_project('Build a URL shortener with analytics')
"

Key Takeaways

  1. MetaGPT materializes SOPs as code -- the Code = SOP(Team) philosophy means each role's behavior is a codified workflow, not a loose prompt.

  2. Structured artifacts are the differentiator -- enforced PRD schemas, system design templates, and code output formats reduce hallucination compared to free-form multi-agent chat.

  3. The fix loop is built in -- QA-to-Engineer feedback with configurable retry limits is a first-class loop engineering pattern.

  4. Per-role model tiering reduces cost -- assign expensive models to reasoning-heavy roles (PM, Architect) and cheaper models to execution roles (Engineer code writing, QA test running).

  5. CrewAI offers more flexibility -- for workflows that don't fit a linear software pipeline, CrewAI's task delegation and consensual decision-making models are more appropriate. For pure software generation from requirements, MetaGPT's opinionated pipeline is more reliable.

The FoundationAgents/MetaGPT repository on GitHub continues to evolve, with the community extending the framework beyond software development into data analysis, research workflows, and game simulations. The core SOP architecture remains the same: decompose a complex task into specialized roles with structured handoffs, and let each role operate within its defined standard operating procedure.