A good CrewAI agent is like a good employee: clear role, clear goal, the right tools. In this lesson you'll learn to define agents precisely and equip them with custom tools.
The role determines how the agent behaves. Be specific:
| Bad | Good |
|---|---|
| "Researcher" | "Senior Market Research Analyst specialized in B2B SaaS" |
| "Writer" | "Technical Content Writer with SEO expertise" |
| "Analyst" | "Financial Analyst focused on startup valuations" |
The goal defines the agent's success metric:
analyst = Agent(
role="Senior Data Analyst",
goal="Create precise, data-driven analyses with clear "
"actionable recommendations for management",
backstory="You have 10 years of experience in data analysis for "
"Fortune 500 companies. You communicate complex "
"findings clearly and actionably."
)
The backstory gives the agent context and personality. It influences communication style and decision-making.
from crewai.tools import tool
@tool("Web Search")
def web_search(query: str) -> str:
"""Searches the web for current information.
Use this tool for research on current topics."""
results = search_api.search(query, num_results=5)
return format_results(results)
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
class DatabaseQueryInput(BaseModel):
query: str = Field(description="SQL query for the database")
database: str = Field(default="analytics", description="Database name")
class DatabaseQueryTool(BaseTool):
name: str = "Database Query"
description: str = "Executes SQL queries on the analytics database"
args_schema: type[BaseModel] = DatabaseQueryInput
def _run(self, query: str, database: str = "analytics") -> str:
return db.execute(query, database)
When allow_delegation=True, an agent can delegate tasks to other agents:
manager = Agent(
role="Project Manager",
goal="Coordinate the team for optimal results",
allow_delegation=True, # Can delegate to other agents
tools=[project_tracker, communication_tool]
)
specialist = Agent(
role="Domain Expert",
goal="Deliver deep domain expertise",
allow_delegation=False, # Executes tasks itself
tools=[knowledge_base, calculation_tool]
)
CrewAI offers three memory types:
| Memory Type | Description | Configuration |
|---|---|---|
| Short-term | Current crew execution | Automatically active |
| Long-term | Across multiple runs | memory=True in Crew |
| Entity | Knowledge about entities | memory=True in Crew |
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, writing_task],
memory=True, # Enables long-term and entity memory
embedder={
"provider": "openai",
"config": {"model": "text-embedding-3-small"}
}
)
Practical tip: Invest time in precise roles and backstories. An agent with "Research Analyst" as its role delivers generic results. An agent with "Senior B2B SaaS Market Research Analyst focused on the DACH region" delivers relevant results.