Hello! Welcome to the final lesson in our module on Retrieval-Augmented Generation.
Introduction
In the previous lesson, you built a complete, end-to-end RAG pipeline. You successfully orchestrated an ingestion workflow to process and store documents and a query workflow to answer questions using that custom knowledge. As a software engineer, you know that building a system is only half the battle. The other half is ensuring it works well, which means measuring its performance.
This lesson directly addresses that need. We will tackle this module's final learning outcome: to evaluate the performance of a RAG system based on retrieval relevance and answer quality.
Simply "vibe checking" — manually testing a few questions and seeing if the answers look good — isn't a scalable or reliable engineering practice. To systematically improve our RAG system, we need objective metrics. We will explore how to:
- Decompose RAG evaluation into two key parts: retrieval and generation.
- Understand the core metrics for assessing each part.
- Create a synthetic dataset for running evaluations.
- Use an open-source framework, RAGAS, to automate the evaluation process and interpret the results.
This process of measurement and iteration is fundamental to taking a project from a proof-of-concept to a production-ready application.
Why RAG Evaluation is a Two-Part Problem
A RAG system's final output quality depends on two distinct components working together:
- The Retriever: How good is it at finding the right information to answer the query?
- The Generator: Given the retrieved information, how good is the LLM at producing a correct, relevant, and faithful answer?
A failure in either component can ruin the final result. If the retriever fetches irrelevant documents, the generator has no chance. If the retriever finds perfect documents but the generator hallucinates or ignores them, the answer is still wrong. Therefore, we must evaluate them separately.
To get a clear overview of this concept, let's start with a short video.
Key Metrics and Evaluation Methods for RAG
The following clip from the video 'Key Metrics and Evaluation Methods for RAG' by Louis-François Bouchard introduces why RAG evaluation is important and breaks it down into evaluating the retrieval and generation components.
Watch the first two minutes of the video (0:00 - 2:00). Focus on the distinction made between evaluating the retrieval system and the answer generation system.
Core Metrics for RAG Evaluation
Now that we understand the two-part nature of RAG evaluation, let's dive into the core metrics used to measure performance. The open-source community has developed a standard set of metrics, which are encapsulated in frameworks like RAGAS.
We'll focus on four primary metrics that provide a comprehensive view of your system's quality. This article provides excellent, clear explanations with visual aids that are very helpful.
RAG Evaluation Metrics Explained: A Complete Guide with ...
Please read the following sections from the article 'RAG Evaluation Metrics Explained' by Sanjeeb Panda. It breaks down the four most important metrics we'll be using.
Read the sections titled 'The Four Core Metrics', '1. Context Precision', '2. Context Recall', '3. Answer Relevancy', and '4. Faithfulness'. Focus on understanding: For Retrieval Quality: What Context Precision and Context Recall measure and the trade-off between them. For Generation Quality: What Answer Relevancy and Faithfulness measure. Pay special attention to how Faithfulness helps detect hallucinations.
Let's summarize these key metrics:
1. Retrieval Metrics
These assess the quality of the documents fetched by your retriever.
- Context Precision: Of the documents you retrieved, how many were actually relevant? A high score means your retriever isn't fetching a lot of noise.
- Context Recall: Of all the relevant documents that exist in your database, how many did you actually retrieve? A high score means your retriever isn't missing crucial information.
Your software engineering background might recognize these as classic precision and recall metrics, now applied to document retrieval. There's often a trade-off: retrieving more documents (top_k) might increase recall (you're less likely to miss something) but could decrease precision (you're more likely to include irrelevant junk).
2. Generation Metrics
These assess the quality of the final answer produced by the LLM.
- Faithfulness: Does the answer stick to the facts provided in the retrieved context? This is your primary defense against hallucination. A low faithfulness score means the LLM is making things up.
- Answer Relevancy: Is the answer actually relevant to the user's question? An answer can be factually correct and faithful to the context, but still useless if it doesn't address what the user asked.
Test your understanding!
Imagine your RAG system gets the following scores:
- Context Precision: 0.9
- Context Recall: 0.4
- Faithfulness: 1.0
- Answer Relevancy: 0.95
What is the primary problem with your RAG system, and which component is likely at fault?
Show answer
The primary problem is the very low Context Recall (0.4). This means the system is failing to retrieve all the necessary information to form a complete answer.
The component at fault is the retriever.
Even though the other scores are high (the retriever is precise with what it does find, and the generator is faithfully and relevantly answering based on that incomplete information), the final answer is likely to be incomplete or missing key details because the retriever didn't provide them. To fix this, you might consider increasing top_k or using a more advanced retrieval strategy.
Creating an Evaluation Dataset
To calculate these metrics, you need a "ground truth" dataset to test against. For RAG evaluation, this typically consists of:
- A
questionthat a user might ask. - A
ground_truthanswer, which is the ideal, human-written answer to that question.
Manually creating a large, high-quality test set is time-consuming. A powerful and common technique is to use a strong LLM (like GPT-4) to help generate this dataset for you, based on your source documents.
The process is:
- Provide the LLM with a chunk of your source text.
- Ask it to generate a relevant
questionwhose answer is contained within that chunk. - Ask it to then generate the
ground_truthanswer based on the same chunk.
The following video demonstrates this process clearly.
Session 7: RAG Evaluation with RAGAS and How to Improve Retrieval
This clip from the AI Makerspace channel demonstrates a practical, code-based approach to creating a RAG evaluation dataset using an LLM to generate question-answer pairs from your documents.
Watch the section from 17:43 to 21:51. Follow along to understand how a 'test set' of questions and ground truth answers is programmatically generated from the source documents. This forms the basis for our evaluation.
Practical Evaluation with the RAGAS Framework
Now we have the metrics and the data. Let's put it all together using the ragas library. RAGAS (Retrieval-Augmented Generation Assessment) automates the calculation of the metrics we've discussed.
The workflow is:
- For each
questionin your evaluation dataset, run it through your RAG pipeline. - Collect the
generated_answerand theretrieved_contexts. - Combine this with the original
questionandground_truthanswer into adatasets.Datasetobject. - Pass this dataset to the
ragas.evaluate()function.
The video you just watched continues to show exactly how this is done and, more importantly, how to interpret the results to improve your system.
Session 7: RAG Evaluation with RAGAS and How to Improve Retrieval
Let's see how to use the RAGAS library to evaluate our pipeline and how to use the scores to drive improvements. This video walks through the entire process, from getting a baseline score to improving it with better retrieval techniques.
Please watch the following segments: Evaluating a Basic RAG System (21:51 - 24:15): See how the evaluation dataset is used with ragas.evaluate() to get initial scores for context_precision (labeled context relevancy in the video), faithfulness, answer_relevancy, and context_recall. Improving Retrieval & Re-evaluating (24:15 - 31:52): This is the key part. The presenter implements two advanced retrieval strategies (Parent Document Retriever and Ensemble Retriever) and runs the evaluation again. Observe how the metric scores change, demonstrating the iterative improvement loop. This is a perfect example of data-driven development for AI systems.
Here's an example of what the final evaluation call looks like in code, using the ragas library:
from ragas import evaluate
from ragas.metrics import (
faithfulness,
answer_relevancy,
context_recall,
context_precision,
)
from datasets import Dataset
# Assume 'evaluation_data' is a list of dictionaries,
# each containing 'question', 'answer', 'contexts', 'ground_truth'
# 'answer' is from your RAG pipeline, 'contexts' are what it retrieved.
dataset = Dataset.from_list(evaluation_data)
# Run the evaluation
result = evaluate(
dataset=dataset,
metrics=[
context_precision,
context_recall,
faithfulness,
answer_relevancy,
],
)
# The 'result' object will be a dictionary of scores
print(result)
# {'context_precision': 0.85, 'context_recall': 0.9, 'faithfulness': 0.95, 'answer_relevancy': 0.88}
This automated, metric-driven approach allows you to experiment with different chunking strategies, embedding models, top_k values, or prompts, and have concrete numbers to prove whether your changes are making the system better or worse.
Conclusion
You have now learned how to move beyond subjective "vibe checks" and apply a rigorous, engineering-based approach to evaluating your RAG systems. This is a critical skill for any AI engineer building reliable and effective applications.
Key Takeaways:
- RAG evaluation must be split into two parts: assessing the retriever (with metrics like Context Precision and Context Recall) and the generator (with metrics like Faithfulness and Answer Relevancy).
- Faithfulness is a crucial metric for measuring and minimizing hallucinations.
- A high-quality evaluation dataset (containing questions and ground truth answers) is a prerequisite for objective measurement. This can be created efficiently using LLMs.
- Frameworks like RAGAS automate the calculation of these metrics, enabling a rapid, data-driven cycle of experimentation and improvement.
- By analyzing the scores, you can diagnose specific problems in your pipeline—whether it's poor retrieval or unfaithful generation—and target your efforts effectively.
Next Up:
This lesson concludes our deep dive into Retrieval-Augmented Generation. We've learned how to build, orchestrate, and now evaluate these powerful systems.
So far, we've improved our RAG system by enhancing the retrieval component. But what if the generator itself is the bottleneck? In the next module, Fine-Tuning Language Models, we will explore techniques like LoRA to adapt the behavior of the LLM itself, giving you another powerful tool to customize and improve your AI applications.