Sub topic 12
Generating embeddings locally
This chapter assumes you can run Ollama and call its REST API from a script, as covered in the earlier chapters. You should also know what a vector is, meaning a list of numbers.
What an embedding is
An embedding is a list of numbers that represents the meaning of a piece of text. Texts with similar meaning get vectors that point in similar directions. Programs use embeddings for semantic search, document clustering, and retrieval, where you fetch the passages most relevant to a question.
Embeddings come from embedding models, which are separate from chat models. A chat model produces text. An embedding model produces only a vector. Using a chat model for embeddings usually gives poor results and runs slowly.
Pull an embedding model
Pull a dedicated embedding model such as nomic-embed-text. Embedding models are small, so the download is quick.
ollama pull nomic-embed-textCall the embed endpoint
The /api/embed endpoint accepts a model name and an input. The input can be one string or a list of strings. The response has an embeddings field holding one vector per input.
curl http://localhost:11434/api/embed -d '{
"model": "nomic-embed-text",
"input": ["The cat sat on the mat.", "A kitten rested on the rug."]
}'Older material may show /api/embeddings with a prompt field. That older endpoint handles one text at a time. Prefer /api/embed, which also accepts batches.
Compare texts with cosine similarity
Cosine similarity measures the angle between two vectors. A score near 1 means the texts are close in meaning. A score near 0 means they are unrelated.
import math
import requests
def embed(texts):
resp = requests.post(
"http://localhost:11434/api/embed",
json={"model": "nomic-embed-text", "input": texts},
timeout=120,
)
resp.raise_for_status()
return resp.json()["embeddings"]
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
texts = [
"The cat sat on the mat.",
"A kitten rested on the rug.",
"Quarterly revenue grew by four percent.",
]
vectors = embed(texts)
print(len(vectors[0]))
print(cosine(vectors[0], vectors[1]))
print(cosine(vectors[0], vectors[2]))The first printed number is the vector length, called its dimension. Every text sent to one model produces vectors of the same length. The second score, for the two animal sentences, should be clearly higher than the third.
Common errors
- Mixing models. Vectors from different models are not comparable, even when their lengths match. Embed your documents and your queries with the same model. If you switch models, re-embed everything.
- Using a chat model. The call may work, but the vectors are weaker and slower to compute.
- Sending one text per request. Batch many texts in one
inputlist to cut request overhead. - Text longer than the context window. Long inputs may be truncated, so split documents into chunks first.
Exercise
You built a search index with vectors from nomic-embed-text. A teammate suggests embedding new queries with a different embedding model that is faster. Why will this break the search, and what must you do?
Show answer
Each model has its own vector space, so scores between vectors from different models are meaningless. Embed queries with the same model as the documents. To switch models, re-embed all documents with the new model.