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".
- 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!
- 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).
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:
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:
Three things here surprised me:
- 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.
- 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.
- 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:
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:
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:
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:
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.