AI Quiz Generator with Python and Gemini

Build a CLI quiz tool that uses Gemini AI to generate and evaluate quizzes.

Introduction

30 Second Summary

Quizzes are one of the best ways to learn something new. What if you could type in any topic and instantly get a custom quiz with AI-powered feedback on your answers?

In this project, you will build a Python command-line tool that uses Google's Gemini AI to generate quizzes on any subject you choose. You'll answer questions in your terminal and get personalized feedback on your responses.

What You'll Build

A Python CLI tool that calls the Gemini API to generate structured quiz questions, presents them interactively, and uses AI to evaluate your free-text answers.

By the end of this project, you'll have:

  • A working Python script that calls the Gemini API to generate quiz questions on any topic.
  • Structured output using Pydantic data models that forces the AI to return valid, parseable JSON.
  • An interactive command-line quiz experience that collects your answers and uses AI to evaluate them with a score and feedback.
  • Secret Mission: Add difficulty levels and a persistent score tracker to your quiz tool.

Are there any prerequisites?

This project assumes you have basic Python knowledge (variables, functions, loops, and input/output). You'll also need a Google account to get a free Gemini API key.

Before We Start

Before you build anything, you need two things in place. You need the Google AI SDK installed so your Python code can talk to Gemini, and you need an API key that grants you access to the model.

In this step, you will install the SDK, grab a free API key from Google AI Studio, and confirm your connection works with a test call.

In this step, get ready to:
  • Install the google-genai Python package.
  • Get a free Gemini API key from Google AI Studio.
  • Verify your API connection with a test script.
