Artificial Intelligence Technology

Multi-Agent Systems With CrewAI — Agentic AI Series Part 3/4

So far in this Agentic AI series, we have focused on the theoretical aspects of agents — why they’re needed, how they work, and what makes them effective. In this third article of the series, we will shift our focus to practical implementation of agents using the CrewAI framework.

Feel free to checkout these links in case you have not gone through our previous article of this series:

Why Do We Need Agents? – Part 1
What Are AI Agents? – Part 2

About CrewAI

CrewAI is one of the many frameworks available for implementing the concept of agents. It simplifies the process of building AI agents by providing features that focus on high-level concepts, allowing you to concentrate more on ideas and objectives rather than implementation details. The term ‘crew’ in CrewAI reflects the idea of a team working together to achieve a goal, emphasising that this framework supports and focuses on multi-agent systems.

CrewAI is a Python framework and can be installed via the following command:

pip install crewai

Core Concepts

CrewAI includes three building blocks for creating agentic systems: agents, tasks, and crews. These are explained below.

Agents

An agent is the smallest functional unit in CrewAI. It performs tasks, makes decisions, and communicates with other agents to achieve its objectives. Agents have attributes such as:

  • Role: Specifies the agent’s function within the system. For example, in a software engineering agent-based system, roles may include ‘a UI designer,’ ‘a frontend developer,’ ‘a backend developer,’ ‘a tester,’ etc.
  • Goal: Defines the agent’s ultimate purpose and the objective it aims to achieve, guiding its decision-making process. For example, for a “tester” agent in a software engineering system, the goal could be “to ensure the codebase is free of all types of bugs, including logical and syntactical ones, and that the code performs according to the requirements”.
  • Backstory: Additional detailed information related to the role and goal that helps provide context and improve performance.

Tasks

Tasks are the specific jobs that agents handle within a multi-agent system. They detail what needs to be done, who’s doing it, and how it should be completed. Key attributes of tasks include:

  • Description: The task’s purpose, objective, and what needs to be done. For instance, a task for a tester agent might be ‘write unit tests for the authentication module.
  • Agent: Specifies the agent that is to perform the task.
  • Expected Output: Describes how the end result of the task should appear and what is expected. For example, for the task of writing tests for the authentication module, the expected output might be “unit test functions for every function in the authentication module.”

Crews

Crews are a team of agents that work together to achieve a common goal by performing a set of tasks. They define how tasks are carried out, how agents collaborate, and the overall flow of the system. Their main attributes include:

  • Tasks: The tasks that the agents in the crew are responsible for.
  • Agents: The agents that are part of the crew.
  • Process: The way tasks are carried out, the order in which they are performed, for example sequential or hierarchical.

There are various other attributes that may be assigned to agents, tasks, and crews, such as the LLM to use, tools to be utilised, and output formats, which can be explored in CrewAI’s documentation: https://docs.crewai.com/

The following diagram illustrates how a typical CrewAI looks. We define agents and assign tasks to them, then assemble them into a crew. We then “kickoff” the crew, initiating task execution and agent collaboration until the output is produced.

Implementing A Single Agent System

Let’s start by creating a single-agent system before progressing to a multi-agent one. For this example, we will develop a travel planning agentic system to create a travel itinerary based on user preferences such as destination, duration of the travel, budget, and interests. Let’s dive into the code.

Import necessary modules:

from crewai import Agent, Task, Crew

Define a function to create the agent, task, and crew, and to execute the agentic system:


def plan_travel_itinerary(destination, duration_days, budget_usd, interests):
   # Define the agent
   travel_planner_agent = Agent(
       role='Travel Itinerary Planner',
       goal='Create personalized travel itineraries',
       backstory="""As a travel itinerary planner, your role is to curate exciting and
       efficient travel plans for individuals or groups based on their preferences and interests.""",
   )
   # Define the task
   task = Task(
       description=f"""Create a travel itinerary for {duration_days} days in {destination} with a budget of ${budget_usd} USD.
       The itinerary should be tailored to the following interests: {interests}.""",
       expected_output='A briefly outlined but comprehensive travel itinerary only.',
       agent=travel_planner_agent,
   )
   # Create crew
   crew = Crew(
       agents=[travel_planner_agent],
       tasks=[task],
   )
   # Execute the crew and obtain results
   travel_plan = crew.kickoff()
   return travel_plan

