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
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.pyand 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.
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" 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.
uv --version 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.
ollama --version 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.
ollama pull nomic-embed-text 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.
curl http://localhost:11434/v1/embeddings -H "Content-Type: application/json" -d '{"model": "nomic-embed-text", "input": "hello"}'curl http://localhost:11434/v1/embeddings -H "Content-Type: application/json" -d '{"model": "nomic-embed-text", "input": "hello"}'Invoke-RestMethod -Uri http://localhost:11434/v1/embeddings -Method Post -ContentType "application/json" -Body '{"model": "nomic-embed-text", "input": "hello"}' | ConvertTo-Json -Depth 4 {"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.
brew install openjdk@21 mavensudo apt install openjdk-21-jdk mavenwinget install Microsoft.OpenJDK.21 Apache.Maven 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.
# 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 - The same OpenAI-compatible base URL as lab 1. The embeddings endpoint lives next to the chat one:
/v1/embeddings.line 2 - The chat model from lab 1. This lab does not use it; the RAG lab after this one does.line 4
- The new setting: which model turns text into vectors.line 5
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"),
) load_dotenv()copies.envintoos.environ. Variables already set in your shell take priority, which is what you want on a server.line 6@dataclasswrites the constructor for you, like a Java record.frozen=Truemakes it read-only.line 9- New: the embedding model, with the same default as
.env.line 22
.venv/
__pycache__/
.env
cache/
index/ - Never commit
.env: one day it holds a real key.line 3 cache/andindex/are generated by the scripts (steps 4 and 5). Anyone can rebuild them fromdocs.jsonl.line 4
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}" - A function, not a global: the tests in step 9 never call it. They hand the code a fake client instead.line 7
max_retries=2: the SDK retries timeouts, 429 and 5xx errors with backoff before it raises.line 9openai.OpenAIErroris the base class of every SDK error. The scripts catch it once and printfriendly(e, ...).line 12isinstance(x, C)is Java'sx instanceof C. The timeout check comes first on purpose:APITimeoutErroris a subclass ofAPIConnectionError, so the other order would report a slow server as "cannot reach".line 14- Ollama answers 404 when the model has not been pulled. The message tells the user the exact command.line 18
uv init semantic-search
cd semantic-search
uv add numpy openai python-dotenv
uv add --dev pytest 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 ...
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.
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.
{"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."} - 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 - 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
- The answer to "stop my monthly plan". The words "stop", "monthly" and "plan" appear nowhere in it.line 21
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']}" list[dict]is the type hint for a list of dictionaries, likeList<Map<String, Object>>. Python does not enforce hints; they document the code and help your editor.line 5Path(...).read_text()reads the whole file into a string (Files.readStringin Java).splitlines()splits it into lines.line 8line.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 9json.loadsparses one line of JSON into a dict, likeJSON.parse.line 10- An f-string: the values in
{...}are put into the text. Single quotes inside, because the f-string itself uses double quotes.line 16
uv run python -c "from corpus import load_docs, doc_text; docs = load_docs(); print(len(docs)); print(doc_text(docs[0]))" 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.
Stuck on this step?
json.decoder.JSONDecodeError: Expecting value- A line in
docs.jsonlis not complete JSON, often because an editor wrapped a long line. Every article must be on exactly one line.
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.
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}") import numpy as np: everyone imports NumPy under the short namenp.line 1- The question gets
search_query:. The answer shares only one word with it ("back").line 7 - The texts we search through get
search_document:.line 8 - One request with four texts. Behind the scenes the SDK asks for the numbers in a compact base64 form and decodes them, so
item.embeddingis always a plain list of floats.line 12 - A list comprehension (
[... for item in ...], likestream().map(...).toList()) collects the four lists.np.arrayturns them into one 4 x 768 table of 32-bit floats (Javafloat), half the memory of Python's default 64-bit floats.line 13 .shapeis the size of each dimension:(4, 768)is 4 rows of 768 numbers.line 15vectors[0, :5]is row 0, columns 0 to 4.:5is a slice: "up to, not including, 5".line 16np.linalg.normis 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@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 21texts[1:]is every item except the first.zipwalks two lists side by side, like a loop over two indexes at once.line 25:.3fprints three decimals, like%.3finString.format.line 26
uv run first_embedding.py 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.
Stuck on this step?
Model 'nomic-embed-text' not foundoropenai.NotFoundError: 404- Run
ollama pull nomic-embed-textand check the name withollama 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.
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).
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] - The two prefixes from step 3, as constants. Upper-case names at module level are Python's convention for constants (
static final).line 3 axis=-1measures the length of each row (the last dimension) instead of the whole table.keepdims=Truekeeps the result as a column, shape(rows, 1), so the division on the next line lines up row by row.line 9- 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 __init__is the constructor andselfisthis, written out. No type forclient: anything withembeddings.create(...)works, which is how the tests pass a fake.line 14range(0, 30, 16)gives 0 and 16: the start of each batch, likefor (start = 0; start < 30; start += 16).line 23- A slice: items
startup to (not including)start + 16. Past the end it simply stops, so the last batch can be shorter.line 24 - Each result carries the
indexof its input text. Sorting by it guarantees row 5 is text 5, whatever order the server used.key=lambda d: d.indexisComparator.comparing(d -> d.index).line 27 - All rows become one
float32table, then every row is scaled to length 1.line 29 - Articles get the document prefix.
DOC_PREFIX + tis string concatenation.line 31 - 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
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") - One embedder for the whole run, 16 texts per request.line 16
time.perf_counter()is a precise clock for measuring durations, likeSystem.nanoTime()but in seconds.line 18- All 30 articles in one call. The embedder splits them into batches itself.line 20
sys.exit("text")prints the text to stderr and ends the program with exit code 1. No stack trace for the common errors.line 22exist_ok=True: no error if the folder is already there (mkdir -p).line 25np.savewrites the array in.npyformat: a small header with the shape and type, then the raw bytes.np.loadgives the identical array back.line 26- Row
iof the array belongs toids[i]. The model name is saved with the vectors so search can check it.line 27 .nbytesis the size in memory: 30 x 768 numbers x 4 bytes.:,adds thousands separators.line 31
uv run build_index.py 30 documents embedded in 2 requests (3.49s) saved index/vectors.npy: shape (30, 768), float32, 92,160 bytes
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.pyoutside the project environment. Useuv run build_index.py.
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.
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) str | Pathmeans "a string or a Path". The tests pass a temporaryPath; the scripts use the default.line 10with ... as saved:closes the file at the end of the block, like Java's try-with-resources.line 14- A dict comprehension:
{key: value for ...}builds a dict in one expression.saved.fileslists the names of the arrays inside the.npzfile.line 15 @staticmethod: a method that needs no object, called asEmbeddingCache.key(...), like a Javastaticmethod.line 19- 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 - The return type
np.ndarray | Noneis Java's "nullable": a vector, orNoneon a miss.line 23 dict.get(key)returnsNonewhen the key is missing, instead of raising an error.line 24**self.vectorspasses every dict entry as a named argument:np.savez(path, abc123=vec1, def456=vec2, ...). Each name becomes one array in the file.line 36
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] - The cache is optional (
Noneby default), so the embedder still works without one, as in the tests.line 16 - One slot per text, filled from the cache or from the API.
[None] * 3is[None, None, None].line 25 todoholds the **positions** of the texts the cache does not have.line 26enumerategives (position, text) pairs, like a loop with an index.line 27- Python's conditional expression:
a if condition else biscondition ? a : b. We writeis not Nonerather thanif self.cache, because an object can define its own idea of true and false.line 28 - The same batching as before, but only over the misses. All hits:
todois empty and no request is sent.line 33 [texts[i] for i in batch]: the texts at those positions.line 35zippairs each position with its result, both in input order.line 37- Each vector is normalized on its own before it is cached, so cached and fresh vectors are the same.line 38
np.vstackstacks the rows into one table, likenormalize(np.array(...))did before, but from a mix of cached and new rows.line 42
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") - Load whatever earlier runs saved. The first run starts with an empty cache.line 17
- Save after a successful run. If the run fails half way, nothing is saved, and the next run simply embeds again.line 26
- Two f-strings next to each other inside the parentheses join into one line of output.line 33
uv run build_index.py
uv run build_index.py 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
Stuck on this step?
- The second run still says
30 embedded - The cache was not saved: check that
cache.save()is inbuild_index.pyand thatcache/embeddings.npzexists. Run both commands from the project folder. - I changed
EMBED_MODELand everything was embedded again - Correct: the model name is part of the key, and vectors from another model must not be reused.
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).
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() tuple[np.ndarray, list[str]]: the function returns two values, the vectors and the ids. The caller unpacks them withvectors, ids = load_index(...).line 16/onPathobjects joins path parts, likePath.resolvein Java:index/meta.json.line 17- 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
- Matrix times vector: (30 x 768) times (768) gives 30 scores, one per article, in one fast call.line 25
np.argsortreturns the **positions** that would sort the array, smallest first. Sorting-scoresputs the highest score first.kind="stable"keeps equal scores in file order, so results are repeatable.[:k]keeps the first k.line 26int(...)andfloat(...)turn NumPy's number types into plain Python ones, which print and compare cleanly.line 27- The query gets the
search_query:prefix insideembed_query.line 31 - Row numbers become article ids: row
ibelongs toids[i].line 32 - A positional argument: the first word (or quoted phrase) after the script name.line 37
- An option:
-k 5shows five results.type=intconverts the text "5" to the number 5.line 38 - No
index/folder yet: tell the user the one command that fixes it.line 44 - A dict from id to title, built in one expression, to print readable results.line 49
- Queries are cached too. Search the same question twice and the second time sends no request.line 50
enumerate(..., start=1)numbers the results from 1.(doc_id, score)unpacks each pair.:<24pads the id to 24 characters, so the titles line up.line 58main()runs only when you start this file (uv run search.py), not when another file imports it.line 62
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.5</version>
</parent>
<groupId>dev.algorung</groupId>
<artifactId>semantic-search</artifactId>
<version>0.1.0</version>
<properties>
<java.version>21</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project> - Spring Boot 3.4 with Java 21, the same as lab 1.line 8
- The Spring AI BOM keeps every Spring AI module on the same version.line 20
- The Ollama starter from lab 1. It sets up an
EmbeddingModelas well as a chat model.line 30
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.embedding.options.model=nomic-embed-text
spring.ai.model.chat=none
spring.main.web-application-type=none - Which model Spring AI's
EmbeddingModeluses. Without this line it uses a different default model, which you have not pulled.line 2 - This app only embeds, so the chat model is switched off.line 3
- A command-line app: no web server.line 4
package dev.algorung;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SemanticSearch {
public record Doc(String id, String title, String text) {}
record Hit(Doc doc, double score) {}
public static void main(String[] args) {
SpringApplication.run(SemanticSearch.class, args);
}
@Bean
CommandLineRunner run(EmbeddingModel embeddingModel) {
return args -> {
ObjectMapper json = new ObjectMapper();
List<Doc> docs = new ArrayList<>();
for (String line : Files.readAllLines(Path.of("docs.jsonl"))) {
if (!line.isBlank()) docs.add(json.readValue(line, Doc.class));
}
List<String> texts = docs.stream()
.map(d -> "search_document: " + d.title() + ". " + d.text())
.toList();
List<float[]> vectors = embeddingModel.embed(texts);
String query = args.length > 0 ? String.join(" ", args) : "stop my monthly plan";
float[] q = embeddingModel.embed("search_query: " + query);
IntStream.range(0, docs.size())
.mapToObj(i -> new Hit(docs.get(i), cosine(q, vectors.get(i))))
.sorted(Comparator.comparingDouble(Hit::score).reversed())
.limit(3)
.forEach(h -> System.out.printf("%.3f %-24s %s%n", h.score(), h.doc().id(), h.doc().title()));
};
}
static double cosine(float[] a, float[] b) {
double dot = 0, na = 0, nb = 0;
for (int i = 0; i < a.length; i++) {
dot += a[i] * b[i];
na += a[i] * a[i];
nb += b[i] * b[i];
}
return dot / (Math.sqrt(na) * Math.sqrt(nb));
}
} - One line of
docs.jsonl. Jackson maps JSON objects straight onto records.line 19 - Spring AI builds an
EmbeddingModelfor Ollama from the properties. You ask for it like any other bean.line 28 - JSON Lines in Java: read every line and parse each one on its own, like
load_docs().line 33 - The same
search_document:prefix and the same "title. text" ascorpus.doc_text(). Spring AI does not add prefixes either.line 37 - The embed step: a list of texts in, one
float[]per text out, in the same order. This sends the whole list at once; for thousands of texts, split it into batches yourself, asEmbedderdoes.line 39 - One text in, one
float[]out: the query vector, with the query prefix.line 42 - Score every article and keep the best 3, like
top_k. Fine for a few thousand articles; a vector store does this at scale (the RAG lab).line 44 - Cosine similarity written out: dot product divided by both lengths. The Python version normalizes once and only needs the dot product.line 52
Java (Spring AI) version of this step:
uv run search.py "stop my monthly plan" 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
mvn -q spring-boot:run -Dspring-boot.run.arguments="stop my monthly plan" 0.530 card-declined Card declined at checkout 0.509 end-membership End your Reading Club membership 0.505 reading-club Reading Club membership
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_MODELafter building. Runuv run build_index.pyagain. - Java:
model "mxbai-embed-large" not found - The
spring.ai.ollama.embedding.options.modelline is missing, so Spring AI used its own default model. Add it, or pull that model. - Java:
NoSuchFileException: docs.jsonl - Copy
docs.jsonlinto the Java project folder (next topom.xml) and run Maven from there.
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.
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] - A set literal
{...}: like aHashSet, with fast "is this in it?" checks.line 5 re.findallreturns 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&on two sets is the intersection (retainAllin Java): the query words that appear in the article.line 21- Articles with no shared word are left out, so keyword search can return nothing at all.line 22
- Sort by the score, highest first. Python's sort is stable, so ties keep the file order.line 24
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() - Reuses the search functions from step 6. Importing
searchdoes not run itsmain().line 11 - "gift card": the article is titled "Gift cards" (plural). Plain keyword matching sees
cards, notcard.line 18 - An exact term. Keyword search is good at these: codes, product names, error numbers.line 19
{'query':<40}pads the word "query" to 40 characters: a header row that lines up with the columns below.line 29- An empty list counts as false:
kw[0][0] if kw else ...avoids anIndexErrorwhen keyword search found nothing.line 34
uv run compare.py 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)
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 tokeywords.pyand import fromkeywords.
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.
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() - A list of tuples:
(question, expected id). Tuples are fixed-size groups of values, like a small record without names.line 14 - Easy for both methods: "password" is in the question and in the article.line 15
- A paraphrase with no useful shared words: "showed up" for "arrived".line 19
searchis any function taking(query, k)and returning(id, score)pairs. Python has no interface for it; anything with that shape works.line 28for doc_id, _ in ...:_is the usual name for a value you ignore (the score).line 32inon a list checks membership, likelist.contains(...).line 33- Hits divided by questions, and the misses so you can read them. A score without the failures teaches you nothing.line 35
- A
lambdais 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 !rprints therepr()of the value: strings appear in quotes, so you see exactly what was searched.line 53- The tests import
recall_at_kfrom this file; this line keeps the import from running the whole evaluation.line 59
uv run evaluate.py 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']
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_WORDSinkeywords.pyand the lines ofdocs.jsonlwith this page.
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.
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"])] SimpleNamespace(a=1)is a quick object with an attributea, like the JavaScript object literal{a: 1}.line 1- Position 0 means "refund", 1 means "delivery", 2 means "password". Synonyms share a position.line 14
- Position 3 is always 0.1, so no vector is all zeros (a zero vector has no direction).line 19
- Lowercase, turn
:and.into spaces, split on spaces. Sosearch_document: Delivery.yields the worddelivery.line 20 - Builds
client.embeddings.createout of a simple object, ending at our method.line 31 **kwargscollects every named argument into a dict, so the fake acceptsmodel=...andinput=....line 33data[::-1]is the list reversed (a slice with step -1).line 37pytest.approxcompares floats with a small tolerance. Never compare floats with==.line 50argmax(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- 40 texts at 16 per batch: three requests of 16, 16 and 8.line 56
tmp_pathis a pytest fixture: a fresh temporary folder for this test, deleted later. pytest passes it in because of the parameter name.line 68- A brand-new cache object reading the same file, like a second run of
build_index.py.line 75 - The rerun sent no request at all, and got exactly the same numbers.line 77
normalizegives every row length 1, sotop_kreturns real cosine scores: 1.0 for the same direction, 0.6 for the next row.line 87- No article contains the word "package", so keyword search finds nothing; the fake vectors put "package" next to "parcel".line 97
- A fake search: a lambda that returns fixed results. Testing
recall_at_kdoes not need embeddings at all.line 103
uv run pytest -q ........ [100%] 8 passed in 0.40s
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.pyis) withuv 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.
uv run pytest -q && uv run build_index.py && uv run evaluate.py 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.
rm -rf index cacherm -rf index cacheRemove-Item -Recurse -Force index, cache -ErrorAction SilentlyContinue 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.
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.
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.