AI Engineering · Concept Library · Free article
Text Embeddings
An embedding is a coordinate: text turned into a fixed-length list of numbers, placed so that passages meaning the same thing land near each other even with no words in common. Retrieval only ever sees what the embedding placed nearby, which makes it the component that decides whether the right passage is found at all. How an encoder builds one, how “near” is measured, which of the dozens of models to trust, and the upgrade that silently wrecks a working search.
An embedding turns a piece of text into a fixed-length list of numbers, a point in a space where things that mean the same thing sit close together, even with no words in common. That is the whole trick behind semantic search: embed the query and every document the same way, then find the nearest points. But the details decide whether it works, which model you pick (there is no single best), how you measure “near,” and the fact that changing models forces you to re-embed everything, because two models don't share a coordinate system.
The RAG page made a promise and then hurried past it. To find the help-center article that answers “you charged me twice”, the one filed under “duplicate-payment reversal,” sharing not a single word with the complaint, it turned every chunk into an embedding, “a list of numbers that captures what the text means.” Then it said the how was a topic for its own page and moved on to retrieval.
This is that page. And it matters more than it sounds, because the embedding is the component that decides whether retrieval ever sees the right passage. Get it wrong, pick a model tuned for the wrong task, feed it chunks longer than it can read, or quietly change models under a live index, and no amount of clever prompting downstream can recover a passage that never got retrieved. So let's open the box: what is this list of numbers, really?
What is a text embedding?
Concretely: you hand the model a string, it hands back a fixed-length array of floating-point numbers, a vector. The length is fixed no matter how long the input was: a three-word query and a three-paragraph article both come back as, say, 768 or 1536 numbers. Each number is one coordinate along one axis of that meaning-space. None of them means anything a human could name, there is no “billing” dimension you could point to, but taken together they pin the text to a location.
Two texts are “similar” when their vectors point in nearly the same direction. Below, the complaint is a fixed vector on the left; pick a candidate reply and its vector snaps in beside it, with the actual closeness score computed from the bars you see.
The interactive version of this example is available when JavaScript loads.
How does text become an embedding?
Inside, the model reads your text as tokens and runs them through a transformer encoder, the same attention machinery a chat model uses, but pointed at a different goal. Instead of predicting the next token, it produces one contextual vector per token, then pools them, usually by averaging, into a single fixed-length vector for the whole passage. That pooled vector is the embedding. A model built this way is called a bi-encoder: it embeds the query and each document independently, which is exactly what makes search cheap, you can embed all your documents once, ahead of time, and only embed the query at request time.
The word “contextual” is doing real work there, and it's the leap that made modern retrieval possible. Take a word that means different things in different sentences and watch whether the vector can tell them apart:
The interactive version of this example is available when JavaScript loads.
The older approach, word2vec and its kin, gave every word one fixed vector from a lookup table, built from overall co-occurrence statistics and blind to the sentence around it. Powerful for its day, but it couldn't tell a refund from a call-back if both said “return.” The jump to transformer encoders that read the whole sentence, popularized for sentence-level vectors by Sentence-BERT, is what lets retrieval work on paraphrases and messy real tickets instead of just synonyms. The vector knows meaning because the model was trained so that related texts land close, typically by showing it millions of should-be-close pairs (a question and its answer passage) and should-be-far pairs, and shaping the space accordingly.
How is “near” actually measured?
“Nearby” needs a number, and for text that number is almost always cosine similarity: the angle between two vectors, with their lengths ignored. There are three common ways to measure it. Cosine similarity measures the angle between two vectors and ignores their length, which is what you want, because length often just reflects how much text there was, not what it meant. Dot product is cosine multiplied back by the two lengths, so it's sensitive to magnitude. Euclidean distance is the straight-line gap between the two points.
| Measure | What it captures | When it's used |
|---|---|---|
| Cosine similarity | The angle only, pure direction, length ignored. 1.0 = same direction, 0 = unrelated. | The default for text retrieval: meaning lives in direction, not magnitude. |
| Dot product | Direction and magnitude together. | Used when vectors are already unit-length, then it equals cosine, but is faster. |
| Euclidean (L2) | Straight-line distance between the two points. | Gives the same ranking as cosine once vectors are normalized, so the choice rarely matters. |
There's a tidy shortcut hiding in that table. If you normalize every vector to length 1 up front, then dot product and cosine become the same computation, and Euclidean gives an identical ranking, so you normalize once at write time and use a plain dot product at query time, getting cosine's meaning at dot product's speed. Some providers hand you normalized vectors already; OpenAI's embeddings guide states its vectors come pre-normalized and recommends cosine, noting the distance function rarely changes much. Vector sizes you'll see range from a few hundred numbers to a few thousand, and more is not automatically better, a point the model-choice section returns to.
Not every embedding is doing the same job
There are dozens of embedding models, and the single most important fact about choosing one is that there is no universal best. The field's standard benchmark, MTEB (and its multilingual successor MMTEB), scores models across many task types, retrieval, classification, clustering, similarity, and its headline finding, still true, is that a model that tops one task can be mediocre at another. So you never read the overall average; you filter the live leaderboard to your task and your language, then shortlist.
One subtlety trips up newcomers: in search, the query and the document are different shapes, a five-word question versus a 500-word article. Many retrieval models handle this asymmetry with role prefixes or instructions you're expected to prepend, the E5 family, for instance, wants queries marked one way and passages another, and skipping the prefixes measurably hurts recall. Read the model card and use its exact recipe; the prefixes aren't decoration. Describe your job below and the fitting kind of model lights up:
The interactive version of this example is available when JavaScript loads.
Two more dials worth knowing. Dimensions: a bigger vector can hold more nuance but costs more to store and compare, with sharply diminishing returns, and Matryoshka-trained models let you truncate a long vector to a shorter one and keep most of the quality, turning dimensions into a runtime knob rather than a fixed choice. Context length: every embedding model has a token limit, and it silently truncates anything past it, feed a chunk longer than the model can read and the tail vanishes with no error, which is why your chunk sizes have to respect the model's real limit.
The models teams actually reach for
The split that matters in practice is hosted API versus open weights you run yourself. APIs are the fastest path and often top the retrieval leaderboards; open models let the data stay inside your walls and remove per-token cost at the price of running the serving yourself. A representative snapshot, treat the exact numbers as moving targets and confirm against the live leaderboard before you commit:
| Kind | Examples | Why you'd pick it |
|---|---|---|
| General hosted API | OpenAI text-embedding-3, Google Gemini embeddings, Cohere Embed, Voyage | Fastest to ship, strong general retrieval, dimensions/quantization knobs built in; you send text out. |
| Open-weight, self-host | BGE, E5, GTE, Nomic, Jina | Data residency and no per-token cost; several land near the best APIs on retrieval, you run the serving. |
| Multilingual | multilingual-E5, BGE-M3, Cohere multilingual, Gemini | Corpus or queries span languages; check the multilingual leaderboard in your languages. |
| Long-context | BGE-M3, Nomic, Jina, Voyage, Cohere (long variants) | Big chunks that would truncate on a 512-token model; keeps the whole passage in view. |
The upgrade that silently breaks retrieval
Here is the mistake that looks harmless and isn't. A newer, higher-ranked embedding model comes out. You update your app so incoming queries use it, a one-line change, and ship. Retrieval quietly falls apart, and your logs look fine. The reason is fundamental: two different models place meaning on different axes. A vector from Model B and a vector from Model A aren't in the same coordinate system, so a similarity computed between them is gibberish. Toggle the query's model against a Model-A index and watch:
The interactive version of this example is available when JavaScript loads.
Embeddings aren't only for retrieval
It's easy to meet embeddings only as “the RAG thing” and stop there, but the same vector is a general-purpose handle on meaning, and knowing that changes what you reach for. Once text is a point in space, a lot of problems become geometry:
The same vector, other jobs
- Clustering, group Wrenlet's incoming tickets by what they're about with no predefined labels, so a spike of a brand-new issue surfaces on its own.
- Classification, embed a ticket, feed the vector to a small, cheap classifier to route it (billing / bug / cancellation) without prompting a big model every time.
- Deduplication, spot near-duplicate tickets or docs by their vectors sitting almost on top of each other, even when the wording differs.
- Recommendation, “more articles like this one” is just the nearest neighbors of the current article's vector.
- Semantic caching, when a new question is close enough to one you've already answered, serve the cached answer instead of paying for another generation, a real cost lever.
How do you judge whether an embedding model is any good?
You don't evaluate an embedding by staring at vectors, you evaluate the retrieval it produces, which needs a small labeled set: real queries, each tagged with the document that actually answers it. Then you measure how well the candidate model surfaces those.
| Metric | What it asks | When it fits |
|---|---|---|
| Recall@k | Of the truly relevant docs, how many made the top-k? | The core first-stage number, you can't rerank what you never retrieved. |
| MRR | How high is the first correct hit, on average? | When essentially one passage is right and you want it near the top. |
| nDCG@k | Are all the relevant docs ranked high, with position discounted? | When relevance is graded or several docs are relevant; MTEB's headline retrieval metric. |
Embedding text in code
Stripped to essentials, using an embedding is four moves. The load-bearing idea: embed once, normalize once, compare with a dot product, sort descending.
The whole flow, step by step
- Embed with one model. Call the endpoint,
embed(text)returns a list of floats, and use the same model for the query and every document. Mixing models is the trap from earlier. - Normalize once. Scale each vector to length 1 at write time (many providers pre-normalize). Now closeness is a single cheap operation.
- Compare with a dot product. Cosine similarity is
dot(q, d) / (norm(q) * norm(d)), and on normalized vectors that collapses to justdot(q, d), no division. - Rank and cut. Sort documents by similarity descending and take the top-k; that's your retrieval result. For a real corpus you store the document vectors in a vector index instead of looping over them, how that index makes the search fast is the next page in this chapter.
Where do embeddings mislead you?
They mislead in the gap between what a similarity score measures and what you wanted it to mean, which is a gap the score itself never reports.
The ones that actually bite
- Reading similarity as relevance. “How do I cancel” and “how do I renew” are near-identical vectors with opposite intent. Cosine scores topic, not correctness, antonyms, negation, and specific numbers or dates are classic misses.
- Expecting exact matches. Embeddings blur rare identifiers, SKUs, error codes, and names, exactly where users want a literal hit. That gap is why hybrid (meaning + keyword) search exists; it's a page of its own.
- Mixing models in one index. Vectors from two models, or two dimension settings of one model, are not comparable. Never compute a similarity across them.
- Chunks that don't fit the model. Too long and the model truncates the tail invisibly, or averages the meaning into mush; too short and a chunk lacks the context to be findable. Granularity is a real tuning knob.
- Porting a threshold. A “relevant if > 0.8” cutoff from one model or corpus doesn't transfer, anisotropy makes each model's baseline different. Recalibrate, or rank instead of threshold.
- Believing the vector “understands.” It encodes statistical relatedness from training pairs, not comprehension or truth. It will place a plausible-but-wrong passage right next to your query and feel confident about it.
Habits that keep an index honest
What senior teams wire in from the start
- Pick by task, then measure on your data. Filter the leaderboard to your task and language, shortlist two to four, and choose by recall@k on your own labeled queries.
- Use the model's prefixes. If it wants a query/passage instruction, apply it everywhere, silently dropping it is a quiet recall leak.
- Normalize, then dot-product. One normalization at write time buys consistent scores and the fastest comparison.
- Version every vector. Stamp each stored vector with its model version and a content hash, so a stale model or a changed document is detectable, not invisible.
- Treat model swaps as migrations. Re-embed the whole corpus and rebuild the index behind a shadow copy; never point new-model queries at an old-model index.
- Right-size the vector. Start smaller than you think, truncatable dimensions and quantization can cut storage and latency dramatically for a sliver of recall you can often rescore back.
- Respect the token limit. Keep chunks inside the model's real context window so nothing is silently truncated.
Interview cheat-sheet: intern to principal
- What is a text embedding, in one sentence?
- A fixed-length vector that positions a piece of text in a space where geometric nearness approximates semantic relatedness, produced by an encoder trained so that related texts land close together.
- Why cosine similarity rather than Euclidean distance?
- Cosine measures the angle, pure direction, and ignores magnitude, which for text usually just reflects length rather than meaning. And once vectors are normalized to unit length, cosine, dot product, and Euclidean all give the same ranking, so people normalize once and use a dot product for speed.
- Bi-encoder vs cross-encoder, what's the difference and when do you use each?
- A bi-encoder embeds the query and each document separately, so document vectors can be pre-computed and searched cheaply, that's first-stage retrieval. A cross-encoder reads the query and a document together for a much sharper relevance score, but must run per pair, so it's used to rerank a shortlist, not to search everything.
- Why can't I compare embeddings from two different models?
- Each model learns its own coordinate space, the axes and the very notion of “close” differ, so a cross-model similarity is meaningless. That's why changing your embedding model forces a full re-embed of the corpus, not just of new queries.
- How do you choose an embedding model?
- Start from MTEB/MMTEB filtered to your task and language, never the overall average, since no model wins every task, shortlist a few, then measure recall@k or nDCG@k on a labeled sample of your own queries, weighing dimensions, cost, context length, and whether it must run privately.
- Are more dimensions always better?
- No. More dimensions add capacity but with steep diminishing returns and higher storage, memory, and compute per comparison. A well-trained 768-dimension model can beat a mediocre 3072-dimension one, and Matryoshka models let you truncate dimensions with little loss.
- Why do all my similarity scores sit in a narrow high band, and what should I do about it?
- Anisotropy: raw embedding spaces crowd into a narrow cone, so even unrelated pairs score high. It means the absolute number isn't calibrated and thresholds don't transfer across models or corpora. Rank and take top-k, calibrate any threshold per deployment, and prefer a retrieval-trained model, which fights the effect.
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.