DEV Community

Cover image for RAG Explained Simply: How AI Reads a 700-Page Book to Answer Your Question
Sahil Sharma
Sahil Sharma

Posted on

RAG Explained Simply: How AI Reads a 700-Page Book to Answer Your Question

The Problem: A 700-Page Book and One Exam Question

Imagine you are a student. Your Software Engineering exam is tomorrow. You have a 700-page textbook on your desk, and one question in your head:

"What are the disadvantages of the Waterfall model?"

You open ChatGPT (or any LLM) and ask it. You get an answer, but there are three problems:

  • It is not from YOUR book. Your professor wants the answer the way your textbook explains it.
  • It might be wrong. LLMs sometimes make things up with full confidence. This is called hallucination.
  • You can't paste 700 pages into the chat. It is too big, too slow and too expensive.

So what if the AI could first find the right pages in your book, read only those, and then answer?

That is exactly what RAG does.

What is RAG?

RAG = Retrieval-Augmented Generation.

Break the name into three words and you already understand it:

Word Meaning In our example
Retrieval Find the relevant information Find the pages about the Waterfall model
Augmented Add that information to the question Attach those pages to the student's question
Generation Let the LLM write the answer The LLM answers using those pages

The simplest analogy: RAG turns a closed-book exam into an open-book exam.

Without RAG, the LLM answers from memory. With RAG, the LLM first opens the right pages of the book, and then answers.

Here is the full architecture I drew for this blog:

RAG Architecture

The diagram has two parts:

  1. The vertical flow (top to bottom): preparing the book. This happens once.
  2. The horizontal flow (left to right): answering a question. This happens every time a student asks something.

Let's walk through both.

Phase 1: Preparing the Book (Indexing)

This is the vertical flow in the diagram. Think of it as making a super-smart index for the book, before anyone asks anything.

Step 1: Concerned Doc

This is our source of knowledge: the 700-page Software Engineering book (as a PDF, for example).

It could be anything: company docs, legal files, a product manual, your college notes. RAG works the same way for all of them.

Step 2: Chunks and Metadata

An LLM can't read 700 pages at once, and we don't want it to. So we cut the book into small pieces called chunks.

  • A chunk is usually a few hundred words (for example, a paragraph or half a page).
  • Chunks often overlap a little, so a sentence cut in the middle is not lost.
  • Our 700-page book might become around 3,000 to 5,000 chunks.

With every chunk, we also save metadata, which is extra info about where the chunk came from:

{
  "text": "The Waterfall model is rigid. Once a phase is completed, going back to change requirements is costly...",
  "chapter": "Chapter 2: Software Process Models",
  "page": 47
}
Enter fullscreen mode Exit fullscreen mode

Metadata helps later, when we want to show "Source: Chapter 2, Page 47" in the answer.

Step 3: Embedding Model

Computers don't understand meaning in words. They understand numbers.

An embedding model converts each chunk into a long list of numbers called a vector (for example, 768 or 1536 numbers). This vector represents the meaning of the text.

The magic part: text with similar meaning gets similar numbers.

  • "Disadvantages of the Waterfall model"
  • "Problems with the linear sequential SDLC approach"

These two sentences use different words, but their vectors will be very close to each other. That is how RAG searches by meaning, not by exact keywords.

Step 4: Vector DB

Now we store every chunk's vector + original text + metadata in a Vector Database (like Pinecone, Qdrant, Chroma, or pgvector).

A Vector DB is built for one special job: "Given a vector, find me the most similar vectors, fast."

And that's it. The book is now ready. This whole phase runs once. You only redo it when the book changes.

Phase 2: Answering the Student (Retrieval + Generation)

This is the horizontal flow at the bottom of the diagram. It runs every time someone asks a question.

Step 1: User asks a question

The student types:

"What are the disadvantages of the Waterfall model?"

Step 2: The question goes through the Embedding Model

The question is converted into a vector, exactly like the chunks were.

Important: this must be the same embedding model used in Phase 1. That's why the diagram shows the Embedding Model twice. If you use different models, the numbers won't match, and the search will return garbage. It's like searching an English index with a French dictionary.

Step 3: Search the Vector DB

The Vector DB compares the question's vector with all ~5,000 chunk vectors and returns the top few closest matches (usually 3 to 5). This is called similarity search.

In a few milliseconds, out of 700 pages, it finds something like:

  • Chunk from page 47: "Waterfall is rigid, going back to a previous phase is costly..."
  • Chunk from page 48: "Working software is only available late in the life cycle..."
  • Chunk from page 112: "Comparison: Agile handles changing requirements better than Waterfall..."

Step 4: Retrieved Doc (Chunks)

These few chunks are the retrieved context. Instead of 700 pages, we now have maybe 2 pages of exactly relevant text.

Step 5: LLM

Now comes the Augmented part. We build a prompt that combines the retrieved chunks with the student's question:

You are a helpful study assistant.
Answer the question using ONLY the context below.
If the answer is not in the context, say "I don't know".

Context:
[Page 47] Waterfall is rigid, going back to a previous phase is costly...
[Page 48] Working software is only available late in the life cycle...
[Page 112] Agile handles changing requirements better than Waterfall...

