Skip to content

Keyboard shortcuts

/
Search posts
CtrlK
Search posts (⌘ K on a Mac)
jk
Next / previous section (in a post)
s
Save or unsave this post
f
Focus mode: hide everything but the text
l
Listen: read the post aloud
t
Cycle theme
+−
Larger / smaller text
gh
Go to the blog home
?
Show this help
Esc
Close panels

Shortcuts are ignored while you type in a field.

Grounded exam generation with RAG: retrieval and evaluation

How ZeroExam AI keeps generated exam questions inside the syllabus: hybrid retrieval, rank fusion, grounding checks and an evaluation plan you can run.

3D illustration of an exam paper with three green ticks, each tied by a glowing thread to a page in a stack of textbooks. Headline: Exam questions that stay inside the syllabus.
On this page 6 sections

Abstract

Teachers don’t want creative exam questions. They want questions that match the syllabus they actually taught. This post describes the retrieval-augmented generation design behind ZeroExam AI: hybrid lexical and dense retrieval over syllabus chapters, reciprocal rank fusion, a grounding check on every generated question, and an evaluation plan that separates retrieval quality from generation quality.

The problem#

A plain LLM asked to “write ten physics questions for grade 9, chapter 3” produces fluent questions, but some of them test concepts that aren’t in that chapter, or in that country’s curriculum at all. For a teacher, one off-syllabus question is enough to stop trusting the tool.

RAG is the obvious fix: retrieve the relevant chapter content and make the model generate from it [1]. The details are where it gets interesting.

Pipeline#

  1. 01Chunkby heading, ~300 tokens
  2. 02RetrieveBM25 + dense, k = 20 each
  3. 03Fusereciprocal rank fusion
  4. 04GenerateJSON schema, cite chunk IDs
  5. 05Verifyis each question grounded?
Figure 1. Every generated question carries the IDs of the chunks it came from.

Chunking by structure#

Textbooks already have structure: chapters, sections, worked examples, exercises. I chunk along headings first and only split long sections by token count. Each chunk keeps its metadata (grade, subject, chapter, section), which lets us filter before ranking. Filtering by chapter removes most of the off-syllabus risk on its own.

Hybrid retrieval#

Dense embeddings are good at paraphrase (“speed” and “velocity”). Lexical search like BM25 [2] is good at exact terms, formulas and names that embeddings blur together. Exam content has plenty of both, so I run both and fuse the rankings.

Reciprocal rank fusion#

Scores from BM25 and cosine similarity live on different scales, so instead of mixing scores, I mix ranks. Reciprocal rank fusion [3] scores a document dd across the ranked lists RR as:

RRF(d)=∑r∈R1k+rankr(d)\mathrm{RRF}(d) = \sum_{r \in R} \frac{1}{k + \mathrm{rank}_r(d)}

where kk is a smoothing constant, commonly k=60k = 60. A chunk that appears near the top of either list gets a boost, and one that appears in both does best. It needs no tuning and no score normalisation, which is exactly what you want in an early system.

fusion.py
python
def rrf(rankings: list[list[str]], k: int = 60) -> list[str]:
    scores: dict[str, float] = {}
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking, start=1):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)

Context ordering#

Models use information at the start and end of a long context more reliably than information in the middle [4]. So I keep the context short (top 6–8 chunks after fusion) and put the strongest chunks first.

Grounding every question#

Generation returns structured JSON. Each question must list the chunk IDs that support it:

question.json
json
{
  "question": "A car accelerates uniformly from rest to 20 m/s in 5 s. Find its acceleration.",
  "type": "numerical",
  "difficulty": "easy",
  "answer": "4 m/s²",
  "sources": ["phy-9-ch3-s2-c04"]
}

A second, cheaper model call then acts as a verifier: given only the cited chunks, can this question be answered, and is the answer correct? Questions that fail are regenerated or dropped. This catches most hallucinated concepts before a teacher ever sees them.

Evaluation plan#

The most common mistake I see in RAG projects is evaluating only the final answer. If the output is bad, you can’t tell whether retrieval or generation failed. So I measure them separately, in the spirit of RAGAS [5].

StageMetricDefinitionTarget
RetrievalRecall@kShare of relevant chunks found in the top kkHigh at k=8k = 8
RetrievalMRRMean of 1/rank1/\text{rank} of the first relevant chunkAbove 0.5
GenerationFaithfulnessShare of questions fully supported by cited chunksClose to 100%
GenerationSyllabus matchTeacher rates question as in-syllabus (yes/no)Close to 100%
ProductEdit rateShare of questions a teacher edits before printingTrending down

Recall at kk for a query with relevant set GG and retrieved list R^k\hat{R}_k:

Recall@k=∣G∩R^k∣∣G∣\mathrm{Recall@}k = \frac{\lvert G \cap \hat{R}_k \rvert}{\lvert G \rvert}

Latency budget#

A teacher will wait a few seconds for a full paper, but not a minute. This is the budget I design against for a single question, not a benchmark:

Design budget per question (ms)

Filter + BM2540 ms
Embed query + ANN120 ms
Fusion5 ms
Generation1800 ms
Verification600 ms
Generation dominates, so questions for a paper are generated in parallel and streamed into the editor as they’re ready.

Open questions#

Things I’m still exploring
  • Answer checking. Grading handwritten or typed long answers against a rubric is a much harder problem than generating questions.
  • Urdu-medium content. Tokenisation and embeddings for Urdu are weaker, which affects both retrieval and generation.
  • Difficulty calibration. “Hard” according to the model doesn’t always mean hard for students. Real student results are the only reliable signal.

Questions readers ask

How do you stop RAG from generating off-syllabus questions?

Filter retrieval by metadata such as grade, subject and chapter first, retrieve with hybrid lexical and dense search, and make every generated question cite its source passages so a grounding check can verify it.

Why use reciprocal rank fusion for hybrid retrieval?

Lexical and dense retrievers produce scores on different scales. Fusing their ranks instead of their scores combines them without fragile score normalisation.

How should a RAG system be evaluated?

Evaluate retrieval and generation separately, so you know whether a bad question came from missing context or from the model.

References

  1. Lewis, P. et al. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. NeurIPS, 2020. https://doi.org/10.48550/arXiv.2005.11401
  2. Robertson, S. and Zaragoza, H. The Probabilistic Relevance Framework: BM25 and Beyond. Foundations and Trends in Information Retrieval, 2009. https://doi.org/10.1561/1500000019
  3. Cormack, G. V., Clarke, C. L. A. and Büttcher, S. Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods. SIGIR, 2009. https://doi.org/10.1145/1571941.1572114
  4. Liu, N. F. et al. Lost in the Middle: How Language Models Use Long Contexts. TACL, 2024. https://doi.org/10.1162/tacl_a_00638
  5. Es, S. et al. RAGAS: Automated Evaluation of Retrieval Augmented Generation, 2023. https://doi.org/10.48550/arXiv.2309.15217