RAG Pipeline Evaluation: Retrieval & Generation Scores
In this article
Evaluating a Retrieval-Augmented Generation (RAG) pipeline with separate retrieval and generation scores gives you a clear picture of where failures occur. Instead of a single overall score, you measure how well the retriever finds relevant documents and how well the generator produces accurate answers from those documents. This separation lets you debug and improve each component independently. Before you start, you need a test set of questions with ground-truth answers and, ideally, a list of relevant documents for each question.
What You'll Need
- A test dataset: at least 20–50 question-answer pairs, with the correct answer text for each question.
- For each question, a list of relevant document IDs or passages (the "ground truth" for retrieval).
- A running RAG pipeline that lets you access the retrieved documents and the final generation separately.
- Python environment with libraries like
pandas,numpy, and optionallyscikit-learnorragasfor metrics. - An LLM API or local model for generation scoring (if using LLM-based metrics).
Step-by-Step
- Prepare your test set. Create a CSV or JSON file with columns:
question,ground_truth_answer, andrelevant_doc_ids. Therelevant_doc_idsshould be a list of document identifiers that contain the information needed to answer the question. If you don't have this, you can manually label a sample. - Run the retrieval step. For each question in your test set, call your retriever (e.g., vector search, BM25) and get the top-k documents (e.g., k=5). Record the retrieved document IDs and their scores (if any). Save these results to a file.
- Compute retrieval metrics. Using the retrieved IDs and the ground-truth relevant IDs, calculate standard retrieval metrics:
- Recall@k: the fraction of relevant documents that appear in the top-k results.
- Precision@k: the fraction of retrieved documents that are relevant.
- Mean Reciprocal Rank (MRR): the average of 1/rank of the first relevant document.
- Normalized Discounted Cumulative Gain (nDCG): accounts for the position of relevant documents.
ranxorpytrec_eval. Average these scores across all questions to get your retrieval score. - Run the generation step. For each question, take the retrieved documents (top-k) and pass them along with the question to your generator (LLM). Record the generated answer text.
- Compute generation metrics. Compare each generated answer to the ground-truth answer using one or more of these metrics:
- Exact Match (EM): binary score if the generated answer exactly matches the ground truth (after normalization).
- F1 score: token-level overlap between generated and ground-truth answers.
- ROUGE-L: measures longest common subsequence, good for longer answers.
- LLM-as-a-judge: use an LLM to rate the answer on a scale (e.g., 1-5) for correctness, faithfulness, or helpfulness. This is more flexible but requires careful prompt design.
- Analyze the combined results. Create a table with each question, retrieval score (e.g., recall@k), and generation score. Look for patterns: if retrieval is low but generation is high, the generator might be hallucinating or ignoring context. If retrieval is high but generation is low, the generator may be failing to use the context effectively.
- Iterate and improve. Based on the scores, focus on the weaker component. For retrieval, try different chunk sizes, embedding models, or hybrid search. For generation, try different prompts, temperature settings, or fine-tuning.
Common Mistakes
- Using only one metric. Relying solely on recall or F1 can miss important issues. Use a combination of retrieval and generation metrics.
- Ignoring the ground truth for retrieval. If you don't have relevant document IDs, you can't accurately measure retrieval quality. Spend time building a good test set.
- Not normalizing answers. For EM and F1, lowercasing and removing punctuation can drastically change scores. Be consistent.
- Using the same test set for tuning and evaluation. You should have a separate validation set to avoid overfitting to the test set.
- Forgetting to check the retrieval context. Sometimes the retriever returns irrelevant documents, but the generator still produces a plausible answer. That's a red flag for hallucination.
Tips
- Start small. Test with 20-30 questions to get a quick sense of performance before scaling up.
- Visualize results. Plot retrieval scores vs. generation scores to see if there's a correlation.
- Use a consistent k. Decide on a fixed top-k (e.g., 5) for both retrieval and generation to make comparisons fair.
- Document your prompts. For LLM-as-a-judge, write a clear rubric and test it on a few examples to ensure consistency.
- Consider using a framework. Libraries like
ragasprovide built-in metrics for RAG evaluation, but understand the underlying formulas.
Troubleshooting
- Retrieval scores are all zero. Check that your ground-truth document IDs match the IDs used by your retriever. Also verify that your retriever is returning results at all.
- Generation scores are very low even with good retrieval. The generator might be truncating answers or not following instructions. Try a different prompt or a more capable model.
- LLM-as-a-judge gives inconsistent scores. Refine your prompt to be more specific. Provide examples of good and bad answers. Also, consider using a higher temperature for the judge to get more varied feedback, or lower it for consistency.
- Metrics take too long to compute. If you're using LLM-as-a-judge, you can sample a subset of questions or use a cheaper/faster model for the judge.
- Retrieval is slow. If you're using a vector database, consider adding an index or using a faster approximate nearest neighbor search.
Frequently Asked Questions
What is the best retrieval metric for RAG?
Recall@k is often the most important because it tells you if the retriever found the needed information. However, nDCG is better when the order of retrieved documents matters, as it gives higher weight to relevant documents that appear earlier.
Should I use exact match or F1 for generation?
Exact match is too strict for most real-world answers. F1 score is more forgiving and correlates better with human judgment. For longer, open-ended answers, ROUGE-L is a good choice.
Can I evaluate generation without ground-truth answers?
Yes, you can use reference-free metrics like faithfulness (checking if the answer is supported by the retrieved context) or answer relevance (using an LLM to judge relevance). These are useful when you don't have human-written answers.
How many test questions do I need?
For a rough estimate, 20-30 questions can give you a ballpark. For reliable conclusions, aim for at least 100 questions, especially if you want to compare different configurations statistically.
What if my retriever returns different documents each time?
This can happen with non-deterministic retrieval (e.g., due to sampling in embeddings). To get stable scores, set a fixed random seed and run retrieval multiple times, averaging the scores.
Is it okay to use the same test set for both retrieval and generation evaluation?
Yes, it's standard. But make sure you have a separate validation set for tuning hyperparameters, and a held-out test set for final evaluation to avoid leakage.