Intermediate6 min read41 of 52

RAG (Retrieval-Augmented Generation)

Retrieving relevant external documents at query time and injecting them into the prompt to ground generation.

SPEC: RAG (Retrieval-Augmented Generation)

Definition

[Definition] RAG (Retrieval-Augmented Generation) is an architecture pattern that combines information retrieval with LLM generation. Instead of relying solely on the model's parametric (baked-in) knowledge, RAG dynamically retrieves relevant documents from an external knowledge base at query time and injects them into the prompt before generation.

The Core Insight

[Key Insight] LLMs know a lot — but their knowledge is frozen at training cutoff, can be wrong, and can't include your private data. RAG solves this by giving the model a "retrieval tool" to look things up at runtime.

Without RAG: Model answers from memory → may hallucinate, outdated With RAG: Model answers from retrieved documents → grounded, current

RAG Architecture

Standard RAG Pipeline

1. INDEXING (offline, done once): Documents → Chunking → Embedding → Vector Store 2. RETRIEVAL (online, per query): User Query → Query Embedding → Vector Search → Top-K Chunks 3. GENERATION (online, per query): System Prompt + Retrieved Chunks + User Query → LLM → Grounded Answer

Phase 1: Indexing

Document Loading

  • Load source documents: PDFs, Word docs, websites, databases, code files
  • Tools: LangChain loaders, LlamaIndex readers, Unstructured.io

Chunking

  • Split documents into smaller pieces (chunks) that fit in the context window
  • Strategies:
    • Fixed-size: every N tokens with M token overlap
    • Recursive character splitting: split on paragraphs > sentences > words
    • Semantic chunking: split at semantic boundaries (topic shifts)
    • Document-structure aware: respect headers, sections, code blocks

Embedding

  • Convert each chunk to a dense vector using an embedding model
  • The vector captures the semantic meaning of the chunk
  • Common models: OpenAI text-embedding-3-large, Cohere embed-v3, BGE, E5

Storage in Vector Database

  • Store (chunk_text, embedding_vector, metadata) in a vector DB
  • Popular vector DBs: Pinecone, Weaviate, Chroma, Qdrant, pgvector, FAISS

Phase 2: Retrieval

Query Embedding

  • Embed the user's question using the same embedding model used for indexing
  • Query and chunk embeddings must be in the same vector space

Similarity Search

  • Find the top-K chunks most similar to the query embedding
  • Default metric: cosine similarity
  • K is typically 3–10 chunks

Retrieval Strategies

StrategyDescriptionBest For
Semantic (dense)Embedding-based similarityConceptual questions
Keyword (sparse, BM25)TF-IDF term matchingExact term lookup
HybridCombine dense + sparse with RRFGeneral purpose
Contextual compressionRe-rank + compress retrieved chunksPrecision
Parent-childRetrieve child, return parent chunkBetter coherence
Multi-queryGenerate N query variants, retrieve for eachRecall
HyDEGenerate a hypothetical answer, retrieve similar to itComplex queries

Phase 3: Generation (Augmented)

System Prompt: "Answer based only on the context below. If not found, say so." Context: [Chunk 1: relevant passage from doc A] [Chunk 2: relevant passage from doc B] [Chunk 3: relevant passage from doc C] Question: [user's query] Answer:

Advanced RAG Techniques

Re-ranking

  • After initial retrieval, use a cross-encoder to re-rank chunks by relevance
  • Cross-encoders compare query + chunk together (slower but more accurate)
  • Models: Cohere Rerank, BAAI/bge-reranker, ColBERT

Query Transformation

  • Query rewriting: rephrase the query for better retrieval
  • HyDE: generate a hypothetical document the answer might come from, then retrieve similar
  • Multi-query: generate multiple query variants to increase recall

Self-RAG

  • Model decides whether to retrieve (not always necessary)
  • After retrieval, critiques relevance of retrieved documents
  • More efficient for mixed queries (some need retrieval, some don't)

Agentic RAG

  • Agent iteratively retrieves and reasons
  • "Read this chunk → need more info → retrieve again → synthesize"
  • Better for complex multi-hop questions

RAG Evaluation Metrics

MetricMeasuresTool
Context PrecisionAre retrieved chunks relevant?RAGAS
Context RecallWere all relevant chunks retrieved?RAGAS
FaithfulnessDoes answer match retrieved context?RAGAS, TruLens
Answer RelevanceDoes answer address the question?RAGAS
End-to-End AccuracyIs the final answer correct?Human eval

RAG vs. Fine-Tuning

AspectRAGFine-Tuning
Knowledge updatesEasy (add to vector DB)Requires retraining
Custom factsExcellentGood
Private dataExcellentPossible but risky
CostRetrieval infraGPU compute
HallucinationLower (grounded)Lower (domain knowledge)
Format/styleLimitedStrong

Rule of thumb: RAG for knowledge, fine-tuning for behavior/style.

RAG Frameworks and Tools

ToolNotes
LangChainFull RAG pipeline, many integrations
LlamaIndexDocument-focused RAG, complex query engines
HaystackEnterprise RAG
AWS Bedrock Knowledge BasesManaged RAG on AWS
Azure AI SearchEnterprise hybrid retrieval
RAGASRAG evaluation framework

Common RAG Failure Modes

FailureCauseFix
Missing relevant chunksPoor chunking or embeddingBetter chunking strategy, hybrid retrieval
Model ignores retrieved contextWeak grounding instructionsStronger system prompt constraints
Retrieved wrong chunksQuery-document mismatchQuery rewriting, re-ranking
Long chunks overwhelm contextK too large or chunks too bigSmaller chunks, contextual compression
Stale knowledge baseIndex not updatedRegular re-indexing pipeline

Related Concepts

  • Embeddings, Vector Database, Grounding, Hallucination, Context Window, Chunking, Retrieval, LLM