Sub topic 1
What a RAG system does and where quality can be measured
A retrieval-augmented generation (RAG) system answers questions from documents it did not memorize. This chapter maps the pipeline and marks the places where you can measure it. The rest of the tutorial builds on that map.
Prerequisites
This chapter assumes you already have:
- A working idea of the RAG pipeline: chunking, embedding, vector search, and prompting an LLM with retrieved text.
- Comfort reading Python. The examples use only the standard library.
- Familiarity with precision and recall from classification.
- Basic probability and averages.
You do not need any evaluation experience. Later chapters define each metric in full.
What a RAG system does
A language model on its own answers from its training data. That data is frozen and may not include your private or recent documents. RAG fixes this by looking up relevant passages at question time and placing them in the prompt. The model is then asked to answer from those passages.
The pipeline has two phases.
- Indexing (offline). Documents are split into chunks. Each chunk is embedded as a vector and stored in an index.
- Answering (online). The question is embedded. The retriever finds the nearest chunks. The system assembles a prompt from the question and those chunks. The generator (the LLM) writes an answer, often with citations.
Evaluation focuses on the online phase. Indexing choices such as chunk size and embedding model matter a great deal, but you judge them by how they change online results.
The two components you evaluate
The retriever and the generator are different kinds of components with different failure behavior.
- The retriever takes a question and returns a ranked list of chunks. Its output is a list of identifiers with scores. You can check it against a set of chunks a human marked as relevant. This is classic information retrieval, and the metrics are well established.
- The generator takes a prompt and returns free text. There is no single correct string. You judge it on properties: is it supported by the context, does it address the question, is it correct.
Because the generator only sees what the retriever hands it, retrieval quality limits answer quality. Good retrieval does not guarantee a good answer, since the model can still ignore or distort the context. The next chapter covers that split in detail. Here the goal is to see where each measurement attaches.
Measurement points in the pipeline
Each dashed line is a place where you can attach a score.
| Point | What you inspect | Typical question | Needs labels? |
|---|---|---|---|
| Ranked chunks | Chunk ids and scores | Did the right chunks come back, and how high? | Yes, relevance labels per question |
| Prompt context | The text the model actually saw | Is the context on topic for the question? | No, a judge can score it |
| Answer vs. context | Claims in the answer | Does the context support each claim? | No |
| Answer vs. question | The answer text | Does it respond to what was asked? | No |
| Answer vs. reference | The answer and a gold answer | Is it factually right? | Yes, a reference answer |
| Citations | Cited ids and claims | Does each cited passage support its claim? | No, but a judge helps |
The "Needs labels?" column drives cost. Metrics with labels are cheap to run and precise, but someone has to write the labels. Reference-free metrics need no labels, but they depend on a judge model whose own accuracy you must check. Both approaches appear later in this tutorial.
Three questions that cover most of the ground
A common way to organize reference-free evaluation is to check three relationships between the question, the context, and the answer.
- Context relevance: is the retrieved context relevant to the question?
- Faithfulness (also called groundedness): is the answer supported by the context?
- Answer relevance: does the answer address the question?
Each relationship can fail on its own. An answer can be faithful to the context and still miss the question. An answer can be relevant and wrong because the context was wrong. Treat the three as separate scores, not one number.
Faithfulness is not correctness. Faithfulness asks whether the answer follows from the retrieved text. Correctness asks whether it is true. If the corpus holds an outdated policy, an answer that repeats it is faithful and incorrect. Keeping the two apart prevents you from blaming the generator for what is really a data problem.
Capturing a trace so you can measure later
You can only score what you recorded. Log, for every request, the question, the exact chunks retrieved with their scores, the final prompt, and the answer. Without the retrieved chunks, you cannot tell a retrieval failure from a generation failure after the fact.
This example wraps a pipeline in a function that returns a trace. The retriever and generator are passed in, so you can swap in real ones. The toy versions here only demonstrate the shape.
import re
from dataclasses import dataclass, field
@dataclass
class RagTrace:
question: str
retrieved: list # list of dicts: {"id", "text", "score"}
prompt: str
answer: str
meta: dict = field(default_factory=dict)
def run_rag(question, retriever, generator, k=2):
retrieved = retriever(question, k)
context = "\n\n".join(f"[{d['id']}] {d['text']}" for d in retrieved)
prompt = (
"Answer using only the context below. "
"Cite chunk ids in square brackets.\n\n"
f"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
)
answer = generator(prompt)
return RagTrace(question, retrieved, prompt, answer, {"k": k})
DOCS = {
"d1": "The warranty lasts 24 months and covers manufacturing defects.",
"d2": "Shipping takes three to five business days.",
"d3": "Returns are accepted within 30 days of delivery.",
}
def words(text):
return set(re.findall(r"[a-z0-9]+", text.lower()))
def toy_retriever(question, k):
q = words(question)
scored = [
{"id": i, "text": t, "score": len(q & words(t))}
for i, t in DOCS.items()
]
scored.sort(key=lambda d: -d["score"]) # stable sort keeps ties in order
return scored[:k]
def toy_generator(prompt):
return "The warranty lasts 24 months. [d1]"
trace = run_rag("How long does the warranty last?", toy_retriever, toy_generator)
print([d["id"] for d in trace.retrieved]) # ['d1', 'd2']
print(trace.answer)With this trace you can compute retrieval metrics from trace.retrieved, faithfulness from trace.answer and the context text, and answer relevance from trace.question and trace.answer. Store traces as structured records (for example, one JSON object per line), not as log text you have to parse later.
Edge cases that shape what you measure
- Empty or low-score retrieval. If the retriever returns nothing useful, the right behavior is often to say "I don't know." A system that answers anyway is making things up. Plan to evaluate refusals as their own category, because a refusal on an answerable question is also a failure.
- Truncated context. If the prompt is cut to fit the model's window, a chunk the retriever found may never reach the generator. Measure retrieval on what was retrieved and context relevance on what was actually in the prompt. The two can differ.
- Multi-step questions. Some questions need several chunks combined. One relevant chunk is not enough, which is why recall matters alongside precision.
- Non-determinism. The same question can give different answers across runs. Treat one run as one sample, and keep this in mind when comparing systems.
- Questions with no answer in the corpus. These are valuable test cases. They check that the system refuses instead of inventing.
How the rest of the tutorial fits this map
The tutorial follows the pipeline from left to right. First you separate retrieval failures from generation failures, then build an evaluation set with relevance labels. After that come set-based and rank-aware retrieval metrics. The second half moves to the generator: faithfulness, answer relevance, claim-level scoring, LLM judges and how to validate them, and citation accuracy. The final chapters cover diagnosing which component is at fault, reporting results with confidence intervals, and using them in regression tests and monitoring.
Exercise
A RAG system answers "What is the refund window?" with "Refunds are accepted within 60 days." The retrieved chunk says "Refunds are accepted within 60 days of delivery," but the company's current policy is 30 days, and the corpus was never updated. Which of faithfulness and correctness is high, which is low, and which component do you fix?
Show answer
Faithfulness is high because the answer follows from the retrieved context. Correctness is low because the answer does not match the current policy. The fault lies in the corpus (stale data), not in the generator or the retriever's ranking. Fix the source document and re-index.
Exercise
You log only the final question and answer for each request. Name two evaluation tasks from this chapter that you can no longer do, and say what you would need to log to enable them.
Show answer
You cannot compute retrieval metrics such as precision@k or recall@k, and you cannot score faithfulness or context relevance, because both need the retrieved chunks. You would need to log the retrieved chunk ids, their text, and their scores, and ideally the final prompt as sent to the model.
Exercise
A retriever returns three chunks, but the prompt builder truncates the context after the first chunk to fit the model's token limit. Which score should reflect the truncation, retrieval metrics or context relevance, and why?
Show answer
Context relevance should reflect it, because it is measured on the text the model actually saw. Retrieval metrics are computed on the retrieved list, which still contains all three chunks. The gap between the two scores is a sign that context assembly is losing information.