AI Engineering · Build lab 5 of 14

Semantic search from scratch in Python: embeddings, cosine similarity and recall@k

Build search that understands meaning. Embed 30 help articles with nomic-embed-text on Ollama, store the vectors in NumPy, rank by cosine similarity, batch and cache the calls, beat keyword search on synonyms, and measure quality with recall@3. Plus Spring AI EmbeddingModel.

⏱ 60 minBeginner to intermediate💸 Free (local model)9 stepsPython + Java

Python 3.12uvOllamanomic-embed-textopenai SDKNumPy 2pytestSpring AI 1.0 (optional)

Overview video

1 / 7

0 of 9 steps done

What you will build

A semantic search tool for a small help centre: 30 short articles about an online bookshop (refunds, delivery, passwords, e-books). You type a question in your own words, like stop my monthly plan, and it puts the article "End your Reading Club membership" in its top 3, even though the two share no words. You will also see where it is not good enough on its own.

You build every piece yourself, with no vector database and no framework: turn text into embeddings (lists of numbers that capture meaning) through Ollama's OpenAI-compatible API, save them as a NumPy array, rank articles by cosine similarity, send texts in batches, and cache every vector by a hash of its text so re-runs cost nothing.

Then you check it like an engineer: compare it with plain keyword search on the same questions, and measure it with a small test set and recall@3 (how often the right article is in the top 3). Everything is unit tested with a fake embedder, so the tests need no model.

Before you start

  • Lab 1 done: Your first LLM call. This lab reuses its .env, config.py and the error handling.
  • Python lists, dicts and classes. NumPy is explained as it appears; NumPy for AI covers the basics.
  • The idea behind it (8 minutes): Embeddings explains what the numbers mean.
  • About 300 MB of free disk space for the embedding model.

Setup

S1Install uv (the Python project tool)

Skip this 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 (runs models on your machine)

Skip this if you did lab 1. Download it from ollama.com/download and open it once. It runs a small server on port 11434 that speaks the same API as the hosted providers, including the embeddings endpoint this lab uses.

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

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

An embedding model does not write text. It reads text and returns a fixed-length list of numbers (a vector). nomic-embed-text returns 768 numbers per text, is small enough for any laptop and is fast even without a GPU. You do not need the chat model from lab 1 for this lab.

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

S5Check the model answers on the embeddings endpoint

One request by hand: the model name and the input text go in, a list of numbers comes out in data[0].embedding. The numbers are long; you only need to see that they arrive.

Run
curl http://localhost:11434/v1/embeddings -H "Content-Type: application/json" -d '{"model": "nomic-embed-text", "input": "hello"}'
You should seeyour text will differ: the model writes it
{"object":"list","data":[{"object":"embedding","embedding":[0.0137,-0.0021,-0.1764,...],"index":0}],"model":"nomic-embed-text",...}

S6Java only (optional): JDK 21 and Maven

Only if you want the Spring AI version of step 6 (switch to Java at the top of the steps). Same tools as lab 1.

Run
brew install openjdk@21 maven
1

Create the project

A fresh project with NumPy, the SDK and pytest, plus the settings from lab 1 and one new one.

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: numpy, the array library almost every AI tool in Python is built on. A NumPy array is a block of numbers of one type (like a Java float[][]) with fast maths on the whole block at once. We store all the embeddings in one array and score every article with one line.

The settings are lab 1's, plus EMBED_MODEL. llm.py builds the client and turns the common errors into one clear sentence, so every script in this lab handles them the same way.

.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

# A hosted API instead: change these lines, nothing else (and rebuild the index, step 4).
# LLM_BASE_URL=https://api.your-provider.com/v1
# LLM_API_KEY=sk-...
# EMBED_MODEL=the-embedding-model-name
  1. The same OpenAI-compatible base URL as lab 1. The embeddings endpoint lives next to the chat one: /v1/embeddings.line 2
  2. The chat model from lab 1. This lab does not use it; the RAG lab after this one does.line 4
  3. The new setting: which model turns text into vectors.line 5
config.py 2 new or changed lines
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


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"),
    )
  1. load_dotenv() copies .env into os.environ. Variables already set in your shell take priority, 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 embedding model, with the same default as .env.line 22
.gitignore
.venv/
__pycache__/
.env
cache/
index/
  1. Never commit .env: one day it holds a real key.line 3
  2. cache/ and index/ are generated by the scripts (steps 4 and 5). Anyone can rebuild them from docs.jsonl.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=60, max_retries=2)


def friendly(err: openai.OpenAIError, model: 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 send fewer texts per request."
    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):
        return f"Model '{model}' not found. Run: ollama pull {model}"
    return f"The request failed: {err}"
  1. A function, not a global: the tests in step 9 never call it. They hand the code a fake client instead.line 7
  2. max_retries=2: the SDK retries timeouts, 429 and 5xx errors with backoff before it raises.line 9
  3. openai.OpenAIError is the base class of every SDK error. The scripts catch it once and print friendly(e, ...).line 12
  4. 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
  5. Ollama answers 404 when the model has not been pulled. The message tells the user the exact command.line 18
Run
uv init semantic-search
cd semantic-search
uv add numpy openai python-dotenv
uv add --dev pytest
You should seeyour text will differ: the model writes it
Initialized project `semantic-search` at `.../semantic-search`
Resolved 19 packages in 450ms
Installed 17 packages in 40ms
 + numpy==2.5.5
 + openai==3.60.0
 + python-dotenv==1.2.4
 ...
Why this way? The client is built in one function and passed into the code that needs it (dependency injection). That is what lets step 9 test the batching, the cache and the search with a fake, in milliseconds.
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.
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 to search

Thirty short help articles in a JSON Lines file, and a loader for them.

Save the file below as docs.jsonl in the project folder. JSON Lines means one complete JSON object per line, with no surrounding [...]. It is the usual format for datasets and logs: you can append a line without rewriting the file, and read it line by line.

Every article has an id (stable, used to save and test results), a title and a short text. Short texts keep the lab fast. Real help centres have long pages; the next lab splits those into chunks before embedding them.

corpus.py reads the file and decides what we embed for each article: the title and the text together, because the title is often the best summary of what an article answers.

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."}
  1. One article per line. Keys are id, title, text. The ids are short, readable names, so search results and test cases are easy to read.line 1
  2. Watch this one in step 8: "the book I ordered never showed up" should find it, and it is the article that semantic search misses.line 12
  3. The answer to "stop my monthly plan". The words "stop", "monthly" and "plan" appear nowhere in it.line 21
