Skip to content
IRC-CodingIRC-Coding
crewaimulti-agent-systemspythonagent-frameworktutorialagent-teams

CrewAI Examples: Building Agent Teams

Practical CrewAI agent team examples. Learn roles, tasks, tools, and crew coordination with Python code.

I

IRC-Coding Team

14 min read
CrewAI Examples: Building Agent Teams

CrewAI Examples: Building and Coordinating Agent Teams

CrewAI is a Python framework for building AI agent teams using a role-based model. Instead of defining complex graphs (as with LangGraph), you simply describe who’s 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.

Created in 2024 by João Moura, CrewAI has quickly become the most beginner-friendly multi-agent framework available. It builds on LangChain but abstracts away the complexity. If you want to spin up a working agent team fast 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 run out of the box and can serve 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 (which orchestrates everything).

---

The 3 core components: Agent (Who?), Task (What?), Crew (How do they work together?).

The biggest advantage: Extremely quick 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 summary!

The CrewAI Architecture — How It Works

The Role Model

CrewAI is built on a simple yet 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 want to achieve? “Find all security vulnerabilities in the code”
  • 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 won’t compromise on standards” will respond differently from one with “You’re a helpful mentor who supports developers”.

The Task Lifecycle

When you call crew.kickoff(), here’s what happens:

  1. Task order is determined: With Process.sequential, tasks run in the order you defined them. With Process.hierarchical, a manager agent decides.
  2. Agent selection: Each task has an agent parameter. The corresponding agent is activated.
  3. LLM call: The agent receives its role, goal, backstory, the task description, and results from previous tasks as context.
  4. Tool use: If the agent has tools, it can call them (web search, file reading, etc.).
  5. Output: The agent’s result is passed to the next task.
  6. Delegation: If allow_delegation=True, an agent can hand off tasks to other agents.

Sequential vs. Hierarchical

Sequential (default): Tasks run one after another. The output of Task 1 automatically becomes context for Task 2. Simple, predictable, great 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, up-to-date, and accurate information on the given topic",
    backstory="""You're an experienced research analyst with 10 years under your belt.
    You have access to scientific databases and know how to distinguish
    reliable sources from unreliable ones.
    You always structure your research clearly and cite sources.""",
    verbose=True,           # Detailed logging
    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 thinks and does. Essential for debugging.
  • allow_delegation: If True, the agent can hand off tasks to other agents. Useful for managers or reviewers, risky if overused (costs add up!).
  • 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: If True, the agent retains memory across multiple tasks.

2. Task — The Assignment

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 include 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 single 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 for this task.
  • 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 the execution order, runs each task (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-researched, current, and accurate information on the topic",
    backstory="""You are a research expert with access to academic sources and 
    tech blogs. You know how to distinguish reliable from unreliable sources. 
    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 value. 
    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 meticulous editor with 20 years of experience. 
    You check for grammar, style, factual correctness, and SEO keywords. 
    You provide concrete feedback and improve the article directly. 
    You do not accept vague 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
    pros and cons, practical examples, and performance comparisons.
    Use web search for current information.""",
    expected_output="""Structured research with top 5 frameworks,
    pros/cons per framework, at least 3 sources per framework,
    and recommendation 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. Write in English, 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 value. Improve vague 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, and can delegate if needed for clarifications. Each step saves output files for debugging. Cost with GPT-4o: approximately $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: first security, then bugs, then style. 
    You assign a severity level to each issue (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: small, safe changes. 
    You never break existing functionality. You explain each change.""",
    tools=[file_reader],
    verbose=True
)

doc_writer = Agent(
    role="Technical Writer",
    goal="Create clear, understandable documentation for the 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: 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 table of all issues
    (file, line, severity, description), grouped by severity,
    with concrete recommendation 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 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 receives 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 problem-solving generalist. You know the knowledge 
    base inside out and can search the documentation. If 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 escalation.""",
    expected_output="""Either a solution with step-by-step instructions and 
    reference to KB articles, 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 troubleshooting steps, customer 
    environment, business impact, and recommendation.""",
    expected_output="""Escalation ticket with summary, all previous steps, 
    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 sequence!
    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 the problem immediately. Sometimes escalation is needed right away. The manager agent decides dynamically. The tradeoff: the manager makes an extra LLM call per decision, which costs more, but the flexibility is worth it.

Custom Tools for CrewAI

You can build your own tools when the built-in options don’t cut it:

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

# Using them:
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]
)

Key points for custom tools:

  • The description is critical — the LLM decides whether to use the tool based on it
  • The _run method must return a string (that’s what the LLM sees)
  • Handle errors in the tool itself: always return a useful string, never raise an exception
  • Security matters: sanitize inputs! The LLM could generate arbitrary SQL queries

Best Practices from the Field

1. Backstory matters more than you’d think

Backstory shapes the agent’s “character” and dramatically affects output quality. “You’re a strict reviewer who backs every claim with sources” produces very 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. Add web search, file access, or API integration and it becomes genuinely useful.

4. Keep costs under control

Each agent makes at least one LLM call. With 3 agents plus delegation plus a manager, that’s easily 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?

AspectCrewAILangGraph
ApproachRole-based (team metaphor)Graph-based (graph theory)
Setup time10 min for 3 agents30–60 min for the same workflow
ControlLess granularHighly granular (conditional edges)
Learning curveShallow — intuitiveSteep — graph concepts required
Cycles/loopsLimited (max_iter)Native (conditional edges)
Human-in-the-loopManualNative (interrupt)
DelegationNative (allow_delegation)Manual implementation
Manager agentNative (Process.hierarchical)Manual as a node
Best forStandard workflows, prototypesComplex, 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, conditions, human-in-the-loop
  • Both can coexist — CrewAI for rapid prototypes, LangGraph for the production version

Common Issues and Solutions

Problem: Agent hallucinates sources

Solution: Give the agent a web search tool and include in the task description: “All claims must be backed up with sources.”

Problem: Agent delegates too much

Solution: Set allow_delegation=False for agents that should work independently. Only managers and reviewers should be allowed to delegate.

Problem: Crew takes too long

Solution: Reduce max_iter, use faster models (GPT-4o-mini), decrease the number of agents, or disable memory.

Problem: Results are superficial

Solution: Refine expected_output with concrete requirements (length, structure, 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=True lets agents hand off tasks to others
  • Tools: Built-in (SerperDev, ScrapeWebsite, FileRead, DirectoryRead) and custom tools (BaseTool)
  • Memory: memory=True for context-aware recall across conversations
  • Output files: output_file per task for debugging and intermediate results
  • Costs: At least 1 LLM call per agent; manager and delegation add overhead
  • Comparison: CrewAI (fast, intuitive, limited control) vs. LangGraph (complex, fine-grained, production-ready)

FAQ

Can CrewAI work with local models? Yes, through 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 are great for development, but cloud models usually deliver better results.

How many agents should a crew have? 3-5 agents are typical and manageable. More than 8 becomes hard to control—agents delegate excessively 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 hand off tasks to each other. 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.

Keine Bücher für Kategorie "ki-agenten" gefunden.

Back to Blog
Share:

Related Posts