The Agentic AI Codex
Ch 09 · RAG & Vector Search
Chapter 09 · Knowledge at scale

Retrieval-Augmented Generation — RAG

LLM context windows are large, but the world is larger. RAG bridges them: retrieve the most relevant pieces from your knowledge base, then generate the answer using only what you retrieved. Done well, it kills hallucinations, lets you cite sources, and works on data far newer than any training cut-off.

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

Docs→ Parse→ Chunk→ Embed→ Vector DB
Question→ Embed→ Search→ Re-rank→ Stuff into prompt→ LLM answer + citations

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.

FamilyDimNotes
OpenAI text-embedding-3-small / large1536 / 3072Strong defaults, multilingual
Voyage AI1024+Top of benchmarks, retrieval-tuned
Cohere embed-multilingual1024Excellent across 100+ languages
BGE / E5 / GTE (open)768–1024Free, self-hostable
Domain-specificvariesCode embeddings, biomedical embeddings
Pick the right model
Multilingual corpus → multilingual embedder. Code corpus → code embedder. Same-language general English → the small/cheap model is usually enough. The "best benchmark" model is rarely the best for your data.

9.4 · Chunking — the most under-rated lever

You don't embed whole documents — you embed chunks. The granularity directly controls retrieval quality.

StrategyWhen
Fixed-size (e.g. 300 tokens, 50 overlap)Simple baseline; works for prose.
Recursive splitterSplits on paragraph → sentence → token. The default in many libs.
Semantic chunkingSplit where embedding-distance crosses a threshold — preserves topical coherence.
Markdown / heading-awareUse the document's natural structure (H1, H2…) as chunk boundaries.
Sentence-windowEmbed sentences but return ±N neighbouring sentences in the prompt.
Parent-docEmbed small chunks; return their larger parent passage to the LLM.
Always add overlap
50–100 token overlap between chunks dramatically reduces "cut-off answer" failures, at minimal cost.

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

IndexDefinitionTrade-off
FlatCompare the query to every stored vector. Exact, brute-force.Perfect quality; cost grows linearly with N.
IVFPartition vectors into clusters at build time; at query time, search only the nearest clusters.Much faster; small recall loss.
HNSWBuilds 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
Ask the LLM to imagine a perfect answer to the query, embed that, and search with it. The "fake" answer's embedding is often closer to real answer chunks than the query itself.
Multi-Vector / ColBERT
Embed every token, not just the whole chunk. Late-interaction lets you do token-level matching at search time. Higher quality, more storage.
GraphRAG
Build a knowledge graph from the corpus (entities, relations), retrieve by graph traversal as well as vector search. Wins on multi-hop questions ("which customer of the company that acquired X was the founder of Y").
Agentic RAG
Let the agent decide when to retrieve, with what query, and how many passes. Far better recall on complex questions, more cost.
Self-RAG
The model emits special tokens to signal "I need to retrieve" and self-critiques retrieved content before using it. Reduces unnecessary retrieval.

9.10 · Evaluating RAG — the four numbers

MetricWhat it asks
Context precisionOf the retrieved chunks, how many are actually relevant?
Context recallOf all relevant chunks, how many did we retrieve?
FaithfulnessDoes the answer only contain facts present in retrieved context?
Answer relevanceDoes 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.

9.11 · Self-check

Q1 · You retrieve 20 chunks; the LLM answers wrong but cites them. Most likely fix?
Switch model
Lower temperature
Add a re-ranker
Bigger context window
Q2 · Best chunking strategy for a 200-page legal contract?
Fixed 1000-token chunks
Heading-aware splitting on sections/clauses
One vector per document
Random 200-char windows