AI Engineering · Build lab 7 of 14

Hybrid search and reranking in Python: BM25, vectors, Reciprocal Rank Fusion and a cross-encoder

Make retrieval better and prove it with numbers. Add BM25 keyword search next to vector search, merge them with Reciprocal Rank Fusion, rerank the top 20 with a cross-encoder or an LLM, and measure recall@5, MRR and latency for each on 24 labelled queries.

⏱ 75 minIntermediate💸 Free (local models)10 steps

Python 3.12uvOllamanomic-embed-textrank-bm25 0.2.2sentence-transformers 6ms-marco-MiniLM-L6-v2llama3.2:3b (optional)pytest

Overview video

1 / 7

0 of 10 steps done

What you will build

A search engine for a help centre with four ways to search the same 44 articles, side by side: keyword search with BM25 (the classic ranking behind Elasticsearch and Lucene), vector search with embeddings (lab 5), hybrid search that runs both and merges the lists with Reciprocal Rank Fusion (RRF), and hybrid + rerank, where a small cross-encoder model reads the question and each of the top 20 candidates together and puts them in a better order. An LLM can do the reranking too; you build that as well and compare.

Every change is measured. A file of 24 labelled questions (each with the article or articles that answer it) drives an evaluation that prints recall@5, MRR and milliseconds per query for every method in one table. On our run the table went from 0.69 (keyword) and 0.88 (vector) to 0.92 (hybrid) and 1.00 (hybrid + rerank), and the latency column shows what each step costs.

The tests use fakes for the embedding API, the cross-encoder and the chat model, so uv run pytest -q downloads nothing and runs in a fraction of a second.

Before you start

  • Lab 5 done: Embeddings and search from scratch. This lab reuses its embedder.py and its idea of recall@k. Every file is shown again in full, so you can also start here.
  • Lab 6 helps: RAG from scratch. This lab improves the retrieval half of RAG. Better retrieval is the cheapest way to better answers.
  • The idea behind it (10 minutes): Hybrid search and reranking explains why keywords and vectors fail in opposite places.
  • About 1 GB of free disk on a Mac (PyTorch plus a 90 MB reranker model) and Ollama with nomic-embed-text. On Linux PyTorch from PyPI pulls about 3 GB of GPU libraries; step 7 shows how to avoid that.

Setup

S1Install uv (skip if you did lab 1)

uv installs Python for you, creates the virtual environment and manages packages: one tool instead of pyenv + venv + pip.

Run
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
You should see
everything's installed!

S2Check uv works

The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own (the installer added it to your shell settings). On Windows, open a new terminal after installing.

Run
uv --version
You should see
uv 0.x.y

S3Install Ollama (skip if you did lab 1)

Download it from ollama.com/download and open it once. It runs a small server on port 11434 with the same API as the hosted providers, including the embeddings endpoint.

Run
ollama --version
You should see
ollama version is 0.x.y

S4Pull the embedding model (nomic-embed-text, about 270 MB)

The same model as lab 5. It turns each text into 768 numbers. If you did lab 5 it is already there and this finishes at once.

Run
ollama pull nomic-embed-text
You should see
pulling manifest
...
success

S5Optional: the chat model for the LLM reranker (step 8)

Step 8 asks a chat model to rerank. Skip this if you only want the cross-encoder; everything else works without it. Ollama 0.5 or newer is needed for the JSON Schema output it uses (ollama --version).

Run
ollama pull llama3.2:3b
You should see
pulling manifest
...
success
1

Create the project

A fresh project with NumPy, the SDK, BM25 and pytest, plus the settings for three models.

uv init creates the project folder and pyproject.toml (the project file, like package.json or pom.xml). uv add installs packages into the project's own virtual environment and records them, so anyone can recreate it with uv sync.

New this time: rank-bm25, a small pure-Python BM25 library (about 250 lines, built on NumPy). We pin the exact version, 0.2.2, because step 3 explains its formula line by line, and a different version could compute it differently. The quotes around it keep zsh and bash from reading anything in it as shell syntax. The reranker library comes in step 7, when you need it.

The settings are lab 5's plus one: RERANK_MODEL, the name of the cross-encoder on Hugging Face. llm.py builds the client and turns the common errors into one clear sentence.

.env
# Local models through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b
EMBED_MODEL=nomic-embed-text
RERANK_MODEL=cross-encoder/ms-marco-MiniLM-L6-v2

# A hosted API instead: change these lines, nothing else (vectors are rebuilt automatically).
# LLM_BASE_URL=https://api.your-provider.com/v1
# LLM_API_KEY=sk-...
# LLM_MODEL=the-chat-model-name
# EMBED_MODEL=the-embedding-model-name
  1. Ollama's OpenAI-compatible API, as in every lab so far. Embeddings come from /v1/embeddings, chat from /v1/chat/completions.line 2
  2. The chat model. Only the LLM reranker in step 8 uses it.line 4
  3. The embedding model from lab 5, for vector search.line 5
  4. The cross-encoder for step 7. It does not run in Ollama: the sentence-transformers library downloads it from Hugging Face (about 90 MB) and runs it inside your Python process.line 6
config.py
import os
from dataclasses import dataclass

from dotenv import load_dotenv

load_dotenv()  # read .env into environment variables (real env vars win)


@dataclass(frozen=True)
class Settings:
    base_url: str
    api_key: str
    model: str
    embed_model: str
    rerank_model: str


def settings() -> Settings:
    return Settings(
        base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
        api_key=os.environ.get("LLM_API_KEY", "ollama"),
        model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
        embed_model=os.environ.get("EMBED_MODEL", "nomic-embed-text"),
        rerank_model=os.environ.get("RERANK_MODEL", "cross-encoder/ms-marco-MiniLM-L6-v2"),
    )
  1. load_dotenv() copies .env into os.environ. Variables already set in your shell win, which is what you want on a server.line 6
  2. @dataclass writes the constructor for you, like a Java record. frozen=True makes it read-only.line 9
  3. New: the reranker name, with the same default as .env. os.environ.get(name, default) is System.getenv with a fallback.line 24
.gitignore
.venv/
__pycache__/
.env
index/
  1. index/ holds the saved document vectors (step 4). The code rebuilds it whenever the articles or the model change.line 4
llm.py
import openai
from openai import OpenAI

from config import settings


def make_client() -> OpenAI:
    s = settings()
    return OpenAI(base_url=s.base_url, api_key=s.api_key, timeout=120, max_retries=2)


def friendly(err: openai.OpenAIError, models: list[str]) -> str:
    """One clear line for the errors you will actually hit."""
    if isinstance(err, openai.APITimeoutError):  # before APIConnectionError: it is a subclass
        return "The model server took too long. Try again, or use a smaller model."
    if isinstance(err, openai.APIConnectionError):
        return "Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)"
    if isinstance(err, openai.NotFoundError):
        pulls = " and ".join(f"ollama pull {m}" for m in models)
        return f"A model was not found. Check ollama list, then: {pulls}"
    return f"The request failed: {err}"
  1. A function, not a global: the tests never call it. They hand the code a fake client instead.line 7
  2. 120 seconds because the LLM reranker in step 8 sends a long prompt to a local model. max_retries=2 retries timeouts, 429 and 5xx with backoff.line 9
  3. isinstance(x, C) is Java's x instanceof C. The timeout check comes first on purpose: APITimeoutError is a subclass of APIConnectionError, so the other order would report a slow server as "cannot reach".line 14
  4. Ollama answers 404 when a model has not been pulled. The 404 does not say which of our models it was, so the caller passes the models it uses and the message lists a pull command for each.line 18
  5. Unlike lab 5, friendly takes a **list** of model names: a search can use the embedding model and the chat model in one query.line 12
Run
uv init hybrid-search
cd hybrid-search
uv add numpy openai python-dotenv "rank-bm25==0.2.2"
uv add --dev pytest
You should seeyour text will differ: the model writes it
Initialized project `hybrid-search` at `.../hybrid-search`
Resolved 20 packages in 480ms
Installed 18 packages in 40ms
 + numpy==2.5.5
 + openai==3.60.0
 + python-dotenv==1.2.4
 + rank-bm25==0.2.2
 ...
Why this way? Every search in this lab is an object with the same method, search(query, k), that returns (id, score) pairs. That one shared shape is what lets you swap, combine, rerank and measure them with the same code.
Stuck on this step?
uv: command not found
Run export PATH="$HOME/.local/bin:$PATH" (macOS and Linux), or open a new terminal so the installer's PATH change applies.
zsh: no matches found or a file called =0.2.2 appears
The package spec was not in quotes. Type it exactly as shown: "rank-bm25==0.2.2".
uv also created main.py
Newer uv versions write a hello-world main.py. This lab does not use it: leave it or delete it.
2

The articles and the labelled questions

A small corpus with both kinds of hard cases, and 24 questions with known answers to measure against.

Make a folder called data and save the two files below in it. Both are JSON Lines: one complete JSON object per line, no surrounding [...].

docs.jsonl is lab 5's bookshop help centre (the first 30 lines) plus 14 new articles full of things users type exactly: error codes (E104, E140, E410: the same three digits in a different order), product names (Lumen X2, Lumen X3), a promo code and an order-number format.

queries.jsonl is the labelled query set: real-sounding questions, each with the ids of the articles that answer it (relevant). A few questions have two right answers. There are three kinds: paraphrases with no shared words ("stop my monthly plan"), exact terms ("E217", "WELCOME10"), and details users quote from the screen ("it says wait 15 minutes"). You write this file before tuning anything, so the numbers cannot be bent to fit.

corpus.py reads both files and decides what we search for each article: the title and the text together.

