Sub topic 10
Creating embeddings locally
This chapter covers the embeddings endpoint of a local OpenAI-compatible server. It assumes you can already point the OpenAI Python client at your server and send a chat completion. You also need an embedding model downloaded on that server, such as nomic-embed-text in Ollama.
What an embedding is
An embedding is a list of floating-point numbers that represents a piece of text. Texts with similar meaning produce vectors that point in similar directions. This lets you compare meaning with arithmetic instead of keyword matching.
Typical uses:
- Semantic search: find the documents closest in meaning to a query.
- Retrieval for question answering: fetch relevant passages before asking a chat model.
- Clustering and deduplication: group or remove near-identical texts.
Embeddings come from a different kind of model than chat. A chat model generates text. An embedding model reads text and returns a fixed-length vector. You usually cannot use a chat model such as llama3.2 for embeddings, and an embedding model cannot chat.
The endpoint and its shape
The OpenAI API defines POST /v1/embeddings. A compatible server accepts the same request body and returns the same response structure.
| Field | Direction | Meaning |
|---|---|---|
| `model` | request | Name of an embedding model on the server |
| `input` | request | One string or a list of strings |
| `data` | response | A list with one item per input, in input order |
| `data[i].embedding` | response | The vector, a list of floats |
| `data[i].index` | response | Position of the matching input |
| `usage` | response | Token counts, when the server reports them |
Because base_url already ends in /v1, the client calls /v1/embeddings for you.
Your first embedding request
This is the example from the plan. It sends two strings in one request and prints how many vectors came back and how long the first one is.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
result = client.embeddings.create(
model="nomic-embed-text",
input=["local models are private", "hosted models are convenient"],
)
print(len(result.data), len(result.data[0].embedding))Expected output with nomic-embed-text:
2 768The first number is the count of inputs. The second is the vector's dimension, which is fixed by the model. If you use a different embedding model, you will see a different length, such as 384 or 1024.
If you pull the model first with Ollama, run ollama pull nomic-embed-text. Other servers load embedding models through their own mechanisms. For example, llama-server needs to be started with an embedding model and an embeddings flag. Check your server's documentation.
Batching inputs
Passing a list in input sends all texts in one HTTP request. This is faster than one request per text, because you pay the connection and scheduling cost once.
Batches have limits:
- Servers may cap the number of items per request or the total tokens.
- Each text is truncated or rejected if it exceeds the model's context length. Embedding models often have short contexts, commonly 512 to 8192 tokens.
- A very large batch can exhaust memory on a small machine.
A safe pattern is to split a large list into chunks and keep the order.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
def embed_all(texts, model="nomic-embed-text", batch_size=32):
vectors = []
for start in range(0, len(texts), batch_size):
batch = texts[start:start + batch_size]
result = client.embeddings.create(model=model, input=batch)
ordered = sorted(result.data, key=lambda item: item.index)
vectors.extend(item.embedding for item in ordered)
return vectors
docs = [
"Ollama runs models on your own machine.",
"The hosted API bills per token.",
"Embeddings turn text into vectors.",
]
vectors = embed_all(docs)
print(len(vectors), len(vectors[0]))Sorting by index guards against a server that returns items out of order. Most return them in order, but the sort costs almost nothing.
Comparing vectors with cosine similarity
The most common way to compare two embeddings is cosine similarity. It measures the angle between the vectors. A value near 1 means very similar direction, near 0 means unrelated, and negative values mean opposed.
The formula is the dot product of the vectors divided by the product of their lengths. You can write it in plain Python.
import math
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
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 = [
"How do I run a model on my laptop?",
"Steps for hosting an LLM locally",
"Recipe for banana bread",
]
result = client.embeddings.create(model="nomic-embed-text", input=texts)
vecs = [item.embedding for item in result.data]
print("laptop vs hosting:", round(cosine(vecs[0], vecs[1]), 3))
print("laptop vs bread: ", round(cosine(vecs[0], vecs[2]), 3))The first score should be clearly higher than the second. Exact numbers differ between models, so compare scores relative to each other rather than against a fixed threshold.
A small semantic search
Combine the pieces to rank documents against a query. This version embeds the corpus once, then embeds each query.
import math
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
MODEL = "nomic-embed-text"
def embed(texts):
result = client.embeddings.create(model=MODEL, input=texts)
return [item.embedding for item in sorted(result.data, key=lambda i: i.index)]
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
corpus = [
"Set the base URL to http://localhost:11434/v1 to reach Ollama.",
"Streaming returns text fragments as they are generated.",
"Temperature controls how random the output is.",
"Embedding models return one vector per input string.",
]
corpus_vectors = embed(corpus)
def search(query, top_k=2):
query_vector = embed([query])[0]
scored = [
(cosine(query_vector, vec), text)
for vec, text in zip(corpus_vectors, corpus)
]
return sorted(scored, reverse=True)[:top_k]
for score, text in search("How do I make answers less random?"):
print(f"{score:.3f} {text}")For a few thousand documents this in-memory approach works. Beyond that, use a vector index or database, and store the vectors so you do not recompute them each run.
Rules that keep results valid
Embeddings are only comparable under certain conditions.
- Use one model for both sides. Vectors from different models live in different spaces. Comparing a
nomic-embed-textvector with amxbai-embed-largevector gives meaningless scores, and the lengths often differ. - Record the model name with stored vectors. If you change models, re-embed everything.
- Follow the model's prefix convention. Some models expect task prefixes in the text, such as
search_query:andsearch_document:fornomic-embed-text. Check the model card. Skipping the prefix lowers quality without raising an error. - Keep text within the context length. Long documents should be split into chunks before embedding.
Differences between servers
The endpoint is the part of the OpenAI contract that local servers support least uniformly. Test it before you depend on it.
| Area | What can differ |
|---|---|
| Availability | Some servers expose no `/v1/embeddings` route, or only when started with a flag |
| Model naming | The `model` string follows the server's naming, not OpenAI's names like `text-embedding-3-small` |
| Input types | Lists of strings are common. Token-ID arrays may be unsupported |
| `dimensions` parameter | Hosted models can shorten vectors. Local servers often ignore or reject it |
| `encoding_format` | `float` is universal. `base64` may not be supported |
| Normalization | Some servers return unit-length vectors and others do not |
| `usage` | Token counts may be zero or missing |
Normalization matters for speed and correctness. If vectors are unit length, cosine similarity equals the dot product, so you can skip the division. If you are unsure, compute the full cosine formula, as the examples above do.
Errors you will meet
The error handling from the earlier chapter applies here. The common cases:
openai.NotFoundError(404): the route does not exist, or the model name is wrong. A model that is not pulled usually gives this error.openai.BadRequestError(400): the input is too long, the batch is too large, or you sent a parameter the server rejects, such asdimensions.openai.APIConnectionError: the server is not running or the base URL is wrong.- A chat model used for embeddings: some servers return an error, and others return vectors of poor quality. Confirm the model is an embedding model.
A wrapper that separates these cases makes failures easy to read.
import openai
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="local",
timeout=60.0,
max_retries=2,
)
try:
result = client.embeddings.create(
model="nomic-embed-text",
input=["check the endpoint"],
)
print("dimension:", len(result.data[0].embedding))
except openai.APIConnectionError:
print("Cannot reach the server. Check that it is running and the base URL.")
except openai.NotFoundError:
print("404: pull the embedding model, and confirm the server has /v1/embeddings.")
except openai.BadRequestError as e:
print(f"Request rejected: {e}")
except openai.APIStatusError as e:
print(f"Server returned status {e.status_code}")A raw HTTP check
When the client gives a confusing error, call the endpoint directly. This shows exactly what the server returns.
curl http://localhost:11434/v1/embeddings \
-H "Content-Type: application/json" \
-d '{"model": "nomic-embed-text", "input": "hello"}'A healthy reply contains a data array with an embedding list. An error reply contains a message that usually names the problem.
The flow end to end
Summary of practices
- Pick an embedding model, not a chat model, and use the same one throughout.
- Send lists to reduce requests, and cap batch size.
- Sort results by
indexbefore using them. - Do not rely on
dimensions,base64, or token-array input without testing. - Store vectors with the model name, and re-embed if the model changes.
Exercise
You built a search index using nomic-embed-text, then switched the query code to a different embedding model. The server returns no errors, but results look random. Why, and what do you do?
Show answer
Vectors from different models are not comparable, so cosine scores between a query vector and the stored document vectors carry no meaning. Nothing errors because both are valid float lists. Re-embed the whole corpus with the new model, or switch the query code back to the original model. Store the model name with the vectors so a mismatch can be detected.
Exercise
Write the one-line call that returns the dimension of the vectors produced by a model, given a client and an embedding model name.
Show answer
len(client.embeddings.create(model="nomic-embed-text", input="x").data[0].embedding). It embeds one short string and measures the length of the first vector. For nomic-embed-text the result is 768.