How to Build an Agent Using CrewAI: Simple Guide
To build an agent using
CrewAI, you define the agent's tasks and environment using Agent and Task classes, then run the agent with agent.run(). CrewAI simplifies creating AI agents by managing task execution and interaction flow.Syntax
The basic syntax to build an agent in CrewAI involves creating an Agent object, defining one or more Task objects, and then running the agent. Each Task represents a specific action or step the agent performs.
Agent(name, tasks): Creates an agent with a name and a list of tasks.Task(name, action): Defines a task with a name and an action function.agent.run(): Starts the agent to execute its tasks in order.
python
from crewai import Agent, Task def greet(): print('Hello from CrewAI agent!') # Define a task greet_task = Task('Greet', greet) # Create an agent with the task agent = Agent('MyAgent', [greet_task]) # Run the agent agent.run()
Output
Hello from CrewAI agent!
Example
This example shows how to build a simple CrewAI agent that performs two tasks: greeting and calculating a sum. It demonstrates defining tasks with functions, creating an agent, and running it to see the output.
python
from crewai import Agent, Task def greet(): print('Hello! I am your CrewAI agent.') def calculate_sum(): result = 5 + 7 print(f'The sum of 5 and 7 is {result}.') # Define tasks greet_task = Task('Greet', greet) sum_task = Task('CalculateSum', calculate_sum) # Create agent with tasks agent = Agent('SimpleAgent', [greet_task, sum_task]) # Run agent agent.run()
Output
Hello! I am your CrewAI agent.
The sum of 5 and 7 is 12.
Common Pitfalls
Common mistakes when building agents with CrewAI include:
- Not defining tasks as callable functions, which causes errors when running.
- Forgetting to pass tasks as a list to the
Agentconstructor. - Not calling
agent.run(), so the agent never executes.
Always ensure tasks are functions and properly linked to the agent.
python
from crewai import Agent, Task # Wrong: task action is not a function # greet_task = Task('Greet', 'say hello') # This will cause an error # Right way: def greet(): print('Hello!') greet_task = Task('Greet', greet) agent = Agent('Agent1', [greet_task]) agent.run()
Output
Hello!
Quick Reference
| Component | Description |
|---|---|
| Agent(name, tasks) | Creates an AI agent with a name and list of tasks |
| Task(name, action) | Defines a task with a name and a function to execute |
| agent.run() | Starts the agent to perform all tasks in order |
Key Takeaways
Define tasks as functions before adding them to an agent.
Pass tasks as a list when creating an Agent instance.
Always call agent.run() to execute the agent's tasks.
CrewAI manages task flow, making agent building simple.
Avoid passing non-callable objects as task actions.