Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Generative AI & LLM · Chapter 15 / 20

Generative AI & LLM

Evaluating RAG systems

Retrieval-augmented generation (RAG) answers a question from documents that are retrieved at the moment the question is asked: policies, manuals, tickets, product data. It lets a model answer about private and current information without training, and it lets every answer cite its sources.

It also multiplies the places where things go wrong. A correct answer needs the right document to be ingested, split well, retrieved, ranked high enough, used by the model, and cited. A wrong answer can come from any of these steps, and an end-to-end score alone does not say which. This chapter explains how a RAG system works and how to test each stage on its own and the system as a whole.

Prerequisites: Embeddings and similarity, Evaluation methodology and datasets, LLM-as-a-judge.

How a RAG system works

Ingestion      load documents, parse formats, clean, attach metadata (source, date, owner, access)
     ↓
Chunking       split documents into passages small enough to retrieve precisely
     ↓
Indexing       embeddings in a vector index and/or a lexical (BM25) index
     ↓
Retrieval      find candidate chunks for the question: semantic, lexical or both (hybrid)
     ↓
Reranking      reorder the candidates with a stronger, slower model; keep the top few
     ↓
Context        assemble the chosen chunks, with IDs, into the prompt
     ↓
Generation     the model answers from the context and cites chunk IDs
     ↓
Validation     check citations, links, refusals and the output contract in code

The first three steps run offline when documents change; the rest run for every question. Each step has its own parameters (chunk size, number of candidates, reranker, prompt) and its own failure modes, which is why RAG is tested stage by stage.

Where RAG systems fail

StageFailureSymptomTest
IngestionA document is missing, truncated or parsed wrongly (tables, PDFs)Answers miss information that existsDocument counts, parse errors, sample comparisons with the source
ChunkingA fact is split across two chunks, or a chunk loses its headingThe right chunk is retrieved but does not contain the answerInvariants: no lost text, size limits, titles kept
RetrievalThe relevant chunk is not among the candidatesWrong or missing answer despite good documentsRecall@k against labelled relevant chunks
RankingThe relevant chunk is retrieved but ranked too low to be usedAnswers depend on chunk orderMRR and nDCG@k
GenerationThe model ignores, misreads or goes beyond the contextUnsupported claims, wrong numbersFaithfulness of claims, with fixed known-good context
CitationCitations point to chunks that do not support the claimUsers cannot verify the answerCitation checks in code, support checks by a judge
AbstentionThe system answers when the documents do not contain the answerConfident invented answersUnanswerable questions in the dataset
AccessA chunk from another customer or a restricted document is retrievedA data leakTenant and permission filters tested with adversarial queries

Testing ingestion and chunking

Chunking decides what retrieval can find. A chunk that is too large dilutes its embedding and fills the context with noise; a chunk that is too small loses the context that makes it understandable. Whatever the strategy, some properties must hold for every document, and they can be tested directly:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

returns-0   14 words  Unworn items with the tags attached can be returned within...
returns-1   19 words  Start a return at shop.example/returns and print the prepa...
returns-2   20 words  Sale items can be returned on the same terms. Items bought...
refunds-3   17 words  Refunds go to the original payment method within 5 busines...
refunds-4   11 words  Delivery costs are refunded only when the whole order is r...
delivery-5  14 words  Standard delivery takes 3-5 business days and is free for ...
delivery-6  16 words  Express delivery takes 1-2 business days and costs 9 EUR. ...
sentences lost: []
largest chunk: 20 words
shared by neighbours: [('returns-1', 'returns-2', 'Sale items can be returned on the same terms.')]

Invariants to test for every chunker: no text is lost, every chunk respects the size limit (except a single sentence longer than the limit, which must not be dropped), chunks never cross section boundaries, and every chunk carries the metadata it needs: section title, source document, date and access rights. The overlap means that a sentence on the border is available to both neighbours, at the price of some duplication in the index.

Retrieval metrics

Retrieval is evaluated against relevance labels: for each question, the chunks that contain the answer. With them, ranked results become numbers:

hit@k        1 if at least one relevant chunk is in the top k, else 0
recall@k     relevant chunks in the top k / all relevant chunks for the question
precision@k  relevant chunks in the top k / k
MRR          mean over questions of 1 / rank of the first relevant chunk (0 when none is found)
nDCG@k       Σ relevance / log2(rank + 1) over the top k, divided by the same sum for a perfect ranking

The script compares a lexical retriever with the same retriever followed by a reranker, on five labelled questions over the chunks above:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

lexical            hit@3 0.80  recall@3 0.80  precision@3 0.33  MRR 0.37  nDCG@3 0.49
lexical + reranker hit@3 0.80  recall@3 0.80  precision@3 0.33  MRR 0.80  nDCG@3 0.80

The reranker moves relevant chunks to the top: MRR and nDCG rise sharply. Recall does not move, because a reranker can only reorder the candidates it receives. The question about getting cash for a gift is lost before reranking: "cash" never appears in the chunk that says "store credit". Fixing that requires better retrieval: hybrid search that combines embeddings with BM25, query rewriting, or adding context to chunks before indexing. Anthropic reported that contextual retrieval, which prepends a short description of the surrounding document to every chunk, cut failed retrievals by 49%, and by 67% together with reranking.

Read the metrics in this order: recall first (is the answer reachable at all?), then MRR and nDCG (is it near the top?), and precision last (how much noise reaches the context?).

Building retrieval labels

Relevance labels are a dataset like any other (Evaluation methodology and datasets), with their own ways of being built:

  • Questions from real traffic, labelled by a domain expert who searches the documents for every chunk that answers them.
  • Synthetic questions per chunk: a model writes questions that a chunk answers, and a person reviews them. Such questions tend to reuse the chunk's own words, which favours lexical retrieval, so mix them with real questions.
  • Pooling: to avoid labelling every chunk for every question, label the union of the top results of several different retrievers. This is the standard practice of information-retrieval evaluation campaigns.
  • Graded relevance: "answers the question" and "related background" can carry different gains in nDCG.

Relabel when documents change: a chunk ID that no longer exists makes a perfectly good retriever look broken.

Evaluating generation: the RAG triad

Three questions locate a failure between retrieval and generation:

ScoreQuestionLow score points toTypical fix
Context relevanceIs the retrieved context about the question?Retrieval or chunkingChunk size, hybrid search, reranking, query rewriting
GroundednessIs every claim in the answer supported by the context?GenerationStricter instructions, required citations, abstention rules, another model
Answer relevanceDoes the answer address the question?The prompt or the understanding of the questionInstructions, clarifying questions

Evaluate generation in isolation as well: run the generator with known-good context, the labelled relevant chunks, instead of the retrieved ones. If answers fail even then, the generator or the prompt is the problem; if they pass, retrieval is. The same split keeps generation tests stable while the retriever changes.

Faithfulness and citations

Faithfulness is checked claim by claim: split the answer into claims, then decide for each one whether the context supports it. FActScore applies the same idea to long texts with atomic facts. In production systems the support decision is made by a judge validated against human labels (LLM-as-a-judge). The structure of the check is the same with a code-level stand-in:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

supported      cited=['refunds-3']  Your refund goes to the original payment method.
supported      cited=['refunds-3']  It arrives within 5 business days after the return reaches our warehouse.
NOT supported  cited=['refunds-4']  Delivery costs are always refunded.
NOT supported  cited=[]  You will also receive a 10% discount code for your next order.
faithfulness 50% of claims; citations that support their claim 67%

The answer cites a real chunk for its third claim, but the chunk says the opposite ("only when the whole order is returned"); the fourth claim has no source at all. Both failure kinds are common: a citation proves that a chunk was retrieved, not that it supports the claim. Split the checks accordingly: code verifies that every cited ID exists in the retrieved set and that every claim carries a citation; a validated judge decides whether the cited text supports the claim.

Questions without an answer

A RAG system must recognise when the documents do not contain the answer and say so, instead of filling the gap from the model's general knowledge. The dataset therefore needs unanswerable questions, and the results need a table with more than one number:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

