← Back to Learning Hub

CrewAI

LangChainLangGraphIntermediate12 min

By: Anacodic Team

TL;DR

CrewAI is a role-based multi-agent framework. You assemble a crew of agents — each with a role, goal, and backstory — assign them tasks (each with a description, expected output, and owning agent), and pick a process that decides how tasks run: sequential (one after another, output flows as context to the next) or hierarchical (a manager agent plans, delegates, and validates). The metaphor is a company org chart: define who does what, hand them jobs, and let the process coordinate. CrewAI is more structured and opinionated than AutoGen's free-form conversation — great when you can name the roles and the workflow up front (research→write→edit, plan→build→review). It's standalone (not built on LangChain) and popular for its clean, declarative API.


Simple explanation + analogy

CrewAI is hiring a small team and giving them a project brief. You write job descriptions (agents: "Senior Researcher", "Tech Writer"), a task list (tasks: "research topic X → produce 10 bullet findings", "write a 500-word article from the findings"), and decide how the team operates (process):

  • Sequential — an assembly line. Researcher finishes, hands findings to the Writer, who hands the draft to the Editor. Each task automatically receives the previous task's output as context.
  • Hierarchical — a manager runs the show. A manager agent (auto-created) plans, decides which agent handles which task, delegates, checks the result, and only then moves on — like a team lead coordinating specialists.

You don't script the messages (as in AutoGen); you declare the structure and CrewAI executes it. Think org chart + job tickets, not open Slack channel.


Diagram

   Crew = Agents + Tasks + Process

   AGENTS (role/goal/backstory)        TASKS (description/expected_output/agent)
   ┌───────────────┐                   ┌────────────────────────────────┐
   │ Researcher    │                   │ T1: research topic → findings  │──┐
   │ Writer        │                   │ T2: write article  → draft     │  │ context
   │ Editor        │                   │ T3: edit draft     → final     │  │ flows
   └───────────────┘                   └────────────────────────────────┘  │ forward

   SEQUENTIAL process:                 HIERARCHICAL process:
     T1 ─▶ T2 ─▶ T3                        ┌──────────────┐
     (output of Tₙ = context               │ Manager agent│  plans / delegates / validates
      for Tₙ₊₁)                            └──────┬───────┘
                                         ┌────────┼─────────┐
                                         ▼        ▼         ▼
                                     Researcher Writer   Editor
                                   (manager assigns tasks by capability,
                                    reviews results before proceeding)

How it works (deep)

1. Agents — role + goal + backstory

A CrewAI Agent is defined by three prompt-shaping fields:

  • role — the job title ("Senior Market Analyst").
  • goal — what success looks like ("surface the three biggest risks").
  • backstory — persona/context that steers tone and expertise.

Plus operational settings: tools (functions the agent can call), llm, allow_delegation (can this agent hand work to teammates?), verbose, max_iter. The role/goal/backstory triad is CrewAI's signature — it front-loads the agent's identity so behavior is consistent across tasks.

2. Tasks — the unit of work

A Task has a description, an expected_output (a concrete spec of the deliverable — critical for quality), the agent responsible, optional tools, and context (other tasks whose output feeds this one). Tasks are where CrewAI differs sharply from AutoGen: work is declared as discrete, typed deliverables, not emergent from chatter. You can also request structured output via output_json / output_pydantic.

3. Crew — the container

A Crew binds agents, tasks, and a process, plus crew-level config (memory, verbose, manager_llm for hierarchical). crew.kickoff(inputs={...}) runs it and returns the final result (with per-task outputs accessible).

4. Processes — how tasks execute

This is the most-asked interview area:

  • Sequential (Process.sequential) — tasks run in list order. Each task automatically receives the previous tasks' output as context, enabling pipeline-style data flow (research → write → edit). Predictable and easy to reason about.
  • Hierarchical (Process.hierarchical) — CrewAI auto-creates a manager agent (you supply manager_llm or a custom manager_agent). Tasks are not pre-assigned to workers; the manager plans, delegates each task to the best-suited agent, evaluates the result, and validates before proceeding. This mirrors a corporate hierarchy and adds dynamic coordination at the cost of extra LLM calls and less determinism.

Key contrast: in sequential the order and ownership are fixed by you; in hierarchical the manager allocates work at runtime based on agent capabilities.

5. Delegation, tools, and memory

  • Delegation: with allow_delegation=True, an agent can ask a teammate to do part of a task — the collaboration primitive. In hierarchical mode the manager delegates centrally.
  • Tools: agents call tools (search, scraping, custom Python) mid-task.
  • Memory: crew memory (short-term, long-term, entity) lets agents recall earlier context across tasks/runs.

