Embeddings

In One Sentence (TL;DR)

Numeric vectors representing the semantic meaning of text so similar concepts sit close together in math space.

What It Is

An embedding model converts a sentence, paragraph, or code snippet into a fixed-length array of floating-point numbers (for example, 768 or 1,536 dimensions). Because the encoder places texts with similar meanings near each other geometrically, you can measure semantic similarity between a question and millions of paragraphs using cosine similarity—even when they share zero exact words.

Software Engineering Analogy

A semantic hash function: unlike SHA-256 (where tiny changes scatter randomly), similar meanings hash to nearby coordinates.

How It Works (Step-by-Step)

  1. 01Pass a chunk of text into an embedding endpoint (e.g., `text-embedding-004`).
  2. 02Receive back a vector like `[0.014, -0.082, 0.041, ...]`.
  3. 03At query time, embed the user's question with the exact same model and find the stored vectors with the smallest angle (highest cosine similarity).

Real-World Scenario

A user searches 'app won't let me sign in after resetting password', and embeddings match a doc titled 'Troubleshooting OAuth session token invalidation' even though neither shares the words 'sign in' or 'OAuth'.

When to Use vs. When NOT to Use

When to Use

Use for semantic search, RAG retrieval, clustering support tickets, duplicate detection, and recommendations.

When NOT to Use

Do not rely purely on dense embeddings for exact IDs, stack-trace symbols, or boolean SQL filtering.

Common Beginner Mistakes

  • Mixing embeddings from two different models (or dimensions) in the same index—the vector spaces are incompatible.
  • Relying only on dense embeddings when users search exact error codes like `ERR_504_GATEWAY` or SKU IDs.
  • Embedding giant 20-page PDFs into a single vector, which averages away specific facts.

Code Example

Embedding text and computing cosine similarity · python
import math
from google import genai

client = genai.Client()

texts = [
    "How do I rotate PostgreSQL credentials?",
    "Steps to update database user passwords safely",
    "Best sourdough bread baking temperature",
]
res = client.models.embed_content(model="text-embedding-004", contents=texts)
vecs = [e.values for e in res.embeddings]

def cosine_sim(a: list[float], b: list[float]) -> float:
    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)))

print("DB vs DB:", round(cosine_sim(vecs[0], vecs[1]), 3))      # High (~0.8+)
print("DB vs Bread:", round(cosine_sim(vecs[0], vecs[2]), 3))   # Low (~0.1-0.2)