Sub topic 1
What a RAG system does and where quality can be measured
Prerequisites
Assume you understand chunking, embeddings, vector search, prompting an LLM, and basic precision and recall.
What a RAG system does
Retrieval-augmented generation (RAG) connects a retriever to a language model. The retriever searches a document collection and returns context. The generator uses the question and that context to write an answer.
Quality can fail at either boundary. Measure retrieval by checking whether the right documents appear near the top. Measure generation by checking whether the answer is relevant and supported by the retrieved context.
Retrieval failures versus generation failures
A retrieval failure occurs when the context omits the document needed to answer the question. It can also return irrelevant or poorly ranked documents. A generation failure occurs when the needed evidence is present, but the model ignores it, misreads it, or invents unsupported details.
| Observation | Likely problem |
|---|---|
| No relevant passage is retrieved | Retriever |
| Relevant passage is retrieved, but the answer contradicts it | Generator |
| Answer is correct but lacks required detail because evidence is missing | Retriever or incomplete labels |
Measure both stages separately. Otherwise, one overall answer score cannot explain what to fix.
Building an evaluation set with relevance labels
Create representative questions from real usage, including easy, ambiguous, and difficult cases. For each question, record the documents that are relevant. These relevance labels are the reference standard for retrieval metrics.
Use stable document IDs rather than comparing passage text. If relevance has degrees, store grades such as 0 for irrelevant, 1 for useful, and 2 for essential. Keep an evaluation set separate from data used to tune the retriever.
Precision@k, recall@k, and hit rate
For the first k results:
- Precision@k is the fraction of returned results that are relevant.
- Recall@k is the fraction of all labelled relevant documents that were returned.
- Hit rate is 1 when at least one relevant document appears, and 0 otherwise.
def retrieval_scores(retrieved, relevant, k):
top_k = retrieved[:k]
hits = sum(doc in relevant for doc in top_k)
precision = hits / len(top_k) if top_k else 0.0
recall = hits / len(relevant) if relevant else None
hit = int(hits > 0)
return precision, recall, hit
print(retrieval_scores(["d7", "d2", "d9"], {"d2", "d5"}, 3))
# (0.3333333333333333, 0.5, 1)Exercise
The top three results contain one relevant document, and the question has four relevant documents in total. What are precision@3, recall@3, and hit rate?
Show answer
Precision@3 is 1/3, recall@3 is 1/4, and hit rate is 1.