← Back
RAG·Jul 26, 2026·7 min read

RAG for (newbies), piece by piece

let's understand RAG in an interactive and visual way

Interactive · RAG at a glance

An LLM taking an open-book exam

Select a step
Swipe to follow the answer →How retrieval augmented generation worksA question searches a company handbook, retrieves the relevant leave policy, and gives it to an LLM to produce a grounded answer.COMPANY HANDBOOKUSER QUESTIONCan I carry overunused leave?RETRIEVALsearchthe notesRETRIEVED CONTEXTcarry over up tofive daysGENERATIONLLMquestion + noteANSWER
The question needs private knowledge

The LLM cannot reliably know this company policy on its own.

RAG lets the model look up the right note before answering. Follow the question from retrieval to a grounded answer.

Imagine you join a new company and want to know:

How many days of annual leave can I carry over to next year?

A general LLM may know how leave policies usually work, but it does not know the exact policy at your company. It might give a common answer, tell you that policies vary, or confidently guess something wrong.

Now imagine we first search the company handbook and find the paragraph that says employees can carry over five days. We place that paragraph beside the question and ask the LLM to answer using it.

That is the basic idea behind Retrieval-Augmented Generation, or RAG.

  1. Retrieve information related to the question.
  2. Augment the question with that information.
  3. Let the LLM generate an answer from the combined context.

The LLM is still doing the writing and reasoning. RAG simply gives it the right notes before it starts.

Why do we need RAG if an LLM already knows a lot?

LLMs know a surprising amount because they were trained on a huge amount of text. But knowing a lot is different from having the exact information needed for every question.

An LLM may not know:

  • your company’s private documents
  • a product change made yesterday
  • the latest version of an internal policy
  • a detail hidden inside a long PDF
  • which source should support its answer

The knowledge inside an LLM is also stored indirectly in its model weights. It cannot browse those weights like a database and fetch one exact record whenever we ask.

RAG helps by keeping the knowledge outside the model, where it can be updated, searched, filtered, and shown to the LLM only when it is useful.

What limitations does RAG help with?

Knowledge can be old. An LLM has a training cutoff. Information created or changed after training is not automatically available to it. A RAG system can search a data source that is updated regularly.

Private data was never in training. Your support tickets, research notes, contracts, and internal documentation are not part of a public model’s knowledge. RAG provides controlled access to this information without retraining the entire model.

The model can make up missing details. When the model does not have enough information, it may still produce an answer that sounds reasonable. Relevant context gives it something concrete to reason from.

Exact recall is difficult. Models are good at patterns and language, but they are not reliable databases. RAG handles the lookup, while the LLM handles understanding and explanation.

The complete RAG pipeline

A RAG system has two broad parts.

The first part prepares the data so it can be searched. The second part uses that prepared data to retrieve context and generate an answer.

We will look at preparation, retrieval, and generation separately. This makes it easier to see what each part is responsible for.

Stage 1: Preparing data for retrieval

Before we can retrieve anything, we need to turn the external data into something searchable.

1. Start with external data. The data can come from PDFs, web pages, Notion, Google Drive, a database, support tickets, or any other source your application needs.

2. Load and parse it. Loading gets the file or record into the pipeline. Parsing extracts useful content from it. For a PDF, this may mean recovering paragraphs, headings, tables, and metadata instead of treating the file as one large block. Good parsing matters because retrieval cannot recover information that was lost or scrambled during extraction.

3. Split the text into chunks. Documents are usually too large to retrieve as one unit. We split them into smaller pieces called chunks.

A chunk might be a few paragraphs, one section, or a small part of a table. It should contain enough context to make sense on its own, but stay focused enough to match a specific question.

4. Create embeddings. An embedding model converts every chunk into a list of numbers called a vector. The vector represents the meaning of the text.

Chunks about similar ideas tend to have vectors that are close to each other, even when they use different words.

5. Save them in a vector database. We store each vector together with its original chunk and useful metadata. The vector database is built to search these vectors quickly.

At this point, the preparation is complete. Our data is now ready for retrieval.

Interactive · preparation

Prepare external data for retrieval

Select a step
Step 1 of 5

Start with external data

