What are embeddings, and how is similarity measured?

Learning path, stage 1 of 5: How LLMs work · question 8 of 10

An embedding is a fixed-length vector that represents the meaning of a piece of text (or an image). Texts with similar meanings get vectors that point in similar directions, so semantic similarity becomes geometry, usually cosine similarity or a dot product.

What they're used for

  • Semantic search and RAG retrieval: embed the query, find the nearest document chunks.
  • Clustering, deduplication, recommendation, classification, anomaly detection.

Similarity measures

  • Cosine similarity: the angle between vectors, from -1 to 1. It ignores length and is the most common choice.
  • Dot product: equal to cosine when vectors are normalised to length 1, and faster.
  • Euclidean (L2) distance: straight-line distance. Gives the same ranking as cosine on normalised vectors.

Practical points

  • Use the same embedding model for documents and queries. Vectors from different models can't be compared.
  • Changing the model means re-embedding everything.
  • Choose models by benchmark (MTEB) and by testing on your own data.
  • Dimensions trade quality for storage and speed (for example 384 versus 3072).
  • Some model providers don't offer an embeddings endpoint. Anthropic, for example, points to third-party embedding providers.

Sources

Code example

tsx
1// Cosine similarity and a brute-force nearest-neighbour search.
2type Vec = number[];
3
4const dot = (a: Vec, b: Vec) => a.reduce((s, v, i) => s + v * b[i], 0);
5const norm = (a: Vec) => Math.sqrt(dot(a, a));
6export const cosine = (a: Vec, b: Vec) => dot(a, b) / (norm(a) * norm(b));
7
8interface Doc { id: string; text: string; vector: Vec }
9
10export function topK(query: Vec, docs: Doc[], k = 3) {
11 return docs
12 .map((d) => ({ ...d, score: cosine(query, d.vector) }))
13 .sort((a, b) => b.score - a.score)
14 .slice(0, k);
15}
16
17// `embed()` would call your embedding provider; brute force is fine
18// up to ~100k vectors. Beyond that use an ANN index (HNSW) in a vector DB.

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app