What is CrewAI?
CrewAI is a framework for building multi-agent AI systems. It lets you define agents with specific roles, goals, and tools, then orchestrate them into crews that collaborate on complex tasks through structured workflows.
Installation
pip install crewai crewai-tools langchain-openai
Creating a Research Crew
from crewai import Agent, Task, Crew
from crewai_tools import SerperDevTool, WebsiteSearchTool
# Define agents
researcher = Agent(
role="Senior Research Analyst",
goal="Research and analyze topics thoroughly",
backstory="Expert researcher with deep analytical skills",
tools=[SerperDevTool(), WebsiteSearchTool()],
verbose=True
)
writer = Agent(
role="Content Writer",
goal="Create compelling content from research",
backstory="Experienced writer who turns research into clear articles",
verbose=True
)
# Define tasks
research_task = Task(
description="Research the latest trends in {topic}",
expected_output="Comprehensive research report with sources",
agent=researcher
)
writing_task = Task(
description="Write an article based on the research findings",
expected_output="Well-structured article ready for publication",
agent=writer,
context=[research_task]
)
# Create and run crew
crew = Crew(agents=[researcher, writer], tasks=[research_task, writing_task])
result = crew.kickoff(inputs={"topic": "AI in healthcare"})
print(result)
Agent Tools
# Built-in tools
from crewai_tools import (
FileReadTool, # Read files
DirectoryReadTool, # Browse directories
CodeInterpreterTool, # Execute code
SerperDevTool, # Web search
ScrapeWebsiteTool, # Scrape websites
)
# Custom tools
from crewai_tools import tool
@tool("Calculator")
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression."""
return str(eval(expression))
Best Practices
- Give agents specific, focused roles for better results
- Use task dependencies (context) to chain agent outputs
- Set verbose=True during development to debug agent reasoning
- Use local models via Ollama for cost control
- Implement guardrails to prevent unwanted agent behaviors