Sub topic 11
Evaluating retrieval and grounded answers
A retrieval-augmented generation (RAG) system fetches documents and asks a model to answer from them. When it gives a wrong answer, either stage may be at fault. This chapter shows how to score the two stages separately so you can tell which one failed.
This chapter assumes you can write basic Python, have called an LLM through an API, and know the harness idea from earlier chapters: a dataset, an application, a scorer, and a pass rate. It also assumes you know what a judge prompt is and what a proportion and a mean are.
Why one end-to-end score is not enough
Suppose your RAG system passes 70% of its test questions. That number does not say why the other 30% failed. There are two distinct causes:
- Retrieval failure. The documents that contain the answer never reached the model.
- Generation failure. The right documents reached the model, but the answer ignored them, contradicted them, or added claims they do not support.
The fixes differ. Retrieval failures call for changes to chunking, embeddings, query rewriting, or the number of results. Generation failures call for changes to the prompt, the model, or the instructions about unsupported claims. If you only have an end-to-end score, you will tune the wrong component.
Evaluating retrieval
Retrieval evaluation needs a dataset where each question is labeled with the documents (or chunks) that contain the answer. These are the relevant IDs. You can write them by hand, derive them from the source document a question was generated from, or collect them from annotators. The labels are scored against the retriever's ranked list of IDs. No LLM call is needed, so these metrics are cheap and deterministic.
Recall at k
Recall at k is the fraction of relevant documents that appear in the top k results. It is the most important retrieval metric for RAG, because a document that is not retrieved cannot be used.
def recall_at_k(retrieved_ids, relevant_ids, k):
if not relevant_ids:
return 0.0
hits = len(set(retrieved_ids[:k]) & set(relevant_ids))
return hits / len(relevant_ids)
print(recall_at_k(["d3", "d7", "d1"], ["d1", "d2"], k=3)) # 0.5Here one of the two relevant documents (d1) was found and d2 was missed, so recall is 0.5.
Precision and rank
Recall ignores noise. A retriever that returns 20 documents will often reach high recall, but it fills the context with irrelevant text. That text costs tokens and can distract the model. Two more metrics cover this.
- Precision at k is the fraction of the top k results that are relevant.
- Reciprocal rank is 1 divided by the rank of the first relevant result. Its mean over a dataset is called MRR (mean reciprocal rank). It matters when only the top few results are shown to the model or the user.
def precision_at_k(retrieved_ids, relevant_ids, k):
top = retrieved_ids[:k]
if not top:
return 0.0
return len(set(top) & set(relevant_ids)) / len(top)
def reciprocal_rank(retrieved_ids, relevant_ids):
for rank, doc_id in enumerate(retrieved_ids, start=1):
if doc_id in relevant_ids:
return 1.0 / rank
return 0.0
retrieved = ["d3", "d7", "d1"]
relevant = ["d1", "d2"]
print(precision_at_k(retrieved, relevant, k=3)) # 0.333...
print(reciprocal_rank(retrieved, relevant)) # 0.333...Pick k to match your system. If the generator receives five chunks, report recall at 5. A recall at 50 does not describe what the model sees.
Edge cases in retrieval labels
- Chunk IDs go stale. If you change the chunk size or splitter, the IDs in your labels no longer match. Label at the level of source document and passage text, or keep a mapping you can rebuild, so you can re-chunk without relabeling.
- Several chunks may answer the question. Decide whether you need all relevant chunks (recall as defined above) or just one (a "hit at k" metric). Multi-hop questions need all of them.
- Unanswerable questions. Include questions whose answer is not in the corpus. Their relevant list is empty, so recall is undefined. Report them separately and score the generator on whether it declines to answer.
- The index changes. Pin a snapshot of the corpus for evaluation. If documents are added or edited, scores can change with no change in your code.
Evaluating grounded answers
Once the model has context, there are three different questions you can ask about its answer.
| Property | Question | Compared against |
|---|---|---|
| Faithfulness (groundedness) | Is every claim supported by the retrieved context? | Context |
| Correctness | Does the answer match the true answer? | Reference answer |
| Answer relevance | Does the answer address what was asked? | Question |
These can disagree. An answer can be faithful but wrong, if the retrieved document is outdated. It can be correct but unfaithful, if the model used its own memory instead of the context. For a system whose promise is "answers come from our documents", the second case is still a failure, because the answer cannot be traced to a source.
Faithfulness is usually scored with an LLM judge. Use a prompt with one criterion and a strict output format, as in the judge chapter. The criterion here is that the answer must be fully supported by the context and add no claims the context does not contain. Always pass the context that the generator actually saw, not the gold documents. If you pass the gold documents, you will score a retrieval failure as a faithful answer to the wrong evidence, or the reverse.
Count unparseable judge replies as a separate number. If 5% of verdicts come back as None, your pass rate has an unknown 5% in it.
Cheap programmatic checks
Some grounding checks need no judge. If your system must cite sources, you can check the following:
- Every cited ID appears in the retrieved set.
- Quoted spans appear verbatim in the context.
- The answer contains a refusal phrase when the question is unanswerable.
These checks catch fabricated citations reliably and cost nothing, so run them before the judge.
Putting it together: a per-case RAG evaluation
The function below evaluates one case in three steps. It retrieves, generates, and then records the retrieval metrics and a faithfulness verdict together. The stubs make the example runnable. In a real system you would pass in your retriever, your model call, and a judge built from the judge prompt.
def recall_at_k(retrieved_ids, relevant_ids, k):
if not relevant_ids:
return 0.0
hits = len(set(retrieved_ids[:k]) & set(relevant_ids))
return hits / len(relevant_ids)
def reciprocal_rank(retrieved_ids, relevant_ids):
for rank, doc_id in enumerate(retrieved_ids, start=1):
if doc_id in relevant_ids:
return 1.0 / rank
return 0.0
def eval_rag_case(case, retriever, generator, judge, k=3):
retrieved = retriever(case["question"], k) # list of (doc_id, text)
ids = [doc_id for doc_id, _ in retrieved]
context = "\n\n".join(text for _, text in retrieved)
answer = generator(case["question"], context)
return {
"id": case["id"],
"recall": recall_at_k(ids, case["relevant_ids"], k),
"rr": reciprocal_rank(ids, case["relevant_ids"]),
"faithful": judge(context, case["question"], answer),
"answer": answer,
}
# Stubs so the example runs without a model.
DOCS = {
"d1": "The warranty lasts 24 months from the purchase date.",
"d2": "Returns are accepted within 30 days.",
"d3": "Our office is closed on public holidays.",
}
def stub_retriever(question, k):
return list(DOCS.items())[:k]
def stub_generator(question, context):
return "The warranty lasts 24 months."
def stub_judge(context, question, answer):
return "24 months" in context # a real judge would call an LLM
case = {"id": "q1", "question": "How long is the warranty?", "relevant_ids": ["d1"]}
print(eval_rag_case(case, stub_retriever, stub_generator, stub_judge))Run this over the whole dataset and average each field separately. Report mean recall, MRR, and the faithfulness rate as three numbers, not one blended score. Because the dataset is small, add a confidence interval to each, using the bootstrap from the statistics chapter. Resample over questions, since the questions are your independent units.
Diagnosing failures
Join the retrieval and grounding results per case. Each case then falls into one of four groups.
| Retrieval found the evidence | Answer is faithful | Likely cause | Where to work |
|---|---|---|---|
| Yes | Yes | Success, or an outdated or wrong source | Check the answer against the reference |
| Yes | No | The model ignored or went beyond the context | Prompt, model, instructions to cite or abstain |
| No | Yes | The model faithfully answered from the wrong text | Chunking, embeddings, query rewriting |
| No | No | Both stages failed, often the model guessing | Fix retrieval first, then re-measure |
Fix retrieval first when both fail. Many "hallucinations" are the generator filling a gap that retrieval left.
Common mistakes
- Reporting only end-to-end accuracy. You lose the ability to locate the failing stage.
- Tuning k on the test set. Changing k until recall looks good overfits your dataset. Choose k from your context budget first.
- Using gold documents as judge context. This hides retrieval failures.
- Ignoring unanswerable questions. A system that always answers will score well on a dataset where every question has an answer.
- Using synthetic questions generated from a single chunk. They share vocabulary with that chunk, so keyword retrieval looks better than it will on real user queries. Mix in real queries.
Exercise
A RAG system has mean recall at 5 of 0.92 and a faithfulness rate of 0.61. Which stage do you investigate first, and what would you look at?
Show answer
Investigate generation first. Retrieval usually delivers the relevant documents, so the low faithfulness points to the model adding claims or ignoring the context. Read the failing cases and check whether the unsupported claims come from the model's own knowledge. Then adjust the prompt or model, for example by instructing it to answer only from the context and to say so when the context is insufficient. Also confirm the judge was given the context the generator actually saw, and check how many judge replies were unparseable.
Exercise
The retriever returns ["d4", "d2", "d9", "d1"] for a question whose relevant IDs are ["d1", "d2"]. Compute recall at 3, precision at 3, and reciprocal rank.
Show answer
The top 3 are d4, d2, d9. Only d2 is relevant, so recall at 3 is 1/2 = 0.5, precision at 3 is 1/3 ≈ 0.333, and the first relevant result is at rank 2, so the reciprocal rank is 0.5.