← Stack

CrewAI

Role-based agent teams: Researcher, Writer, Validator, coordinated out of the box.

Overview

CrewAI is an MIT-licensed Python framework for orchestrating collaborative multi-agent systems through role assignment. The core abstraction is a Crew: a team of Agents (each carrying a role, goal, and backstory) executing a list of Tasks through a defined process. Created by Joao Moura in October 2023 and first released on PyPI in December 2023, CrewAI reached 150 enterprise customers within six months of its January 2024 company launch.

The positioning is deliberate: CrewAI sits one abstraction level above LangGraph. Where LangGraph exposes nodes, edges, reducers, and a Pregel runtime that you assemble yourself, CrewAI exposes roles. You declare a Researcher agent, a Writer agent, and a Validator agent, and the framework handles coordination. That trade-off is the right one when the problem naturally divides into distinct human-style roles and when the flow is sequential or hierarchical, not cyclic.

Two execution patterns cover most use cases. A Crew runs agents through a sequential or hierarchical process: sequential executes tasks in declaration order, each passing its output as context to the next; hierarchical delegates through a manager agent that validates outputs before proceeding. A Flow (introduced in 2024-2025) adds branching, event-driven triggers (@start, @listen, @router), and structured state management for coordinating multiple Crews inside one longer pipeline.

Architecture

Two mental models cover the majority of production use. The Crew model defines Agents by role and assembles them into a sequential or hierarchical Task pipeline. The Flow model adds an event-driven coordinator on top: decorated methods connect through @start / @listen / @router, carry a shared state (structured or unstructured), and can embed Crew kickoffs as sub-steps. Memory is orthogonal to both: pass memory=True on Crew creation and a LanceDB-backed system tracks context across calls.

CREWprocess: sequentialResearcherresearch expertrole / goal / backstoryTask 1descriptioncontextWritercontent writerrole / goal / backstoryTask 2expected_outputcontextValidatorquality validatorrole / goal / backstoryTask 3output_pydanticResultcrew.kickoff()memory=TrueLanceDB
Crew model: Agents (role + goal + backstory) execute Tasks in sequential or hierarchical process
Shared statePydantic / dict@start()ResearchCrew kickoff@router()Routereturns label@listen("deep_dive")Deep dive@listen("write")Write@listen@listen@listen()Final reportfinal output
Flow model: @start / @listen / @router decorators coordinate Crew kickoffs with branching and shared state

Key concepts

Agent
An LLM-powered autonomous unit defined by role (what it does), goal (what it optimises for), and backstory (context shaping its personality). Optional fields: tools, memory, llm, max_iter (default 20), allow_delegation.
Task
A unit of work assigned to an Agent. Carries description, expected_output, context (list of upstream Tasks whose outputs feed this one), optional output_pydantic for structured output validation.
Crew
The orchestrator: a team of Agents running a list of Tasks through a process (sequential or hierarchical). Key params: agents, tasks, process, memory, manager_llm (required for hierarchical), max_rpm, cache.
Sequential process
The default Crew execution mode: Tasks run in the order they are declared. Each Task output is available as context to all subsequent Tasks. No manager agent needed.
Hierarchical process
A Crew execution mode where a manager agent (auto-created or custom) delegates Tasks to the right agent, validates outputs, and determines what runs next. Requires manager_llm or manager_agent.
Flow
An event-driven coordinator built on Python class decorators: @start marks entry, @listen triggers on method completion, @router branches on a returned label. Carries a typed state (Pydantic or dict) and can embed Crew kickoffs as steps.
Memory
CrewAI unified Memory class backed by LanceDB. When enabled (memory=True on Crew), the LLM analyzes and categorizes each task output at save time. Retrieval ranks by semantic similarity + recency + importance. Persists across Crew runs by default.

When to use

Good fit

  • Role-based pipelines: the problem splits naturally into distinct human-style functions, Researcher, Writer, Validator, Editor, each owning a clear scope.
  • Sequential content generation: each agent builds on the previous output (research -> draft -> review -> final), no cycles needed.
  • Report and document automation: multi-agent pipelines that gather data, synthesise it, and format the result, a pattern where the role concept maps directly onto the workflow.
  • Fast iteration on agent teams: CrewAI's YAML configuration and role-first model reduce the code surface needed to define and swap agents, shortening the prototype-to-test cycle.
  • Hierarchical delegation: when a coordinator agent should assign, review, and route tasks dynamically, the hierarchical process with a manager_llm fits without custom graph wiring.
  • Multi-crew pipelines: when the overall workflow has branching, parallel Crew executions, or state that must persist across Crew boundaries, Flows layer on top without rewriting the Crews.

