Skip to content

Quizzes are a useful way to practice what you or your students have learned and to keep track of progress. In this project, you'll build a educational quiz bot to help you generate quiz questions. Imagine you are a teacher needing to create a pop quiz based on your most recent lecture, or you are a student wanting to quiz yourself on this lecture. This tool will help you automate this task, track which questions have been asked to avoid repetition, and validate the responses.

You'll leverage OpenAI and prompt engineering to generate relevant questions.

The Data:

This quiz bot allows you to generate quizzes from any educational text. You have been provided with a sample data file from a physics-focused corpus, stored in the physics_lecture.txt file.

The text covers fundamental physics concepts, including speed, velocity, Newton's third law, and more. This content is sourced from ScienceQA (Saikh et al., 2022), a dataset originally designed for Machine Reading Comprehension (MRC) tasks. For this project, the dataset has been filtered to focus specifically on natural science topics related to physics, making it ideal for use with the quiz bot.

Source: https://huggingface.co/datasets/tasksource/ScienceQA_text_only?row=40 Saikh, Tanik et al. “ScienceQA: a novel resource for question answering on scholarly articles.” International Journal on Digital Libraries 23 (2022): 289 - 301.

Image generated with DALL-E (OpenAI)

# Import OpenAI and supporting libraries
import os
from openai import OpenAI

def read_text_from_file(filename):
    """
    Reads the first 500 lines of content from a file and returns it as a string.
    Args: filename (str): The name of the file to read.
    Returns: str: The content of the file as a string, or an empty string if the file is not found.
    """
    try:
        with open(filename, 'r') as file:
            return ''.join([next(file) for _ in range(500)])
    except FileNotFoundError:
        print(f"Error: {filename} not found.")
        return ""

# Read content from the file
content = read_text_from_file("physics_lecture.txt")

# Set up the OpenAI client
client = OpenAI()

# Setting up the recommended model
model = "gpt-4o-mini"
from openai import OpenAI

client = OpenAI()

# 1️⃣ Define the system prompt
system_prompt = """
You are a quiz bot designed to help educators and students.
Your role is to generate multiple-choice questions from educational text.
You support educators by creating structured quizzes that are clear, varied, and avoid repetition.
Each question should test understanding of the material and include plausible options.
"""

# 2️⃣ Define the user prompt template
user_prompt = """
Based on the following educational text, generate 5 multiple-choice quiz questions.
Each question must follow this format exactly:

Question: <Your question here>
Options:
A. <Option A>
B. <Option B>
C. <Option C>
D. <Option D>
Answer: <Correct option letter>

Educational text:
{educational_text}
"""

# 3️⃣ Function to generate quiz questions
def generate_quiz_questions(educational_text: str) -> list:
    prompt = user_prompt.format(educational_text=educational_text)

    response = client.chat.completions.create(
        model="gpt-4o-mini",  # <-- use supported model!
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": prompt}
        ],
        temperature=0.7
    )

    output_text = response.choices[0].message.content

    # Parse the 5 questions
    questions = []
    current = ""
    for line in output_text.strip().splitlines():
        if line.startswith("Question:") and current:
            questions.append(current.strip())
            current = line
        else:
            current += "\n" + line
    if current:
        questions.append(current.strip())

    return questions[:5]

# Example educational text
educational_text = """
Speed is the distance traveled divided by the time taken.
Velocity includes both speed and direction.
Newton's Third Law states that for every action there is an equal and opposite reaction.
Acceleration is the change in velocity over time.
"""

quiz_data = generate_quiz_questions(educational_text)

for i, q in enumerate(quiz_data, 1):
    print(f"\nQuestion {i}:\n{q}")