Instead of memorizing another AI framework, let’s build Retrieval-Augmented Generation from first principles and understand what actually happens behind the scenes.♦Image created by author using AIA few months ago, I asked an AI assistant a question about a project I had been working on. The answer looked perfect. It was well-written. Confident. Detailed. There was only one problem. It was completely wrong.
The model confidently referenced functions that didn’t exist, explained behaviors my code never implemented, and even invented configuration files that had never been created.
That was the moment I truly understood something important about Large Language Models (LLMs). They are excellent at generating language, but they are not databases.
They don’t magically know what’s inside your company’s documentation, your PDFs, or your private knowledge base.
They only know what they learned during training.
This is exactly why Retrieval-Augmented Generation (RAG) has become one of the most important techniques in modern AI.
Instead of asking a model to answer from memory, RAG first retrieves relevant information and then lets the language model answer using that information as context.
That’s how tools like ChatGPT with document uploads, GitHub Copilot Chat, enterprise AI assistants, and countless customer support bots produce answers grounded in real data instead of educated guesses.
What Is Retrieval-Augmented Generation?Whenever someone first hears the term Retrieval-Augmented Generation, it sounds much more complicated than it really is.
Let’s simplify it.
Imagine you’re taking an exam. Without the textbook, you answer questions from memory. Sometimes you’ll remember correctly. Sometimes you’ll forget details. Sometimes you’ll confidently write something completely wrong.
Now imagine the teacher allows you to search the textbook before answering. Did you suddenly become smarter?
No. You simply gained access to reliable information before responding.
That’s exactly what RAG does.
Instead of asking an AI model to rely entirely on what it learned during training, we first search through relevant documents, retrieve the most useful pieces, and provide them to the model as context.
The language model doesn’t magically know more.
It simply has better information available when generating its answer.
At its core, RAG is only three steps:
- Find relevant information.
- Give that information to the language model.
- Generate an answer using the retrieved context.
Everything else embeddings, vector databases, similarity search, chunking are all simply an optimization of those three steps.
Why Can’t Large Language Models Just Remember Everything?This is one of the most common beginner questions.
If GPT is trained on the internet, why can’t it just answer everything?
Because that’s not how language models work. An LLM doesn’t store documents like a search engine.
It stores patterns. During training, the model learns statistical relationships between billions of words. It becomes incredibly good at predicting the next token.
Notice what’s missing. There’s no giant folder inside GPT called:
- Company Documents
- Financial Reports
- Python Notes
- My PDF Files
That folder simply doesn’t exist.
This creates several limitations.
1. Knowledge Becomes Outdated
Suppose OpenAI releases a brand-new API today. A model trained months ago has never seen it. Without external knowledge, it can’t explain something it has never encountered.
2. Private Information Isn’t Available
Internal documentation, engineering wiki, customer database, meeting notes…None of these were part of the model’s training.
So asking an LLM about them is like asking someone to summarize a book they’ve never read.
3. Hallucinations Happen
When the model lacks information, it doesn’t usually respond with:
“I don’t know.”
Instead, it predicts the most likely answer based on patterns. Sometimes those predictions happen to be correct. Sometimes they’re beautifully written fiction. This is called hallucination.
RAG dramatically reduces hallucinations by giving the model reliable information before it starts generating text.
The Complete RAG PipelineNow that we understand the motivation, let’s look at the entire workflow.
♦Image generated by AuthorStep 1 — Collecting DocumentsEverything begins with data. Without documents, there is nothing to retrieve. Those documents could come from almost anywhere:
- PDFs
- Word files
- Markdown documentation
- Confluence pages
- Notion
- SQL databases
- CSV files
- Websites
- Product manuals
- API documentation
- Internal wikis
For learning purposes, imagine we have a simple text file.
with open("python_notes.txt", "r") as file:
document = file.read()
print(document[:500])That’s it. Our knowledge base now exists as a string.
Of course, real systems ingest thousands or even millions of documents. But conceptually, they’re all just text waiting to be processed.
Step 2 - Why We Don’t Store Entire DocumentsSuppose your document is a 500-page programming book.
A user asks:
What is list comprehension?
Should we send all 500 pages to GPT? Absolutely not.
There are three major reasons.
Context Window
LLMs have limits. Even models with very large context windows shouldn’t receive unnecessary information.
More tokens mean higher latency and increased cost.
Irrelevant Information
If only one paragraph answers the user’s question, why include hundreds of unrelated pages?
Extra context often hurts answer quality.
Retrieval Accuracy
Searching an enormous document is much harder than searching smaller pieces. That’s why we split documents into smaller sections. This process is called chunking.
Step 3 — Chunking: The Most Underrated Part of RAGWhen people first hear about RAG, they usually focus on vector databases or embeddings.
In reality, one of the biggest contributors to retrieval quality is how you split your documents.
Imagine you have a 600-page Python book.
A user asks:
“What is a decorator?”
If your system stores the entire book as one document, the retriever has a difficult task. It must decide whether all 600 pages are relevant to a question that only needs a few paragraphs.
That’s inefficient.
Now imagine you’ve split the book into small, meaningful sections. Instead of searching one massive document, you’re searching hundreds of focused pieces. The chances of finding the right answer increase dramatically. Those smaller pieces are called chunks.
Think of chunking like cutting a pizza. It’s still the same pizza. It’s just much easier to serve the slice someone actually wants.
Why Not Make Chunks Extremely Small?
At first, this seems like a good idea.
Why not split every sentence?
For example:
Python is popular.
Functions help organize code.
Decorators modify functions.
Generators produce values lazily.
Now imagine someone asks:
Why are decorators useful?
The retriever might return only this sentence:
Decorators modify functions.
Technically correct. But not very helpful. The explanation lost all its surrounding context. Tiny chunks often remove the information needed to answer a question properly.
Why Not Make Chunks Extremely Large?
Let’s try the opposite. Suppose one chunk contains fifty pages.
Now the retrieved context includes:
- Classes
- Loops
- Functions
- Exceptions
- Decorators
- Async programming
- Networking
Only two paragraphs are actually relevant.
Everything else wastes tokens and makes it harder for the language model to focus on the important information.
Large chunks introduce noise.
Finding the Sweet Spot
Good chunking is a balance between:
- Enough context
- Minimal noise
A typical chunk might contain:
- 200–500 words
- 300–800 tokens
There’s no universal best size.
The ideal chunk size depends on:
- document type
- writing style
- retrieval model
- language model
- question complexity
One of the biggest lessons you’ll learn while building production RAG systems is that chunk size is something you experiment with, not something you memorize.
Chunk Overlap
Imagine our document says:
Decorators wrap another function.
They allow developers to add functionality without modifying the original implementation.
This makes logging and authentication much easier.
Suppose our chunk ends here:
Decorators wrap another function.
The next chunk starts here:
They allow developers...
The explanation has been split into two different chunks.
Neither chunk contains the complete idea.
This is why many RAG systems use overlap.
Instead of cutting documents like this:
Chunk 1: AAAAAAAAAA
Chunk 2: BBBBBBBBBB
We create overlapping chunks:
Chunk 1: AAAAAAAAAABBBB
Chunk 2: BBBBCCCCCCCC
Notice how part of the previous chunk appears again.
That overlap preserves context across chunk boundaries.
It slightly increases storage requirements, but retrieval quality usually improves.
Types of ChunkingNot all chunking strategies are the same.
Let’s explore the most common ones.
1. Fixed-Size Chunking
The simplest approach.
Split every 500 words.
chunks = [text[i:i+500] for i in range(0, len(text), 500)]
Advantages:
- Very simple
- Fast
- Easy to implement
Disadvantages:
- Can split ideas in half
- Ignores document structure
This is fine for learning RAG but rarely ideal in production.
2. Paragraph Chunking
Instead of cutting every fixed number of words, split by paragraphs. Paragraph 1, Paragraph 2 and so on.
Advantages:
- Preserves ideas
- Better readability
- Natural boundaries
Disadvantages:
- Paragraph sizes vary considerably.
3. Semantic Chunking
Instead of looking at characters or paragraphs, semantic chunking tries to keep related ideas together.
Imagine a document discussing:
- Python basics
- Functions
- Decorators
- Async programming
Rather than splitting every few hundred words, the algorithm identifies where topics naturally change.
This often produces significantly better retrieval quality.
The downside?
It’s computationally more expensive.
4. Recursive Chunking
This is one of the most widely used approaches today.
Instead of immediately splitting into fixed lengths, we progressively divide the document using increasingly smaller boundaries.
For example:
♦Image generated by AuthorLibraries such as LangChain use recursive splitting because it preserves as much semantic structure as possible.
Step 4 — Embeddings: Turning Meaning into NumbersNow we have chunks. But computers don’t understand text. They understand numbers.
This is where embeddings come in.
Imagine trying to describe every city on Earth using GPS coordinates.
New York might be: 40.71, -74.00
London has different coordinates.
Tokyo has different coordinates.
The numbers themselves aren’t important. What’s important is that nearby coordinates represent nearby places.
Embeddings work the same way.
Instead of mapping locations, they map meaning. Every sentence becomes a point in a high-dimensional space.
For example:
Python is easy to learn. -> [-0.42, 0.18, 0.73, … 0.91]
A completely different sentence receives another vector.
Java is widely used. -> [-0.40, 0.15, 0.70, ... 0.88]
Although the wording differs, both sentences discuss programming languages.
Their vectors tend to appear close together.
Now compare that with:
Chocolate cake recipe -> [0.91, -0.62, 0.07, ...-0.34]
This vector ends up much farther away because the meaning is unrelated.
That’s the entire purpose of embeddings. They transform language into geometry.
Similar meanings become nearby points. Different meanings become distant points.
Generating Embeddings in PythonInstead of implementing an embedding model ourselves, we use a pretrained model.
One of the most popular beginner-friendly options is Sentence Transformers.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
embedding = model.encode("Python decorators wrap functions.")
print(len(embedding))
Output:
384
The sentence is now represented by a vector of 384 numbers. Those numbers don’t have human-readable meaning. What matters is their relationship to other vectors.
Every chunk in our document collection will receive its own embedding. Likewise, every user question will also be converted into an embedding.
Once everything exists in the same vector space, we can compare them.
Why Keyword Search Isn’t EnoughTraditional search engines mostly rely on matching words.
Imagine our document contains:
“Automobiles are becoming increasingly electric.”
A user asks:
“Tell me about electric cars.”
Keyword search may struggle because the document uses automobiles, while the user asks about cars.
The wording changed. The meaning didn’t.
Embeddings solve this problem. Instead of matching words, they compare meaning.
That’s why semantic search feels so much smarter than traditional keyword search.
It understands what you mean, not just what you typed.
♦Image created by AuthorImagine your knowledge base contains 100 documents.
Finding the most relevant one is easy.
Now imagine it contains:
- 10,000 documents
- 1 million documents
- 100 million documents
Searching every embedding one by one suddenly becomes expensive.
This is exactly why vector databases exist.
Let’s build one ourselves before we rely on production tools.
Step 5 — Building a Tiny Vector DatabaseA vector database stores two things:
- The embedding
- The original text (and metadata)
For a tiny RAG application, we could represent it like this:
documents = [
{
"text": "Python decorators wrap functions.",
"embedding": embedding1
},
{
"text": "Generators produce values lazily.",
"embedding": embedding2
},
{
"text": "Context managers simplify resource management.",
"embedding": embedding3
}
]
That’s it.
You’ve just created the simplest possible vector database.
Of course, production databases such as FAISS, Pinecone, Weaviate, Qdrant, Chroma, and Milvus optimize storage and search using sophisticated indexing algorithms.
But conceptually, they all store vectors alongside the information those vectors represent.
The magic isn’t in storing vectors.
The magic is in searching them efficiently.
Step 6 — Understanding Similarity SearchSuppose our knowledge base contains three chunks.
Chunk A: Python decorators wrap functions.
Chunk B: Generators allow lazy iteration.
Chunk C: Docker containers package applications.
Now the user asks:
How do decorators work?
The question is converted into an embedding. Now we compare that embedding against every stored embedding. Whichever document is closest in meaning gets retrieved.
We are not comparing words. We’re comparing vectors.
That’s the heart of semantic search.
How Do We Measure Similarity?Imagine you’re standing in a large field.
Nearby people are easy to reach.
People farther away require more walking.
Embeddings work similarly.
Vectors that represent similar ideas appear closer together.
Vectors with unrelated meanings appear farther apart.
One of the most common ways to measure this closeness is Cosine Similarity.
You don’t need to understand the underlying mathematics to build useful RAG systems.
Just remember this rule:
Similar meanings produce similar vectors.
Computing Similarity in PythonUsing Sentence Transformers makes this surprisingly easy.
from sentence_transformers import SentenceTransformer
from sentence_transformers.util import cos_sim
model = SentenceTransformer("all-MiniLM-L6-v2")
documents = ["Python decorators wrap functions.",
"Generators produce values lazily.",
"Docker packages applications."]
doc_embeddings = model.encode(documents)
query = "Explain Python decorators"
query_embedding = model.encode(query)
scores = cos_sim(
query_embedding,
doc_embeddings
)
print(scores)
The output might look something like this:
♦Image generated by AuthorThe system never searched for the exact words.
Instead, it searched for similar meaning.
That’s a huge improvement over traditional keyword search.
Retrieving the Top K DocumentsWe usually don’t retrieve just one chunk.
Instead, we retrieve the Top K most relevant chunks.
For example: top_k = 3
The retriever returns something like this:
Chunk 15: Python decorators wrap another function...
Chunk 28: Decorators preserve function signatures...
Chunk 42: Using decorators for logging...
Now the language model has multiple pieces of evidence instead of a single paragraph.
This often produces significantly better answers.
Choosing K is another tuning parameter.
With too few documents, the model may miss useful context.
Too many, and we increase cost while introducing irrelevant information.
Step 7 — Constructing the PromptMany beginners think the retrieved documents magically become part of the model’s memory.
That’s not what happens.
The retrieved chunks are simply inserted into the prompt.
For example:
You are a helpful AI assistant.
Answer the question using ONLY the information below.
Context:
Python decorators wrap another function.
Decorators are commonly used for logging,
authentication, and caching.
Question:
What is a decorator?
Answer:
The model now has reliable information available while generating its response.
Instead of relying on memory, it reasons over the retrieved context.
This is why RAG dramatically reduces hallucinations.
Building the Entire PipelineNow let’s connect everything we’ve learned.
♦Image generated by AuthorA Minimal RAG PipelineNow let’s put everything together.
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sentence_transformers import SentenceTransformer
def load_documents(doc_list=None):
return [ "The capital of France is Paris.",
"Python is a popular programming language.",
"Generative AI models can create new content.",
"The Eiffel Tower is located in Paris.",
"Machine learning is a subset of AI." ]
def chunk_documents(documents):
#Splits documents into smaller chunks (for simplicity, we return documents as chunks).
#In real scenario, this would involve more sophisticated text splitting.
print(f"Chunking {len(documents)} documents...")
return documents
embedding_model = model = SentenceTransformer("all-MiniLM-L6-v2")
class VectorStore:
def __init__(self, chunks, embeddings):
self.chunks = chunks
self.embeddings = embeddings
self.nn_model = NearestNeighbors(n_neighbors=1, metric='cosine')
if embeddings.shape[0] > 0:
self.nn_model.fit(embeddings)
else:
print("Warning: VectorStore initialized with no embeddings. Search will not work.")
def search(self, query_embedding, top_k=3):
#Finds the top_k most similar chunks to the query embedding."""
if self.embeddings.shape[0] == 0:
return []
query_embedding_reshaped = query_embedding.reshape(1, -1) # Reshape for single query
distances, indices = self.nn_model.kneighbors(query_embedding_reshaped, n_neighbors=min(top_k, len(self.chunks)))
retrieved_chunks = [self.chunks[i] for i in indices.flatten()]
print(f"Retrieved {len(retrieved_chunks)} relevant chunks.")
return retrieved_chunks
def build_vector_store(chunks, embeddings):
return VectorStore(chunks, embeddings)
def create_prompt(query):
#context_str = "\n".join(context)
prompt = f"Question: {query}\n\nAnswer:"
print("Prompt created.")
return prompt
class MockLLM:
#A mock Language Model for demonstration purposes."""
def generate(self, prompt):
print("Generating answer with mock LLM...")
# In a real application, this would be an API call to an actual LLM
if "Paris" in prompt and "capital of France" in prompt:
return "The capital of France is Paris, where the Eiffel Tower is located."
elif "Python" in prompt:
return "Python is a popular programming language, often used with generative AI models."
elif "generative AI" in prompt:
return "Generative AI models can create new content, and machine learning is a core component of AI."
else:
return "I am a mock LLM and cannot answer that precisely"
llm = MockLLM()
print("Mock LLM initialized.")
# Load documents
documents = load_documents()
# 2. Split into chunks
chunks = chunk_documents(documents)
# 3. Generate embeddings
embeddings = embedding_model.encode(chunks)
# 4. Store vectors
vector_store = build_vector_store(chunks, embeddings)
# 5. Receive user question
query = input("Ask something: ")
# 6. Embed query
query_embedding = embedding_model.encode(query)
# 7. Retrieve relevant chunks
context = vector_store.search(query_embedding, top_k=3)
# 8. Build prompt
prompt = create_prompt(query)
print(prompt)
# 9. Generate answer
answer = llm.generate(prompt)
print(answer)
That’s RAG.
Everything else you see in modern frameworks is largely an optimization of this workflow.
Why Do We Need Vector Databases?At this point, you might wonder:
Why can’t we simply keep embeddings inside a Python list?
For a few hundred documents, you absolutely can.
But imagine storing:
- 5 million PDF pages
- 200 million customer support tickets
- 1 billion product descriptions
Searching every embedding one by one becomes painfully slow.
Vector databases solve this problem by building specialized indexes that make nearest-neighbor search incredibly fast.
Instead of checking every vector, they intelligently narrow the search space.
This allows retrieval in milliseconds, even across millions of embeddings.
That’s why production systems rely on vector databases rather than plain Python lists.
Popular Vector DatabasesOnce you understand the concepts, choosing a vector database becomes much easier.
Some popular options include:
1. FAISS
- Best for: Local development and research.
- Useful for fast similarity searches on vectors.
2. Chroma
- Best for: Beginner projects.
- Easy to use when learning and building RAG applications.
3. Qdrant
- Best for: Open-source production deployments.
- Suitable for scalable applications with vector search and filtering.
4. Weaviate
- Best for: Knowledge graphs and hybrid search.
- Combines vector search with keyword search and structured data.
5. Pinecone
- Best for: Fully managed cloud services.
- Provides hosted vector database infrastructure without managing servers.
6. Milvus
- Best for: Large-scale enterprise search.
- Designed to handle massive amounts of vector data and high-performance searches.
Notice something interesting.
These tools don’t change how RAG works.
They simply make the retrieval step faster, more scalable, and easier to manage.
That’s why learning RAG from scratch first is so valuable.
You’ll understand what these tools are doing behind the scenes instead of treating them like black boxes.
Common Beginner MistakesEmbedding Entire PDFsIf your PDF has 400 pages, don’t create one giant embedding.
Split it into meaningful chunks first.
Choosing Huge Chunk SizesLarge chunks often contain irrelevant information.
The retriever may find the right document but still return too much noise.
Ignoring Chunk OverlapWithout overlap, important ideas may be split across chunk boundaries.
This reduces retrieval quality.
Retrieving Too Many ChunksMore context isn’t always better.
Irrelevant information can distract the language model.
Sometimes fewer, more focused chunks produce better answers.
Thinking RAG Eliminates HallucinationsRAG significantly reduces hallucinations.
It does not eliminate them.
If retrieval fails, the language model still has incomplete information.
Always evaluate retrieval quality separately from generation quality.
♦Complete RAG PipelineKey TakeawaysRAG isn’t a mysterious AI architecture. It’s a carefully designed pipeline.
We start with documents.
We split them into meaningful chunks.
We convert those chunks into embeddings.
We store the embeddings for efficient retrieval.
When a user asks a question, we embed the query, retrieve the most relevant chunks, and include them in the prompt sent to the language model.
The model doesn’t magically learn new knowledge.
It simply receives the right information at the right time.
Once you understand these building blocks, every RAG framework, whether it’s LangChain, LlamaIndex, Haystack, or something else, becomes much less intimidating.
♦Build Retrieval-Augmented Generation (RAG) from Scratch: The Beginner-Friendly Guide I Wish I Had was originally published in Code Like A Girl on Medium, where people are continuing the conversation by highlighting and responding to this story.