CrewAI Multi-Agent Guide

Describe a team by its roles and tasks, then put a flow around it so that your code stays in charge.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

CrewAI models work as a crew of agents with roles, carrying out tasks in an order or under a manager. Flows are event-driven Python classes that control state, branching and when a crew runs. A dependable design usually keeps the outer process in a flow and uses a crew only for the part that benefits from several viewpoints.

What you will learn: the building blocks, a runnable crew and flow, passing results between tasks, guardrails and limits, testing without a model, and how CrewAI compares with LangGraph and AutoGen.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and Topologies, Specialist Teams and Debate.

Versions used

Checked in November 2026 and run with crewai 1.15.45. A scripted model class replaces the real one, so the output shows how the framework moves work around, not how well a model writes. CrewAI releases often; check the changelog for your version.

Beginner Roles, tasks and crews

The building blocks

PartWhat you defineDesign question
AgentRole, goal, backstory, model, toolsWhat may this worker see and do?
TaskDescription, expected output, agent, contextHow will you know it is done?
CrewAgents, tasks and a processWho decides the order?
FlowState and methods triggered by eventsWhat must always happen?
Memory and knowledgeInformation carried across work or loaded from sourcesWho can read, correct and delete it?
Flow startvalidate input
Routerchoose path
Crewresearch, then write
Checkscode and people
Result
Fixed steps live in code; open-ended work lives in the crew.

What a role really changes

Role, goal and backstory become part of the prompt. They steer tone and focus but grant no skill or permission. Differences that matter come from different tools, different data, different checks or a fresh context. If two agents share all of those, one agent with clear instructions is usually cheaper and easier to debug. See Single-Agent vs Multi-Agent Systems.

A two-agent crew

A researcher gathers facts about a late order, and a writer turns them into a message. The writer's task lists the research task as context, and a guardrail function checks the length of the result.

import os

os.environ["CREWAI_DISABLE_TELEMETRY"] = "true"
os.environ["CREWAI_TRACING_ENABLED"] = "false"

from crewai import LLM, Agent, Crew, Process, Task  # noqa: E402
from crewai.llms.base_llm import BaseLLM  # noqa: E402

SEEN = []


class ScriptedLLM(BaseLLM):
    """Offline stand-in: one prepared answer per agent."""

    reply: str = ""

    def call(self, messages, *args, **kwargs):
        SEEN.append(str(messages))
        return f"Thought: I now know the answer\nFinal Answer: {self.reply}"


researcher = Agent(
    role="Researcher",
    goal="Collect facts about the order delay",
    backstory="You report only what the records show.",
    llm=ScriptedLLM(model="fake", reply="Carrier delay; new date Friday."),
    allow_delegation=False, max_iter=3,
)
writer = Agent(
    role="Support writer",
    goal="Write a short, accurate customer message",
    backstory="You never promise what the facts do not support.",
    llm=ScriptedLLM(model="fake",
                    reply="Your parcel is now expected on Friday."),
    allow_delegation=False, max_iter=3,
)


def short_enough(output):
    """Task guardrail: return (passed, value or feedback)."""
    text = output.raw.strip()
    return (len(text) < 200, text if len(text) < 200 else "Too long")


research = Task(description="Find why order {order_id} is late.",
                expected_output="Two facts.", agent=researcher)
message = Task(description="Tell the customer about order {order_id}.",
               expected_output="One short paragraph.", agent=writer,
               context=[research], guardrail=short_enough)

crew = Crew(agents=[researcher, writer], tasks=[research, message],
            process=Process.sequential, verbose=False)
result = crew.kickoff(inputs={"order_id": "A-17"})

for item in result.tasks_output:
    print(f"{item.agent}: {item.raw}")
print("final:", result.raw)
print("writer saw the research:", "Carrier delay" in SEEN[-1])

Output:

Researcher: Carrier delay; new date Friday.
Support writer: Your parcel is now expected on Friday.
final: Your parcel is now expected on Friday.
writer saw the research: True

The final line confirms that the writer's prompt contained the researcher's result. {order_id} in the task descriptions was filled from the inputs given to kickoff. Treat such inputs as untrusted: validate their shape before they are placed in a prompt.

Write expected outputs you can check

"Two facts, each with its record identifier" can be tested. "A great analysis" cannot. Where other code reads the result, ask for a typed output and validate it.

Giving agents tools

Tools come from the crewai.tools module, either by decorating a function with @tool or by subclassing BaseTool with a typed argument schema. The description is what the model reads when choosing, so state what the tool returns and when it should not be used.

