Building an AI-Powered Learning Assistant with CrewAI

Himanshu Ranjan Last Updated : 11 Feb, 2025
6 min read

With the rapid advancements in AI, automating educational content creation has become more accessible and efficient. CrewAI is a powerful framework that enables developers to build AI-driven agents capable of handling structured workflows. In this guide, we demonstrate how to integrate CrewAI with OpenAI’s GPT models and Serper API to create an intelligent learning assistant. This system generates learning materials, quizzes, and project ideas based on user input, offering a personalized and interactive learning experience. By defining specialized agents and tasks, we automate the content creation process, making AI-powered education more scalable and effective.

Learning Objectives

  • Learn how CrewAI enables developers to create AI-driven agents that perform structured tasks efficiently.
  • Set up API keys and configure AI models to enhance agent capabilities.
  • Define and implement agents that generate learning materials, quizzes, and project ideas based on user input.
  • Create specialized tools, such as a project suggestion tool, to improve the AI-driven learning experience.
  • Use CrewAI to structure and automate the generation of educational resources, making learning personalized and scalable.

This article was published as a part of the Data Science Blogathon.

Building an AI-Powered Learning Assistant with CrewAI

Building an AI-powered learning assistant with CrewAI enables automated content generation for personalized education. By leveraging OpenAI’s GPT models and the Serper API, we can create agents that curate learning materials, generate quizzes, and suggest project ideas based on user input, making the learning process more interactive and scalable.

Prerequisites

Before we dive in, ensure you have the following:

  • Python installed (preferably Python 3.8+)
  • An OpenAI API key
  • A Serper API key

Step 1: Installing Dependencies

First, install the necessary Python package using:

!pip install crewai
!pip install crewai_tools

This will install CrewAI along with additional tools required for handling API integrations.

Step 2: Setting Up API Keys

To access OpenAI API and Serper API, you need to set environment variables in your Python script. Replace “your-openai-api-key” and “your-serper-api-key” with your actual API keys:

import os

# Set API keys as environment variables
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["SERPER_API_KEY"] = "your-serper-api-key"

How to Get OpenAI API Key?

  • Visit OpenAI’s API page.
  • Sign up or log in.
  • Navigate to API Keys and create a new key.
  • Copy the key and use it in the script above.

How to Get Serper API Key?

  • Visit Serper API.
  • Sign up and get an API key.
  • Copy the key and use it in your script.

Step 3: Importing Required Libraries

from typing import List, Dict, Type
from crewai import Agent, Crew, Task, LLM
from pydantic import BaseModel, Field
from crewai_tools import SerperDevTool
from crewai.tools import BaseTool

This imports the necessary modules for handling agents, tasks, and LLM interactions.

Step 4: Initializing the OpenAI Model

We will use GPT-4o as our language model for generating intelligent responses:

# Initialize LLM
llm = LLM(model="gpt-4o")

Step 5: Defining Output Models

We need structured output models for learning materials, quizzes, and project ideas.

class LearningMaterial(BaseModel):
    topic: str
    resources: List[str]

class Quiz(BaseModel):
    questions: List[str]
    feedback: Dict[str, str]

class ProjectIdea(BaseModel):
    topic: str
    expertise: str
    project_ideas: List[str]

These Pydantic models structure learning-related data:

  • LearningMaterial: Stores a topic and a list of resources (e.g., links, books).
  • Quiz: Contains questions and feedback (mapping questions/answers to explanations).
  • ProjectIdea: Defines a topic, required expertise, and a list of project_ideas.

They ensure consistency and easy validation in applications

Step 6: Creating a Custom Tool for Project Suggestions

We create a tool that generates project ideas based on user expertise:

class ProjectSuggestionInput(BaseModel):
    topic: str = Field(..., description="Main subject area for projects")
    expertise: str = Field(..., description="Skill level (beginner/intermediate/advanced)")

class ProjectSuggestionTool(BaseTool):
    name: str = "Project Idea Generator Tool"
    description: str = "Generates tailored project ideas based on subject and skill level"
    args_schema: Type[BaseModel] = ProjectSuggestionInput

    def _run(self, topic: str, expertise: str) -> Dict:
        ideas = []
        expertise = expertise.lower()

        if expertise == "beginner":
            ideas = [
                f"Create a basic {topic} concept explainer",
                f"Build a simple {topic} demonstration",
                f"Develop a {topic} vocabulary quiz"
            ]
        elif expertise == "intermediate":
            ideas = [
                f"Design a {topic} analysis tool",
                f"Create a {topic} comparison study",
                f"Build a {topic} data visualization"
            ]
        elif expertise == "advanced":
            ideas = [
                f"Develop an AI-powered {topic} assistant",
                f"Create a machine learning model for {topic} prediction",
                f"Build an automated {topic} analysis system"
            ]
        
        return {"topic": topic, "expertise": expertise, "project_ideas": ideas}