corpus.py
import json
from pathlib import Path


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


def doc_text(doc: dict) -> str:
    """The text we embed for a document: its title, then its body."""
    return f"{doc['title']}. {doc['text']}"
  1. 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 and help your editor.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. line.strip() removes spaces and the newline. 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. Single quotes inside, because the f-string itself uses double quotes.line 16
Run
uv run python -c "from corpus import load_docs, doc_text; docs = load_docs(); print(len(docs)); print(doc_text(docs[0]))"
You should see
30
Reset your password. 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.
Why this way? Collect the documents and a few real questions before writing any search code. Step 8 turns those questions into a test set, and every later change (a new model, a new prefix, chunking) is measured against it.
Stuck on this step?
json.decoder.JSONDecodeError: Expecting value
A line in docs.jsonl is not complete JSON, often because an editor wrapped a long line. Every article must be on exactly one line.
3

Your first embeddings

See what an embedding is, and measure how close two texts are in meaning with cosine similarity.

An embedding is a list of numbers that stands for a text. The model is trained so that texts with similar meaning get similar lists, even when they use different words. Think of each list as a point (an arrow from the origin) in a space with 768 directions.

Cosine similarity compares two arrows by the angle between them: 1 means the same direction (same meaning), 0 means unrelated. The formula is the dot product (multiply the numbers pairwise and add them up) divided by the two lengths. It ignores the length on purpose: only the direction carries meaning.

The prefixes matter. nomic-embed-text was trained with a task instruction at the start of every text: search_query: for the question a user types, and search_document: for the texts you search through. Ollama does not add them for you. Leave them out and results get worse. Other embedding models use other instructions or none at all, so check the model card when you switch.

The SDK call is client.embeddings.create(model=..., input=[...]). You can send one text or a list; you get back one vector per text, in resp.data.

first_embedding.py
import numpy as np

from config import settings
from llm import make_client

texts = [
    "search_query: how do I get my money back?",
    "search_document: We pay the full price back to your card within 5 days.",
    "search_document: Standard delivery takes 2 to 4 working days.",
    "search_document: Gift cards never expire.",
]
resp = make_client().embeddings.create(model=settings().embed_model, input=texts)
vectors = np.array([item.embedding for item in resp.data], dtype=np.float32)

print("shape:", vectors.shape)
print("first 5 numbers of the query:", np.round(vectors[0, :5], 3))
print("length of the query vector:", round(float(np.linalg.norm(vectors[0])), 3))


def cosine(a: np.ndarray, b: np.ndarray) -> float:
    return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))


print("similarity to the query:")
for text, vec in zip(texts[1:], vectors[1:]):
    print(f"  {cosine(vectors[0], vec):.3f}  {text}")
  1. import numpy as np: everyone imports NumPy under the short name np.line 1
  2. The question gets search_query: . The answer shares only one word with it ("back").line 7
  3. The texts we search through get search_document: .line 8
  4. One request with four texts. Behind the scenes the SDK asks for the numbers in a compact base64 form and decodes them, so item.embedding is always a plain list of floats.line 12
  5. A list comprehension ([... for item in ...], like stream().map(...).toList()) collects the four lists. np.array turns them into one 4 x 768 table of 32-bit floats (Java float), half the memory of Python's default 64-bit floats.line 13
  6. .shape is the size of each dimension: (4, 768) is 4 rows of 768 numbers.line 15
  7. vectors[0, :5] is row 0, columns 0 to 4. :5 is a slice: "up to, not including, 5".line 16
  8. np.linalg.norm is the length of the vector: the square root of the sum of squares. Ollama returns vectors of length 1 already; not every provider does.line 17
  9. @ is the dot product in NumPy (a[0]*b[0] + a[1]*b[1] + ...). Divided by both lengths, that is the cosine. float(...) turns NumPy's number type into a plain Python float.line 21
  10. texts[1:] is every item except the first. zip walks two lists side by side, like a loop over two indexes at once.line 25
  11. :.3f prints three decimals, like %.3f in String.format.line 26
Run
uv run first_embedding.py
You should seeyour text will differ: the model writes it
shape: (4, 768)
first 5 numbers of the query: [ 0.066  0.034 -0.189  0.002  0.046]
length of the query vector: 1.0
similarity to the query:
  0.682  search_document: We pay the full price back to your card within 5 days.
  0.439  search_document: Standard delivery takes 2 to 4 working days.
  0.478  search_document: Gift cards never expire.
Why this way? Look at the scores, not just the winner. The refund sentence scores clearly higher than the other two. The unrelated ones still score around 0.4 to 0.5, not 0: with this model, scores bunch together, so you compare them with each other (which document ranks first) rather than reading a single score as "good" or "bad".
Stuck on this step?
Model 'nomic-embed-text' not found or openai.NotFoundError: 404
Run ollama pull nomic-embed-text and check the name with ollama list.
openai.APIConnectionError: Connection error.
Ollama is not running. Open the Ollama app or run ollama serve, then try again.
My numbers are different from the ones above
Expected: they depend on the exact model build and your hardware. The order of the three scores is what should match.
4

Embed every article in batches and save the vectors

Turn the 30 articles into one 30 x 768 NumPy array, with as few requests as possible, and save it to disk.

One request per text works, but each request has a fixed cost (HTTP, queueing, loading the batch onto the model). Sending 16 texts per request turns 30 articles into 2 requests. Hosted APIs limit how many texts or tokens one request may carry, so the batch size is a setting.

embedder.py is the one place that talks to the embedding API. It also normalizes every vector to length 1. Then the cosine similarity of two vectors is just their dot product, so search later is a single matrix multiplication.

