Connecting Your Own Data (RAG)
How LLMs learned to look something up before answering — RAG explained.
You ask ChatGPT about your company's vacation policy. It confidently invents an answer — because it has never seen your HR handbook. RAG fixes this: instead of trusting the model's memory, it teaches the model to look things up first. That, by the way, is how the business versions of ChatGPT work when you connect them to drives like SharePoint or Google Drive: they search there and cite their sources.
In this article, you will learn how RAG works: from the core principle through data preparation to searching vector databases. You will discover why the quality of a RAG application critically depends on how documents are prepared.
The RAG Principle — Look It Up, Don't Guess
Retrieval-Augmented Generation (RAG) extends a language model with an external knowledge base. Instead of relying on knowledge baked into the model's weights during training, the system retrieves relevant documents at query time and injects them into the prompt as context. The concept was introduced by Patrick Lewis et al. in 2020. RAG mitigates three fundamental LLM problems: hallucinations, outdated knowledge, and data privacy.
RAG: When Language Models Look Things Up First
A language model only knows what was in its training data — and when in doubt, it confidently makes something up. In 2020, Patrick Lewis and colleagues at Facebook AI showed a way out: Retrieval-Augmented Generation, or RAG. The idea is compellingly simple. Before the model answers, it searches an external knowledge source — Wikipedia, say — for relevant passages and then bases its answer on what it found. This lets knowledge be updated without retraining the model, and makes the answer verifiable. After the success of ChatGPT, RAG became the standard method for tying language models to current, checkable sources — the foundation of almost every application that lets you chat with your own documents. For an honest assessment: RAG reduces hallucinations but does not eliminate them. If what it retrieves is wrong, or the model misreads it, it still errs. It provides evidence, not genuine understanding — and it builds on earlier retrieval research.
Definition
Retrieval-Augmented Generation
Analogy
Definition
In a real open-book exam, the student picks up the textbook and flips through it. In RAG, the "flipping" is automated by a retrieval algorithm that might return the wrong pages. The quality of the lookup is not guaranteed.
Note
The RAG Pipeline in Three Steps
- 1. Indexing: Split documents into chunks, encode as vectors, and store in a vector database.
- 2. Retrieval: Encode the user query as a vector and find the most similar chunks via similarity search.
- 3. Augmented Generation: Inject the retrieved chunks as context into the prompt and let the LLM generate an answer.
Hallucinations
↓
Answers are grounded in real documents instead of invented knowledge
Up-to-date
✓
Knowledge base can be updated at any time — no expensive retraining needed
Data Privacy
✓
Sensitive data stays in your own database; only the retrieved passages are sent to the model, provided you run the embedding model and database yourself
A company chatbot has 500 internal PDFs (HR handbook, compliance guidelines, product manuals). An employee asks: "How do I apply for special leave?" The system converts the question into a vector, finds the 3 most relevant sections from the current HR handbook, and injects them into the prompt. The language model generates an answer with the correct procedure. Without RAG, it would either refuse or invent a plausible but wrong procedure.
Caution
Misconception: RAG eliminates hallucinations completely
RAG markedly reduces hallucinations but does not eliminate them completely. The model can still misinterpret retrieved chunks, combine information from unrelated chunks incorrectly, or generate fluent nonsense when the retrieval step returns irrelevant results. RAG shifts the problem from "the model invents facts" to "the model might misread its reference material."
Chunking & Embeddings — Preparing the Library
Before documents can be searched semantically, they must be split into smaller pieces called chunks and transformed into embedding vectors. Chunk size determines search quality: very small chunks (around 200 tokens) are precise but lose context. Very large chunks (around 1000 tokens) preserve context but dilute search precision. Overlap (50-100 tokens) prevents information loss at cut boundaries.
Definition
Chunking
Analogy
Definition
Index card summaries are written by a human who understands the content. Embedding models compute vectors mathematically — they capture semantic similarity but not necessarily logical relationships.
High precision but context loss. A pronoun like "it" cannot be resolved if the referent appeared in the previous chunk. A warranty sentence stands isolated from the context about what counts as a "manufacturing defect."
Context preserved but search precision diluted. The warranty paragraph is mixed with unrelated content about product specifications. More irrelevant text per result.
A 50-page product manual with about 48,000 tokens is chunked with 500 tokens per chunk and 100 tokens overlap. Because of the overlap, each new chunk moves on only 400 tokens, so this produces 120 chunks. Each chunk is converted into a vector with 1536 dimensions: a matrix of 120 x 1536 numbers stored in the vector database. When searching for "warranty conditions," the query is also embedded into a 1536-dimensional vector and compared against all 120 stored vectors.
Caution
Misconception: Smallest possible chunks give the best precision
Smaller chunks increase precision but decrease recall and context. A chunk containing only "It lasts 24 months" without the surrounding context is useless — the "It" has no referent. The art of chunking is finding the size where each chunk is self-contained enough to be useful without being so large that it dilutes the search.
Fixed size: Document is cut into uniform blocks. Simple to implement but ignores content structure. A paragraph can be split mid-sentence.
Paragraph-based: Natural paragraph boundaries are respected. Preserves topical coherence but produces chunks of varying sizes.
Semantic: An embedding model detects topic changes in the text and sets boundaries there. Can improve quality, but is computationally expensive and more complex to implement.
Vector Databases — The AI's Memory
A vector database is a specialized storage system for embedding vectors. Unlike traditional relational databases that match exact values (SQL: WHERE name = 'Max'), vector databases search by mathematical similarity — they find the stored vectors closest to a query vector in high-dimensional space.
Definition
Vector Database
Analogy
Definition
A real recommendation system uses collaborative filtering (what did similar users like?). A vector database relies purely on mathematical vector proximity — it captures semantic similarity but not user preferences.
Exact match required. LIKE '%return conditions%' finds nothing when the document says "refund policy." Fast for structured data but blind to synonyms and natural language.
Finds results by meaning. "Return conditions" and "refund policy" have similar embedding vectors despite different words. Enables natural-language queries.
A user types: "What are the return conditions?" The embedding model converts this question into a 1536-dimensional vector. The vector database finds the 5 closest stored vectors via cosine similarity. These come from the "Refund Policy" section — even though the user wrote "return conditions" and the manual says "refund policy." In contrast: an SQL query with LIKE '%return conditions%' would find nothing because the manual uses different words. In practice, many RAG systems combine both (hybrid search): vector search finds paraphrases, keyword search finds exact matches such as part numbers or names, which embeddings tend to miss.
Caution
Misconception: A vector database is just a regular database with an extra column
The search mechanism is fundamentally different. Relational databases use B-trees and hash indexes for exact matching. Vector databases use specialized data structures (HNSW graphs, IVF indexes) optimized for high-dimensional nearest-neighbor search. pgvector brings such indexes (HNSW, IVFFlat) to PostgreSQL as well, but dedicated vector databases like Pinecone or Weaviate include optimizations (such as distributed sharding across many servers) designed specifically for vector workloads at scale.
Try it: retrieval in vector space
RAG doesn't match keywords — it matches meaning. Below, a small knowledge base of three documents lives as points in a 2D vector space. Pick a question and watch cosine similarity pull out the nearest chunks. Then grow the chunk size and see why bigger chunks can still retrieve the right document but a worse-fitting passage.
Interactive: The RAG Flow Step by Step
Follow the complete data flow of a RAG query: from document through chunking and embedding into the vector database, then back through retrieval to the LLM, which generates the final answer.
RAG significantly reduces hallucinations but does not eliminate them completely. The model can misinterpret retrieved information or incorrectly combine chunks from different contexts.
Garbage in, garbage out applies to RAG too: if the knowledge base is poorly structured, outdated, or contains errors, RAG also produces wrong answers — just with source references.
RAG and fine-tuning solve different problems. RAG adds external knowledge (ideal for current facts, company data). Fine-tuning changes the model's behavior (ideal for style, tone, domain-specific language). For best results, both approaches are often combined. And sometimes I don't need RAG at all: many current models hold a million tokens in their context window, roughly 2,000 book pages. A single manual then fits into the prompt in full. RAG pays off when the knowledge base is larger, changes often, or every request should stay cheap and fast, because long prompts cost more, and in a lot of context models overlook details more easily.
Note
Key Takeaways
- RAG teaches a language model to look up information before answering — easing problems with hallucinations, staleness, and privacy without retraining the model.
- The quality of retrieval depends on chunking: chunks too small lose context, chunks too large dilute relevance. Overlap prevents information loss at cut boundaries.
- Vector databases search by meaning, not by keywords — this is why a natural-language question can find the right document, even when the exact words differ.
Check
Quiz: RAG
What is the main purpose of the "Retrieval" step in a RAG pipeline?
Select one answer
1. What is the main purpose of the "Retrieval" step in a RAG pipeline?
2. You build a RAG system for a medical knowledge base. Doctors report that answers sometimes miss important dosage details that appear in the sentence right before a chunk boundary. What is the most effective fix?
3. A customer asks your RAG chatbot: "Can I return shoes after 30 days?" The knowledge base document says: "Footwear refund requests must be submitted within four weeks of purchase." A keyword search for "return shoes 30 days" finds nothing. Why does the vector search succeed?
4. A startup uses RAG with the OpenAI API to answer questions about their 200-page product manual. The chatbot sometimes gives wrong answers with high confidence. What is the most likely explanation?
Check
Comprehension Check
Can you explain this in your own words? Tick what you've got.
0 of 3 done