correct answer                        70
wrong answer                           8
false abstention                       7
correct abstention                     9
answer to an unanswerable question     6
accuracy on answerable questions      82%
abstains when it should               60%
answers only when sure (precision)    83%

Six of fifteen unanswerable questions received an invented answer, which is the most damaging outcome for a support system. Tightening the abstention rule usually trades it against false abstentions on answerable questions, so track both and decide the balance with the product owner. Note that "the documents do not say" and "the answer is no" are different: a question about delivery to Antarctica is unanswerable only if no policy mentions it.

Robustness tests

Metamorphic tests (LLM-as-a-judge) catch RAG failures that labelled datasets miss:

  • Order of chunks: shuffle the retrieved chunks in the context; the answer must not change. Models use information at the start and the end of a long context better than in the middle, so order effects are real.
  • Distractors: add a relevant-looking but wrong chunk, for example an outdated policy; the answer must follow the current one or point out the conflict.
  • Paraphrased questions: the same question in other words, in another language, with typos; retrieval must find the same chunks.
  • Stale and conflicting documents: two versions of a policy; the system must prefer the newer one by metadata, not by luck.
  • Access control: questions designed to retrieve another customer's tickets or an internal document must return nothing from them. Filters by tenant and permission belong in the retrieval query itself, not in the prompt.

Metric libraries

Ragas, ARES and TruLens provide ready-made RAG metrics such as context precision and recall, faithfulness and answer relevance. Most of them use a model as a judge, so they inherit everything from the previous chapter: they need validation against your labels before their numbers mean anything, and their versions must be pinned. Deterministic retrieval metrics against relevance labels need no model at all; compute them yourself where you can, and use library metrics for the parts that require reading.

Changing a RAG system safely

Every parameter changes behaviour: chunk size, overlap, embedding model, number of candidates, reranker, prompt. Treat changes as experiments:

  • Change one thing at a time and compare against the baseline on the same questions (Statistics for evaluation).
  • Measure retrieval and end-to-end results separately, so that a retrieval gain is not hidden by a generation loss.
  • Version the index together with the chunker, the embedding model and the document snapshot; a new embedding model means re-embedding everything, and queries embedded with the old model must never search the new index.
  • Watch cost and latency: more candidates and a reranker improve quality and cost time on every question.

Case study: the RAG behind this site

The Learning Path Advisor of GimmeJob retrieves from one canonical RAG pipeline that runs in a Cloudflare Worker, and it applies several practices of this chapter:

  • Sections are the retrieval units. Every published ## section of the learning material, including this chapter, becomes its own document with a deep link, so retrieval can point to the narrowest useful passage.
  • A degradation path. Vector search provides semantic candidates; a lexical ranker in the same pipeline takes over when the vector index is unavailable.
  • Deterministic retrieval metrics. The AI service implements precision@k, recall@k, hit rate@k, reciprocal rank and nDCG@k with unit tests (ai-service/src/gimmejob_ai/rag_metrics.py).
  • Runtime quality scores. Traces record scores such as the top retrieval score, the share of grounded items and the validity of cited sources.
  • Links are validated by shape. Consumers check that a cited path is a canonical learning route instead of trusting model output.

Example project

The methods of this chapter are implemented and tested in examples/llm-testing/12-rag-testing: a chunker with property-based invariant tests, a BM25 retriever written out step by step, retrieval metrics against labelled questions, a small RAG pipeline with a fake generator, claim-level faithfulness and citation checks, abstention metrics, and metamorphic tests for chunk order, distractors, paraphrases and tenant isolation. All tests run offline, without a model or API keys:

uv sync --project examples/llm-testing
uv run --project examples/llm-testing pytest examples/llm-testing/12-rag-testing

Common mistakes

  • Only end-to-end scores, which cannot say whether retrieval or generation failed.
  • Improving ranking when recall is the problem: a reranker cannot rank what was never retrieved.
  • Synthetic questions only, which reuse the words of the chunks and flatter lexical retrieval.
  • Trusting citations without checking that the cited text supports the claim.
  • No unanswerable questions in the dataset.
  • Relevance labels that point to chunk IDs from an older index.
  • Access control in the prompt instead of in the retrieval query.
  • Library metrics used without validation against your own labels.

