Chapter 4

Measuring retrieval

How do you know the search is good, or that a change made it better? You measure it, on questions whose right answers you wrote down in advance. This chapter is the difference between an AI demo and an AI system.

Why bother

The model can only be as good as what retrieval hands it. If the right page isn't in the top 5, no model, however smart, can answer correctly; it will say "I don't know" (best case) or improvise (worst case). And every knob in chapters 2 and 3 (chunk size, embedding model, query prefix, tokenizer, k in RRF) moves retrieval quality in ways you can't feel by trying three questions by hand. Without numbers, you tune by vibes.

The golden set

evals/questions.jsonl holds 40 questions written the way visitors might ask them, each with the id of the document(s) that contain the answer. They deliberately mix styles: keyword-heavy ("Hacker Cup rank"), paraphrased ("How did he make huge GeoJSON files load fast on a map?"), vague ("Has he done any robotics?").

Writing good eval questions

Write them before looking at what the system returns, otherwise you unconsciously write questions it already answers. Use the visitor's vocabulary, not your content's. And when a real visitor's question fails in production (you can read them in the SQLite history), add it to the set.

The three numbers

For each question we run search, collapse chunks to their documents (three chunks of one page count once), and find the position of the first right document:

  • hit@1: the first result is right. What a "top answer" feature would care about.
  • hit@5: a right document is anywhere in the top 5. That's what the LLM sees, so it's the ceiling on answer quality.
  • MRR, mean reciprocal rank: average of 1/position. First = 1, second = 0.5, third = 0.33, missing = 0. One number that rewards ranking the right thing high.

Results

python -m evals.retrieval --misses
Search modehit@1hit@5MRR
BM25 (keywords only)78%98%0.863
Dense (embeddings only)80%92%0.867
Hybrid (RRF)92%98%0.954

Neither retriever alone is great at putting the right page first; together they get it right 37 times out of 40. This table is the empirical case for chapter 3's hybrid design. The three misses:

QuestionRight doc rankWhat happened
Where is he based?2The Drivago predictor page uses "region" and "based" (as in "rule-based"), so it edges out the profile chunk on both rankings (5th vs 7th semantically, 3rd vs 4th by BM25). "based" is a word with two meanings; the retrievers can't tell which one the visitor means.
Did he use OR-Tools?6"OR-Tools" appears on the Drivago overview and the skills list too, which rank above the scheduler page itself. Still answerable from those.
How was the EV charging behaviour calibrated?2DeepVolt's market-expansion page also talks about EV charging stations (a 100k+ station dataset), so "EV charging" pulls it up first.
Caught by the eval

