Introduction
The three core abstractions in CrewAI - Agents, Tasks, and Crews - form the foundation of all multi-agent applications. Understanding how to effectively configure and combine these components is essential for building powerful AI teams.
Section Overview: We'll explore each component in depth, covering all configuration options, best practices, and common patterns.
Agents in Detail
Agent Configuration
🐍python
1from crewai import Agent
2from langchain_openai import ChatOpenAI
3from crewai_tools import SerperDevTool, WebsiteSearchTool
4
5# Full agent configuration
6agent = Agent(
7 # Identity
8 role="Senior Data Scientist",
9 goal="Analyze data and provide actionable insights",
10 backstory="""You are a senior data scientist with expertise in
11 machine learning and statistical analysis. You have worked at
12 top tech companies and published research in leading journals.
13 You excel at finding patterns in complex datasets and explaining
14 technical concepts to non-technical stakeholders.""",
15
16 # LLM Configuration
17 llm=ChatOpenAI(model="gpt-4o", temperature=0.3),
18
19 # Tools
20 tools=[SerperDevTool(), WebsiteSearchTool()],
21
22 # Behavior Settings
23 verbose=True, # Print agent reasoning
24 allow_delegation=True, # Can delegate to other agents
25 max_iter=15, # Max iterations per task
26 max_rpm=None, # Rate limit (requests per minute)
27
28 # Memory
29 memory=True, # Enable memory
30
31 # Function calling
32 function_calling_llm=None, # Separate LLM for function calls
33
34 # Execution
35 step_callback=None, # Callback after each step
36 cache=True # Cache tool results
37)Agent Parameters Explained
| Parameter | Type | Description |
|---|---|---|
| role | str | The agent's job title or function |
| goal | str | What the agent is trying to achieve |
| backstory | str | Background that shapes behavior |
| llm | LLM | Language model to use (default: GPT-4) |
| tools | List[Tool] | Tools the agent can use |
| allow_delegation | bool | Can delegate to other agents |
| verbose | bool | Print detailed execution logs |
| max_iter | int | Maximum reasoning iterations |
| memory | bool | Enable memory system |
Creating Specialized Agents
🐍python
1from crewai import Agent
2from crewai_tools import SerperDevTool, FileReadTool, DirectoryReadTool
3
4# Research Agent
5researcher = Agent(
6 role="Lead Research Analyst",
7 goal="Conduct thorough research and gather comprehensive data",
8 backstory="""You are a meticulous researcher with a talent for
9 finding obscure but relevant information. You always verify your
10 sources and provide citations for your findings.""",
11 tools=[SerperDevTool()],
12 allow_delegation=False, # Focuses on their own work
13 verbose=True
14)
15
16# Analysis Agent
17analyst = Agent(
18 role="Senior Data Analyst",
19 goal="Analyze research data and extract meaningful insights",
20 backstory="""You are an analytical thinker who excels at finding
21 patterns and correlations in data. You approach problems methodically
22 and always support conclusions with evidence.""",
23 tools=[FileReadTool(), DirectoryReadTool()],
24 allow_delegation=False,
25 verbose=True
26)
27
28# Writer Agent
29writer = Agent(
30 role="Content Strategist",
31 goal="Create compelling and well-structured content",
32 backstory="""You are a skilled writer with expertise in technical
33 communication. You can take complex information and present it in
34 a clear, engaging way for various audiences.""",
35 tools=[], # No external tools needed
36 allow_delegation=True, # Can ask others for clarification
37 verbose=True
38)
39
40# Manager Agent (for hierarchical crews)
41manager = Agent(
42 role="Project Manager",
43 goal="Coordinate the team and ensure high-quality deliverables",
44 backstory="""You are an experienced project manager who excels at
45 breaking down complex projects into manageable tasks. You know how
46 to leverage each team member's strengths.""",
47 tools=[],
48 allow_delegation=True, # Delegates to team members
49 verbose=True
50)Tasks in Detail
Task Configuration
🐍python
1from crewai import Task
2
3# Full task configuration
4task = Task(
5 # Core Definition
6 description="""Conduct comprehensive research on the current state
7 of autonomous AI agents. Focus on:
8 1. Major frameworks and platforms
9 2. Key capabilities and limitations
10 3. Recent breakthroughs and trends
11 4. Real-world applications and case studies
12
13 Be thorough and cite your sources.""",
14
15 expected_output="""A detailed research report containing:
16 - Executive summary
17 - Framework comparison table
18 - Capability analysis
19 - Trend predictions
20 - At least 10 cited sources""",
21
22 # Assignment
23 agent=researcher, # Agent responsible for this task
24
25 # Task Dependencies
26 context=[previous_task], # Use output from previous tasks
27
28 # Output Configuration
29 output_file="research_report.md", # Save output to file
30 output_json=None, # Pydantic model for JSON output
31 output_pydantic=None, # Pydantic model for structured output
32
33 # Execution Settings
34 async_execution=False, # Run asynchronously
35 human_input=False, # Require human approval
36
37 # Callbacks
38 callback=None # Function called on completion
39)Task Parameters Explained
| Parameter | Type | Description |
|---|---|---|
| description | str | Detailed task instructions |
| expected_output | str | What the output should contain |
| agent | Agent | Agent assigned to the task |
| context | List[Task] | Previous tasks to use as context |
| output_file | str | File path to save output |
| output_json | Type | Pydantic model for JSON output |
| async_execution | bool | Run task asynchronously |
| human_input | bool | Require human approval |
Advanced Task Patterns
🐍python
1from crewai import Task
2from pydantic import BaseModel
3from typing import List
4
5# Structured Output with Pydantic
6class ResearchReport(BaseModel):
7 title: str
8 summary: str
9 key_findings: List[str]
10 sources: List[str]
11 confidence_score: float
12
13research_task = Task(
14 description="Research AI agent frameworks",
15 expected_output="Structured research report",
16 agent=researcher,
17 output_pydantic=ResearchReport # Enforces structure
18)
19
20
21# Task with Dependencies (Context)
22task1 = Task(
23 description="Research the topic",
24 expected_output="Research findings",
25 agent=researcher
26)
27
28task2 = Task(
29 description="Analyze the research findings",
30 expected_output="Analysis report",
31 agent=analyst,
32 context=[task1] # Uses output from task1
33)
34
35task3 = Task(
36 description="Write a blog post based on the analysis",
37 expected_output="Blog post in markdown",
38 agent=writer,
39 context=[task1, task2] # Uses both previous outputs
40)
41
42
43# Async Task Execution
44async_task = Task(
45 description="Long-running research task",
46 expected_output="Comprehensive report",
47 agent=researcher,
48 async_execution=True # Runs without blocking
49)
50
51
52# Human-in-the-Loop Task
53approval_task = Task(
54 description="Generate content for review",
55 expected_output="Content draft",
56 agent=writer,
57 human_input=True # Pauses for human approval
58)
59
60
61# Task with Callback
62def on_complete(output):
63 print(f"Task completed with output: {output}")
64 # Send notification, update database, etc.
65
66callback_task = Task(
67 description="Task with callback",
68 expected_output="Some output",
69 agent=researcher,
70 callback=on_complete
71)Crews in Detail
Crew Configuration
🐍python
1from crewai import Crew, Process
2from crewai.memory import LongTermMemory, ShortTermMemory, EntityMemory
3
4# Full crew configuration
5crew = Crew(
6 # Core Components
7 agents=[researcher, analyst, writer],
8 tasks=[research_task, analysis_task, writing_task],
9
10 # Process Type
11 process=Process.sequential, # or Process.hierarchical
12
13 # Manager (for hierarchical process)
14 manager_llm=None, # LLM for manager decisions
15 manager_agent=None, # Custom manager agent
16
17 # Memory Configuration
18 memory=True,
19 long_term_memory=LongTermMemory(),
20 short_term_memory=ShortTermMemory(),
21 entity_memory=EntityMemory(),
22
23 # Embedder for memory
24 embedder={
25 "provider": "openai",
26 "config": {"model": "text-embedding-3-small"}
27 },
28
29 # Execution Settings
30 verbose=True,
31 max_rpm=None, # Rate limiting
32
33 # Output
34 output_log_file="crew_log.txt",
35 full_output=False, # Return full or just final output
36
37 # Callbacks
38 step_callback=None,
39 task_callback=None
40)Process Types
🐍python
1from crewai import Crew, Process
2
3# Sequential Process
4# Tasks execute in order, each using previous outputs
5sequential_crew = Crew(
6 agents=[researcher, analyst, writer],
7 tasks=[research_task, analysis_task, writing_task],
8 process=Process.sequential,
9 verbose=True
10)
11
12"""
13Sequential Flow:
14researcher → research_task → [output]
15 ↓
16analyst → analysis_task → [output]
17 ↓
18writer → writing_task → [final output]
19"""
20
21
22# Hierarchical Process
23# Manager agent coordinates other agents
24hierarchical_crew = Crew(
25 agents=[researcher, analyst, writer],
26 tasks=[research_task, analysis_task, writing_task],
27 process=Process.hierarchical,
28 manager_llm=ChatOpenAI(model="gpt-4o"), # Manager uses this LLM
29 verbose=True
30)
31
32"""
33Hierarchical Flow:
34 ┌──────────┐
35 │ Manager │
36 └────┬─────┘
37 ┌───────────────┼───────────────┐
38 ▼ ▼ ▼
39 ┌──────────┐ ┌──────────┐ ┌──────────┐
40 │researcher│ │ analyst │ │ writer │
41 └──────────┘ └──────────┘ └──────────┘
42
43Manager decides:
44- Which agent handles each task
45- When to delegate
46- How to combine outputs
47"""Memory Configuration
🐍python
1from crewai import Crew
2from crewai.memory import LongTermMemory, ShortTermMemory, EntityMemory
3
4# Crew with full memory configuration
5memory_crew = Crew(
6 agents=[researcher, analyst],
7 tasks=[research_task, analysis_task],
8 memory=True,
9
10 # Short-term memory: Current context and recent interactions
11 short_term_memory=ShortTermMemory(),
12
13 # Long-term memory: Persistent knowledge across sessions
14 long_term_memory=LongTermMemory(),
15
16 # Entity memory: Track entities and relationships
17 entity_memory=EntityMemory(),
18
19 # Custom embedder for memory operations
20 embedder={
21 "provider": "openai",
22 "config": {
23 "model": "text-embedding-3-small",
24 "api_key": "your-key"
25 }
26 }
27)
28
29# Memory enables:
30# 1. Agents remember previous interactions
31# 2. Knowledge persists across crew runs
32# 3. Entities and relationships are tracked
33# 4. Context is maintained throughout executionPutting It All Together
🐍python
1from crewai import Agent, Task, Crew, Process
2from crewai_tools import SerperDevTool, FileReadTool
3from langchain_openai import ChatOpenAI
4
5# Configure LLM
6llm = ChatOpenAI(model="gpt-4o", temperature=0.7)
7
8# Define Agents
9researcher = Agent(
10 role="Senior Technology Researcher",
11 goal="Research and analyze technology trends",
12 backstory="""You are an expert technology researcher with deep
13 knowledge of AI, software development, and emerging technologies.
14 You excel at finding reliable sources and synthesizing information.""",
15 llm=llm,
16 tools=[SerperDevTool()],
17 verbose=True
18)
19
20analyst = Agent(
21 role="Strategic Analyst",
22 goal="Provide strategic insights based on research",
23 backstory="""You are a strategic analyst who excels at connecting
24 dots and identifying implications of technology trends. You think
25 critically and challenge assumptions.""",
26 llm=llm,
27 tools=[FileReadTool()],
28 verbose=True
29)
30
31writer = Agent(
32 role="Technical Content Writer",
33 goal="Create clear, engaging technical content",
34 backstory="""You are a skilled technical writer who can explain
35 complex topics simply. You focus on clarity and actionability.""",
36 llm=llm,
37 verbose=True
38)
39
40# Define Tasks
41research_task = Task(
42 description="""Research the current state of AI agent frameworks.
43 Focus on LangGraph, CrewAI, and AutoGPT. Compare their:
44 - Architecture and design philosophy
45 - Key features and capabilities
46 - Use cases and limitations
47 - Community and ecosystem""",
48 expected_output="""A comprehensive research document with:
49 - Overview of each framework
50 - Comparison table
51 - Key insights and trends""",
52 agent=researcher
53)
54
55analysis_task = Task(
56 description="""Analyze the research findings to identify:
57 - Which framework is best for different use cases
58 - Emerging patterns in agent development
59 - Predictions for the future of AI agents""",
60 expected_output="""A strategic analysis with:
61 - Framework recommendations by use case
62 - Key trends and predictions
63 - Actionable recommendations""",
64 agent=analyst,
65 context=[research_task] # Uses research output
66)
67
68writing_task = Task(
69 description="""Write a blog post titled "Choosing the Right
70 AI Agent Framework in 2025" based on the research and analysis.
71 Make it engaging, practical, and actionable.""",
72 expected_output="""A blog post in markdown format with:
73 - Compelling introduction
74 - Framework comparisons
75 - Decision guide
76 - Conclusion with recommendations""",
77 agent=writer,
78 context=[research_task, analysis_task],
79 output_file="blog_post.md"
80)
81
82# Create and Run Crew
83crew = Crew(
84 agents=[researcher, analyst, writer],
85 tasks=[research_task, analysis_task, writing_task],
86 process=Process.sequential,
87 verbose=True,
88 memory=True
89)
90
91# Execute
92result = crew.kickoff()
93print("\n=== Final Output ===\n")
94print(result)Key Takeaways
- Agents need clear roles, goals, and backstories to maintain consistent, specialized behavior.
- Tasks define specific work with clear descriptions and expected outputs.
- Task context enables information flow - outputs from previous tasks inform subsequent ones.
- Crews orchestrate execution - sequential for ordered workflows, hierarchical for dynamic coordination.
- Memory enables learning across tasks and sessions.
Next Section Preview: We'll explore role-based agent design patterns for creating effective, specialized AI team members.