Is your RAG actually working? Measure retrieval and generation separately

Is your RAG actually working? Measure retrieval and generation separately

Part 7 of 7 in the RAG in Production series: engineer-level, on Azure, mapped to Microsoft exam AI-103.

TL;DR for managers. A RAG system can fail in two places: it can fetch the wrong documents, or it can fetch the right ones and still answer badly. Measure the two separately, using a fixed set of real questions with known correct sources. Without that, every change is a guess, and teams spend weeks rewriting prompts when the problem is the search index.

Parts 1 to 6 were about building the funnel. This part is about knowing whether it works, and which stage to fix when it doesn't.

Two failure modes, two kinds of metric

Failure Symptom Measure with Fix in
Retrieval miss Right answer exists in the corpus but isn't in the context Recall@k, MRR, nDCG against labelled sources Chunking, hybrid settings, filters, re-ranker, k
Generation failure Right chunks were in the context, answer still wrong or made up Groundedness, relevance, completeness Prompt, model choice, number and order of chunks

A quick triage I use on any failing answer: look at the context that was sent. If the answer is in there, it's a generation problem. If it isn't, it's retrieval, and the prompt is irrelevant.

Build a golden set

Collect 50 to 200 real questions (from search logs, help-desk tickets, or the people who will use the system) and, for each, the chunk IDs that contain the answer. Include questions with exact codes, paraphrases, negations, and some with no answer in the corpus, so you can check the system says so. This takes a few days of a subject expert's time. It's the most valuable few days in the project.

Retrieval metrics, worked through

One question has two relevant chunks, D2 and D7. The system returns D5, D2, D9, D7, D1.

Metric Question it answers Calculation Value
Recall@3 What share of the relevant chunks made the top 3? Only D2 → 1 of 2 0.50
Recall@5 ...the top 5? D2 and D7 → 2 of 2 1.00
MRR How high is the first relevant chunk? First hit at rank 2 → 1/2 0.50
nDCG@5 How close is the order to ideal? (1/log₂3 + 1/log₂5) ÷ (1/log₂2 + 1/log₂3) = 1.062 ÷ 1.631 0.651

Recall@k at the k you actually send to the model is the number to watch. If you send 5 chunks and recall@5 is 0.6, then 40% of the time the model is answering without the evidence it needs.

import math

def recall_at_k(retrieved, relevant, k):
    return len(set(retrieved[:k]) & relevant) / len(relevant)

def mrr(retrieved, relevant):
    for rank, doc in enumerate(retrieved, start=1):
        if doc in relevant:
            return 1 / rank
    return 0.0

def ndcg_at_k(retrieved, relevant, k):
    dcg = sum(1 / math.log2(i + 1) for i, d in enumerate(retrieved[:k], start=1) if d in relevant)
    ideal = sum(1 / math.log2(i + 1) for i in range(1, min(len(relevant), k) + 1))
    return dcg / ideal

retrieved = ["D5", "D2", "D9", "D7", "D1"]
relevant  = {"D2", "D7"}
print(recall_at_k(retrieved, relevant, 3))       # 0.5
print(recall_at_k(retrieved, relevant, 5))       # 1.0
print(mrr(retrieved, relevant))                  # 0.5
print(round(ndcg_at_k(retrieved, relevant, 5), 3))  # 0.651

Compare configurations, don't guess

With a golden set, comparing vector-only, hybrid and hybrid plus semantic ranking is a short script. Run it whenever you change chunking, embedding model, analysers, weights or k:

CONFIGS = {
    "vector only":       dict(search_text=None, semantic=False),
    "hybrid":            dict(search_text="{q}", semantic=False),
    "hybrid + semantic": dict(search_text="{q}", semantic=True),
}

for name, cfg in CONFIGS.items():
    r5, rr = [], []
    for item in golden_set:                       # [{"question": ..., "relevant": {"chunk-17", ...}}, ...]
        q = item["question"]
        kwargs = dict(search_text=cfg["search_text"].format(q=q) if cfg["search_text"] else None,
                      vector_queries=[VectorizableTextQuery(text=q, k_nearest_neighbors=50,
                                                            fields="content_vector")],
                      top=5, select=["chunk_id"])
        if cfg["semantic"]:
            kwargs.update(query_type="semantic", semantic_configuration_name="default")
        ids = [r["chunk_id"] for r in search.search(**kwargs)]
        r5.append(recall_at_k(ids, item["relevant"], 5))
        rr.append(mrr(ids, item["relevant"]))
    print(f"{name:<18} recall@5 {sum(r5)/len(r5):.3f}   MRR {sum(rr)/len(rr):.3f}")