These files contain the knowledge we want the LLM to use. They can also come from Notion, a website, support tickets, or a database.

Select each step to see what changes. This preparation usually happens before a user asks a question.

Chunk overlap deserves a closer look because the percentage can feel abstract. The diagram below uses a fixed chunk size of 512 tokens and shows exactly what changes when we repeat part of one chunk inside the next.

Interactive · chunk overlap

Move the overlap and watch the chunks change

Try the controls
Overlap between consecutive chunks10%
Example document

Employees may carry over up to five unused leave days. Requests must be submitted before the end of December.

chunk 1 endschunk 2 starts
Swipe to follow all three chunks →Three chunks with adjustable overlapEach chunk contains 512 tokens. Consecutive chunks repeat 51 tokens.DOCUMENT TOKEN POSITIONS051210241434Chunk 1512 tokensChunk 2512 tokensChunk 3512 tokens51 repeated tokens
Chunk size512 tokensmaximum text inside each chunk
Repeated context51 tokenscopied from one chunk into the next
Stride461 tokensdistance before the next chunk begins
Balanced starting point

Around 10 percent is a common starting point. The next chunk receives enough of the previous ending to understand the transition.

Why repeat anything?

A chunk boundary is arbitrary. It can land in the middle of a sentence, explanation, or table row. Overlap copies a small amount of text into the next chunk so both sides keep enough context to make sense during retrieval.

The useful overlap depends on the document and embedding model. Around 10 to 20 percent is a practical range to test, not a rule that works for every dataset.

Stage 2: Retrieving the right context

Now a user asks a question.

The same embedding model converts the question into a vector. We then compare this query vector with the chunk vectors already stored in the database.

One common comparison method is cosine similarity. In simple terms, it measures whether two vectors point in a similar direction. A higher score usually means the question and chunk are closer in meaning.

The database sorts the chunks by similarity and returns the top-k results.

If k = 3, we retrieve the three chunks that appear most relevant to the question.

This is semantic search. A question about "time off that moves to next year" can still match a chunk containing "annual leave carryover," even though the wording is different.

Interactive · retrieval

See similarity search choose the top-k chunks

Try the controls
QuestionHow many leave days can I carry over?
Query embedding[0.3, 1.2, 0.7, …]
Comparecosine similarity
How many chunks should we return?

Top-k keeps the highest scoring matches.

1
Annual leave carryover

Employees may carry over up to five unused leave days.

0.94retrieved
2
Requesting annual leave

Submit planned annual leave through the employee portal.

0.72retrieved
3
Sick leave

Sick leave does not reduce an employee’s annual leave balance.

0.38not selected
4
Company holidays

The company observes twelve public holidays each year.

0.21not selected
Change k to see how the retriever includes more chunks as context. Higher k gives more coverage, but may also introduce less relevant information.

The similarity score is calculated once for every candidate chunk. The query vector stays the same while each stored chunk vector takes its turn in the comparison. After all scores are calculated, the chunks can be ranked from most similar to least similar.

Interactive · cosine

Watch one query compare against five chunks

Try the controls
QuestionHow many leave days can I carry over?
Query embedding[0.82, -0.14, 0.51, 0.21]The question is converted into the same vector space as the chunks.
Comparing chunk 1 of 5

Each stored chunk vector is compared with the same query vector.

Chunk 1
Annual leave carryover

Employees may carry over up to five unused leave days.

[0.79, -0.18, 0.48, 0.25]
waiting
Chunk 2
Requesting annual leave

Submit planned leave requests through the employee portal.

[0.6, 0.2, 0.18, 0.32]
waiting
Chunk 3
Sick leave

Sick leave does not reduce the annual leave balance.

[-0.2, 0.72, 0.1, 0.1]
waiting
Chunk 4
Company holidays

The company observes twelve public holidays each year.

[0.1, -0.1, 0.7, -0.2]
waiting
Chunk 5
Expense policy

Travel expenses require receipts and manager approval.

[-0.3, 0.05, -0.1, 0.8]
waiting
Cosine similarity
query · chunk‖query‖ × ‖chunk‖