data/docs.jsonl
{"id": "reset-password", "title": "Reset your password", "text": "On the sign-in page choose Forgot password. We email you a link that works for 30 minutes. Pick a new password of at least 10 characters."}
{"id": "change-email", "title": "Change the email address on your account", "text": "Open Account settings, choose Email and type the new address. Confirm it from the message we send there."}
{"id": "close-account", "title": "Close your account", "text": "Write to support from the address on your account. We delete your data within 30 days, and e-books you bought stay downloadable until then."}
{"id": "two-step-sign-in", "title": "Turn on two-step sign-in", "text": "In Security settings choose Two-step sign-in and scan the code with an authenticator app. After that you type a six-digit code when you sign in on a new device."}
{"id": "refunds", "title": "Refunds for printed books", "text": "If a printed book arrives damaged, or you change your mind within 14 days, we pay the full price back to your original payment method within 5 working days."}
{"id": "return-a-book", "title": "Send a printed book back", "text": "Print the prepaid label from Your orders, pack the book in its original box and drop it at any post office."}
{"id": "ebook-refunds", "title": "Refunds for e-books", "text": "An e-book can be refunded within 7 days if you have read less than 10 percent of it."}
{"id": "delivery-times", "title": "Delivery times", "text": "Orders placed before 2 pm leave our warehouse the same day. Standard delivery takes 2 to 4 working days; express takes 1."}
{"id": "delivery-charges", "title": "Delivery charges", "text": "Standard delivery is free on orders over 25 dollars and costs 3.99 below that. Express costs 7.99 on any order."}
{"id": "ordering-from-abroad", "title": "Ordering from abroad", "text": "We send printed books to 40 countries. Import duties and taxes are charged by your country's customs when the parcel arrives."}
{"id": "track-an-order", "title": "Track an order", "text": "Your dispatch email has a tracking number. Enter it on the carrier's website to see where the parcel is right now."}
{"id": "missing-parcel", "title": "An order has not arrived", "text": "If the tracking has not changed for 5 working days, contact us and we send a replacement or refund the order."}
{"id": "cancel-an-order", "title": "Cancel an order", "text": "You can cancel in Your orders until the book is dispatched. After that, send it back instead."}
{"id": "change-delivery-address", "title": "Change the delivery address", "text": "Before dispatch, edit the address in Your orders. Once the parcel has left, ask the carrier to redirect it."}
{"id": "ways-to-pay", "title": "Ways to pay", "text": "We accept Visa, Mastercard, American Express, PayPal and gift cards. We never store your full card number."}
{"id": "card-declined", "title": "Card declined at checkout", "text": "Check the expiry date and the billing postcode, then try again. Your bank may also block online payments until you approve them in its app."}
{"id": "invoices", "title": "Download an invoice", "text": "Every order has a PDF invoice in Your orders, with our VAT number for business expenses."}
{"id": "gift-cards", "title": "Gift cards", "text": "Gift cards come in amounts from 10 to 200 dollars, never expire and work for printed books and e-books."}
{"id": "gift-wrap", "title": "Gift wrapping and messages", "text": "Add gift wrap for 2.50 at checkout and write a message of up to 200 characters. Prices are left out of the parcel."}
{"id": "reading-club", "title": "Reading Club membership", "text": "Reading Club costs 9.99 a month and gives you one e-book credit every month plus free express delivery."}
{"id": "end-membership", "title": "End your Reading Club membership", "text": "Go to Account settings, then Membership, and choose End membership. You keep the benefits until the end of the period you paid for."}
{"id": "sync-reading-position", "title": "Sync your reading position", "text": "The app saves your last page to your account whenever you are online, so you can carry on from your phone, tablet or e-reader."}
{"id": "offline-reading", "title": "Read without an internet connection", "text": "Tap Download on a book's cover. Downloaded books open in airplane mode."}
{"id": "text-size", "title": "Change the font size", "text": "In a book, tap the Aa button to change the font size, the typeface and the line spacing. Dark mode is in the same menu."}
{"id": "supported-devices", "title": "Devices you can read on", "text": "Our app runs on iPhone, iPad, Android phones and tablets, and in a web browser. Up to 6 devices can be signed in at once."}
{"id": "audiobooks", "title": "Audiobooks", "text": "Audiobooks play in the same app. You can set the speed from 0.5x to 3x and add a sleep timer."}
{"id": "pre-orders", "title": "Pre-order a book", "text": "Pre-ordered books are charged on release day and are delivered or downloaded as soon as they come out."}
{"id": "price-drop", "title": "Price drops after you buy", "text": "If a book gets cheaper within 7 days of your order, we refund the difference. Send support your order number."}
{"id": "contact-support", "title": "Contact support", "text": "Chat with us in the app from 8 am to 8 pm, or send an email, and we reply within one working day."}
{"id": "privacy", "title": "What we do with your data", "text": "We use your reading history only to recommend books. We never sell personal data, and you can download a copy of it in Account settings."}
{"id": "error-e104", "title": "Error E104 at checkout", "text": "E104 means your bank asked for an extra security check. Approve the payment in your banking app, then press Pay again."}
{"id": "error-e217", "title": "Error E217 when downloading", "text": "E217 means the download stopped halfway. Free up some storage on the device and tap Download again."}
{"id": "error-e330", "title": "Error E330 when signing in", "text": "E330 means there were too many sign-in attempts. Wait 15 minutes, or reset your password to get in straight away."}
{"id": "lumen-x2-charging", "title": "The Lumen X2 does not charge", "text": "Use the USB-C cable from the box and hold the power button for 20 seconds to restart it. The light turns amber while the battery charges."}
{"id": "lumen-x2-wifi", "title": "Connect the Lumen X2 to Wi-Fi", "text": "Open Settings, then Network, pick your network and type its password. The Lumen X2 only works with 2.4 GHz networks."}
{"id": "promo-codes", "title": "Promo codes", "text": "Type the code in the Promo code box at checkout. Codes like WELCOME10 work once per account and cannot be combined."}
{"id": "student-discount", "title": "Student discount", "text": "Students get 15 percent off printed books after confirming a university email address."}
{"id": "epub-import", "title": "Add your own EPUB files", "text": "Send EPUB and PDF files to the library address shown in Account settings. Files with copy protection cannot be added."}
{"id": "family-sharing", "title": "Family Library", "text": "Link up to 5 accounts in Family Library. Members can read each other's e-books, but audiobooks are not shared."}
{"id": "order-number", "title": "Find your order number", "text": "Order numbers start with BK and 8 digits, like BK20251130. You find yours in the confirmation email and in Your orders."}
{"id": "error-e140", "title": "Error E140 when paying with a gift card", "text": "E140 means the gift card balance is lower than the order total. Pay the rest with a card, or remove an item."}
{"id": "error-e410", "title": "Error E410 when opening a book", "text": "E410 means the book licence on this device has expired. Sign out of the app, sign in again and open the book once while online."}
{"id": "lumen-x3-charging", "title": "The Lumen X3 does not charge", "text": "The Lumen X3 charges wirelessly on its stand. Clean the metal contacts and place it on the stand until the screen shows a battery icon."}
{"id": "lumen-x3-wifi", "title": "Connect the Lumen X3 to Wi-Fi", "text": "Swipe down from the top, tap the Wi-Fi icon and choose your network. The Lumen X3 works with 2.4 GHz and 5 GHz networks."}
  1. The answer to "stop my monthly plan". The words "stop", "monthly" and "plan" appear nowhere in it, so keyword search cannot find it.line 21
  2. From here on: the new articles. Codes like E104 mean nothing in plain English, and the next two articles use the same digits in another order (E140, E410).line 31
  3. "Wait 15 minutes" is a detail a user reads off the screen and types into search. Watch what vector search does with it in step 4.line 33
  4. Two products with near-identical articles (X2 and X3). The model name is the only reliable difference.line 34
data/queries.jsonl
{"query": "I forgot my password", "relevant": ["reset-password"]}
{"query": "can I read on the plane", "relevant": ["offline-reading"]}
{"query": "stop my monthly plan", "relevant": ["end-membership"]}
{"query": "the book I ordered never showed up", "relevant": ["missing-parcel"]}
{"query": "the letters are too small", "relevant": ["text-size"]}
{"query": "talk to a human", "relevant": ["contact-support"]}
{"query": "how much is postage", "relevant": ["delivery-charges"]}
{"query": "do you ship to Canada", "relevant": ["ordering-from-abroad"]}
{"query": "share books with my kids", "relevant": ["family-sharing"]}
{"query": "refund for an ebook I barely read", "relevant": ["ebook-refunds"]}
{"query": "E217", "relevant": ["error-e217"]}
{"query": "E140", "relevant": ["error-e140"]}
{"query": "payment refused with E104", "relevant": ["error-e104", "card-declined"]}
{"query": "E330 locked out", "relevant": ["error-e330"]}
{"query": "WELCOME10 does not work", "relevant": ["promo-codes"]}
{"query": "where is my BK number", "relevant": ["order-number"]}
{"query": "import EPUB", "relevant": ["epub-import"]}
{"query": "Lumen X2 wifi", "relevant": ["lumen-x2-wifi"]}
{"query": "Lumen X3 wifi 5 GHz", "relevant": ["lumen-x3-wifi"]}
{"query": "discount for university students", "relevant": ["student-discount"]}
{"query": "it says wait 15 minutes", "relevant": ["error-e330"]}
{"query": "less than 10 percent", "relevant": ["ebook-refunds"]}
{"query": "my e-reader will not charge", "relevant": ["lumen-x2-charging", "lumen-x3-charging"]}
{"query": "charging stand for the e-reader", "relevant": ["lumen-x3-charging"]}
  1. Lines 1 to 10: paraphrases. The user's words differ from the article's.line 1
  2. Lines 11 to 20: exact terms. Codes, product names, a promo code.line 11
  3. Two right answers: the error code article and the general "Card declined" article. recall@5 is 0.5 if only one is in the top 5.line 13
  4. Lines 21 to 24: details and mixed cases. Numbers and product words that only appear in the article text.line 21
corpus.py
import json
from pathlib import Path


def read_jsonl(path: str) -> list[dict]:
    """Read a JSON Lines file: one JSON object per line."""
    rows = []
    for line in Path(path).read_text(encoding="utf-8").splitlines():
        if line.strip():
            rows.append(json.loads(line))
    return rows


def load_docs(path: str = "data/docs.jsonl") -> list[dict]:
    return read_jsonl(path)


def load_queries(path: str = "data/queries.jsonl") -> list[dict]:
    """Each row: {"query": "...", "relevant": ["doc-id", ...]}."""
    return read_jsonl(path)


def doc_text(doc: dict) -> str:
    """The text we search for a document: its title, then its body."""
    return f"{doc['title']}. {doc['text']}"
  1. One reader for both files. list[dict] is the type hint for a list of dictionaries, like List<Map<String, Object>>; Python does not enforce hints, they document the code.line 5
  2. Path(...).read_text() reads the whole file into a string (Files.readString in Java). splitlines() splits it into lines.line 8
  3. An empty string counts as false, so blank lines (like one at the end of the file) are skipped.line 9
  4. json.loads parses one line of JSON into a dict, like JSON.parse.line 10
  5. An f-string: the values in {...} are put into the text. Keyword search, vector search and the reranker all read this same text.line 25
Run
uv run python -c "from corpus import load_docs, load_queries; print(len(load_docs()), 'articles,', len(load_queries()), 'labelled queries')"
You should see
44 articles, 24 labelled queries
Why this way? Without labelled questions you can only compare search methods by trying a few queries and picking the one that "feels" better, and you will pick the queries that make your favourite look good. Twenty-four questions is small, but it is enough to see each method fail in its own way. Grow it from real search logs: add every question users ask that comes back wrong.
Stuck on this step?
FileNotFoundError: data/docs.jsonl
Run the command from the project folder, and check the files are inside data/ (not next to it).
json.decoder.JSONDecodeError
A line is not complete JSON, often because an editor wrapped a long line. Every object must be on exactly one line.
3

Keyword search with BM25

Rank articles by the words they share with the query, the way search engines have for decades.

Lab 5's keyword search counted shared words. BM25 ("Best Matching 25") improves on that with three ideas: a word that appears in few documents is worth more (E217 tells you far more than book); repeating a word helps, but less and less (saturation); and a match in a short document counts more than the same match in a long one.