Option or habitWhy it helps
max_usage_countCaps how often one tool may be used
result_as_answerReturns the tool's output directly, with no rewriting by the model
Crew caching, off by default in this versionSaves repeated calls, but cached data can be out of date
Narrow argumentsAn order identifier is safer than a free-form query
Server-side identityThe tool decides what this user may see

Attach tools to the agent or task that needs them and nowhere else. A writer that cannot query the database cannot leak from it, whatever a prompt says. For tools that change records, add an operation key and an approval step in your own code; see Reliable Tool Execution and Error Recovery.

What each agent actually sees

An agent does not share the others' thoughts. It sees its own role, its task, the context you attached and results from its tools. That is useful, because a reviewer with a fresh view can notice what an author missed. It also means that a detail left out of one result is gone for everyone downstream.

Research taskreads records
Typed resultfacts, sources, gaps
Writing taskuses only these
State what is unknown so the next task does not fill the gap by guessing.

Long results passed along a chain make every later prompt larger and dearer. Ask upstream tasks for compact, structured output with references to the full material. Handoffs, Routing, Shared State and Communication gives patterns for this.

Intermediate Processes, guardrails and flows

Sequential and hierarchical processes

AspectSequentialHierarchical
OrderAs you list the tasksA manager delegates and reviews
NeedsAgents assigned to tasksA manager model or manager agent
PredictabilityHigherLower
Model callsFewerMore, for planning and review
Use whenThe steps are knownSubtasks depend on what is found

Start sequential. Move to a manager only when your evaluation shows that a fixed order fails on real cases, and compare cost per successful task before and after.

Guardrails and limits

A task guardrail returns whether the output passed, together with either the accepted value or feedback. On failure the task can be attempted again with that feedback, up to a limit. Use code for rules that code can decide, such as length, required fields, allowed values and arithmetic.

SettingControls
max_iterSteps an agent may take for a task; the default in this version is 25
max_retry_limitRetries after an error
guardrail_max_retriesRetries after a failed guardrail
max_execution_timeTime allowed for an agent's task
max_rpmRequests per minute, for rate limits
allow_delegationWhether an agent may hand work to colleagues

These limits multiply. Several tasks, each with retries and many iterations, can allow far more calls than you expect. Set values deliberately, record calls per run and add an overall budget in your own code.

Running generated code

The agent option for code execution is marked deprecated in this version, which points to dedicated sandbox services instead. Whatever you use, never run model-written code with your application's permissions. See Tool Permissions, Approvals and Abuse Risks.

Flows: your code in charge

In a flow, @start marks the entry method, @listen runs a method after another method or a named route, and @router returns the name of the path to take. State can be a Pydantic model, which gives fields and types.

import os

os.environ["CREWAI_DISABLE_TELEMETRY"] = "true"
os.environ["CREWAI_TRACING_ENABLED"] = "false"

from crewai.flow.flow import Flow, listen, router, start  # noqa: E402
from pydantic import BaseModel  # noqa: E402


class Ticket(BaseModel):
    text: str = ""
    queue: str = ""
    reply: str = ""


class Triage(Flow[Ticket]):
    @start()
    def receive(self):
        return self.state.text.lower()

    @router(receive)
    def choose(self, text):
        self.state.queue = "refund" if "refund" in text else "general"
        return self.state.queue

    @listen("refund")
    def refund_path(self):
        # A real flow would start a crew here with crew.kickoff(...)
        self.state.reply = "Sent to a person for approval."

    @listen("general")
    def general_path(self):
        self.state.reply = "Answered from the help center."


for text in ["Please refund my order", "How do I change my address?"]:
    flow = Triage(suppress_flow_events=True)
    flow.kickoff(inputs={"text": text})
    print(f"{flow.state.queue:8} {flow.state.reply}")

Output:

refund   Sent to a person for approval.
general  Answered from the help center.

This routing uses a keyword so that it can run without a model. A real classifier needs a safe default for uncertain cases, and a message that mentions refunds in passing should be part of your test set.

NeedFlow feature to look at
Wait for several methodsand_
Continue after any one of themor_
Keep state across restarts@persist and a persistence backend
Collect a person's decision@human_feedback
Multi-turn chatConversational flows

These features exist in the version used here, but the listings above do not exercise them. Test persistence and approval with a restart before relying on either.

Memory and knowledge

Knowledge sources load material for agents to search. Memory stores information from earlier work and recalls it later. Both can improve answers and both can introduce stale, private or planted content into prompts. Decide what may be written, scope it to the right user or team, keep the source of each item, and provide a way to delete it. Check where embeddings and records are stored and which provider creates them. See Agent Memory Types and Persistence.

