CrewAI: role-based agent crews and flows
What you’ll learn
Section titled “What you’ll learn”- How CrewAI’s four concepts fit together: agents, tasks, crews and flows.
- How a sequential crew passes work from one agent to the next, and how a guardrail checks output in code.
- How a flow gives you deterministic control and calls a crew only where reasoning is needed.
- What the hierarchical process, memory and tools add, and what they cost.
- When a crew of agents is the wrong design.
Summary
Section titled “Summary”CrewAI is an open-source Python framework for multi-agent systems. You describe agents by role, goal and backstory, give them tasks with an expected output, and group them into a crew that runs the tasks in order or under a manager. Around that, flows provide event-driven, stateful control: ordinary Python methods wired together with decorators, which start crews at the points where judgment is required.
The role-and-task vocabulary is quick to read and quick to prototype with. The price is less control over each model call than a graph runtime gives you, and a cost that grows with every agent you add.
Context and forces
Section titled “Context and forces”Some work divides naturally by role: one step gathers facts, another writes, a third reviews. Putting all three into one prompt makes the prompt long and the output hard to check. Splitting them gives each step a narrow instruction and a checkable result.
The opposing force is cost and reliability. Each agent is at least one model call, usually several. Each handoff is a place where context is dropped or distorted. A framework has to make the split easy without hiding what is being sent to the model. CrewAI’s answer is a high-level description (roles and tasks) for the reasoning parts, and flows for the parts that should be plain, testable code.
The design
Section titled “The design”| Concept | What it is | Key settings |
|---|---|---|
| Agent | A model with a role, goal and backstory, optional tools | llm, tools, max_iter (default 25), max_rpm, max_execution_time, allow_delegation (default False) |
| Task | One unit of work with a description and an expected_output |
agent, context (earlier tasks whose output it receives), guardrail, output_pydantic, human_input |
| Crew | Agents plus tasks plus a process | process (Process.sequential or Process.hierarchical), memory, manager_llm or manager_agent |
| Flow | A class whose methods are steps, connected by @start, @listen and @router |
Typed state (a Pydantic model), persistence, human feedback |
Sequential process: tasks run in the order listed, and each task can receive earlier outputs through context.
Hierarchical process: a manager agent decides which agent does what and reviews the results. You must supply manager_llm or manager_agent. It is more flexible and noticeably more expensive, because the manager’s planning and review are extra model calls.
Models are set with a provider/model-id string, for example LLM(model="anthropic/claude-sonnet-5-5"), and the key is read from the provider’s environment variable.
Running the samples
Section titled “Running the samples”The samples were run with Python 3.11 and crewai 1.15.41 (pip install crewai; CrewAI requires Python 3.10 or later and below 3.14). They use a scripted stand-in for the model, so they need no API key and produce the same output on every run. Save each as a .py file and run it with python. The two environment variables at the top switch off CrewAI’s anonymous usage telemetry and its tracing prompt, which keeps the output clean; the samples print only the lines shown, and CrewAI also logs a notice to stderr that token counts for the stub model are approximate.
To use a real model, replace ScriptedLLM(...) with a model string. This fragment requires an API key and was not executed:
# Fragment: requires ANTHROPIC_API_KEY in the environment; not executedfrom crewai import LLM
llm = LLM(model="anthropic/claude-sonnet-5-5")Worked example: a late-delivery report
Section titled “Worked example: a late-delivery report”The example domain is operations reporting for an invented shop, OrdersPortal.
A sequential crew with a guardrail
Section titled “A sequential crew with a guardrail”An analyst agent finds the cause of late deliveries and a writer agent turns it into a manager summary. A guardrail function checks the summary before the crew accepts it.
# crew_report.py - two agents, two tasks, sequential process, with a scripted LLM (no API key)import os
os.environ["CREWAI_DISABLE_TELEMETRY"] = "true"os.environ["CREWAI_TRACING_ENABLED"] = "false"
from crewai import Agent, BaseLLM, Crew, Process, Task
class ScriptedLLM(BaseLLM): """Stand-in for a real model: returns canned answers in order."""
replies: list[str] = [] calls: int = 0
def call(self, messages, **kwargs) -> str: reply = self.replies[self.calls % len(self.replies)] self.calls += 1 return reply
llm = ScriptedLLM( model="scripted", replies=[ "Thought: I can answer.\nFinal Answer: 42 late orders last week; 31 were on the northern route.", # The writer's first draft has no figure, so the guardrail rejects it and the agent retries. "Thought: I can answer.\nFinal Answer: Late deliveries rose sharply, mostly on the northern route.", "Thought: I can answer.\nFinal Answer: Late deliveries rose to 42. Most (31) were on the northern " "route, so the carrier review should start there.", ],)
analyst = Agent( role="Delivery data analyst", goal="Find the main cause of late OrdersPortal deliveries", backstory="You read delivery logs and report numbers without speculation.", llm=llm, max_iter=5,)writer = Agent( role="Operations report writer", goal="Turn findings into a two-sentence summary for the operations manager", backstory="You write plainly and never add facts that are not in the findings.", llm=llm, max_iter=5,)
def has_a_number(output) -> tuple[bool, str]: """Guardrail: reject a summary that contains no figure. Returns (passed, value or feedback).""" if any(ch.isdigit() for ch in output.raw): print("guardrail: passed") return True, output.raw print("guardrail: rejected, asking for a retry") return False, "Include the number of late orders."
analyze = Task( description="Analyze late deliveries for the week starting {week}.", expected_output="Count of late orders and the main cause.", agent=analyst,)summarize = Task( description="Write the manager summary from the analysis.", expected_output="Two sentences.", agent=writer, context=[analyze], # the writer receives the analyst's output guardrail=has_a_number, # checked in code before the crew accepts the output)
crew = Crew(agents=[analyst, writer], tasks=[analyze, summarize], process=Process.sequential)result = crew.kickoff(inputs={"week": "2026-11-02"})
print("final:", result.raw)print("task outputs:", [t.raw[:28] + "..." for t in result.tasks_output])print("model calls:", llm.calls)Output:
guardrail: rejected, asking for a retryguardrail: passedfinal: Late deliveries rose to 42. Most (31) were on the northern route, so the carrier review should start there.task outputs: ['42 late orders last week; 31...', 'Late deliveries rose to 42. ...']model calls: 3What to notice:
{week}in the task description is filled fromkickoff(inputs=...).context=[analyze]is the handoff. Without it, in a sequential crew a task still sees the previous task’s output, but naming the dependency makes it explicit and lets a task draw on several earlier ones.- The guardrail is ordinary code that returns
(True, value)or(False, feedback). The scripted writer’s first draft has no figure, so the guardrail rejects it and the agent retries with the feedback; that retry is the third model call. Retries stop atguardrail_max_retries(default 3), after which the task fails. Checks that can be written as code should be code, not another agent. result.rawis the final text, andresult.tasks_outputholds each task’s output for logging and tests.max_iter=5bounds each agent’s reasoning loop. The default of 25 (increwai1.15.41) is generous for a simple task.
A flow that decides when a crew is needed
Section titled “A flow that decides when a crew is needed”Most complaints about a late order need a template reply, not a team of agents. A flow routes them in code and reserves the crew for the hard cases.
# crew_flow.py - a Flow routes each complaint; only one branch would need a crewimport os
os.environ["CREWAI_DISABLE_TELEMETRY"] = "true"os.environ["CREWAI_TRACING_ENABLED"] = "false"
from crewai.flow.flow import Flow, listen, router, startfrom pydantic import BaseModel
class ComplaintState(BaseModel): order_id: str = "" days_late: int = 0 outcome: str = ""
class ComplaintFlow(Flow[ComplaintState]): @start() def load_order(self): print(f"loaded {self.state.order_id}: {self.state.days_late} days late")
@router(load_order) def triage(self): return "simple" if self.state.days_late <= 3 else "complex"
@listen("simple") def send_apology(self): self.state.outcome = "template apology sent" # plain code, no model call
@listen("complex") def investigate(self): # In a real flow: InvestigationCrew().crew().kickoff(inputs={...}) self.state.outcome = "handed to the investigation crew"
for order_id, days in [("A1001", 2), ("A1002", 9)]: flow = ComplaintFlow(suppress_flow_events=True) flow.kickoff(inputs={"order_id": order_id, "days_late": days}) print(" ->", flow.state.outcome)Output:
loaded A1001: 2 days late -> template apology sentloaded A1002: 9 days late -> handed to the investigation crew@start marks the entry point, @router returns a label, and @listen("label") methods run for that label. State is a typed Pydantic model, filled from kickoff(inputs=...). suppress_flow_events=True only hides the console panels CrewAI prints for each step. Flows also support persisted state and a @human_feedback decorator for approval steps (CrewAI 1.8.0 or later, per the docs).
Tools, memory and structured output
Section titled “Tools, memory and structured output”Tools are functions an agent may call. The @tool decorator from crewai.tools turns a typed, documented function into one; the docstring is what the model reads to decide when to call it. The separate crewai-tools package provides prebuilt tools for search, scraping and files. CrewAI can also connect agents to MCP servers.
# Fragment: verified with crewai 1.15.41 by calling carrier_status.run(tracking_number="TRK123")from crewai.tools import tool
@tool("Carrier status lookup")def carrier_status(tracking_number: str) -> str: """Return the carrier's latest scan for a tracking number. Use for delivery questions only.""" return {"TRK123": "out for delivery"}.get(tracking_number, "unknown tracking number")Memory. Current CrewAI has a unified Memory class that replaces the separate short-term, long-term and entity memories described in older tutorials. Crew(memory=True) enables it: after each task the crew extracts facts and stores them, and before each task it recalls relevant ones into the prompt. Two consequences are easy to miss. Memory itself uses a model to analyze what it saves, and the default embedder is an OpenAI embedding model, so enabling memory adds calls, cost and a provider dependency unless you configure an embedder. Stored memories can also carry a wrong conclusion from one run into the next.
Structured output. Set output_pydantic on a task to get a validated object instead of free text. Use it wherever another program consumes the result.
Trade-offs and alternatives
Section titled “Trade-offs and alternatives”Seen from CrewAI, the first decision is how much of it to use (crew alone, or flow plus crews); the second is whether another tool fits better.
| If you choose instead | You gain over a CrewAI crew | You give up from CrewAI | Choose it when |
|---|---|---|---|
| A CrewAI flow with crews inside | Deterministic routing and typed state in code, with agents only where reasoning is needed | Nothing from CrewAI, but there are two concepts to learn | Production pipelines with branching and state; the usual end state |
| One agent with tools | Fewest model calls, simplest traces | Role separation and the task-by-task handoff | The task fits one clear instruction set |
| LangGraph | Explicit state and edges, durable checkpoints and interrupts that you design | The role-and-task vocabulary and generated agent prompts; more code to write | Complex loops, approvals and long-running runs where every transition must be explicit |
LangChain create_agent |
A standard single-agent tool loop with middleware and a wide integration catalog | Multi-agent roles, delegation and crew-level guardrails | A tool-calling assistant or RAG app with one agent |
Failure modes and operations
Section titled “Failure modes and operations”- Cost multiplies quietly. Agents times tasks times iterations, plus the manager in hierarchical mode, plus memory. Log model calls and tokens per run and set
max_iter,max_rpmandmax_execution_time. - Handoff loss. The next agent sees a summary, not the source. Numbers and caveats disappear. Pass structured output between tasks and keep source references in it.
- Decorative backstories. Long role-play text consumes tokens and can pull the model off task. Keep backstories short and put constraints in the task and the guardrail.
- A reviewer agent as the only check. A model grading a model is weak evidence. Use code guardrails and a fixed test set as well.
- Hierarchical drift. A manager can delegate in circles or skip an agent. Prefer sequential or a flow unless routing truly cannot be decided in advance.
- Non-determinism in tests. Use a stub LLM, as above, for wiring tests, and a graded set of real inputs for quality. The
crewai testcommand runs a crew several times and scores it; the docs state it currently supports only OpenAI models. - Telemetry and tracing. CrewAI sends anonymous usage telemetry by default; set
CREWAI_DISABLE_TELEMETRY=trueto turn it off, and review what is collected before using it with regulated data. - Version drift. The framework releases often and older tutorials (for example, the separate short-term, long-term and entity memory types) no longer match. Pin the version and read the changelog on upgrade.
- Prompt injection through tools. Web pages and documents an agent reads can contain instructions. Limit tool permissions and keep destructive actions behind human approval.
When not to use it
Section titled “When not to use it”- A single prompt or a single agent can do it. Extra agents add cost without adding accuracy.
- The steps are fixed and deterministic. Write a function or a flow with no agents.
- You need exact control of every prompt and every transition. Use a lower-level runtime or the provider SDK.
- Latency matters. A multi-agent run takes several sequential model calls; it is a poor fit for interactive responses.
- Your stack is not Python. CrewAI is a Python framework.
Interview questions
Section titled “Interview questions”1. What is the difference between a crew and a flow? A crew is a team of agents working through tasks, where the model decides how to accomplish each one. A flow is code you write: methods connected by start, listen and router decorators, with typed state. Flows give deterministic control and call crews for the steps that need reasoning.
2. Sequential or hierarchical process? Sequential when the order of work is known, which is most of the time: it is cheaper and predictable. Hierarchical when the set and order of subtasks depends on the input and cannot be decided in advance. It needs a manager model, adds planning and review calls, and should have iteration and time limits.
3. How do you test a crew? At three levels. Wiring: a stub LLM and assertions on task order, context passing and guardrails, with no network. Components: each tool as a normal unit test. Quality: a graded set of real inputs run against the real model, scored by code checks first and by a rubric where needed, tracked across versions.
4. Senior scenario: a four-agent content crew produces good drafts but costs five times the estimate and sometimes invents figures. What do you change?
Measure first: log calls and tokens per agent and task to find where the spend is. Typical fixes are lowering max_iter, removing an agent whose step can be a code guardrail, using a smaller model for extraction and formatting steps, and switching off memory if it adds calls without measurable benefit. For invented figures, make the research task return structured output with a source for each number, pass that object through context, and add a guardrail that rejects any figure in the draft that is not in the research object. Then re-run the graded set to confirm quality held while cost fell.
5. Senior scenario: the business wants the crew to email customers directly. What must be true before you agree? The send action must be a narrow tool with a fixed sender, an allowlist of templates or a length and content guardrail, and rate limits. There must be human approval for anything outside a low-risk category, at least initially, an audit log of what was sent and why, and an idempotency key so a retry cannot send twice. Customer data sent to the model and to any memory store must be covered by the data-processing agreements. Start in a draft-only mode and compare drafts with human replies before enabling sending.
Key takeaways
Section titled “Key takeaways”- Agents have roles, tasks have expected outputs, crews run tasks, flows control the whole.
- Prefer sequential crews inside flows; reserve hierarchical for truly dynamic work.
- Put checks in code guardrails and structured output, not in another agent.
- Count model calls: every agent, manager and memory feature adds some.
- Test wiring with a stub LLM and quality with a graded set.
- If one agent or one function does the job, do not build a crew.
Related pages
Section titled “Related pages”Official references
Section titled “Official references”- CrewAI documentation: introduction
- Agents, tasks (guardrails, structured output) and crews
- Processes and flows
- Memory and LLMs
- Telemetry
crewaion PyPI (1.15.41 as of November 2026)- crewAIInc/crewAI on GitHub (documentation source used for verification)