Code examples:

RAG Retrieval Evaluation — Finding Out Whether Retrieval or the Model Is to Blame

December 1, 2026 14 min read By Jaffar Kazi
Real-World AI Engineering RAG Evaluation
C# Python Azure

What You'll Learn

  • Why a wrong RAG answer can come from retrieval or from generation, and why only one of them can be measured cheaply
  • How to build a golden set whose labels survive a change of chunking strategy
  • How Recall@K, Precision@K, MRR and nDCG each answer a different question
  • How to compare configurations on quality and context cost together, and save the winner
  • How to separate retrieval errors from generation errors, and test the whole thing without a model

The Problem

A RAG assistant tells an employee that unused leave never expires. The policy says it expires on 31 March. The first instinct is to blame the model and rewrite the prompt. But the answer has two possible origins, and they need opposite fixes. Either the retriever never delivered the passage about expiry, in which case no prompt can recover it, or the passage was sitting in the context and the model ignored it, in which case better retrieval changes nothing.

Judging only the final answer hides this. A wrong answer is a symptom, and tuning against symptoms produces changes that feel productive and measure nothing. Retrieval is the better place to start because it is the one half of the pipeline that can be scored without a model at all. Given a question and the passage that answers it, either the passage came back in the top results or it didn't, and that check is deterministic, fast and free.

The previous articles in this series built chunking, vector search and citation checking. Each has settings: chunk size, overlap, how many chunks to retrieve. Without a measurement, those settings are guesses. With one, they become a comparison.

The Shape of a Real Solution

Offline retrieval evaluation is a small, repeatable experiment with five parts:

  • A golden set: real questions, each paired with the evidence that answers it.
  • A runner that executes retrieval for every question under each configuration.
  • Rank metrics that turn each result list into numbers: Recall@K, Precision@K, MRR and nDCG.
  • A cost meter that records how much context each configuration puts in front of the model.
  • A report and a selection rule that choose a winner and save it with its price.

The metric is not the hard part. The hard parts are labelling so the golden set outlives a chunking change, and choosing a winner when quality and cost pull in opposite directions.

Architecture Overview

Architecture diagram showing a golden set of questions with gold evidence snippets and a set of configurations feeding a runner that retrieves top-K chunks per question. A relevance judge checks whether each chunk contains the gold snippet, feeding rank metrics (Recall@K, Precision@K, MRR, nDCG@K). A cost meter records context tokens per query. Both flow into a benchmark report, a selection rule that picks the cheapest configuration meeting a recall floor, and a saved best configuration. The report also feeds an evaluation harness, and a failure triage step combines recall with answer correctness from a separate generation run.
  • No LLM sits in the evaluation loop. Embedding the questions is the only model usage, so a full run costs almost nothing and can run on every change.
  • Cost is measured next to quality, from the same retrieval results, so the two can never drift apart.
  • The report is a plain artefact. One row per configuration, saved as data, so a later evaluation harness can consume it unchanged.
  • Triage is a separate step that only needs answer-correctness labels from a generation run, which keeps the cheap measurement independent of the expensive one.

Core Implementation: The Golden Set and Relevance

A golden set is a list of questions, each with the evidence that answers it. The obvious labelling approach is to record the IDs of the relevant chunks, and it breaks the first time the chunking changes. Chunk hr-p2-c1 under 200-token chunks covers different text than hr-p2-c1 under 400-token chunks, so every label silently turns wrong, and the comparison the whole exercise exists for becomes impossible.

The fix is to label the evidence itself. Each question carries one or more short evidence snippets copied from the source document, and a retrieved chunk counts as relevant if it contains a snippet after whitespace and case are normalised. Labels now describe the documents, not the index, so the same golden set scores every chunking strategy fairly. Questions that need two facts get two snippets, which is what lets recall mean "how much of the needed evidence arrived" rather than a yes or no.

Two cautions apply. Snippets should be short and distinctive, because a snippet that straddles a chunk boundary is found by neither chunk. And the set should be drawn from questions people actually ask, including the awkward ones, since a golden set of easy questions rewards every configuration equally. A few dozen well-chosen questions beat several hundred generated ones, because every label can be reviewed by a person.

Models.cs / eval_models.py