Question: What are the disadvantages of the Waterfall model?
Enter fullscreen mode Exit fullscreen mode

The LLM reads this small, focused prompt and writes the answer. It is no longer guessing from memory. It is answering from the book.

Step 6: Response

The student gets something like:

The main disadvantages of the Waterfall model are:

  1. It is rigid. Changing requirements after a phase is done is costly.
  2. Working software comes very late in the cycle.
  3. It handles changing requirements poorly compared to Agile.

Source: Chapter 2, Pages 47, 48 and 112

Accurate, from the textbook, and with page numbers to verify. That's RAG.

Deep Dive: How the Vector DB Finds the Right Chunks (Semantic Search + Top-K)

Step 3 of Phase 2 is the heart of RAG. If this step picks the wrong pages, even the best LLM will give a wrong answer. So let's open it up.

Keyword Search vs Semantic Search

Keyword search Semantic search
Matches by Exact words Meaning
Query: "Waterfall drawbacks" Misses a page that says "limitations of the linear model" Finds it, because the meaning is the same
Query: "bug" Can match an insect page Understands the software context
Works with Text Vectors (numbers)

Old-school search (like Ctrl+F) looks for the same words. Semantic search looks for the same meaning. That is why RAG uses vectors.

Think of Vectors as Points on a Map

Imagine every chunk of the book as a dot on a giant map.

  • Chunks about Waterfall sit close together in one area.
  • Chunks about Agile and Scrum sit in a nearby area (related topic).
  • Chunks about Software Testing sit further away.
  • Chunks about UML diagrams sit in a completely different corner.

When the student asks a question, the question also becomes a dot on this map. Semantic search simply asks: "Which book dots are closest to the question dot?"

Real vectors have hundreds or thousands of dimensions, not 2. But the idea is exactly the same: close = similar meaning.

How "Close" is Measured: Cosine Similarity

The most common way to measure closeness is cosine similarity. It checks the angle between two vectors:

  • Same direction (small angle) = very similar meaning, score close to 1
  • At a right angle = unrelated, score close to 0
  • Opposite direction = opposite meaning, score close to -1

The formula (A = question vector, B = chunk vector):

cosine similarity(A,B)=A⋅B∥A∥ ∥B∥=∑i=1nAiBi∑i=1nAi2 ∑i=1nBi2 \text{cosine similarity}(A, B) = \frac{A \cdot B}{\lVert A \rVert \, \lVert B \rVert} = \frac{\sum_{i=1}^{n} A_i B_i}{\sqrt{\sum_{i=1}^{n} A_i^2} \, \sqrt{\sum_{i=1}^{n} B_i^2}}

In simple words: multiply the matching numbers of both vectors, add them up, then divide by their lengths.

Other measures you will see in Vector DB settings:

Metric What it measures Better score
Cosine similarity Angle between vectors Higher
Dot product Angle + length together Higher
Euclidean (L2) distance Straight-line distance between points Lower

Rule of thumb: use the metric your embedding model recommends. Most text models work best with cosine.

Example: Scoring Chunks for Our Question

Question: "What are the disadvantages of the Waterfall model?"

The Vector DB compares it with the chunks and gets scores like these (illustrative numbers):

Rank Chunk (page) Text preview Cosine score
1 Page 47 "Waterfall is rigid, going back to a phase is costly..." 0.89
2 Page 48 "Working software comes late in the life cycle..." 0.84
3 Page 112 "Agile handles changing requirements better than Waterfall..." 0.78
4 Page 46 "Phases of the Waterfall model: requirements, design..." 0.71
5 Page 301 "Unit testing checks individual modules..." 0.22

Notice page 46. It is about Waterfall, but it describes the phases, not the disadvantages. So it scores a bit lower. That is semantic search understanding the exact intent of the question.

What is Top-K?

Top-K = "give me the K best-matching chunks."

If K = 3, the Vector DB returns ranks 1, 2 and 3 (pages 47, 48, 112) and ignores the rest. These K chunks become the context for the LLM.

Choosing K is a balance:

K value What happens
Too small (K = 1) You may miss important info. Our answer would only have 1 disadvantage.
Balanced (K = 3 to 5) Enough context, little noise. A good default.
Too big (K = 20) Irrelevant chunks sneak in, the LLM gets confused, and token cost goes up.

Extra Controls Used with Top-K

  • Similarity threshold: only keep chunks above a minimum score (for example 0.75). If nothing passes, the bot can say "I don't know" instead of guessing. In our table, page 301 (0.22) would be dropped even if K was 5.
  • Metadata filtering: search only inside certain chunks, like chapter = "Chapter 2". This is where the metadata from Phase 1 pays off.
  • Re-ranking: fetch more chunks first (say top 20), then use a smarter re-ranker model to pick the best 3 to 5. More accurate, a bit slower.
  • MMR (Maximal Marginal Relevance): avoids picking 3 chunks that all say the same thing, so the context covers more points.
  • Hybrid search: combine keyword search + semantic search. Useful for exact terms like error codes, names or formulas ("COCOMO", "IEEE 830").

