CrewAI makes it easy to build teams of AI agents that collaborate on complex tasks. This tutorial walks you through creating your first agent crew.
## What is CrewAI?
CrewAI is a Python framework for orchestrating role-playing autonomous AI agents. It handles:
- Agent definition and configuration
- Task delegation and execution
- Inter-agent communication
- Result aggregation
## Installation
```bash
pip install crewai crewai-tools
```
## Core Concepts
### Agents
An agent is an autonomous unit with:
- A role (what it does)
- A goal (what it tries to achieve)
- A backstory (context that shapes behavior)
- Tools (capabilities it can use)
### Tasks
A task is a specific objective with:
- A description
- An expected output
- An assigned agent
### Crew
A crew orchestrates agents working on tasks together.
## Building a Research Crew
Let's build a crew that researches topics and creates reports.
### Step 1: Define Agents
```python
from crewai import Agent
from crewai_tools import SerperDevTool, WebsiteSearchTool
# Research Agent
researcher = Agent(
role="Senior Research Analyst",
goal="Uncover cutting-edge developments and insights on the given topic",
backstory="""You are a seasoned researcher with a keen eye for detail.
You excel at finding relevant information from multiple sources and
synthesizing it into coherent insights. You always verify facts and
cite your sources.""",
tools=[SerperDevTool(), WebsiteSearchTool()],
verbose=True
)
# Writer Agent
writer = Agent(
role="Technical Content Writer",
goal="Create engaging, well-structured content based on research findings",
backstory="""You are an experienced technical writer who transforms
complex research into accessible, engaging content. You maintain
technical accuracy while ensuring readability for a broad audience.""",
verbose=True
)
# Editor Agent
editor = Agent(
role="Senior Editor",
goal="Ensure content is polished, accurate, and publication-ready",
backstory="""You are a meticulous editor with years of experience
in technical publishing. You check facts, improve clarity, and ensure
consistent style and tone throughout.""",
verbose=True
)
```
### Step 2: Define Tasks
```python
from crewai import Task
# Research Task
research_task = Task(
description="""Research the topic: {topic}
Your research should cover:
1. Current state and recent developments
2. Key players and their contributions
3. Challenges and opportunities
4. Future outlook
Provide detailed findings with sources.""",
expected_output="A comprehensive research report with cited sources",
agent=researcher
)
# Writing Task
writing_task = Task(
description="""Using the research findings, write a compelling article about {topic}.
The article should:
- Have an engaging introduction
- Present information in logical sections
- Include practical insights
- End with forward-looking conclusions
Target length: 1500-2000 words.""",
expected_output="A well-structured article in markdown format",
agent=writer,
context=[research_task] # Depends on research
)
# Editing Task
editing_task = Task(
description="""Edit and polish the article for publication.
Check for:
- Factual accuracy
- Grammar and spelling
- Clarity and flow
- Consistent formatting
Provide the final publication-ready version.""",
expected_output="A polished, publication-ready article",
agent=editor,
context=[writing_task] # Depends on writing
)
```
### Step 3: Assemble the Crew
```python
from crewai import Crew, Process
research_crew = Crew(
agents=[researcher, writer, editor],
tasks=[research_task, writing_task, editing_task],
process=Process.sequential, # Tasks run in order
verbose=True
)
```
### Step 4: Run the Crew
```python
result = research_crew.kickoff(
inputs={"topic": "AI Agents in Enterprise Software Development"}
)
print(result)
```
## Understanding the Execution
When you run the crew:
1. **Researcher** uses search tools to gather information
2. **Writer** receives research and drafts the article
3. **Editor** reviews and polishes the final output
Each agent sees the context from previous tasks, enabling coherent collaboration.
## Advanced Patterns
### Hierarchical Process
Use a manager agent to delegate:
```python
crew = Crew(
agents=[researcher, writer, editor],
tasks=[research_task, writing_task, editing_task],
process=Process.hierarchical,
manager_llm=ChatOpenAI(model="gpt-4")
)
```
### Custom Tools
Create specialized tools for your agents:
```python
from crewai_tools import BaseTool
class DatabaseQueryTool(BaseTool):
name: str = "Database Query"
description: str = "Query the internal knowledge database"
def _run(self, query: str) -> str:
results = database.search(query)
return format_results(results)
```
### Async Execution
Run crews asynchronously:
```python
import asyncio
async def run_research(topic):
result = await research_crew.kickoff_async(inputs={"topic": topic})
return result
results = asyncio.run(asyncio.gather(
run_research("AI Agents"),
run_research("Cloud Computing"),
run_research("Cybersecurity")
))
```
## Best Practices
1. **Clear role definitions**: Distinct roles prevent overlap
2. **Specific backstories**: Context shapes agent behavior
3. **Focused tasks**: One objective per task
4. **Appropriate tools**: Only include relevant tools
5. **Iterative refinement**: Test and adjust prompts
CrewAI abstracts the complexity of multi-agent coordination, letting you focus on defining what agents should do rather than how they communicate.