For each query word t, BM25 adds idf(t) × tf × (k1 + 1) / (tf + k1 × (1 − b + b × dl / avgdl)) to the document's score. tf is how often the word appears in the document, dl the document's length in words, avgdl the average length. k1 = 1.5 controls saturation and b = 0.75 how much length matters (rank-bm25's defaults; Lucene and Elasticsearch use k1 = 1.2). rank-bm25 computes idf(t) = ln((N − n + 0.5) / (n + 0.5)), where N is the number of documents and n how many contain the word. A word in more than half the documents would get a negative idf, so rank-bm25 replaces that with a small positive floor: 0.25 times the average idf.

A worked example, for the query E217. After tokenize, the article "Error E217 when downloading" has dl = 16 words and contains e217 twice (title and text), so tf = 2. Only that one article of N = 44 contains it: idf = ln(43.5 / 1.5) = ln(29) = 3.367. The average length is avgdl = 18.32. So the score is 3.367 × 2 × 2.5 / (2 + 1.5 × (0.25 + 0.75 × 16 / 18.32)) = 3.367 × 5 / 3.358 = 5.014. That is exactly the number you will see below.

Tokenizing decides what a "word" is: lowercase, runs of letters and digits, minus filler words. It matters more than the formula: e-book becomes e and book, so a user typing ebook does not match. Real engines add stemming ("ships" matches "ship") and language analyzers.

Two more files: systems.py lists every search by name, and builds each one only when it is first used (no embedding calls when you only want keywords). search.py is the command-line tool; it does not change again in this lab.

keywords.py
import re

from rank_bm25 import BM25Okapi

from corpus import doc_text

STOP_WORDS = {
    "a", "an", "and", "are", "be", "can", "do", "does", "for", "how", "i", "in", "is", "it",
    "me", "my", "not", "of", "on", "or", "the", "to", "what", "when", "where", "will", "with", "you", "your",
}


def tokenize(text: str) -> list[str]:
    """Lowercase words and numbers, without filler words. Repeats are kept: BM25 counts them."""
    return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP_WORDS]


class BM25Search:
    def __init__(self, docs: list[dict]):
        self.ids = [d["id"] for d in docs]
        self.bm25 = BM25Okapi([tokenize(doc_text(d)) for d in docs])

    def search(self, query: str, k: int = 5) -> list[tuple[str, float]]:
        """The k best documents as (id, score), best first. Documents with no query word are left out."""
        scores = self.bm25.get_scores(tokenize(query))
        order = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
        return [(self.ids[i], float(scores[i])) for i in order[:k] if scores[i] > 0]
  1. The package is called rank-bm25; the module you import is rank_bm25. Python names cannot contain -.line 3
  2. A set literal {...}: like a HashSet, with fast "is this in it?" checks. BM25 already gives common words a low idf; removing them also keeps them from adding noise.line 7
  3. Returns a **list**, not a set: BM25 needs to count repeats (tf).line 13
  4. re.findall returns every match of the regex: runs of letters and digits. r"..." is a raw string (backslashes are not escapes). The [... for w in ... if ...] around it is a list comprehension, like stream().filter(...).toList().line 15
  5. BM25Okapi is the classic BM25. It takes the corpus already split into words, one list per document, and computes idf and the lengths once, up front.line 21
  6. One score per document, in corpus order, as a NumPy array. Documents with none of the query words get 0.line 25
  7. The document positions sorted by score, highest first. key=lambda i: scores[i] is Comparator.comparing(i -> scores[i]). Python's sort is stable, so ties keep the file order.line 26
  8. Leave out documents with no query word at all. Keyword search can return fewer than k results, or none.line 27
systems.py
from functools import cache

from corpus import load_docs
from keywords import BM25Search


@cache
def docs() -> list[dict]:
    return load_docs()


@cache
def keyword() -> BM25Search:
    return BM25Search(docs())


# name -> function that builds that search (only when it is first used)
SYSTEMS = {"keyword": keyword}
DEFAULT = ["keyword"]
  1. @cache remembers a function's result: the first call runs it, every later call returns the same object. Here that makes each search a lazily created singleton.line 1
  2. Builds the BM25 index over all articles. -> BM25Search is the return type hint.line 13
  3. A dict from a name to a **function** (not called yet: no parentheses). SYSTEMS["keyword"]() builds or fetches the search. Later steps add entries here.line 18
  4. Which searches the evaluation in step 5 runs when you name none.line 19
search.py
import argparse
import sys
import time

import openai

from config import settings
from llm import friendly
from systems import SYSTEMS, docs

parser = argparse.ArgumentParser(description="Search the help articles.")
parser.add_argument("query")
parser.add_argument("--mode", choices=list(SYSTEMS), default="keyword")
parser.add_argument("-k", type=int, default=5, help="how many results")
args = parser.parse_args()

s = settings()
models = [s.embed_model, s.model] if args.mode == "hybrid+llm" else [s.embed_model]
titles = {d["id"]: d["title"] for d in docs()}
try:
    system = SYSTEMS[args.mode]()
    start = time.perf_counter()
    results = system.search(args.query, args.k)
    ms = (time.perf_counter() - start) * 1000
except openai.OpenAIError as e:
    sys.exit(friendly(e, models))

print(f"{args.mode}: {args.query!r} ({ms:.0f} ms)")
if not results:
    print("  (nothing found)")
for n, (doc_id, score) in enumerate(results, start=1):
    print(f"{n:>3}. {score:8.4f}  {doc_id:<22} {titles[doc_id]}")
  1. argparse is the standard library's command-line parser: it reads sys.argv, checks it and prints --help for you.line 11
  2. A positional argument: the text to search for.line 12
  3. --mode must be one of the names in SYSTEMS. list(a_dict) gives its keys.line 13
  4. Which Ollama models this mode needs, for the error message: the embedding model, plus the chat model for hybrid+llm (step 8). Keyword search needs none and never fails this way.line 18
  5. A dict comprehension: id to title, to print readable results.line 19
  6. Look up the builder and call it. Building happens outside the timer, so the milliseconds are the search alone.line 21
  7. OpenAIError is the base class of every SDK error. The keyword search never raises it; the vector search (next step) can.line 25
  8. !r prints the value with repr(): strings appear in quotes, so you see exactly what was searched.line 28
  9. enumerate gives (number, item) pairs, counting from 1. (doc_id, score) unpacks each item. :>3, :8.4f and :<22 are widths and alignments, like %3d, %8.4f and %-22s in String.format.line 31
Run
uv run search.py "E217"
uv run search.py "stop my monthly plan"
You should see
keyword: 'E217' (0 ms)
  1.   5.0144  error-e217             Error E217 when downloading
keyword: 'stop my monthly plan' (0 ms)
  (nothing found)
Why this way? BM25 is precise and very fast: scoring 44 articles takes well under a millisecond, and real engines score millions with an inverted index (a map from each word to the documents that contain it). But it only sees words. "stop my monthly plan" shares no word with "End your Reading Club membership", so it finds nothing at all. That is the gap vector search fills next.
Stuck on this step?
My E217 score is not 5.0144
The score depends on every article (through N, idf and avgdl) and on STOP_WORDS. Compare data/docs.jsonl and keywords.py with this page: keyword search uses no model, so it must match exactly.
ModuleNotFoundError: No module named 'rank_bm25'
You ran python search.py outside the project environment, or skipped uv add. Use uv run search.py, which always uses the project's packages.
4

Vector search with embeddings

The lab 5 search by meaning, as a second search with the same `search(query, k)` shape.

embedder.py is lab 5's, unchanged in what it does: it sends texts to the embeddings API in batches, adds the search_document: and search_query: prefixes that nomic-embed-text was trained with, and scales every vector to length 1, so a dot product is the cosine similarity.

vectors.py embeds all articles once and saves the vectors in index/. Next to them it saves a key: a SHA-256 hash of the model name and every article text. On the next run, if the key matches, it loads the saved vectors and sends no request; if you edit an article or change EMBED_MODEL, the key changes and it embeds again. (Lab 5 cached each text separately; one key for the whole set is simpler and enough here.)

embedder.py
import numpy as np

DOC_PREFIX = "search_document: "
QUERY_PREFIX = "search_query: "


def normalize(v: np.ndarray) -> np.ndarray:
    """Scale every row to length 1, so a dot product is the cosine similarity."""
    norms = np.linalg.norm(v, axis=-1, keepdims=True)
    return v / np.where(norms == 0, 1, norms)


class Embedder:
    def __init__(self, client, model: str, batch_size: int = 16):
        self.client = client
        self.model = model
        self.batch_size = batch_size

    def embed(self, texts: list[str]) -> np.ndarray:
        """One row per text, in the same order, each of length 1."""
        rows = []
        for start in range(0, len(texts), self.batch_size):
            batch = texts[start:start + self.batch_size]
            resp = self.client.embeddings.create(model=self.model, input=batch)
            for item in sorted(resp.data, key=lambda d: d.index):
                rows.append(item.embedding)
        return normalize(np.array(rows, dtype=np.float32))

    def embed_documents(self, texts: list[str]) -> np.ndarray:
        return self.embed([DOC_PREFIX + t for t in texts])

    def embed_query(self, text: str) -> np.ndarray:
        return self.embed([QUERY_PREFIX + text])[0]
  1. The task instructions nomic-embed-text expects. Leave them out and results get worse. Other models use other instructions or none.line 3
  2. The length of each row. keepdims=True keeps the result as a column so the division on the next line works row by row (NumPy "broadcasting").line 9
  3. Replaces a zero length with 1, so an all-zero vector cannot cause a division by zero.line 10
  4. range(0, 44, 16) gives 0, 16 and 32: the start of each batch, like for (start = 0; start < 44; start += 16).line 22
  5. Each result carries the index of its input text. Sorting by it guarantees row 5 is text 5, whatever order the server used.line 25
  6. A query is one text: embed a list of one and take row [0], a 1-D array of 768 numbers.line 32
vectors.py
import hashlib
import json
from pathlib import Path

import numpy as np

from corpus import doc_text
from embedder import Embedder


class VectorSearch:
    def __init__(self, docs: list[dict], embedder: Embedder, folder: str = "index"):
        self.ids = [d["id"] for d in docs]
        self.embedder = embedder
        self.vectors = self._load_or_build([doc_text(d) for d in docs], Path(folder))

    def _load_or_build(self, texts: list[str], folder: Path) -> np.ndarray:
        """Reuse saved vectors when the model and every text are unchanged; otherwise embed again."""
        key = hashlib.sha256(json.dumps([self.embedder.model, texts]).encode()).hexdigest()
        vec_file, key_file = folder / "vectors.npy", folder / "key.txt"
        if key_file.exists() and key_file.read_text() == key:
            return np.load(vec_file)
        vectors = self.embedder.embed_documents(texts)
        folder.mkdir(exist_ok=True)
        np.save(vec_file, vectors)
        key_file.write_text(key)
        return vectors

    def search(self, query: str, k: int = 5) -> list[tuple[str, float]]:
        """The k most similar documents as (id, cosine similarity), best first."""
        scores = self.vectors @ self.embedder.embed_query(query)
        order = np.argsort(-scores, kind="stable")[:k]
        return [(self.ids[i], float(scores[i])) for i in order]
  1. A fingerprint of the model name plus every text. json.dumps turns the list into one string, .encode() into bytes, and .hexdigest() gives 64 hex characters. Any change to any article gives a different key.line 19
  2. Two assignments in one line. folder / "vectors.npy" joins paths: Path overloads /, like Path.resolve in Java.line 20
  3. Same key: load the saved array and skip the embedding calls entirely.line 22
  4. np.save writes NumPy's .npy format: a small header with the shape and type, then the raw numbers.line 25
  5. @ is matrix multiplication: a (44 × 768) table times a 768-long query gives 44 dot products, one cosine similarity per article, in one line.line 31
  6. argsort returns the positions that would sort the array, smallest first; negating the scores puts the highest first. kind="stable" keeps ties in file order. [:k] keeps the first k.line 32
  7. float(...) turns NumPy's number type into a plain Python float, so it prints and compares like any other number.line 33
