Intermediate

Agents & Roles

Learn to design effective agents with clear roles, specific goals, compelling backstories, and the right tools for each job.

Agent Anatomy

Every CrewAI agent is defined by three required properties and several optional ones:

Python
from crewai import Agent

agent = Agent(
    # Required: What is this agent's job title?
    role="Senior Data Scientist",

    # Required: What is the agent trying to achieve?
    goal="Analyze datasets and extract actionable insights",

    # Required: Background that shapes the agent's behavior
    backstory="""You are a seasoned data scientist with 10 years
    of experience in statistical analysis and machine learning.
    You are known for finding patterns others miss and
    communicating findings clearly to stakeholders.""",

    # Optional configurations
    verbose=True,              # Show reasoning steps
    allow_delegation=True,    # Can delegate to other agents
    max_iter=15,              # Max reasoning iterations
    max_rpm=10,               # Rate limit (requests/minute)
    memory=True,              # Enable memory
    llm="gpt-4o",              # LLM model to use
    tools=[],                 # List of tools
)

Crafting Effective Roles

Poor RoleBetter RoleWhy Better
"Helper""Senior Research Analyst"Specific expertise and seniority
"Writer""Technical Blog Writer"Domain-specific writing style
"Coder""Python Backend Developer"Language and specialization
"Reviewer""QA Editor with SEO Expertise"Clear scope and dual skills

Adding Tools

Python
from crewai_tools import (
    SerperDevTool,       # Web search
    ScrapeWebsiteTool,   # Web scraping
    FileReadTool,        # Read files
    DirectoryReadTool,   # Read directories
)

# Search tool (requires SERPER_API_KEY)
search_tool = SerperDevTool()
scrape_tool = ScrapeWebsiteTool()

# Research agent with web tools
researcher = Agent(
    role="Web Research Specialist",
    goal="Find accurate, up-to-date information online",
    backstory="Expert at finding reliable information online.",
    tools=[search_tool, scrape_tool],
    verbose=True
)

# File-reading agent
analyst = Agent(
    role="Data Analyst",
    goal="Analyze data files and extract insights",
    backstory="Expert at reading and analyzing data files.",
    tools=[FileReadTool(), DirectoryReadTool()],
    verbose=True
)

Custom Tools

Python
from crewai.tools import tool

@tool("Calculate ROI")
def calculate_roi(investment: float, returns: float) -> str:
    """Calculate Return on Investment given investment and returns."""
    roi = ((returns - investment) / investment) * 100
    return f"ROI: {roi:.2f}%"

@tool("Get Stock Price")
def get_stock_price(symbol: str) -> str:
    """Get the current stock price for a given ticker symbol."""
    # In production, call a real API
    return f"{symbol}: $150.25"

# Agent with custom tools
financial_analyst = Agent(
    role="Financial Analyst",
    goal="Provide accurate financial analysis",
    backstory="Expert in financial modeling and valuation.",
    tools=[calculate_roi, get_stock_price],
    verbose=True
)

Agent Design Patterns

🔎

The Researcher

Gathers information using search and scraping tools. Focus the backstory on thoroughness and source evaluation.

📝

The Writer

Transforms research into content. Specify the writing style, audience, and format expectations in the backstory.

🔍

The Analyst

Processes data and extracts insights. Give tools for file reading, calculation, and data visualization.

The Reviewer

Validates quality and catches errors. Backstory should emphasize attention to detail and standards.

Backstory tip: The backstory is the most powerful lever for controlling agent behavior. A detailed backstory with specific expertise, personality traits, and working style produces much better results than a generic one.

What's Next?

In the next lesson, we will learn how to define tasks with clear descriptions, expected outputs, context dependencies, and callbacks.