using System.Text.RegularExpressions;

public record Chunk(string Id, string Source, int Page, string Text);

// Labels point at evidence text, not chunk IDs, so one golden set works across every chunking strategy.
public record GoldItem(string Question, IReadOnlyList<string> EvidenceSnippets);

public interface IRetriever
{
    Task<IReadOnlyList<Chunk>> RetrieveAsync(string question, int k, CancellationToken ct = default);
}

public record Config(string Name, int K, IRetriever Retriever);

public static class Relevance
{
    static string Norm(string s) => Regex.Replace(s.ToLowerInvariant(), @"\s+", " ").Trim();

    public static bool Contains(Chunk chunk, string snippet) => Norm(chunk.Text).Contains(Norm(snippet));

    public static bool IsRelevant(Chunk chunk, GoldItem gold) =>
        gold.EvidenceSnippets.Any(s => Contains(chunk, s));

    // Rough estimate (about 1.3 tokens per word). Use the model's tokenizer for billing-grade numbers.
    public static int EstimateTokens(string text) =>
        (int)Math.Ceiling(text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length * 1.3);
}

import re
from dataclasses import dataclass
from math import ceil
from typing import Protocol


@dataclass(frozen=True)
class Chunk:
    id: str
    source: str
    page: int
    text: str


@dataclass(frozen=True)
class GoldItem:
    # Labels point at evidence text, not chunk IDs, so one golden set works across every chunking strategy.
    question: str
    evidence_snippets: list[str]


class Retriever(Protocol):
    def retrieve(self, question: str, k: int) -> list[Chunk]: ...


@dataclass(frozen=True)
class Config:
    name: str
    k: int
    retriever: Retriever


def _norm(s: str) -> str:
    return re.sub(r"\s+", " ", s.lower()).strip()


def contains(chunk: Chunk, snippet: str) -> bool:
    return _norm(snippet) in _norm(chunk.text)


def is_relevant(chunk: Chunk, gold: GoldItem) -> bool:
    return any(contains(chunk, s) for s in gold.evidence_snippets)


def estimate_tokens(text: str) -> int:
    # Rough estimate (about 1.3 tokens per word). Use the model's tokenizer for billing-grade numbers.
    return ceil(len(text.split()) * 1.3)

Core Implementation: The Rank Metrics

Each metric answers a different question about the same ranked list, which is why reporting only one of them misleads.

  • Recall@K asks how much of the required evidence appeared in the top K. This is the ceiling for the whole system: evidence that isn't retrieved can't be used.
  • Precision@K asks how much of the top K was useful. Low precision means the model reads mostly noise and the prompt is paying for it.
  • MRR (mean reciprocal rank) averages 1 divided by the position of the first relevant chunk. It captures how quickly the right evidence appears, which matters when only the top few chunks are used.
  • nDCG@K rewards relevant chunks for ranking high and discounts them logarithmically as they sink. It is the most complete single number and the least intuitive.

A worked example shows how they diverge. A question needs two snippets, and retrieval returns five chunks: noise, evidence one, noise, evidence two, noise. At K=3 only one snippet has arrived, so Recall@3 is 0.5, Precision@3 is 0.33 and the reciprocal rank is 0.5. At K=5 both have arrived, so Recall@5 is 1.0, Precision@5 is 0.4 and nDCG@5 is 0.65, because both relevant chunks still sit below the first position. Doubling the recall required two more chunks of context, and that is the trade-off the rest of this article manages.

Precision divides by K rather than by the number of results returned, so a retriever that returns fewer chunks than requested is not rewarded for it. Token counts here use a rough words-times-1.3 estimate; for billing-grade numbers, use the model's own tokenizer.

Metrics.cs / eval_metrics.py

public record QueryScore(double Recall, double Precision, double Rr, double Ndcg, int ContextTokens);

public static class Metrics
{
    static double Gain(int rank) => 1.0 / Math.Log2(rank + 1);   // rank is 1-based