build_index.py saves two files in index/: vectors.npy (NumPy's own binary format: the numbers plus their shape and type) and meta.json, which says which article each row is and which model made the vectors. Vectors from different models are not comparable, so search refuses an index built with another model (step 6).

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
        self.requests = 0

    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)
            self.requests += 1
            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 two prefixes from step 3, as constants. Upper-case names at module level are Python's convention for constants (static final).line 3
  2. axis=-1 measures the length of each row (the last dimension) instead of the whole table. keepdims=True keeps the result as a column, shape (rows, 1), so the division on the next line lines up row by row.line 9
  3. Dividing a table by a column divides every row by its own length (NumPy "broadcasting"). np.where(norms == 0, 1, norms) replaces a zero length with 1, so an all-zero vector cannot cause a division by zero.line 10
  4. __init__ is the constructor and self is this, written out. No type for client: anything with embeddings.create(...) works, which is how the tests pass a fake.line 14
  5. range(0, 30, 16) gives 0 and 16: the start of each batch, like for (start = 0; start < 30; start += 16).line 23
  6. A slice: items start up to (not including) start + 16. Past the end it simply stops, so the last batch can be shorter.line 24
  7. Each result carries the index of its input text. Sorting by it guarantees row 5 is text 5, whatever order the server used. key=lambda d: d.index is Comparator.comparing(d -> d.index).line 27
  8. All rows become one float32 table, then every row is scaled to length 1.line 29
  9. Articles get the document prefix. DOC_PREFIX + t is string concatenation.line 31
  10. A query is one text: embed it as a list of one and take row [0], a 1-D array of 768 numbers.line 35
build_index.py
import json
import sys
import time
from pathlib import Path

import numpy as np
import openai

from config import settings
from corpus import doc_text, load_docs
from embedder import Embedder
from llm import friendly, make_client

s = settings()
docs = load_docs()
embedder = Embedder(make_client(), s.embed_model, batch_size=16)

start = time.perf_counter()
try:
    vectors = embedder.embed_documents([doc_text(d) for d in docs])
except openai.OpenAIError as e:
    sys.exit(friendly(e, s.embed_model))
seconds = time.perf_counter() - start

Path("index").mkdir(exist_ok=True)
np.save("index/vectors.npy", vectors)
meta = {"model": s.embed_model, "ids": [d["id"] for d in docs]}
Path("index/meta.json").write_text(json.dumps(meta, indent=2))

print(f"{len(docs)} documents embedded in {embedder.requests} requests ({seconds:.2f}s)")
print(f"saved index/vectors.npy: shape {vectors.shape}, {vectors.dtype}, {vectors.nbytes:,} bytes")
  1. One embedder for the whole run, 16 texts per request.line 16
  2. time.perf_counter() is a precise clock for measuring durations, like System.nanoTime() but in seconds.line 18
  3. All 30 articles in one call. The embedder splits them into batches itself.line 20
  4. sys.exit("text") prints the text to stderr and ends the program with exit code 1. No stack trace for the common errors.line 22
  5. exist_ok=True: no error if the folder is already there (mkdir -p).line 25
  6. np.save writes the array in .npy format: a small header with the shape and type, then the raw bytes. np.load gives the identical array back.line 26
  7. Row i of the array belongs to ids[i]. The model name is saved with the vectors so search can check it.line 27
  8. .nbytes is the size in memory: 30 x 768 numbers x 4 bytes. :, adds thousands separators.line 31
Run
uv run build_index.py
You should seeyour text will differ: the model writes it
30 documents embedded in 2 requests (3.49s)
saved index/vectors.npy: shape (30, 768), float32, 92,160 bytes
Why this way? The maths is worth knowing for the interview: 768 floats x 4 bytes is about 3 KB per text. A million articles is about 3 GB of vectors, which still fits in memory, and a NumPy dot product over all of them takes well under a second on a laptop. Brute force goes further than people expect; a vector database earns its place with filtering, updates and much larger collections.
Stuck on this step?
Model 'nomic-embed-text' not found. Run: ollama pull nomic-embed-text
That is friendly() at work: pull the model, then run the script again.
It is slow (more than 30 seconds)
The first request loads the model into memory. Run it again: later runs are much faster, and step 5 makes them free.
ModuleNotFoundError: No module named 'numpy'
You ran python build_index.py outside the project environment. Use uv run build_index.py.
5

Cache embeddings by text hash

Never pay for the same embedding twice: a re-run with unchanged articles sends zero requests.

Embedding is deterministic: the same model and the same text give the same vector. So we keep every vector we have computed, keyed by a SHA-256 hash of the model name and the exact text (prefix included). Re-run after editing one article, and only that article is embedded again: its text changed, so its hash changed.

The cache lives in cache/embeddings.npz, NumPy's format for many named arrays in one file (a zip of .npy files). It loads into a dict from hash to vector.

Three files change. cache.py is new. In embedder.py, embed() now looks every text up first and sends only the misses to the API. build_index.py creates the cache, saves it at the end and reports hits and misses.

cache.py
import hashlib
from pathlib import Path

import numpy as np


class EmbeddingCache:
    """Embeddings saved on disk, keyed by a hash of the model name and the text."""

    def __init__(self, path: str | Path = "cache/embeddings.npz"):
        self.path = Path(path)
        self.vectors: dict[str, np.ndarray] = {}
        if self.path.exists():
            with np.load(self.path) as saved:
                self.vectors = {key: saved[key] for key in saved.files}
        self.hits = 0
        self.misses = 0

    @staticmethod
    def key(model: str, text: str) -> str:
        return hashlib.sha256(f"{model}\n{text}".encode("utf-8")).hexdigest()

    def get(self, model: str, text: str) -> np.ndarray | None:
        vec = self.vectors.get(self.key(model, text))
        if vec is None:
            self.misses += 1
        else:
            self.hits += 1
        return vec

    def put(self, model: str, text: str, vec: np.ndarray) -> None:
        self.vectors[self.key(model, text)] = vec

    def save(self) -> None:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        np.savez(self.path, **self.vectors)
  1. str | Path means "a string or a Path". The tests pass a temporary Path; the scripts use the default.line 10
  2. with ... as saved: closes the file at the end of the block, like Java's try-with-resources.line 14
  3. A dict comprehension: {key: value for ...} builds a dict in one expression. saved.files lists the names of the arrays inside the .npz file.line 15
  4. @staticmethod: a method that needs no object, called as EmbeddingCache.key(...), like a Java static method.line 19
  5. The model name goes into the key, so switching models can never return a vector from the old one. .encode() turns the string into bytes; .hexdigest() gives 64 hex characters.line 21
  6. The return type np.ndarray | None is Java's "nullable": a vector, or None on a miss.line 23
  7. dict.get(key) returns None when the key is missing, instead of raising an error.line 24
  8. **self.vectors passes every dict entry as a named argument: np.savez(path, abc123=vec1, def456=vec2, ...). Each name becomes one array in the file.line 36
embedder.py 20 new or changed lines
import numpy as np