6. Crews vs Flows

Modern CrewAI has two layers: Crews (autonomous role-based collaboration, above) and Flows (event-driven, deterministic orchestration with explicit control flow — closer in spirit to a LangGraph workflow). Interviewers may ask when to use which: Crews for autonomous teamwork, Flows for precise, auditable step control (you can even embed crews inside flows).


The math

CrewAI has no bespoke algorithm, but two quantitative ideas frame the design tradeoffs.

Sequential context accumulation. In a sequential crew of k tasks, task i receives the outputs of prior tasks as context. If each output is ~m tokens, task i's input includes roughly (i-1)·m context tokens, so total token consumption across the crew is:

$$\text{tokens} \approx \sum_{i=1}^{k} \big(p + (i-1),m\big) = k,p + m\binom{k}{2} = O(k^2 m)$$

where p is the base prompt size. Long chains of tasks grow quadratically in context — a reason to keep expected_output tight and to summarize between tasks.

Hierarchical overhead. Hierarchical mode adds the manager's planning/validation calls. For k tasks, expect on the order of k extra manager LLM calls (plan + validate per task) on top of the worker calls — trading tokens/latency for dynamic allocation and quality control. If a task DAG is already well-understood, sequential is cheaper and more predictable.


Real code

A canonical sequential research→write crew:

from crewai import Agent, Task, Crew, Process

researcher = Agent(
    role="Senior Travel Researcher",
    goal="Find the best-rated {destination} hotels in {region} with traveler notes",
    backstory="A meticulous travel writer who cross-checks ratings and reviews.",
    tools=[search_tool],
    allow_delegation=False,
    verbose=True,
)

writer = Agent(
    role="Travel Writer",
    goal="Write a warm, concise recommendation from the research",
    backstory="A friendly travel blogger who knows every hidden gem.",
    verbose=True,
)

research_task = Task(
    description="Research {destination} stays in {region}. Note ratings, price, and amenities.",
    expected_output="A list of 5 hotels: name, rating, price range, one standout feature.",
    agent=researcher,
)

write_task = Task(
    description="Using the research, recommend ONE hotel in 3-4 sentences.",
    expected_output="A conversational recommendation naming a feature and neighbourhood.",
    agent=writer,
    context=[research_task],        # explicit: this task consumes the research output
)

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

result = crew.kickoff(inputs={"destination": "Kyoto", "region": "Japan"})
print(result)

The hierarchical variant — a manager coordinates delegation and validation:

crew = Crew(
    agents=[researcher, writer, editor],
    tasks=[research_task, write_task, edit_task],
    process=Process.hierarchical,
    manager_llm="gpt-4o",           # CrewAI auto-creates a manager agent
    verbose=True,
)
result = crew.kickoff(inputs={"destination": "Kyoto", "region": "Japan"})
# Manager plans → delegates each task to the best agent → validates → proceeds

Structured output from a task:

from pydantic import BaseModel

class Recommendation(BaseModel):
    hotel: str
    feature: str
    reason: str

write_task = Task(
    description="Recommend one hotel.",
    expected_output="A structured recommendation.",
    agent=writer,
    output_pydantic=Recommendation,   # typed, validated result
)

Real-world example (relating to a real stack)

A trip-planning assistant built with Strands + Bedrock solves trip planning with an orchestrator agent that calls specialist agents (budget, flights, hotels, activities) as tools and synthesizes a reply. Its shape is orchestrator-as-tools, closely analogous to CrewAI's hierarchical process — one coordinator directing specialists.

Rebuilt in CrewAI, those specialists become role-based agents: a Budget Analyst (goal: fit the price cap), a Flights Agent (goal: find flight options via a search tool), a Hotels Agent (goal: match preferences and filter by dates), an Activities Planner (goal: suggest activities). You'd declare each planning step as a Task with a precise expected_output, then choose:

  • Sequential if the pipeline is fixed (search flights → budget-filter → hotel-match → plan activities), or
  • Hierarchical if you want a manager to dynamically decide which specialists a given query even needs (an activities query may skip the budget agent).

The teaching point: the Strands orchestrator is code you wrote to call tools; CrewAI would express the same collaboration declaratively as roles + tasks + a process. Same problem, more structure and less glue — but also less low-level control over exactly what each specialist is prompted with.


Interview questions companies actually ask