Let’s try out the system, here we are hard coding the travel parameters but you could take them as input from users:

travel_plan = plan_travel_itinerary(
   destination='Abu Dhabi, UAE',
   duration_days=5,
   budget_usd=2000,
   interests=['adventure', 'cuisine', 'architecture'],
)
print(travel_plan.raw)

The output:

**5-Day Travel Itinerary for Abu Dhabi, UAE on a $2000 Budget**
**Day 1: Arrival and Initial Exploration**
- **Morning:**
 - Arrive at Abu Dhabi International Airport.
 - Transfer to your hotel (budget-friendly options: Premier Inn Abu Dhabi International Airport Hotel or Centro Yas Island).
 - Check-in and freshen up.
- **Afternoon:**
 - Visit Sheikh Zayed Grand Mosque (Free Entry).
 - Explore the stunning architecture and learn about Islamic culture.
- **Evening:**
 - Dine at Al Fanar Restaurant & Cafe for traditional Emirati cuisine.
 - Cost: ~$30
**Day 2: Adventure and City Tour**
- **Morning:**
 - Breakfast at the hotel.
 - Head to Ferrari World Abu Dhabi.
 - Experience thrilling rides and the world's fastest roller coaster.
 - Cost: ~$80
- **Afternoon:**
 - Lunch at Il Podio in Ferrari World.
 - Cost: ~$25
 - Visit Yas Marina Circuit for a guided tour of the Formula 1 track.
 - Cost: ~$60
- **Evening:**
 - Dinner at Yas Island's Cipriani for Italian cuisine with a view.
 - Cost: ~$60
**Day 3: Cultural and Architectural Delights**
- **Morning:**
 - Breakfast at the hotel.
 - Visit Qasr Al Watan, the Presidential Palace.
 - Explore the stunning architecture and exhibitions.
 - Cost: ~$15
- **Afternoon:**
 - Lunch at Cafe Milano, located in the Four Seasons Hotel.
 - Cost: ~$40
 - Visit the Louvre Abu Dhabi.
 - Discover a blend of art, culture, and impressive architecture.
 - Cost: ~$17
- **Evening:**
 - Dinner at Li Beirut, a fine-dining Lebanese restaurant.
 - Cost: ~$50
**Day 4: Desert Adventure**
- **Morning:**
 - Breakfast at the hotel.
 - Relax and enjoy the hotel amenities or a brief city walk.
- **Afternoon:**
 - Lunch at a local restaurant (budget option: Zahrat Lebnan).
 - Cost: ~$15
 - Embark on a Desert Safari Adventure.
 - Activities include dune bashing, sandboarding, camel riding, and a BBQ dinner.
 - Cost: ~$100
- **Evening:**
 - Enjoy the desert camp entertainment and dinner.
 - Return to the hotel late in the evening.
**Day 5: Souk Shopping and Departure**
- **Morning:**
 - Breakfast at the hotel.
 - Visit the Heritage Village for a glimpse into traditional Bedouin life.
 - Free Entry.
- **Afternoon:**
 - Lunch at Al Dhafra Restaurant, featuring traditional Emirati cuisine.
 - Cost: ~$30
 - Explore the Abu Dhabi Souk for last-minute shopping.
 - Purchase souvenirs and local handicrafts.
- **Evening:**
 - Return to the hotel, check out, and transfer to the airport.
 - Departure from Abu Dhabi International Airport.
**Estimated Total Cost:**
- Accommodation: ~$400 (5 nights at a budget hotel)
- Meals: ~$285
- Activities and Entrance Fees: ~$337
- Transport (local taxis, transfers): ~$200
- Miscellaneous/Souvenirs: ~$100
**Total: ~$1322 (leaving room for flexibility within the $2000 budget)**
Enjoy your adventure-filled and culturally immersive trip to Abu Dhabi!

Not bad is it! It came up with a very comprehensive plan considering user’s parameters, especially well keeping within budget constraints.

Implementing A Multi-Agent System

For our multi-agent system example, we’ll develop a game development system involving software and Quality Assurance engineers. The system will take a game description and write Python code for it.