from cache import EmbeddingCache

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, cache: EmbeddingCache | None = None):
        self.client = client
        self.model = model
        self.batch_size = batch_size
        self.cache = cache
        self.requests = 0

    def embed(self, texts: list[str]) -> np.ndarray:
        """One row per text, in the same order, each of length 1."""
        vectors = [None] * len(texts)
        todo = []
        for i, text in enumerate(texts):
            hit = self.cache.get(self.model, text) if self.cache is not None else None
            if hit is None:
                todo.append(i)
            else:
                vectors[i] = hit
        for start in range(0, len(todo), self.batch_size):
            batch = todo[start:start + self.batch_size]
            resp = self.client.embeddings.create(model=self.model, input=[texts[i] for i in batch])
            self.requests += 1
            for i, item in zip(batch, sorted(resp.data, key=lambda d: d.index)):
                vec = normalize(np.array(item.embedding, dtype=np.float32))
                vectors[i] = vec
                if self.cache is not None:
                    self.cache.put(self.model, texts[i], vec)
        return np.vstack(vectors)

    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 cache is optional (None by default), so the embedder still works without one, as in the tests.line 16
  2. One slot per text, filled from the cache or from the API. [None] * 3 is [None, None, None].line 25
  3. todo holds the **positions** of the texts the cache does not have.line 26
  4. enumerate gives (position, text) pairs, like a loop with an index.line 27
  5. Python's conditional expression: a if condition else b is condition ? a : b. We write is not None rather than if self.cache, because an object can define its own idea of true and false.line 28
  6. The same batching as before, but only over the misses. All hits: todo is empty and no request is sent.line 33
  7. [texts[i] for i in batch]: the texts at those positions.line 35
  8. zip pairs each position with its result, both in input order.line 37
  9. Each vector is normalized on its own before it is cached, so cached and fresh vectors are the same.line 38
  10. np.vstack stacks the rows into one table, like normalize(np.array(...)) did before, but from a mix of cached and new rows.line 42
build_index.py 6 new or changed lines
import json
import sys
import time
from pathlib import Path

import numpy as np
import openai

from cache import EmbeddingCache
from config import settings
from corpus import doc_text, load_docs
from embedder import Embedder
from llm import friendly, make_client

s = settings()
docs = load_docs()
cache = EmbeddingCache("cache/embeddings.npz")
embedder = Embedder(make_client(), s.embed_model, batch_size=16, cache=cache)

start = time.perf_counter()
try:
    vectors = embedder.embed_documents([doc_text(d) for d in docs])
except openai.OpenAIError as e:
    sys.exit(friendly(e, s.embed_model))
seconds = time.perf_counter() - start
cache.save()

Path("index").mkdir(exist_ok=True)
np.save("index/vectors.npy", vectors)
meta = {"model": s.embed_model, "ids": [d["id"] for d in docs]}
Path("index/meta.json").write_text(json.dumps(meta, indent=2))

print(f"{len(docs)} documents: {cache.misses} embedded in {embedder.requests} requests, "
      f"{cache.hits} from the cache ({seconds:.2f}s)")
print(f"saved index/vectors.npy: shape {vectors.shape}, {vectors.dtype}, {vectors.nbytes:,} bytes")
  1. Load whatever earlier runs saved. The first run starts with an empty cache.line 17
  2. Save after a successful run. If the run fails half way, nothing is saved, and the next run simply embeds again.line 26
  3. Two f-strings next to each other inside the parentheses join into one line of output.line 33
Run
uv run build_index.py
uv run build_index.py
You should seeyour text will differ: the model writes it
30 documents: 30 embedded in 2 requests, 0 from the cache (3.49s)
saved index/vectors.npy: shape (30, 768), float32, 92,160 bytes
30 documents: 0 embedded in 0 requests, 30 from the cache (0.00s)
saved index/vectors.npy: shape (30, 768), float32, 92,160 bytes
Why this way? In real projects embedding is often the biggest cost of building a search index, and you re-run the build all the time (a new article, a fixed typo, a new chunk size). A content-hash cache makes the rebuild cost proportional to what changed. The same idea is how build tools and CDNs avoid repeating work.
Stuck on this step?
The second run still says 30 embedded
The cache was not saved: check that cache.save() is in build_index.py and that cache/embeddings.npz exists. Run both commands from the project folder.
I changed EMBED_MODEL and everything was embedded again
Correct: the model name is part of the key, and vectors from another model must not be reused.
6

Search by meaning: a small command-line tool

Type a question, get the 3 closest articles with their scores.

Search is three moves: embed the query (with the query prefix), score every article with one matrix-vector product, and take the top k. Because every row has length 1, vectors @ query gives the cosine similarity of the query with all 30 articles at once.

argparse is Python's standard library for command-line arguments, like picocli in Java or commander in Node. It also writes --help for you.

The file ends with if __name__ == "__main__": main(). Python sets __name__ to "__main__" only for the file you run. When the tests import search to use top_k, main() does not run (there are no command-line arguments to read in a test).

search.py
import argparse
import json
import sys
from pathlib import Path

import numpy as np
import openai

from cache import EmbeddingCache
from config import settings
from corpus import load_docs
from embedder import Embedder
from llm import friendly, make_client


def load_index(model: str, folder: str = "index") -> tuple[np.ndarray, list[str]]:
    meta = json.loads((Path(folder) / "meta.json").read_text())
    if meta["model"] != model:
        raise ValueError(f"the index was built with {meta['model']}, but EMBED_MODEL is {model}")
    return np.load(Path(folder) / "vectors.npy"), meta["ids"]


def top_k(query_vec: np.ndarray, vectors: np.ndarray, k: int = 3) -> list[tuple[int, float]]:
    """Row numbers and scores of the k rows most similar to the query."""
    scores = vectors @ query_vec
    best = np.argsort(-scores, kind="stable")[:k]
    return [(int(i), float(scores[i])) for i in best]


def semantic_search(query: str, embedder: Embedder, vectors: np.ndarray, ids: list[str], k: int = 3) -> list[tuple[str, float]]:
    q = embedder.embed_query(query)
    return [(ids[i], score) for i, score in top_k(q, vectors, k)]


