Retrieval-Augmented Generation

How RAG actually works - the complete picture

LLMs are frozen at their training cutoff and know nothing about your private data. RAG fixes that: it retrieves relevant chunks from your knowledge base at query time and augments the prompt with them, so the model answers from real, current, cited sources instead of guessing.

Embeddings Vector search Chunking Grounding & citations
01 - What

What is RAG?

Retrieval-Augmented Generation is a pattern that connects a language model to an external knowledge store. Instead of relying only on what the model memorized during training, you retrieve the most relevant passages for a question and paste them into the prompt as context. The model then generates an answer grounded in that retrieved evidence.

πŸ“₯ Ingestion (offline)

Documents are split into chunks, embedded into vectors, and stored in a vector database. Done once, ahead of time.

πŸ”Ž Retrieval (online)

At query time, the question is embedded and the closest chunks are fetched by semantic similarity.

🧠 Generation (online)

Retrieved chunks are stitched into the prompt; the model answers using them, ideally with citations.

The core building blocks

PieceWhat it doesCommon choices
ChunkerSplits documents into retrievable unitsFixed-size, recursive, semantic, by-heading
Embedding modelTurns text into vectors capturing meaningtext-embedding-3, open models
Vector storeIndexes vectors for fast similarity searchpgvector, Pinecone, Weaviate, FAISS
RetrieverFinds top-k relevant chunks per queryDense, keyword (BM25), hybrid
RerankerRe-scores candidates for precisionCross-encoders, LLM rerankers
Key mental model: RAG doesn't teach the model new facts - it puts the right facts in front of the model at the moment it answers. Retrieval quality, not the LLM, is usually what makes or breaks a RAG system.
02 - Why

Why RAG exists

Fine-tuning bakes knowledge into weights - it's slow, expensive, and stale the moment your data changes. RAG keeps knowledge outside the model, where it's cheap to update and easy to control.

🎯 Reduces hallucination

Grounding answers in retrieved text sharply cuts made-up facts and lets you cite sources for verification.

πŸ”„ Always current

Update the knowledge base and answers change instantly - no retraining. Add, edit, or delete a document and it's reflected on the next query.

πŸ” Private & access-controlled

Your data never enters model weights. You can filter retrieval by user permissions so people only see what they're allowed to.

πŸ’Έ Cheaper than fine-tuning

No training runs. You pay for embeddings once and a bit of extra context per query - a fraction of the cost and effort.

In Plain Terms

RAG explained with analogies

Same idea, four ways to picture it, so it clicks whoever you are.

πŸŽ“ For a student

RAG is an open-book exam. The model doesn't have to memorize everything; it looks up the relevant pages first, then writes the answer with the book open in front of it.

πŸ‘©β€πŸ’» For a developer

It's like putting a search index in front of a function. Instead of hardcoding knowledge, you query the store for the rows that matter, then pass them in as arguments to the model call.

🏒 For a professional

Think of a research assistant who pulls the exact files from the cabinet before your meeting, so your briefing quotes real documents instead of vague memory.

🍳 Everyday version

A chef who checks the recipe card before cooking, rather than guessing from memory. The skill is the same; the facts come from the card.

03 - How

How it works under the hood

RAG has two pipelines: an offline ingestion pipeline that builds the index, and an online query pipeline that runs per request.

πŸ“¦ Ingestion pipeline

Load β†’ clean β†’ chunk β†’ embed β†’ upsert into the vector store. Metadata (source, section, permissions, timestamp) rides along with each chunk.

⚑ Query pipeline

Embed the question β†’ search top-k β†’ (optionally) rerank β†’ assemble a grounded prompt β†’ generate β†’ return answer + citations.

The architecture at a glance

Architecture - ingestion builds the index; queries read from it
flowchart LR
    subgraph Ingest["πŸ“¦ Offline ingestion"]
        D["πŸ“„ Documents"] --> CH["βœ‚οΈ Chunk"]
        CH --> EM1["πŸ”’ Embed"]
        EM1 --> VDB[("πŸ—„οΈ Vector DB")]
    end
    subgraph Query["⚑ Online query"]
        Q["❓ User question"] --> EM2["πŸ”’ Embed query"]
        EM2 --> SR["πŸ”Ž Similarity search"]
        VDB --> SR
        SR --> RR["πŸ“Š Rerank"]
        RR --> PR["🧩 Build prompt + context"]
        PR --> LLM["🧠 LLM"]
        LLM --> ANS["βœ… Grounded answer + citations"]
    end
        

A minimal query in pseudocode

