How to build AI quiz generator
Quick answer
Build an AI quiz generator by using a large language model like
gpt-4o to generate questions and answers from a given topic prompt. Use the OpenAI Python SDK to send prompts and parse the model's output into quiz format.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the openai Python package and set your API key as an environment variable for secure access.
pip install openai output
Collecting openai Downloading openai-1.x.x-py3-none-any.whl (xx kB) Installing collected packages: openai Successfully installed openai-1.x.x
Step by step
This example shows how to generate a 5-question multiple-choice quiz on a topic using gpt-4o. The prompt instructs the model to output questions with options and answers in JSON format for easy parsing.
import os
from openai import OpenAI
import json
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
def generate_quiz(topic: str, num_questions: int = 5):
prompt = f"""
Create a {num_questions}-question multiple-choice quiz on the topic: {topic}.
Format the output as a JSON array of objects with 'question', 'options' (list), and 'answer' (correct option).
"""
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
content = response.choices[0].message.content
try:
quiz = json.loads(content)
except json.JSONDecodeError:
raise ValueError("Failed to parse quiz JSON from model output")
return quiz
if __name__ == "__main__":
topic = "Python programming basics"
quiz = generate_quiz(topic)
for i, q in enumerate(quiz, 1):
print(f"Q{i}: {q['question']}")
for idx, option in enumerate(q['options'], 1):
print(f" {idx}. {option}")
print(f"Answer: {q['answer']}\n") output
Q1: What is the keyword to define a function in Python? 1. func 2. def 3. function 4. define Answer: def Q2: Which data type is used to store text in Python? 1. int 2. str 3. bool 4. list Answer: str Q3: How do you start a comment in Python? 1. // 2. <!-- 3. # 4. /* Answer: # Q4: What symbol is used for string concatenation? 1. + 2. & 3. * 4. % Answer: + Q5: Which keyword is used to create a loop that iterates over a sequence? 1. for 2. while 3. loop 4. iterate Answer: for
Common variations
You can customize the quiz generator by using different models like gpt-4o-mini for faster responses or claude-3-5-sonnet-20241022 for alternative style. Async calls and streaming responses are also possible for interactive apps.
import os
import asyncio
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
async def generate_quiz_async(topic: str, num_questions: int = 5):
prompt = f"Create a {num_questions}-question multiple-choice quiz on the topic: {topic}. Format as JSON."
response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
if __name__ == "__main__":
quiz_json = asyncio.run(generate_quiz_async("Machine learning basics"))
print(quiz_json) output
[{"question": "What is supervised learning?", "options": ["A", "B", "C", "D"], "answer": "A"}, ...] Troubleshooting
- If the model output is not valid JSON, try adding explicit instructions to the prompt to format strictly as JSON.
- Check your API key environment variable
OPENAI_API_KEYis set correctly. - If you get rate limit errors, reduce
max_tokensor switch to a smaller model.
Key Takeaways
- Use
gpt-4owith clear JSON formatting prompts to generate structured quiz data. - Parse the model's JSON output to build interactive quizzes programmatically.
- Customize quiz length, topic, and model choice for different use cases.
- Async and streaming APIs enable responsive quiz generation in web apps.
- Validate and sanitize model output to handle parsing errors gracefully.