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.
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.
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.
The building blocks
| Part | What you define | Design question |
|---|---|---|
| Agent | Role, goal, backstory, model, tools | What may this worker see and do? |
| Task | Description, expected output, agent, context | How will you know it is done? |
| Crew | Agents, tasks and a process | Who decides the order? |
| Flow | State and methods triggered by events | What must always happen? |
| Memory and knowledge | Information carried across work or loaded from sources | Who can read, correct and delete it? |
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.
"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 habit | Why it helps |
|---|---|
max_usage_count | Caps how often one tool may be used |
result_as_answer | Returns the tool's output directly, with no rewriting by the model |
| Crew caching, off by default in this version | Saves repeated calls, but cached data can be out of date |
| Narrow arguments | An order identifier is safer than a free-form query |
| Server-side identity | The 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.
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.
Sequential and hierarchical processes
| Aspect | Sequential | Hierarchical |
|---|---|---|
| Order | As you list the tasks | A manager delegates and reviews |
| Needs | Agents assigned to tasks | A manager model or manager agent |
| Predictability | Higher | Lower |
| Model calls | Fewer | More, for planning and review |
| Use when | The steps are known | Subtasks 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.
| Setting | Controls |
|---|---|
max_iter | Steps an agent may take for a task; the default in this version is 25 |
max_retry_limit | Retries after an error |
guardrail_max_retries | Retries after a failed guardrail |
max_execution_time | Time allowed for an agent's task |
max_rpm | Requests per minute, for rate limits |
allow_delegation | Whether 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.
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.
| Need | Flow feature to look at |
|---|---|
| Wait for several methods | and_ |
| Continue after any one of them | or_ |
| Keep state across restarts | @persist and a persistence backend |
| Collect a person's decision | @human_feedback |
| Multi-turn chat | Conversational 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.
| Scenario | Model calls | Input tokens |
|---|---|---|
| Normal run | 3 × 4 = 12 | About 36,000 |
| One task retried twice | 12 + 8 = 20 | About 60,000 |
| Manager adds one call before and after each task | 12 + 6 = 18 | About 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.
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
| Symptom | Likely cause | What to try |
|---|---|---|
| Agent repeats the same tool call | The result does not tell it what to do next | Return a clearer status; cap the tool's use |
| Run stops at the iteration limit | Task too broad or tools missing | Split the task or supply the missing data |
| Writer invents details | Upstream result omitted them | Require sources and an explicit list of unknowns |
| Output will not parse | Model ignores the format under pressure | Use a typed output and a guardrail with specific feedback |
| Manager picks the wrong worker | Roles overlap | Sharpen roles, or return to a sequential process |
| Cost rises after a release | Longer context or more retries | Compare 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
| Aspect | LangGraph | CrewAI | AutoGen |
|---|---|---|---|
| Mental model | Graph over shared state | Roles and tasks, plus flows | Agents exchanging messages |
| Control of the path | Explicit edges | Process type, or flow methods | Conversation patterns and team rules |
| Pause and resume | Checkpoints and interrupts | Flow persistence and human feedback | Saving and loading state |
| Status in November 2026 | Maintained, 1.x line | Maintained, frequent releases | Archived, not maintained by Microsoft |
| Fits | Defined processes needing control | Work that splits naturally into roles | Existing code only; migrate |
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
- Put validation, authorization and side effects in flow code or services, outside agent prompts.
- Give each agent only the tools its tasks need.
- Require approval before actions that are costly or hard to undo.
- Store run records you control, with identifiers that link to traces.
- Pin the version and replay recorded cases before upgrading.
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
| Mistake | Better practice |
|---|---|
| Many roles with identical tools and data | Add an agent only when something real differs |
| Vague expected outputs | State checkable results |
| A model deciding steps that never vary | Put them in a flow |
| Relying on backstory for safety | Enforce permissions in tools |
| Default limits everywhere | Set iterations, retries, time and budget |
| Passing whole transcripts onward | Pass 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
- CrewAI Flows
- CrewAI changelog
- CrewAI documentation
- AutoGen repository and status notice
- LangGraph graph API
Next steps
AutoGen, Semantic Kernel and Microsoft Agent Framework
The successor to AutoGen.
Supervisor and Orchestrator-Worker Patterns
Design delegation well.
Securing, Evaluating and Running Multi-Agent Systems
Operate teams of agents.