Sub topic 6
Turning text into embeddings
This chapter assumes you can read basic Python, know what a vector and a dot product are, and have called an HTTP API that returns JSON. It covers the step between chunking and similarity search. You have a list of text chunks, and you need to turn each one into a vector that a search index can compare.
What an embedding is
An embedding is a fixed-length list of floating-point numbers that represents a piece of text. An embedding model produces it. The model is trained so that texts with similar meaning land close together in vector space, and unrelated texts land far apart.
Two properties matter for RAG:
- Every input produces a vector of the same length, called the dimension. Common sizes are 384, 768, 1024, and 1536. A 40-word chunk and a 400-word chunk both become, say, 768 numbers.
- Individual numbers have no human-readable meaning. Only the distances and angles between vectors carry information.
An embedding model is not a chat model. It does not generate text. It reads text and returns one vector, and it costs far less per call than a generation model.
Where embeddings fit in the pipeline
Embeddings are used twice, and both uses must come from the same model.
- At indexing time, you embed every chunk and store the vector next to the chunk text and its metadata.
- At query time, you embed the user's question and search the stored vectors for the nearest ones.
Calling an embedding model
Most providers expose an endpoint that accepts a list of strings and returns a list of vectors. The example below uses the open-source sentence-transformers library, which runs locally. Install it with pip install sentence-transformers.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
chunks = [
"Refunds are issued within 14 days of a returned item being received.",
"Our headquarters are located in Lisbon, Portugal.",
"To reset your password, open Settings and choose Security.",
]
vectors = model.encode(chunks, normalize_embeddings=True)
print(vectors.shape)
query_vec = model.encode(
"How long does a refund take?", normalize_embeddings=True
)
scores = vectors @ query_vec
best = int(scores.argmax())
print(chunks[best], float(scores[best]))The first print shows (3, 384): three chunks, 384 dimensions each. The refund chunk should score highest, even though the question shares almost no wording with it except "refund".
Hosted APIs follow the same shape. You send a list of strings and receive one vector per string, in the same order. Always match results to inputs by position, and check that the counts are equal before storing anything.
Normalization and the dot product
Cosine similarity measures the angle between two vectors and ignores their length. If every vector is scaled to length 1 (normalized), cosine similarity equals the plain dot product. The dot product is cheaper to compute, and most vector indexes are optimized for it.
That is why the example passes normalize_embeddings=True. Many hosted models already return unit-length vectors, but not all do. Check the model's documentation, or measure it:
import math
def norm(v):
return math.sqrt(sum(x * x for x in v))
print(norm(vectors[0]))A result close to 1.0 means the vectors are already normalized. If you use a dot-product index with unnormalized vectors, longer vectors get higher scores for reasons unrelated to meaning.
Choosing a model
Pick a model by testing on your own data, not by leaderboard rank alone. The factors that matter:
| Factor | Why it matters |
|---|---|
| Maximum input length | Text beyond the limit is usually truncated silently, so the tail of a long chunk is never represented. |
| Dimension | Larger vectors cost more to store and search. 1536 dimensions in float32 is about 6 KB per chunk. |
| Language coverage | An English-only model performs poorly on other languages. Use a multilingual model if your corpus is mixed. |
| Domain fit | Legal, medical, and code text may need a model trained or tuned for that domain. |
| Cost and latency | Hosted models charge per token. Local models cost compute but keep data on your machine. |
| Query/document modes | Some models expect different prefixes or task settings for queries and documents. |
The last row catches many people. Some models are asymmetric. They were trained to match a short question to a long passage, and require a prefix such as query: or passage:, or a parameter such as an input type. If you skip it, retrieval still runs but quality drops with no error. Read the model card.
Embedding at scale
A real corpus has thousands to millions of chunks, so embedding is a batch job.
- Batch your inputs. Send 32 to 256 chunks per call instead of one at a time. Hosted APIs limit batch size and total tokens per request, so check the limits.
- Retry on rate limits with exponential backoff.
- Cache by content hash. If a chunk's text has not changed, reuse its stored vector. This makes re-ingestion cheap.
- Record the model name and version in the metadata of each vector. This lets you detect stale vectors after a model change.
import hashlib
def embed_with_cache(chunks, model, cache):
# cache maps a text hash to its vector
keys = [hashlib.sha256(c.encode("utf-8")).hexdigest() for c in chunks]
missing = [(k, c) for k, c in zip(keys, chunks) if k not in cache]
if missing:
texts = [c for _, c in missing]
new_vectors = model.encode(texts, normalize_embeddings=True)
if len(new_vectors) != len(texts):
raise RuntimeError("embedding count does not match input count")
for (k, _), vec in zip(missing, new_vectors):
cache[k] = vec
return [cache[k] for k in keys]Include the model name in the cache key if one cache serves several models.
Edge cases and common errors
- Empty or whitespace-only chunks. Some APIs reject them, and others return a meaningless vector. Filter them out during cleaning.
- Truncation. A chunk longer than the model's token limit is cut off. Make your chunk size fit the limit, and measure length in tokens, not characters.
- Boilerplate dominance. A chunk that is mostly a header, footer, or navigation text embeds close to every other chunk with the same boilerplate. Remove it during cleaning.
- Lost exact terms. Embeddings capture meaning, but they blur rare identifiers such as error codes, product SKUs, and names. A query for
ERR_4471may retrieve chunks about errors in general. Keyword search handles this better, which is why the hybrid search chapter combines both. - Negation and numbers. "Refunds are allowed" and "Refunds are not allowed" often embed very close together. Do not rely on embeddings alone for distinctions like this. Let the generation step read the actual text.
- Language drift. A query in one language can match documents in another only with a multilingual model.
Checking that your embeddings work
Before building more of the pipeline, do a quick sanity test. Pick five questions you know the answers to, embed them, and look at the top three chunks for each. If the right chunk is not near the top, the cause is usually one of three things: a poor chunking choice, the wrong model for the domain, or a missing query prefix. Fixing these now is much cheaper than debugging them after the full pipeline exists.
Exercise
You switch from an embedding model with 768 dimensions to a newer one with 768 dimensions, and you only re-embed new documents. Search quality drops, though no code raises an error. Why, and what should you do?
Show answer
The two models produce vectors in different spaces, so the same dimension does not make them comparable. Old and new vectors now sit in one index and are compared as if they were consistent, which gives meaningless scores. Re-embed the entire corpus with the new model, and store the model name in each vector's metadata so a mismatch can be detected.
Exercise
A model returns vectors that are not normalized, and your index scores with the dot product. Which chunks get an unfair advantage, and how do you remove the problem?
Show answer
Chunks whose vectors have a larger length get higher dot-product scores regardless of meaning. Normalize every vector to length 1 before storing it and normalize the query vector too, so the dot product equals cosine similarity. Alternatively, configure the index to use cosine similarity directly.