1. Installation & Environment Setup
CrewAI is a Python framework for orchestrating autonomous AI agents that collaborate to accomplish complex tasks. It requires Python 3.10 or higher and provides both a core library and an optional tools package for extended capabilities.
Install CrewAI with the tools extension for full capability:
# Install CrewAI core + tools
pip install crewai
pip install 'crewai[tools]'
# Verify installation
crewai version
CrewAI uses LLMs under the hood. By default it connects to OpenAI, but supports any provider. Set your API keys as environment variables:
# Required: LLM provider key (OpenAI is default)
export OPENAI_API_KEY="sk-your-openai-key-here"
# Optional: For web search tools
export SERPER_API_KEY="your-serper-key-here"
# Optional: For other providers
export ANTHROPIC_API_KEY="your-anthropic-key-here"
1.1 Verifying Your Setup
Confirm everything works with a minimal Python check:
import crewai
print(f"CrewAI version: {crewai.__version__}")
# Verify LLM connectivity
from crewai import LLM
llm = LLM(model="openai/gpt-4o-mini")
response = llm.call("Say hello in one word.")
print(f"LLM response: {response}")
pyenv or conda to create an environment: conda create -n crewai python=3.12 && conda activate crewai.
2. CrewAI CLI
The CrewAI CLI is your primary tool for scaffolding, running, testing, and training crews. It generates a well-structured project with YAML configuration files and Python entry points.
2.1 Project Scaffolding
Create a new crew project with a single command:
# Scaffold a new crew project
crewai create crew my_research_crew
# Scaffold a Flow project (event-driven orchestration)
crewai create flow my_research_flow
# Navigate into the project
cd my_research_crew
The scaffolded project structure looks like this:
my_research_crew/
├── pyproject.toml # Project config & dependencies
├── README.md # Auto-generated docs
├── .env # Environment variables (API keys)
├── .gitignore
└── src/
└── my_research_crew/
├── __init__.py
├── main.py # Entry point (kickoff)
├── crew.py # Crew class with decorators
└── config/
├── agents.yaml # Agent definitions
└── tasks.yaml # Task definitions
2.2 Run, Test & Train Commands
The CLI provides commands for the full development lifecycle:
# Run your crew
crewai run
# Test your crew (runs multiple iterations for quality assessment)
crewai test --n-iterations 3
# Train your crew (human feedback loop for agent improvement)
crewai train --n-iterations 5
# Install dependencies defined in pyproject.toml
crewai install
# Reset crew memories (long-term, short-term, entity)
crewai reset-memories --all
crewai run executes src/your_crew/main.py, which calls crew().kickoff(inputs={}). The crew() function returns a configured Crew instance assembled from your YAML definitions and Python decorators.
3. Build Your First Crew
A CrewAI crew consists of agents (who they are) and tasks (what they do). Both are defined in YAML files for clean separation of configuration from code.
3.1 Defining Agents in agents.yaml
# src/my_research_crew/config/agents.yaml
researcher:
role: "Senior Research Analyst"
goal: "Find comprehensive, accurate information about {topic}"
backstory: >
You are a seasoned research analyst with 15 years of experience
in synthesizing complex information from multiple sources.
You are meticulous about accuracy and always cite your sources.
verbose: true
allow_delegation: false
writer:
role: "Content Writer"
goal: "Write a compelling, well-structured article about {topic}"
backstory: >
You are an award-winning technical writer known for making
complex topics accessible. You structure content for maximum
clarity and reader engagement.
verbose: true
allow_delegation: false
3.2 Defining Tasks in tasks.yaml
# src/my_research_crew/config/tasks.yaml
research_task:
description: >
Research the topic: {topic}
Find key facts, recent developments, expert opinions,
and supporting data. Organize findings by theme.
expected_output: >
A detailed research brief with sections for key findings,
data points, expert quotes, and source references.
agent: researcher
writing_task:
description: >
Using the research provided, write a comprehensive article
about {topic}. Include an introduction, main sections with
headers, key takeaways, and a conclusion.
expected_output: >
A polished 1500-word article in markdown format with clear
structure, engaging prose, and factual accuracy.
agent: writer
output_file: "output/article.md"
3.3 Wiring in crew.py
The crew.py file connects your YAML definitions to Python using decorators:
from crewai import Agent, Task, Crew, Process
from crewai.project import CrewBase, agent, task, crew
@CrewBase
class MyResearchCrew:
"""My Research Crew for generating articles."""
agents_config = "config/agents.yaml"
tasks_config = "config/tasks.yaml"
@agent
def researcher(self) -> Agent:
return Agent(config=self.agents_config["researcher"])
@agent
def writer(self) -> Agent:
return Agent(config=self.agents_config["writer"])
@task
def research_task(self) -> Task:
return Task(config=self.tasks_config["research_task"])
@task
def writing_task(self) -> Task:
return Task(config=self.tasks_config["writing_task"])
@crew
def crew(self) -> Crew:
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True,
)
Run it with the CLI or directly from Python:
from my_research_crew.crew import MyResearchCrew
# Kickoff with dynamic inputs (replaces {topic} in YAML)
result = MyResearchCrew().crew().kickoff(
inputs={"topic": "The future of quantum computing in 2026"}
)
print(f"Final output:\n{result.raw}")
print(f"\nToken usage: {result.token_usage}")
Content Marketing at Scale
A startup uses CrewAI to produce 50 blog posts/week: a Research Agent finds trending topics, a Writing Agent drafts content, and an Editor Agent refines for tone and SEO. The crew reduced content production time from 4 hours to 20 minutes per post while maintaining quality.
4. Build with AI
CrewAI’s Build with AI feature lets you describe what you want in natural language and generates the crew configuration for you — agents, tasks, and wiring code.
4.1 AI-Assisted Crew Generation
# Use natural language to generate a crew
crewai create crew market_analyzer --provider openai
# The CLI will prompt you to describe your crew:
# "I need a crew that analyzes stock market trends,
# identifies investment opportunities, and generates
# a daily briefing report with risk assessments."
The AI assistant generates appropriate agent roles, task descriptions, and process configuration based on your description. You can then iterate:
# Review generated files
cat src/market_analyzer/config/agents.yaml
cat src/market_analyzer/config/tasks.yaml
# Edit and refine as needed
# Then test your crew
crewai run
5. Project Structure & Configuration
5.1 Understanding pyproject.toml
The pyproject.toml file manages dependencies and project metadata:
[project]
name = "my_research_crew"
version = "0.1.0"
description = "A CrewAI crew for research and writing"
requires-python = ">=3.10,<3.13"
dependencies = [
"crewai[tools]>=0.100.0",
]
[tool.crewai]
type = "crew"
5.2 Environment Variables & .env
CrewAI automatically loads .env files from your project root:
# .env file in project root
OPENAI_API_KEY=sk-your-key-here
OPENAI_MODEL_NAME=gpt-4o
SERPER_API_KEY=your-serper-key
# For alternative LLM providers:
ANTHROPIC_API_KEY=your-anthropic-key
GROQ_API_KEY=your-groq-key
You can also configure the default LLM per-agent in YAML:
# agents.yaml — override LLM per agent
researcher:
role: "Senior Research Analyst"
goal: "Find comprehensive information about {topic}"
backstory: "You are a meticulous researcher..."
llm: "anthropic/claude-sonnet-4-20250514"
writer:
role: "Content Writer"
goal: "Write compelling articles about {topic}"
backstory: "You are an award-winning writer..."
llm: "openai/gpt-4o"
.env to your .gitignore. Never commit API keys. For production deployments, use secret managers (AWS Secrets Manager, GCP Secret Manager, Azure Key Vault) instead of environment variables.
Next in the CrewAI SDK Track
In Part 2: Agents & Capabilities, we’ll deep dive into agent anatomy — LLM configuration for any provider, attaching tools, connecting MCP servers, injecting skills and knowledge sources, and crafting agents that consistently deliver high-quality results.