Evaluating and improving RAG
You can't improve what you don't measure. This module shows how to test a RAG system properly — and how to make it better, one fix at a time.
Learning objectives
- Separate retrieval failures from generation failures
- Build a representative RAG test set
- Compute recall@k and MRR
- Use an LLM judge responsibly
- Run an evidence-based improvement loop
- Compare retrievers on the same test set and read the failures
- Describe agentic RAG and when its cost is justified
Setup: the documents and helper functions from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport numpy as np
from openai import OpenAI
embed_client = OpenAI() # the real SDK reads OPENAI_API_KEY from the environment
EMBED_MODEL = "YOUR-EMBEDDING-MODEL" # copy a current model name from the provider's docs
def embed(texts):
resp = embed_client.embeddings.create(model=EMBED_MODEL, input=list(texts))
return np.array([d.embedding for d in resp.data])
documents = {
"Returns Policy v7": """Damaged items can be returned within 30 days for a full refund. Send a photo of the damage to support before returning the item.
Unwanted items in their original packaging can be returned within 14 days. The customer pays the return postage for unwanted items.
Refunds are paid to the original payment method within 7 days of the return arriving.""",
"Delivery FAQ": """Standard UK delivery takes 3 to 5 working days and costs £3.95. Orders over £40 are delivered free.
Express delivery arrives the next working day if ordered before 2pm and costs £7.95.
Delivery to Ireland takes 5 to 7 working days.""",
"Care Guide": """Hand-wash bamboo boards in warm soapy water and dry them upright. Never put a bamboo board in the dishwasher.
Oil the board once a month with food-safe mineral oil to stop it cracking.
Product code BB-204 is the large bamboo board, 45 cm by 30 cm. Product code BB-110 is the small bamboo board.""",
"Gift Cards": """Gift cards are valid for 12 months from the date of purchase. They can be used online only.
A gift card cannot be exchanged for cash.""",
}
def chunk_text(text, max_words=180, overlap_words=40):
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
chunks, current = [], []
for para in paragraphs:
words = para.split()
if current and len(current) + len(words) > max_words:
chunks.append(" ".join(current))
current = current[-overlap_words:] if overlap_words else []
current.extend(words)
if current:
chunks.append(" ".join(current))
return chunks
chunks = []
for title, text in documents.items():
for c in chunk_text(text, max_words=20, overlap_words=0): # these documents are short: one paragraph per chunk
chunks.append({"id": f"{title}#{len(chunks)}", "source": title, "text": f"{title}: {c}"})
vectors = embed([c["text"] for c in chunks])
def retrieve(question, k=3):
scores = vectors @ embed([question])[0] # cosine similarity: the vectors are normalised
return [chunks[i] for i in np.argsort(-scores)[:k] if scores[i] > 0] # nothing in common: not a result
import anthropic
llm = anthropic.Anthropic() # the real SDK reads ANTHROPIC_API_KEY from the environment
def call_llm(prompt):
msg = llm.messages.create(model="YOUR-MODEL-NAME", max_tokens=500,
messages=[{"role": "user", "content": prompt}])
return msg.content[0].text
def answer(question, k=3):
hits = retrieve(question, k=k)
sources = "\n".join(f"[{i+1}] ({h['source']}) {h['text']}" for i, h in enumerate(hits))
prompt = f"""Answer using ONLY the sources. Cite like [1].
If the answer isn't in the sources, say you can't find it.
<sources>
{sources}
</sources>
<question>{question}</question>"""
return call_llm(prompt), hits6.1 Evaluate retrieval and generation separately
A wrong answer could be the retriever's fault (the right passage never arrived) or the generator's (it was there, but ignored or misread). Measure both.
| Stage | Metric | Question it answers |
|---|---|---|
| Retrieval | Recall@k (hit rate) | Is a relevant passage in the top k results? |
| Mean reciprocal rank (MRR) | How high does the first relevant passage appear? | |
| Generation | Faithfulness (groundedness) | Is every claim supported by the retrieved passages? |
| Answer relevance / correctness | Does it actually answer the question, correctly? | |
| Citation accuracy | Do citations point to passages that support the claim? |
6.2 Build a test set
Collect 50–200 realistic questions with the passage(s) that answer them and a reference answer. Include: common questions, paraphrases, exact identifiers, questions spanning two documents, questions the documents can't answer, and tricky or adversarial ones. You can use an LLM to draft questions from your documents — then review them by hand.
Python · recall@k and MRRtest_set = [
{"q": "Can I return a cracked board?", "relevant": "Returns Policy v7"},
{"q": "How long is UK delivery?", "relevant": "Delivery FAQ"},
{"q": "Is it OK to put the board in the dishwasher?", "relevant": "Care Guide"},
{"q": "When do gift cards run out?", "relevant": "Gift Cards"},
{"q": "I changed my mind about my order", "relevant": "Returns Policy v7"},
{"q": "How fast is the quickest shipping?", "relevant": "Delivery FAQ"},
{"q": "What size is BB-204?", "relevant": "Care Guide"},
{"q": "Which is bigger, BB-204 or BB-110?", "relevant": "Care Guide"},
{"q": "Does my present expire?", "relevant": "Gift Cards"},
{"q": "Can the voucher be used in a shop?", "relevant": "Gift Cards"},
]
def evaluate_retrieval(test_set, k=3, retriever=retrieve):
hits, rr = 0, 0.0
for t in test_set:
sources = [c["source"] for c in retriever(t["q"], k=k)]
if t["relevant"] in sources:
hits += 1
rr += 1 / (sources.index(t["relevant"]) + 1)
n = len(test_set)
return {"recall@k": round(hits / n, 2), "MRR": round(rr / n, 2)}
print("k=1:", evaluate_retrieval(test_set, k=1))
print("k=3:", evaluate_retrieval(test_set, k=3))
Ten questions is only enough to show the method. Even so, the numbers say something useful: two questions in ten fail, and retrieving three passages instead of one doesn't rescue them. Section 6.7 finds out which questions fail and why.
6.3 LLM-as-judge for answers
Grading answer quality by hand doesn't scale. A common approach is an LLM judge with a clear rubric — for example, "Is every factual claim in the answer supported by the sources? Answer SUPPORTED or UNSUPPORTED, then explain." Anthropic's guidance on evaluations recommends detailed rubrics, simple outputs (e.g. correct/incorrect or 1–5), letting the grader reason first, and using a different model to grade than the one that generated. Always check a sample of the judge's verdicts against human judgement before trusting it.
Python · a faithfulness judge (practice mode on this page)def judge(answer_text, hits):
sources = "\n".join(f"[{i+1}] ({h['source']}) {h['text']}" for i, h in enumerate(hits))
prompt = f"""Is every factual claim in the answer supported by the sources?
Reply SUPPORTED or UNSUPPORTED, then explain in one sentence.
<sources>
{sources}
</sources>
<answer>{answer_text}</answer>"""
return call_llm(prompt)
reply, hits = answer("Do you deliver to Ireland?")
print(reply)
print(" judge:", judge(reply, hits))
print(" judge:", judge("Delivery to Ireland is free and takes two days.", hits))
The first answer is taken from the sources and passes. The second sounds just as confident, and the judge flags it: nothing in the sources says Irish delivery is free or takes two days. A judge is itself a model and makes mistakes of its own, which is why a sample of its verdicts has to be checked by a person.
6.4 The improvement loop
- Run the test set; record metrics.
- Look at failures and classify them: retrieval miss, bad chunk, ignored context, hallucination, refusal when it shouldn't.
- Fix the biggest category — chunking, hybrid search, reranking, prompt or metadata.
- Re-run and compare. Keep changes that help.
6.5 Beyond basic RAG
- Agentic RAG: an LLM decides when and what to search, runs several searches, and checks whether it has enough information before answering (6.8).
- Structured data: for questions about numbers in databases, let the model write and run queries (with strict, read-only permissions) instead of embedding table rows.
- Knowledge graphs: represent entities and relationships for questions that need connecting many facts.
- Long-context models: context windows of hundreds of thousands of tokens make it practical to skip retrieval for small, stable document sets (Module 1.6). RAG still wins on cost, freshness, scale, per-user permissions and citations for large collections — and the two combine well: retrieve whole documents, not fragments, when the window allows.
6.6 Production checklist
- Permissions enforced at retrieval time
- Documents labelled as untrusted data in the prompt
- Fresh index with versioning and deletion
- Visible citations and an "I can't find that" path
- Retrieval and answer metrics tracked on a test set
- User feedback captured and reviewed
- Personal data handled in line with data protection law
6.7 Find the failures, then fix the biggest
An average hides what to do next. List the questions where the right source was not the top result:
Python · which questions fail, and what was retrieved instead?for t in test_set:
found = retrieve(t["q"], k=1)
got = found[0]["text"][:70] + "..." if found else "nothing at all"
if not found or found[0]["source"] != t["relevant"]:
print(f"MISS {t['q']}\n wanted {t['relevant']}, got: {got}")
Read each miss and ask why. The two product-code questions fail for the reason Module 2 predicted: an embedding model gets nothing from "BB-204". That points to a specific fix, hybrid search, and the test set can tell you whether the fix works:
Python · the same test set, three retrieversimport math, re
def tokens(text):
return re.findall(r"[a-z0-9£.-]+", text.lower())
doc_tokens = [tokens(c["text"]) for c in chunks]
def keyword_retrieve(question, k=3):
def rarity(w):
n = sum(w in t for t in doc_tokens)
return math.log(1 + len(chunks) / n) if n else 0.0
scores = np.array([sum(rarity(w) for w in set(tokens(question)) if w in t) for t in doc_tokens])
return [chunks[i] for i in np.argsort(-scores, kind="stable")[:k] if scores[i] > 0]
def hybrid_retrieve(question, k=3):
scores = {}
for ranked in (keyword_retrieve(question, k=5), retrieve(question, k=5)):
for rank, c in enumerate(ranked, start=1):
scores[c["id"]] = scores.get(c["id"], 0) + 1 / (60 + rank)
by_id = {c["id"]: c for c in chunks}
return [by_id[i] for i in sorted(scores, key=scores.get, reverse=True)[:k]]
for name, retriever in [("keyword", keyword_retrieve), ("semantic", retrieve), ("hybrid", hybrid_retrieve)]:
print(f"{name:9} k=1 {evaluate_retrieval(test_set, k=1, retriever=retriever)} "
f"k=3 {evaluate_retrieval(test_set, k=3, retriever=retriever)}")
This is the improvement loop from 6.4 in miniature: measure, read the failures, change one thing, measure again. Keyword search handles the product codes and fails on the paraphrased questions ("I changed my mind", "quickest shipping", "does my present expire"); semantic search is the reverse; the hybrid gets all ten. Whether a change helps is a question for the test set, never for intuition — on your own documents the answer may come out differently.
6.8 Agentic RAG: letting the system search more than once
Basic RAG searches once, with the user's question as typed. That fails on questions with two parts, where one search can't bring back both passages. In agentic RAG a model plans the retrieval: it breaks the question up, searches for each part, looks at what came back, and searches again if something is missing. Here is the skeleton, with a simple rule standing in for the planning model:
Python · one search against a planned set of searchesquestion = "How long is a gift card valid and can I put the board in the dishwasher?"
reply, hits = answer(question, k=2)
print("One search:")
print(" ", reply, "| sources:", sorted({h["source"] for h in hits}))
def plan(question): # a real system asks an LLM to write the sub-questions
return [part.strip(" ?") + "?" for part in question.split(" and ")]
print("Planned searches:")
for sub in plan(question):
reply, hits = answer(sub, k=2)
print(" ", sub, "->", reply, "| source:", hits[0]["source"])
The single search answers at most one half of the question. Splitting it gives each half its own search and its own grounded answer. Real agentic systems add more: choosing between several sources (documents, a database, the web), judging whether the results are good enough, and stopping after a set number of steps.
That power has a price: every extra step is another model call, so answers are slower and cost more, and there are more places for things to go wrong. A sound rule is to add this complexity only when your test set shows questions that simpler retrieval can't answer. The AI Agents course covers how such loops are built and kept under control.
A good RAG system says "I can't find that" when it should. Using answer(), work out for the six questions in the starter code how often the system refuses, split by whether the question is answerable. What would a perfect system score?
Your turnchecks = [ # (question, can the documents answer it?)
("How long is a gift card valid?", True),
("Can I put the board in the dishwasher?", True),
("How much is express delivery?", True),
("Do you sell knives?", False),
("What is your phone number?", False),
("Can I pay in euros?", False),
]
# Count refusals for answerable and unanswerable questions, then press RunShow a solution
checks = [ # (question, can the documents answer it?)
("How long is a gift card valid?", True),
("Can I put the board in the dishwasher?", True),
("How much is express delivery?", True),
("Do you sell knives?", False),
("What is your phone number?", False),
("Can I pay in euros?", False),
]
results = {True: [], False: []}
for q, answerable in checks:
reply, _ = answer(q)
results[answerable].append("can't find" in reply.lower())
print("Refused when it SHOULD answer: ", sum(results[True]), "of", len(results[True]))
print("Refused when it should NOT answer:", sum(results[False]), "of", len(results[False]))
# A perfect system scores 0 on the first line and 3 of 3 on the second.
# Both errors matter: refusing too often makes the system useless; too rarely makes it untrustworthy.For each failed case in the starter code, decide whether it is a retrieval failure (the right source was not retrieved) or a generation failure (it was retrieved, but the answer is still wrong). Print a count of each. Which part of the system would you work on first?
Your turnfailures = [
{"q": "What size is BB-204?", "needed": "Care Guide", "retrieved": ["Returns Policy v7", "Delivery FAQ"]},
{"q": "Is delivery free?", "needed": "Delivery FAQ", "retrieved": ["Delivery FAQ", "Gift Cards"]},
{"q": "Can I return a used board?", "needed": "Returns Policy v7", "retrieved": ["Care Guide", "Care Guide"]},
{"q": "Do you ship to Dublin?", "needed": "Delivery FAQ", "retrieved": ["Gift Cards", "Returns Policy v7"]},
]
# Classify each failure, then press RunShow a solution
failures = [
{"q": "What size is BB-204?", "needed": "Care Guide", "retrieved": ["Returns Policy v7", "Delivery FAQ"]},
{"q": "Is delivery free?", "needed": "Delivery FAQ", "retrieved": ["Delivery FAQ", "Gift Cards"]},
{"q": "Can I return a used board?", "needed": "Returns Policy v7", "retrieved": ["Care Guide", "Care Guide"]},
{"q": "Do you ship to Dublin?", "needed": "Delivery FAQ", "retrieved": ["Gift Cards", "Returns Policy v7"]},
]
counts = {"retrieval": 0, "generation": 0}
for case in failures:
kind = "generation" if case["needed"] in case["retrieved"] else "retrieval"
counts[kind] += 1
print(f"{kind:10} | {case['q']}")
print(counts)
# Most of these are retrieval failures, so a better prompt or a bigger model would not help.
# Classifying failures before fixing anything stops you improving the wrong half of the system.Key takeaways
- Measure retrieval (recall@k, MRR) and generation (faithfulness, correctness, citations) separately.
- Test sets need paraphrases, identifiers, multi-document and unanswerable questions.
- LLM judges need clear rubrics and human spot-checks.
- Classify failures, fix the biggest category, re-measure.
- Production RAG needs permissions, freshness, citations and feedback.
- List the failing questions and classify them before changing anything.
- Agentic RAG handles multi-part questions at the price of more calls; add it when the test set shows the need.