RAG · Lesson 57 of 120
Reranking
A second, closer look.
Fast search is good at finding candidates, but not perfect at ordering them. A reranker takes a second, closer look at each candidate, and reorders them. It's slower, so we only use it on a few.

- Fast search finds
- Reranker orders
- Only on a few
Rerank the candidates
Hybrid search fetches ten candidates. Rerank scores each one against the question, and keeps the best three. Run it. Before reranking, the top chunk is about faulty items. After, it's the chunk about spreading the cost.
rerank.pypython
from rag_kit import load_docs, make_chunks
from hybrid import Hybrid, rerank
search = Hybrid(make_chunks(load_docs()))
q = "Can I spread the payments?"
candidates = search.search(q, k=10)
print("before:", candidates[0]["text"][:50])
print("after: ", rerank(q, candidates)[0]["text"][:50])Output
before: ## Faulty items If an item is faulty, you can retu after: You can spread the cost of any bike over £400 with
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]Retrieve, then rerank
The question goes in. Fast search fetches many candidates, like twenty. The reranker scores each one carefully. And we keep the best three for the prompt.
- Question
- Fetch 20
- Rerank
- Keep 3

Summary
Retrieve many candidates fast, then rerank them carefully, and keep the best few. Next, how cross encoders work.
Key takeaways- Fetch many
- Rerank
- Keep few
Next up: Cross-Encoders — scoring each pair