    public static QueryScore Score(GoldItem gold, IReadOnlyList<Chunk> hits, int k)
    {
        if (gold.EvidenceSnippets.Count == 0)
            throw new ArgumentException("A gold item needs at least one evidence snippet.");

        var top = hits.Take(k).ToList();
        var rel = top.Select(c => Relevance.IsRelevant(c, gold)).ToList();

        // Recall@K: how much of the required evidence made it into the top K.
        var covered = gold.EvidenceSnippets.Count(s => top.Any(c => Relevance.Contains(c, s)));
        var recall = (double)covered / gold.EvidenceSnippets.Count;

        // Precision@K: how much of the top K was useful. Divide by K so a short list is not rewarded.
        var precision = (double)rel.Count(r => r) / k;

        // Reciprocal rank: 1 / position of the first relevant chunk (0 if none).
        var first = rel.FindIndex(r => r);
        var rr = first < 0 ? 0 : 1.0 / (first + 1);

        // nDCG@K with binary relevance: relevant chunks count more the higher they rank.
        var dcg = rel.Select((r, i) => r ? Gain(i + 1) : 0).Sum();
        var ideal = Enumerable.Range(1, Math.Min(gold.EvidenceSnippets.Count, k)).Sum(Gain);
        var ndcg = ideal == 0 ? 0 : dcg / ideal;

        var tokens = top.Sum(c => Relevance.EstimateTokens(c.Text));
        return new QueryScore(recall, precision, rr, ndcg, tokens);
    }
}

from dataclasses import dataclass
from math import log2


@dataclass(frozen=True)
class QueryScore:
    recall: float
    precision: float
    rr: float
    ndcg: float
    context_tokens: int


def _gain(rank: int) -> float:  # rank is 1-based
    return 1.0 / log2(rank + 1)


def score(gold: GoldItem, hits: list[Chunk], k: int) -> QueryScore:
    if not gold.evidence_snippets:
        raise ValueError("A gold item needs at least one evidence snippet.")

    top = hits[:k]
    rel = [is_relevant(c, gold) for c in top]

    # Recall@K: how much of the required evidence made it into the top K.
    covered = sum(any(contains(c, s) for c in top) for s in gold.evidence_snippets)
    recall = covered / len(gold.evidence_snippets)

    # Precision@K: how much of the top K was useful. Divide by K so a short list is not rewarded.
    precision = sum(rel) / k

    # Reciprocal rank: 1 / position of the first relevant chunk (0 if none).
    rr = next((1.0 / (i + 1) for i, r in enumerate(rel) if r), 0.0)

    # nDCG@K with binary relevance: relevant chunks count more the higher they rank.
    dcg = sum(_gain(i + 1) for i, r in enumerate(rel) if r)
    ideal = sum(_gain(i) for i in range(1, min(len(gold.evidence_snippets), k) + 1))
    ndcg = dcg / ideal if ideal else 0.0

    return QueryScore(recall, precision, rr, ndcg, sum(estimate_tokens(c.text) for c in top))

Key Technical Challenge: Comparing Configurations Honestly

Running one configuration produces numbers. Running several produces a decision problem, because the configuration with the best recall is rarely the cheapest. Retrieving more chunks, or larger chunks, raises the chance the evidence is present and also raises the tokens sent on every request. A report that sorts by recall will always recommend the most expensive option.

Making the cost a column in the same report turns the argument into a rule. A workable one has two steps: set a recall floor that reflects how often missing evidence is acceptable, then pick the configuration with the smallest context among those that clear it, breaking ties on nDCG. The floor is a product decision, not a technical one, and writing it down is the point. The saved output is the winning row plus the exact settings that produced it, so the choice can be reproduced and defended later.

The same discipline applies to what is varied. Change one setting per comparison where possible, such as chunk size with K fixed, so a difference in the table has one explanation. And keep the golden set fixed across runs. A metric that moves because the questions changed isn't measuring the retriever.

Evaluator.cs / eval_runner.py

public record ConfigReport(
    string Name, int K, double Recall, double Precision, double Mrr, double Ndcg,
    double AvgContextTokens, int ZeroRecallQueries, IReadOnlyList<string> MissedQuestions);

