You ask a chatbot something about your own company: “How many vacation days can I carry over to next year?” It answers confidently, and the answer is wrong, because it has never seen your HR handbook. So how do companies build assistants that answer from their documents, and point to the page they used?
The usual answer is a technique called RAG. In plain words: before the AI writes its reply, a piece of software looks up the relevant passages in your own documents and hands them over, so the answer comes from your text and can point to where it came from. This post explains how that works, from zero: it is for anyone who has used a chatbot and wants to know how such assistants are built. No prior knowledge of AI needed.
First, the words
These are the only terms you need to follow this post. Each one is explained again where it first appears.
- Language model (LLM, large language model) — a program trained on vast amounts of text that writes text in reply to text; the engine behind chat assistants.
- Prompt — everything you send to the model in one go: rules, background material and the question.
- Hallucination — a fluent, confident answer that is not true.
- Retrieval — the step that finds the few passages in your documents that are relevant to a question.
- Chunk — a small passage, a few paragraphs long, cut from a larger document so it can be searched and quoted.
- Embedding — a list of numbers that represents the meaning of a text, so that similar meanings get similar numbers.
- Vector database — a database that stores embeddings and quickly finds the ones closest to a new one.
- Context window — the maximum amount of text a model can take in at once.
The short answer
RAG (Retrieval-Augmented Generation): retrieval means finding, augmented means added to, generation means writing the answer. Put together: before the language model (the AI that writes the reply) answers, your software first finds the relevant pieces of your documents and puts them into the model’s input. The model then writes its answer from that text instead of from memory.
The analogy I’ll use throughout: an open-book exam. A large language model (LLM, the kind of AI behind chat assistants) is a bright student who has read a huge amount of public material but has never seen your company’s handbook. A closed-book exam forces the student to guess. In an open-book exam, the student looks up the right page first and then writes the answer in their own words. RAG is the machinery that hands the student the right pages.
Why it exists
An LLM on its own has three limits that matter the moment you ask about your own business.
It has a training cutoff. A model learns during training: it is shown a huge snapshot of text collected up to a certain date and adjusts itself to the patterns in that text. Anything that changed afterwards, including last month’s policy update, does not exist for it.
It has never seen your private data. Your HR handbook, contracts, support tickets (requests logged in a help-desk system) and internal wiki (the company’s own editable pages of knowledge) were not on the public internet, so they were never part of that snapshot.
It can hallucinate. An LLM produces text that sounds right. When it lacks a fact, it often does not say “I don’t know”. It writes a plausible sentence anyway. “Most companies allow ten days of carry-over” reads fine and may be completely false for your company.
There is a fourth, quieter problem: no sources. Even when the model is right, you cannot check where the answer came from.
These are old observations. The 2020 paper that introduced the term, Lewis et al., “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks” (NLP stands for natural language processing, the part of computing that deals with human language), describes exactly this: knowledge stored inside a model is hard to update and hard to trace, so the authors paired the model with an external, searchable memory. Change the memory and the answers change, with no retraining (no need to train the model again).
How it works, step by step
RAG has two phases. Indexing happens ahead of time: you prepare the book so pages can be found quickly. Answering happens every time someone asks a question.
Our running example: a company support assistant, and an employee asking “How many vacation days do I have left to carry over?” The rule lives in the HR handbook; the question is worded around the employee’s own balance on purpose, and step 10 shows why that matters. (The numbers and section names below are made up for illustration.)
Phase 1: Indexing
Step 1. Collect the sources
First you decide what the assistant is allowed to know: the HR handbook PDF, the internal wiki, maybe policy announcements.
Why it matters: the assistant can only ever be as good as this pile. If an outdated version of the handbook sits next to the current one, the assistant may quote the wrong one.
Step 2. Clean
Raw documents are messy. A PDF page contains headers, footers, page numbers and tables that turn into scrambled lines when extracted. Cleaning means turning each document into plain, readable text, and keeping useful labels alongside it: title, section, date, who may see it. These labels are called metadata.
Skip this and you index garbage. “Page 14 of 62 — Confidential — Page 14 of 62” becomes a searchable passage that crowds out real content.
Step 3. Chunk
A handbook is too long to hand over whole for every question, and most of it is irrelevant to any single question. So you cut each document into small passages called chunks: a few paragraphs each.
For example, section 4 of our handbook becomes:
- Chunk 11 (§4.1): “Full-time employees receive 25 vacation days per calendar year…”
- Chunk 12 (§4.2): “Up to 5 unused vacation days may be carried over. Carried-over days must be used by 31 March…”
- Chunk 13 (§4.3): “Leave requests are submitted through the HR portal…”
In exam terms, this is cutting the book into index cards so the student can pull out three cards instead of carrying the whole book to the desk.
Step 4. Embed
Now we need a way to find chunks by meaning, not only by matching words. The employee says “carry over”; the handbook might say “transfer unused leave to the following year”.
An embedding model solves this. It reads a piece of text and outputs a long list of numbers, called an embedding or vector, that works like coordinates on a map of meaning. Texts about similar things land close together on that map, even if they share no words.
Every chunk goes through the embedding model once. Chunk 12 becomes something like [0.12, -0.48, 0.90, …], hundreds or thousands of numbers long. For the full story, see Embeddings and vector databases explained.
Step 5. Store and index
The vectors, the original chunk text and the metadata are saved in a vector database: a database built to answer one question very fast: “which stored vectors are closest to this one?” It builds an internal structure (an index) so it does not have to compare against every chunk one by one.
Phase 2: Answering
Step 6. The user asks
“How many vacation days do I have left to carry over?”
Step 7. Embed the question
The question goes through the same embedding model as the chunks. It must be the same one: different models draw different maps, and coordinates from one map mean nothing on another.
Step 8. Retrieve
The vector database returns the chunks whose vectors are closest to the question’s vector. You ask for a fixed number of them, called top-k. With k = 3 we might get (scores are example numbers; higher means closer in meaning):
| Rank | Chunk | Score |
|---|---|---|
| 1 | Chunk 12, §4.2 Carry-over rule | 0.82 |
| 2 | Chunk 11, §4.1 Annual allowance | 0.74 |
| 3 | Chunk 13, §4.3 How to request leave | 0.61 |
This is the student flipping to the right pages. It is also the step that decides a large part of the final quality: if the right chunk is not retrieved, the model never sees it.
Step 9. Assemble the prompt
Your software now builds the text the model will actually read, called the prompt. It has three parts:
Rules: Answer only from the context below. If the answer
is not there, say you don't know. Cite the section.
Context: [§4.2] Up to 5 unused vacation days may be carried over.
Carried-over days must be used by 31 March…
[§4.1] Full-time employees receive 25 vacation days…
[§4.3] Leave requests are submitted through the HR portal…
Question: How many vacation days do I have left to carry over?
The rules matter as much as the context. Without “say you don’t know”, the model falls back to guessing when retrieval comes up empty.
Step 10. Generate a grounded answer with citations
The model reads the prompt and writes:
You can carry over up to 5 unused vacation days, and they must be used by 31 March of the following year (HR Handbook, §4.2).
An answer built from supplied text is called grounded. The citation is possible because your software knows exactly which chunks it handed over, so it can show links to them.
Notice one honest gap. The employee asked how many days they have left. The handbook holds the rule, not this person’s balance; that number sits in the HR system. The answer above gives the rule and stops there. A good assistant would also say that it cannot see the personal balance, or would fetch it through a separate connection to that system. RAG over documents answers “what is the policy”, not “what is my record”.
Chunk size and overlap
How big should a chunk be? There is a real trade-off.
- Too small (a sentence or two): each chunk is precise, but it loses its surroundings. “They must be used by 31 March”: what must? The chunk no longer says.
- Too large (several pages): the answer is in there somewhere, but so is everything else. The embedding becomes a blurry average of many topics, so it matches nothing well, and you pay to send the model text it does not need.
Overlap softens the cut. Each chunk repeats a little of the end of the previous one, so a rule split across a boundary still appears whole in at least one chunk. More overlap means safer boundaries but more duplicated storage and near-identical results.
There is no universal right number. As one starting point, Microsoft’s Azure AI Search documentation suggests beginning with chunks of about 512 tokens (a token is roughly a short word or word piece) and 25% overlap, then adjusting for your content. Better still is to cut along the document’s own structure, by headings and paragraphs, so a chunk is a complete thought.
Keyword, semantic, hybrid search, and reranking
Step 8 used search by meaning. It is not the only kind, and often not enough alone: sometimes it misses the right chunk. Here are the standard ways to make it miss less.
- Keyword search finds chunks containing the exact words of the question. It is the classic search engine approach (a common scoring method is called BM25: it ranks a chunk higher when it contains the question’s words, especially the rarer ones). It is excellent for exact things: a form number like “HR-204”, a product code, a person’s name. It fails when the wording differs: “carry over” versus “transfer unused leave”.
- Semantic search (also called vector search) compares embeddings, as described above. It handles different wording well, but can miss exact codes and rare terms, which all look alike on the map of meaning.
- Hybrid search runs both and merges the two result lists into one. You get exact matches and matches by meaning. It is a sensible default for company documents, which are full of codes and names.
- Reranking is a second, more careful pass. The first search is fast and rough, so you let it return a larger batch of candidates. A separate reranker model then reads the question together with each candidate and scores how well it really answers it. Only the best few go into the prompt.
Anthropic’s engineering write-up Introducing Contextual Retrieval (its main idea is to add a short note about the surrounding document to each chunk before indexing it) reports that, in their tests, combining embeddings with BM25 and adding a reranking step each reduced the share of failed retrievals further.
RAG vs fine-tuning vs a long context window
RAG is not the only way to give a model knowledge. Two alternatives come up constantly. Fine-tuning means training an existing model further on your own examples so its behaviour changes. A long context window means simply pasting all your documents into the prompt, since modern models can read a lot of text at once (the context window is the maximum amount a model can read in one go).
| RAG | Fine-tuning | Just a long context window | |
|---|---|---|---|
| Exam analogy | Open book, look up the right pages | Study for weeks before the exam | Bring the whole book to the desk and read all of it each time |
| Best for | Large or changing knowledge; answers that need sources | Changing how the model writes or behaves: tone, format, a narrow task | A small, stable set of documents |
| Updating knowledge | Update the index; takes effect at once | Retrain the model | Change the pasted text |
| Citations | Natural: you know which chunks were used | Not available: knowledge is blended into the model | Possible, but the model must point to the place itself |
| Access control per user | Yes, filter at retrieval | No, the model knows what it knows | Only by choosing what to paste |
| Cost per question | Low: only a few chunks are sent | Low at question time, high up front | Grows with the size of everything you paste |
| Main risk | Wrong or missing chunks retrieved | Outdated facts, still hallucinates | Slow, expensive, exceeds the limit as documents grow |
They combine well: RAG for facts, prompting or fine-tuning for style.
Typical failure modes
When a RAG system gives a bad answer, the cause is usually one of these.
- The right chunk was never retrieved. Wording mismatch, a bad chunk boundary, or k too small.
- The right chunk was retrieved but buried under loosely related ones, and the model picked up a neighbour.
- The chunk lost its context. “The limit is 5 days”: for which country, which contract? The heading that said so was cut off.
- Stale or duplicate content. The old policy is still indexed next to the new one.
- The question needs several lookups. “Compare our carry-over rule in Germany and Poland” is two searches, not one.
- The answer is not in the documents at all, like the personal balance in our example, and the model guessed instead of saying so.
Common mistakes and misconceptions
- “RAG trains the model on our data.” It does not. The model is unchanged. Your documents are only shown to it at question time, like pages handed over in the exam.
- “RAG eliminates hallucinations.” It reduces them, and makes them checkable through citations. A model can still misread a chunk or fill a gap.
- “A better model will fix it.” If the right page never reaches the student, a smarter student does not help. Fix retrieval first.
- “RAG means a vector database.” Retrieval is the idea; vector search is one way to do it. Keyword search, a SQL query (a question written in the language databases understand) or a call to another system can all be the “R”.
- “We’ll evaluate it by trying a few questions.” Without a fixed test set you cannot tell an improvement from a regression (something that worked before and broke after a change).
When you don’t need it
RAG adds moving parts: more pieces that have to be built, kept up to date and can break. Sometimes they are not worth it:
- Your knowledge is small. If everything fits comfortably in the model’s context window, paste it in. Anthropic’s write-up mentioned above (September 2024) makes this point directly: for a knowledge base under roughly 200,000 tokens (about 500 pages, by their estimate), putting the whole thing in the prompt can be the simpler choice. That figure dates from 2024, so treat it as a rough guide, not a fixed threshold.
- The answer is a number in a database. “How many days do I have left?” is a lookup in the HR system, not a document search. Give the assistant a tool (a function in your program that the AI is allowed to ask to run) that queries that system (see AI agents and tool calling explained from zero). MCP (Model Context Protocol, an open standard for connecting tools and data to AI apps) is one standard way to connect such tools.
- The question is general knowledge. “What is a carry-over policy?” needs no private documents.
- Ordinary search would do. If people just need to find the document, a search box may serve them better than a generated paragraph.
For the broader version of this question, see when not to use AI tools.
What production adds on top
If this is your first time reading about RAG, you can skip this section: it is for developers who will run such a system for real, and nothing later in the post depends on it.
The ten steps above fit in a small prototype (a first, small working version). A system a whole company relies on in production (the live system that real people use every day, as opposed to a test copy) needs more.
Continuous ingestion. Ingestion means taking documents into the index. Documents change every day. Re-processing everything every night is slow and leaves answers a day stale, so many production systems listen for changes instead. For files and wiki pages that can be a change notification from the system that stores them, or a regular scan for recently modified documents. When the source is a database (a program that stores records in tables, one row per record), a common technique is change data capture (CDC): a tool watches the database and emits an event (a short message saying what changed) for every row that is added, changed or deleted, in order. Your indexing code reacts to each event: a librarian who gets a note the moment a page is rewritten, instead of re-reading the whole library every week.
Re-indexing on updates and deletes. When §4.2 changes from 5 days to 3, the old chunks must be removed and new ones created and embedded. Otherwise both versions sit in the database and the assistant may quote either. A withdrawn policy must disappear from answers too.
Access permissions. Not everyone may read everything. Salary files must never surface in an answer to someone who could not open the original. The standard approach is to store who-may-see-it as metadata on every chunk and filter the search by the asking user’s rights before anything reaches the model. Asking the model to “not reveal confidential things” is not a security control.
Orchestration. Collect, clean, chunk, embed, store is a chain of jobs. An orchestrator (a program that runs other jobs) runs them in order, retries failures and prevents half-finished updates.
Monitoring and evaluation. Keep a test set of real questions with known correct answers and source passages, and measure two things separately: did retrieval find the right chunks, and did the answer stick to them. Open-source tools (free tools whose code is public) such as Ragas name these measurements: context recall (was the needed information retrieved?) and faithfulness (is every claim in the answer supported by the retrieved text?). More in our post on evals, the repeatable tests that score an AI system’s answers.
How to get there
This section is for readers who want to build a RAG system themselves. If you only wanted to understand the idea, you can skip it.
A learning order I’d recommend to a beginner:
- Basic Python and calling an LLM through an API. Python is a programming language and the common default here; if you already know C#, Java or Go, you can do all of this in it; an API (application programming interface) is the defined way your program sends text to the model provider and gets the reply back. Paste a paragraph of your own text into the prompt and ask about it. You have just done the “AG” (augmented generation) part of RAG by hand.
- Prompt writing. Practise the rules block: answer only from context, admit when you don’t know, cite the section.
- Embeddings. Embed twenty sentences, compare a question against them, print the closest three.
- A tiny end-to-end RAG. Take one long document you know well. Chunk it, embed it, keep the vectors in a simple local store (for example, a file on your own computer), answer with citations. Skip frameworks (ready-made libraries that do all these steps for you) at first; they make more sense once you know what they hide.
- Break it and measure it. Write roughly 20–50 questions with expected answers and source sections (an example size, not a rule). Change chunk size, overlap and k, and watch which failure mode appears.
- Improve retrieval, then think about production (the live system real users rely on). Add keyword search and a reranker and check against your test set. Then re-index only what changed, and filter by a “who may see this” label.
Practice projects, in order: a “chat with one PDF” script; a bot over a folder of notes with clickable sources; the same bot with a test set and a before/after report for one retrieval change.
Mini glossary
- LLM (large language model): an AI model that reads and writes text, the engine behind chat assistants.
- Hallucination: a fluent, confident answer that is not true.
- Chunk: a small passage cut from a larger document.
- Embedding (vector): a list of numbers that represents the meaning of a text.
- Vector database: a database that quickly finds the stored vectors closest to a given one.
- Top-k: how many of the best-matching chunks you retrieve.
- Prompt: the full text sent to the model: rules, context and question.
- Grounded answer: an answer based on supplied source text rather than the model’s memory.
- Hybrid search: keyword search and semantic search combined.
- Reranker: a model that re-scores retrieved candidates more carefully and keeps the best.
Going deeper
Courses: Building LLM-Powered Apps: RAG & Agents builds this pipeline (the whole chain of steps above) end to end. Building with Claude API covers calling a model from code, Prompt Engineering & AI Workflow Automation the skills behind step 9, AWS Bedrock & AI Services for Developers models and document search run for you by a cloud provider, and Building MCP Servers & AI Tool Integrations connecting an assistant to live systems such as an HR database.
Related posts: Embeddings and vector databases explained, The layers of an AI system, Context engineering, Evals and Token economics.
Sources and further reading
- Lewis et al., “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks” (2020)
- Anthropic: Introducing Contextual Retrieval
- Microsoft Learn: Chunk documents for vector search
- Microsoft Learn: Hybrid search overview
- Ragas: available metrics
- Debezium documentation
This post is part of the “AI engineering from zero” series: The AI engineer roadmap · Vibe coder vs AI engineer vs AI solutions engineer · 8 types of AI models · Embeddings and vector databases · AI agents and tool calling · The 7 layers of an AI system.
Part 5 of 7 in “AI engineering from zero”. Previous: Embeddings and Vector Databases Explained from Zero · Next: AI Agents and Tool Calling Explained from Zero