Sub topic 12
Generating embeddings locally
This chapter assumes you can run ollama pull and call the local REST API from the earlier chapters. It also assumes you know what a vector is: a list of numbers. Here you will use a local model to turn text into vectors and compare them to find text with similar meaning.
What an embedding is
An embedding is a fixed-length list of floating-point numbers that represents a piece of text. An embedding model is trained so that texts with similar meaning get vectors that point in similar directions. "How do I reset my password?" ends up close to "I forgot my login credentials" and far from "Best hiking trails in Norway".
An embedding model is not a chat model. It does not generate text. It reads the input and returns one vector. Embeddings are the basis of semantic search, document clustering, duplicate detection, and retrieval-augmented generation (RAG), where you retrieve relevant passages and paste them into a chat prompt.
Running embeddings locally has two practical benefits. Your documents never leave your machine, and embedding thousands of chunks costs only electricity and time.
Choosing an embedding model
Embedding models in the Ollama library are small compared to chat models, so they load quickly and run well on CPU.
| Model | Vector size | Notes |
|---|---|---|
| `all-minilm` | 384 | Very small and fast. Lower quality on hard retrieval. |
| `nomic-embed-text` | 768 | Good general-purpose default with a long input limit. |
| `mxbai-embed-large` | 1024 | Larger and usually more accurate. Slower. |
| `bge-m3` | 1024 | Multilingual, long inputs. |
Check the model page in the library for current sizes and limits. You can also run ollama show <model>, which prints the embedding length.
Pull one to follow along:
ollama pull nomic-embed-textCalling the embed endpoint
The current endpoint is POST /api/embed. It takes a model and an input, which is either one string or a list of strings.
curl http://localhost:11434/api/embed -d '{
"model": "nomic-embed-text",
"input": ["The cat sat on the mat.", "A kitten rests on a rug."]
}'The response holds one vector per input, in the same order:
{
"model": "nomic-embed-text",
"embeddings": [[0.012, -0.034, 0.081], [0.009, -0.029, 0.077]]
}The real vectors are much longer than three numbers. The example is shortened for display. The response also contains timing fields such as total_duration and load_duration.
Sending a list in one request is faster than sending one request per text, because the model is loaded once and the inputs are processed together.
The older endpoint
Older tutorials use POST /api/embeddings. It takes prompt instead of input, accepts only one string, and returns a single embedding array. It still works in many versions, but /api/embed is the one to use for new code. The two endpoints differ in field names and response shape, so a script written for one will not work against the other without changes.
Comparing vectors with cosine similarity
To measure how close two texts are, compare their vectors. The usual measure is cosine similarity, the cosine of the angle between the vectors. It ranges from -1 to 1. Higher means more similar in meaning.
The /api/embed endpoint returns vectors normalized to length 1. For normalized vectors, cosine similarity equals the dot product. The code below computes the full formula anyway, so it stays correct if you switch to an endpoint or model that does not normalize.
import math
import requests
OLLAMA = "http://localhost:11434"
MODEL = "nomic-embed-text"
def embed(texts):
resp = requests.post(
f"{OLLAMA}/api/embed",
json={"model": MODEL, "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)
documents = [
"To reset your password, open Settings and choose Security.",
"Our office is closed on public holidays.",
"You can export your data as CSV from the Reports page.",
"If you forgot your login, use the Forgot Password link.",
]
query = "I can't sign in to my account"
doc_vectors = embed(documents)
query_vector = embed([query])[0]
scored = sorted(
((cosine(query_vector, v), d) for v, d in zip(doc_vectors, documents)),
reverse=True,
)
for score, doc in scored:
print(f"{score:.3f} {doc}")The two password-related documents should rank at the top, even though the query shares almost no words with them. This is the difference from keyword search, which matches on the words themselves.
How the pieces fit together
A typical local search pipeline has an indexing phase and a query phase. Both phases must use the same embedding model.
For a few thousand chunks, a Python list and the loop above is enough. For larger collections, use a vector database or an index library, which avoids comparing the query against every vector.
Common errors and gotchas
Mixing models
Vectors from different models are not comparable. They may even have different lengths. If you change the embedding model, re-embed everything. Store the model name alongside your vectors so you can detect a mismatch.
Using a chat model for embeddings
Ollama will often return vectors from a chat model such as llama3.2, but they are poor for similarity search because the model was not trained for it. Use a model built for embeddings.
Input longer than the context
Each embedding model has a maximum input length measured in tokens. By default, Ollama truncates input that exceeds it. The request succeeds, but the end of your text does not influence the vector. You can pass "truncate": false to get an error instead. Splitting documents into chunks before embedding avoids the problem and usually improves retrieval, since a vector for a short, focused passage is more specific than one for a whole file.
Task prefixes
Some models were trained with prefixes in the text. For example, nomic-embed-text is documented to work best when you prefix with search_document: for stored text and search_query: for queries. Ollama does not add these for you. Read the model card, and apply the prefixes consistently.
Cold starts
The first request loads the model into memory, which adds latency. Later requests are fast until the model is unloaded after the keep-alive period. If you also chat with a larger model, the embedding model and chat model may both need to be loaded. ollama ps shows what is resident. You can send "keep_alive" in the request to control how long the embedding model stays loaded.
Wrong response field
A common bug is reading embedding from the /api/embed response or embeddings from /api/embeddings. /api/embed returns embeddings, a list of vectors, even when you send a single string.
Embeddings through the OpenAI-compatible endpoint
Ollama also serves /v1/embeddings, so the OpenAI client works with the same base URL you used for chat:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
result = client.embeddings.create(
model="nomic-embed-text",
input=["first text", "second text"],
)
print(len(result.data), len(result.data[0].embedding))This is useful when an existing library or framework expects an OpenAI-style embeddings client and you want to switch it to local inference by changing only the base URL.
Exercise
You indexed 10,000 chunks with nomic-embed-text. A teammate suggests switching to mxbai-embed-large for better accuracy and says you only need to embed new queries with the new model. Why does this fail, and what must you do?
Show answer
The two models produce vectors in different spaces, and with different lengths (768 versus 1024). A query vector from the new model cannot be meaningfully compared with stored vectors from the old one. You must re-embed all 10,000 chunks with mxbai-embed-large, and from then on embed queries with the same model.
Exercise
A request to /api/embed with "input": "hello" succeeds, but your code fails with a KeyError on ["embedding"]. What is the fix?
Show answer
/api/embed returns a field named embeddings, which is a list of vectors, even for one string. Read resp.json()["embeddings"][0] to get the single vector. The embedding field belongs to the older /api/embeddings endpoint.