public class Evaluator
{
    public async Task<ConfigReport> RunAsync(Config cfg, IReadOnlyList<GoldItem> gold, CancellationToken ct = default)
    {
        var scores = new List<(GoldItem Gold, QueryScore Score)>();
        foreach (var g in gold)
        {
            var hits = await cfg.Retriever.RetrieveAsync(g.Question, cfg.K, ct);
            scores.Add((g, Metrics.Score(g, hits, cfg.K)));
        }

        var missed = scores.Where(s => s.Score.Recall == 0).Select(s => s.Gold.Question).ToList();
        return new ConfigReport(
            cfg.Name, cfg.K,
            scores.Average(s => s.Score.Recall),
            scores.Average(s => s.Score.Precision),
            scores.Average(s => s.Score.Rr),
            scores.Average(s => s.Score.Ndcg),
            scores.Average(s => s.Score.ContextTokens),
            missed.Count, missed);
    }

    // Selection rule: clear the recall floor first, then take the cheapest context; ties go to better ranking.
    public static ConfigReport? Select(IEnumerable<ConfigReport> reports, double recallFloor) =>
        reports.Where(r => r.Recall >= recallFloor)
               .OrderBy(r => r.AvgContextTokens)
               .ThenByDescending(r => r.Ndcg)
               .FirstOrDefault();

    // Context cost per 1,000 queries. Input tokens = retrieved context + a fixed prompt overhead.
    public static double CostPer1000Queries(ConfigReport r, double promptOverheadTokens, double pricePerMillionInput) =>
        (r.AvgContextTokens + promptOverheadTokens) * pricePerMillionInput / 1_000_000 * 1000;
}

from dataclasses import dataclass


@dataclass(frozen=True)
class ConfigReport:
    name: str
    k: int
    recall: float
    precision: float
    mrr: float
    ndcg: float
    avg_context_tokens: float
    zero_recall_queries: int
    missed_questions: list[str]


def _mean(values) -> float:
    values = list(values)
    return sum(values) / len(values)


def run_config(cfg: Config, gold: list[GoldItem]) -> ConfigReport:
    scored = []
    for g in gold:
        hits = cfg.retriever.retrieve(g.question, cfg.k)
        scored.append((g, score(g, hits, cfg.k)))

    missed = [g.question for g, s in scored if s.recall == 0]
    return ConfigReport(
        cfg.name, cfg.k,
        _mean(s.recall for _, s in scored),
        _mean(s.precision for _, s in scored),
        _mean(s.rr for _, s in scored),
        _mean(s.ndcg for _, s in scored),
        _mean(s.context_tokens for _, s in scored),
        len(missed), missed,
    )


def select(reports: list[ConfigReport], recall_floor: float) -> ConfigReport | None:
    # Selection rule: clear the recall floor first, then take the cheapest context; ties go to better ranking.
    eligible = [r for r in reports if r.recall >= recall_floor]
    return min(eligible, key=lambda r: (r.avg_context_tokens, -r.ndcg), default=None)


def cost_per_1000_queries(r: ConfigReport, prompt_overhead_tokens: float, price_per_million_input: float) -> float:
    # Input tokens = retrieved context + a fixed prompt overhead.
    return (r.avg_context_tokens + prompt_overhead_tokens) * price_per_million_input / 1_000_000 * 1000

Key Technical Challenge: Separating Retrieval Errors from Generation Errors

The retrieval metrics say whether the evidence arrived. They say nothing about whether the answer was right. Joining the two is what answers the original question of whom to blame. Run the questions through the full pipeline, label each answer correct or not, and combine that with the per-question recall.

Evidence complete?Answer correct?DiagnosisWhere to work
YesYesHealthyNothing to fix
YesNoGeneration errorPrompt, model choice, citation checks
NoNoRetrieval missChunking, embeddings, K, hybrid search
NoYesUngrounded correctTreat as a risk: the model answered from memory

The fourth row is the one teams skip. A correct answer without its evidence isn't a success, because it was right by luck or by training data, and it will be wrong the first time the document and the model's memory disagree. Counting these separately keeps a good-looking accuracy figure from hiding an ungrounded system.

Recall is the right gate here, not precision. Missing evidence makes a correct grounded answer impossible, while extra noise only makes it harder.

Triage.cs / eval_triage.py

public enum Failure { Ok, RetrievalMiss, GenerationError, UngroundedCorrect }