Summary

  • A RAG system is a pipeline: ingestion, chunking, indexing, retrieval, reranking, context, generation and validation; each stage fails in its own way and is tested on its own.
  • Test chunkers with invariants: no lost text, size limits, section boundaries and metadata.
  • Evaluate retrieval with relevance labels: recall@k first, then MRR and nDCG for ranking, precision for noise.
  • Locate failures with the RAG triad and by running generation with known-good context.
  • Check faithfulness claim by claim, verify citations in code, and judge support with a validated judge.
  • Include unanswerable questions and track invented answers and false abstentions separately.
  • Add metamorphic tests for order, distractors, paraphrases, stale documents and access control, and change one parameter at a time.

Source registry

15 chapter references
Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks

Introduces retrieval-augmented generation: a generator conditioned on passages retrieved for each question.

Lewis et al. — arXiv / NeurIPS 2020 · paper
Source ↗
Retrieval-Augmented Generation for Large Language Models: A Survey

Overview of RAG architectures, retrieval and augmentation techniques, and their evaluation.

Gao et al. — arXiv 2023 · paper
Source ↗
Ragas: Automated Evaluation of Retrieval Augmented Generation

Reference-free RAG metrics for faithfulness, answer relevance and context relevance.

Es et al. — arXiv / EACL 2024 demo · paper
Source ↗
Ragas documentation

Library implementations of context precision and recall, faithfulness and answer relevance.

Ragas · tool
Source ↗
ARES: An Automated Evaluation Framework for Retrieval-Augmented Generation Systems

Trained judges for context relevance, faithfulness and answer relevance, calibrated with a small set of human labels.

Saad-Falcon et al. — arXiv / NAACL 2024 · paper
Source ↗
RAG Triad

Context relevance, groundedness and answer relevance as three checks that locate RAG failures.

TruLens · tool
Source ↗
FActScore: Fine-grained Atomic Evaluation of Factual Precision in Long Form Text Generation

Factual precision measured over atomic facts checked against a knowledge source.

Min et al. — arXiv / EMNLP 2023 · paper
Source ↗
Cumulated Gain-Based Evaluation of IR Techniques

Discounted cumulative gain and its normalized form nDCG for graded relevance.

Järvelin and Kekäläinen — ACM Transactions on Information Systems 2002 · paper
Source ↗
Evaluation in information retrieval (Introduction to Information Retrieval, chapter 8)

Relevance judgements, pooling, precision, recall and ranked-retrieval metrics.

Manning, Raghavan and Schütze — Cambridge University Press 2008 · article
Source ↗
The Probabilistic Relevance Framework: BM25 and Beyond

The BM25 ranking function implemented in the example project.

Robertson and Zaragoza — Foundations and Trends in Information Retrieval 2009 · paper
Source ↗
BEIR: A Heterogenous Benchmark for Zero-shot Evaluation of Information Retrieval Models

Retrieval evaluation across domains; BM25 remains a strong baseline for dense retrievers.

Thakur et al. — arXiv / NeurIPS 2021 · paper
Source ↗
Passage Re-ranking with BERT

Reranking first-stage candidates with a cross-encoder.

Nogueira and Cho — arXiv 2019 · paper
Source ↗
Contextual Retrieval

Adding document context to chunks before embedding and BM25 indexing reduced failed retrievals by 49%, and by 67% with reranking.

Anthropic · article
Source ↗
Lost in the Middle: How Language Models Use Long Contexts

Documents position sensitivity in long contexts, the basis for position-sweep tests.

Liu et al. — arXiv / TACL 2024 · paper
Source ↗
On Faithfulness and Factuality in Abstractive Summarization

Defines intrinsic and extrinsic hallucination, used throughout the course for faithfulness checks.

Maynez et al. — arXiv / ACL 2020 · paper
Source ↗