systems.py 9 new or changed lines
from functools import cache

from config import settings
from corpus import load_docs
from embedder import Embedder
from keywords import BM25Search
from llm import make_client
from vectors import VectorSearch


@cache
def docs() -> list[dict]:
    return load_docs()


@cache
def keyword() -> BM25Search:
    return BM25Search(docs())


@cache
def vector() -> VectorSearch:
    return VectorSearch(docs(), Embedder(make_client(), settings().embed_model))


# name -> function that builds that search (only when it is first used)
SYSTEMS = {"keyword": keyword, "vector": vector}
DEFAULT = ["keyword", "vector"]
  1. The first call embeds the 44 articles (or loads them from index/). Later calls return the same object, thanks to @cache.line 22
  2. Now two searches, so --mode vector works.line 27
Run
uv run search.py "stop my monthly plan" --mode vector
uv run search.py "it says wait 15 minutes" --mode vector
uv run search.py "it says wait 15 minutes"
You should seeyour text will differ: the model writes it
vector: 'stop my monthly plan' (72 ms)
  1.   0.5286  end-membership         End your Reading Club membership
  2.   0.5111  card-declined          Card declined at checkout
  3.   0.4983  close-account          Close your account
  4.   0.4848  cancel-an-order        Cancel an order
  5.   0.4847  reading-club           Reading Club membership
vector: 'it says wait 15 minutes' (76 ms)
  1.   0.6327  missing-parcel         An order has not arrived
  2.   0.5984  contact-support        Contact support
  3.   0.5953  reset-password         Reset your password
  4.   0.5934  price-drop             Price drops after you buy
  5.   0.5924  delivery-times         Delivery times
keyword: 'it says wait 15 minutes' (0 ms)
  1.   8.8849  error-e330             Error E330 when signing in
  2.   3.1694  student-discount       Student discount
  3.   2.6581  reset-password         Reset your password
Why this way? Each method fails where the other wins. Vector search finds the membership article that keyword search could not see. But "wait 15 minutes" means "waiting" to the embedding model, so it returns articles about waiting for parcels and replies; the E330 article that literally says "Wait 15 minutes" is not in its top 5. BM25 puts it first, because 15, minutes and wait are rare words that article shares with the query. The first query of a run is slower: it builds the index or loads it from disk (outside the timer) and warms up the model.
Stuck on this step?
A model was not found. Check ollama list, then: ollama pull nomic-embed-text
That is friendly() at work: pull the model, check the name with ollama list, and run the command again.
ValueError: matmul: Input operand 1 has a mismatch in its core dimension
The saved vectors came from a different server that uses the same model name, with another vector size. Delete the index folder and run again.
My scores and order differ a little from the ones above
Expected: they depend on the model build and your hardware. The keyword lines must match exactly.
5

Measure before you improve: recall@5, MRR and latency

One table that scores every search on the 24 labelled questions, so every later change is a number.

recall@k asks: of the articles that answer this question, what share is in the top k? With one right answer it is 1 or 0; with two, finding one of them gives 0.5. We use k = 5, about what a RAG prompt holds. The table shows the average over all questions.

MRR (mean reciprocal rank) asks: how high is the first right answer? First place scores 1, second 1/2, third 1/3, not in the top k scores 0; then average. Recall says "it is in there somewhere"; MRR says "it is near the top", which matters because people (and language models) pay most attention to the first results.

ms/query is the median time per question. The median ignores one slow outlier, like the first call to a cold model. The evaluation also runs one "warm up" search before timing, so loading models is not counted.

evaluate() takes the search as a function parameter, so the same code measures every method. It is the last version of evaluate.py: when you add a search to SYSTEMS and DEFAULT, it appears in the table.

metrics.py
import statistics
import time


def recall_at_k(found: list[str], relevant: list[str], k: int) -> float:
    """Share of the relevant documents that appear in the top k."""
    return len(set(found[:k]) & set(relevant)) / len(relevant)


def reciprocal_rank(found: list[str], relevant: list[str], k: int) -> float:
    """1 / position of the first relevant document in the top k, or 0 if there is none."""
    for position, doc_id in enumerate(found[:k], start=1):
        if doc_id in relevant:
            return 1 / position
    return 0.0


def evaluate(search, queries: list[dict], k: int = 5) -> dict:
    """Run every query through `search` and average the scores. Also times each query."""
    recalls, ranks, millis, misses = [], [], [], []
    for q in queries:
        start = time.perf_counter()
        found = [doc_id for doc_id, _ in search(q["query"], k)]
        millis.append((time.perf_counter() - start) * 1000)
        recalls.append(recall_at_k(found, q["relevant"], k))
        ranks.append(reciprocal_rank(found, q["relevant"], k))
        if recalls[-1] < 1:
            misses.append(q["query"])
    return {
        "recall": statistics.mean(recalls),
        "mrr": statistics.mean(ranks),
        "ms": statistics.median(millis),
        "misses": misses,
    }
  1. found[:k] is the first k ids. set(a) & set(b) is the intersection (retainAll): the relevant ids that were found. Divided by how many relevant ids there are.line 5
  2. Walks the top k from position 1. The first relevant hit returns 1 / position straight away.line 10
  3. search is any function taking (query, k) and returning (id, score) pairs. Python has no interface for this; anything with that shape works, like passing a BiFunction in Java.line 18
  4. Four empty lists in one line.line 20
  5. perf_counter() is a precise clock for durations, like System.nanoTime() but in seconds. Times 1000 gives milliseconds.line 22
  6. _ is the usual name for a value you ignore (the score).line 23
  7. [-1] is the last element. A question counts as a miss when not every right article was found.line 27
  8. statistics is in the standard library: mean and median of a list.line 32
evaluate.py
import argparse
import sys

import openai

from config import settings
from corpus import load_queries
from llm import friendly
from metrics import evaluate
from systems import DEFAULT, SYSTEMS


def unusable(search) -> int:
    """LLM replies this search had to ignore so far (0 for searches without an LLM reranker)."""
    return getattr(getattr(search, "reranker", None), "unusable", 0)


parser = argparse.ArgumentParser(description="Measure every search on the labelled queries.")
parser.add_argument("names", nargs="*", help=f"which searches (default: {' '.join(DEFAULT)})")
parser.add_argument("-k", type=int, default=5)
args = parser.parse_args()
names = args.names or DEFAULT
unknown = [n for n in names if n not in SYSTEMS]
if unknown:
    sys.exit(f"Unknown search {unknown[0]!r}. Choose from: {', '.join(SYSTEMS)}")

s = settings()
models = [s.embed_model, s.model] if "hybrid+llm" in names else [s.embed_model]
queries = load_queries()
print(f"{len(queries)} labelled queries, k = {args.k}\n")
print(f"{'search':<15}{f'recall@{args.k}':>10}{'MRR':>8}{'ms/query':>10}")
results = {}
try:
    for name in names:
        search = SYSTEMS[name]()
        search.search("warm up", args.k)  # load models and the index before timing
        before = unusable(search)
        results[name] = r = evaluate(search.search, queries, args.k)
        print(f"{name:<15}{r['recall']:>10.2f}{r['mrr']:>8.2f}{r['ms']:>10.1f}")
        if unusable(search) > before:
            print(f"{'':<15}({unusable(search) - before} LLM replies unusable: kept the hybrid order)")
except openai.OpenAIError as e:
    sys.exit(friendly(e, models))

for name, r in results.items():
    if r["misses"]:
        print(f"\n{name} missed: " + "; ".join(r["misses"]))
  1. Only the LLM reranker (step 8) has an unusable counter. getattr(obj, "name", default) reads an attribute by name and returns the default when it does not exist, so this works for every search.line 13
  2. Zero or more search names: uv run evaluate.py hybrid hybrid+rerank. We check the names ourselves below: with nargs="*" and a default list, Python 3.12's argparse rejects its own default if you also pass choices.line 19
  3. No names given (an empty list counts as false): use DEFAULT from systems.py.line 22
  4. The models these searches need, for friendly(): the chat model only when hybrid+llm is in the list.line 28
  5. An f-string inside an f-string, so the header says recall@5 or recall@20. :>10 right-aligns in 10 characters.line 31
  6. One throwaway search first, so loading a model or the index is not counted in the timing.line 36
  7. A chained assignment: both names point to the same dict. search.search (no parentheses) passes the method itself as the function to call.line 38
  8. Only printed for the LLM reranker, when some replies could not be used (step 8).line 40
  9. Joins the missed questions into one line. Read them: the misses tell you what to fix.line 47
Run
uv run evaluate.py
You should seeyour text will differ: the model writes it
24 labelled queries, k = 5

search           recall@5     MRR  ms/query
keyword              0.69    0.64       0.0
vector               0.88    0.64      12.8

keyword missed: stop my monthly plan; the book I ordered never showed up; the letters are too small; talk to a human; how much is postage; do you ship to Canada; share books with my kids; payment refused with E104

vector missed: the book I ordered never showed up; talk to a human; E140
Why this way? Read the two miss lists. Keyword search misses the paraphrases ("stop my monthly plan", "the letters are too small"). Vector search gets those, but misses E140: to an embedding model, E104, E140 and E410 look almost the same, and with hundreds of look-alike codes that only gets worse. Two questions ("the book I ordered never showed up", "talk to a human") beat both, so fusion alone will not fix them. And look at MRR: vector search finds the right article as often as recall says, but often not first (0.64). The keyword row must match exactly; the vector row comes from the model, so one question more or less is normal. Keyword search shows 0.0 ms because it takes a few hundredths of a millisecond; vector search pays for one embedding call per query (about 13 ms on an Apple-silicon Mac).
Stuck on this step?
The keyword row differs
Keyword search uses no model, so it must match: compare data/, STOP_WORDS and tokenize with this page.
Unknown search 'hybrid'
You are ahead of the lab: hybrid arrives in the next step.
6

Hybrid search: merge both lists with Reciprocal Rank Fusion

Run both searches and combine their rankings into one list that keeps the best of each.

