Generative AI & LLM

Module 5 of 16

Module 05: Embeddings and Vector Databases

4 min read783 words
What you'll learn
Explain what embeddings are and why they're foundational to modern AIGenerate text embeddings using OpenAI and open-source modelsImplement similarity search using cosine similarity and dot productSet up and query ChromaDB, Pinecone, Weaviate, and QdrantChoose the right indexing strategy (HNSW, IVF) for your use case

Duration: 4 hours | Difficulty: Intermediate | Prerequisites: Modules 01–03

Learning Objectives

By the end of this module, you will be able to:

  • Explain what embeddings are and why they're foundational to modern AI
  • Generate text embeddings using OpenAI and open-source models
  • Implement similarity search using cosine similarity and dot product
  • Set up and query ChromaDB, Pinecone, Weaviate, and Qdrant
  • Choose the right indexing strategy (HNSW, IVF) for your use case

1. What Are Embeddings?

The Intuition

Embeddings turn text into vectors (lists of floats). Similar meaning → vectors point in similar directions, even when the words differ. Picture a meaning map: “king” and “queen” are neighbors; “king” and “cucumber” are not.

Text AText BEmbedding story
“Refund my invoice”“I need my money back”Close vectors
“Refund my invoice”“Deploy Kubernetes”Far apart

Fun Fact: You can’t read individual dimensions like English—each dimension is a learned feature mash-up.

Why Embeddings Matter

Use caseRole of embeddings
Semantic searchQuery vector near doc vectors
RAGRetrieve chunks by meaning
Clustering / dedupeGroup similar items
Recommendations“More like this”

Try This! Write three paraphrases of one policy sentence—your goal later is for all three to hit the same chunk in retrieval.

2. Generating Embeddings

OpenAI Embeddings

Hosted models: send strings, get vectors. Great when you don’t want GPU ops on your laptop.

Batch Embeddings

Batching amortizes HTTP overhead—one call, many rows—and usually saves money vs naive loops.

Open-Source Embeddings

sentence-transformers runs locally; good for dev, air-gapped, or high-volume offline indexing.

Model flavorWhen it fits
OpenAI text-embedding-3-smallFast API, solid default
OpenAI text-embedding-3-largeMax quality, higher cost
all-MiniLM-L6-v2Free, small, great for prototypes

Key Example: Create a vector from a sentence with the OpenAI embeddings endpoint.

python
[object Object], openai ,[object Object], OpenAI

client = OpenAI(api_key=,[object Object],)

,[object Object], ,[object Object],(,[object Object],) -> ,[object Object],[,[object Object],]:
    r = client.embeddings.create(,[object Object],=text, model=model)
    ,[object Object], r.data[,[object Object],].embedding


vec = get_embedding(,[object Object],)
,[object Object],(,[object Object],, ,[object Object],(vec))
,[object Object],(,[object Object],, vec[:,[object Object],])

Embedding Model Comparison

ModelDimsWhere it runsCost
text-embedding-3-small1536APILow per 1M tokens
text-embedding-3-large3072APIHigher
all-MiniLM-L6-v2384Local CPU/GPUFree (compute only)

Key Takeaway

Pick one embedding model per index—mixing models without re-embedding breaks geometry.

3. Similarity Search

Cosine Similarity

Measures angle between vectors—popular because length matters less than direction for many text models.

MetricIntuition
Cosine similaritySame direction = high score
Dot productCares about magnitude too
Euclidean distanceStraight-line distance in space

Plain-English algorithm: (1) embed query, (2) embed corpus (or precompute), (3) score every doc, (4) return top-k.

Concept: “Nearest neighbors” in embedding space ≈ “most related paragraphs” in human space—usually.

4. Vector Databases

They store vectors + metadata and run approximate nearest neighbor (ANN) search fast.

EngineVibe
ChromaLocal-friendly, fast to prototype
PineconeManaged, scales without ops drama
WeaviateGraph + vector hybrid features
QdrantOSS, rich filtering, nice Docker story

Key Example: Chroma in-memory collection + query—pattern matches most tutorials.

python
[object Object], chromadb

client = chromadb.Client()
col = client.create_collection(,[object Object],, metadata={,[object Object],: ,[object Object],})

docs = [
    ,[object Object],,
    ,[object Object],,
    ,[object Object],,
]
col.add(documents=docs, ids=[,[object Object], ,[object Object], i ,[object Object], ,[object Object],(,[object Object],(docs))])

hits = col.query(query_texts=[,[object Object],], n_results=,[object Object],)
,[object Object], doc, dist ,[object Object], ,[object Object],(hits[,[object Object],][,[object Object],], hits[,[object Object],][,[object Object],]):
    ,[object Object],(,[object Object],(,[object Object], - dist, ,[object Object],), doc)

Metadata Filtering

Add metadatas=[{...}] per row, then where={...} on query—think SQL predicates on top of semantic search.

VendorStandout
PineconeManaged scale, straightforward ops story
WeaviateHybrid + modules ecosystem
QdrantStrong OSS filtering, Docker-friendly
ChromaFastest “hello world” locally

Try This! Tag chunks with doc_version now; future you will thank past you when PDFs update.

Concept: Metadata filters are cheap precision—use them before you bump embedding dimensions.

5. Indexing Strategies

HNSW (Hierarchical Navigable Small World)

Graph-like index: “local hops + occasional long jumps.” Default in many DBs—great general-purpose ANN.

KnobTradeoff
More links / higher efBetter recall, slower build/search

IVF (Inverted File)

Cluster vectors, search only promising clusters—great at huge scale; needs training / parameter tuning.

Choosing the Right Strategy

StrategyBest forBuildQueryMemory
Flat brute forceTiny setsinstantslowlow
HNSWMost prod RAG sizesmediumfasthigher
IVF (+ PQ variants)Massive corporahigherfasttunable

Fun Fact: ANN means approximate—you trade perfect recall for speed. Always benchmark on your queries.

Practice Exercises

LevelIdea
Beginner20 FAQs in Chroma; compare keyword vs semantic hits
IntermediateSame corpus with two embedding models; compare misfires
AdvancedBenchmark Chroma vs Qdrant at 100k vectors (latency + recall)

Mini-Project: Personal Knowledge Base

CLI: add path/to.md, search "question". Steps: load text → chunk → embed with one model → store in persistent Chroma → query with citations in the printed output.

Key Takeaways

Key Takeaway

  • Embeddings are semantic coordinates for text.
  • Cosine similarity is the usual default for matching sentences.
  • Vector DBs = vectors + metadata + fast ANN.
  • HNSW is the first index to try; IVF when scale forces it.
  • Never mix embedding models in one index without a plan.

Resources for Further Learning

← Previous: Prompt Chaining | Next: RAG Fundamentals →