While adding page awareness, I also added one sentence about it to knowledge/assistant.md (the assistant's description of itself). Hybrid hit@1 dropped from 92% to 90%: "What's his email address?" now ranked the assistant's self-description above the profile page. Nothing in the new sentence mentions email; the longer chunk had simply drifted closer, by meaning, to "a question a visitor asks". Removing the sentence brought it back to 92%. Lesson: adding content can make other questions worse, in ways you would never guess. Without the eval this would have shipped silently.

The same command ends with a second, smaller table for page awareness: 8 vague questions asked on a page ("Summarize this page", "What stack did this use?"), each tagged with the page:

Page-aware questions (8)Right page among the sources the LLM sees
Searched without the page3 / 8
Searched with the page (index.retrieve)8 / 8

The metric here is different on purpose: not "ranked first" but "among what the model receives", because the feature adds chunks rather than re-ranking. Pick the metric that matches what the feature promises.

An experiment: chunk size

Settings are environment variables, so experiments are one-liners:

CHUNK_MAX_CHARS=400  python -m evals.retrieval
CHUNK_MAX_CHARSChunksHybrid hit@1hit@5MRR
40010995%100%0.969
8007290%100%0.943
1200 (current)4792%98%0.954
24002692%100%0.956
Read this carefully

Small chunks "win". So why keep 1200? Two reasons, and both are lessons:

  1. The differences are noise. With 40 questions, one question = 2.5 points. 95% vs 92% is one question. You'd need hundreds of questions before differences this small mean anything. Don't over-read small evals.
  2. The metric doesn't measure what the LLM needs. It checks that the right page ranks high, not that the retrieved chunk contains enough to answer. A 400-character chunk can be on the right page and still miss the sentence with the number. Larger chunks hand the model fuller context. Measuring that needs an answer-level eval (below).

Every metric is a proxy. Know what yours does and doesn't capture.

Next level: evaluating answers

Retrieval evals are cheap and deterministic. Answer quality is harder, because there are many right ways to word an answer. The standard tools:

  • Reference answers + LLM-as-judge: write the expected answer for each question; ask a strong model "does the candidate answer agree with the reference, yes/no, why?". Cheap and surprisingly reliable for factual questions; spot-check the judge.
  • Faithfulness (a.k.a. groundedness): is every claim in the answer supported by the retrieved sources? That's the hallucination metric that matters most here.
  • Refusal tests: questions whose answer is not in the portfolio ("What's his salary?", "Does he know Rust?"). The right answer is "I don't know from the portfolio". These catch invention.

Libraries like Ragas and promptfoo package these. Building a small version yourself first is the better way to learn; it's exercise 2 in chapter 9.

A first step: comparing the models

Choosing the order of LLM_MODELS was the first time answers needed measuring, so evals/models.py does a small version of the above: the same real prompts for every model, then the numbers a visitor feels (seconds to the first word, to the full answer), whether answers cite their sources, and one refusal test. It calls each model directly, not through the router, so a failing model shows up as a failure instead of being quietly replaced. The results are in chapter 1.

It's deliberately crude: "cites" only checks that some [n] appears, and the trap check is a regular expression for phrases like "don't have information". Good enough to rank five models; an LLM-as-judge would be the next step.

The eval set that grows itself: 👍 / 👎

Every answer in the widget has a thumbs up and a thumbs down (the same pattern as the docs assistants of Mintlify, kapa.ai or Inkeep). A click is one PUT /api/messages/{id}/feedback, stored in the feedback column of the answer's row (chapter 5). On its own a 👎 fixes nothing. Its value is what you do with it:

  1. Read them. GET /api/admin/feedback (with the admin token) lists every rated answer next to the question that prompted it and the sources it cited:
curl -H "Authorization: Bearer $ADMIN_TOKEN" http://localhost:8000/api/admin/feedback
  1. Diagnose. For each 👎, paste the question into the Retrieval Lab. Right page missing from the top 5? It's a retrieval problem (content wording, chunking, a missing synonym). Right page present but the answer is still wrong? It's a generation problem (prompt, model).
  2. Turn it into a test. Add the question to evals/questions.jsonl with the document that should answer it. Now it can never silently break again, and your golden set reflects what real visitors ask instead of what you imagined they'd ask.
Why this matters

This loop (real usage → feedback → labeled eval case → fix → re-run the eval) is how production RAG systems actually improve. The hand-written 40 questions got the system started; visitor feedback keeps it honest.

Evals vs. tests

The repo has both, and they answer different questions. Tests (tests/, run with pytest) check that code is correct: BM25 ranks a matching document first, citations parse, rate limits refuse the third request, the API streams events in order. Pass or fail, deterministic, no network (the fake echo model). Evals check that the system is good: a score you track over time and compare between versions.

You swap in a bigger embedding model and hybrid hit@1 goes from 92% to 95% on the 40 questions. What should you conclude?

Small evals give you direction, not precision. Reading the individual flips (--misses) often teaches more than the aggregate.

Which number best predicts whether the LLM can answer correctly?

Order within the top 5 matters a little (models attend more to the start of the context), but presence is what makes an answer possible.

A visitor gives 👎 to the answer for "Does he know Kubernetes?". The Retrieval Lab shows the Skills chunk ranked 1st, and Kubernetes isn't in it. What's the right fix?

Not every 👎 is a bug: sometimes the visitor wanted an answer the content can't give. Diagnose before you "fix", and never trade away faithfulness to please a rating.

Go further