Estimating cost before you run

The example below is arithmetic, not a measurement. Suppose three tasks each need about four model calls in a normal run, with an average of 3,000 input tokens per call.

ScenarioModel callsInput tokens
Normal run3 × 4 = 12About 36,000
One task retried twice12 + 8 = 20About 60,000
Manager adds one call before and after each task12 + 6 = 18About 54,000

Real numbers differ because context grows during a task. Measure from traces, then set a budget that stops the run with a clear status.

Expert Testing, operating and comparing

Testing a crew

The scripted model in the first listing subclasses the framework's base model class. It records each prompt, which lets a test assert what a downstream agent received.

  • The right context reaches each task, and nothing private leaks into it
  • A failing guardrail retries and then stops at the limit
  • A tool error produces a defined outcome
  • Every router path, including the fallback, is exercised
  • A real-model evaluation set runs before releases

Observing runs

Record for each task the agent, model, calls, tokens, time, guardrail results and tool calls. CrewAI has its own observability and tracing features, some tied to its hosted platform. Anonymous telemetry and tracing are separate settings; the examples disable them with environment variables. Review what leaves your network before using real data.

Troubleshooting common symptoms

SymptomLikely causeWhat to try
Agent repeats the same tool callThe result does not tell it what to do nextReturn a clearer status; cap the tool's use
Run stops at the iteration limitTask too broad or tools missingSplit the task or supply the missing data
Writer invents detailsUpstream result omitted themRequire sources and an explicit list of unknowns
Output will not parseModel ignores the format under pressureUse a typed output and a guardrail with specific feedback
Manager picks the wrong workerRoles overlapSharpen roles, or return to a sequential process
Cost rises after a releaseLonger context or more retriesCompare traces for the same inputs before and after

Change one thing at a time and rerun the same cases. Rewriting a backstory, adding an agent and switching models together leaves you unable to say which change helped. Keep the failing input as a permanent test.

LangGraph, CrewAI and AutoGen

AspectLangGraphCrewAIAutoGen
Mental modelGraph over shared stateRoles and tasks, plus flowsAgents exchanging messages
Control of the pathExplicit edgesProcess type, or flow methodsConversation patterns and team rules
Pause and resumeCheckpoints and interruptsFlow persistence and human feedbackSaving and loading state
Status in November 2026Maintained, 1.x lineMaintained, frequent releasesArchived, not maintained by Microsoft
FitsDefined processes needing controlWork that splits naturally into rolesExisting code only; migrate
AutoGen is archived

The AutoGen repository states that Microsoft no longer provides bug fixes, security fixes, features or support, and recommends Microsoft Agent Framework for new work. See AutoGen, Semantic Kernel and Microsoft Agent Framework before building on older AutoGen tutorials.

Moving toward production

  1. Put validation, authorization and side effects in flow code or services, outside agent prompts.
  2. Give each agent only the tools its tasks need.
  3. Require approval before actions that are costly or hard to undo.
  4. Store run records you control, with identifiers that link to traces.
  5. Pin the version and replay recorded cases before upgrading.
Illustrative design, not a real deployment

A weekly market summary uses a flow to fetch approved sources, a crew of two agents to draft and critique, code to check that every figure appears in the sources, and a person to publish. The crew never has permission to publish.

Common mistakes

MistakeBetter practice
Many roles with identical tools and dataAdd an agent only when something real differs
Vague expected outputsState checkable results
A model deciding steps that never varyPut them in a flow
Relying on backstory for safetyEnforce permissions in tools
Default limits everywhereSet iterations, retries, time and budget
Passing whole transcripts onwardPass the structured result needed

Checklist

  • A single-agent baseline was compared with the crew
  • Every task has a verifiable expected output
  • Fixed process steps are in a flow
  • Limits are set at agent, task and run level
  • Tests run offline with a scripted model
  • Telemetry and tracing settings are chosen on purpose
  • The version is pinned

Frequently asked questions

Do I need a flow to use a crew?

No. A crew can be started directly. A flow helps once you need branching, state, several crews or steps that must always run.

How many agents should a crew have?

As few as the work needs, often two or three. Each addition should raise measured quality by enough to justify its calls.

Can agents run tasks in parallel?

Tasks can be marked for asynchronous execution, and a later task can take their results as context. Check ordering and rate limits in tests.

Which models does CrewAI work with?

It connects to a range of providers and can use custom model classes. Tool calling and structured output differ between models, so test yours.

References and further reading

Next steps