Store embeddings and search by meaning
Save local embeddings with their source text and model identity, then use them to find paraphrases across sessions.
On this page
Add a vector index
Reuse the notes folder and index_notes.py from the text search lab. Save this script beside index_notes.py. Keep Ollama running and download the embedding model if needed. On macOS or Linux use python3 if python is unavailable. On Windows use py -3.
View semantic_notes.py
import argparse
from contextlib import closing
from itertools import islice
import json
import math
from pathlib import Path
import sqlite3
from urllib.error import HTTPError
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
BASE = "http://127.0.0.1:11434"
MODEL = "all-minilm:latest"
MAX_PASSAGES = 200
class NoRedirects(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def api(endpoint, payload=None):
request = Request(BASE + endpoint)
if payload is not None:
request.data = json.dumps(payload).encode("utf-8")
request.add_header("Content-Type", "application/json")
opener = build_opener(ProxyHandler({}), NoRedirects())
with opener.open(request, timeout=120) as response:
return json.load(response)
def model_digest():
for model in api("/api/tags")["models"]:
if model["name"] == MODEL:
return model["digest"]
raise ValueError(f"Pull {MODEL} with Ollama first.")
def embed(texts):
result = api("/api/embed", {
"model": MODEL,
"input": texts,
"truncate": False,
})["embeddings"]
if len(result) != len(texts):
raise ValueError("Ollama returned the wrong number of embeddings.")
return result
def cosine(left, right):
if len(left) != len(right):
raise ValueError("Vector dimensions changed. Rebuild the index.")
length = math.hypot(*left) * math.hypot(*right)
return sum(x * y for x, y in zip(left, right)) / length if length else 0
def build_index(folder, database):
from index_notes import passages
rows = list(islice(passages(folder), MAX_PASSAGES + 1))
if not rows or len(rows) > MAX_PASSAGES:
raise ValueError(f"Use 1–{MAX_PASSAGES} nonempty passages for this example.")
digest = model_digest()
stored = []
for start in range(0, len(rows), 16):
batch = rows[start:start + 16]
vectors = embed([text for _, _, text in batch])
stored.extend((*row, json.dumps(vector)) for row, vector in zip(batch, vectors))
if model_digest() != digest:
raise ValueError("The embedding model changed during indexing. Build the index again.")
with closing(sqlite3.connect(database)) as connection, connection:
connection.execute("CREATE TABLE IF NOT EXISTS model (name TEXT, digest TEXT)")
connection.execute(
"CREATE TABLE IF NOT EXISTS passages "
"(source TEXT, number INTEGER, text TEXT, vector TEXT)"
)
connection.execute("DELETE FROM passages")
connection.execute("DELETE FROM model")
connection.execute("INSERT INTO model VALUES (?, ?)", (MODEL, digest))
connection.executemany("INSERT INTO passages VALUES (?, ?, ?, ?)", stored)
print(f"Saved {len(stored)} embeddings in {database}.")
def find_notes(database, query):
if not query.strip() or not database.is_file():
raise ValueError("Build the index and enter a nonempty question.")
with closing(sqlite3.connect(database.resolve().as_uri() + "?mode=ro", uri=True)) as connection:
connection.execute("BEGIN")
identity = connection.execute("SELECT name, digest FROM model").fetchone()
rows = connection.execute("SELECT source, number, text, vector FROM passages").fetchall()
digest = model_digest()
if identity != (MODEL, digest):
raise ValueError("The embedding model differs from the one in the index. Rebuild it.")
vector, = embed([query])
if model_digest() != digest:
raise ValueError("The embedding model changed during the query. Rebuild the index.")
matches = [
(cosine(json.loads(embedding), vector), source, number, text)
for source, number, text, embedding in rows
]
ranked = sorted(matches, key=lambda match: match[0], reverse=True)
for score, source, number, text in ranked[:3]:
print(f"{score:.3f} | {source}, passage {number}\n{text}\n")
def main():
parser = argparse.ArgumentParser(description="Store local embeddings and search them later.")
parser.add_argument("--db", type=Path, default=Path("notes-vectors.sqlite3"))
commands = parser.add_subparsers(dest="command", required=True)
build = commands.add_parser("build")
build.add_argument("folder", type=Path)
find = commands.add_parser("find")
find.add_argument("query")
args = parser.parse_args()
try:
if args.command == "build":
build_index(args.folder, args.db)
else:
find_notes(args.db, args.query)
except HTTPError as error:
raise SystemExit(f"Ollama returned HTTP {error.code}: {error.read().decode()}") from None
except (OSError, sqlite3.Error, ValueError) as error:
raise SystemExit(str(error)) from None
if __name__ == "__main__":
main()ollama pull all-minilm
python semantic_notes.py build notes
python semantic_notes.py find "How long may I borrow books?"
The build step sends passages to the local embedding endpoint in small batches. It stores the vectors, passage text, source filename, and embedding model digest in notes-vectors.sqlite3. Search embeds just the question, reads the saved vectors, and ranks them by cosine similarity.
With the supplied notes, the results should include the passage about 21-day book loans. Check the source filename and passage number to verify it. The query asks about borrowing, while the note uses the word “loans.”
Compare with keyword search
Run the same question through index_notes.py find. Its all-words query is unlikely to match this wording. Try an exact identifier such as “Room 204” in both tools. Record which system ranks the correct passage higher for each kind of query.
The vector search returns the nearest candidates even for unrelated questions. Check whether any passage supports an answer before handing it to a chat model. The similarity score is a ranking signal. Choose any rejection threshold using relevant and unrelated questions from your collection.
Refresh an index and repeat the query
Change the book loan to 14 days, rebuild, and confirm that the retrieved passage reflects the edit. Rebuild again whenever you swap embedding models. This script checks the model digest so a change to the files behind a tag is visible. It uses a linear scan and limits the index to 200 passages for the lab.
Check your understanding
Two embedding models both produce 384-number vectors. Can you embed a query with one model and compare it to passages embedded by the other?
Use the same model revision for both. Equal vector length by itself says nothing about whether their coordinates mean the same thing.
Sources
Progress is saved in this browser.