Anti-patterns

  • Cyclic state machines: if the pipeline needs to loop back on intermediate results (reflect, retry, iterate), reach for LangGraph. CrewAI's sequential and hierarchical processes are acyclic; cycles require workarounds that fight the abstraction.
  • Durable crash recovery: if the process must resume from an exact superstep after a process crash at 3am, LangGraph with a PostgresSaver checkpointer is the correct tool. CrewAI Flows have resumption, but the core Crew executor does not snapshot every step.
  • Precise state machine topology: when the control flow itself is the product, with conditional edges, retry counts, typed reducers per key, and auditable state transitions, LangGraph's explicit graph model gives finer control than role delegation.
  • Unbounded agent loops: without explicit max_iter limits and clear expected_output criteria, agents can loop through tool calls, burning tokens. Set max_iter on each agent and define concrete exit conditions in expected_output.
  • Tight latency SLAs: the hierarchical process routes through a manager LLM call before delegating each task, adding latency. Sequential is faster; for sub-second requirements, consider a simpler tool-calling loop outside a Crew.

Code examples

Minimal Crew: Researcher -> Writer, sequential process

from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool

search_tool = SerperDevTool()

researcher = Agent(
    role="Senior Research Analyst",
    goal="Find and summarise the latest developments on {topic}",
    backstory="Expert at distilling complex information into clear insights.",
    tools=[search_tool],
    verbose=True,
)

writer = Agent(
    role="Content Writer",
    goal="Write a concise, accurate report based on the research findings",
    backstory="Skilled at turning research into readable prose.",
    verbose=True,
)

research_task = Task(
    description="Research the current state of {topic}. Identify key trends.",
    expected_output="A bullet-point summary of 5-10 key findings with sources.",
    agent=researcher,
)

write_task = Task(
    description="Write a 3-paragraph report based on the research findings.",
    expected_output="A polished 3-paragraph report, ready to publish.",
    agent=writer,
    context=[research_task],  # output of research_task feeds this task
)

crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, write_task],
    process=Process.sequential,
    verbose=True,
)

result = crew.kickoff(inputs={"topic": "CrewAI multi-agent frameworks"})

context=[research_task] is the key wiring: the Writer receives the Researcher's output as context. Without it, agents run in isolation and the Writer has no research to draw from.

Hierarchical Crew with manager LLM and memory

from crewai import Agent, Task, Crew, Process
import os

manager_llm = "claude-sonnet-4-5"  # or any LLM identifier

analyst = Agent(
    role="Data Analyst",
    goal="Extract structured insights from raw data",
    backstory="Precise, detail-oriented data specialist.",
)

validator = Agent(
    role="Quality Validator",
    goal="Verify accuracy and completeness of analysis outputs",
    backstory="Critical thinker who catches errors before they ship.",
)

writer = Agent(
    role="Report Writer",
    goal="Produce a clear, stakeholder-ready report",
    backstory="Expert at translating technical findings into business language.",
)

analyse_task = Task(
    description="Analyse the dataset at {data_path} and extract key metrics.",
    expected_output="Structured JSON with metrics: totals, trends, anomalies.",
)

validate_task = Task(
    description="Check the analysis output for accuracy and completeness.",
    expected_output="Validation report: pass/fail per metric with notes.",
)

report_task = Task(
    description="Write an executive summary based on validated analysis.",
    expected_output="2-page executive summary with charts described in text.",
)

crew = Crew(
    agents=[analyst, validator, writer],
    tasks=[analyse_task, validate_task, report_task],
    process=Process.hierarchical,
    manager_llm=manager_llm,
    memory=True,  # LanceDB-backed memory across calls
    verbose=True,
)

result = crew.kickoff(inputs={"data_path": "/data/q2-report.csv"})

In hierarchical mode, the manager LLM assigns tasks and validates outputs before proceeding. memory=True activates LanceDB-backed memory so agents recall context from earlier calls. Watch the extra LLM call cost per task delegation.

Flow: event-driven routing between Crews with typed state

from crewai.flow.flow import Flow, listen, start, router
from crewai import Crew, Process
from pydantic import BaseModel

class ReportState(BaseModel):
    topic: str = ""
    research_summary: str = ""
    needs_deep_dive: bool = False
    final_report: str = ""