How is it So Fast? (ANN Search)

For our book (~5,000 chunks), the DB could simply compare the question with every chunk. This is called brute-force or exact search, and it's fine at small scale.

But real apps can have millions of chunks. Comparing with all of them for every question is too slow. So Vector DBs use ANN (Approximate Nearest Neighbor) search.

The most popular ANN method is HNSW (Hierarchical Navigable Small World). Think of it like travelling across India:

  1. First take a flight to the right state (top layer, few long jumps).
  2. Then a train to the right city (middle layer).
  3. Then an auto to the exact street (bottom layer, short precise steps).

You never check every house in the country, but you still reach the right address. HNSW does the same with vectors: it jumps through layers of a graph and reaches the closest chunks in milliseconds.

"Approximate" means it may very rarely miss the absolute best match, but it is thousands of times faster. For RAG, that trade-off is almost always worth it.

Other ANN index types you might see: IVF (group vectors into clusters, search only the closest clusters) and PQ (compress vectors to save memory).

Semantic Search + Top-K in JavaScript (Brute-Force Version)

function cosineSimilarity(a, b) {
  let dot = 0, normA = 0, normB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}

function semanticSearch(queryVector, chunks, { topK = 3, minScore = 0.75 } = {}) {
  return chunks
    .map(chunk => ({ ...chunk, score: cosineSimilarity(queryVector, chunk.vector) }))
    .filter(chunk => chunk.score >= minScore)   // similarity threshold
    .sort((a, b) => b.score - a.score)          // best match first
    .slice(0, topK);                            // keep only Top-K
}
Enter fullscreen mode Exit fullscreen mode

A real Vector DB does the same job, just with an ANN index (like HNSW) instead of looping over every chunk.

Semantic Search in One Line

Turn the question into a vector, find the K closest chunk vectors by cosine similarity, and hand those chunks to the LLM.

The Whole Flow in One Table

# Box in the diagram What happens Book example
1 Concerned Doc Load the source The 700-page SE book
2 Chunks and Metadata Split into small pieces + save info ~5,000 chunks with chapter and page
3 Embedding Model Text to vectors (meaning as numbers) Each chunk becomes a vector
4 Vector DB Store vectors for fast search Book is now searchable by meaning
5 User Asks a question "Disadvantages of Waterfall?"
6 Embedding Model Question to vector (same model!) Question becomes a vector
7 Vector DB Similarity search, top-k chunks Finds pages 47, 48, 112
8 Retrieved Doc (Chunks) Relevant context ~2 pages instead of 700
9 LLM Question + context to answer Writes a grounded answer
10 Response Shown to the user Answer with page sources

Steps 1 to 4 run once. Steps 5 to 10 run for every question.

The same thing in (pseudo) JavaScript

// Phase 1: run once
const chunks = splitIntoChunks(book, { size: 500, overlap: 50 });
for (const chunk of chunks) {
  const vector = await embed(chunk.text);
  await vectorDB.insert({ vector, text: chunk.text, page: chunk.page });
}

// Phase 2: run for every question
async function askRAG(question) {
  const qVector = await embed(question);                 // same model!
  const topChunks = await vectorDB.search(qVector, { topK: 3 });
  const context = topChunks.map(c => `[Page ${c.page}] ${c.text}`).join("\n");
  return llm.generate(`Answer using only this context:\n${context}\n\nQuestion: ${question}`);
}
Enter fullscreen mode Exit fullscreen mode

That's the full idea of RAG in around 15 lines.

Why Not Just Paste the Whole Book?

Approach Problem
Ask the LLM directly Answers from general memory, may hallucinate, not from your book
Paste all 700 pages Too many tokens, slow, costly, and LLMs miss details in very long inputs
Fine-tune the LLM on the book Expensive, needs retraining when the book changes, still no page sources
RAG Sends only the relevant pages, cheap, up to date, and can cite sources

Where RAG Can Go Wrong

RAG is simple, but not magic. Watch out for these:

  • Bad chunking: chunks too small lose context, chunks too big add noise.
  • Wrong chunks retrieved: if search finds the wrong pages, the LLM gives a wrong answer with confidence.
  • Different embedding models: question and chunks must use the same model.
  • Stale data: if the book gets a new edition, you must re-index it.

Most real-world RAG work is about fixing these four things.

A Big Thank You

Everything I explained here, I learned from Akshay Saini and his Namaste AI course.

Akshay has a rare talent: he takes a topic that sounds scary, like RAG, embeddings or vector databases, and makes it feel simple and obvious. The way he explains the why behind every step is what made this architecture click for me.

Thank you, Akshay, for teaching with so much clarity and passion. If you want to learn AI engineering from the basics, the Namaste AI course is a great place to start.

Wrapping Up

One line to remember:

RAG = find the right pages first, then let the LLM answer from them.

It is the open-book exam for AI. And now, you can explain it to anyone.

If this helped you, drop a like or a comment. Tell me what you want me to break down next: chunking strategies, vector databases, or building a RAG app in Node.js?

Happy learning!

Top comments (0)