RAG (Retrieval-Augmented Generation) is a technique that improves AI answers by
first searching relevant documents, then feeding that context to a language model to generate accurate, up-to-date responses.
Think of it like an open-book exam — instead of relying solely on memorized knowledge,
the AI can look up relevant information before answering.
The Problem RAG Solves
❌ Without RAG — LLM Only
Training data has a knowledge cutoff — can't answer about recent events
Often hallucinates — generates confident but wrong answers
Cannot access private data (company docs, personal files)
Context window limits how much information fits in one prompt
✅ With RAG — Grounded AI
Always retrieves current information from your documents
Answers are grounded in real sources — citations included
Works with private knowledge bases — no fine-tuning needed
Scales to millions of documents efficiently
Core Building Blocks
🔢
Vector Embeddings
Text is converted into arrays of numbers (vectors) that capture semantic meaning. Similar texts produce similar vectors, enabling meaning-based search rather than just keyword matching.
🗄️
Vector Database
A specialized database that stores and searches embedding vectors at speed. Examples: Pinecone, Weaviate, Chroma, Qdrant, FAISS. Finds the most similar vectors in milliseconds.
✂️
Chunking
Large documents are split into smaller pieces (chunks) — typically 200–500 tokens each — with some overlap between adjacent chunks to preserve context across boundaries.
🎯
Semantic Similarity
Retrieval uses cosine similarity or dot product to rank chunks by relevance. The top-k most relevant chunks are selected and injected into the prompt as context.
Glossary
embedding
Numerical representation of text as a high-dimensional vector (e.g., 1536 dimensions)
chunk
A small segment of a document, usually 100–500 tokens with optional overlap
vector store
Database optimized for storing and querying embedding vectors by similarity
top-k
The k most relevant chunks retrieved for a given query (typically k = 3–10)
context window
Maximum number of tokens an LLM can process in a single call
prompt template
A structured template that combines retrieved context + user query into an LLM prompt
When an LLM generates plausible-sounding but factually incorrect information
The RAG Pipeline — Two Phases
RAG operates in two distinct phases: Indexing (done once, offline) and Querying (done at runtime, per user request).
📥 Phase 1 — Indexing (Offline)Run once when documents are added
1
📄Load Documents
Import raw documents from various sources — PDFs, Word files, web pages, databases, APIs. Document loaders handle format conversion to plain text.
PDFHTMLCSVMarkdownJSON
↓
2
✂️Split into Chunks
Large documents are split into smaller, overlapping text chunks. Chunk size (200–500 tokens) and overlap (10–20%) are tunable hyperparameters that affect retrieval quality.
RecursiveCharacterSplitteroverlaptoken-based
↓
3
🔢Generate Embeddings
Each chunk is sent through an embedding model, which converts it into a dense vector of numbers. The vector captures the semantic meaning of the text.
Embeddings (plus the original chunk text and metadata) are stored in a vector database. This creates a searchable index that can find similar vectors in milliseconds.
PineconeChromaFAISSWeaviate
⚡ Runtime Query Phase Begins Here
💬 Phase 2 — Querying (Online)Runs on every user request
5
❓Receive User Query
A user submits a question or request. This is the starting point of the real-time pipeline. The query will be processed the same way as document chunks — converted to an embedding.
natural languagereal-time
↓
6
🔍Embed the Query
The user query is passed through the same embedding model used during indexing. This produces a query vector in the same vector space as the document chunks.
same embedding modelquery vector
↓
7
🎯Retrieve Top-K Chunks
The vector database performs a similarity search, comparing the query vector against all stored document vectors. The top-k most similar chunks are returned (typically k=3–5).
cosine similarityANN searchtop-k=5
↓
8
📝Build Augmented Prompt
Retrieved chunks are inserted into a structured prompt template alongside the original user query. The LLM is instructed to answer using only the provided context.
prompt templatecontext injectionsystem prompt
↓
9
🤖LLM Generates Answer
The augmented prompt is sent to the LLM (GPT-4, Claude, Llama, etc.). The model generates a response grounded in the retrieved context, dramatically reducing hallucinations.