Open VS Code and install the google-genai package
  • Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
  • Type Visual Studio Code and press Enter to open it.
  • Open a terminal inside VS Code by pressing Ctrl+` (backtick) or selecting Terminal then New Terminal from the top menu.

The google-genai package is Google's official Python SDK for calling Gemini models. It handles authentication, request formatting, and response parsing.

  • Install the package by running this command:
pip install google-genai==2.9.0

What does this command do?

This installs version 2.9.0 of the google-genai SDK from PyPI. Pinning the version ensures your project uses the same version as this tutorial, avoiding unexpected differences.

Pydantic (a data validation library you will use later) is bundled as a dependency, so you do not need to install it separately.

  • Confirm the install worked by running:
pip show google-genai
  • Look for Version: 2.9.0 in the output.

✔️ I see Version: 2.9.0

The package is installed and ready. Move on to the next substep.

ⓧ pip: command not found

Some systems use pip3 instead of pip for Python 3. Try running:

pip3 install google-genai==2.9.0

If that still fails, confirm Python is on your system path by running python --version in the same terminal.

Get a free Gemini API key from Google AI Studio

To call the Gemini API, you need an API key. Google provides free-tier access with no credit card or billing setup required.

  • Open https://aistudio.google.com in your browser.
  • Sign in with your Google account.
  • Accept the Terms of Service when prompted. This automatically creates a default project and API key for you.
  • Open the Dashboard from the left panel.
  • Click API Keys to view your keys.
  • Copy your API key and save it somewhere safe. You will need it in the next substep.

Is this really free?

Gemini 2.5 Flash has free input and output tokens on the free tier. No credit card is required. This project makes roughly 5-10 API calls per session, well within the free allowance.

One caveat: content sent on the free tier may be used to improve Google products.

Keep your API key private

Your API key is like a password. Do not share it publicly, commit it to Git, or paste it into forums. If someone else gets your key, they can use your quota.

Can't find your API key?

Make sure you accepted the Terms of Service first. The key is auto-created after acceptance. Look for the API Keys section under Dashboard in the left panel.

If you still cannot find a key, click Create API key at the top of the API Keys page to generate a new one.

Help me find my API key in Google AI Studio.

Set the API key and verify your connection

The google-genai SDK automatically reads your API key from an environment variable called GEMINI_API_KEY. Setting this variable lets the SDK authenticate without you hardcoding the key in your script.

  • In your VS Code terminal (PowerShell), set your API key as an environment variable by running this command:
$env:GEMINI_API_KEY = "your-api-key-here"
  • Replace your-api-key-here with the actual API key you copied from Google AI Studio.

Why an environment variable?

Environment variables keep secrets out of your code. If you hardcode the key in a file, you risk accidentally sharing it when pushing to GitHub. The SDK knows to look for GEMINI_API_KEY automatically, so you never need to write the key in your Python files.

Now create a small test script to confirm everything is connected.

  • In VS Code, click File in the top menu bar.
  • Click New File.
  • Save the file immediately with Ctrl+S (Windows) or Cmd+S (macOS) and name it test_connection.py.
  • Copy the following code into test_connection.py:
from google import genai

# Create a client (uses GEMINI_API_KEY automatically)
client = genai.Client()

# Make a test call to verify the connection
interaction = client.interactions.create(
    model="gemini-2.5-flash",
    input="Why is the sky blue?"
)

# Print the response
print(interaction.output_text)

What does this code do?

  • genai.Client() creates a connection to Google's API using your GEMINI_API_KEY environment variable.
  • client.interactions.create() sends a prompt to the gemini-2.5-flash model.
  • interaction.output_text contains the text the model generated in response.
  • Save test_connection.py and run it in your terminal:
python test_connection.py
  • You should see a paragraph or two from Gemini explaining why the sky is blue.

✔️ Awesome, I've got everything!

Great. Your connection to Gemini is working and you are ready to build your quiz generator.

ⓧ I'd like to double check the full code

Here is the complete test_connection.py file for comparison:

from google import genai

# Create a client (uses GEMINI_API_KEY automatically)
client = genai.Client()

# Make a test call to verify the connection
interaction = client.interactions.create(
    model="gemini-2.5-flash",
    input="Why is the sky blue?"
)

# Print the response
print(interaction.output_text)

Seeing an error when you run the script?

If you see an authentication or API key error, make sure you set the environment variable in the same terminal session where you run the script. PowerShell environment variables reset when you close the terminal window.

If you see ModuleNotFoundError: No module named 'google.genai', run pip install google-genai==2.9.0 again in the same terminal and retry.

My test script is failing with an error. How do I fix it?

Your environment is ready and your connection to Gemini is confirmed. Next up, you will write your first real AI call and explore how different prompts produce different outputs.

Make Your First AI Call

Your connection to Gemini is verified. Now it's time to build the actual script that will power your quiz generator.

In this step, you'll create the main Python file and write your first real API call. You'll also discover an important limitation of plain text AI responses that shapes how we build the rest of the tool.

In this step, get ready to:
  • Create quiz_generator.py with a working Gemini API call.
  • Explore why unstructured AI responses need a better solution.
Create quiz_generator.py and call the Gemini API

The Interactions API is Google's recommended way to call Gemini from Python. It handles sending your prompt to the model and returning the response in a single method call.

  • In VS Code, press Cmd+N (macOS) or Ctrl+N (Windows) to create a new file.
  • Save it immediately with Cmd+S (macOS) or Ctrl+S (Windows) and name it quiz_generator.py.
  • Add the following code to make your first quiz-related API call:
from google import genai

# Create a client that uses your GEMINI_API_KEY automatically
client = genai.Client()

# Send a prompt to Gemini and get a response
interaction = client.interactions.create(
    model="gemini-2.5-flash",
    input="Generate a short quiz about the solar system.",
)
print(interaction.output_text)

What does this code do?

  • from google import genai imports the Google GenAI SDK you installed in the previous step.
  • genai.Client() creates a client that automatically reads your GEMINI_API_KEY environment variable to authenticate.
  • client.interactions.create() sends your prompt to the gemini-2.5-flash model and returns the AI's response.
  • interaction.output_text contains the plain text response from the model.
  • Save quiz_generator.py.
  • Run the script in your terminal by running:
python quiz_generator.py
  • You should see a quiz about the solar system printed in your terminal, with questions and answers in plain text.

Not seeing any output?

  • Make sure you saved quiz_generator.py before running it.
  • Check that your GEMINI_API_KEY environment variable is still set in the same terminal session. If you opened a new terminal, you need to set it again.
  • Confirm you typed gemini-2.5-flash exactly as shown. A typo in the model name causes an error.

Why isn't my quiz_generator.py script producing output?

Experiment with prompt engineering

Your script works. But take a close look at the output format. Each time you run the script, the AI might format the quiz differently.

  • Run the script a second time:
python quiz_generator.py
  • Compare the output to your first run. Notice how the number of questions, the formatting style, or even the structure might be completely different.

Sometimes the AI uses numbered lists. Other times it uses bullet points, bold text, or paragraph form. The content changes too.

  • Try changing the input string to something more specific, like "Generate exactly 3 quiz questions about the solar system. Number each question and put the answer on the next line." and run the script again.
  • Observe that even with detailed instructions, the AI still returns unpredictable plain text. It might follow your format, or it might not.
  • Change your input back to "Generate a short quiz about the solar system." and save the file.

Why is unstructured output a problem?

If you wanted to build a real quiz app, you'd need to extract each question, its answer, and maybe a hint from this text. With plain text output, you'd have to write fragile string-parsing code that breaks every time the AI decides to format things differently.

This is the core problem structured output solves. Instead of hoping the AI responds in a usable format, you can force it to return valid JSON matching an exact schema you define.

✔️ Awesome, I've got everything!

Great. Double check you've saved your file with the original prompt before moving on.

ⓧ I'd like to double check the full code

Here's the complete quiz_generator.py file at this point:

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-2.5-flash",
    input="Generate a short quiz about the solar system.",
)
print(interaction.output_text)

Your script generates quizzes, but the AI returns whatever format it wants. In the next step, you'll use Pydantic and structured output to force the AI to respond in a specific JSON format your code can reliably parse.

Generate Structured Quiz Questions

In the previous step, you called the Gemini API and got back a plain text response. You saw firsthand that unstructured text is difficult to parse into something your program can use reliably.

Now you'll solve this by telling Gemini exactly what shape of data you want back. Using Pydantic data models and Gemini's structured output feature, you'll get the AI to return valid JSON that matches a schema you define.

In this step, get ready to:
  • Define Pydantic data models that describe the shape of a quiz.
  • Use structured output to get valid JSON from Gemini.
  • Test the quiz generator by printing a validated Quiz object.
Define your Pydantic data models

Pydantic lets you define Python classes that describe the exact shape of your data. When you give this schema to Gemini, it constrains the AI to return JSON matching your structure perfectly.

  • In VS Code, open quiz_generator.py.
  • Select all the existing code and replace it with the following:
import json
from google import genai
from pydantic import BaseModel, Field
from typing import List


# Define the shape of a single quiz question
class QuizQuestion(BaseModel):
    question: str = Field(description="The quiz question")
    correct_answer: str = Field(description="The correct answer to the question")
    hint: str = Field(description="A helpful hint for the question")


# Define the overall quiz structure containing multiple questions
class Quiz(BaseModel):
    topic: str = Field(description="The topic of the quiz")
    questions: List[QuizQuestion] = Field(description="List of quiz questions")

What does this code do?

You're importing BaseModel and Field from Pydantic, which is already installed as a dependency of google-genai.

QuizQuestion defines the shape of one question with three fields: the question text, the correct answer, and a hint. Quiz groups a topic and a list of QuizQuestion objects together.

The description parameter in each Field tells Gemini what kind of content to put in that field. These descriptions become part of the JSON schema that guides the AI.

  • Save quiz_generator.py.
  • You won't see any output yet. The next chunk adds the function that uses these models.
Create the generate_quiz() function

Gemini's structured output feature lets you pass a JSON schema alongside your prompt. The API then returns data that matches your schema exactly, so you can parse it directly into a Pydantic object.

  • Add the following function below your Quiz class:
def generate_quiz(client, topic, num_questions=3):
    # Call Gemini with structured output format
    interaction = client.interactions.create(
        model="gemini-2.5-flash",
        input=(
            f"Generate a quiz with {num_questions} questions about: {topic}. "
            f"Make the questions interesting and educational. "
            f"Each question should have a clear, concise correct answer."
        ),
        # Tell Gemini to return JSON matching our Quiz schema
        response_format={
            "type": "text",
            "mime_type": "application/json",
            "schema": Quiz.model_json_schema(),
        },
    )
    # Parse the JSON response into a validated Quiz object
    quiz = Quiz.model_validate_json(interaction.output_text)
    return quiz

What does this code do?

The response_format parameter is where the magic happens. You pass Quiz.model_json_schema() which converts your Pydantic model into a JSON schema that Gemini follows.

Setting mime_type to application/json tells Gemini to respond with pure JSON instead of free-form text. Then Quiz.model_validate_json() parses that JSON string directly into a validated Python object in one step.

  • Save quiz_generator.py.
  • You won't see output yet. The next chunk adds test code to run the function.
Test the quiz generator

With the function defined, you need a few lines of test code to actually call it and see the structured output in action.

  • Add the following at the very bottom of quiz_generator.py, below the generate_quiz function:
# Test the quiz generation
client = genai.Client()
quiz = generate_quiz(client, "solar system")
print(quiz)

What does this code do?

This creates a Gemini client (which reads your GEMINI_API_KEY environment variable automatically), calls generate_quiz with the topic "solar system", and prints the resulting Quiz object.

If structured output is working correctly, you'll see a Quiz object with a topic and three QuizQuestion entries, each containing a question, correct answer, and hint.

  • Save quiz_generator.py.
  • Run the script in your terminal:
python quiz_generator.py
  • You should see a Quiz object printed with a topic of "solar system" and 3 questions, each with question, correct_answer, and hint fields filled in.

Not seeing a Quiz object?

  • If you see a "ValidationError", check that your response_format dictionary matches the code above exactly. A typo in mime_type or schema will cause parsing to fail.
  • If you see a permissions or API key error, make sure your GEMINI_API_KEY environment variable is still set in this terminal session.
  • If you see a rate limit error, wait a minute and try again.

Help me debug my structured output quiz generator

✔️ Awesome, I've got everything!

Great. Double check you've saved your file.

ⓧ I'd like to double check the full code

import json
from google import genai
from pydantic import BaseModel, Field
from typing import List


class QuizQuestion(BaseModel):
    question: str = Field(description="The quiz question")
    correct_answer: str = Field(description="The correct answer to the question")
    hint: str = Field(description="A helpful hint for the question")


class Quiz(BaseModel):
    topic: str = Field(description="The topic of the quiz")
    questions: List[QuizQuestion] = Field(description="List of quiz questions")


def generate_quiz(client, topic, num_questions=3):
    interaction = client.interactions.create(
        model="gemini-2.5-flash",
        input=(
            f"Generate a quiz with {num_questions} questions about: {topic}. "
            f"Make the questions interesting and educational. "
            f"Each question should have a clear, concise correct answer."
        ),
        response_format={
            "type": "text",
            "mime_type": "application/json",
            "schema": Quiz.model_json_schema(),
        },
    )
    quiz = Quiz.model_validate_json(interaction.output_text)
    return quiz


client = genai.Client()
quiz = generate_quiz(client, "solar system")
print(quiz)

Why structured output instead of parsing text?

Without structured output, you'd need to write fragile string-parsing logic to extract questions from free-form text. Every time Gemini changed its phrasing slightly, your parser could break.

With structured output, Gemini guarantees its response matches your schema. Your code goes from "hope the AI formatted it right" to "the data is validated before I use it."

Your quiz generator now returns structured, validated data instead of unpredictable text. Next up, you'll build an interactive quiz experience that lets users answer questions and get AI-powered feedback on their responses.

Build the Interactive Quiz and Evaluator

Your quiz generator can now produce structured, validated questions from any topic you throw at it.

In this step, you'll turn those questions into a full interactive experience. You'll build a function to present questions and collect answers, then use Gemini again to evaluate free-text responses and provide a score with feedback.

In this step, get ready to:
  • Build a function that presents quiz questions and collects user answers.
  • Build an evaluation function that uses Gemini to grade responses.
  • Wire everything into a main function for an end-to-end quiz experience.
Create a run_quiz() function that displays questions and collects answers

Right now your script generates questions and prints the raw Quiz object. You need a function that loops through each question, shows it to the user with its hint, and stores their typed answer.

  • In quiz_generator.py, scroll to the bottom and find these three lines:
client = genai.Client()
quiz = generate_quiz(client, "solar system")
print(quiz)
  • Delete all three lines. You'll replace them with proper functions shortly.
  • Below the generate_quiz() function, add the run_quiz() function by copying this code:
def run_quiz(quiz):
    # Display a formatted quiz header
    print(f"\n{'=' * 50}")
    print(f"  QUIZ: {quiz.topic}")
    print(f"{'=' * 50}\n")

    # Loop through each question and collect answers
    user_answers = []
    for i, q in enumerate(quiz.questions, 1):
        print(f"Question {i}: {q.question}")
        print(f"  (Hint: {q.hint})")
        answer = input("\nYour answer: ")
        user_answers.append(answer)
        print()

    return user_answers

What does this code do?

  • The function prints a formatted header showing the quiz topic between lines of = characters.
  • enumerate(quiz.questions, 1) loops through questions starting the count at 1 instead of 0, so the display says "Question 1", "Question 2", etc.
  • Each question is displayed with its hint, then input() pauses the program and waits for the user to type an answer.
  • user_answers collects all responses into a list that gets returned for evaluation later.
  • Save quiz_generator.py.

Seeing a syntax error?

Make sure the f-strings use curly braces correctly. The {'=' * 50} part is a Python expression inside an f-string that repeats the = character 50 times.

Also confirm you deleted all three lines of the old test code. Leftover lines will cause conflicts.

Help me fix a syntax error in my run_quiz function

Create an evaluate_answers() function that uses Gemini to grade responses

The quiz collects free-text answers, not multiple choice. This means you can't just compare strings to check correctness. Instead, you'll send the questions, correct answers, and user answers to Gemini and let the AI evaluate them.

  • Below the run_quiz() function, add the evaluate_answers() function by copying this code:
def evaluate_answers(client, quiz, user_answers):
    # Build the evaluation prompt with all questions and answers
    evaluation_input = (
        "Evaluate these quiz answers. For each answer, determine if it is "
        "correct, partially correct, or incorrect. Give a score out of the "
        "total number of questions and brief feedback for each.\n\n"
    )

    # Append each question with the correct answer and user's answer
    for i, (q, user_ans) in enumerate(zip(quiz.questions, user_answers), 1):
        evaluation_input += f"Question {i}: {q.question}\n"
        evaluation_input += f"Correct answer: {q.correct_answer}\n"
        evaluation_input += f"User's answer: {user_ans}\n\n"

    # Send the evaluation prompt to Gemini
    interaction = client.interactions.create(
        model="gemini-2.5-flash",
        input=evaluation_input,
    )
    return interaction.output_text

What does this code do?

  • The function builds a prompt string that contains all the context Gemini needs to judge each answer.
  • zip(quiz.questions, user_answers) pairs each question with the corresponding user answer so they stay aligned.
  • This call does NOT use structured output. The evaluation comes back as plain text with a score and feedback, which is easier to display directly.

Why use AI for evaluation instead of string matching?

A user might answer "Mars" while the correct answer is "The planet Mars". Simple string comparison would mark that wrong. Gemini can understand that both answers mean the same thing, and even give partial credit for incomplete answers.

  • Save quiz_generator.py.

Seeing an indentation error?

Check that the for loop and the interaction = client.interactions.create(...) call are both indented one level inside the function. Python is strict about consistent indentation.

Help me fix an indentation error in evaluate_answers

Wire everything together in a main() function

You have all the pieces now. The main() function ties them together into a single flow: ask for a topic, generate questions, run the quiz, evaluate answers, and display results.

  • Below the evaluate_answers() function, add the main() function and the entry point guard by copying this code:
def main():
    # Create the Gemini client
    client = genai.Client()

    print("Welcome to the AI Quiz Generator!")
    print("-" * 35)
    topic = input("What topic would you like to be quizzed on? ")

    # Generate the quiz using structured output
    print(f"\nGenerating quiz about '{topic}'...")
    quiz = generate_quiz(client, topic)

    # Run the interactive quiz and collect answers
    user_answers = run_quiz(quiz)

    # Evaluate answers using Gemini
    print("Evaluating your answers...\n")
    feedback = evaluate_answers(client, quiz, user_answers)

    # Display the final results
    print(f"{'=' * 50}")
    print("  RESULTS")
    print(f"{'=' * 50}")
    print(feedback)


if __name__ == "__main__":
    main()

What does this code do?

  • main() orchestrates the full quiz flow in sequence: prompt for a topic, generate questions, present them, evaluate answers, and print results.
  • The client = genai.Client() call is now inside main() instead of floating at the top level. This keeps your code organized.
  • if __name__ == "__main__" is a Python pattern that runs main() only when the script is executed directly, not when imported as a module.
  • Save quiz_generator.py.
  • Run the complete script by entering this command in your terminal:
python quiz_generator.py
  • When prompted, type a topic (for example, solar system) and press Enter.
  • Answer each question as it appears, pressing Enter after each answer.
  • After you submit your final answer, you should see an "Evaluating your answers..." message followed by a RESULTS section with a score and feedback for each question.

Script crashes or no output?

If you see a NameError, make sure your functions are defined in order: generate_quiz, then run_quiz, then evaluate_answers, then main.

If the script hangs after "Generating quiz...", the API call is running. Give it a few seconds to respond.

If you see an API error, confirm your GEMINI_API_KEY environment variable is still set in this terminal session.

Help me debug my quiz generator script

✔️ Awesome, I've got everything!

Great. Double check you've saved your file.

ⓧ I'd like to double check the full code

Here's the complete quiz_generator.py file. Compare your code against this:

import json
from google import genai
from pydantic import BaseModel, Field
from typing import List


class QuizQuestion(BaseModel):
    question: str = Field(description="The quiz question")
    correct_answer: str = Field(description="The correct answer to the question")
    hint: str = Field(description="A helpful hint for the question")


class Quiz(BaseModel):
    topic: str = Field(description="The topic of the quiz")
    questions: List[QuizQuestion] = Field(description="List of quiz questions")


def generate_quiz(client, topic, num_questions=3):
    interaction = client.interactions.create(
        model="gemini-2.5-flash",
        input=(
            f"Generate a quiz with {num_questions} questions about: {topic}. "
            f"Make the questions interesting and educational. "
            f"Each question should have a clear, concise correct answer."
        ),
        response_format={
            "type": "text",
            "mime_type": "application/json",
            "schema": Quiz.model_json_schema(),
        },
    )
    quiz = Quiz.model_validate_json(interaction.output_text)
    return quiz


def run_quiz(quiz):
    print(f"\n{'=' * 50}")
    print(f"  QUIZ: {quiz.topic}")
    print(f"{'=' * 50}\n")

    user_answers = []
    for i, q in enumerate(quiz.questions, 1):
        print(f"Question {i}: {q.question}")
        print(f"  (Hint: {q.hint})")
        answer = input("\nYour answer: ")
        user_answers.append(answer)
        print()

    return user_answers


def evaluate_answers(client, quiz, user_answers):
    evaluation_input = (
        "Evaluate these quiz answers. For each answer, determine if it is "
        "correct, partially correct, or incorrect. Give a score out of the "
        "total number of questions and brief feedback for each.\n\n"
    )

    for i, (q, user_ans) in enumerate(zip(quiz.questions, user_answers), 1):
        evaluation_input += f"Question {i}: {q.question}\n"
        evaluation_input += f"Correct answer: {q.correct_answer}\n"
        evaluation_input += f"User's answer: {user_ans}\n\n"

    interaction = client.interactions.create(
        model="gemini-2.5-flash",
        input=evaluation_input,
    )
    return interaction.output_text


def main():
    client = genai.Client()

    print("Welcome to the AI Quiz Generator!")
    print("-" * 35)
    topic = input("What topic would you like to be quizzed on? ")

    print(f"\nGenerating quiz about '{topic}'...")
    quiz = generate_quiz(client, topic)

    user_answers = run_quiz(quiz)

    print("Evaluating your answers...\n")
    feedback = evaluate_answers(client, quiz, user_answers)

    print(f"{'=' * 50}")
    print("  RESULTS")
    print(f"{'=' * 50}")
    print(feedback)


if __name__ == "__main__":
    main()

Secret mission

Add Difficulty Levels and Score Tracking

Your quiz generator works, but every quiz feels the same. What if the learner could choose how hard the questions are? And what if you could track your progress over time? In this mission, you'll add difficulty levels that change the AI's prompting strategy and a persistent score tracker that saves results to a JSON file.

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely locally and uses the Gemini API free tier, so there are no ongoing costs. Decide whether to keep your resources for future projects or delete them entirely.

Resources you used:

  • Project files (quiz_generator.py and quiz_history.json).
  • The google-genai Python package.
  • Your Gemini API key in Google AI Studio.

Keep everything running

No action needed. Choose this if you plan to keep building on this project or want to use the Gemini API for other experiments.

  • Your Gemini API key stays active on the free tier at no cost.
  • Your project files remain on your machine ready to run again.
  • The GEMINI_API_KEY environment variable only lasts for your current PowerShell session. You will need to set it again next time you open a new terminal.

Pause - I'll come back to this later

Shut down any running processes to free up memory. Your files and API key stay intact for when you return.

  • Close the terminal session you used to run the quiz generator.
  • Your API key remains active on the free tier. No charges accrue while it is idle.
  • Your project files stay on disk. Re-set GEMINI_API_KEY in a new terminal session when you return.

Delete - I don't want to use this again

Remove all project resources and revoke your API key so nothing remains active.

  • Delete your project files by running this command in PowerShell from the folder containing them:
Remove-Item quiz_generator.py, quiz_history.json
  • Uninstall the google-genai package by running:
pip uninstall google-genai
  • Type y and press Enter when prompted to confirm the uninstall.
  • Delete your Gemini API key from Google Cloud:
  • Open the Google Cloud API Credentials page at https://console.cloud.google.com/apis/credentials.
  • Find the API key you created for this project and click the Actions icon (three dots).
  • Select Delete API key.
  • In the confirmation modal, click Delete. Deletion takes a few minutes to propagate.

Nice Work!

Nice Work!

You just built a fully functional AI-powered quiz generator from scratch. It takes any topic, generates structured quiz questions using Gemini, and evaluates free-text answers with AI feedback.

You've learned how to:

  • Called the Gemini API from Python using the google-genai SDK to generate and evaluate quiz content.
  • Used structured output with Pydantic data models to get reliable, parseable JSON from an LLM.
  • Built an interactive CLI application that collects user input, generates AI content, and displays AI-powered evaluation results.
  • Secret Mission: Added difficulty levels that demonstrate advanced prompt engineering, and built persistent score tracking with file I/O.

Ready to quiz yourself?