class ReportFlow(Flow[ReportState]):

    @start()
    def kick_off_research(self):
        research_crew = build_research_crew()
        result = research_crew.kickoff(inputs={"topic": self.state.topic})
        self.state.research_summary = str(result)

    @router(kick_off_research)
    def route_by_depth(self):
        # Send to deep dive if summary flagged gaps
        if "insufficient data" in self.state.research_summary.lower():
            return "deep_dive"
        return "write"

    @listen("deep_dive")
    def run_deep_dive(self):
        deep_crew = build_deep_dive_crew()
        result = deep_crew.kickoff(
            inputs={"summary": self.state.research_summary}
        )
        self.state.research_summary += " " + str(result)

    @listen("write")
    @listen("run_deep_dive")
    def write_report(self):
        write_crew = build_write_crew()
        result = write_crew.kickoff(
            inputs={"research": self.state.research_summary}
        )
        self.state.final_report = str(result)

flow = ReportFlow()
flow.kickoff(inputs={"topic": "AI agent orchestration trends 2026"})

@router returns a label that determines which @listen branch executes next, enabling conditional branching without rewriting Crews. Use Flows when the coordination logic (branching, state passing) outgrows what a single Crew process can express.

Comparison

vs LangGraph

Abstraction level, flow control, fault tolerance

CrewAI raises the abstraction: define roles (Researcher, Writer, Validator), and the framework handles coordination. Less code for sequential role-based pipelines. LangGraph exposes the graph directly: nodes, edges, reducers, a Pregel runtime with a checkpointer that snapshots every superstep. Reach for LangGraph when cycles are required, when the state machine topology is the product, or when durable crash recovery is a hard requirement. Source: docs.crewai.com, docs.langchain.com/oss/python/langgraph.

vs AutoGen / AG2

Programming model, flow control, project status

CrewAI is role-and-task-structured: agents have explicit roles, tasks have explicit expected outputs, and the process (sequential or hierarchical) is declared upfront. AutoGen models agent interaction as a conversation with emergent routing; roles are softer and flow control is implicit. CrewAI suits business pipelines with clear role boundaries; AutoGen suits multi-agent debate, simulation, or research scenarios where roles evolve. Status matters: the original Microsoft AutoGen is in maintenance (successor: Microsoft Agent Framework); AG2 is the community fork preserving the v0.2 API. Sources: github.com/ag2ai/ag2, pecollective.com/blog/ai-agent-frameworks-compared.

vs n8n

Code vs visual, abstraction, graduation path

n8n is a visual workflow canvas for integration glue and fast prototyping; its AI Agent node runs on LangChain under the hood. CrewAI is code-first and role-oriented, suited to teams comfortable with Python who need finer control over agent behaviour than a drag-and-drop canvas provides. A common path: prototype the agent team shape in n8n to validate the role split quickly, then rewrite it in CrewAI when the logic earns tested, version-controlled code. Source: docs.n8n.io.

Resources

FAQ

What is the difference between a Crew and a Flow in CrewAI?
A Crew is agent-centric: a team of Agents runs a list of Tasks through a sequential or hierarchical process. A Flow is process-centric: decorated Python methods connect through @start / @listen / @router with explicit branching and a typed shared state. Use a Crew when a single linear or delegated pipeline suffices. Add a Flow when you need to branch between multiple Crews, carry state across them, or gate execution on a condition.
When should I use CrewAI instead of LangGraph?
Use CrewAI when the problem naturally splits into distinct human-style roles (Researcher, Writer, Validator) and the flow is sequential or hierarchical, not cyclic. The role-first model is faster to write and easier to reason about for business workflows. Reach for LangGraph when you need cycles, when the state machine topology is the product itself, or when durable crash recovery (superstep checkpointing to Postgres) is a hard requirement.
Is CrewAI open source?
The core framework is MIT-licensed: free to use, modify, and self-host with no commercial restriction. The hosted platform (CrewAI Enterprise / AMP) is commercial, with a free tier of 50 executions per month and paid plans starting at $25/month. Self-hosting incurs no platform cost; you pay only LLM token costs to your chosen provider.
How does CrewAI memory work?
Pass memory=True when creating a Crew and CrewAI activates a unified Memory class backed by LanceDB (stored locally in .crewai/memory by default). At save time, the LLM analyzes the content and infers its scope, category, and importance. Retrieval ranks results by a composite score of semantic similarity, recency, and importance. Memory persists across Crew kickoffs, so agents can recall context from earlier runs.
What happens if a Crew run crashes mid-execution?
For a bare Crew (sequential or hierarchical process), there is no automatic superstep snapshotting: if the process crashes, the run must restart from the beginning. CrewAI Flows have resumption capabilities via their state model. For hard durable execution requirements, LangGraph with a PostgresSaver checkpointer is the more appropriate tool: it snapshots every superstep and can resume from the last stable state after a crash.