How to Test a RAG System: Build an Evaluation Set From Real Questions
Most retrieval-augmented generation (RAG) systems are shown working, not measured. Someone asks five questions, the answers look good, and the demo is declared a success. Then a real customer asks something slightly different and the assistant answers from the wrong page, or confidently from nowhere. The fix is not a better demo. It is a small, fixed set of real questions with known answers, and a script that scores your retrieval against it every time you change something.
This guide builds that harness in plain PHP. The retriever behind it is a deliberately simple stand-in, because the harness is the part you keep: you swap in your own retriever and keep the questions.
What this article is, and is not
Everything here ran on PHP 8.3. The documents are made up: a six-page help centre for an invented product, 538 words in total, with 24 answerable questions and 5 that have no answer. The retriever is a keyword scorer in the BM25 family, not embeddings and not a vector database. So the numbers below show how the method behaves on a toy corpus. They do not tell you how chunk size, embeddings or any provider will perform on yours. I make no claim about any embedding model or vector store, and the comments about what could help are expectations that you should test.
Step 1: Build the question set
- Use real questions. Take them from support tickets, chat transcripts, search logs and sales e-mails, anonymised. Invented questions are written in the vocabulary of the documents, which hides the very gap you need to find.
- Start with about fifty. More is better, but a small set you will actually maintain beats a large one you will not.
- Record the gold answer as an exact sentence that a correct retrieval must contain, or as a passage id. The script checks for it automatically.
- Include questions that have no answer, perhaps one in six. A good assistant must refuse them, and you cannot measure refusal without them.
- Keep the set fixed and versioned. If you keep editing it to make the scores look better, it no longer measures anything.
Two entries from the example set, so you can see the shape:
['question' => 'Can I get an older version of my document back?',
'gold' => 'You can restore a previous version of a file for up to 90 days on Plus'],
['question' => 'What is the weather in Paris?', 'gold' => null], // no answer exists
Step 2: Choose what to measure
| Metric | Question it answers |
|---|
| hit@k | Is a chunk containing the gold sentence among the top k results? Use hit@1 if you pass one chunk to the model, hit@5 if you pass five. |
| MRR (mean reciprocal rank) | How high does the right chunk rank on average? 1 means always first, 0.5 means typically second. |
| False accept rate | For questions with no answer, how often does the best result score high enough that the assistant would answer anyway? |
Step 3: The code
Three small classes. The chunker splits a document into overlapping pieces of roughly a given number of words.
Chunker.php
<?php
/** Splits a document into overlapping chunks of roughly $size words. */
final class Chunker
{
public function __construct(private int $size, private int $overlap = 0) {}
/** @return array<int, string> */
public function chunk(string $text): array
{
$words = preg_split('/\s+/', trim($text), -1, PREG_SPLIT_NO_EMPTY);
$step = max(1, $this->size - $this->overlap);
$chunks = [];
for ($i = 0; $i < count($words); $i += $step) {
$chunks[] = implode(' ', array_slice($words, $i, $this->size));
if ($i + $this->size >= count($words)) {
break;
}
}
return $chunks;
}
}
The evaluator only needs one thing from a retriever: a search($query, $k) method that returns the top chunks with their text and a score, best first. That is the contract you reproduce for your own retriever.
Evaluator.php
<?php
/**
* Scores any retriever against a question set.
* A question is a "hit" at k if one of the top k chunks contains its gold sentence.
*/
final class Evaluator
{
/**
* @param array<int, array{question: string, gold: ?string}> $questions gold = null means "no answer exists"
* @return array{answerable: int, hit_at_1: float, hit_at_3: float, hit_at_5: float, mrr: float, unanswerable: int, false_accept: float}
*/
public function run(KeywordRetriever $retriever, array $questions, float $minScore): array
{
$answerable = $hit1 = $hit3 = $hit5 = $unanswerable = $falseAccept = 0;
$rr = 0.0;
foreach ($questions as $q) {
$results = $retriever->search($q['question'], 5);
if ($q['gold'] === null) {
$unanswerable++;
// The assistant should refuse: wrongly "accepting" means the best score cleared the bar.
if (($results[0]['score'] ?? 0) >= $minScore) {
$falseAccept++;
}
continue;
}
$answerable++;
$rank = null;
foreach ($results as $i => $r) {
if (str_contains($r['text'], $q['gold'])) {
$rank = $i + 1;
break;
}
}
if ($rank !== null) {
$rr += 1 / $rank;
$hit5++;
$rank <= 3 && $hit3++;
$rank === 1 && $hit1++;
}
}
return [
'answerable' => $answerable,
'hit_at_1' => round($hit1 / max(1, $answerable), 3),
'hit_at_3' => round($hit3 / max(1, $answerable), 3),
'hit_at_5' => round($hit5 / max(1, $answerable), 3),
'mrr' => round($rr / max(1, $answerable), 3),
'unanswerable' => $unanswerable,
'false_accept' => round($falseAccept / max(1, $unanswerable), 3),
];
}
}
For the example I used a small keyword retriever, shown here only so that the experiment is reproducible. In real use you replace it with a class that calls your embeddings and vector store but has the same search() signature.
KeywordRetriever.php (the stand-in)
<?php
/**
* A deliberately simple retriever (BM25-style keyword scoring). It stands in for
* your real one (embeddings, a vector database...). The evaluation code only
* needs search(), so you can swap it out.
*/
final class KeywordRetriever
{
/** @var array<int, array{id: string, text: string, terms: array<string, int>, len: int}> */
private array $chunks = [];
/** @var array<string, int> */
private array $docFreq = [];
private float $avgLen = 0.0;
private const STOP = ['the','a','an','of','to','in','is','are','and','or','for','on','at','by','be','it','this','that','with','as','do','does','how','what','can','i','my','you','your','from','there','if','was','were','will','have','has'];
/** @param array<int, array{id: string, text: string}> $chunks */
public function __construct(array $chunks)
{
foreach ($chunks as $c) {
$terms = array_count_values($this->tokens($c['text']));
$this->chunks[] = $c + ['terms' => $terms, 'len' => array_sum($terms)];
foreach (array_keys($terms) as $t) {
$this->docFreq[$t] = ($this->docFreq[$t] ?? 0) + 1;
}
}
$this->avgLen = count($this->chunks) ? array_sum(array_column($this->chunks, 'len')) / count($this->chunks) : 0;
}
/** @return array<int, array{id: string, text: string, score: float}> best first */
public function search(string $query, int $k): array
{
$n = count($this->chunks);
$scored = [];
foreach ($this->chunks as $c) {
$score = 0.0;
foreach ($this->tokens($query) as $t) {
$tf = $c['terms'][$t] ?? 0;
if ($tf === 0) {
continue;
}
$idf = log(1 + ($n - $this->docFreq[$t] + 0.5) / ($this->docFreq[$t] + 0.5));
$score += $idf * ($tf * 2.2) / ($tf + 1.2 * (0.25 + 0.75 * $c['len'] / max(1, $this->avgLen)));
}
$scored[] = ['id' => $c['id'], 'text' => $c['text'], 'score' => $score];
}
usort($scored, fn ($a, $b) => $b['score'] <=> $a['score']);
return array_slice($scored, 0, $k);
}
/** @return array<int, string> */
private function tokens(string $text): array
{
$words = preg_split('/[^a-z0-9]+/', strtolower($text), -1, PREG_SPLIT_NO_EMPTY);
return array_values(array_filter($words, fn ($w) => ! in_array($w, self::STOP, true)));
}
}
The runner builds a retriever for each chunking setting and prints the scores. It also refuses to run if a gold sentence is not actually present in the documents, which catches a typo that would otherwise quietly count as a miss.
$all = implode(' ', $data['docs']);
foreach ($data['questions'] as $q) {
if ($q['gold'] !== null && ! str_contains($all, $q['gold'])) {
fwrite(STDERR, "Gold sentence not found in documents: {$q['gold']}\n");
exit(1);
}
}
foreach ([[25, 0], [25, 8], [60, 0], [60, 15], [150, 0], [400, 0]] as [$size, $overlap]) {
$res = (new Evaluator)->run(build($data['docs'], $size, $overlap), $data['questions'], 0);
// print $res['hit_at_1'], $res['hit_at_3'], $res['hit_at_5'], $res['mrr'] ...
}
What it showed
| Chunk size / overlap (words) | Chunks | hit@1 | hit@3 | hit@5 | MRR |
|---|
| 25 / 0 | 26 | 0.29 | 0.46 | 0.54 | 0.389 |
| 25 / 8 | 33 | 0.33 | 0.62 | 0.71 | 0.477 |
| 60 / 0 | 13 | 0.46 | 0.58 | 0.58 | 0.521 |
| 60 / 15 | 13 | 0.54 | 0.79 | 0.79 | 0.667 |
| 150 / 0 | 6 | 0.79 | 0.83 | 0.92 | 0.824 |
| 400 / 0 | 6 | 0.79 | 0.83 | 0.92 | 0.824 |
Read it carefully before drawing conclusions:
- Small chunks scored worst here, and overlap helped them. With 25-word chunks, a sentence and the words that make it findable often end up in different pieces. Overlap repairs some of that, which lifted hit@5 from 0.54 to 0.71.
- 150 and 400 words give identical results because every document is shorter than 150 words, so each is one chunk. On this toy corpus the best "chunking" is no chunking. That says nothing about long documents.
- Do not copy these numbers. On real documents the picture can differ a lot, which is exactly why you run the same script on yours.
The refusal threshold
An assistant that answers every question will answer the five that have no answer. A minimum score for the best result lets it refuse. Raising the threshold removes wrong answers but also removes right ones:
| Minimum score | Answerable questions still answered (of 24) | Unanswerable questions wrongly answered (of 5) |
|---|
| 0 (none) | 24 | 5 |
| 1 | 20 | 2 |
| 2 | 18 | 1 |
| 3 | 13 | 1 |
| 4 | 7 | 0 |
| 5 | 5 | 0 |
On this data there is no clean cut: the threshold that stops the last false answer also throws away most correct ones. The five unanswerable questions scored 0.00, 3.59, 1.79, 0.00 and 0.00. The 3.59 belongs to "Does Acme Drive offer a desktop app for Linux?", which scored high because it contains the product name that appears all over the help centre. The 1.79 belongs to "How many employees does Acme have?", for the same reason. In a real system you would pick the threshold from your own curve, and you would send the borderline cases to a person.
Read the failures, not only the averages
The most useful output is the list of questions that missed. At chunk size 150, two of the 24 never reached the top five:
- "How do I invite a colleague?" The page says "add team members". The words do not overlap.
- "Is the service down right now?" The page says "status page" and "incidents".
Both are vocabulary mismatches, and a keyword retriever cannot bridge them. Retrieval based on meaning is designed to help here, and rewriting or expanding the query is another option, but I did not test either, so treat them as hypotheses. The point of the harness is that you can now try them and see whether the score moves.
Using it with your real system
- Write a class with the same
search() signature that calls your retriever.
- Run the question set before you change anything and save the output in the repository as your baseline.
- Change one thing (chunk size, overlap, an embedding model, a prompt that rewrites the question) and run it again.
- Keep the change only if the scores improve and no important question got worse.
- When a real customer question fails in production, add it to the set.
What retrieval scores do not tell you
A hit means the right text was retrieved. It does not mean the assistant then answered correctly, used the text, or refused when it should have. That needs a second check on the generated answers, either by a person or by a carefully designed automated grader, and I did not test one here. Keep retrieval quality and answer quality as two separate measurements.
Common mistakes
- Judging by a handful of demo questions.
- Writing questions from the documents, so every question uses the same words as the answer.
- No unanswerable questions, so refusal is never measured.
- Tuning against the same questions until the score rises, then trusting the score. Keep a few questions out of the tuning.
- Comparing runs with different question sets.
- Treating one average as the answer. Look at which questions fail.
Frequently asked questions
How many questions do I need?
Start with about fifty real ones. The set should be large enough that one question changing does not swing the score, and small enough that you maintain it.
Can an AI model write the questions?
It can help you paraphrase, but questions generated from your documents share their vocabulary. Real customer wording is more valuable.
Which retriever should I use?
Whichever scores best on your questions. This article does not recommend one.
Is this the same as testing the whole chatbot?
No. This measures retrieval only. You also need tests of the final answers, of refusals and of the handover to a person.
Where this fits
If you are building an assistant that answers from your own documents and want it measured properly, see AI Customer Support & Chatbot Automation and AI Automation Services, or describe your knowledge base here. My AI Customer Support Agent portfolio project describes the design principle of answering only from approved knowledge, without claiming results. More guides on this topic are collected under RAG.