This custom tool generates project ideas based on expertise:

ProjectSuggestionInput: Defines input (topic, expertise) using Pydantic.

ProjectSuggestionTool:

  • Extends BaseTool, with a name, description, and structured input.
  • _run() suggests projects based on skill level:
    • Beginner → Simple explainers/quizzes.
    • Intermediate → Analysis/visualization.
    • Advanced → AI-powered/automated solutions.

It helps learners get tailored project ideas efficiently.

Step 7: Initializing Tools

search_tool = SerperDevTool()
project_tool = ProjectSuggestionTool()

These tools provide essential functionalities:

  • search_tool → Fetches external data.
  • project_tool → Generates project suggestions.

Together, they enhance an application by offering learning resources and tailored project ideas.

Step 8: Defining Agents

Agents are responsible for handling different tasks. We define three agents for learning materials, quizzes, and project ideas.

learning_material_agent = Agent(
    llm=llm,
    role="Learning Material Assistant",
    backstory="An AI agent that curates learning materials based on the user input",
    goal="Provide personalized learning materials which will help them to learn fast",
    tools=[search_tool],
    verbose=True
)

quiz_creator_agent = Agent(
    llm=llm,
    role="Quiz Creator Assistant",
    backstory="An AI agent that generates quizzes based on learning materials",
    goal="Provide personalized quizzes for topics.",
    tools=[search_tool],
    verbose=True
)

project_idea_agent = Agent(
    llm=llm,
    role="Project Idea Assistant",
    backstory="An AI agent that suggests project ideas based on user expertise",
    goal="Provide personalized project ideas for topics.",
    tools=[project_tool],
    verbose=True
)

This code initializes three AI agents with specific roles:

  • learning_material_agent → Curates learning materials using search_tool.
  • quiz_creator_agent → Generates quizzes based on topics, also using search_tool.
  • project_idea_agent → Suggests project ideas using project_tool.

Each agent has a backstory, goal, and tools to provide personalized learning support

Step 9: Creating Tasks

Each agent is assigned a specific task:

learning_material_task = Task(
    description="Generate learning materials for educational topics: {topics}.",
    expected_output='{"topic": "Physics", "resources": ["List of videos, articles, and exercises"]}',
    output_pydantic=LearningMaterial,
    agent=learning_material_agent
)

quiz_task = Task(
    description="Generate a quiz based on learning materials.",
    expected_output='{"questions": ["List of quiz questions"], "feedback": {"Q1": "Feedback", ...}}',
    output_pydantic=Quiz,
    agent=quiz_creator_agent
)

project_idea_task = Task(
    description="Generate project ideas for topics based on the expertise level.",
    expected_output='{"topic": "AI", "expertise": "Intermediate", "project_ideas": ["List of project ideas"]}',
    output_pydantic=ProjectIdea,
    agent=project_idea_agent
)

This code defines three tasks, each handled by a specific AI agent:

  • learning_material_task → Generates learning materials (LearningMaterial).
  • quiz_task → Creates quizzes with feedback (Quiz).
  • project_idea_task → Suggests project ideas based on expertise (ProjectIdea).

Each task has a description, expected JSON output, validation model, and assigned agent, ensuring structured and automated educational assistance.

Step 10: Creating the Crew and Running the Workflow

crew = Crew(
    agents=[learning_material_agent, quiz_creator_agent, project_idea_agent],
    tasks=[learning_material_task, quiz_task, project_idea_task],
    verbose=True
)

# Kickoff the workflow
crew.kickoff(inputs={
    "topics": "Machine Learning, Deep Learning, and Data Science",
    "expertise": "Intermediate"
})

The Crew initializes a team of AI agents—learning_material_agent, quiz_creator_agent, and project_idea_agent—to handle educational tasks like curating materials, generating quizzes, and suggesting projects. Each agent is assigned a specific task (learning_material_task, quiz_task, and project_idea_task), with verbose mode enabled for detailed logging. The crew.kickoff(…) function starts the workflow using input parameters such as topics (“Machine Learning, Deep Learning, and Data Science”) and expertise level (“Intermediate”). The agents process these inputs and dynamically generate structured learning resources, quizzes, and project ideas, automating and personalizing the learning experience.

