3.3 A Practical Example: Quiz Generation
Why Quizzes
Quiz generation is a good example for studying how to build product mechanics on top of an LLM. The task looks simple at first glance: the input is a topic or a text, and the output is a set of questions with answer options. But when you start turning this idea into a stable, reproducible pipeline, real engineering challenges appear: structuring the input data, designing a prompt for a fixed output format, validating results, and testing quality.
Organizing the Source Data
Figure 32. Hierarchical structure of the topic bank.
Before generating quizzes, you need to define what they are based on. In practice, different sources are used: a topic bank with categories, a corpus of texts, and fact bases. The choice of data structure affects the quality and controllability of the generation.
As shown in Fig. 32, the topic bank is a hierarchical structure: categories contain subtopics, and subtopics contain specific facts. Each fact is labeled with a difficulty level. Each topic has a list of keywords for validation.
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Fact:
statement: str
source: Optional[str] = None
difficulty: str = "medium"
@dataclass
class Topic:
name: str
description: str
facts: list[Fact] = field(default_factory=list)
keywords: list[str] = field(default_factory=list)
@dataclass
class Category:
name: str
topics: list[Topic] = field(default_factory=list)
quiz_bank = [
Category(
name="History of Science",
topics=[
Topic(
name="Discovery of penicillin",
description="The history of Alexander Fleming's discovery of the first antibiotic",
facts=[
Fact("Penicillin was discovered in 1928", difficulty="easy"),
Fact("Alexander Fleming discovered penicillin by accident", difficulty="medium"),
Fact("Mass production of penicillin began in the 1940s", difficulty="hard")
],
keywords=["penicillin", "Fleming", "antibiotic", "1928"]
)
]
)
]
Such a structure allows several things at once: it controls the difficulty of the generated questions (by selecting facts of the required level), ties the questions to verified facts instead of hallucinations, and provides keywords for validating the generated questions.
Designing a Prompt for Structured Output
Figure 33. Structure of the prompt for quiz generation.
Quiz generation requires strictly structured output. The model must return not just text, but a set of fields: the question, the answer options, the correct answer, and an explanation. An unstructured format complicates parsing and further processing.
As shown in Fig. 33, the best solution is to use JSON. This format is easy to parse programmatically, validate, and integrate into a pipeline.
QUIZ_GENERATION_PROMPT = """You are a generator of educational quizzes. Create a question based on the provided topic.
Topic: {topic_name}
Description: {topic_description}
Key facts:
{facts}
Requirements:
1. The question must be based on one of the key facts
2. There must be exactly 4 answer options
3. Only one option must be correct
4. Incorrect options must be plausible, but clearly wrong
5. Question difficulty: {difficulty}
Return the answer ONLY in JSON format, without any additional text:
{{
"question": "question text",
"options": ["option A", "option B", "option C", "option D"],
"correct_answer": "the option that is correct",
"explanation": "a brief explanation of why this answer is correct",
"based_on_fact": "the fact on which the question is based"
}}"""
def format_facts(facts: list[Fact]) -> str:
return "\n".join([f"- {fact.statement} (difficulty: {fact.difficulty})" for fact in facts])
def build_quiz_prompt(topic: Topic, difficulty: str = "medium") -> str:
relevant_facts = [f for f in topic.facts if f.difficulty == difficulty]
if not relevant_facts:
relevant_facts = topic.facts
return QUIZ_GENERATION_PROMPT.format(
topic_name=topic.name,
topic_description=topic.description,
facts=format_facts(relevant_facts),
difficulty=difficulty
)
The key points of the prompt are: an explicit statement of the required JSON format, an example of the structure, and the instruction "ONLY in JSON format, without any additional text" (this helps avoid preambles such as "Here is the JSON..."). These details significantly increase the probability of getting a correct output.
Example: An Educational Platform
Imagine a system in which teachers upload lecture texts, and the platform automatically generates tests to check knowledge. The key requirements here are control of difficulty, binding to specific parts of the material, and minimizing incorrect questions.
A simple task statement ("create 5 questions based on the text") gives unstable results: some questions turn out too easy or, on the contrary, too hard, some have no unambiguous answer, and the output format changes from run to run.
The solution requires an iterative approach. First, a strict format is introduced through JSON, which stabilizes the structure of the response. Then a separate fact-extraction stage is added: the model first highlights the key statements from the text and only then generates questions based on them. This ensures a link to the specific content.
In the final version, the pipeline consists of three steps: extracting facts with their difficulty levels, generating questions based on the selected facts, and validating the results.
@dataclass
class GeneratedQuiz:
question: str
options: list[str]
correct_answer: str
explanation: str
based_on_fact: str
topic: str
difficulty: str
validation_passed: bool = False
validation_errors: list[str] = field(default_factory=list)
class QuizGenerator:
def __init__(self, llm_client):
self.llm = llm_client
def extract_facts(self, text: str, num_facts: int = 5) -> list[Fact]:
prompt = f"""Extract {num_facts} key facts from the text.
For each fact, specify its difficulty: easy, medium, or hard.
Text:
{text}
Return a JSON array:
[{{"statement": "fact", "difficulty": "medium"}}]"""
response = self.llm.generate(prompt)
facts_data = json.loads(response)
return [Fact(**f) for f in facts_data]
def generate_quiz(self, topic: Topic, difficulty: str = "medium") -> GeneratedQuiz:
prompt = build_quiz_prompt(topic, difficulty)
for attempt in range(3):
try:
response = self.llm.generate(prompt, temperature=0.7)
quiz_data = self.parse_response(response)
quiz = GeneratedQuiz(
question=quiz_data["question"],
options=quiz_data["options"],
correct_answer=quiz_data["correct_answer"],
explanation=quiz_data["explanation"],
based_on_fact=quiz_data["based_on_fact"],
topic=topic.name,
difficulty=difficulty
)
return quiz
except (json.JSONDecodeError, KeyError) as e:
if attempt == 2:
raise ValueError(f"Failed to generate valid quiz after 3 attempts: {e}")
raise ValueError("Quiz generation failed")
def parse_response(self, response: str) -> dict:
json_match = re.search(r'\{.*\}', response, re.DOTALL)
if not json_match:
raise ValueError("No JSON found in response")
return json.loads(json_match.group())
The retry logic matters here: if JSON parsing fails, the model is asked again. Often a second attempt is enough to fix the error.
Validation: Several Levels
Figure 34. Multi-level validation of generated quizzes.
Generative models can produce incorrect or low-quality results, so validation is a mandatory stage.
As shown in Fig. 34, several levels of checking are used. Structural validation is responsible for the format: correct JSON, presence of the required fields, and conformity of types. Semantic validation analyzes the content: it checks that the correct answer is among the options, that the question relates to the topic (for example, contains the keywords), and that the answer options do not repeat.
class QuizValidator:
def __init__(self):
self.errors = []
def validate(self, quiz: GeneratedQuiz, topic: Topic) -> bool:
self.errors = []
self.validate_structure(quiz)
self.validate_answer_in_options(quiz)
self.validate_keywords(quiz, topic)
self.validate_options_uniqueness(quiz)
self.validate_question_length(quiz)
quiz.validation_passed = len(self.errors) == 0
quiz.validation_errors = self.errors.copy()
return quiz.validation_passed
def validate_structure(self, quiz: GeneratedQuiz):
if not quiz.question or len(quiz.question) < 10:
self.errors.append("Question too short or empty")
if len(quiz.options) != 4:
self.errors.append(f"Expected 4 options, got {len(quiz.options)}")
if not quiz.correct_answer:
self.errors.append("Correct answer is empty")
def validate_answer_in_options(self, quiz: GeneratedQuiz):
if quiz.correct_answer not in quiz.options:
close_matches = [
opt for opt in quiz.options
if quiz.correct_answer.lower() in opt.lower()
or opt.lower() in quiz.correct_answer.lower()
]
if not close_matches:
self.errors.append("Correct answer not found in options")
def validate_keywords(self, quiz: GeneratedQuiz, topic: Topic):
question_lower = quiz.question.lower()
options_text = " ".join(quiz.options).lower()
full_text = question_lower + " " + options_text
keyword_matches = sum(
1 for kw in topic.keywords
if kw.lower() in full_text
)
if keyword_matches == 0:
self.errors.append("No topic keywords found in question or options")
def validate_options_uniqueness(self, quiz: GeneratedQuiz):
options_lower = [opt.lower().strip() for opt in quiz.options]
if len(options_lower) != len(set(options_lower)):
self.errors.append("Duplicate options detected")
def validate_question_length(self, quiz: GeneratedQuiz):
if len(quiz.question) > 500:
self.errors.append("Question too long (>500 chars)")
Testing Generative Systems
Figure 35. Three levels of testing generative systems.
Testing generative systems differs fundamentally from testing deterministic code. The same input can lead to different but correct results, so a combination of methods is required.
As shown in Fig. 35, three levels of testing are usually used. Structural tests check the format and basic properties of the output and must always pass. Statistical tests evaluate quality on a sample (for example, through the share of valid results). Golden set tests use prepared reference examples and help detect quality regressions when the system changes.
import pytest
class TestQuizGeneration:
def setup_method(self):
self.generator = QuizGenerator(mock_llm_client)
self.validator = QuizValidator()
self.sample_topic = Topic(
name="Test Topic",
description="Test description",
facts=[Fact("Test fact", difficulty="medium")],
keywords=["test", "keyword"]
)
def test_quiz_has_required_fields(self):
quiz = self.generator.generate_quiz(self.sample_topic)
assert quiz.question is not None
assert len(quiz.options) == 4
assert quiz.correct_answer is not None
assert quiz.explanation is not None
def test_correct_answer_in_options(self):
quiz = self.generator.generate_quiz(self.sample_topic)
assert quiz.correct_answer in quiz.options
def test_options_are_unique(self):
quiz = self.generator.generate_quiz(self.sample_topic)
assert len(quiz.options) == len(set(quiz.options))
Statistical tests run generation many times and check the distribution of results:
def test_generation_quality_over_samples():
generator = QuizGenerator(real_llm_client)
validator = QuizValidator()
topics = load_test_topics()
results = []
for topic in topics[:20]:
quiz = generator.generate_quiz(topic)
is_valid = validator.validate(quiz, topic)
results.append(is_valid)
pass_rate = sum(results) / len(results)
assert pass_rate >= 0.9, f"Pass rate {pass_rate:.2%} below threshold 90%"
Golden set tests use a set of reference examples for which the characteristics of a good answer are known. This helps catch regressions:
GOLDEN_TESTS = [
{
"topic": "Discovery of penicillin",
"expected_keywords_in_question": ["penicillin", "discovered"],
"expected_answer_pattern": r"192[0-9]|Fleming"
}
]
def test_golden_set():
generator = QuizGenerator(real_llm_client)
for golden in GOLDEN_TESTS:
topic = get_topic_by_name(golden["topic"])
quiz = generator.generate_quiz(topic)
question_lower = quiz.question.lower()
for keyword in golden["expected_keywords_in_question"]:
assert keyword.lower() in question_lower
if golden.get("expected_answer_pattern"):
assert re.search(
golden["expected_answer_pattern"],
quiz.correct_answer
)
Packaging in a Kubeflow Pipeline
Figure 36. Quiz generation pipeline in Kubeflow.
Once the solution works stably locally, the next step is packaging it into a full-fledged pipeline for scaling and automation.
As shown in Fig. 36, the process can be broken down into several stages: generating quizzes for each topic, validating the results, filtering, and removing duplicates. Such a pipeline scales easily on a cluster, can run on a schedule or trigger, and ensures reproducibility thanks to fixed parameters.
from kfp import dsl
from kfp import compiler
@dsl.component(
base_image="python:3.10",
packages_to_install=["openai==1.0.0"]
)
def generate_quizzes_batch(
topics_json: str,
difficulty: str,
num_per_topic: int
) -> str:
import json
from quiz_generator import QuizGenerator, QuizValidator
topics = json.loads(topics_json)
generator = QuizGenerator()
validator = QuizValidator()
results = []
for topic_data in topics:
topic = Topic(**topic_data)
for _ in range(num_per_topic):
quiz = generator.generate_quiz(topic, difficulty)
validator.validate(quiz, topic)
if quiz.validation_passed:
results.append({
"question": quiz.question,
"options": quiz.options,
"correct_answer": quiz.correct_answer,
"explanation": quiz.explanation,
"topic": quiz.topic,
"difficulty": quiz.difficulty
})
return json.dumps(results)
@dsl.component
def filter_and_deduplicate(
quizzes_json: str,
similarity_threshold: float = 0.8
) -> str:
import json
quizzes = json.loads(quizzes_json)
unique_quizzes = []
seen_questions = []
for quiz in quizzes:
is_duplicate = any(
similar(quiz["question"], seen) > similarity_threshold
for seen in seen_questions
)
if not is_duplicate:
unique_quizzes.append(quiz)
seen_questions.append(quiz["question"])
return json.dumps(unique_quizzes)
@dsl.pipeline(name="quiz-generation-pipeline")
def quiz_pipeline(
topics_json: str,
difficulty: str = "medium",
num_per_topic: int = 3
):
generate_task = generate_quizzes_batch(
topics_json=topics_json,
difficulty=difficulty,
num_per_topic=num_per_topic
)
filter_task = filter_and_deduplicate(
quizzes_json=generate_task.output
)
Questions for Reflection and Practice
Theoretical questions
-
Which data structures are suitable for organizing a bank of topics and facts?
-
How do you design a prompt for obtaining structured output in a fixed format?
-
Which levels of validation are necessary for generative mechanics, and what does each one check?
-
How do you organize the testing of generative functions, given their non-determinism?
-
What role do keywords play in validating the relevance of generated questions?
-
How do statistical tests help evaluate the quality of generation on a sample?
-
What are golden set tests, and how do they help catch regressions?
-
How do you package a generative mechanic into a reproducible pipeline?
Practical exercises
-
Create a data structure for a bank of topics with categories, facts, and keywords.
-
Design a prompt for quiz generation with an explicit specification of the JSON output format.
-
Implement the QuizGenerator class with methods for extracting facts and generating questions.
-
Create a QuizValidator with checks for structure, presence of the answer among the options, and keywords.
-
Write a set of tests: structural, statistical, and golden set tests for quiz generation.
-
Package the quiz generation system into a Kubeflow Pipeline with batch processing and deduplication.