q_vec   = embed(question)
hits    = vector_db.search(q_vec, top_k=20, filter=user_acl)
top     = rerank(question, hits)[:5]
context = "\n\n".join(h.text + f"  [source: {h.source}]" for h in top)

answer = llm.generate(
    system="Answer ONLY from the context. Cite sources. Say 'I don't know' if absent.",
    user=f"Context:\n{context}\n\nQuestion: {question}"
)

Notice the system prompt constrains the model to the retrieved context and tells it to abstain - this is what turns retrieval into trustworthy, grounded generation.

04 - Sequence Diagrams

Detailed sequence diagrams

Three views: offline ingestion, the online query path, and an advanced flow with reranking and abstention.

Diagram 1 - Ingestion: building the vector index (offline, once)
sequenceDiagram
    autonumber
    participant Src as πŸ“„ Source docs
    participant Pipe as βš™οΈ Ingest pipeline
    participant Emb as πŸ”’ Embedding model
    participant VDB as πŸ—„οΈ Vector DB

    Src->>Pipe: Load raw files (PDF, HTML, DB)
    Pipe->>Pipe: Clean & normalize text
    Pipe->>Pipe: Split into chunks (+ metadata)
    loop for each chunk
        Pipe->>Emb: embed(chunk)
        Emb-->>Pipe: vector[1536]
    end
    Pipe->>VDB: upsert(vectors + text + metadata)
    VDB-->>Pipe: index updated
        
Diagram 2 - Query: retrieval then grounded generation (the hot path)
sequenceDiagram
    autonumber
    participant U as πŸ‘€ User
    participant App as πŸ–₯️ RAG app
    participant Emb as πŸ”’ Embedding model
    participant VDB as πŸ—„οΈ Vector DB
    participant LLM as 🧠 LLM

    U->>App: Ask a question
    App->>Emb: embed(question)
    Emb-->>App: query vector
    App->>VDB: search(query vector, top_k, filter=ACL)
    VDB-->>App: top-k chunks + sources
    App->>App: Assemble prompt (context + question)
    App->>LLM: generate(grounded prompt)
    LLM-->>App: answer with citations
    App-->>U: Answer + linked sources
        
Diagram 3 - Advanced: rerank, abstain, and fall back
sequenceDiagram
    autonumber
    participant U as πŸ‘€ User
    participant App as πŸ–₯️ RAG app
    participant VDB as πŸ—„οΈ Vector DB
    participant RR as πŸ“Š Reranker
    participant LLM as 🧠 LLM

    U->>App: Question
    App->>VDB: hybrid search (dense + BM25), top_k=20
    VDB-->>App: 20 candidates
    App->>RR: rerank(question, candidates)
    RR-->>App: ordered by relevance
    alt top score below threshold
        App-->>U: "I don't have enough information"
    else relevant context found
        App->>LLM: generate(top 5 chunks + question)
        LLM-->>App: grounded answer + citations
        App-->>U: Answer + sources
    end
        
05 - Step by Step

The 0 β†’ 100 flow

From an empty knowledge base to a cited, grounded answer - the whole journey in order.

00
Ingest

Collect & clean sources

Gather the documents - wikis, PDFs, tickets, databases - and strip boilerplate, headers, and noise so only useful text remains.

10
Chunk

Split into retrievable units

Break documents into chunks sized for retrieval (often 200–800 tokens) with slight overlap, attaching metadata like source and section.

20
Embed

Turn chunks into vectors

Run each chunk through an embedding model to get a vector that captures its meaning in high-dimensional space.

30
Index

Store in a vector database

Upsert vectors plus their text and metadata into a vector store with an ANN index for fast similarity search.

40
Query

User asks a question

A request arrives. The question is embedded with the same model used for ingestion so the vectors live in the same space.

50
Retrieve

Find the top-k chunks

Search the vector store for the nearest neighbors, filtered by the user's access permissions. Hybrid search adds keyword matching.

60
Rerank

Sharpen relevance

A cross-encoder or LLM reranker re-scores the candidates so the most on-point passages rise to the top before they hit the prompt.

70
Gate

Decide: answer or abstain

If the best score is too low, the system says "I don't know" rather than hallucinate - a crucial trust step.

80
Augment

Assemble the grounded prompt

Stitch the selected chunks into the prompt with instructions to answer only from context and cite each source.

90
Generate

Model answers from evidence

The LLM produces an answer using the retrieved context, attaching citations that point back to the exact sources.

100
Deliver

Return answer + sources

The user gets a grounded, verifiable answer with clickable citations. Feedback and logs feed evals to improve retrieval over time.

Common Pitfalls

Pitfalls & anti-patterns

Most RAG systems fail on retrieval, not on the model. These are the usual culprits.