First, let’s define the agents: a software engineer agent, a QA engineer agent, and a chief QA engineer agent, using two QAs to ensure the produced code quality is top-notch.

software_engineer_agent = Agent(
   role='Senior Software Engineer',
   goal='Create software as needed',
   backstory="""
       You are a Senior Software Engineer at a leading tech think tank.
       Your expertise in programming in python. and do your best to
       produce perfect code
   """,
   allow_delegation=False,
)
qa_engineer_agent = Agent(
   role='Software Quality Control Engineer',
   goal='create prefect code, by analizing the code that is given for errors',
   backstory="""
       You are a software engineer that specializes in checking code for errors.
       You have an eye for detail and a knack for finding hidden bugs.
       You check for missing imports, variable declarations, mismatched brackets and syntax errors.
       You also check for security vulnerabilities, and logic errors""",
   allow_delegation=False,
)
chief_qa_engineer_agent = Agent(
   role='Chief Software Quality Control Engineer',
   goal='Ensure that the code does the job that it is supposed to do',
   backstory="""
       You feel that programmers always do only half the job, so you are
       super dedicated to make high quality code.
   """,
   allow_delegation=True,
)

For the tasks, we have used an object-oriented approach to simplify task initialization, as each task requires a different agent. We have defined a code task, a review task, and an evaluate task:

class GameTasks:
@staticmethod
def code_task(agent, instructions):
 return Task(
  description=f"""
   You will create a game using python, be as simple as possible, prefer using simpler and builtin python libraries
   like turtle instead of pygame but feel free to use advanced libraries if required. These are the instructions:
   Instructions
   ------------
   {instructions}
   Your Final answer must be the full python code, only the python code and nothing else.
  """,
  agent=agent,
  expected_output="Full Python code for the game, only the python code and nothing else."
 )
@staticmethod
def review_task(agent, instructions):
 return Task(
  description=f"""
   You are helping create a game using python, these are the instructions:
   Instructions
   ------------
   {instructions}
   Using the code you got, check for errors. Check for logic errors,
   syntax errors, missing imports, variable declarations, mismatched brackets,
   and security vulnerabilities.
a
   Your Final answer must be the full python code, only the python code and nothing else.
  """,
  agent=agent,
  expected_output="Full Python code for the game, only the python code and nothing else."
 )
@staticmethod
def evaluate_task(agent, instructions):
 return Task(
  description=f"""
   You are helping create a game using python, these are the instructions:
   Instructions
   ------------
   {instructions}
   You will look over the code to insure that it is complete and
   does the job that it is supposed to do.
   Your Final answer must be the full python code, only the python code and nothing else.
  """,
  agent=agent,
  expected_output="Full Python code for the game, only the python code and nothing else."
 )

Finally, we define the function that creates and runs the the crew:

def develop_game(instructions):
   crew = Crew(
       agents=[
           software_engineer_agent,
           qa_engineer_agent,
           chief_qa_engineer_agent,
       ],
       tasks = [
           GameTasks.code_task(software_engineer_agent, instructions),
           GameTasks.review_task(qa_engineer_agent, instructions),
           GameTasks.evaluate_task(chief_qa_engineer_agent, instructions),
       ]
   )

   result = crew.kickoff()
   game_code = result.raw
   return game_code

Let’s try it out! We will attempt to create a Snake game as an example.

game_instructions = """
A Snake game. User plays as and controls the snake moves which around the screen and grows longer by eating food.
The game ends if the snake collides with itself or the walls/edges. It includes a score counter and an option to
restart by pressing Enter.
"""
game_code = develop_game(game_instructions)
print(game_code)

The code is too long to show here, but here’s a screenshot of the result of running the produced game code, and it works surprisingly well!

So now you have a brief overview of how to create agentic systems. We encourage you to experiment with CrewAI for your own ideas, such as an Instagram post writer, a stock analyzer, or any other agentic system concept you can imagine. Just think about the agents you need, the tasks they should perform, and assemble them using CrewAI. You can also check out CrewAI’s documentation (https://docs.crewai.com/) for additional features that might assist you as you build larger and more complex systems.

In our final part of the Agentic AI Series, we’ll dive into the future impact and possibilities of AI agents.