public static class Triage
{
    // recall comes from the retrieval run; answerCorrect comes from a separate, labelled generation run.
    public static Failure Classify(double recall, bool answerCorrect) => (recall >= 1.0, answerCorrect) switch
    {
        (true, true)   => Failure.Ok,                 // evidence arrived and the answer is right
        (true, false)  => Failure.GenerationError,    // evidence arrived, the model still got it wrong
        (false, false) => Failure.RetrievalMiss,      // evidence missing: fix retrieval, not the prompt
        (false, true)  => Failure.UngroundedCorrect,  // right answer without the evidence: memory or luck
    };

    public static Dictionary<Failure, int> Summarise(IEnumerable<(double Recall, bool Correct)> results) =>
        results.GroupBy(r => Classify(r.Recall, r.Correct)).ToDictionary(g => g.Key, g => g.Count());
}

from collections import Counter
from enum import Enum


class Failure(Enum):
    OK = "ok"
    RETRIEVAL_MISS = "retrieval_miss"
    GENERATION_ERROR = "generation_error"
    UNGROUNDED_CORRECT = "ungrounded_correct"


def classify(recall: float, answer_correct: bool) -> Failure:
    # recall comes from the retrieval run; answer_correct comes from a separate, labelled generation run.
    evidence_complete = recall >= 1.0
    if evidence_complete and answer_correct:
        return Failure.OK                  # evidence arrived and the answer is right
    if evidence_complete:
        return Failure.GENERATION_ERROR    # evidence arrived, the model still got it wrong
    if not answer_correct:
        return Failure.RETRIEVAL_MISS      # evidence missing: fix retrieval, not the prompt
    return Failure.UNGROUNDED_CORRECT      # right answer without the evidence: memory or luck


def summarise(results: list[tuple[float, bool]]) -> Counter:
    return Counter(classify(recall, correct) for recall, correct in results)

What This Costs

Evaluation itself is nearly free: no generation calls, and a short embedding call per question. The cost that matters is the one the evaluation exposes, which is the context sent on every production query. Context is input tokens, so the arithmetic is simple. At the time of writing, OpenAI's published list prices per million input tokens were roughly $0.10 for the GPT-6 Luna tier, $1.00 for GPT-6.1 Terra and $2.00 for GPT-6.2 Sol. Third-party price trackers disagreed on some tiers, so treat these as indicative.

The table compares three illustrative configurations. The recall and token figures are assumptions chosen to show the trade-off, not measurements. Configuration A uses 200-token chunks with K=3, B uses 400-token chunks with K=5, and C uses 200-token chunks with K=5. Input per query is the retrieved context plus about 150 tokens of instructions and question.

ConfigurationRecall@KInput tokens per queryGPT-6 Luna, per 1,000 queriesGPT-6.1 Terra, per 1,000 queriesGPT-6.2 Sol, per 1,000 queries
A: 200-token chunks, K=30.70750about $0.08about $0.75about $1.50
B: 400-token chunks, K=50.882,150about $0.22about $2.15about $4.30
C: 200-token chunks, K=50.831,150about $0.12about $1.15about $2.30

Cost Reality

Configuration B retrieves the most evidence and costs almost three times as much per query as A. With a recall floor of 0.80, C wins: it clears the floor at roughly half of B's input cost. Under these assumptions, B's extra five points of recall cost about twice as much context, and whether that is worth it is the product decision the floor encodes. Retrieval that grows the context also grows latency and the room for the model to be distracted, which no per-token price captures.

These are OpenAI direct list prices and they change, so check current pricing. Azure OpenAI is priced separately and varies by deployment tier: Global Standard, Data Zone and regional deployments, Batch (discounted, with a 24-hour turnaround) and Provisioned throughput (reserved capacity). Each tier suits a different purpose, such as interactive traffic, bulk offline jobs or steady high-volume workloads. Azure rates could not be retrieved at the time of writing, so none are quoted here, and the figures in this article may be slightly out of date for Azure deployments.

Observability

Treat each evaluation run as a record worth keeping. Save the configuration settings, the golden-set version, the metrics, the average context tokens and the list of questions with zero recall. Zero-recall questions are the most valuable output, because each one is a concrete retrieval failure that can be inspected and fixed.

