Part 17 / Stage 4
Retrieval-augmented generation (RAG)
Goal: Answer questions from your own documents — with retrieval measured before anything is generated. Time: ~3 hours · Needs: Parts 14–16
What you will learn
- The RAG pipeline: ingest, chunk, embed, retrieve, generate
- Measuring retrieval: recall@k on labelled questions
- Grounded prompts
- Measuring answers
- Common failure modes
- Improving RAG: reranking, query rewriting, filters
Topics in this part
Practice
Run from the repo root with PYTHONPATH=tools. Exercises 1–3 are offline; Exercise 4 uses the local mock (see Part 14's setup line) or a real key.
Exercise 1: MRR
Extend the retrieval eval with mean reciprocal rank: for each question, score 1/rank of the relevant doc (0 if absent from top-5). Print per-question ranks and the MRR.
Show the solution to Exercise 1
# Exercise 1: MRR
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from ailab import EVAL_QUESTIONS, SUPPORT_DOCS
texts = [d["title"] + ". " + d["text"] for d in SUPPORT_DOCS]
vec = TfidfVectorizer(stop_words="english").fit(texts)
doc_vectors = vec.transform(texts)
def ranked_ids(question, k=5):
scores = cosine_similarity(vec.transform([question]), doc_vectors)[0]
return [SUPPORT_DOCS[i]["id"] for i in scores.argsort()[::-1][:k]]
total = 0.0
for q in EVAL_QUESTIONS:
ranking = ranked_ids(q["question"])
rr = 1 / (ranking.index(q["relevant"]) + 1) if q["relevant"] in ranking else 0.0
total += rr
print(f"rank {'—' if rr == 0 else int(1 / rr)} rr={rr:.2f} {q['question']!r}")
print(f"\nMRR = {total / len(EVAL_QUESTIONS):.3f}")
Exercise 2: Rescue by rewriting
The eval's k=1 misses are paraphrase gaps. Write rewrite(question) that expands the two missed questions with likely document words ("return", "shipping") — a stand-in for an LLM rewriter — and show recall@1 before and after.
Show the solution to Exercise 2
# Exercise 2: Rescue by rewriting
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from ailab import EVAL_QUESTIONS, SUPPORT_DOCS
texts = [d["title"] + ". " + d["text"] for d in SUPPORT_DOCS]
vec = TfidfVectorizer(stop_words="english").fit(texts)
doc_vectors = vec.transform(texts)
def retrieve1(question):
scores = cosine_similarity(vec.transform([question]), doc_vectors)[0]
return SUPPORT_DOCS[int(scores.argmax())]["id"]
# Stand-in for an LLM query rewriter: expand paraphrases with document words.
EXPANSIONS = {
"send something back": "return refund",
"express order arrive": "express shipping delivery days",
}
def rewrite(question):
q = question.lower()
extra = " ".join(words for key, words in EXPANSIONS.items() if key in q)
return question + (" " + extra if extra else "")
def recall1(transform):
return sum(retrieve1(transform(q["question"])) == q["relevant"]
for q in EVAL_QUESTIONS)
print(f"recall@1 without rewriting: {recall1(lambda q: q)}/8")
print(f"recall@1 with rewriting : {recall1(rewrite)}/8")
# Note: 5/8 here vs the lesson's 6/8 — the lesson's retriever breaks all-zero
# ties by argsort order and happens to land on 'damaged' for the blender
# question; argmax breaks the same tie toward index 0. A hit at similarity
# 0.000 is luck, not retrieval — one more reason to eval with ex03's threshold.
for q in EVAL_QUESTIONS:
before, after = retrieve1(q["question"]), retrieve1(rewrite(q["question"]))
if before != after:
print(f"rescued: {q['question']!r} {before} -> {after}")
Exercise 3: Unanswerable cases
Add two unanswerable questions ("Do you price match?", "Can I pay in Bitcoin?") with relevant=None. Extend the harness: for these, a retrieval "hit" means the TOP-1 score is below a threshold you choose (the system should escalate, not answer). Print the threshold and the full score.
Show the solution to Exercise 3
# Exercise 3: Unanswerable cases
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from ailab import EVAL_QUESTIONS, SUPPORT_DOCS
texts = [d["title"] + ". " + d["text"] for d in SUPPORT_DOCS]
vec = TfidfVectorizer(stop_words="english").fit(texts)
doc_vectors = vec.transform(texts)
THRESHOLD = 0.15 # below this top-1 similarity, escalate instead of answering
cases = EVAL_QUESTIONS + [
{"question": "Do you price match?", "relevant": None},
{"question": "Can I pay in Bitcoin?", "relevant": None},
]
hits = 0
for q in cases:
scores = cosine_similarity(vec.transform([q["question"]]), doc_vectors)[0]
top_idx = int(scores.argmax())
top_id, top_score = SUPPORT_DOCS[top_idx]["id"], float(scores[top_idx])
if q["relevant"] is None:
ok = top_score < THRESHOLD # correctly looks unanswerable
verdict = f"escalate (top {top_id}@{top_score:.3f})"
else:
ok = top_id == q["relevant"] and top_score >= THRESHOLD
verdict = f"{top_id}@{top_score:.3f}"
hits += ok
print(f"{'✓' if ok else '✗'} {q['question']!r:52s} -> {verdict}")
print(f"\nthreshold={THRESHOLD}; score {hits}/{len(cases)}")
# The threshold is a dial: raise it and more real questions escalate; lower it
# and unanswerable ones get confident wrong answers. Pick it with THIS eval.
Exercise 4: Grounded call
Assemble the full RAG call for "How long do refunds take to arrive?": retrieve top-2, build the grounded prompt, call the API (mock or real), and print the retrieved ids and the reply. Label the reply honestly if it came from the mock.
Show the solution to Exercise 4
# Exercise 4: Grounded call (run with the local mock or a real key — Part 14 setup)
import os
import anthropic
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from ailab import SUPPORT_DOCS
texts = [d["title"] + ". " + d["text"] for d in SUPPORT_DOCS]
vec = TfidfVectorizer(stop_words="english").fit(texts)
doc_vectors = vec.transform(texts)
question = "How long do refunds take to arrive?"
scores = cosine_similarity(vec.transform([question]), doc_vectors)[0]
top = [SUPPORT_DOCS[i] for i in scores.argsort()[::-1][:2]]
context = "\n".join(f'<doc id="{d["id"]}">{d["text"]}</doc>' for d in top)
response = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=16000,
system="Answer only from the documents. Cite doc ids in [brackets]. "
"If the documents do not answer the question, say so.",
messages=[{"role": "user", "content": f"<documents>\n{context}\n</documents>\n\n{question}"}],
)
text = "".join(b.text for b in response.content if b.type == "text")
print("retrieved:", [d["id"] for d in top])
mocked = "ANTHROPIC_BASE_URL" in os.environ
print(f"answer{' (placeholder from local mock, not Claude)' if mocked else ''}:", text)
Mini-project: Support bot v1
One answer(question) function: retrieve top-2, grounded prompt with citations, generation (mock or real). Plus an eval report: recall@1 and recall@3 over EVAL_QUESTIONS with every miss printed.
A complete version is in solutions/mini_support_bot.py.
Stretch: add reranking (score top-5 by keyword overlap, keep the best 2) and show the recall change.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Prompting before measuring retrieval | Polishing generation that never sees the right doc | recall@k first |
| One blended "RAG score" | Can't tell which box broke | Retrieval eval + answer eval |
| No unanswerable cases in the eval | The worst failure goes unmeasured | Include them, expect "I don't know" |
| k as big as fits | Cost up, answers down (buried docs) | Small k + reranking |
| Set-and-forget index | Stale answers with confident citations | Re-ingest on change |
Quick recap
- RAG is chunking, embedding, retrieval and a grounded prompt — and you built every one of those pieces.
- Measure retrieval first: this index scored 6/8 at k=1 and 7/8 at k=3, with both misses explained.
- The grounding rules are to answer only from the documents, cite ids, and admit gaps.
- Answers get their own evals: faithfulness and correctness.
- Failures localise to boxes; improvements (rerank, rewrite, filter) are measured with the same harness.
Checklist
- I can draw the pipeline and name each box's Part.
- I ran the recall eval and can explain both misses.
- I can recite the three grounding rules and what each prevents.
- I keep retrieval and answer scores separate, and know why.
- I can pick the right upgrade for a given measured failure.
Read more: Prompt engineering overview · Embeddings guide