AI Hints
Home›RAG Tutorial›Routing and Practice
RAG · Lesson 68 of 120

Practice: Fix a Bad Retriever

Step by step.

⏱ 2 min read▶ Video at 1:07:27🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Let's put this section together. We'll take six questions where we know which fact should be found, and improve the retriever step by step, measuring each time.

Practice: Fix a Bad Retriever
From the video: Practice: Fix a Bad Retriever
  • Six questions
  • Known facts
  • Measure each step

Three retrievers

Each test is a question, and a piece of text the right chunk contains. Hits counts how many questions find their fact in the top three. We test plain embeddings, hybrid search, and hybrid with chunk headers. Run it. Each step finds more facts than the last.

fix_retriever.pypython
from rag_kit import load_docs, make_chunks, Index
from hybrid import Hybrid
docs = load_docs()
chunks = make_chunks(docs)
titles = {d["source"]: d["text"].splitlines()[0].lstrip("# ") for d in docs}
headed = [{**c, "text": titles[c["source"]] + ": " + c["text"]}
          for c in chunks if len(c["text"]) > 40]

tests = {"What does E03 mean?": "E03", "What is the APR?": "APR",
         "Can I spread the payments?": "spread the cost",
         "How many hours until my e-bike is full again?": "4 hours",
         "How long until my money comes back?": "Refunds go",
         "Can I get next-day delivery on a bike?": "Next-day"}
hits = lambda search: sum(any(f in c["text"] for c in search(q)) for q, f in tests.items())
dense, hybrid, hybrid_h = Index(chunks), Hybrid(chunks), Hybrid(headed)
print("embeddings:", hits(lambda q: [c for s, c in dense.search(q, 3)]), "of 6")
print("hybrid:    ", hits(lambda q: hybrid.search(q, 3)), "of 6")
print("+ headers: ", hits(lambda q: hybrid_h.search(q, 3)), "of 6")
Output
embeddings: 2 of 6
hybrid:     4 of 6
+ headers:  6 of 6

Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses llm.py
from langchain.chat_models import init_chat_model

llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".

Context:
{context}

Question: {question}"""

def answer(question, chunks):
    context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
    return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()
Also uses keyword_search.py
import re
from rank_bm25 import BM25Okapi

def words(text):
    return re.findall(r"[a-z0-9]+", text.lower())

class Keyword:
    def __init__(self, chunks):
        self.chunks = chunks
        self.bm25 = BM25Okapi([words(c["text"]) for c in chunks])

    def search(self, query, k=3):
        scores = self.bm25.get_scores(words(query))
        top = sorted(range(len(scores)), key=lambda i: -scores[i])[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses hybrid.py
from rag_kit import Index
from keyword_search import Keyword
from sentence_transformers import CrossEncoder

def rrf(*ranked_lists, k=60):
    scores, chunks = {}, {}
    for ranked in ranked_lists:
        for rank, chunk in enumerate(ranked):
            key = chunk["text"]
            scores[key] = scores.get(key, 0) + 1 / (k + rank + 1)
            chunks[key] = chunk
    return [chunks[t] for t in sorted(scores, key=lambda t: -scores[t])]

class Hybrid:
    def __init__(self, chunks):
        self.dense, self.sparse = Index(chunks), Keyword(chunks)

    def search(self, query, k=5):
        a = [c for _, c in self.dense.search(query, k=10)]
        b = [c for _, c in self.sparse.search(query, k=10)]
        return rrf(a, b)[:k]

reranker = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1", device="cpu")

def rerank(query, chunks, k=3):
    scores = reranker.predict([(query, c["text"]) for c in chunks])
    order = sorted(range(len(chunks)), key=lambda i: -scores[i])[:k]
    return [chunks[i] for i in order]

The method

Write test questions with known answers. Measure. Change one thing. Measure again. Keep what helps, and drop what doesn't. In the next section, we'll turn this into a proper evaluation.

keyvalue
1test questions
2measure
3change one thing
4measure again

Summary

Improve retrieval one step at a time, and measure every change. Next, the retrieval quiz.

Key takeaways
  • Known answers
  • One change at a time
  • Measure
Next up: Retrieval Quiz — test yourself