In production, log the retrieved chunk IDs and similarity scores per request, and track the same context-size figure the benchmark used. If live context size drifts from the benchmarked number, the benchmark no longer describes the system. Avoid storing question text and chunk text by default, since both can contain personal or confidential data.

Testing

Retrieval evaluation has no LLM call to mock, which makes it unusually easy to test. The retriever is injected, and a fake returns canned ranked lists and records how many times it was called and with what K. Everything else, from relevance matching to the metrics to selection to triage, is ordinary deterministic code.

The tests use the worked example from earlier, so each number can be checked by hand. At K=3 the question scores recall 0.5 and reciprocal rank 0.5. At K=5 recall reaches 1.0 and nDCG is 0.651, while the context-token count rises, which is the brief's scenario of more relevant chunks at a higher cost. The runner test asserts the retriever was called once per question with the configured K, proving the evaluation actually retrieved rather than returning defaults. The selection test confirms that the cheapest configuration above the floor wins, and that an unreachable floor returns nothing instead of a best-effort guess. A triage test covers all four quadrants.

These tests prove the metrics and the selection logic are correct. They do not prove a particular retriever is good: that is what the benchmark run against a real golden set is for.

RetrievalEvalTests.cs / test_retrieval_eval.py

using Xunit;

public class FakeRetriever : IRetriever
{
    readonly Dictionary<string, List<Chunk>> _hits;
    public int CallCount { get; private set; }
    public int LastK { get; private set; }

    public FakeRetriever(Dictionary<string, List<Chunk>> hits) => _hits = hits;

    public Task<IReadOnlyList<Chunk>> RetrieveAsync(string question, int k, CancellationToken ct = default)
    {
        CallCount++;
        LastK = k;
        return Task.FromResult<IReadOnlyList<Chunk>>(_hits[question].Take(k).ToList());   // honours K like a real retriever
    }
}

public class RetrievalEvalTests
{
    const string Q = "Can unused leave roll over, and when does it expire?";

    static readonly GoldItem Gold = new(Q, new[] { "up to 5 unused days", "expires on 31 March" });

    // Ranking: noise, evidence 1, noise, evidence 2, noise.
    static readonly List<Chunk> Ranked = new()
    {
        new("hr-p1-c0", "hr.pdf", 1, "Public holidays are listed in the annual calendar."),
        new("hr-p2-c0", "hr.pdf", 2, "Employees may carry over up to 5 unused days each year."),
        new("hr-p3-c0", "hr.pdf", 3, "Leave requests go through the manager."),
        new("hr-p2-c1", "hr.pdf", 2, "Carried-over leave expires on 31 March."),
        new("hr-p4-c0", "hr.pdf", 4, "Sick leave is tracked separately."),
    };

    [Fact]
    public void Score_AtK3_FindsHalfTheEvidence()
    {
        var s = Metrics.Score(Gold, Ranked, k: 3);
        Assert.Equal(0.5, s.Recall, 3);
        Assert.Equal(1.0 / 3, s.Precision, 3);
        Assert.Equal(0.5, s.Rr, 3);          // first relevant chunk is at rank 2
    }

    [Fact]
    public void Score_AtK5_RaisesRecallButCostsMoreContext()
    {
        var k3 = Metrics.Score(Gold, Ranked, k: 3);
        var k5 = Metrics.Score(Gold, Ranked, k: 5);
        Assert.Equal(1.0, k5.Recall, 3);
        Assert.Equal(0.651, k5.Ndcg, 3);
        Assert.True(k5.ContextTokens > k3.ContextTokens);
    }

    [Fact]
    public async Task RunAsync_CallsRetrieverOncePerQuestion_WithConfiguredK()
    {
        var retriever = new FakeRetriever(new() { [Q] = Ranked });
        var report = await new Evaluator().RunAsync(new Config("B", 5, retriever), new[] { Gold });

        Assert.Equal(1, retriever.CallCount);      // proves the runner actually retrieved, once per question
        Assert.Equal(5, retriever.LastK);
        Assert.Equal(1.0, report.Recall, 3);
        Assert.Empty(report.MissedQuestions);
    }

