Sub topic 15
Evaluating a RAG System
This chapter assumes you can read basic Python, know how a RAG pipeline fits together (chunking, embeddings, top-k retrieval, prompt assembly), and understand cosine similarity. It covers how to measure a RAG system in two separate parts, retrieval and generation, so you can tell which part is failing.
Why evaluate in two parts
A RAG answer can be wrong for two different reasons. The retriever may not have found the right passages. Or the retriever may have found them and the model may have ignored or misread them. If you only grade the final answer, you cannot tell these apart, and you may spend a week tuning prompts when the real problem is chunking.
So evaluate each stage on its own:
- Retrieval quality: did the right passages appear in the top k?
- Generation quality: given the passages, was the answer faithful to them and did it address the question?
Build an evaluation set
Every metric below needs a test set. A small, well-made one beats a large, sloppy one. Start with 30 to 100 questions.
Each example should contain:
- A question written the way real users ask it.
- The IDs of the chunks (or documents) that contain the answer. These are the "relevant" documents.
- Optionally, a reference answer written by a person.
Take questions from real logs or support tickets when you can. Questions that you write yourself while looking at the documents tend to reuse the document's own wording. That makes retrieval look easier than it is. Include some questions that have no answer in the corpus, so you can test whether the system admits it doesn't know.
You can use a language model to draft questions from chunks, which is cheap. Have a person review them, because generated questions are often too easy or ambiguous.
{
"id": "q-014",
"question": "How long do I have to request a refund?",
"relevant_ids": ["policy-refunds-03"],
"reference_answer": "30 days from the delivery date.",
"answerable": true
}Measuring retrieval
Recall at k
Recall at k is the fraction of relevant documents that appear in the top k results. If two chunks hold the answer and one is in the top 5, recall at 5 is 0.5.
def recall_at_k(retrieved_ids, relevant_ids, k):
relevant = set(relevant_ids)
if not relevant:
return 0.0
hits = set(retrieved_ids[:k]) & relevant
return len(hits) / len(relevant)Recall is the most important retrieval metric for RAG. The model can only use what you hand it. If a relevant passage is not in the top k, no prompt can fix that.
Precision and MRR
Precision at k is the fraction of the top k results that are relevant. Low precision means the prompt is padded with noise, which costs tokens and can distract the model.
Mean reciprocal rank (MRR) looks at the position of the first relevant result. For each question, the score is 1 divided by that rank, or 0 if nothing relevant was found. Then you average over all questions. A first hit at rank 1 scores 1.0, at rank 2 scores 0.5, and at rank 4 scores 0.25. MRR matters when the order of passages matters, for example when you truncate the context to fit a token budget.
def precision_at_k(retrieved_ids, relevant_ids, k):
if k <= 0:
return 0.0
relevant = set(relevant_ids)
top = retrieved_ids[:k]
return sum(1 for d in top if d in relevant) / k
def reciprocal_rank(retrieved_ids, relevant_ids):
relevant = set(relevant_ids)
for rank, doc_id in enumerate(retrieved_ids, start=1):
if doc_id in relevant:
return 1.0 / rank
return 0.0
def evaluate_retrieval(examples, retrieve, k=5):
# retrieve(question) returns a ranked list of chunk ids
recalls, precisions, rrs = [], [], []
for ex in examples:
if not ex["answerable"]:
continue
ids = retrieve(ex["question"])
recalls.append(recall_at_k(ids, ex["relevant_ids"], k))
precisions.append(precision_at_k(ids, ex["relevant_ids"], k))
rrs.append(reciprocal_rank(ids, ex["relevant_ids"]))
n = len(recalls)
return {
"recall@k": sum(recalls) / n,
"precision@k": sum(precisions) / n,
"mrr": sum(rrs) / n,
}Skip unanswerable questions in these metrics, because they have no relevant IDs.
Which metric to watch
| Metric | Question it answers | Typical use |
|---|---|---|
| Recall@k | Did the needed passage make it in? | Primary retrieval metric |
| Precision@k | How much noise is in the context? | Tuning k and reranking |
| MRR | How high is the first good passage? | Tight context budgets |
A common pattern is to retrieve a wide set (say k = 20) and check recall there. Then check recall at the smaller k you actually send to the model. A big gap suggests adding a reranker.
Measuring generation
Generation metrics are harder because answers are free text. Three questions cover most needs.
- Faithfulness (groundedness): is every claim in the answer supported by the retrieved passages?
- Answer relevance: does the answer address the question that was asked?
- Correctness: does the answer match the reference answer?
Faithfulness is the metric most specific to RAG. An answer can be correct by luck, because the model memorized the fact, and still be unfaithful. That is a risk, because the same model will invent facts when its memory fails.
Judging with a model
The usual approach is "LLM as judge." You give a second model the question, the passages, and the answer, and ask it to grade against a rubric. Keep the rubric narrow and ask for a short explanation before the score.
def build_judge_prompt(question, passages, answer):
context = "\n\n".join(f"[{i}] {p}" for i, p in enumerate(passages, start=1))
return (
"You are grading a question-answering system.\n"
"List each factual claim in the answer. For each claim, say whether "
"the context supports it. Then output a final line in the form "
"'SUPPORTED: <supported claims>/<total claims>'.\n\n"
f"Context:\n{context}\n\n"
f"Question: {question}\n"
f"Answer: {answer}\n"
)Faithfulness is then supported claims divided by total claims. Judges have known biases. They tend to favor longer answers and answers that resemble their own style. Reduce the risk with these habits:
- Check the judge against 20 to 30 answers that a person graded. If they disagree often, fix the rubric.
- Use a judge model that is at least as capable as the one being graded.
- Keep the judge's settings fixed between runs so scores stay comparable.
Testing refusals
For unanswerable questions, the correct behavior is to say the context does not contain the answer. Measure the refusal rate on those questions. Also measure the opposite error: how often the system refuses on answerable questions. A model that always says "I don't know" has perfect refusal accuracy on one set and fails on the other.
Checking citations
If the prompt asks for citations like [1], you can partly check them with code. Parse the markers and confirm each points to a passage that was actually provided. Then check with the judge that the cited passage supports the sentence.
import re
def invalid_citations(answer, num_passages):
cited = {int(m) for m in re.findall(r"\[(\d+)\]", answer)}
return sorted(c for c in cited if c < 1 or c > num_passages)Reading the results together
Combine the two sets of numbers to locate the problem.
| Recall@k | Faithfulness | Likely cause |
|---|---|---|
| Low | Any | Retrieval is missing the answer. Look at chunking, embeddings, hybrid search, query rewriting. |
| High | Low | The model ignores or invents beyond the context. Look at the prompt, context order, and noise. |
| High | High, but answers wrong | The source is wrong, outdated, or the question was misread. Check the corpus. |
| High | High | The pipeline is working. Look at latency and cost. |
Practical habits
- Fix the test set before tuning. If you change questions and settings together, you cannot tell what helped.
- Change one thing per run. Chunk size, overlap, embedding model, k, and prompt each affect several metrics.
- Store per-question results. Averages hide regressions. Diff the failing questions between runs.
- Report confidence. With 50 questions, a change of two points is noise. Look for consistent gains across metrics.
- Keep a held-out set. If you tune on every question, you overfit to them. Reserve a portion you only check at the end.
- Add real failures. When a user reports a bad answer, turn it into a new test case.
Exercise
A system scores recall@5 of 0.92 but faithfulness of 0.55. Where would you look first, and why?
Show answer
Look at generation, not retrieval. High recall means the relevant passages usually reach the model. Low faithfulness means the answer contains claims the passages do not support. Check the prompt (does it say to answer only from the context and to refuse otherwise?), the amount of irrelevant context (precision@k), and the order of passages. Also read a sample of unfaithful answers to see whether the model is adding background knowledge.
Exercise
For one question, the relevant chunk IDs are ["a", "b"] and the retriever returns ["c", "a", "d", "e", "b"]. Compute recall@3, precision@3, and the reciprocal rank.
Show answer
The top 3 are ["c", "a", "d"]. Only "a" is relevant, so recall@3 = 1/2 = 0.5 and precision@3 = 1/3 ≈ 0.33. The first relevant result is "a" at rank 2, so the reciprocal rank is 1/2 = 0.5.
Exercise
Why should an evaluation set include questions that have no answer in the corpus?
Show answer
Without them you cannot measure whether the system refuses correctly. A system that always produces an answer would look perfect on answerable questions while inventing answers whenever the corpus lacks the information. Unanswerable questions let you measure refusal rate and false answers.