---
title: "Grounded exam generation with RAG: retrieval and evaluation"
description: "How ZeroExam AI keeps generated exam questions inside the syllabus: hybrid retrieval, rank fusion, grounding checks and an evaluation plan you can run."
author: Muhammad Gulzaib
orcid: https://orcid.org/0009-0000-8709-6989
published: 2026-07-18
url: https://gulzaib.vercel.app/blog/grounded-exam-generation-with-rag-retrieval-and-evaluation
category: AI Research
tags: [rag, llm, evaluation, retrieval, edtech]
reading_time: 5 min
license: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/); code samples MIT
---

# 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.

By Muhammad Gulzaib · 2026-07-18 · 5 min read · https://gulzaib.vercel.app/blog/grounded-exam-generation-with-rag-retrieval-and-evaluation

**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\]](#ref-lewis2020 "Lewis, P. et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020)"). The details are where it gets interesting.

## Pipeline

1.  **Chunk**: by heading, ~300 tokens
2.  **Retrieve**: BM25 + dense, k = 20 each
3.  **Fuse**: reciprocal rank fusion
4.  **Generate**: JSON schema, cite chunk IDs
5.  **Verify**: is 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\]](#ref-robertson2009 "Robertson, S. and Zaragoza, H., The Probabilistic Relevance Framework: BM25 and Beyond (2009)") 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\]](#ref-cormack2009 "Cormack, G. V., Clarke, C. L. A. and Büttcher, S., Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods (2009)") scores a document $d$ across the ranked lists $R$ as:

$$
\mathrm{RRF}(d) = \sum_{r \in R} \frac{1}{k + \mathrm{rank}_r(d)}
$$

where $k$ is a smoothing constant, commonly $k = 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\]](#ref-liu2023 "Liu, N. F. et al., Lost in the Middle: How Language Models Use Long Contexts (2024)"). So I keep the context short (top 6–8 chunks after fusion) and put the strongest chunks first.

> **Insight**
>
> More context is not better context. Fewer, well-ranked chunks gave cleaner questions than stuffing the whole chapter into the prompt.

## 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\]](#ref-es2023 "Es, S. et al., RAGAS: Automated Evaluation of Retrieval Augmented Generation (2023)").

| Stage | Metric | Definition | Target |
| --- | --- | --- | --- |
| Retrieval | Recall@k | Share of relevant chunks found in the top $k$ | High at $k = 8$ |
| Retrieval | MRR | Mean of $1/\text{rank}$ of the first relevant chunk | Above 0.5 |
| Generation | Faithfulness | Share of questions fully supported by cited chunks | Close to 100% |
| Generation | Syllabus match | Teacher rates question as in-syllabus (yes/no) | Close to 100% |
| Product | Edit rate | Share of questions a teacher edits before printing | Trending down |

Recall at $k$ for a query with relevant set $G$ and retrieved list $\hat{R}_k$:

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

> **Build the gold set with teachers**
>
> Ask two or three teachers to write 30 realistic requests and mark which sections answer them. It takes an afternoon, and it turns “it seems better” into a number.

## 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.

> **Key takeaways**
>
> -   Filter by metadata first. It removes most off-syllabus risk cheaply.
> -   Use hybrid retrieval and fuse ranks, not scores.
> -   Make every generated item cite its sources, then verify it.
> -   Evaluate retrieval and generation separately.

## 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](https://arxiv.org/abs/2005.11401). NeurIPS, 2020. [https://doi.org/10.48550/arXiv.2005.11401](https://doi.org/10.48550/arXiv.2005.11401)
2.  Robertson, S. and Zaragoza, H. [The Probabilistic Relevance Framework: BM25 and Beyond](https://doi.org/10.1561/1500000019). Foundations and Trends in Information Retrieval, 2009. [https://doi.org/10.1561/1500000019](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](https://doi.org/10.1145/1571941.1572114). SIGIR, 2009. [https://doi.org/10.1145/1571941.1572114](https://doi.org/10.1145/1571941.1572114)
4.  Liu, N. F. et al. [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172). TACL, 2024. [https://doi.org/10.1162/tacl\_a\_00638](https://doi.org/10.1162/tacl_a_00638)
5.  Es, S. et al. [RAGAS: Automated Evaluation of Retrieval Augmented Generation](https://arxiv.org/abs/2309.15217), 2023. [https://doi.org/10.48550/arXiv.2309.15217](https://doi.org/10.48550/arXiv.2309.15217)