It measures the angle between two vectors. A score closer to 1 means their directions, and usually their meanings, are more similar. A score near 0 means little relation. A negative score means the directions point away from each other.

computing chunk 1
What the scores tell us

The retriever ranks chunks by score. The highest scoring chunks become candidates for the top-k context.

c1Annual leave carryover...
c2Requesting annual leave...
c3Sick leave...
c4Company holidays...
c5Expense policy...
These short vectors make the calculation visible. Real embedding models produce much larger vectors, but cosine similarity follows the same process.

Stage 3: Augmenting and generating

We now have three useful ingredients:

  1. the system prompt, which tells the model how to behave
  2. the user’s question
  3. the top-k retrieved chunks

We combine them into one prompt. This is the augmentation step.

It may look roughly like this:

You are a helpful company assistant. Answer only from the provided context.
Context: Employees may carry over up to five days of annual leave.
Question: How many leave days can I carry over?

The LLM reads this complete prompt and generates the final answer:

You can carry over up to five days of annual leave.

The answer is useful because the LLM can explain naturally, but it is grounded because the important fact came from the company handbook.

Interactive · generation

See what retrieved context changes

Try the controls
System prompt

Answer from the supplied company context.

User query

How many leave days can I carry over?

Retrieved chunks

Employees may carry over up to five unused leave days.

LLM
Grounded answer

You can carry over up to five unused leave days.

The exact fact came from the retrieved handbook chunk.
Toggle the retrieved context to compare a grounded answer with a plausible answer produced from general model knowledge.

Putting it all together

RAG is easier to understand when we separate the jobs:

  • The parser turns source files into usable text.
  • The chunker divides that text into searchable pieces.
  • The embedding model represents meaning as vectors.
  • The vector database stores and searches those vectors.
  • The retriever selects the most relevant chunks.
  • The LLM reads the retrieved context and writes the answer.

RAG does not make the model know everything. It gives the model a way to look up what it needs.

How do we know if RAG actually works?

A RAG answer has two chances to fail.

The retriever may fail to find the evidence, or the LLM may receive good evidence and still produce a poor answer. If we only score the final answer, we cannot tell which part needs fixing.

Start with a small evaluation dataset. Each example should contain:

  • a realistic question
  • the evidence retrieval should find
  • an optional reference answer
  • the expected behavior when no answer exists

Then evaluate in pipeline order. Test retrieval first, verify that enough evidence reached the LLM, and only then evaluate generation.

This follows the practical eval workflow described by Hamel Husain, where evaluations should be specific to the product and useful for debugging. Jason Liu’s RAG eval framing reduces the system to three things: question, retrieved context, and answer. Looking at their relationships makes failures much easier to locate.

Interactive · RAG evaluation

Test the researcher before testing the writer

Follow the evaluation order
Exam 1 · RetrievalDid we find the right evidence?
Evidence gateIs there enough context to answer?
Exam 2 · GenerationDid the LLM use that evidence well?
Start with examplesDefine what good looks like before changing the system

Each row pairs a realistic question with the evidence retrieval should find. A reference answer is useful when the wording or exact facts matter.

QuestionExpected evidenceExpected answer

How many leave days can I carry over?

Employees may carry over five unused days.

Five days, usable by March 31.

Do remote employees get an office budget?

Remote employees receive an annual home-office allowance.

Yes, an annual allowance.

Does the policy cover pet insurance?

No supporting chunk exists.

Say the answer is not in the policy.

Use real language Sample production questions, not only clean examples.Label the evidence A human marks which chunks actually contain the answer.Include no-answer cases Test whether the system safely admits missing evidence.
A compact RAG evaluation loop: define examples, test retrieval, inspect generation with known evidence, and use the score pattern to decide what to fix.

RAG is useful, but it is not magic

The final answer can only be as good as the information that reaches the model.

If parsing loses a table, chunking separates an important sentence from its context, or retrieval chooses the wrong chunks, the LLM may still answer poorly. More retrieved chunks do not always help either. Too much irrelevant context can distract the model.

This is why real RAG systems need evaluation. We should test whether the right information was parsed, whether the retriever found it, and whether the final answer used it correctly.

But the core idea stays simple: find the right information first, then ask the LLM to answer with it.