What Are Embeddings?
You've probably heard that AI models don't really "understand" text — they work with numbers. But how exactly do words become numbers? The answer is embeddings.
Embeddings are the mathematical foundation of modern AI. They're how search engines find relevant results, how recommendation systems know what you'll like, how chatbots understand your questions, and how RAG (Retrieval-Augmented Generation) systems ground AI responses in real data.
This guide explains what embeddings are, how they work, and why every AI developer should understand them.
What Is an Embedding?
An embedding is a numerical representation of data — text, images, audio, or any other input — as a vector (a list of numbers) in a high-dimensional space. The key property is that similar items have similar vectors.
Think of it like a map. On a map of the world, cities that are close together in meaning — "Paris" and "France" — appear near each other. Cities that are far apart in meaning — "Paris" and "quantum physics" — are far apart on the map. Embeddings create this kind of "meaning map" for any kind of data.
Each embedding is a list of numbers, typically 384 to 3072 dimensions long. You can't visualize 1536 dimensions directly, but mathematically the relationships between vectors capture semantic meaning:
"dog" → [0.23, -0.45, 0.78, 0.12, ..., -0.33] (1536 numbers)
"puppy" → [0.25, -0.42, 0.80, 0.10, ..., -0.30] (close to "dog")
"car" → [-0.61, 0.33, -0.15, -0.72, ..., 0.51] (far from "dog")
The embedding vector for "puppy" is numerically similar to the vector for "dog" because the words are semantically related.
Text Embeddings vs. Word Embeddings
The terms are sometimes used differently:
| Term | Meaning |
|---|---|
| Word embeddings | Vectors for individual words (e.g., Word2Vec, GloVe) — one vector per word |
| Text embeddings | Vectors for sentences, paragraphs, or documents — captures full context |
| Sentence embeddings | A type of text embedding optimized for sentence-length inputs |
| AI embeddings | General term for embeddings used in AI systems |
Modern applications use text embeddings because they handle context. The same word in different sentences gets a different embedding: "bank" in "river bank" has a different vector than "bank" in "savings bank."
How Embeddings Work
The Embedding Model
An embedding model is a neural network trained to convert text into vectors. The training process teaches the model to place similar texts close together in vector space and dissimilar texts far apart.
Popular embedding models include:
| Model | Dimensions | Best For |
|---|---|---|
| OpenAI embeddings (text-embedding-3-small) | 512–1536 | General purpose, high quality |
| text-embedding-3-large | 256–3072 | Maximum accuracy |
| sentence-transformers/all-MiniLM-L6-v2 | 384 | Local/offline use, fast |
| Cohere Embed v3 | 1024 | Enterprise/search use cases |
| BGE (BAAI General Embedding) | 1024 | Open-source, competitive |
The best embedding model depends on your use case. For production systems, OpenAI embeddings (text-embedding-3-small) offer an excellent balance of quality, speed, and cost. For offline or privacy-sensitive applications, open-source models like sentence-transformers work well.
Embedding Search
The most common use of embeddings is embedding search (also called semantic search). Instead of searching for exact keyword matches, you:
- Convert your query into an embedding
- Find the closest vectors in your database using embedding similarity
- Return the corresponding texts
This is far more powerful than keyword search. A search for "how to fix a broken laptop screen" will find results about "repairing damaged display panels" — even though none of those exact words match.
Embedding Similarity
Similarity between embeddings is measured using distance metrics:
- Cosine similarity (most common) — measures the angle between vectors, range -1 to 1
- Dot product — magnitude-weighted similarity
- Euclidean distance — straight-line distance in vector space
Cosine similarity is the standard for text embeddings because it's insensitive to vector magnitude (a long text and short text on the same topic get the same similarity score).
Embedding Dimension
The embedding dimension is the number of numbers in each vector. Higher dimensions capture more nuance but require more storage and computation:
| Dimensions | Storage (1M vectors) | Use Case |
|---|---|---|
| 384 | ~1.5 GB | Quick prototyping, mobile |
| 768 | ~3 GB | General purpose |
| 1024 | ~4 GB | Enterprise search |
| 1536 | ~6 GB | High-accuracy systems |
| 3072 | ~12 GB | Maximum fidelity |
Embeddings vs. LLMs
Embeddings and large language models (LLMs) are complementary technologies:
| Embeddings | LLMs | |
|---|---|---|
| Purpose | Represent meaning as numbers | Generate text |
| Output | A vector (list of numbers) | Tokens (text) |
| Use case | Search, clustering, classification | Chat, writing, reasoning |
| Speed | Very fast (milliseconds) | Slower (seconds) |
| Cost | Cheap | Expensive |
| Context window | Unlimited (database scale) | Limited (model-dependent) |
In a RAG system, embeddings handle the retrieval step (find relevant documents) while the LLM handles the generation step (write an answer based on those documents).
Embeddings for RAG
Embeddings for RAG is the most important practical application. RAG (Retrieval-Augmented Generation) works in three steps:
- Index — Split your documents into chunks and generate an embedding for each chunk
- Retrieve — When a user asks a question, embed the question and find the most similar chunks
- Generate — Feed those chunks to an LLM as context, and let it answer
# Simplified RAG with embeddings
from openai import OpenAI
client = OpenAI()
# Step 1: Embed your knowledge base
def embed_text(text):
response = client.embeddings.create(
model="text-embedding-3-small",
input=text
)
return response.data[0].embedding
# Step 2: Find relevant context
def search(query, embeddings_db):
query_vec = embed_text(query)
results = cosine_similarity(query_vec, embeddings_db)
return top_k(results, k=3)
# Step 3: Generate answer with context
def answer_question(question, context):
prompt = f"Answer based on this context:\n{context}\n\nQuestion: {question}"
return client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
The quality of your embedding model directly affects RAG quality. Better embeddings = better retrieval = better answers.
Embedding Database and Vector Storage
To use embeddings at scale, you need an embedding database (also called a vector database). These databases are optimized for storing and searching high-dimensional vectors:
| Database | Type | Notable Features |
|---|---|---|
| Pinecone | Managed | Fully serverless, high performance |
| Weaviate | Open-source | Hybrid search (vector + keyword) |
| Qdrant | Open-source | Rust-based, very fast |
| Chroma | Open-source | Simple, Python-native |
| pgvector | PostgreSQL extension | Use existing Postgres database |
An embedding database stores both the vector and the original text, and supports fast nearest-neighbor search using algorithms like HNSW (Hierarchical Navigable Small World).
Embedding Visualization
Embedding visualization helps you understand what your embeddings look like. Since vectors have hundreds of dimensions, you need to reduce them to 2D or 3D for visualization:
- t-SNE — Preserves local structure, good for clusters
- PCA — Preserves global structure, faster
- UMAP — Best balance of speed and structure preservation
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
# Reduce 1536-dim vectors to 2D for visualization
reduced = TSNE(n_components=2).fit_transform(embeddings)
plt.scatter(reduced[:, 0], reduced[:, 1])
plt.title("Embedding Visualization (t-SNE)")
plt.show()
Embedding visualization is useful for debugging — you can check if related documents are actually clustering together.
Getting Started with Embeddings
Using OpenAI Embeddings (easiest)
pip install openai
from openai import OpenAI
client = OpenAI()
response = client.embeddings.create(
model="text-embedding-3-small",
input="What is machine learning?"
)
vector = response.data[0].embedding
print(f"Dimension: {len(vector)}")
# Output: 1536
Using Local Embeddings (free, offline)
pip install sentence-transformers
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-MiniLM-L6-v2')
vector = model.encode("What is machine learning?")
print(f"Dimension: {len(vector)}")
# Output: 384
Best Practices
- Normalize your embeddings — cosine similarity works best with normalized vectors
- Chunk your documents wisely — 256–512 tokens per chunk is a good starting point
- Test your embedding model — the best model depends on your domain (medical, legal, code, etc.)
- Monitor embedding drift — models get updated; re-embed periodically
- Cache embeddings — don't re-embed the same text twice
FAQ
What are embeddings? Embeddings are numerical representations of data (text, images, audio) as vectors in high-dimensional space. Similar items have similar vectors, enabling semantic search and AI understanding.
What is the difference between word embeddings and text embeddings? Word embeddings represent individual words, while text embeddings represent sentences or documents, capturing full context. Most modern applications use text embeddings.
Which embedding model is best? OpenAI's text-embedding-3-small (1536 dimensions) is the most popular for production due to its quality/speed balance. For offline use, sentence-transformers/all-MiniLM-L6-v2 (384 dimensions) is a solid open-source choice.
How do you measure embedding similarity? Cosine similarity is the standard metric. It measures the angle between two vectors, with values from -1 (opposite) to 1 (identical).
What is an embedding database? An embedding database (vector database) is optimized for storing and searching high-dimensional vectors. Examples include Pinecone, Weaviate, Qdrant, and Chroma.
What is embedding dimension? Embedding dimension is the number of numbers in each vector. Higher dimensions capture more nuance but require more storage. Common values range from 384 to 3072.