def main() -> None:
    parser = argparse.ArgumentParser(description="Search the help centre by meaning.")
    parser.add_argument("query", help="what you are looking for, in your own words")
    parser.add_argument("-k", type=int, default=3, help="how many results to show (default 3)")
    args = parser.parse_args()

    s = settings()
    try:
        vectors, ids = load_index(s.embed_model)
    except FileNotFoundError:
        sys.exit("No index yet. Run: uv run build_index.py")
    except ValueError as e:
        sys.exit(f"{e}. Run: uv run build_index.py")

    titles = {d["id"]: d["title"] for d in load_docs()}
    cache = EmbeddingCache()
    embedder = Embedder(make_client(), s.embed_model, cache=cache)
    try:
        results = semantic_search(args.query, embedder, vectors, ids, args.k)
    except openai.OpenAIError as e:
        sys.exit(friendly(e, s.embed_model))
    cache.save()

    for rank, (doc_id, score) in enumerate(results, start=1):
        print(f"{rank}. {score:.3f}  {doc_id:<24} {titles[doc_id]}")


if __name__ == "__main__":
    main()
  1. tuple[np.ndarray, list[str]]: the function returns two values, the vectors and the ids. The caller unpacks them with vectors, ids = load_index(...).line 16
  2. / on Path objects joins path parts, like Path.resolve in Java: index/meta.json.line 17
  3. Refuse to mix models. Comparing a query vector from one model with article vectors from another gives meaningless scores, or a shape error if the lengths differ.line 18
  4. Matrix times vector: (30 x 768) times (768) gives 30 scores, one per article, in one fast call.line 25
  5. np.argsort returns the **positions** that would sort the array, smallest first. Sorting -scores puts the highest score first. kind="stable" keeps equal scores in file order, so results are repeatable. [:k] keeps the first k.line 26
  6. int(...) and float(...) turn NumPy's number types into plain Python ones, which print and compare cleanly.line 27
  7. The query gets the search_query: prefix inside embed_query.line 31
  8. Row numbers become article ids: row i belongs to ids[i].line 32
  9. A positional argument: the first word (or quoted phrase) after the script name.line 37
  10. An option: -k 5 shows five results. type=int converts the text "5" to the number 5.line 38
  11. No index/ folder yet: tell the user the one command that fixes it.line 44
  12. A dict from id to title, built in one expression, to print readable results.line 49
  13. Queries are cached too. Search the same question twice and the second time sends no request.line 50
  14. enumerate(..., start=1) numbers the results from 1. (doc_id, score) unpacks each pair. :<24 pads the id to 24 characters, so the titles line up.line 58
  15. main() runs only when you start this file (uv run search.py), not when another file imports it.line 62
Run
uv run search.py "stop my monthly plan"
You should seeyour text will differ: the model writes it
1. 0.530  card-declined            Card declined at checkout
2. 0.509  end-membership           End your Reading Club membership
3. 0.505  reading-club             Reading Club membership
Why this way? Two things to see here. The good news: "stop my monthly plan" shares no words with "End your Reading Club membership", and the model still puts it in the top 3, next to the other membership article. The bad news: it is second, and "Card declined at checkout" is first, probably because "monthly plan" sounds like payments. The three scores are only a few hundredths apart, which means the model cannot really tell them apart. This is normal for a small embedding model, and it is why search systems return a few results (top 3, not top 1), why you measure with a test set (step 8) instead of trusting a few examples, and why the hybrid search lab adds a reranker that reads the question and each article together. Your scores may differ a little from these.
Stuck on this step?
No index yet. Run: uv run build_index.py
Build the index first (step 4), from the same folder.
the index was built with ..., but EMBED_MODEL is ...
You changed EMBED_MODEL after building. Run uv run build_index.py again.
Java: model "mxbai-embed-large" not found
The spring.ai.ollama.embedding.options.model line is missing, so Spring AI used its own default model. Add it, or pull that model.
Java: NoSuchFileException: docs.jsonl
Copy docs.jsonl into the Java project folder (next to pom.xml) and run Maven from there.
7

Keyword search vs semantic search

Run both on the same questions and see where each one wins.

To know what embeddings buy you, compare them with the simplest alternative: keyword search. It splits the query and each article into lowercase words, drops filler words like "the" and "my", and ranks articles by how many query words they contain. That is roughly how a basic LIKE '%word%' search behaves, and the idea behind BM25, the classic ranking in search engines like Elasticsearch, which also weights rare words.

The file is called keywords.py, not keyword.py: Python already has a standard-library module named keyword, and it is loaded before your script starts. So from keyword import keyword_search would find the standard module and fail with an ImportError. Avoid file names that the standard library already uses (keyword, json, random, test...).

compare.py prints the top result of each method for seven questions.

keywords.py
import re

from corpus import doc_text

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


def words(text: str) -> set[str]:
    """The distinct lowercase words of a text, without common filler words."""
    return {w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP_WORDS}


def keyword_search(query: str, docs: list[dict], k: int = 3) -> list[tuple[str, int]]:
    """Rank documents by how many of the query's words they contain."""
    wanted = words(query)
    scored = []
    for doc in docs:
        overlap = len(wanted & words(doc_text(doc)))
        if overlap > 0:
            scored.append((doc["id"], overlap))
    scored.sort(key=lambda pair: pair[1], reverse=True)
    return scored[:k]
  1. A set literal {...}: like a HashSet, with fast "is this in it?" checks.line 5
  2. re.findall returns every match of the regex: runs of letters and digits. r"..." is a raw string (backslashes are not escapes), the usual way to write regexes. The {w for ...} around it builds a set, so each word counts once.line 13
  3. & on two sets is the intersection (retainAll in Java): the query words that appear in the article.line 21
  4. Articles with no shared word are left out, so keyword search can return nothing at all.line 22
  5. Sort by the score, highest first. Python's sort is stable, so ties keep the file order.line 24
compare.py
import sys

import openai

from cache import EmbeddingCache
from config import settings
from corpus import load_docs
from embedder import Embedder
from keywords import keyword_search
from llm import friendly, make_client
from search import load_index, semantic_search

QUERIES = [
    "stop my monthly plan",
    "the letters are too small",
    "is my information sold to advertisers",
    "listen to books",
    "gift card",
    "VAT number",
    "when will my package come",
]

s = settings()
docs = load_docs()
vectors, ids = load_index(s.embed_model)
cache = EmbeddingCache()
embedder = Embedder(make_client(), s.embed_model, cache=cache)

print(f"{'query':<40}{'keyword':<20}semantic")
try:
    for query in QUERIES:
        kw = keyword_search(query, docs, k=1)
        sem = semantic_search(query, embedder, vectors, ids, k=1)
        kw_text = kw[0][0] if kw else "(nothing)"
        print(f"{query:<40}{kw_text:<20}{sem[0][0]} ({sem[0][1]:.3f})")