    [Fact]
    public void Select_PicksCheapestConfigAboveTheRecallFloor()
    {
        var a = new ConfigReport("A", 3, 0.70, 0.33, 0.62, 0.61, 600, 5, new List<string>());
        var b = new ConfigReport("B", 5, 0.88, 0.27, 0.66, 0.71, 2000, 1, new List<string>());
        var c = new ConfigReport("C", 5, 0.83, 0.26, 0.64, 0.69, 1000, 2, new List<string>());

        Assert.Equal("C", Evaluator.Select(new[] { a, b, c }, recallFloor: 0.80)!.Name);
        Assert.Null(Evaluator.Select(new[] { a, b, c }, recallFloor: 0.95));   // nothing qualifies: say so
    }

    [Theory]
    [InlineData(1.0, true, Failure.Ok)]
    [InlineData(1.0, false, Failure.GenerationError)]
    [InlineData(0.5, false, Failure.RetrievalMiss)]
    [InlineData(0.0, true, Failure.UngroundedCorrect)]
    public void Triage_SeparatesRetrievalFromGenerationErrors(double recall, bool correct, Failure expected) =>
        Assert.Equal(expected, Triage.Classify(recall, correct));
}

import pytest

Q = "Can unused leave roll over, and when does it expire?"
GOLD = GoldItem(Q, ["up to 5 unused days", "expires on 31 March"])

# Ranking: noise, evidence 1, noise, evidence 2, noise.
RANKED = [
    Chunk("hr-p1-c0", "hr.pdf", 1, "Public holidays are listed in the annual calendar."),
    Chunk("hr-p2-c0", "hr.pdf", 2, "Employees may carry over up to 5 unused days each year."),
    Chunk("hr-p3-c0", "hr.pdf", 3, "Leave requests go through the manager."),
    Chunk("hr-p2-c1", "hr.pdf", 2, "Carried-over leave expires on 31 March."),
    Chunk("hr-p4-c0", "hr.pdf", 4, "Sick leave is tracked separately."),
]


class FakeRetriever:
    def __init__(self, hits: dict[str, list[Chunk]]):
        self.hits = hits
        self.call_count = 0
        self.last_k = None

    def retrieve(self, question: str, k: int) -> list[Chunk]:
        self.call_count += 1
        self.last_k = k
        return self.hits[question][:k]  # honours K like a real retriever


def test_score_at_k3_finds_half_the_evidence():
    s = score(GOLD, RANKED, k=3)
    assert s.recall == pytest.approx(0.5)
    assert s.precision == pytest.approx(1 / 3)
    assert s.rr == pytest.approx(0.5)  # first relevant chunk is at rank 2


def test_score_at_k5_raises_recall_but_costs_more_context():
    k3 = score(GOLD, RANKED, k=3)
    k5 = score(GOLD, RANKED, k=5)
    assert k5.recall == pytest.approx(1.0)
    assert k5.ndcg == pytest.approx(0.651, abs=0.001)
    assert k5.context_tokens > k3.context_tokens


def test_run_config_calls_retriever_once_per_question_with_configured_k():
    retriever = FakeRetriever({Q: RANKED})
    report = run_config(Config("B", 5, retriever), [GOLD])

    assert retriever.call_count == 1  # proves the runner actually retrieved, once per question
    assert retriever.last_k == 5
    assert report.recall == pytest.approx(1.0)
    assert report.missed_questions == []


def test_select_picks_cheapest_config_above_the_recall_floor():
    a = ConfigReport("A", 3, 0.70, 0.33, 0.62, 0.61, 600, 5, [])
    b = ConfigReport("B", 5, 0.88, 0.27, 0.66, 0.71, 2000, 1, [])
    c = ConfigReport("C", 5, 0.83, 0.26, 0.64, 0.69, 1000, 2, [])

    assert select([a, b, c], recall_floor=0.80).name == "C"
    assert select([a, b, c], recall_floor=0.95) is None  # nothing qualifies: say so


@pytest.mark.parametrize("recall, correct, expected", [
    (1.0, True, Failure.OK),
    (1.0, False, Failure.GENERATION_ERROR),
    (0.5, False, Failure.RETRIEVAL_MISS),
    (0.0, True, Failure.UNGROUNDED_CORRECT),
])
def test_triage_separates_retrieval_from_generation_errors(recall, correct, expected):
    assert classify(recall, correct) == expected

