All posts

Understanding RAG - Giving Your LLM an Open-Book Exam

October 31, 2026 · 11 min read

Introduction

Ask an LLM "What kinds of pets do I like?" and you'll get a polite version of "I don't have access to your personal memory". Fair enough - it has never met you.

Now paste one sentence into the prompt - "My favorite pet is a cat." - and ask again. The answer comes back: "you like cats".

Without context
Context
none
Question
What kinds of pets do I like?
Answer
Since I don't have access to your personal memory or past conversations, I don't know yet!
With one sentence of context
Context
My favorite pet is a cat.
Question
What kinds of pets do I like?
Answer
Based on the provided context, you like cats (specifically, a cat is your favorite pet).
Same model (Gemini), same question. The only difference is one sentence in the prompt.

That's Retrieval-Augmented Generation (RAG) in a nutshell. LLMs only know what was in their training data. Your company's docs, last week's incident report, a PDF someone sent you this morning - none of it is in there. You could fine-tune the model on it, but that's slow, expensive, and stale the moment the docs change. RAG takes the cheaper route: when a question comes in, find the relevant text and put it in the prompt. It turns a closed-book exam into an open-book one. The model doesn't have to memorise your data, it just has to read the right page.

I worked through the whole pipeline in a notebook, with real outputs at every step, in my understanding-rag repo. This post walks through the ideas. The notebook has the runnable code.

I'm learning this by following freeCodeCamp's Learn RAG From Scratch course, taught by Lance Martin from LangChain. This post covers the basics from the first part of it. My notebook follows the course's code, switched over to Gemini, with my own experiments added on top.

The stack is LangChain, Gemini for both embeddings and chat, and Chroma as the vector store, with Lilian Weng's LLM Powered Autonomous Agents post as the knowledge base.


The Pipeline

RAG has two phases. Indexing happens once, ahead of time. Retrieval and generation happen on every question:

1 · Indexingonce, ahead of time
Loadfetch the post
Split50 chunks
Embedchunk → vector
StoreChroma
2 · Retrievalevery question
Questionplain text
Embedsame model
Searchnearest vectors
Top k4 chunks
3 · Generationevery question
Promptinstructions + chunks + question
LLMGemini
Answergrounded in the chunks
Indexing does the expensive work once. Each question then costs one embedding, one search and one LLM call.

Everything interesting hinges on one step: find the most similar chunks. That needs a way to measure whether two pieces of text mean the same thing.


Embeddings: Turning Meaning into Numbers

An embedding model takes a piece of text and returns a vector - with gemini-embedding-001, a list of 3,072 numbers. On their own the numbers mean nothing. What matters is that the model is trained so texts with similar meaning land close together in that space.

"Close" is usually measured with cosine similarity, the cosine of the angle between two vectors. Close to 1 means they point the same way. Close to 0 means unrelated.

Here's the pets question scored against five candidate sentences:

about pets or animalsunrelated
My favorite pet is a cat.0.783
I'm allergic to fur, so animals aren't really my thing.0.753
I adore my golden retriever, we go to the park every day.0.709
Python is a popular programming language.0.594
The stock market closed higher today.0.543
Cosine similarity to “What kinds of pets do I like?”, on a 0 to 1 scale. Real scores from gemini-embedding-001.

Three things here surprised me:

  1. Meaning beats keywords. The golden retriever sentence shares no meaningful words with the question, and it still beats the finance and programming sentences comfortably. A keyword search would have missed it entirely.
  2. Embeddings capture topic, not stance. The allergy sentence is about not wanting pets, and it ranks second, above the golden retriever. It's still about pets. Retrieval finds text that's related; working out what that text actually says is the LLM's job.
  3. Scores are relative. The stock market sentence has nothing to do with pets and still scores 0.54. The absolute number tells you very little - the ranking and the gaps do.

