Master Multi-Agent AI Systems with CrewAI: Ultimate Beginner to Advanced Guide
Jaypalsinh Jadeja
Content Strategist for Web3 & AI Brands | 130K+ Impressions | Making crypto accessible and understandable to everyone | SEO Expert |
Imagine you have a small team of digital assistants, each with its own specialty: one can search the web, another can write files, and a third can generate creative marketing copy. Now picture them working together to complete a larger project—like combing through a website to collect data and then suggesting a personalized campaign based on that data. That is the magic of a multi-agent system.
CrewAI is an open-source Python framework for orchestrating these teams of specialized AI agents. You can think of it as a project manager that gives each agent a role and a set of tools, assigns tasks in a certain order, and then oversees the entire operation. This makes it possible to tackle projects more complex than any single agent could handle alone.
In this blog post, we’ll walk through the fundamental concepts behind multi-agent systems, then dive deep into how CrewAI helps you build one from scratch. We’ll explore how to scrape websites, store text files, perform text searches, and even build a simple recommendation engine that suggests courses to students based on their profile. By the end, you’ll have a clear understanding of how to build your own multi-agent system—no matter if you’re a beginner just testing the waters or an experienced developer curious about the next level.
Key Insights About Multi-Agent Systems
The idea of having multiple AI agents work together goes back several decades, in fields like robotics and distributed computing. Early AI researchers realized that coordinating many small, specialized programs could outperform a single “monolithic” system. Over time, as computing power and machine learning techniques grew, multi-agent systems moved from labs into real-world scenarios—like supply chain optimization, automated trading bots, and even interactive game environments.
Today, frameworks such as CrewAI simplify the creation of multi-agent systems. Instead of coding every single detail about how agents communicate and share data, you can rely on CrewAI’s built-in mechanisms for “agent roles,” “tasks,” and “crews.” This gives you a quick setup without reinventing the wheel.
In-Depth Explanation of CrewAI’s Building Blocks
Before we dive into code, let’s break down the core components you’ll need to understand:
Setting Up the Environment
1. Prerequisites
2. Installation
Create and activate a virtual environment:
python -m venv venv
source venv/bin/activate # on Ubuntu/macOS
venv\Scripts\activate # on Windows
Install the required packages:
pip install crewai-tools crewai langchain_openai python-dotenv
3. Environment Variables
You’ll need an OpenAI API key to run certain language model–based agents. Create a file named .env in your project folder and add your OpenAI API key:
OPENAI_API_KEY=sk-xxxxxx...
(If you prefer a different LLM, you can adapt the code to use another provider.)
Example 1: Building a Web Search Tool
Let’s build a simple system that scrapes a webpage, writes the content to a text file, and then uses that text file for quick searches.
Step 1: Scraping the Website
ScrapeWebsiteTool: This tool fetches text from a webpage. In the example below, we’re scraping the Wikipedia page on Artificial Intelligence.
from crewai_tools import ScrapeWebsiteTool, FileWriterTool, TXTSearchTool
from crewai import Agent, Task, Crew
import os
from dotenv import load_dotenv
# Load .env variables
load_dotenv()
os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')
# Initialize the ScrapeWebsiteTool
scraper = ScrapeWebsiteTool(website_url='https://en.wikipedia.org/wiki/Artificial_intelligence')
scraped_text = scraper.run()
print(scraped_text[:500]) # Just print the first 500 characters for a quick peek
Tip: Always check if the site you want to scrape allows it by reading their robots.txt or Terms of Service.
Step 2: Storing the Scraped Data
Use FileWriterTool to write the scraped text to a file (e.g., ai.txt):
file_writer = FileWriterTool()
scraped_text_ascii = scraped_text.encode("ascii", "ignore").decode() # Clean up non-ASCII chars
result = file_writer._run(filename='ai.txt', content=scraped_text_ascii, overwrite="True")
print(result)
Step 3: Setting Up TXTSearchTool
Once we’ve got ai.txt, we can use TXTSearchTool for quick lookups:
领英推荐
search_tool = TXTSearchTool(txt='ai.txt')
query_result = search_tool.run('What is Natural Language Processing?')
print(query_result)
Step 4: Creating an Agent to Answer Questions
Now we can create a simple Educator agent that processes the “context” from the text search and answers a question. In practice, you’d want a language model agent that uses the query_result as context.
data_analyst = Agent(
role='Educator',
goal='Based on the context provided, answer the question - "What is Natural Language Processing?"',
backstory='You are a data expert',
verbose=True,
allow_delegation=False,
tools=[search_tool]
)
test_task = Task(
description="Understand the topic and give the correct response",
tools=[search_tool],
agent=data_analyst,
expected_output='Give a correct response'
)
crew = Crew(
agents=[data_analyst],
tasks=[test_task]
)
answer = crew.kickoff()
print(answer)
Example 2: Creating a Recommendation Campaign
Next, let’s do something more intricate: building an education recommendation system. The idea is that we have a list of student profiles (degrees, hobbies, GPA, etc.) and a list of courses. We want a set of agents to figure out which three courses are best for each student, then generate a marketing message.
Step 1: Prepare the Data
We’ll store student data in a CSV format. Each row has columns like “Academic Goals,” “Major,” “Hobbies,” “Computer Skills,” etc. We also have a list of courses with short descriptions:
import pandas as pd
csv_data = '''Academic Goals, Major, Hobbies, Computer Skills, Interest in Languages, GPA
To become a software engineer, Computer Science, Gaming, Advanced, Spanish, 3.7
To study environmental science, Environmental Science, Hiking, Intermediate, French, 3.5
...
'''
df_customers = pd.read_csv(StringIO(csv_data), sep=",")
Then we store available courses in a Python string:
courses = """
"Introduction to Computer Science" - Offered by Harvard University on edX
"Biology: Life on Earth" - Offered by Coursera
...
"""
Step 2: Define Agents and Tasks
We’ll create three main agents for the first stage:
After that, a second Crew will have:
from crewai import Agent, Task, Crew, Process
from textwrap import dedent
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo-16k", temperature=0.1, max_tokens=8000)
student_profiler = Agent(
role='student_profiler',
goal='From limited data, you logically deduct conclusions about students.',
backstory='Expert psychologist with decades of experience.',
llm=llm,
allow_delegation=False,
verbose=True
)
course_specialist = Agent(
role='course specialist',
goal='Match the suitable course to the students',
backstory='Exceptional knowledge of the courses.',
llm=llm,
allow_delegation=False,
verbose=True
)
Chief_Recommendation_Director = Agent(
role="Chief Recommendation Director",
goal=dedent("""\
Oversee the work done by your team to make sure it's top quality.
You can review, approve, or ask clarifying questions."""),
backstory='Chief Promotion Officer of a large EdTech company.',
llm=llm,
allow_delegation=False,
verbose=True
)
campaign_agent = Agent(
role="campaign_agent",
goal="Develop compelling content for ad campaigns.",
backstory="Creative Content Creator at a top-tier digital marketing agency.",
llm=llm,
allow_delegation=False,
verbose=True
)
Step 3: Define Task Functions
Each Task describes the prompt, the agent to handle it, and what we expect in return. For instance, get_ad_campaign_task instructs the Chief Recommendation Director to pick exactly three courses for a student.
def get_ad_campaign_task(agent, customer_description, courses):
return Task(
description=dedent(f"""
You're creating a targeted marketing campaign tailored to the student.
Choose exactly three courses to promote next. Use this list: {courses}
Student details: {customer_description}
Your final answer MUST be exactly 3 courses, each with a short reason.
"""),
agent=agent,
expected_output='A refined finalized version of the marketing campaign in markdown format'
)
def get_ad_campaign_written_task(agent, selection):
return Task(
description=dedent(f"""
We have chosen these three courses for the student: {selection}.
Write a short promotional message (around 3 paragraphs).
Your final answer MUST include the 3 courses with a brief message for each.
"""),
agent=agent,
expected_output='A refined finalized version of the marketing campaign in markdown format'
)
Step 4: Execute the Process
We iterate through each student in our dataset. For each row:
df_output_list = []
for index, row in df_customers.iterrows():
customer_description = f"""
Academic goals: {row['Academic Goals']}
Major: {row[' Major']}
Hobbies: {row[' Hobbies']}
Computer skills: {row[' Computer Skills']}
Languages: {row[' Interest in Languages']}
GPA: {row[' GPA']}
"""
task1 = get_ad_campaign_task(Chief_Recommendation_Director, customer_description, courses)
targetting_crew = Crew(
agents=[student_profiler, course_specialist, Chief_Recommendation_Director],
tasks=[task1],
verbose=True,
process=Process.sequential
)
targetting_result = targetting_crew.kickoff()
task2 = get_ad_campaign_written_task(Chief_Recommendation_Director, targetting_result)
copywriting_crew = Crew(
agents=[campaign_agent, Chief_Recommendation_Director],
tasks=[task2],
verbose=True,
process=Process.sequential
)
copywriting_result = copywriting_crew.kickoff()
df_output_list.append({
'customer': customer_description,
'targeted_courses': targetting_result,
'promo_msg': copywriting_result
})
df_output = pd.DataFrame(df_output_list)
print(df_output)
When you run python app.py, you’ll see a table in your terminal with each student’s description, the recommended courses, and a promotional message.
Practical Tips For Building Multi-Agent Systems
Conclusion
Building a multi-agent system may sound complicated, but frameworks like CrewAI make it far more approachable. By splitting tasks among specialized agents—who can delegate, communicate, and collaborate in a structured way—you can solve bigger, more interesting problems. From a simple web scraper that answers questions about a Wikipedia page, all the way to a multi-step recommendation pipeline for an EdTech company, the possibilities are huge.
The biggest takeaway is that multi-agent systems harness the power of specialization and coordination. Once you grasp these basics, you can go on to design anything from business automation flows to advanced academic research tools. The only limit is your imagination!
Additional Resources and External Links Building Multi-Agent Systems
Thanks for reading! If you found this tutorial useful, consider sharing it or leaving a comment. Good luck exploring the world of collaborative AI agent teams!
Harnessing Agentic AI, Data, and Human Behavior to Drive Innovation ? Fueled by Coffee and Curiosity ??
3 周Nice insights on multi-agent AI! A key challenge in real-world applications is balancing autonomy and coordination. Too much autonomy, and agents operate in silos; too much coordination, and you introduce bottlenecks. How does CrewAI handle explainability when agents interact dynamically? #aiagents #multiagentsystem #autonomy
Web3 @RFX Exchange and @Showdown Gaming | $2mil+ TVL | 12k+ Gamers | Building zksync Era's best capital Efficient perpetual DEX | Exploring Advanced Tech Solutions
1 个月Love this Jaypalsinh Jadeja Keep sharing this helpful content.