Technology Choices

C#/.NET Implementation

Why choose C#: If your backend is .NET, you get first-party Microsoft support and enterprise patterns.

  • Native Azure integration — Azure AI Search or an Azure OpenAI embedding client sits behind IRetriever, so the metrics never know which one produced the ranking
  • Enterprise patterns — immutable records for gold items and reports, dependency injection for the retriever under test
  • Production-ready — the benchmark runs as a test project in CI and fails the build if recall drops below the floor

Python Implementation

Why choose Python: If your team writes Python, you get access to the richest AI/ML ecosystem.

  • Library ecosystem — pandas for comparing report rows, and ready-made IR metric libraries for cross-checking your own numbers
  • Rapid prototyping — quick iteration over chunk sizes and K values in a notebook
  • Community — most RAG evaluation tooling is Python-first

The Bottom Line

C#/.NET team? Use C#. Python team? Use Python. Don't fight your stack. The metrics are plain arithmetic over a ranked list, so they port between languages and between OpenAI and Azure OpenAI unchanged. If Azure OpenAI is the provider, check the deployment tier and current rates before budgeting, because they differ from the OpenAI list prices quoted in this article.

Engineering Trade-offs

Offline retrieval evaluation pays off when more than one retrieval setting is plausible, when the corpus changes often, and when quality complaints need a diagnosis rather than a guess. It adds a golden set to maintain, a labelling habit and a report to read. It replaces arguments about chunk size with a table.

When to Skip or Rethink This

  • The golden set is tiny or unrepresentative. Ten easy questions produce confident numbers that mean little. Metrics are only as good as the questions.
  • The corpus is small enough to fit in the prompt. If everything fits in context, there is no retrieval to evaluate.
  • Snippet matching can't capture relevance. Questions answered by paraphrase, tables or synthesis across many passages need graded labels or human review, and substring matching will undercount them.
  • You treat retrieval scores as answer quality. Perfect recall still allows a wrong answer. Retrieval metrics gate one half of the pipeline, not the whole of it.

The benchmark report is also a natural input to a full evaluation harness, which adds generation scoring on top of the retrieval numbers built here.

Key Takeaways

  • A wrong RAG answer has two possible origins. Measure retrieval separately, because it is the half that needs no model.
  • Label evidence snippets rather than chunk IDs, so one golden set scores every chunking strategy.
  • Recall@K is the ceiling, Precision@K is the noise, MRR is speed to the first hit and nDCG is ranking quality. Report all of them.
  • Put context tokens in the same report as quality, and choose with a recall floor followed by lowest cost.
  • Combine recall with answer correctness to triage failures into retrieval misses and generation errors, and count the ungrounded correct answers.
  • Inject the retriever, fake it in tests, and assert call counts so the runner is proven to retrieve.

Interview Questions

Which information retrieval metrics matter for RAG? Recall@K shows whether the needed evidence reached the model, Precision@K shows how much noise came with it, MRR shows how early the first relevant result appears, and nDCG scores the whole ranking. Recall usually gates the choice, and the others refine it.

Why does ranking matter if the model reads all K chunks? Models attend unevenly to long contexts, and many systems truncate or cap the context. Relevant evidence ranked first survives both, so ranking quality affects answers even when recall is equal.

What is offline evaluation, and what are its limits? It scores a system against a fixed labelled set before release, which is repeatable and cheap. It can't capture questions nobody labelled or shifts in live traffic, so it complements online monitoring rather than replacing it.

How do you separate retrieval errors from generation errors? Score retrieval on its own with recall against labelled evidence, then join it with answer correctness. Wrong answers with missing evidence are retrieval problems, and wrong answers with complete evidence are generation problems.

How do you pick between two configurations when one retrieves more but costs more? Set a recall floor from the product's tolerance for missed evidence, then choose the cheapest configuration that clears it. Measure context tokens in the same run so quality and cost are compared from one dataset.

Want More Practical AI Tutorials?

Practical production AI engineering with Azure, Python and C#, published twice a week in the Real-World AI Engineering series.

Read More Articles →

Written by Jaffar Kazi, a software engineer in Sydney building AI-powered applications. Connect on LinkedIn.