One small detail: the question goes through embed_query and the documents through embed_documents. Gemini embeds them in different modes (RETRIEVAL_QUERY vs RETRIEVAL_DOCUMENT), because a question and the passage that answers it are usually worded nothing alike.

That's really the core of retrieval: embed the question, score it against every stored chunk, keep the top k. The rest is plumbing to do that over real documents.


Chunking: Why Not Embed the Whole Thing?

The agents post comes in at about 43,000 characters, or 9,411 tokens. Why not embed it as one vector?

  • Precision. One embedding for the whole post is roughly the average of everything in it - planning, memory, tool use, case studies. A question about one topic would match all of it, weakly. Small chunks each have a sharp, specific meaning.
  • Context budget. You only want the relevant parts in the prompt, not 9,000 tokens of everything.

So the post gets split with RecursiveCharacterTextSplitter into 50 chunks of up to 300 tokens, with 50 tokens of overlap between neighbours:

text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
    chunk_size=300,
    chunk_overlap=50,
)
splits = text_splitter.split_documents(blog_docs)

"Recursive" means it tries to break on paragraphs first, then lines, then words, so chunks end at natural boundaries. The overlap exists so an idea that straddles a cut still shows up whole in at least one chunk. Something I didn't expect: the overlap only appears where the splitter had to cut through the middle of a section. When a chunk ends on a clean paragraph break there's nothing to repeat, so only 12 of the 49 boundaries actually overlap:

50 chunks · width = token count
shares text with the next chunkno overlapzoomed in below
chunk 3 · end
…LLM to interact with the environment (e.g. use Wikipedia search API), while the latter prompting LLM to generate reasoning traces in natural language. The ReAct prompt template incorporates explicit steps for LLM to think, roughly formatted as:
chunk 4 · start
The ReAct prompt template incorporates explicit steps for LLM to think, roughly formatted as: Thought: ... Action: ... Observation:…
Each block is one chunk of the post, its width proportional to its token count. Chunk 3 had to be cut mid-section, so its last sentence is repeated at the start of chunk 4.

Storing and Retrieving

The chunks get embedded and stored in Chroma, a vector store - a database built to answer one question quickly: which stored vectors are closest to this one?

One gotcha that bit me: adding documents to a Chroma collection appends. Every time I re-ran the indexing cell, every chunk was stored again, and retrieval slowly filled up with duplicates. Resetting the collection first fixes it:

vectorstore = Chroma(collection_name="rag_from_scratch", embedding_function=embeddings)
vectorstore.reset_collection()  # start empty so re-running doesn't duplicate chunks
vectorstore.add_documents(splits)

retriever = vectorstore.as_retriever(search_kwargs={"k": 4})

Asking "What is Task Decomposition?" returns these four chunks:

Distance · lower is closer
#10.643relevant
Component One: Planning# A complicated task usually involves many steps. An agent needs to…
#20.686related
Illustration of how HuggingGPT works. (Image source: Shen et al. 2023) The system comprise…
#30.692related
(2) Model selection: LLM distributes the tasks to expert models, where the request is fram…
#40.707noise
10. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>" 11. Delete …
Top 4 chunks for “What is Task Decomposition?”. Chroma reports a distance rather than a similarity.

The first is exactly right - it's the section on task decomposition. The next two are about HuggingGPT, which also splits requests into tasks: related, but not what I asked. The fourth is AutoGPT's list of commands, which most likely matched on all its "task" wording.

That's the lesson: retrieval always returns k results, even when fewer than k are relevant. The model has to read past that noise, and reducing it is a big part of what the more advanced RAG techniques do.


Generation: It's Just a Prompt

The "augmented" part of RAG is less magic than it sounds. It's a prompt template with a slot for the retrieved text:

template = """Answer the question based only on the following context:
{context}

Question: {question}
"""

The words "based only on the following context" do a lot of work. They're what keep the model grounded in your document instead of whatever it memorised during training.

