Sub topic 11
Evaluating retrieval and grounded answers
This chapter assumes you can write basic Python, have called an LLM through an SDK, and know how a retrieval-augmented generation (RAG) pipeline works. It also assumes you have the evaluation harness from earlier chapters. A RAG system first retrieves documents and then generates an answer from them. Each step can fail on its own, so you should score each step separately.
Why one score is not enough
Suppose a RAG system gives a wrong answer. There are two likely causes:
- The retriever did not return the document that contains the answer.
- The retriever returned the right document, but the model ignored it or invented details.
A single end-to-end pass rate cannot tell these apart, and each cause needs a different fix. Measure retrieval quality and answer faithfulness separately.
Evaluating retrieval
Retrieval evaluation needs a dataset where each question lists the IDs of the documents that contain the answer. Recall at k is the fraction of those relevant documents that appear in the top k results.
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.5This metric needs no LLM call, so it is cheap and deterministic. You can run it on every change to chunking, embeddings, or the index. Pick k to match how many documents you pass to the generator. If the generator sees five chunks, recall at 5 is the number that matters.
Evaluating grounded answers
An answer is grounded, or faithful, when the retrieved context supports every claim in it. This differs from correctness. An answer can be true in the real world and still be ungrounded, because the model took it from its training data instead of the context. Faithfulness is hard to check with string matching, so an LLM judge is the usual tool. The prompt below states one criterion and a strict output format.
JUDGE_PROMPT = """You are grading an answer to a question.
Criterion: the answer must be fully supported by the provided context and must not add claims that the context does not contain.
Context:
{context}
Question:
{question}
Answer:
{answer}
On the first line, write only PASS or FAIL. On the second line, give a one-sentence reason."""
def build_judge_prompt(context: str, question: str, answer: str) -> str:
return JUDGE_PROMPT.format(context=context, question=question, answer=answer)
def parse_verdict(judge_output: str):
lines = judge_output.strip().splitlines()
if not lines:
return None
first = lines[0].strip().upper()
if first in ("PASS", "FAIL"):
return first == "PASS"
return None # unparseable: count and review these separatelyCount the None results instead of treating them as failures. A rising count usually means the judge prompt or model has a problem.
Reading the two scores together
| Recall at k | Faithfulness | Likely problem |
|---|---|---|
| Low | High | Retriever misses documents. The model stays within the poor context it was given. |
| High | Low | The generator ignores or embellishes the context. Tighten the prompt or change the model. |
| Low | Low | Fix retrieval first, then re-measure. |
| High | High | Check answer correctness against references. |
Common errors
- Judging faithfulness against the gold document instead of the context that was actually retrieved. The judge must see what the generator saw.
- Building questions from a document's own wording, so retrieval looks better than it will with real users. Include paraphrased questions.
- Having no questions whose answer is absent from the corpus. A good system should say it does not know, so add these cases and check for refusals.
- Never validating the faithfulness judge against human labels. Do this before trusting its numbers.
Exercise
A RAG system scores recall at 5 of 0.95 but only 60% on the faithfulness judge. Which stage should you investigate first, and why?
Show answer
The generator. Retrieval is finding the relevant documents, so the failures come from answers that add claims the context does not support. Inspect the failing cases, look at the judge's reasons, and check whether the prompt lets the model fall back on its own knowledge.