You cannot simply add the scores: a BM25 score of 8.9 and a cosine of 0.63 are on different scales, and the scales change with every query. Reciprocal Rank Fusion (Cormack, Clarke and Büttcher, 2009) ignores the scores and uses only the positions: every list gives each of its documents 1 / (k + rank), and you add up what each document collects. rank starts at 1, and k = 60 is the value from the paper, still the usual default.

A worked example (rrf_demo.py prints it). Keyword search ranks error-e104, ways-to-pay, card-declined; vector search ranks card-declined, error-e104, refunds. error-e104 gets 1/61 + 1/62 = 0.03252 (1st and 2nd). card-declined gets 1/63 + 1/61 = 0.03227 (3rd and 1st). ways-to-pay only gets 1/62 = 0.01613, refunds only 1/63 = 0.01587. Being found by both searches roughly doubles a score, so agreement wins.

What k does: with k = 60, first place earns 1/61 = 0.0164 and tenth place 1/70 = 0.0143, a gentle slope, so a document near the top of both lists beats one at the very top of only one. A small k (like 1) makes first place count far more. Keep 60 unless your measurements say otherwise.

HybridSearch asks each search for its top depth = 20, fuses, and cuts to k. Both lists must be deep enough: a right answer at rank 12 in one list can still win if the other list ranks it well.

fusion.py
def rrf(rankings: list[list[str]], k: int = 60) -> list[tuple[str, float]]:
    """Reciprocal Rank Fusion: every list gives each document 1 / (k + rank); add them up, best first."""
    scores: dict[str, float] = {}
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking, start=1):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1 / (k + rank)
    return sorted(scores.items(), key=lambda pair: pair[1], reverse=True)


class HybridSearch:
    def __init__(self, keyword, vector, depth: int = 20):
        self.keyword = keyword
        self.vector = vector
        self.depth = depth

    def search(self, query: str, k: int = 5) -> list[tuple[str, float]]:
        """Top `depth` from each search, fused with RRF, cut to k."""
        kw = [doc_id for doc_id, _ in self.keyword.search(query, self.depth)]
        vec = [doc_id for doc_id, _ in self.vector.search(query, self.depth)]
        return rrf([kw, vec])[:k]
  1. rankings is a list of ranked id lists, best first. Scores are not needed, only the order.line 1
  2. A type hint on a variable: an empty dict from id to fused score, like new HashMap<String, Double>().line 3
  3. Ranks count from 1, as in the formula.line 5
  4. get with a default is getOrDefault: a document seen for the first time starts at 0.line 6
  5. .items() gives (id, score) pairs; sorting by pair[1] (the score), highest first. Ties keep the order in which documents were first seen.line 7
  6. The same search(query, k) shape as the other two, so search.py and evaluate.py work with it unchanged.line 10
  7. Only the ids, in order. A list comprehension drops the scores.line 18
  8. Fuse the two lists and keep the first k. More lists (a second embedding model, a title-only search) would just be more items in this list.line 20
rrf_demo.py
from fusion import rrf

keyword = ["error-e104", "ways-to-pay", "card-declined"]
vector = ["card-declined", "error-e104", "refunds"]

print("rank  keyword        vector")
for rank, (a, b) in enumerate(zip(keyword, vector), start=1):
    print(f"{rank:>4}  {a:<14} {b}")

print("\nRRF with k = 60: score = sum of 1 / (60 + rank)")
for doc_id, score in rrf([keyword, vector]):
    parts = [f"1/{60 + r.index(doc_id) + 1}" for r in (keyword, vector) if doc_id in r]
    print(f"  {doc_id:<14} {' + '.join(parts):<13} = {score:.5f}")
  1. Two made-up rankings for "payment refused with E104", so the numbers are easy to check by hand.line 3
  2. zip walks two lists side by side, like a loop over two indexes at once. (a, b) unpacks each pair.line 7
  3. Rebuilds the formula for display: r.index(doc_id) is the 0-based position (indexOf), so the rank is that plus 1. if doc_id in r skips a list that does not contain it.line 12
  4. Joins the parts with + , like String.join(" + ", parts).line 13
systems.py 6 new or changed lines
from functools import cache

from config import settings
from corpus import load_docs
from embedder import Embedder
from fusion import HybridSearch
from keywords import BM25Search
from llm import make_client
from vectors import VectorSearch


@cache
def docs() -> list[dict]:
    return load_docs()


@cache
def keyword() -> BM25Search:
    return BM25Search(docs())


@cache
def vector() -> VectorSearch:
    return VectorSearch(docs(), Embedder(make_client(), settings().embed_model))


@cache
def hybrid() -> HybridSearch:
    return HybridSearch(keyword(), vector(), depth=20)


# name -> function that builds that search (only when it is first used)
SYSTEMS = {"keyword": keyword, "vector": vector, "hybrid": hybrid}
DEFAULT = ["keyword", "vector", "hybrid"]
  1. Reuses the two cached searches: no second index, no extra embedding of the articles. Each query now runs BM25 (fast) and one embedding call.line 28
Run
uv run rrf_demo.py
uv run search.py "it says wait 15 minutes" --mode hybrid
uv run evaluate.py
You should seeyour text will differ: the model writes it
rank  keyword        vector
   1  error-e104     card-declined
   2  ways-to-pay    error-e104
   3  card-declined  refunds

RRF with k = 60: score = sum of 1 / (60 + rank)
  error-e104     1/61 + 1/62   = 0.03252
  card-declined  1/63 + 1/61   = 0.03227
  ways-to-pay    1/62          = 0.01613
  refunds        1/63          = 0.01587
hybrid: 'it says wait 15 minutes' (14 ms)
  1.   0.0328  error-e330             Error E330 when signing in
  2.   0.0317  reset-password         Reset your password
  3.   0.0298  student-discount       Student discount
  4.   0.0161  missing-parcel         An order has not arrived
  5.   0.0156  refunds                Refunds for printed books
24 labelled queries, k = 5

search           recall@5     MRR  ms/query
keyword              0.69    0.64       0.0
vector               0.88    0.64      12.8
hybrid               0.92    0.79      14.3

keyword missed: stop my monthly plan; the book I ordered never showed up; the letters are too small; talk to a human; how much is postage; do you ship to Canada; share books with my kids; payment refused with E104

vector missed: the book I ordered never showed up; talk to a human; E140

hybrid missed: the book I ordered never showed up; talk to a human
Why this way? Both numbers went up. Recall 0.88 to 0.92: E140 is back in the top 5, because keyword search finds the exact code and RRF keeps it. MRR 0.64 to 0.79: articles that both searches rank well rise to the top, like "Error E330" for "wait 15 minutes", now first. Look at the scores though: E330 and "Reset your password" are 0.0328 against 0.0317, almost a tie. RRF only sees ranks, never the text. And the two questions both searches missed are still missed, because fusion can only reorder what at least one search returns. Getting the right article to the top, reliably, needs a model that reads the question and the article together: a reranker.
Stuck on this step?
uv run rrf_demo.py prints different numbers
It uses no model, so it must match exactly. Check fusion.py: the rank must start at 1 (start=1), and the formula is 1 / (k + rank).
7

Rerank the top 20 with a cross-encoder

Let a small model read the question and each candidate together, and reorder the hybrid results.

Embedding search is a bi-encoder: the question and each article are turned into vectors separately, and compared afterwards. That is what makes it fast (articles are embedded once, in advance), but the model never sees the question and the article at the same time.

A cross-encoder reads both together, as one input, and outputs one relevance score. It can notice that "wait 15 minutes" matches the sentence "Wait 15 minutes, or reset your password" in an error article. It is far more accurate, and far too slow to run on every article: it needs one model run per (question, article) pair, at query time. So you use it as a second stage: a cheap search fetches 20 candidates, the cross-encoder reorders only those.

We use cross-encoder/ms-marco-MiniLM-L6-v2: a 6-layer, 22-million-parameter model trained on MS MARCO (real Bing search queries and the passages that answered them, in English). It is about 90 MB and fast on a laptop CPU. Its scores are raw numbers (higher is more relevant, often from about -11 to +10), useful for ordering, not as probabilities. Older code calls it cross-encoder/ms-marco-MiniLM-L-6-v2; Hugging Face redirects that old name to this one.

It runs with sentence-transformers, which is built on PyTorch. uv add below installs both. On a Mac that is a download of about 200 MB; on Linux, PyTorch from PyPI also pulls about 3 GB of NVIDIA GPU libraries (see Stuck below for the CPU-only version). The model itself downloads from Hugging Face on first use and is cached in ~/.cache/huggingface.

rerank.py
from corpus import doc_text


class CrossEncoderReranker:
    def __init__(self, docs: list[dict], model_name: str, model=None):
        self.texts = {d["id"]: doc_text(d) for d in docs}
        if model is None:
            from sentence_transformers import CrossEncoder  # imported here: loading PyTorch takes seconds

            model = CrossEncoder(model_name, device="cpu")
        self.model = model

    def rerank(self, query: str, ids: list[str]) -> list[tuple[str, float]]:
        """Score every (query, document) pair together, best first."""
        if not ids:
            return []
        scores = self.model.predict([(query, self.texts[i]) for i in ids])
        ranked = sorted(zip(ids, scores), key=lambda pair: pair[1], reverse=True)
        return [(doc_id, float(score)) for doc_id, score in ranked]


