9.1 · Why RAG, in one paragraph
Pre-trained LLMs know a lot of the world, but they don't know your contracts, your tickets, your codebase, your last 24 hours of Slack. RAG augments the prompt with the k most relevant snippets from a knowledge base you control, so the model can answer with current, private, citable knowledge — without retraining.
9.2 · The standard pipeline
9.3 · Embeddings — choosing the right model
An embedding model turns text into a dense vector $\mathbf{e} \in \mathbb{R}^d$ such that semantically similar texts have high cosine similarity.
| Family | Dim | Notes |
|---|---|---|
| OpenAI text-embedding-3-small / large | 1536 / 3072 | Strong defaults, multilingual |
| Voyage AI | 1024+ | Top of benchmarks, retrieval-tuned |
| Cohere embed-multilingual | 1024 | Excellent across 100+ languages |
| BGE / E5 / GTE (open) | 768–1024 | Free, self-hostable |
| Domain-specific | varies | Code embeddings, biomedical embeddings |
9.4 · Chunking — the most under-rated lever
You don't embed whole documents — you embed chunks. The granularity directly controls retrieval quality.
| Strategy | When |
|---|---|
| Fixed-size (e.g. 300 tokens, 50 overlap) | Simple baseline; works for prose. |
| Recursive splitter | Splits on paragraph → sentence → token. The default in many libs. |
| Semantic chunking | Split where embedding-distance crosses a threshold — preserves topical coherence. |
| Markdown / heading-aware | Use the document's natural structure (H1, H2…) as chunk boundaries. |
| Sentence-window | Embed sentences but return ±N neighbouring sentences in the prompt. |
| Parent-doc | Embed small chunks; return their larger parent passage to the LLM. |
9.5 · Vector stores — what each one is
A vector store (a.k.a. vector database) is a database optimised for one operation: given a query vector, return the k nearest stored vectors. They differ in how they store, index, filter, and scale those vectors.
FAISS
What it is. A Facebook-built library (not a server) for in-memory nearest-neighbour search at extreme speed.
Example. A research notebook with 1M product embeddings — load FAISS in Python, search in milliseconds.
Chroma
What it is. A persistent, SQLite-style vector DB designed for local development and prototypes.
Example. A side-project RAG bot that stores 50,000 doc chunks on your laptop.
pgvector
What it is. A Postgres extension that adds a vector column type plus index support.
Example. Your SaaS already uses Postgres for users / orders — add embeddings to the same DB, join across them in one query.
Qdrant
What it is. A self-hostable Rust vector DB with rich filtering on payload fields (tags, timestamps).
Example. Multi-tenant RAG where every search must be filtered by tenant_id and language before vector match.
Weaviate
What it is. Open-source vector DB with built-in hybrid search and modular vectorisers.
Example. A news-site search that combines keyword and semantic ranking out of the box.
Pinecone
What it is. A fully managed vector DB — auto-scaling, no ops, paid per pod / serverless query.
Example. A funded startup that wants 99.9% uptime on RAG without hiring an infra engineer.
Milvus
What it is. An OSS vector DB engineered for billion-scale collections on a cluster.
Example. Image-search at scale across hundreds of millions of product photos.
Indexes you’ll hear about — definitions
| Index | Definition | Trade-off |
|---|---|---|
| Flat | Compare the query to every stored vector. Exact, brute-force. | Perfect quality; cost grows linearly with N. |
| IVF | Partition vectors into clusters at build time; at query time, search only the nearest clusters. | Much faster; small recall loss. |
| HNSW | Builds a multi-layer graph where each node links to its neighbours; search hops greedily down layers. | Near-perfect quality at sub-ms latency. The default in 2026. |
| PQ (Product Quantization) | Splits each vector into chunks and compresses each chunk to a code-book index. | 10–100× memory savings; small accuracy hit. Used inside billion-scale indexes. |
9.6 · Retrieval strategies — what each one does
Dense (vector) search
Definition. Embed the query, rank stored chunks by cosine similarity to that vector.
Example. "How do I cancel my plan?" matches a chunk titled "Subscription termination steps" — same meaning, different words.
Sparse (BM25 / TF-IDF)
Definition. Rank chunks by keyword overlap, weighted by how rare each word is across the corpus.
Example. "Error code E-2317" — dense embeddings often miss exact codes; BM25 finds them instantly.
Hybrid
Definition. Run dense and sparse in parallel, then fuse their rankings (Reciprocal Rank Fusion or weighted sum).
Example. Production RAG with mixed natural-language and code/ID queries.
Metadata filter
Definition. Apply a SQL-like filter on payload fields before doing vector search (tenant_id, date, language).
Example. "Show me support articles updated in the last 90 days, in Urdu, for premium tier".
Multi-query
Definition. Ask the LLM to rewrite the query 3–5 ways; union the hits from each.
Example. A long, ambiguous question gets variants like "X causes Y", "why does Y happen", "factors leading to Y" — broader recall.
HyDE
Definition. Ask the LLM to imagine a perfect answer to the query, embed that, and search with it instead of the query.
Example. Short queries like "ramp"; the hypothetical answer text is closer to real chunks than the bare word.
9.7 · Re-ranking — the cheapest quality lift
Retrieval is fast and approximate. Re-ranking is slower but exact: a cross-encoder reads the query + chunk together and outputs a relevance score.
top_20 = vector.search(query, k=20) # cheap recall
top_5 = reranker.rerank(query, top_20)[:5] # precise precision
answer = llm.generate(query, context=top_5)
Cohere Rerank, Voyage Rerank, and BAAI/bge-reranker are standard choices.
9.8 · The generation step — making the LLM behave
- Pass retrieved chunks as numbered passages, then ask for cited answers — "use [1], [2]…"
- Explicitly state: "If the answer is not in the passages, say you don't know."
- Always show citations to users — it builds trust and makes hallucinations spottable.
- Keep the retrieved context shorter than the model can comfortably reason over, even if the window is bigger. Models attend best to the start and end.
9.9 · Advanced patterns
HyDE — Hypothetical Document Embeddings
Multi-Vector / ColBERT
GraphRAG
Agentic RAG
Self-RAG
9.10 · Evaluating RAG — the four numbers
| Metric | What it asks |
|---|---|
| Context precision | Of the retrieved chunks, how many are actually relevant? |
| Context recall | Of all relevant chunks, how many did we retrieve? |
| Faithfulness | Does the answer only contain facts present in retrieved context? |
| Answer relevance | Does the answer actually address the question? |
Toolkits like Ragas, TruLens, and DeepEval automate these with LLM-as-judge. Always pair them with 50–100 human-labelled queries for sanity.