CrewAI Examples: Building and Coordinating Agent Teams
CrewAI is a Python framework for building AI agent teams that uses a role-based model. Instead of defining complex graphs (like with LangGraph), you simply describe who is on your team, what each person does, and how they work together. It’s more intuitive — you think in roles and tasks, not nodes and edges.
CrewAI was developed by João Moura in 2024 and quickly established itself as the most beginner-friendly multi-agent framework. It builds on LangChain but abstracts away the complexity. If you want to get a working agent team up and running without learning graph theory, CrewAI is your best bet.
In this tutorial, I’ll walk you through three complete, production-ready examples: a content creation crew, a code review crew, and a customer support crew. All examples are runnable and can be used directly as templates for your own projects.
TL;DR — CrewAI in 90 Seconds
CrewAI is a role-based multi-agent framework: you define agents (with role, goal, and backstory), tasks (with description and expected output), and a crew (that coordinates everything).
---
The 3 core components: Agent (Who?), Task (What?), Crew (How do they work together?).
The biggest advantage: Incredibly fast to set up. A working 3-agent team in 50 lines of Python.
The limitation: Less fine-grained control than LangGraph. Complex conditional workflows and loops are harder to implement.
End of quick overview!
CrewAI Architecture — How It Works
The Role Model
CrewAI is built on a simple but powerful idea: you model an agent team like a real team. Each team member has:
- Role: Who is the agent? “Senior Data Analyst”, “Tech Writer”, “Security Expert”
- Goal: What does the agent aim to achieve? “Find all security vulnerabilities in the codebase”
- Backstory: What experience and personality does the agent have? “You’re a security expert with 15 years of penetration testing experience”
- Tools: What tools does the agent have access to? Web search, code execution, file access
The backstory matters — it shapes how the LLM “thinks” and responds. An agent with the backstory “You’re a strict reviewer who tolerates no compromises” will answer differently than one with “You’re a helpful mentor who supports developers”.
The Task Lifecycle
When you call crew.kickoff(), here’s what happens:
- Task order is determined: With
Process.sequential, tasks run in the order they’re defined. WithProcess.hierarchical, a manager agent decides. - Agent assignment: Each task has an
agentparameter. The corresponding agent is activated. - LLM call: The agent receives its role, goal, backstory, the task, and results from previous tasks as context.
- Tool use: If the agent has tools, it can invoke them (web search, file reading, etc.).
- Output: The agent’s result is passed to the next task.
- Delegation: If
allow_delegation=True, an agent can delegate tasks to other agents.
Sequential vs. Hierarchical
Sequential (default): Tasks execute one after another. The output of Task 1 automatically appears in the context of Task 2. Simple, predictable, good for linear workflows.
Hierarchical: A manager agent receives all tasks and decides which agent does what and in what order. The manager can redistribute tasks, reorder them, and evaluate results. Good for complex workflows, but more expensive (additional LLM call for the manager).
Installation and Setup
pip install crewai crewai-tools
API Keys:
export OPENAI_API_KEY="sk-..."
# For web search with SerperDev:
export SERPER_API_KEY="..."
Local models (free for development):
# Install Ollama and load a model
ollama pull llama3.1:8b
# Use in CrewAI:
from langchain_community.llms import Ollama
llm = Ollama(model="llama3.1:8b")
The 3 Core Components — In Detail
1. Agent — The Team Member
from crewai import Agent
researcher = Agent(
role="Senior Research Analyst",
goal="Find comprehensive, current, and precise information on a given topic",
backstory="""You are an experienced research analyst with 10 years of experience.
You have access to scientific databases and know how to distinguish reliable
sources from unreliable ones. You always structure your research clearly
and cite your sources.""",
verbose=True, # Detailed logs
allow_delegation=False, # This agent doesn't delegate
tools=[search_tool], # Tools this agent can use
llm=llm # Optional: custom LLM for this agent
)
Key parameters:
verbose=True: Shows detailed logs of what the agent is thinking and doing. Essential for debugging.allow_delegation: IfTrue, the agent can delegate tasks to other agents. Useful for managers or reviewers, but risky if overused (cost implications!).tools: List of LangChain tools. Without tools, the agent is just a chatbot.llm: You can use a different LLM per agent. For example, GPT-4o for complex tasks, GPT-4o-mini for simple ones.max_iter: Maximum number of iterations (default: 25). Protects against infinite loops.memory: IfTrue, the agent retains memory across multiple tasks.
2. Task — The Job
from crewai import Task
research_task = Task(
description="""Research the latest developments in AI programming in 2026.
Consider new tools, best practices, and real-world examples. The report
should cover at least 5 main points.""",
expected_output="""A detailed report with 5 main points (2-3 sentences each),
source citations, and a summary at the end.""",
agent=researcher,
output_file="output/research_report.md" # Optional: save output to file
)
Key parameters:
description: Be specific — vague tasks produce vague results.expected_output: Describe exactly how the output should look. This is the most important parameter. Instead of “write an article” → “write an 800-word article in Markdown with an introduction, 3 subheadings, and a conclusion”.agent: Which agent should handle this task?context: List of other tasks whose results should serve as context.output_file: Saves the output to a file. Handy for debugging.
3. Crew — The Team
from crewai import Crew, Process
crew = Crew(
agents=[researcher, writer, editor],
tasks=[research_task, write_task, edit_task],
process=Process.sequential, # or Process.hierarchical
verbose=True,
memory=True, # Memory across multiple runs
cache=True, # Cache for tool results
max_rpm=10 # Rate-limiting: requests per minute
)
result = crew.kickoff()
What kickoff() does: It validates agents and tasks, determines execution order, runs each task in sequence (agent receives context + task → LLM call → result), and returns the final output.
Example 1: Content-Creation Crew (Complete)
A team of researcher, writer, and editor for blog articles—with real tools, detailed prompts, and output files.
import os
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool, ScrapeWebsiteTool
# Initialize tools
search_tool = SerperDevTool()
web_scraper = ScrapeWebsiteTool()
# --- AGENTS ---
researcher = Agent(
role="Senior Content Researcher",
goal="Gather well-founded, current, and precise information on the topic",
backstory="""You are a research expert with access to academic sources
and tech blogs. You know how to distinguish reliable sources from
unreliable ones. You always structure your research clearly and
provide all sources with URLs.""",
tools=[search_tool, web_scraper],
verbose=True,
allow_delegation=False
)
writer = Agent(
role="Tech Journalist",
goal="Write an engaging, informative, and well-structured article",
backstory="""You are an award-winning tech journalist who explains
complex topics clearly. You write for a technical audience seeking
practical relevance. You use active language, short sentences, and
concrete examples.""",
verbose=True,
allow_delegation=False
)
editor = Agent(
role="Senior Editor",
goal="Ensure quality, accuracy, readability, and SEO optimization",
backstory="""You are a strict editor with 20 years of experience.
You check grammar, style, factual accuracy, and SEO keywords. You
provide concrete feedback and improve the article directly. You
do not accept imprecise statements or missing sources.""",
verbose=True,
allow_delegation=True # Editor can delegate to researcher or writer
)
# --- TASKS ---
research_task = Task(
description="""Research the topic 'Python Frameworks 2026'.
Find the top 5 Python frameworks for web development in 2026 with
strengths, weaknesses, practical examples, and performance comparisons.
Use web search for current information.""",
expected_output="""Structured research with top 5 frameworks,
strengths and weaknesses per framework, at least 3 sources per
framework, and recommendations for 3 use cases (startup, enterprise,
prototype).""",
agent=researcher,
output_file="output/research.md"
)
write_task = Task(
description="""Write a blog article (800-1200 words) based on the
research. Structure: introduction, main body with subheadings,
comparison table, practical examples, conclusion. Use active language.""",
expected_output="""Complete blog article in Markdown: 800-1200 words,
H1/H2 structure, comparison table, code examples, clear recommendation.""",
agent=writer,
output_file="output/article_draft.md"
)
edit_task = Task(
description="""Review and improve the article: grammar, style, factual
accuracy, SEO (meta description, keywords, headings), and practical
relevance. Improve any imprecise statements.""",
expected_output="""Final polished article in Markdown with SEO meta
description, improved readability, verified sources.""",
agent=editor,
output_file="output/article_final.md"
)
# --- CREW ---
content_crew = Crew(
agents=[researcher, writer, editor],
tasks=[research_task, write_task, edit_task],
process=Process.sequential,
verbose=True,
memory=True
)
result = content_crew.kickoff()
print(result)
What happens here: The researcher uses web search → the writer receives the research as context and writes the article → the editor reviews and improves it, delegating if needed for clarification. Each step saves output files for debugging. Cost with GPT-4o: roughly $0.50–$2.00 per run.
Example 2: Code-Review Crew (Complete)
A team for automated code reviews with a security focus.
from crewai import Agent, Task, Crew, Process
from crewai_tools import DirectoryReadTool, FileReadTool
file_reader = FileReadTool()
dir_reader = DirectoryReadTool(directory="src/")
# --- AGENTS ---
code_reviewer = Agent(
role="Senior Security Code Reviewer",
goal="Identify bugs, security issues, performance problems, and best-practice violations",
backstory="""You are a security expert with 15 years of experience.
You know OWASP Top 10, CWE Top 25, and common security patterns. You
review code systematically: security first, then bugs, then style. You
assign each issue a severity level (Critical/High/Medium/Low).""",
tools=[file_reader, dir_reader],
verbose=True
)
refactorer = Agent(
role="Refactoring Specialist",
goal="Improve code quality without changing functionality",
backstory="""You specialize in Clean Code, SOLID principles, and design
patterns. You refactor conservatively with small, safe changes. You
never break existing functionality. You explain every change.""",
tools=[file_reader],
verbose=True
)
doc_writer = Agent(
role="Technical Writer",
goal="Create clear, understandable documentation for improved code",
backstory="""You write clear technical documentation for developers.
You use code examples, diagrams, and tables. You document not just
WHAT, but also WHY.""",
verbose=True
)
# --- TASKS ---
review_task = Task(
description="""Review all code in the src/ directory.
Check for: OWASP Top 10, auth issues, hardcoded secrets, error handling,
performance (N+1 queries), code smells. Use DirectoryReadTool and
FileReadTool to read all files.""",
expected_output="""Code review report with a table of all issues
(file, line, severity, description), grouped by severity,
with concrete recommendations per issue.""",
agent=code_reviewer,
output_file="output/code_review.md"
)
refactor_task = Task(
description="""Refactor the code based on the review.
Priority: 1. Fix Critical/High issues, 2. Close security gaps,
3. Reduce code smells. IMPORTANT: Do not change functionality!""",
expected_output="""Refactored code with all changes listed
(file, what changed, why), before/after comparison for critical
changes, justification per refactoring.""",
agent=refactorer,
output_file="output/refactored_code.md"
)
doc_task = Task(
description="""Document the changes and new code.
Create CHANGELOG.md, function documentation, and a security checklist.""",
expected_output="""Complete documentation: CHANGELOG.md,
module documentation with function descriptions, code examples,
security checklist for future development.""",
agent=doc_writer,
output_file="output/documentation.md"
)
# --- CREW ---
code_crew = Crew(
agents=[code_reviewer, refactorer, doc_writer],
tasks=[review_task, refactor_task, doc_task],
process=Process.sequential,
verbose=True
)
result = code_crew.kickoff()
print(result)
Why this setup works: The reviewer reads code and finds issues using file tools → the refactorer gets the issue list and improves the code → the doc writer documents everything. Sequential process: each step builds on the previous one.
Example 3: Customer Support Crew (Hierarchical)
A team for automated customer support with manager coordination.
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool, FileReadTool
search_tool = SerperDevTool()
kb_reader = FileReadTool()
# --- AGENTS ---
triage_agent = Agent(
role="Support Triage Specialist",
goal="Correctly categorize and prioritize incoming support tickets",
backstory="""You analyze support requests in seconds. You identify
severity level, category (Technical, Billing, Feature Request), and
urgency. You route each ticket to the right agent.""",
verbose=True
)
solver_agent = Agent(
role="Technical Support Engineer",
goal="Resolve customer technical issues quickly and accurately",
backstory="""You're a generalist in technical troubleshooting.
You know the knowledge base inside out and can search documentation.
When you don't know a solution, you say so honestly and suggest
workarounds.""",
tools=[search_tool, kb_reader],
verbose=True
)
escalation_agent = Agent(
role="Escalation Manager",
goal="Escalate unresolved issues to the right team with full context",
backstory="""You decide when a problem needs specialist attention.
You ensure all information is passed along so the specialist doesn't
start from scratch. You prioritize escalations by business impact.""",
verbose=True
)
# --- TASKS ---
triage_task = Task(
description="""Analyze the support ticket: 'Customer can't log in.
Error message: Invalid token. Chrome on Windows 11.'
Determine category, severity, urgency, and recommended agent.""",
expected_output="""Triage report with category, severity + justification,
urgency, recommended agent, and initial assessment (2-3 sentences).""",
agent=triage_agent
)
solve_task = Task(
description="""Attempt to resolve the issue. Search the knowledge base
for 'Invalid token' and 'Login problems'. Search the web for solutions.
If solvable: provide step-by-step instructions. If not: prepare for escalation.""",
expected_output="""Either a solution proposal with step-by-step instructions
and knowledge base article reference, or an escalation report with all information
and recommendation for the receiving team.""",
agent=solver_agent
)
escalation_task = Task(
description="""If the issue couldn't be resolved, prepare
a professional escalation with problem description, previous resolution attempts,
customer system details, business impact, and recommendation.""",
expected_output="""Escalation ticket with summary, all previous
steps taken, assessed business impact, and priority recommendation.""",
agent=escalation_agent
)
# --- CREW (HIERARCHICAL) ---
support_crew = Crew(
agents=[triage_agent, solver_agent, escalation_agent],
tasks=[triage_task, solve_task, escalation_task],
process=Process.hierarchical, # Manager decides the order!
verbose=True
)
result = support_crew.kickoff()
print(result)
Why hierarchical? With support tickets, the right sequence isn’t always obvious. Sometimes the solver can fix it immediately. Sometimes escalation is needed right away. The manager agent decides dynamically. The trade-off: the manager makes an extra LLM call per decision — more expensive, but the flexibility is worth it.
Custom Tools for CrewAI
You can create custom tools when built-in tools aren’t enough:
from crewai_tools import BaseTool
class DatabaseQueryTool(BaseTool):
name: str = "Database Query Tool"
description: str = "Executes SQL queries and returns results."
def _run(self, query: str) -> str:
import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
try:
cursor.execute(query)
results = cursor.fetchall()
return str(results)
except Exception as e:
return f"Query failed: {str(e)}"
finally:
conn.close()
class APIRequestTool(BaseTool):
name: str = "API Request Tool"
description: str = "Makes HTTP requests to an API."
def _run(self, url: str, method: str = "GET") -> str:
import requests
response = requests.request(method, url)
return response.text
# Usage:
db_tool = DatabaseQueryTool()
api_tool = APIRequestTool()
analyst = Agent(
role="Data Analyst",
goal="Analyze data from the database",
backstory="You're a SQL expert.",
tools=[db_tool, api_tool]
)
Critical points for custom tools:
- The
descriptionis crucial — the LLM decides whether to use the tool based on it - The
_runmethod must return a string (that’s what the LLM sees) - Error handling in the tool: always return a useful string, never raise an exception
- Security: sanitize inputs! The LLM could generate arbitrary SQL queries
Best Practices from the Field
1. Backstory matters more than you think
The backstory shapes the agent’s “character” and heavily influences output quality. “You’re a strict reviewer who backs every claim with sources” produces dramatically different results than “You’re a reviewer.”
2. Expected output must be precise
“Write an article” → vague output. “Write an 800-word article in Markdown with H1/H2 structure, 3 code examples, and a comparison table” → precise output.
3. Tools make the difference
An agent without tools is just a chatbot. With web search, file access, or API integration, it becomes genuinely useful.
4. Control costs
Each agent makes at least one LLM call. With 3 agents + delegation + manager, you easily hit 10+ calls. Use GPT-4o-mini for simple tasks and GPT-4o only for complex ones.
5. Use output files
output_file per task saves intermediate results. Gold for debugging — you see exactly what each agent produced.
CrewAI vs. LangGraph — Which for What?
| Aspect | CrewAI | LangGraph |
|---|---|---|
| Approach | Role-based (team metaphor) | Graph-based (graph theory) |
| Setup time | 10 minutes for 3 agents | 30-60 minutes for the same workflow |
| Control | Less granular | Highly granular (conditional edges) |
| Learning curve | Shallow — intuitive | Steep — requires graph concepts |
| Cycles/loops | Limited (max_iter) | Native (conditional edges) |
| Human-in-the-loop | Manual | Native (interrupt) |
| Delegation | Native (allow_delegation) | Manual implementation |
| Manager agent | Native (Process.hierarchical) | Manual as a node |
| Best for | Standard workflows, prototypes | Complex, conditional workflows, production |
My recommendation:
- CrewAI for: content creation, code review, customer support, simple 2-5 agent teams
- LangGraph for: complex production workflows with loops, conditionals, human-in-the-loop
- Both can coexist — CrewAI for quick prototypes, LangGraph for production versions
Common Issues and Solutions
Problem: Agent hallucinates sources
Solution: Give the agent a web search tool and include this in the task description: “All claims must be backed by sources.”
Problem: Agent over-delegates
Solution: Set allow_delegation=False for agents that should work independently. Only manager and reviewer agents should be allowed to delegate.
Problem: Crew takes too long
Solution: Lower max_iter, use faster models (GPT-4o-mini), reduce the number of agents, or disable memory.
Problem: Results lack depth
Solution: Refine expected_output with concrete requirements for length, structure, and format.
Key Exam Topics
- CrewAI: Role-based multi-agent framework built on top of LangChain
- 3 core components: Agent (role, goal, backstory, tools), Task (description, expected_output, agent), Crew (agents + tasks + process)
- Process types: Sequential (linear order) vs. Hierarchical (manager agent coordinates)
- Delegation:
allow_delegation=Truelets agents delegate tasks to others - Tools: Built-in (SerperDev, ScrapeWebsite, FileRead, DirectoryRead) and custom tools (BaseTool)
- Memory:
memory=Truefor cross-context recall - Output files:
output_fileper task for debugging and intermediate results - Costs: At least 1 LLM call per agent; manager and delegation incur additional costs
- Comparison: CrewAI (fast, intuitive, limited control) vs. LangGraph (complex, fine-grained, production-ready)
FAQ
Can CrewAI work with local models?
Yes, via Ollama integration: from langchain_community.llms import Ollama; llm = Ollama(model="llama3.1:8b"). You can set llm per agent or globally in the crew. Local models work well for development, but cloud models typically deliver better results.
How many agents should a crew have? 3-5 agents are typical and manageable. More than 8 becomes difficult to control—agents over-delegate and costs spiral. For complex requirements, split into multiple smaller crews instead.
Can agents communicate with each other?
Yes, with allow_delegation=True agents can delegate tasks to one another. With Process.hierarchical, the manager agent can coordinate all agents and redistribute tasks.
How do I debug a crew?
Three tools: 1) verbose=True for detailed logs. 2) output_file per task for intermediate results. 3) LangSmith tracing (environment variables: LANGCHAIN_TRACING_V2=true).
What does a CrewAI run cost? With GPT-4o and 3 agents: roughly $0.50–$2.00 per run. With GPT-4o-mini: roughly $0.05–$0.20. With local models (Ollama): $0 but slower and lower quality.
Recommended Reading
Keine Bücher für Kategorie "ki-agenten" gefunden.