class RerankedSearch:
    def __init__(self, first_stage, reranker, candidates: int = 20):
        self.first_stage = first_stage
        self.reranker = reranker
        self.candidates = candidates

    def search(self, query: str, k: int = 5) -> list[tuple[str, float]]:
        """Fetch `candidates` documents cheaply, then let the reranker put them in order."""
        ids = [doc_id for doc_id, _ in self.first_stage.search(query, self.candidates)]
        return self.reranker.rerank(query, ids)[:k]
  1. model=None is an optional parameter. The real program passes nothing and gets the real model; the tests pass a fake (dependency injection), so they never load PyTorch.line 5
  2. Id to the full text, the same doc_text the other searches use.line 6
  3. An import inside a function runs only when that line runs. Importing PyTorch takes a few seconds, so keyword-only runs and the tests never pay for it.line 8
  4. Downloads the model on first use (then loads it from the cache). device="cpu": without it, sentence-transformers picks a GPU when it finds one (NVIDIA, or Apple's MPS). For a model this small the CPU is fast and behaves the same everywhere.line 10
  5. No candidates (a query nothing matched): return early instead of calling the model with an empty list.line 15
  6. One score per (question, text) pair, in the same order, as a NumPy array. All 20 pairs go through the model in one batch.line 17
  7. Pairs each id with its score; sorted by the score, highest first.line 18
  8. Two stages behind the usual search(query, k) shape: any search for candidates, any reranker to order them.line 22
  9. Ask the first stage for 20, not 5. The reranker can only reorder what it is given: an article that is not among the candidates cannot come back.line 30
  10. Rerank all candidates, keep the best k.line 31
systems.py 7 new or changed lines
from functools import cache

from config import settings
from corpus import load_docs
from embedder import Embedder
from fusion import HybridSearch
from keywords import BM25Search
from llm import make_client
from rerank import CrossEncoderReranker, RerankedSearch
from vectors import VectorSearch


@cache
def docs() -> list[dict]:
    return load_docs()


@cache
def keyword() -> BM25Search:
    return BM25Search(docs())


@cache
def vector() -> VectorSearch:
    return VectorSearch(docs(), Embedder(make_client(), settings().embed_model))


@cache
def hybrid() -> HybridSearch:
    return HybridSearch(keyword(), vector(), depth=20)


@cache
def hybrid_rerank() -> RerankedSearch:
    reranker = CrossEncoderReranker(docs(), settings().rerank_model)
    return RerankedSearch(hybrid(), reranker, candidates=20)


# name -> function that builds that search (only when it is first used)
SYSTEMS = {"keyword": keyword, "vector": vector, "hybrid": hybrid, "hybrid+rerank": hybrid_rerank}
DEFAULT = ["keyword", "vector", "hybrid", "hybrid+rerank"]
  1. Hybrid search for 20 candidates, then the cross-encoder. Loading the model happens here, once.line 34
  2. The evaluation now has four rows.line 41
Run
uv add "sentence-transformers>=6.3.0,<7"
uv run search.py "it says wait 15 minutes" --mode hybrid+rerank
uv run evaluate.py
You should seeyour text will differ: the model writes it
Resolved 52 packages in 1.10s
Installed 34 packages in 2.3s
 + sentence-transformers==6.3.0
 + torch==2.15.0
 + transformers==5.24.1
 ...
hybrid+rerank: 'it says wait 15 minutes' (219 ms)
  1.   2.4936  error-e330             Error E330 when signing in
  2. -10.3300  reset-password         Reset your password
  3. -10.6558  refunds                Refunds for printed books
  4. -10.7696  ebook-refunds          Refunds for e-books
  5. -10.7919  delivery-times         Delivery times
24 labelled queries, k = 5

search           recall@5     MRR  ms/query
keyword              0.69    0.64       0.0
vector               0.88    0.64      12.8
hybrid               0.92    0.79      14.3
hybrid+rerank        1.00    0.95      44.8

keyword missed: stop my monthly plan; the book I ordered never showed up; the letters are too small; talk to a human; how much is postage; do you ship to Canada; share books with my kids; payment refused with E104

vector missed: the book I ordered never showed up; talk to a human; E140

hybrid missed: the book I ordered never showed up; talk to a human
Why this way? Look at the scores in the single search: the E330 article scores 2.49 and everything else is below -10. The cross-encoder is not just reordering, it is sure. In the table, recall reaches 1.00 and MRR jumps from 0.79 to 0.95: right answers are now found and near the top. The price is in the last column: about 30 ms more per query on an Apple-silicon Mac (and several times that on a small cloud CPU), for 20 model runs. Even the two questions both searches missed are now found, because the reranker reads all 20 candidates, not just the top 5. Step 9 measures that trade-off properly.
Stuck on this step?
Linux: uv add downloads several GB (nvidia-cublas, nvidia-cudnn-cu13, ...)
PyPI's PyTorch for Linux includes GPU libraries. For a CPU-only install, add this to pyproject.toml and run uv sync: toml [tool.uv.sources] torch = [{ index = "pytorch-cpu", marker = "sys_platform == 'linux'" }] [[tool.uv.index]] name = "pytorch-cpu" url = "https://download.pytorch.org/whl/cpu" explicit = true macOS and Windows already get a CPU build from PyPI.
Intel Mac: torch has no wheel for this platform
PyTorch stopped publishing builds for Intel Macs after version 2.2, and recent sentence-transformers needs newer ones. Run the reranker on an Apple-silicon Mac or Linux, or use the LLM reranker from step 8 instead.
Lines like Warning: You are sending unauthenticated requests to the HF Hub and Loading weights: 100%
Normal. Hugging Face prints them while it downloads or loads the model. The model is public: no token needed.
OSError: We couldn't connect to 'https://huggingface.co' to load the files
No internet on first use, or a company proxy blocks huggingface.co. Download once on a network that works; after that it loads from ~/.cache/huggingface. Set HF_HUB_OFFLINE=1 to stop it from checking online at all.
The first run takes 10 to 20 seconds
Importing PyTorch and loading the model. search.py times only the search itself; evaluate.py warms up first.
8

An LLM as the reranker

Rerank with a chat model and one prompt instead of a cross-encoder, and compare honestly.

Any model that can judge relevance can rerank. A chat model is the obvious candidate: you already run one for RAG, it needs no extra library, and a big hosted model is a strong judge. This is listwise reranking: one call shows the model the question and all candidates and asks for the ids in order. (The pointwise alternative scores each candidate in its own call: simpler to parse, but one call per candidate.)

The reply must be machine-readable, so the request uses JSON Schema output from lab 3: the schema says "an object with a list ids, where every item is one of these candidate ids" (enum). Ollama 0.5 and newer constrain the reply to that shape. The code still checks it: it keeps only known ids, drops repeats, appends anything the model left out in the old order, and if the reply cannot be used at all, keeps the hybrid order and counts it in unusable. A reranker must never make search fail.

We send only the top 10 candidates: every candidate makes the prompt longer, and on a laptop the prompt is what makes a local model slow.

rerank.py 38 new or changed lines
import json

from corpus import doc_text


class CrossEncoderReranker:
    def __init__(self, docs: list[dict], model_name: str, model=None):
        self.texts = {d["id"]: doc_text(d) for d in docs}
        if model is None:
            from sentence_transformers import CrossEncoder  # imported here: loading PyTorch takes seconds

            model = CrossEncoder(model_name, device="cpu")
        self.model = model

    def rerank(self, query: str, ids: list[str]) -> list[tuple[str, float]]:
        """Score every (query, document) pair together, best first."""
        if not ids:
            return []
        scores = self.model.predict([(query, self.texts[i]) for i in ids])
        ranked = sorted(zip(ids, scores), key=lambda pair: pair[1], reverse=True)
        return [(doc_id, float(score)) for doc_id, score in ranked]


SYSTEM = (
    "You rank help articles for a search engine. You get a question and numbered articles. "
    "Return the ids of all the articles, the one that best answers the question first."
)


class LLMReranker:
    def __init__(self, docs: list[dict], client, model: str):
        self.docs = {d["id"]: d for d in docs}
        self.client = client
        self.model = model
        self.unusable = 0  # replies we could not use, so the old order was kept

    def rerank(self, query: str, ids: list[str]) -> list[tuple[str, float]]:
        """One chat call ranks all candidates. Falls back to the incoming order if the reply is unusable."""
        if not ids:
            return []
        articles = "\n".join(f"[{i}] {self.docs[i]['title']}. {self.docs[i]['text']}" for i in ids)
        schema = {
            "type": "object",
            "properties": {"ids": {"type": "array", "items": {"type": "string", "enum": ids}}},
            "required": ["ids"],
        }
        resp = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": SYSTEM},
                {"role": "user", "content": f"Question: {query}\n\nArticles:\n{articles}"},
            ],
            response_format={"type": "json_schema", "json_schema": {"name": "ranking", "schema": schema}},
            temperature=0,
        )
        try:
            ranked = json.loads(resp.choices[0].message.content or "")["ids"]
            order = list(dict.fromkeys(i for i in ranked if i in ids))
        except (json.JSONDecodeError, KeyError, TypeError):
            self.unusable += 1
            order = []
        order += [i for i in ids if i not in order]
        return [(doc_id, 1 / position) for position, doc_id in enumerate(order, start=1)]


class RerankedSearch:
    def __init__(self, first_stage, reranker, candidates: int = 20):
        self.first_stage = first_stage
        self.reranker = reranker
        self.candidates = candidates

    def search(self, query: str, k: int = 5) -> list[tuple[str, float]]:
        """Fetch `candidates` documents cheaply, then let the reranker put them in order."""
        ids = [doc_id for doc_id, _ in self.first_stage.search(query, self.candidates)]
        return self.reranker.rerank(query, ids)[:k]
  1. New import for parsing the model's JSON reply.line 1
  2. The instructions. Asking for **all** ids keeps the reply complete; the code fills gaps anyway.line 24
  3. A counter the evaluation prints. If it climbs, your model or server does not follow the schema.line 35
  4. One line per candidate: [id] Title. Text. Real ids (not 1, 2, 3) mean the reply can be checked against the candidates directly.line 41
  5. Every item must be one of the candidate ids, so the model cannot invent one. enum is standard JSON Schema.line 44
  6. The JSON Schema output from lab 3: name labels the schema, schema is the dict above.line 53
  7. The most likely tokens every time: a ranking should not change between runs.line 54
  8. json.loads parses the reply; ["ids"] takes the list. Prose instead of JSON raises JSONDecodeError; a missing key, KeyError; another shape (a number, a list, null), TypeError.line 45
  9. Keeps only ids that are candidates and drops repeats, in order. dict.fromkeys(...) keeps the first occurrence of each, like a LinkedHashSet.line 58
  10. Unusable reply: count it, and start from an empty order, so the next line restores the hybrid order.line 60
  11. Anything the model left out goes at the end, in the order the first stage gave.line 62
  12. A listwise ranking has no scores, so the score is 1 for first, 1/2 for second, and so on. Only the order matters.line 63
systems.py 13 new or changed lines
from functools import cache

from config import settings
from corpus import load_docs
from embedder import Embedder
from fusion import HybridSearch
from keywords import BM25Search
from llm import make_client
from rerank import CrossEncoderReranker, LLMReranker, RerankedSearch
from vectors import VectorSearch


@cache
def docs() -> list[dict]:
    return load_docs()


@cache
def keyword() -> BM25Search:
    return BM25Search(docs())


@cache
def vector() -> VectorSearch:
    return VectorSearch(docs(), Embedder(make_client(), settings().embed_model))


@cache
def hybrid() -> HybridSearch:
    return HybridSearch(keyword(), vector(), depth=20)


@cache
def hybrid_rerank() -> RerankedSearch:
    reranker = CrossEncoderReranker(docs(), settings().rerank_model)
    return RerankedSearch(hybrid(), reranker, candidates=20)


@cache
def hybrid_llm() -> RerankedSearch:
    reranker = LLMReranker(docs(), make_client(), settings().model)
    return RerankedSearch(hybrid(), reranker, candidates=10)


# name -> function that builds that search (only when it is first used)
SYSTEMS = {
    "keyword": keyword,
    "vector": vector,
    "hybrid": hybrid,
    "hybrid+rerank": hybrid_rerank,
    "hybrid+llm": hybrid_llm,
}
DEFAULT = ["keyword", "vector", "hybrid", "hybrid+rerank"]  # hybrid+llm is slow: ask for it by name
  1. Hybrid search for 10 candidates, then the chat model from LLM_MODEL.line 40
  2. Not in DEFAULT: 24 chat calls take a while on a laptop. Ask for it by name.line 53
Run
uv run evaluate.py hybrid hybrid+rerank hybrid+llm
You should seeyour text will differ: the model writes it
24 labelled queries, k = 5

search           recall@5     MRR  ms/query
hybrid               0.92    0.79      14.3
hybrid+rerank        1.00    0.95      44.8
hybrid+llm           0.92    0.84    3800.0