except openai.OpenAIError as e:
    sys.exit(friendly(e, s.embed_model))
cache.save()
  1. Reuses the search functions from step 6. Importing search does not run its main().line 11
  2. "gift card": the article is titled "Gift cards" (plural). Plain keyword matching sees cards, not card.line 18
  3. An exact term. Keyword search is good at these: codes, product names, error numbers.line 19
  4. {'query':<40} pads the word "query" to 40 characters: a header row that lines up with the columns below.line 29
  5. An empty list counts as false: kw[0][0] if kw else ... avoids an IndexError when keyword search found nothing.line 34
Run
uv run compare.py
You should seeyour text will differ: the model writes it
query                                   keyword             semantic
stop my monthly plan                    (nothing)           card-declined (0.530)
the letters are too small               (nothing)           text-size (0.602)
is my information sold to advertisers   (nothing)           privacy (0.645)
listen to books                         close-account       offline-reading (0.605)
gift card                               ways-to-pay         ways-to-pay (0.737)
VAT number                              invoices            ways-to-pay (0.614)
when will my package come               gift-cards          missing-parcel (0.639)
Why this way? Read the table row by row; it shows the strengths and weaknesses of each method. Paraphrases ("letters" for font size, "information sold" for personal data, "package" for parcel) find nothing or the wrong article by keyword, and semantic search gets them. Keyword search picks "close-account" for "listen to books" just because the word "books" appears there. But look at "VAT number": keyword search finds "invoices", the article that mentions VAT, while semantic search drifts to "ways-to-pay" because the question sounds like payments. Exact terms, codes and names are where embeddings are weak. "gift card" lands on "ways-to-pay" for both (that article lists gift cards as a way to pay), and "stop my monthly plan" is the near-miss from step 6. So neither method wins everywhere, which is why real systems combine them (the hybrid search lab). The keyword column is exact; the semantic column comes from the model, so your scores may differ a little.
Stuck on this step?
ImportError: cannot import name 'keyword_search' from 'keyword' (.../lib/python3.12/keyword.py)
You named the file keyword.py, and Python found its own standard-library module of that name instead (look at the path in the message). Rename your file to keywords.py and import from keywords.
8

Measure it: a test set and recall@3

One number that says how good the search is, so you can tell whether a change helped.

A few good-looking examples prove nothing. Write down questions real users ask together with the article that answers each one (a test set, or eval set), then count how often the search gets it right.

recall@k is the share of questions whose right article appears in the top k results. We use k = 3: if the article is anywhere in the first three, a reader (or, in the next lab, a language model) will find it. 0.9 means 9 of 10 questions found their article.

recall_at_k takes the search as a function parameter, so the same code measures keyword search and semantic search. Passing functions around is everyday Python, like passing a BiFunction in Java or a callback in JavaScript.

evaluate.py
import sys

import openai

from cache import EmbeddingCache
from config import settings
from corpus import load_docs
from embedder import Embedder
from keywords import keyword_search
from llm import friendly, make_client
from search import load_index, semantic_search

# A question a real user might ask, and the document that answers it.
EVAL = [
    ("I forgot my password", "reset-password"),
    ("can I read on the plane", "offline-reading"),
    ("my payment did not go through", "card-declined"),
    ("I need a receipt for my company", "invoices"),
    ("the book I ordered never showed up", "missing-parcel"),
    ("how much is postage", "delivery-charges"),
    ("do you ship to Canada", "ordering-from-abroad"),
    ("continue reading on another device", "sync-reading-position"),
    ("it got cheaper the day after I bought it", "price-drop"),
    ("talk to a human", "contact-support"),
]


def recall_at_k(search, pairs, k: int = 3) -> tuple[float, list]:
    """Share of queries whose expected document is in the top k, and the queries that missed."""
    misses = []
    for query, expected in pairs:
        found = [doc_id for doc_id, _ in search(query, k)]
        if expected not in found:
            misses.append((query, expected, found))
    return (len(pairs) - len(misses)) / len(pairs), misses


def main() -> None:
    s = settings()
    docs = load_docs()
    vectors, ids = load_index(s.embed_model)
    cache = EmbeddingCache()
    embedder = Embedder(make_client(), s.embed_model, cache=cache)
    systems = {
        "keyword": lambda query, k: keyword_search(query, docs, k),
        "semantic": lambda query, k: semantic_search(query, embedder, vectors, ids, k),
    }
    try:
        for name, search in systems.items():
            recall, misses = recall_at_k(search, EVAL, k=3)
            print(f"{name:<9} recall@3 = {recall:.2f} ({len(EVAL) - len(misses)} of {len(EVAL)})")
            for query, expected, found in misses:
                print(f"   missed {query!r}: wanted {expected}, got {found}")
    except openai.OpenAIError as e:
        sys.exit(friendly(e, s.embed_model))
    cache.save()


if __name__ == "__main__":
    main()
  1. A list of tuples: (question, expected id). Tuples are fixed-size groups of values, like a small record without names.line 14
  2. Easy for both methods: "password" is in the question and in the article.line 15
  3. A paraphrase with no useful shared words: "showed up" for "arrived".line 19
  4. search is any function taking (query, k) and returning (id, score) pairs. Python has no interface for it; anything with that shape works.line 28
  5. for doc_id, _ in ...: _ is the usual name for a value you ignore (the score).line 32
  6. in on a list checks membership, like list.contains(...).line 33
  7. Hits divided by questions, and the misses so you can read them. A score without the failures teaches you nothing.line 35
  8. A lambda is a one-line anonymous function, like (query, k) -> keywordSearch(query, docs, k) in Java. Both adapt a search to the same (query, k) shape.line 45
  9. !r prints the repr() of the value: strings appear in quotes, so you see exactly what was searched.line 53
  10. The tests import recall_at_k from this file; this line keeps the import from running the whole evaluation.line 59
Run
uv run evaluate.py
You should seeyour text will differ: the model writes it
keyword   recall@3 = 0.30 (3 of 10)
   missed 'my payment did not go through': wanted card-declined, got ['refunds', 'missing-parcel', 'end-membership']
   missed 'I need a receipt for my company': wanted invoices, got []
   missed 'the book I ordered never showed up': wanted missing-parcel, got ['pre-orders', 'refunds', 'return-a-book']
   missed 'how much is postage': wanted delivery-charges, got []
   missed 'do you ship to Canada': wanted ordering-from-abroad, got []
   missed 'continue reading on another device': wanted sync-reading-position, got ['two-step-sign-in', 'reading-club', 'end-membership']
   missed 'talk to a human': wanted contact-support, got []
