CrewAI Tutorial: The Complete Beginner's Guide (2026)
Table of Contents
- What Is CrewAI and Why Does It Matter?
- Prerequisites
- Installation and Setup
- Core Concepts: Agents, Tasks, Crews
- Agents
- Tasks
- Crews
- Building Your First Crew: An AI News Researcher
- Step 1: Define Your Tools
- Step 2: Create Your Agents
- Step 3: Define Tasks
- Step 4: Assemble and Run
- Adding Memory for Smarter Agents
- Using Different LLM Providers
- Anthropic Claude
- Local Models with Ollama
- Model Routing
- Process Types: Sequential vs Hierarchical
- Sequential Process
- Hierarchical Process
- Integrating Custom Tools
- Structured Output with Pydantic
- Production Tips
- Error Handling
- Observability
- Cost Control
- CrewAI Studio
- CrewAI vs Other Frameworks
- What to Build Next
- Key Takeaways
What Is CrewAI and Why Does It Matter?
CrewAI is a Python framework for building multi-agent AI systems using a role-based metaphor. Instead of writing complex orchestration logic, you define agents with roles, goals, and backstories, give them tasks to complete, and CrewAI handles the coordination.The framework has become one of the most popular choices for multi-agent development, with a growing ecosystem of tools, integrations, and enterprise features through CrewAI Enterprise. Its GitHub repository has attracted a large community of contributors, and companies are using it for everything from customer support automation to complex research pipelines.
What makes CrewAI stand out is its opinionated, high-level approach. Where LangGraph gives you a blank canvas and AutoGen focuses on conversational patterns, CrewAI gives you building blocks that map directly to how teams work — roles, tasks, and processes.
Prerequisites
Before starting, you need:
- Python 3.10 or higher
- An OpenAI API key (CrewAI uses OpenAI models by default, though you can configure others)
- Basic Python knowledge (functions, classes, pip)
Installation and Setup
Install CrewAI and its tools package:
bash
pip install crewai crewai-tools
Set your API key:
bash
export OPENAIAPIKEY="your-api-key-here"
You can also use other LLM providers. CrewAI supports Anthropic, Google, and any OpenAI-compatible endpoint through LiteLLM integration.
Core Concepts: Agents, Tasks, Crews
Agents
An Agent is a specialized AI worker with a defined role. Think of it as a team member with specific expertise.
python
from crewai import Agent
researcher = Agent(
role="Senior Research Analyst",
goal="Find comprehensive, accurate data on emerging AI trends",
backstory="""You are a seasoned research analyst with 15 years of experience
in technology markets. You excel at finding primary sources, identifying
patterns across datasets, and separating signal from noise. You never
fabricate data — if you can't find a reliable source, you say so.""",
verbose=True,
allow_delegation=False,
tools=[searchtool, scrapetool]
)
Key parameters:
- role: What this agent does (used in prompts to other agents)
- goal: What the agent is trying to achieve
- backstory: Context that shapes the agent's behavior and personality
- tools: What external capabilities the agent has access to
- allow_delegation: Whether this agent can delegate subtasks to other agents
- verbose: Whether to print detailed execution logs
Tasks
A Task is a specific piece of work assigned to an agent.
python
from crewai import Task
research_task = Task(
description="""Research the current state of AI agent frameworks.
Focus on: market adoption, key players, recent funding rounds,
and technical capabilities. Use web search to find recent data.""",
expected_output="""A structured research brief with:
- Top 5 frameworks by adoption
- Key differentiators
- Recent developments (last 6 months)
- Market trajectory analysis""",
agent=researcher
)
Key parameters:
- description: What the task requires (be specific — this drives quality)
- expected_output: What the output should look like (format and content)
- agent: Which agent handles this task
- context: Optional list of other tasks whose outputs feed into this one
Crews
A Crew is the team that executes tasks together.
python
from crewai import Crew, Process
crew = Crew(
agents=[researcher, writer],
tasks=[researchtask, writingtask],
process=Process.sequential,
verbose=True
)
result = crew.kickoff()
print(result)
Building Your First Crew: An AI News Researcher
Let's build a practical example — a crew that researches AI news and produces a summary report.
Step 1: Define Your Tools
CrewAI integrates with many tool providers. For search, you can use Serper or Tavily:
python
from crewai_tools import SerperDevTool, ScrapeWebsiteTool
search_tool = SerperDevTool()
scrape_tool = ScrapeWebsiteTool()
Step 2: Create Your Agents
python
from crewai import Agent
researcher = Agent(
role="AI Industry Researcher",
goal="Find the most important AI developments from the past week",
backstory="""You track AI industry developments daily. You know which
sources are reliable, which claims need verification, and how to
distinguish genuine breakthroughs from marketing hype.""",
tools=[searchtool, scrapetool],
verbose=True
)
editor = Agent(
role="Editorial Director",
goal="Transform raw research into a polished, engaging news brief",
backstory="""You've edited technology publications for years. You know
how to structure information for busy readers — lead with the most
important story, provide context, and keep it concise.""",
verbose=True
)
Step 3: Define Tasks
python
from crewai import Task
research_task = Task(
description="""Search for the top 5 most significant AI developments
from the past week. For each development:
- What happened (factual summary)
- Why it matters (impact analysis)
- Source URL
Focus on: new model releases, framework updates, major funding rounds,
and regulatory developments.""",
expected_output="""A list of 5 developments, each with a factual summary,
impact analysis, and source URL. Ordered by significance.""",
agent=researcher
)
editing_task = Task(
description="""Take the research findings and create a polished weekly
AI news brief. Structure it as:
- A compelling headline for each story
- 2-3 paragraph summary
- "Why it matters" section
- Keep total length under 1500 words.""",
expected_output="A formatted weekly AI news brief ready for publication.",
agent=editor,
c[research_task]
)
Step 4: Assemble and Run
python
from crewai import Crew, Process
crew = Crew(
agents=[researcher, editor],
tasks=[researchtask, editingtask],
process=Process.sequential,
verbose=True
)
result = crew.kickoff()
print(result)
Adding Memory for Smarter Agents
CrewAI supports memory, allowing agents to remember information across tasks and even across separate crew runs.
python
crew = Crew(
agents=[researcher, editor],
tasks=[researchtask, editingtask],
process=Process.sequential,
memory=True,
verbose=True
)
When memory is enabled, agents can:
- Remember what they've already researched (avoiding duplicate work)
- Build on previous findings
- Maintain context across long workflows
For persistent memory across sessions, integrate with Mem0 or Zep.
Using Different LLM Providers
CrewAI isn't locked to OpenAI. You can use any provider:
Anthropic Claude
python
researcher = Agent(
role="Researcher",
goal="Find accurate information",
backstory="Expert researcher",
llm="anthropic/claude-3-5-sonnet-20241022"
)
Local Models with Ollama
python
researcher = Agent(
role="Researcher",
goal="Find accurate information",
backstory="Expert researcher",
llm="ollama/llama3.1"
)
Use Ollama for local development and testing without API costs. Switch to a cloud provider for production.
Model Routing
Different agents can use different models. Put your budget-heavy reasoning on Claude or GPT-4o, and simple formatting tasks on GPT-4o Mini:
python
researcher = Agent(role="Researcher", llm="gpt-4o", ...) # Complex reasoning
formatter = Agent(role="Formatter", llm="gpt-4o-mini", ...) # Simple formatting
Process Types: Sequential vs Hierarchical
Sequential Process
Tasks execute in order. Each task's output feeds into the next task's context. Good for linear workflows.
python
crew = Crew(
agents=[researcher, writer, editor],
tasks=[researchtask, writingtask, editing_task],
process=Process.sequential
)
Hierarchical Process
A manager agent automatically coordinates the crew, deciding which agent handles what and in what order. Good for complex workflows where the optimal sequence isn't known in advance.
python
crew = Crew(
agents=[researcher, writer, editor],
tasks=[researchtask, writingtask, editing_task],
process=Process.hierarchical,
manager_llm="gpt-4o"
)
Integrating Custom Tools
You can create custom tools for any capability your agents need:
python
from crewai.tools import BaseTool
from pydantic import Field
class DatabaseQueryTool(BaseTool):
name: str = "Database Query"
description: str = "Queries the product database and returns results"
def _run(self, query: str) -> str:
# Your database query logic here
results = db.execute(query)
return str(results)
db_tool = DatabaseQueryTool()
analyst = Agent(
role="Data Analyst",
goal="Extract insights from product data",
backstory="Expert data analyst",
tools=[db_tool]
)
Structured Output with Pydantic
Force agents to return structured data:
python
from pydantic import BaseModel
class ResearchReport(BaseModel):
title: str
findings: list[str]
confidence: float
sources: list[str]
research_task = Task(
description="Research AI agent frameworks",
expected_output="Structured research report",
agent=researcher,
output_pydantic=ResearchReport
)
This integrates naturally with Pydantic AI and Instructor patterns.
Production Tips
Error Handling
Set retry limits and handle failures gracefully:
python
task = Task(
description="...",
agent=researcher,
maxretrylimit=3
)
Observability
Monitor your crews in production:
- LangSmith: Trace every agent step and identify bottlenecks
- LangFuse: Open-source cost tracking and performance monitoring
- AgentOps: Purpose-built agent analytics
Cost Control
- Use
max_rpmon agents to limit API calls per minute - Set
max_tokenson tasks to cap output length - Use cheaper models for simple tasks
CrewAI Studio
For teams that want a visual interface, CrewAI Studio provides a drag-and-drop builder for designing crews, testing configurations, and monitoring production runs.
CrewAI vs Other Frameworks
| Feature | CrewAI | LangGraph | AutoGen |
|---------|--------|-----------|---------|
| Learning Curve | Low | Medium-High | Medium |
| Control Level | High-level | Low-level | Medium |
| Best For | Role-based teams | Custom workflows | Conversational agents |
| Built-in Memory | Yes | Yes (checkpointing) | Yes |
| Visual Builder | CrewAI Studio | LangGraph Studio | AutoGen Studio |
| Process Types | Sequential, Hierarchical | Any graph topology | Group chat |
What to Build Next
Now that you have the basics, try these projects:
- Content pipeline: Research → Write → SEO optimize → Publish
- Customer support crew: Classifier → Specialist → Quality checker
- Data analysis team: Collector → Cleaner → Analyst → Visualizer
- Code review crew: Reviewer → Security auditor → Documentation checker
Each project will deepen your understanding of agent design, task decomposition, and tool integration. Check our guide to building multi-agent systems for architecture patterns that work at scale.
Key Takeaways
- CrewAI's role-based approach makes multi-agent development accessible. Define roles, tasks, and let the framework handle orchestration.
- Start with sequential processes. Move to hierarchical only when your workflow genuinely benefits from dynamic coordination.
- Write specific task descriptions. Vague tasks produce vague results. Include format requirements, constraints, and examples.
- Use different models for different agents. Save money by routing simple tasks to cheaper models.
- Add memory when agents need context. Memory prevents duplicate work and enables learning across runs.
- Monitor everything in production. Cost, latency, and output quality per agent.
Master AI Agent Building
Get our comprehensive guide to building, deploying, and scaling AI agents for your business.
What you'll get:
- 📖Step-by-step setup instructions for 10+ agent platforms
- 📖Pre-built templates for sales, support, and research agents
- 📖Cost optimization strategies to reduce API spend by 50%
Get Instant Access
Join our newsletter and get this guide delivered to your inbox immediately.
We'll send you the download link instantly. Unsubscribe anytime.
🔧 Tools Featured in This Article
Ready to get started? Here are the tools we recommend:
CrewAI
CrewAI is an open-source Python framework for orchestrating autonomous AI agents that collaborate as a team to accomplish complex tasks. You define agents with specific roles, goals, and tools, then organize them into crews with defined workflows. Agents can delegate work to each other, share context, and execute multi-step processes like market research, content creation, or data analysis. CrewAI supports sequential and parallel task execution, integrates with popular LLMs, and provides memory systems for agent learning. It's one of the most popular multi-agent frameworks with a large community and extensive documentation.
LangChain
Toolkit for composing LLM apps, chains, and agents.
Serper
Google SERP API optimized for AI retrieval pipelines. - Enhanced AI-powered platform providing advanced capabilities for modern development and business workflows. Features comprehensive tooling, integrations, and scalable architecture designed for professional teams and enterprise environments.
LangSmith
Tracing, evaluation, and observability for LLM apps and agents.
Enjoyed this article?
Get weekly deep dives on AI agent tools, frameworks, and strategies delivered to your inbox.