Skip to content
Visual explainer 3h 30m to learn 5 steps

Evaluate retrieval and answer quality

Measure retrieval recall, citation accuracy, answer quality, latency and cost on a seeded fixture set.

By Invicly Tech, , in FastAPI with Python for AI Backends. About 11 minutes to read.

Topic 20 of 29

In short

An AI answer can fail in three separate places: retrieval missed the right chunk, the answer cited the wrong source, or the wording was wrong. A seeded evaluation set of questions with known answers and known source chunks lets you measure each of these on its own, along with latency and cost. Running the same set after every change shows whether quality went up or down.

Think of it like this: An evaluation set is a practice exam with a marking scheme: the same questions every time, so you can compare scores between attempts.

Explained simply

Normal tests check that code does exactly the right thing. AI answers are fuzzier: the wording changes and two answers can both be fine. So instead of one exact check, you score the service on a fixed set of questions and watch the scores over time. This is called an evaluation, or eval.

Start with a small set of documents you control, such as five synthetic policy files for a made-up company called Contoso. Write 20 to 50 questions. For each one, write down which chunks hold the answer and the key facts a good answer must include. Add a few questions the documents cannot answer.

Then measure the pipeline in parts. Did retrieval find the right chunks? Did the answer cite the right chunks? Did the answer state the right facts without inventing new ones? Keeping these scores separate tells you whether to fix search, prompts or the model.

Quality is not the only number. Record how long each question took and how many tokens it used. A change that improves answers a little but doubles the cost or the wait may not be worth shipping. Save every run so you can compare it with the last one.

Press Play on a diagram to walk through it one step at a time.

FlowOne evaluation run
  1. 1
    Load fixtures

    Seeded documents and questions with expected chunks

  2. 2
    Retrieve

    Top k chunks per question

  3. 3
    Score retrieval

    Recall@k against expected chunks

  4. 4
    Generate

    Answer with citations

  5. 5
    Score answer

    Citation accuracy and rubric grade

  6. 6
    Report

    Scores, p95 latency, tokens and cost

MapWhat an eval report breaks down
Eval run
  • Retrieval
    • Recall@k
    • Hit rate@k
    • MRR
  • Citations
    • Cited IDs were retrieved
    • Cited text supports claim
  • Answers
    • Required facts present
    • No-source when expected
    • Judge score with reason
  • Cost and speed
    • p50 and p95 latency
    • Tokens per question
    • Cost per run
  • Safety
    • Cross-tenant items return no source

In depth

Building a seeded question set

Seeded means fixed and repeatable: the same documents, the same chunking and the same questions every run. Store them in the repository as JSON or YAML next to the tests. Each item needs an ID, the tenant, the question, the expected chunk IDs and a short list of required facts. Mark items with tags such as lookup, multi-hop, no-answer and cross-tenant so you can read scores per type.

Write questions the way users ask them, not by copying sentences from the documents, or keyword search will look better than it is. Include at least one question per tenant whose answer only exists in the other tenant's documents. The right result there is a no-source answer, which proves the tenant filter works inside retrieval too. When you change chunking, chunk IDs change, so map expectations to a document and a short quote, then resolve them to chunk IDs at load time.

  • Start with 20 to 50 items; grow from real failures
  • Tag items by type for per-type scores
  • Version the set; never edit it in the same change as the code
  • Synthetic documents only, no customer data

Measuring retrieval: recall@k and friends

Recall@k is the main retrieval number. For one question, take the top k chunks the retriever returned and count how many of the expected chunks are in them, divided by the number expected. Average over all questions. With k = 5 and two expected chunks, finding one gives 0.5.

A simpler variant, hit rate@k, scores 1 if any expected chunk is in the top k. Mean reciprocal rank (MRR) rewards putting the right chunk first: 1 for rank one, 0.5 for rank two, and so on. Pick k to match what you actually send to the model. If the prompt only takes the top 4 chunks, recall@20 is a nice number that the model never benefits from. Retrieval scores need no model call at all, so they run fast and cheap after every chunking or embedding change.

CompareThree retrieval scores
Recall@k
  • Share of expected chunks in top k
  • Best when answers need several chunks
  • 0.0 to 1.0 per question
Hit rate@k
  • 1 if any expected chunk is in top k
  • Simple and easy to explain
  • Hides partly missing context
MRR
  • 1 divided by rank of first correct chunk
  • Rewards good ordering
  • Useful when only the top few are used

Checking citations and grading answers

Citation accuracy has two checks. First, structural: every cited chunk ID must be one the retriever actually returned for this request; a citation to anything else is invented. Code can check this exactly. Second, support: the cited chunk must contain the fact the sentence claims. You can approximate this by checking that the required facts appear in the cited text, or by asking a grader.

For answer quality, start with rules: required facts present, no forbidden claims, a no-source reply when expected. Rules are cheap and stable. A model used as a judge can grade softer qualities such as completeness, but it has its own errors. Give the judge a written rubric, ask for a score and a short reason, and hand-check a sample of its grades whenever you change the judge prompt or model. With the course's deterministic fake model, answer scores only change when your code changes, which makes the eval itself easy to test.