βœ‚οΈ Bad chunking

Chunks too large bury the answer in noise; too small and they lose context. Splitting mid-sentence or mid-table destroys meaning. Chunk by structure, not by blind character count.

πŸ”€ Embedding mismatch

Embedding queries and documents with different models, or changing the model without re-indexing, puts vectors in incompatible spaces and retrieval collapses.

πŸ“‰ No reranking

Relying on raw vector similarity alone often surfaces "related but wrong" chunks. Skipping a reranker is the most common cause of plausible-but-off answers.

πŸ“š Over-stuffing context

Cramming 30 chunks into the prompt raises cost and triggers "lost in the middle," where the model ignores the middle of a long context. Retrieve broad, but send few.

🎭 No abstention

If the system never says "I don't know," low-relevance retrievals get answered anyway, and the model confidently hallucinates. Always gate on a relevance threshold.

πŸ•°οΈ Stale or leaky index

Forgetting to re-embed changed docs serves outdated answers; skipping access filters leaks data across users. The index is a living, permissioned asset.

How to Measure

How to measure RAG

Evaluate retrieval and generation separately, so you know which half to fix.

MetricWhat it tells youGood sign
Recall@kDid the relevant chunk make it into the top-k retrieved?High: the answer is reachable
Context precisionWhat fraction of retrieved chunks are actually relevant?High: little noise in the prompt
Faithfulness / groundednessIs the answer supported by the retrieved context?High: few hallucinations
Answer relevanceDoes the answer actually address the question?High: on-topic responses
Citation accuracyDo the cited sources really back the claims?High: trustworthy references
Latency & cost / queryEnd-to-end time and token spend per requestWithin your SLA and budget
Rule of thumb: if faithfulness is low but recall is high, fix the prompt and reranking; if recall itself is low, fix chunking and embeddings first. Measure both before touching the model.
06 - Case Studies

Real-world case studies

Three representative patterns showing RAG in production-style use.

🎧

1 Β· Customer-support assistant over a help center

Pattern: grounded Q&A with citations

A SaaS company wants an assistant that answers customer questions from its docs without inventing features.

  • Help-center articles and release notes are chunked by heading and embedded nightly.
  • Each answer must cite the article it came from; low-confidence queries route to a human.
  • Retrieval is filtered by product tier so customers only see docs for what they bought.
βœ… Outcome: Deflection of routine tickets with far fewer wrong answers, because every response is grounded and traceable to a real doc.
βš–οΈ

2 Β· Legal & contract search

Pattern: precision retrieval over sensitive documents

A legal team needs to ask questions across thousands of contracts and get exact clauses, not paraphrases.

  • Hybrid search (semantic + keyword) captures both meaning and exact legal terms.
  • A cross-encoder reranker ensures the precise clause ranks first.
  • Strict access controls and on-prem embeddings keep confidential data inside the firm.
βœ… Outcome: Lawyers find governing clauses in seconds with citations to the source contract, while sensitive text never leaves the security boundary.
πŸ₯

3 Β· Internal knowledge base for engineers

Pattern: enterprise search across many systems

An engineering org unifies wikis, runbooks, Slack, and code docs into one assistant.

  • Connectors ingest from many sources; metadata records origin and freshness.
  • Stale chunks are re-embedded on change so answers reflect the current state.
  • Answers link back to the exact runbook or thread for verification.
βœ… Outcome: Engineers stop hunting across five tools; the assistant surfaces the right runbook with a citation, cutting resolution time.
07 - Future

Where RAG is heading

RAG is evolving from a single retrieve-then-read step into richer, more adaptive systems.

πŸ€– Agentic RAG

Agents that plan multi-step retrieval - decomposing questions, searching iteratively, and deciding when they have enough evidence.

πŸ•ΈοΈ GraphRAG

Combining vector search with knowledge graphs to answer questions that require connecting facts across many documents.

πŸ“ˆ Retrieval evals as first-class

Measuring recall, precision, and faithfulness continuously - treating retrieval quality as the metric that matters most.

🧩 Long-context vs. RAG

Bigger context windows won't kill RAG; they complement it - RAG controls cost, freshness, and access at any scale.

πŸŽ›οΈ Adaptive retrieval

Systems that decide whether to retrieve at all, and how much, based on the question's difficulty and confidence.

πŸ–ΌοΈ Multimodal RAG

Retrieving over images, tables, audio, and video - not just text - for grounded answers across every data type.

Bottom line: RAG is how you give a general model your specific, current, permissioned knowledge - cheaply and verifiably. As models and retrievers improve, the pattern only gets more central to real AI products.