The retriever returns LangChain Document objects, and the first version of my notebook passed them straight into the prompt. That works, but the model ends up reading Python reprs - Document(metadata={...}, page_content='...') - which is noise and wasted tokens. A one-line helper fixes it:

def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)

With four chunks plus the question, the final prompt is 1,068 tokens, and almost all of it is retrieved context:

Prompt · 1,068 tokens
Instruction12 tokensAnswer the question based only on the following context:
Context · 4 retrieved chunks1,037 tokensComponent One: Planning# A complicated task usually involves many steps. An agent needs to know what they are and plan ahead…
Question19 tokensQuestion: According to the post, what are the three ways task decomposition can be done?
The prompt the model receives, split by token count. Counted with tiktoken's cl100k_base, so Gemini's own count will differ slightly.

It's worth printing the prompt at least once. Seeing the plain string the model actually receives takes most of the mystery out of RAG.

Asked "According to the post, what are the three ways task decomposition can be done?" with that context, the model answers:

1. By LLM with simple prompting (e.g. "Steps for XYZ.\n1.")
2. By using task-specific instructions (e.g. "Write a story outline.")
3. With human inputs

That matches the retrieved chunk almost word for word. The answer is grounded in a source you control, and you can point at exactly where it came from.


Wiring It Together

Up to here retrieval and generation are separate calls. The final step chains them, so a single question string flows through everything:

“What is Task Decomposition?”
retrievertop 4 chunks
format_docsjoin their text
{context}
RunnablePassthroughpasses it on unchanged
{question}
rag_promptfills both slots
llmGemini
StrOutputParsermessage → text
answer
The same question goes down both branches: one turns it into context, the other passes it through to fill the question slot.

In LangChain that's:

rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | rag_prompt
    | llm
    | StrOutputParser()
)

rag_chain.invoke("What is Task Decomposition?")

The dict at the start runs both branches on the same input. The question goes to the retriever to fetch context, and it's also passed through untouched to fill the question slot.

For this chain I switched to the popular rlm/rag-prompt from the LangChain Hub, which adds two useful instructions: if you don't know the answer, say so, and keep it to three sentences. The first one earns its place quickly. Ask "How do I bake sourdough bread?" and you get:

I don't know. The provided context does not contain any information
about how to bake sourdough bread.

The model knows plenty about sourdough. It declines because nothing relevant was retrieved, and for a system meant to answer from your documents, that's the behaviour you want.


A Trap When Testing RAG

My first "without retrieval" test asked the bare model about the three ways to decompose a task, from Lilian Weng's post. I expected it to fail, to prove the point. Instead it nailed the answer - the post is famous enough to be in its training data.

So if you're checking whether retrieval is actually doing the work, test with information the model can't have memorised: private docs, something recent, or something made up. A single sentence about your cat is a surprisingly good test case.


Where Basic RAG Falls Short

This pipeline works, but every step has an obvious weak spot, and the more advanced techniques each target one of them:

  • Questions are worded unlike their answers. Query rewriting, generating several versions of the query (multi-query), or embedding a hypothetical answer (HyDE) all improve recall.
  • Top-k by similarity isn't always the best k. As the AutoGPT chunk showed, re-ranking and fusing results from several searches (RAG-Fusion) help clear out the noise.
  • Chunk size is a trade-off. Too small and chunks lose their context; too big and they lose precision.
  • "It looks right" isn't evaluation. Without a test set and some metrics, you can't tell whether a change helped.

Conclusion

Strip away the frameworks and RAG is four ideas: chunk your documents, turn each chunk into a vector, find the chunks closest to the question, and paste them into the prompt. Each of those is simple on its own. The interesting work is in the details - chunk boundaries, noisy retrievals, prompts that know when to say I don't know.

The full notebook, with every step above runnable and its output included, is in Rishabh-10/understanding-rag. If you'd rather learn it from video, the Learn RAG From Scratch course I'm following is a great place to start.