Latency, cost and comparing runs

For each question, record wall time for retrieval, for generation and in total, plus input and output tokens. Report p50 and p95 rather than the average, because a few slow questions are what users notice. Cost is tokens multiplied by your provider's price per token; keep prices in a config file because they change.

Write each run to a results file with the git commit, the model name and the fixture version. A small script then prints the difference from the last saved run. In CI, fail the build only on clear drops, for example recall@5 falling more than 0.05 or any cross-tenant item returning a citation, since small changes in model grading are noise.

  • Report p50 and p95, not only the mean
  • Cost = input tokens x input price + output tokens x output price
  • Store commit, model and fixture version with each run
  • Gate on big drops and on any tenant leak

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Build a seeded question set~40m
  2. 2
    Measure retrieval recall@k~40m
  3. 3
    Check citation accuracy~40m
  4. 4
    Grade answer quality~40m
  5. 5
    Track latency and cost per run~40m

Key points

  • Score retrieval and generation separately, or you cannot tell which part to fix.
  • Recall@k asks: of the chunks that should have been found, how many appeared in the top k?
  • A citation is accurate only if it points to a retrieved chunk that actually supports the claim.
  • Include questions with no answer in the documents; the correct result is a clear no-source reply.
  • Record latency percentiles and tokens per run, because a better answer that costs three times more is a trade-off.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
def recall_at_k(retrieved: list[str], expected: set[str], k: int) -> float:
    if not expected:
        return 1.0
    top = set(retrieved[:k])
    return len(top & expected) / len(expected)

assert recall_at_k(["c7", "c2", "c9"], {"c2", "c4"}, k=3) == 0.5

Recall@k for one question: one of two expected chunks was found.

A fixture item and a parametrized retrieval test

Step 1: store items in evals/questions.json, each with a question, tenant and expected chunk IDs. Step 2: load them and parametrize one pytest test over the items. Step 3: call the retriever directly, not the HTTP route, so no model is needed. Step 4: assert recall@5 is at least the threshold you agreed for that tag. Expected evidence: one test case per question in the output, with the failing questions named, which tells you exactly where retrieval is weak.

python
import json, pytest
from app.retrieval import search
from evals.metrics import recall_at_k

ITEMS = json.load(open("evals/questions.json"))

@pytest.mark.parametrize("item", ITEMS, ids=[i["id"] for i in ITEMS])
@pytest.mark.anyio
async def test_retrieval_recall(item, seeded_db):
    hits = await search(seeded_db, tenant_id=item["tenant"], query=item["question"], k=5)
    score = recall_at_k([h.chunk_id for h in hits], set(item["expected_chunks"]), k=5)
    assert score >= item.get("min_recall", 0.5)

Reading a run that got worse

You change the chunk size from 800 to 300 tokens and rerun. Step 1: overall recall@5 drops from 0.86 to 0.71. Step 2: per-tag scores show lookup questions are fine but multi-hop questions fell sharply, because each answer is now split across more chunks than k allows. Step 3: citation accuracy is unchanged, so generation is not the problem. Step 4: tokens per question fell by 30 percent. Decision: try k = 8 with small chunks and compare again, rather than reverting blindly.

Quick reference

  • Recall@k = expected chunks found in top k / expected chunks.
  • Score retrieval without the model: it is fast, cheap and deterministic.
  • A citation to a chunk that was not retrieved is invented; check it in code.
  • Include no-answer and cross-tenant questions; both should produce no citations.
  • Report p50 and p95 latency and tokens per question with every run.
  • Save commit, model, prompt version and fixture version with each result.
  • Hand-check a sample whenever a model is used as the grader.

Common mistakes

  • Writing questions that copy sentences from the documents, so keyword search scores perfectly and the test means little.
  • Using a model as the only grader without spot-checking its grades by hand.
  • Changing the fixture set and the code at the same time, so you cannot compare runs.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Two chunks are expected and the top 5 results contain one of them. What is recall@5?

Question 2

2Retrieval recall is high, but answers often miss required facts. What should you change first?

Question 3

3Which citation check can be done exactly in code with no model?

Question 4

4Why report p95 latency instead of only the average?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write mrr(retrieved, expected) that returns 1 divided by the rank of the first expected chunk, or 0 if none is found.

  2. Exercise 2medium

    Write citation_precision(cited, retrieved) that returns the share of cited IDs that were actually retrieved, and returns 1.0 when there are no citations.

  3. Exercise 3hard

    Write a script that runs all questions, computes mean recall@5, p95 total latency and total tokens, and exits with code 1 if recall@5 dropped more than 0.05 from evals/last_run.json.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How many questions do I need for a useful eval?
Twenty to fifty well-chosen questions are enough to catch big regressions. Add a new item every time you find a real failure.
Can I use a model to grade answers?
Yes, with a written rubric and regular hand checks of a sample. Use rules for anything you can check exactly, such as required facts and citation IDs.
Should evals run in CI?
Retrieval scores with the fake model are cheap enough for every pull request. Runs against a real paid model are usually scheduled or manual to control cost.

Go deeper

ShareXLinkedInWhatsApp