1. What is CrewAI and what are its core components? [easy] A role-based multi-agent framework. Core pieces: agents (role/goal/backstory), tasks (description/expected_output/owning agent), and crews (agents + tasks + a process). It coordinates specialized agents toward a shared goal. (CrewAI: role-based orchestration)

2. What defines an agent in CrewAI? [easy] role, goal, and backstory (the identity/persona), plus tools, llm, and allow_delegation. The role/goal/backstory triad shapes the agent's prompt so its behavior is consistent across tasks. (Intro to Agents, Tasks, Crews)

3. Sequential vs hierarchical process — explain the difference. [medium] Sequential: tasks run in list order; each task automatically receives prior outputs as context (pipeline flow). Hierarchical: a manager agent plans, delegates each task to the best-suited agent, and validates results before proceeding — tasks aren't pre-assigned. (Process types)

4. In hierarchical mode, who assigns tasks and how? [medium] An auto-created manager agent (configured via manager_llm or a custom manager_agent) allocates tasks to workers at runtime based on their capabilities, coordinates execution, and validates outcomes before moving on — no pre-assignment. (Hierarchical process)

5. Why does expected_output matter on a Task? [medium] It specifies the concrete deliverable shape, which both steers the LLM toward the right form and lets downstream tasks consume a predictable input. Combined with output_pydantic/output_json, it turns free text into validated structured data.

6. How does context flow between tasks? [medium] In sequential mode, each task automatically gets prior tasks' outputs as context; you can also set context=[other_task] explicitly so a task consumes specific upstream results — enabling pipeline-style data flow. (Sequential vs hierarchical)

7. How does CrewAI differ from AutoGen and LangGraph? [hard] CrewAI is declarative and role-structured — you name roles, tasks, and a process; coordination is built-in. AutoGen is conversation-driven (agents message each other, control flow emerges). LangGraph is a graph you wire node-by-node with explicit state. CrewAI sits between AutoGen's openness and LangGraph's low-level control.

8. What's the difference between CrewAI Crews and Flows? [hard] Crews are autonomous role-based collaboration (agents decide how to accomplish tasks). Flows are event-driven, deterministic orchestration with explicit control flow — closer to a LangGraph workflow, and you can embed crews inside flows for autonomy where you want it and determinism where you need it.

9. When would you choose CrewAI over a single-agent chain? [medium] When the work naturally decomposes into specialist roles with distinct goals and a coordination pattern (research→write→edit, plan→build→review). If it's one linear LLM task, a chain is simpler — don't add a crew for a job one agent can do.

10. What are CrewAI's main risks in production? [hard] Quadratic context growth in long sequential crews, extra manager overhead (tokens/latency) in hierarchical mode, and less low-level control over each agent's exact prompt than a hand-rolled orchestrator. Mitigate with tight expected_output, memory/summarization, and using Flows where determinism matters.


When to use / tradeoffs

Use CrewAI when:

  • The task decomposes cleanly into named roles with distinct goals.
  • The workflow is expressible as tasks with clear deliverables (research→write→edit).
  • You want a fast, declarative way to stand up a specialist team without writing orchestration glue.
  • You want a choice between fixed pipelines (sequential) and dynamic delegation (hierarchical).

Avoid when:

  • You need free-form, emergent debate/critique between agents → AutoGen.
  • You need fine-grained, auditable state-machine control → LangGraph (or CrewAI Flows).
  • The task is a single linear LLM step → an LCEL chain is simpler.

Tradeoffs: CrewAI trades low-level control for a clean, opinionated, declarative model. You gain readable role/task definitions and built-in coordination; you give up some control over exact prompting and pay quadratic context growth on long task chains plus manager overhead in hierarchical mode.


CrewAI models a multi-agent system as a company: agents (role/goal/backstory), tasks (deliverables with expected_output), and a process (sequential pipeline or hierarchical manager-led delegation). It's the most structured and declarative of the multi-agent frameworks — ideal when you can name the roles and the workflow. Compared to a hand-coded Strands orchestrator, CrewAI expresses the same specialist collaboration as roles + tasks, trading control for clarity.

Related articles:

  • AutoGen — conversation-driven multi-agent (looser structure than CrewAI).
  • Framework Comparison — CrewAI vs Strands vs AutoGen vs LangGraph vs OpenAI Agents SDK.
  • Multi-Agent Orchestration Patterns — hierarchical, sequential, delegation.
  • LangGraph — deterministic, state-machine control (compare to CrewAI Flows).

Runnable notebook

Run it end to end — the mock model needs no API key; add your own key for the real Claude section.

Open In Colab