semantic  recall@3 = 0.90 (9 of 10)
   missed 'the book I ordered never showed up': wanted missing-parcel, got ['pre-orders', 'cancel-an-order', 'return-a-book']
Why this way? Keyword search found 3 of 10, semantic search 9 of 10, on questions written the way people really ask. Now read the one miss: the user says "ordered" and "book", and the model ranks "Pre-order a book" first. The article that answers it is titled "An order has not arrived". A test set turns "it feels better" into a number, and its misses tell you what to fix next: a clearer title, more questions, or hybrid search and reranking (later labs). Keep adding real questions from your logs; ten is a start, not a benchmark.
Stuck on this step?
My semantic score is 0.80 or 1.00, not 0.90
Small differences between model builds can move one question in or out of the top 3. With only 10 questions, one question is 0.10. That is a reason to grow the test set, not to worry.
The keyword line differs from the one above
Keyword search does not use the model, so it must match exactly. Compare STOP_WORDS in keywords.py and the lines of docs.jsonl with this page.
9

Test it with a fake embedder

Unit tests for batching, ordering, prefixes, the cache, ranking and recall, in milliseconds and with no model.

Tests should not call a real model: it is slow and its numbers change between versions. The code only uses one thing from the client, client.embeddings.create(model=..., input=[...]), which returns an object with .data, each item having .index and .embedding. 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 gives deterministic vectors: the same text always gets the same numbers. It even "understands" a few synonyms, because words like parcel and package add to the same position in the vector. That is enough to test that semantic search finds a synonym that keyword search misses, without any model.

It returns the results in reverse order on purpose, so the test proves the embedder sorts by index.

test_search.py
from types import SimpleNamespace

import numpy as np
import pytest

from cache import EmbeddingCache
from corpus import doc_text
from embedder import Embedder, normalize
from evaluate import recall_at_k
from keywords import keyword_search
from search import semantic_search, top_k

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


def fake_vector(text: str) -> list[float]:
    """Deterministic: the same text always gives the same 4 numbers."""
    v = [0.0, 0.0, 0.0, 0.1]
    for word in text.lower().replace(":", " ").replace(".", " ").split():
        if word in AXES:
            v[AXES[word]] += 1.0
    return v


