How to Build an AI Agent with CrewAI
CrewAIMulti-Agent
Learn how to build multi-agent systems using CrewAI framework from scratch.
How to Build an AI Agent with CrewAI
Introduction
Learn how to build multi-agent systems using CrewAI framework from scratch.
Prerequisites
- Python 3.10+
- OpenAI API key (or compatible LLM API)
- Basic understanding of Python
Step 1: Installation
pip install crewai
Step 2: Set Up Your API Key
export OPENAI_API_KEY="your-api-key-here"
Step 3: Define Your Agents
from crewai import Agent
# Research agent
researcher = Agent(
role='Senior Research Analyst',
goal='Uncover cutting-edge developments in AI and data science',
backstory="""You are an expert at understanding the nuances of AI and data science.
You are skilled at turning complex data into actionable insights.""",
verbose=True,
allow_delegation=True,
)
# Writer agent
writer = Agent(
role='Technical Writer',
goal='Create well-structured, engaging technical content',
backstory="""You are a skilled technical writer with expertise in AI and technology.
You can explain complex topics in an accessible way.""",
verbose=True,
allow_delegation=False,
)
Step 4: Define Your Tasks
from crewai import Task
research_task = Task(
description="""
Analyze the latest developments in AI and data science.
Focus on:
- Recent breakthroughs
- Emerging trends
- Industry impact
""",
expected_output="A comprehensive research report on AI developments",
agent=researcher,
)
writing_task = Task(
description="""
Write a technical blog post based on the research findings.
Make it accessible to developers and technical enthusiasts.
""",
expected_output="A well-structured blog post ready for publication",
agent=writer,
context=[research_task],
)
Step 5: Create Your Crew and Run
from crewai import Crew
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, writing_task],
verbose=2,
)
result = crew.kickoff()
print(result)
Advanced: Custom Tools
Create a Custom Tool
from crewai import Agent, Task, Crew, Tool
from crewai_tools import SerperDevTool
# Use built-in search tool
search_tool = SerperDevTool()
researcher = Agent(
role='Research Analyst',
goal='Find the latest information',
backstory='Expert researcher',
tools=[search_tool],
)
Create a Custom Tool
from crewai_tools import BaseTool
class MyCustomTool(BaseTool):
name: str = "My Custom Tool"
description: str = "Does something useful"
def _run(self, argument: str) -> str:
# Your custom logic here
return f"Result for: {argument}"
tool = MyCustomTool()
agent = Agent(role='Agent', goal='Goal', backstory='Backstory', tools=[tool])
Process Types
| Process | Description |
|---|---|
sequential | Tasks execute in order (default). |
hierarchical | Manager agent assigns tasks. |
consensual | All agents agree on assignments. |
Using Hierarchical Process
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, writing_task],
process=Process.hierarchical,
manager_llm="gpt-4",
)
Best Practices
- Define clear roles - Each agent should have a specific purpose.
- Write detailed backstories - Helps guide agent behavior.
- Use task context - Pass outputs between tasks.
- Enable delegation - Let agents collaborate.
- Use verbose mode - For debugging and understanding.
Troubleshooting
| Issue | Solution |
|---|---|
| API errors | Check your API key and quota |
| Poor results | Improve agent backstories and task descriptions |
| Slow execution | Reduce verbose mode, use smaller models for simple tasks |
| Delegation loops | Set allow_delegation=False on critical agents |