Microsoft Foundry has a built-in Document Retrieval evaluator for the same job. Give it labelled relevance per document and it reports Fidelity, NDCG, XDCG, max relevance and "holes" (retrieved documents with no label, which tell you your golden set needs more labels).

Generation metrics with Foundry evaluators

For the answer itself, the Azure AI Evaluation SDK has RAG evaluators that use an LLM as judge and return 1 to 5 scores with a default pass threshold of 3:

  • Groundedness: is every claim in the response supported by the context? (precision)
  • Response completeness: does it cover what the ground-truth answer covers? (recall)
  • Relevance: does it answer the question asked?
  • Retrieval: are the retrieved chunks relevant to the query, when you don't have labels?

Groundedness Pro, in preview, uses Azure AI Content Safety and returns a strict pass or fail.

from azure.ai.evaluation import GroundednessEvaluator, RelevanceEvaluator, evaluate

model_config = {
    "azure_endpoint": AOAI_ENDPOINT,
    "azure_deployment": "gpt-4o-mini",      # the judge model deployment
    "api_version": "2024-10-21",
}

# rag_eval.jsonl: one line per test question, produced by running your RAG app
# {"query": "...", "context": "chunk 1\n\nchunk 2 ...", "response": "..."}
result = evaluate(
    data="rag_eval.jsonl",
    evaluators={
        "groundedness": GroundednessEvaluator(model_config),   # is every claim supported by the context?
        "relevance": RelevanceEvaluator(model_config),         # does the response answer the query?
    },
)
print(result["metrics"])

LLM judges are models too. Spot-check a sample of their verdicts by hand, especially early on, and keep the judge model and prompt fixed while you compare configurations.

In production

AI-103 lists "monitor model performance, drift, safety events, and grounding quality" and "monitor data ingestion quality, search index health, and relevance performance" as exam skills, and they are the right list for operations too. In practice:

  • Trace every request: question, the 50 stage-1 candidates, the re-ranked top 5, reranker scores and the answer.
  • Track the share of questions where nothing clears your reranker threshold. A rise usually means new content that hasn't been indexed, or a new kind of question.
  • Re-run the golden set on every change to the index, the embedding model or the prompt, and before every release.
  • Add failed real questions to the golden set every month.

Series recap

  1. Use RAG for knowledge and fine-tuning for behaviour.
  2. Retrieve in a funnel: broad, fuse, re-rank, truncate.
  3. Stage 1 runs ANN and BM25 together because each misses what the other finds.
  4. Stage 2 fuses by rank with RRF (k=60), because the scores aren't comparable.
  5. Stage 3 re-ranks the top 50 with a cross-encoder-style model and gives you a score you can threshold.
  6. At 10 million documents, compression, embedding throughput and filters become design decisions.
  7. Measure retrieval and generation separately, against a golden set.

Learning this for AI-103? Microsoft's AI-103 exam (Azure AI Apps and Agents Developer Associate) asks you to implement RAG, configure semantic, hybrid and vector search for grounding, and monitor relevance and grounding quality. Our live online AI-103 course builds these pipelines hands-on in Microsoft Foundry and Azure AI Search, on UK time, with mock assessments before you book the exam. If testing AI systems is your role, our Generative AI and LLM Evaluation Bootcamp covers RAG evaluation, prompt injection and red teaming in depth.

The RAG in Production series

  1. Part 1: RAG or fine-tuning?
  2. Part 2: The RAG retrieval funnel
  3. Part 3: Stage 1: ANN + BM25 hybrid search
  4. Part 4: Stage 2: Reciprocal Rank Fusion
  5. Part 5: Stage 3: re-ranking with cross-encoders
  6. Part 6: Scaling: 10,000 vs 10 million documents
  7. Part 7: Evaluating RAG: retrieval vs generation (you are here)
Back to blog

Ready to take the first step?

Live online courses on UK time, mapped to the current Microsoft AI exams. No coding needed for AI at work.

Explore AI coursesAsk us a question