class FakeClient:
    """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):
        texts = kwargs["input"]
        self.requests.append(texts)
        data = [SimpleNamespace(index=i, embedding=fake_vector(t)) for i, t in enumerate(texts)]
        return SimpleNamespace(data=data[::-1])  # reversed on purpose: the code must sort by index


DOCS = [
    {"id": "refunds", "title": "Refunds", "text": "We refund the full price."},
    {"id": "delivery", "title": "Delivery", "text": "Every parcel ships in 2 days."},
    {"id": "password", "title": "Password", "text": "Reset your password by email."},
]


def test_rows_keep_their_order_and_have_length_one():
    vectors = Embedder(FakeClient(), "fake").embed(["refund", "parcel", "password"])
    assert vectors.shape == (3, 4)
    assert np.linalg.norm(vectors, axis=1) == pytest.approx([1, 1, 1])
    assert list(vectors.argmax(axis=1)) == [0, 1, 2]


def test_texts_are_sent_in_batches():
    client = FakeClient()
    Embedder(client, "fake", batch_size=16).embed([f"text {i}" for i in range(40)])
    assert [len(batch) for batch in client.requests] == [16, 16, 8]


def test_prefixes_for_documents_and_queries():
    client = FakeClient()
    embedder = Embedder(client, "fake")
    embedder.embed_documents(["Refunds. We refund."])
    embedder.embed_query("money back")
    assert client.requests == [["search_document: Refunds. We refund."], ["search_query: money back"]]


def test_cache_makes_a_rerun_free(tmp_path):
    path = tmp_path / "embeddings.npz"
    first = Embedder(FakeClient(), "fake", cache=EmbeddingCache(path))
    before = first.embed(["refund", "parcel"])
    first.cache.save()

    client = FakeClient()
    cache = EmbeddingCache(path)
    after = Embedder(client, "fake", cache=cache).embed(["refund", "parcel"])
    assert client.requests == []
    assert (cache.hits, cache.misses) == (2, 0)
    assert np.array_equal(before, after)


def test_cache_key_includes_the_model():
    assert EmbeddingCache.key("model-a", "hello") != EmbeddingCache.key("model-b", "hello")


def test_top_k_orders_by_cosine_similarity():
    vectors = normalize(np.array([[1.0, 0.0], [0.6, 0.8], [0.0, 1.0]], dtype=np.float32))
    results = top_k(np.array([1.0, 0.0], dtype=np.float32), vectors, k=2)
    assert [i for i, _ in results] == [0, 1]
    assert [score for _, score in results] == pytest.approx([1.0, 0.6])


def test_semantic_search_finds_a_synonym_that_keyword_search_misses():
    embedder = Embedder(FakeClient(), "fake")
    vectors = embedder.embed_documents([doc_text(d) for d in DOCS])
    ids = [d["id"] for d in DOCS]
    assert keyword_search("where is my package", DOCS) == []
    assert semantic_search("where is my package", embedder, vectors, ids, k=1)[0][0] == "delivery"


def test_recall_at_k_counts_hits_and_lists_misses():
    answers = {"q1": ["a", "b", "c"], "q2": ["d", "e", "f"]}
    search = lambda query, k: [(doc_id, 1.0) for doc_id in answers[query][:k]]
    recall, misses = recall_at_k(search, [("q1", "c"), ("q2", "z")], k=3)
    assert recall == 0.5
    assert misses == [("q2", "z", ["d", "e", "f"])]
  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 means "delivery", 2 means "password". Synonyms share a position.line 14
  3. Position 3 is always 0.1, so no vector is all zeros (a zero vector has no direction).line 19
  4. Lowercase, turn : and . into spaces, split on spaces. So search_document: Delivery. yields the word delivery.line 20
  5. Builds client.embeddings.create out of a simple object, ending at our method.line 31
  6. **kwargs collects every named argument into a dict, so the fake accepts model=... and input=....line 33
  7. data[::-1] is the list reversed (a slice with step -1).line 37
  8. pytest.approx compares floats with a small tolerance. Never compare floats with ==.line 50
  9. argmax(axis=1): the position of the largest number in each row. "refund" points along 0, "parcel" along 1, and so on, which proves the rows are in input order.line 51
  10. 40 texts at 16 per batch: three requests of 16, 16 and 8.line 56
  11. tmp_path is a pytest fixture: a fresh temporary folder for this test, deleted later. pytest passes it in because of the parameter name.line 68
  12. A brand-new cache object reading the same file, like a second run of build_index.py.line 75
  13. The rerun sent no request at all, and got exactly the same numbers.line 77
  14. normalize gives every row length 1, so top_k returns real cosine scores: 1.0 for the same direction, 0.6 for the next row.line 87
  15. No article contains the word "package", so keyword search finds nothing; the fake vectors put "package" next to "parcel".line 97
  16. A fake search: a lambda that returns fixed results. Testing recall_at_k does not need embeddings at all.line 103
Run
uv run pytest -q
You should see
........                                                                 [100%]
8 passed in 0.40s
Why this way? These tests check your code: batching, ordering, prefixes, caching, ranking and the metric. How well a particular model ranks your articles is a different question, answered by the test set in evaluate.py. Keep both: unit tests on every commit, the evaluation whenever you change the model, the prefixes or the documents.
Stuck on this step?
ModuleNotFoundError: No module named 'embedder'
Run pytest from the project folder (where embedder.py is) with uv run pytest -q.

Check it works

Three checks: the tests pass with no model, the index builds (from the cache, so instantly), and the evaluation prints both recall lines.

Keyword search should be exactly 0.30. Semantic search should be around 0.90; one question more or less is normal between model builds.

Test
uv run pytest -q && uv run build_index.py && uv run evaluate.py
You should see
8 passed in 0.40s
30 documents: 0 embedded in 0 requests, 30 from the cache (0.00s)
saved index/vectors.npy: shape (30, 768), float32, 92,160 bytes
keyword   recall@3 = 0.30 (3 of 10)
   ...
semantic  recall@3 = 0.90 (9 of 10)
   missed 'the book I ordered never showed up': wanted missing-parcel, got ['pre-orders', 'cancel-an-order', 'return-a-book']

Troubleshooting

Model 'nomic-embed-text' not found. Run: ollama pull nomic-embed-text

The model is not on this machine (or EMBED_MODEL has a typo). Run ollama pull nomic-embed-text and check with ollama list.

Results are poor: unrelated articles rank first

Check the prefixes. Documents must be embedded with search_document: and queries with search_query: , and the index must be rebuilt after you change either one (the cache key includes the prefix, so the rebuild re-embeds automatically).

Every score is between 0.4 and 0.8. Is 0.5 a good match?

Cosine scores from one model are only meaningful compared with each other. Do not hard-code a threshold like "above 0.7 is relevant"; if you need one (for "no good answer found"), choose it from your test set, and choose it again when you change models.

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0 ... (size 1024 is different from 768)

The query and the index come from models with different vector sizes. load_index normally prevents this; if you built index/ some other way, delete it and run uv run build_index.py.

Long documents give worse results

One vector has to summarise the whole text, so a long page with many topics ends up "about everything". Embedding models also have an input limit, and servers cut off or reject longer text. Split long documents into chunks of a few hundred words before embedding: the next lab does exactly that.

What changes in production

  • Store the model name with the vectors, and re-embed everything when it changes. Vectors from two models (or two versions of one model) cannot be compared. Plan a full rebuild as part of any model upgrade.
  • Embed at write time, not at query time. Articles are embedded once when they are added or edited (with a content-hash cache like this one); a search only embeds the query. Batch the writes, and respect the provider's limits on texts and tokens per request.
  • Brute force first, then a vector store. A NumPy dot product over tens of thousands of vectors is milliseconds. You need pgvector or a vector database when you have millions of vectors, frequent updates, or filters like "only this customer's documents" (the RAG lab uses pgvector).
  • Keep a test set and track recall@k on every change. Add the questions users really ask, especially the ones that failed. Combine with keyword search for exact terms like order numbers and product codes (the hybrid search lab).

Interview angle

“How does semantic search work, and how do you know it is any good?”

An embedding model turns each document into a fixed-length vector, trained so that texts with similar meaning point in similar directions. I embed the documents once, in batches, with a content-hash cache so unchanged documents are never re-embedded, and store the vectors with the model name. At query time I embed the query with the same model (with the query instruction the model expects, like search_query: for nomic-embed-text), score every document by cosine similarity, which is a plain dot product when the vectors are normalized, and return the top k. Brute force is fine up to large collections; beyond that, or with filters, I use an approximate index like HNSW in pgvector. To know it is good I keep a test set of real queries with the expected document and track recall@k, and I read the misses. I compare against keyword search, because exact terms like codes and names are where embeddings are weak, and that usually leads to hybrid search.

Clean up

Keep the project: the RAG lab builds on embedder.py, cache.py and search.py. The index/ and cache/ folders can be deleted any time; uv run build_index.py recreates them. Keep the embedding model too, the next lab uses it.

Run
rm -rf index cache

Practice

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

Cosine similarity by hand

Write cosine(a, b) for two lists of numbers of the same length, without NumPy: the dot product divided by the product of the two lengths (a length is the square root of the sum of squares). If either vector is all zeros, return 0.0 instead of dividing by zero.

Exercise
import math


def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot


print(cosine([1, 0], [1, 1]))
Hint

Compute `na = math.sqrt(sum(x * x for x in a))` and the same for `b`. If `na == 0 or nb == 0`, return `0.0`; otherwise return `dot / (na * nb)`.

Mean reciprocal rank

recall@3 only asks "is it in the top 3?". Mean reciprocal rank (MRR) also rewards ranking it first. For each query, take 1 divided by the position of the expected document (1 for first, 1/2 for second, 1/3 for third), or 0 if it is missing. MRR is the average over all queries. Write mrr(results, expected) where results is a list of ranked id lists (one per query) and expected is the list of right ids.

Exercise
def mrr(results, expected):
    total = 0.0
    for found, want in zip(results, expected):
        if want in found:
            total += 1
    return total / len(expected)


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

`found.index(want)` gives the 0-based position, so the rank is that plus 1. Add `1 / rank` instead of 1.

The full project

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

Download Python project (.zip) Download Java project (.zip)