hybrid missed: the book I ordered never showed up; talk to a human

hybrid+llm missed: the book I ordered never showed up; talk to a human; ...
Why this way? The hybrid+llm row above is an illustration of the shape, not a measurement: yours depends heavily on the model and the machine. Two things hold in general. The latency is in seconds, not milliseconds: one chat call that reads about 600 tokens of prompt and writes the ids, many times slower than the cross-encoder. And a 3-billion-parameter chat model is a weak judge: it often does no better than hybrid, and can be worse. A large hosted model reranks well, at the price of a paid call per search. The cross-encoder was trained for exactly this job: for most search boxes it is the better choice. The LLM reranker earns its place when you already pay for a strong model, have few queries, or need judgement a small model cannot make.
Stuck on this step?
A line like (24 LLM replies unusable: kept the hybrid order)
The replies were not JSON in the requested shape, so every query kept the hybrid order. Check ollama --version (0.5 or newer is needed for JSON Schema output) and that LLM_MODEL is a chat model you pulled.
A model was not found. Check ollama list, then: ollama pull nomic-embed-text and ollama pull llama3.2:3b
Run ollama list: usually the chat model is missing. Pull it, or set LLM_MODEL in .env to a chat model you have.
It takes minutes
Normal on a CPU: 24 queries, each a full chat call. Try uv run search.py "it says wait 15 minutes" --mode hybrid+llm for one query first.
9

Latency vs quality: how many candidates to rerank?

Measure what each extra candidate costs and buys, and pick the number with data.

Reranking more candidates gives the reranker more chances to find the right article, and costs one more model run per candidate. tradeoff.py runs the same evaluation with the cross-encoder reranking the top 5, 10, 20 and 40 hybrid results, plus hybrid alone as the baseline.

It reuses the objects from systems.py: the same hybrid search and the same loaded cross-encoder, wrapped in a new RerankedSearch for each size. Nothing is loaded twice.

tradeoff.py
import sys

import openai

from config import settings
from corpus import load_queries
from llm import friendly
from metrics import evaluate
from rerank import RerankedSearch
from systems import hybrid, hybrid_rerank

queries = load_queries()
print(f"{'rerank top':<12}{'recall@5':>10}{'MRR':>8}{'ms/query':>10}")
try:
    first_stage = hybrid()
    r = evaluate(first_stage.search, queries, k=5)
    print(f"{'(none)':<12}{r['recall']:>10.2f}{r['mrr']:>8.2f}{r['ms']:>10.1f}")
    reranker = hybrid_rerank().reranker
    for n in (5, 10, 20, 40):
        search = RerankedSearch(first_stage, reranker, candidates=n)
        r = evaluate(search.search, queries, k=5)
        print(f"{n:<12}{r['recall']:>10.2f}{r['mrr']:>8.2f}{r['ms']:>10.1f}")
except openai.OpenAIError as e:
    sys.exit(friendly(e, [settings().embed_model]))
  1. The builder functions from systems.py. Thanks to @cache, calling them again returns the same objects.line 10
  2. The baseline first: hybrid with no reranking.line 15
  3. Borrow the loaded cross-encoder from the hybrid+rerank search instead of loading a second copy.line 18
  4. A tuple of sizes to try. With 40, the fused list is shorter than 40 for most queries (each search gives 20, many overlap), so it reranks all of them.line 19
  5. Only the number of candidates changes between rows. Everything else is the same, so the difference is caused by that number.line 20
Run
uv run tradeoff.py
You should seeyour text will differ: the model writes it
rerank top    recall@5     MRR  ms/query
(none)            0.92    0.79      14.3
5                 0.94    0.94     108.4
10                0.96    0.94     142.4
20                1.00    0.95     197.5
40                1.00    0.95     206.6
Why this way? Read it row by row. Reranking only the top 5 already lifts MRR from 0.79 to 0.94, because the right answer was often in the top 5, just not first; recall cannot change, since the same 5 articles come back. Going to 10 and 20 raises recall, because articles from ranks 6 to 20 can now climb into the top 5. Past 20 nothing improves here, while time keeps growing. That is the pattern to look for on your own data: rerank as many candidates as it takes for recall to stop rising, and no more. On a big corpus that is often 20 to 100; set a time budget too, and fall back to the hybrid order when the reranker is slow or down.
Stuck on this step?
My ms column is very different
Expected: it depends on your CPU and on what else is running. Compare the rows with each other, not with ours. Run it twice: the second run is steadier.
10

Test it with fakes

Unit tests for BM25, the vector cache, RRF, both rerankers and the metrics, with no model and no download.

Each piece depends on something slow through a parameter: the embedder on a client with embeddings.create, the cross-encoder reranker on a model with predict, the LLM reranker on a client with chat.completions.create. A fake only has to look like that ("duck typing": Python checks attributes when the code runs, so no interface or mocking library is needed).

The fake embedder gives deterministic vectors and "understands" a few synonyms, because words like parcel and package add to the same position. The fake cross-encoder scores by shared words. The fake chat client returns whatever reply the test gives it, so you can test a good ranking, a reply with made-up and repeated ids, prose, and the wrong JSON shape.

test_search.py
from types import SimpleNamespace

import pytest

from embedder import Embedder
from fusion import HybridSearch, rrf
from keywords import BM25Search, tokenize
from metrics import evaluate, recall_at_k, reciprocal_rank
from vectors import VectorSearch

DOCS = [
    {"id": "refunds", "title": "Refunds", "text": "We pay your money back within 5 days."},
    {"id": "delivery", "title": "Delivery", "text": "Every parcel ships in 2 days."},
    {"id": "error-e217", "title": "Error E217", "text": "The download stopped. Try again."},
]

# Words that mean the same thing share an axis, so the fake "understands" a few synonyms.
AXES = {"refund": 0, "refunds": 0, "money": 0, "delivery": 1, "parcel": 1, "package": 1, "download": 2}


def fake_vector(text: str) -> list[float]:
    v = [0.0, 0.0, 0.0, 0.1]
    for word in tokenize(text):
        if word in AXES:
            v[AXES[word]] += 1.0
    return v


class FakeEmbeddingsClient:
    """Stands in for OpenAI(): answers embeddings.create and records every request."""

    def __init__(self):
        self.requests = []
        self.embeddings = SimpleNamespace(create=self.create)

    def create(self, **kwargs):
        self.requests.append(kwargs["input"])
        data = [SimpleNamespace(index=i, embedding=fake_vector(t)) for i, t in enumerate(kwargs["input"])]
        return SimpleNamespace(data=data)


def test_tokenize_keeps_codes_and_numbers_and_drops_filler_words():
    assert tokenize("What does E217 mean on my X2?") == ["e217", "mean", "x2"]


def test_bm25_finds_the_exact_code_and_skips_documents_without_query_words():
    results = BM25Search(DOCS).search("E217", k=5)
    assert [doc_id for doc_id, _ in results] == ["error-e217"]


def test_vector_search_finds_a_synonym(tmp_path):
    search = VectorSearch(DOCS, Embedder(FakeEmbeddingsClient(), "fake"), folder=str(tmp_path))
    assert search.search("where is my package", k=1)[0][0] == "delivery"


def test_vectors_are_reused_when_nothing_changed(tmp_path):
    VectorSearch(DOCS, Embedder(FakeEmbeddingsClient(), "fake"), folder=str(tmp_path))
    client = FakeEmbeddingsClient()
    VectorSearch(DOCS, Embedder(client, "fake"), folder=str(tmp_path))
    assert client.requests == []
    VectorSearch(DOCS, Embedder(client, "another-model"), folder=str(tmp_path))
    assert len(client.requests) == 1


def test_rrf_worked_example():
    fused = rrf([["error-e104", "ways-to-pay", "card-declined"], ["card-declined", "error-e104", "refunds"]])
    assert [doc_id for doc_id, _ in fused] == ["error-e104", "card-declined", "ways-to-pay", "refunds"]
    assert fused[0][1] == pytest.approx(1 / 61 + 1 / 62)
    assert fused[3][1] == pytest.approx(1 / 63)


def test_rrf_smaller_k_rewards_the_top_more():
    gentle = dict(rrf([["a", "b"]], k=60))
    steep = dict(rrf([["a", "b"]], k=1))
    assert gentle["a"] / gentle["b"] < steep["a"] / steep["b"]


def test_hybrid_fuses_both_lists_and_asks_each_for_depth_results():
    asked = []

    def fake(results):
        def search(query, k):
            asked.append(k)
            return [(doc_id, 1.0) for doc_id in results]
        return SimpleNamespace(search=search)

    hybrid = HybridSearch(fake(["a", "b"]), fake(["b", "c"]), depth=7)
    assert [doc_id for doc_id, _ in hybrid.search("q", k=2)] == ["b", "a"]
    assert asked == [7, 7]


def test_recall_counts_every_relevant_document():
    assert recall_at_k(["a", "x", "b"], ["a", "b"], k=3) == 1.0
    assert recall_at_k(["a", "x", "b"], ["a", "b"], k=2) == 0.5


def test_reciprocal_rank_uses_the_first_relevant_hit():
    assert reciprocal_rank(["x", "a", "b"], ["a", "b"], k=5) == 0.5
    assert reciprocal_rank(["x", "y"], ["a"], k=5) == 0.0


def test_evaluate_averages_and_lists_misses():
    answers = {"q1": ["a", "b"], "q2": ["c", "d"]}
    search = lambda query, k: [(doc_id, 1.0) for doc_id in answers[query][:k]]
    queries = [{"query": "q1", "relevant": ["b"]}, {"query": "q2", "relevant": ["z"]}]
    result = evaluate(search, queries, k=5)
    assert result["recall"] == 0.5
    assert result["mrr"] == 0.25
    assert result["misses"] == ["q2"]
  1. SimpleNamespace(a=1) is a quick object with an attribute a, like the JavaScript object literal {a: 1}.line 1
  2. Position 0 means "refund", 1 "delivery", 2 "download". Synonyms share a position.line 18
  3. Position 3 is always 0.1, so no vector is all zeros (a zero vector has no direction).line 22
  4. Builds client.embeddings.create out of a simple object, ending at our method.line 34
  5. **kwargs collects every named argument into a dict, so the fake accepts model=... and input=....line 36
  6. Codes and model names survive tokenizing; "what", "does", "on" and "my" are dropped.line 42
  7. Only one document contains e217; the others have no query word, so they are left out.line 46
  8. tmp_path is a pytest fixture: a fresh temporary folder for this test. pytest passes it in because of the parameter name.line 51
  9. The second build sends no request (same model, same texts); a different model name sends one again.line 56
  10. pytest.approx compares floats with a small tolerance. Never compare floats with ==.line 68
  11. With k = 1, first place is worth 1/2 and second 1/3; with k = 60 they are almost equal. The ratio proves it.line 72
  12. A small factory: returns an object whose search returns fixed results and records the k it was asked for. A function defined inside a function can use the outer variables (a closure).line 81
  13. Both searches were asked for depth results, not for k.line 89
  14. A fake search: a lambda returning fixed results. Testing evaluate needs no search engine at all.line 104
