Create Embeddings Locally with Ollama, Hands-On
A support colleague asks the handbook assistant "Can a customer get their money back?" The handbook never says "money back"; it says "refund", so a search that matches words finds nothing. To search by meaning, each chunk from the last lesson needs an embedding. In this lesson you create embeddings locally with Ollama, compare them with cosine similarity, and save a vector for every chunk of the handbook.
Embeddings: meaning as a list of numbers
An embedding is a list of numbers that a model computes for a piece of text, so that texts with similar meanings get similar lists. What Are Embeddings? explains the idea; here you make them. Such a list is a vector, and how many numbers it holds is its dimension.
An embedding model is trained for that one job: text in, one vector out, no reply text. You use nomic-embed-text, an open model from Nomic that Ollama can download. It is about 300 MB on disk, against about 2 GB for llama3.2:3b, and every vector it makes has 768 numbers, however long the text.
Pull nomic-embed-text and call /api/embed
In 01-ollama-setup, with the container from lesson 1 running, pull the model once. It ends with success, and without a tag the name means nomic-embed-text:latest, as ollama list then shows:
docker compose exec ollama ollama pull nomic-embed-text
Ollama serves embeddings on the same port 11434 as chat, at POST /api/embed. The JSON body names the model and gives the input, one string or a list of strings. Try one string with curl:
curl http://localhost:11434/api/embed -d '{"model": "nomic-embed-text", "input": "refund policy"}'
The reply is one long line. Here it is trimmed, and the numbers are illustrative:
{"model":"nomic-embed-text","embeddings":[[0.0153,0.0402,-0.1617,-0.0146,0.0569, ...]],
"total_duration":...,"load_duration":...,"prompt_eval_count":...}
embeddings is a list of vectors, one per input, even for a single string, and prompt_eval_count is the number of tokens read, as in lesson 2. Send a list such as ["refund policy", "office parking"] and one request returns one vector per text, in the same order. A typo in the model name gets HTTP 404 with not found; curl's Failed to connect means the container is stopped.
A text longer than the model's context window is cut at the end by default ("truncate": true in the API docs), so its vector ignores the tail. An 800-character chunk is far shorter.
Compare meanings with cosine similarity
Picture each vector as an arrow from a common starting point. Cosine similarity is the cosine of the angle between two arrows: 1.0 when they point the same way, 0 at a right angle, −1.0 when opposite. It compares direction and ignores length. The lab computes it in plain Python:
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b)) # multiply pair by pair, then add up
norm_a = math.sqrt(sum(x * x for x in a)) # the length of each arrow
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
With NumPy it is np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)). Ollama's docs say /api/embed returns unit-length vectors, arrows of length 1, so here the cosine equals the dot product; the full formula also works for vectors from elsewhere. The lab's version also refuses vectors of different lengths, because zip() would quietly stop at the shorter one.
One detail belongs to this model: it was trained with a task label at the start of each text, search_query: for the text you search with and search_document: for the texts you search through. embed_demo.py treats "refund policy" as the query, the other two phrases as documents, and sends all three in one request.
In course-labs/building-llm-apps/08-embeddings, set up a virtual environment and pip install -r requirements.txt as in lesson 2, then run python3 embed_demo.py. The lines come from the script; the numbers are illustrative, and yours will differ:
Model: nomic-embed-text | 3 texts in one request -> 3 vectors
Each vector has 768 numbers
First 5 numbers for 'refund policy': 0.0153, 0.0402, -0.1617, -0.0146, 0.0569
Norm (its length as an arrow): 1.000
Cosine similarity with 'refund policy':
0.712 money back rules
0.418 office parking
Closest in meaning: 'money back rules'
It worked if each vector has 768 numbers, the norm is 1.000, and money back rules comes first by a clear margin, although it shares no word with "refund policy". Do not expect 0 for the unrelated phrase: compare scores with each other, not with a fixed line.
Embed every chunk in batches
embed_chunks.py embeds the whole handbook. It loads chunk.py from 07-chunking and cuts the handbook exactly as the last lesson did, with --mode headings --size 800, so you get the same 34 chunks without needing a saved chunks.jsonl. It then sends the texts in batches, groups of up to 32 texts per request.
Why batches? One request per chunk means a round trip each; one request for thousands of chunks is a long call that can time out and lose everything. Each chunk also gets an id, its source file and start offset, such as 05-customer-returns.md#137. The core of the loop, simplified:
for batch in batches(chunks, 32):
texts = [DOCUMENT_PREFIX + chunk["text"] for chunk in batch] # "search_document: ..."
vectors.extend(embed(texts, model)) # one POST /api/embed per batch
The vectors come back in the order of the input, so vector number i belongs to chunk number i. Run python3 embed_chunks.py in 08-embeddings. The time varies; the counts do not:
Read 34 chunks from 6 files in ../07-chunking/data/handbook (chunk.py --mode headings --size 800)
Embedding with nomic-embed-text, 32 chunks per request:
batch 1/2: chunks 1-32 -> 32 vectors
batch 2/2: chunks 33-34 -> 2 vectors
Done in 4.2 s: 34 vectors of 768 numbers
Saved to embeddings.json (model: nomic-embed-text, first id: 01-welcome.md#0)
It worked if there are two batches, 32 and 2, and 34 vectors. Each record in embeddings.json holds id, source, section, start, length, text and embedding. ../07-chunking/data/handbook is not a folder means you ran it outside 08-embeddings.
One model for documents and questions
Every embedding model builds its own map of meaning. Vectors from two models are like postal codes from two countries: both are numbers, but comparing them means nothing. If their lengths differ, the maths fails loudly. If two models both happen to give 768 numbers, it fails silently, with scores that look normal and are not.
So embed documents and questions with the same model, and with this model, the matching labels. If you change the model, re-embed every chunk, because old and new vectors cannot be mixed. Re-embed any chunk whose text changes, too. That is why embeddings.json also stores model, document_prefix and query_prefix: the code that searches it can check them. Searching it is the next lesson.
Check yourself
"Money back rules" scores high against "refund policy", yet they share no word. Why can an embedding search find it when a keyword search cannot?
The model was trained to place texts with related meanings in similar directions, and cosine similarity compares those directions, not the spelling. A keyword search only sees that no word matches.
You switch to a new embedding model that also gives 768 numbers, but keep the old embeddings.json and embed only new questions. What happens?
No error, because the lengths match, but the scores are meaningless: each model has its own map, so a new question vector cannot be compared with old chunk vectors. Re-embed every chunk with the new model.
"Office parking" scores 0.418 against "refund policy", not 0. Is something broken?
No. Embeddings of unrelated texts are rarely at right angles, so their cosine stays above 0. What matters is the gap: the related phrase scores clearly higher.