# Agent: Learning Material Assistant
## Final Answer:
{
"topic": "Physics",
"resources":[
}
]
"Machine Learning: Machine learning course, exercises week 37 - [YouTube Video]
(https://www.youtube.com/watch?v=bk4AEcTu-oM)", "Machine Learning for Everybody - 
Full Course by [freeCodeCamp on YouTube](https://www.youtube.com/watch?
v=i_LwzRVP7bg)", "Project worksheets from [Machine Learning for Kids]
(https://machinelearningforkids.co.uk/worksheets)",
"Interactive exercises on Neural networks by [Google](https://developers.google.com/machine-learning/crash-course/neural-
networks/interactive-exercises)", "What is machine learning? - [Khan Academy Video]
(https://www.khanacademy.org/computing/code-org/x86138d92:how-ai-
works/x06130d92:what-is-ai/v/ai-what-is-machine-learning)",
"Deep Learning: Practical Deep Learning for Coders: Lesson 1 - [YouTube Video]
(https://www.youtube.com/watch?v=85F_h3xF3cE)",
"MIT Introduction to Deep Learning | 6.S191 - [YouTube Video]
(https://www.youtube.com/watch?v=ErnWZxJovaM)",
"Resources to get practice in deep learning - [Medium Article](https://medium.com/@moein.shariatnia/my-2-year-journey-into-deep-learning-part-iii-
resources-to-get-practice-and- "PyTorch and Tensorflow 2: Deep Learning and 
Artificial Intelligence - [Course Exercises](https://deeplearningcourses.com/c/deep-
learning-exercises)",
"Deep Learning Fundamentals -- Code material and exercises - [GitHub]
(https://github.com/Lightning-AI/dl-fundamentals)",
"Data Science: Data Science Lessons - [YouCubed](https://www.youcubed.org/data-
science-lessons/)",
"Learn Data Science Tutorial Full Course for Beginners by [freeCodeCamp YouTube
 Video](https://www.youtube.com/watch?v=ua-CiDNNj30)",
"Data Science Hands-On Crash Course - [YouTube Video](https://m.youtube.com/watch?
v=XU5pw3QRYjQ&t=269s)",
"65 Free Data Science Resources for Beginners - [EliteDataScience]
(https://elitedatascience.com/data-science-resources)",
"Data Science A-ZTM: Real-Life Data Science Exercises Included - [Udemy Course]
(https://www.udemy.com/course/datascience/?
srsltid=AfmBOoraZJVzu_Jn60aC5rPmdRArI_Gpo1m1w8-UIa3uBrd

Conclusion

We explored how to set up CrewAI with Serper API and OpenAI API to create a structured, AI-driven learning assistant. By defining agents, tasks, and a crew, we automated the generation of learning materials, quizzes, and project ideas based on user input. The integration of tools like SerperDevTool for search and a custom project suggestion tool enhanced the system’s ability to provide personalized recommendations. Finally, by executing the Crew workflow, we demonstrated how AI agents can collaborate to deliver structured educational content efficiently. This setup serves as a scalable foundation for building intelligent learning assistants, making AI-driven education more accessible and tailored to individual needs.

Key Takeaways

  • CrewAI automates educational content creation using AI agents.
  • It integrates seamlessly with OpenAI and Serper API for personalized learning.
  • Structured workflows improve content organization and efficiency.
  • Custom tools enhance AI capabilities for tailored recommendations.
  • CrewAI enables scalable, AI-powered interactive learning experiences.

Frequently Asked Questions

Q1. What is CrewAI used for?

A. CrewAI is a framework for building AI-driven agents that automate tasks, workflows, and decision-making processes.

Q2. How does CrewAI work?

A. CrewAI allows users to define agents with specific roles, assign tasks, and enable collaboration among them to achieve a goal efficiently.

Q3. Can CrewAI integrate with external APIs?

A. Yes, CrewAI supports integration with APIs like OpenAI, Serper, and custom tools for enhanced functionality.

Q4. Is CrewAI suitable for non-developers?

A. CrewAI requires Python knowledge, making it more suitable for developers or those with coding experience.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Hi there! I’m Himanshu a Data Scientist at KPMG, and I have a deep passion for data everything from crunching numbers to finding patterns that tell a story. For me, data is more than just numbers on a screen; it’s a tool for discovery and insight. I’m always excited by the possibility of what data can reveal and how it can solve real-world problems.

But it’s not just data that grabs my attention. I love exploring new things, whether that’s learning a new skill, experimenting with new technologies, or diving into topics outside my comfort zone. Curiosity drives me, and I’m always looking for fresh challenges that push me to think differently and grow. At heart, I believe there’s always more to learn, and I’m on a constant journey to expand my knowledge and perspective.

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details