test_rerank.py
import json
from types import SimpleNamespace

from keywords import tokenize
from rerank import CrossEncoderReranker, LLMReranker, RerankedSearch

DOCS = [
    {"id": "refunds", "title": "Refunds", "text": "We pay your money back."},
    {"id": "delivery", "title": "Delivery", "text": "Every parcel ships in 2 days."},
    {"id": "gift-cards", "title": "Gift cards", "text": "Gift cards never expire."},
]


class FakeCrossEncoder:
    """Stands in for CrossEncoder: the score is the number of shared words. Records every call."""

    def __init__(self):
        self.calls = []

    def predict(self, pairs):
        self.calls.append(pairs)
        return [float(len(set(tokenize(q)) & set(tokenize(d)))) for q, d in pairs]


class FakeChatClient:
    """Stands in for OpenAI(): returns one fixed reply and records every request."""

    def __init__(self, reply: str):
        self.reply = reply
        self.requests = []
        self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))

    def create(self, **kwargs):
        self.requests.append(kwargs)
        message = SimpleNamespace(content=self.reply)
        return SimpleNamespace(choices=[SimpleNamespace(message=message)])


def test_cross_encoder_reorders_by_score():
    model = FakeCrossEncoder()
    reranker = CrossEncoderReranker(DOCS, "unused", model=model)
    ranked = reranker.rerank("when does my parcel ship", ["refunds", "gift-cards", "delivery"])
    assert ranked[0] == ("delivery", 1.0)
    assert model.calls[0][0] == ("when does my parcel ship", "Refunds. We pay your money back.")


def test_cross_encoder_with_no_candidates_does_not_call_the_model():
    model = FakeCrossEncoder()
    assert CrossEncoderReranker(DOCS, "unused", model=model).rerank("q", []) == []
    assert model.calls == []


def test_reranked_search_fetches_candidates_then_cuts_to_k():
    asked = []

    def first_stage(query, k):
        asked.append(k)
        return [("refunds", 0.9), ("gift-cards", 0.8), ("delivery", 0.7)]

    search = RerankedSearch(SimpleNamespace(search=first_stage), CrossEncoderReranker(DOCS, "x", model=FakeCrossEncoder()), candidates=20)
    assert [doc_id for doc_id, _ in search.search("parcel ships", k=1)] == ["delivery"]
    assert asked == [20]


def test_llm_ranking_is_used_and_cleaned_up():
    client = FakeChatClient(json.dumps({"ids": ["delivery", "delivery", "made-up"]}))
    reranker = LLMReranker(DOCS, client, "fake-model")
    ranked = reranker.rerank("where is my parcel", ["refunds", "delivery", "gift-cards"])
    assert [doc_id for doc_id, _ in ranked] == ["delivery", "refunds", "gift-cards"]
    assert reranker.unusable == 0
    schema = client.requests[0]["response_format"]["json_schema"]["schema"]
    assert schema["properties"]["ids"]["items"]["enum"] == ["refunds", "delivery", "gift-cards"]


def test_llm_reply_that_is_not_json_keeps_the_old_order():
    reranker = LLMReranker(DOCS, FakeChatClient("Sure! The best article is Delivery."), "fake-model")
    ranked = reranker.rerank("where is my parcel", ["refunds", "delivery"])
    assert [doc_id for doc_id, _ in ranked] == ["refunds", "delivery"]
    assert reranker.unusable == 1


def test_llm_reply_with_the_wrong_shape_keeps_the_old_order():
    reranker = LLMReranker(DOCS, FakeChatClient('{"ids": 5}'), "fake-model")
    assert [doc_id for doc_id, _ in reranker.rerank("q", ["delivery", "refunds"])] == ["delivery", "refunds"]
    assert reranker.unusable == 1
  1. Has the one method the reranker uses, predict(pairs). It records each call so the tests can check what was sent.line 14
  2. Stands in for OpenAI(): one fixed reply, every request recorded. The same idea as the fake client in lab 3.line 25
  3. "parcel" is the one shared word, so Delivery wins with a score of 1.line 43
  4. The first pair sent to the model: the question and the full text of the first candidate.line 44
  5. The first stage is asked for 20 candidates; the result is cut to k = 1.line 53
  6. A reply with a repeated id and an id that is not a candidate. Both are cleaned up, and the missing candidates are added in their old order.line 66
  7. Checks that the request really limited the reply to the candidate ids.line 72
  8. Prose instead of JSON: the hybrid order is kept and the reply is counted as unusable.line 76
  9. Valid JSON, wrong shape: 5 is not a list. The TypeError is caught the same way.line 83
Run
uv run pytest -q
You should see
................                                                         [100%]
16 passed in 0.09s
Why this way? These tests check your code: tokenizing, the cache key, the RRF formula, the plumbing between stages, the cleanup of LLM replies and the metrics. How good the models are is a different question, answered by evaluate.py and the labelled queries. Keep both: unit tests on every commit, the evaluation whenever you change a model, the documents, the fusion or the number of candidates.
Stuck on this step?
ModuleNotFoundError: No module named 'keywords'
Run pytest from the project folder with uv run pytest -q.
The tests are slow or download something
Something created a real CrossEncoder or client. Every test passes its fake explicitly (model=FakeCrossEncoder()); check you did not drop that argument.

Check it works

Two checks: the tests pass with no model, and the evaluation prints all four rows.

The keyword row must be exactly 0.69 0.64. The others come from models: within a question or two of ours is normal. What should hold: hybrid recall is at least vector recall, and hybrid + rerank has the best MRR.

Test
uv run pytest -q && uv run evaluate.py
You should see
16 passed in 0.09s
24 labelled queries, k = 5

search           recall@5     MRR  ms/query
keyword              0.69    0.64       0.0
vector               0.88    0.64      12.8
hybrid               0.92    0.79      14.3
hybrid+rerank        1.00    0.95      44.8
...

Troubleshooting

Hybrid search is worse than vector search on my own data

It happens when one search is much weaker than the other: RRF gives both lists the same weight. Check the weak one first (for BM25: tokenizing, stemming, the language). Then try a weight per list, weight / (k + rank), chosen with your labelled queries, or rerank, which repairs most fusion mistakes.

Keyword search misses obvious matches like "ebook" vs "e-book" or "ship" vs "ships"

That is the tokenizer. Normalise the text (remove hyphens in known words), add stemming (for example the snowballstemmer package), or use a search engine whose analyzers do this (Elasticsearch, OpenSearch, Postgres full-text search).

huggingface_hub.errors.RepositoryNotFoundError: 401 Client Error

Usually a typo in RERANK_MODEL: Hugging Face answers 401 for a model name that does not exist (it will not say whether a private model of that name exists). The exact name is cross-encoder/ms-marco-MiniLM-L6-v2.

Reranking makes non-English queries worse

The MS MARCO cross-encoders were trained on English. For other languages use a multilingual reranker (for example BAAI/bge-reranker-v2-m3, much larger and slower) and measure it on your queries.

The cross-encoder is too slow in production

Rerank fewer candidates (step 9 shows where recall stops rising), keep texts short (it reads at most 512 tokens per pair), batch, run it on a GPU or as an ONNX model, or use a hosted rerank API. And always fall back to the hybrid order when it is slow or fails.

What changes in production

  • Let the database do the hybrid part. Elasticsearch and OpenSearch have BM25 built in and can fuse with vector results; Postgres can combine full-text search with pgvector in one SQL query (lab 6's database); many vector databases offer hybrid search with RRF. The fusion and reranking code here stays the same idea.
  • Keep both indexes in sync. Every insert, update and delete goes to the keyword index and the vector index with the same document ids, or fused results point at articles that no longer exist.
  • Give reranking a budget and a fallback. A fixed number of candidates, a timeout, and the hybrid order when the reranker is slow or down. Log the reranker latency separately from the search.
  • Re-measure on every change. Run the labelled queries in CI on a new embedding model, tokenizer, fusion setting or candidate count, and track recall@k, MRR and latency together. Add every real query that came back wrong to the set.

Interview angle

“Users say search misses exact error codes but works for normal questions. How do you improve retrieval, and how do you know it worked?”

Embeddings capture meaning, so they are weak on exact strings like error codes, part numbers and rare names, while keyword search like BM25 is precise on those but blind to paraphrases. So I run both, take the top 20 or so from each, and merge them with Reciprocal Rank Fusion: each list contributes 1 over 60 plus the rank, which needs no score normalisation and rewards documents both searches agree on. Then I rerank the merged candidates with a cross-encoder, which reads the query and each candidate together and orders them far better, at the cost of one small model run per candidate, so I rerank only a few dozen and fall back to the fused order if it is slow. To know it worked, I build a labelled query set from real searches, especially the failing ones, and compare recall at k, MRR and p50 or p95 latency for keyword, vector, hybrid and hybrid plus rerank, then choose the candidate count where recall stops improving.

Clean up

The index folder can be deleted any time; the next run rebuilds it. The cross-encoder lives in the Hugging Face cache (about 90 MB); delete it if you will not use it again. Keep nomic-embed-text: the next labs use it.

Run
rm -rf index ~/.cache/huggingface/hub/models--cross-encoder--ms-marco-MiniLM-L6-v2

Practice

No model needed: these run in your browser and check your answer.

Reciprocal Rank Fusion by hand

Write rrf(rankings, k=60). rankings is a list of ranked id lists, best first. Each list gives each of its ids 1 / (k + rank), with rank starting at 1; add up what each id collects. Return a list of (id, score) pairs, highest score first.

Exercise
def rrf(rankings, k=60):
    scores = {}
    for ranking in rankings:
        for doc_id in ranking:
            scores[doc_id] = scores.get(doc_id, 0) + 1
    return sorted(scores.items(), key=lambda pair: pair[1], reverse=True)


print(rrf([["a", "b", "c"], ["c", "a", "d"]]))
Hint

Use `for rank, doc_id in enumerate(ranking, start=1):` and add `1 / (k + rank)` instead of 1.

One BM25 term, by hand

Write bm25_term(tf, n, N, dl, avgdl, k1=1.5, b=0.75): the score one query word adds to one document, the way rank-bm25 computes it (without the negative-idf floor). tf: times the word appears in the document; n: documents containing it; N: documents in total; dl: this document's length; avgdl: the average length. Use idf = math.log((N - n + 0.5) / (n + 0.5)) and the formula from step 3. Check: the E217 example (tf=2, n=1, N=44, dl=16, avgdl=18.318181818181817) gives about 5.0144.

Exercise
import math


def bm25_term(tf, n, N, dl, avgdl, k1=1.5, b=0.75):
    idf = math.log((N - n + 0.5) / (n + 0.5))
    return idf * tf


print(round(bm25_term(2, 1, 44, 16, 18.318181818181817), 4))
Hint

Multiply `idf` by `tf * (k1 + 1) / (tf + k1 * (1 - b + b * dl / avgdl))`.

The full project

Every file from this lab, as it is after the last step.

Download Python project (.zip)