What is RAG? Retrieval-augmented generation, embeddings and vector databases explained
RAG (retrieval-augmented generation) is a way to make a large language model answer from your own documents. Before the model answers, a search step finds the passages that matter, they are added to the prompt, and the model writes its answer from them, with citations. It fixes three gaps of LLMs: the knowledge cutoff, private data the model never saw, and hallucinated answers. A RAG system has two pipelines: indexing (load, chunk, embed, store) and querying (embed the question, retrieve the top k chunks, augment the prompt, generate).
Video · What Is RAG? Retrieval-Augmented Generation, Embeddings and Vector Databases Explained · 18:47
What is RAG? The short answer
Prefer to watch? The 18-minute video covers the same ground with diagrams for every concept. In a hurry? The one-minute Short: What is RAG?.
A customer asks a shop's chatbot: "Can I return my sofa after 40 days?" The chatbot answers at once, friendly and sure of itself: "Of course, you have 90 days." The real policy says 30. The model was not lying. It had simply never read that shop's policy.
Retrieval-augmented generation (RAG) is how we fix that. Before the model answers, we search our own documents and hand it the passages that matter. Retrieval finds the passages, augmented means they are added to the prompt, and generation is the model writing the answer from them.
Think of it as turning a closed-book exam into an open-book exam. The model does not need to remember the returns policy; it just needs to read it. The name comes from a 2020 paper by Patrick Lewis and colleagues, which paired a language model with a searchable vector index of Wikipedia and found its answers more specific and more factual.
Throughout this guide we use one running example: Oakline, a made-up furniture shop, and its support assistant. Oakline has a help center with a few hundred articles, a returns policy, a warranty document and a table of delivery rules, and the policies change a few times a year.
Why LLMs need RAG: knowledge cutoff, private data and hallucination
A large language model (LLM) learns from a huge amount of public text. Then training stops, and what it knows is frozen at that point, the knowledge cutoff. That leaves three gaps:
- The knowledge cutoff. It knows nothing that happened after training.
- Private data. It has never seen your internal policies, tickets or orders.
- Hallucination. When it does not know, it often produces something plausible instead of saying so.
The third gap comes from how an LLM writes: one piece at a time, each time picking a likely next word. That makes it very good at sounding right, which is not the same as being right. "90 days" sounds like a normal return policy, so that is what it said. We explain the causes and the other fixes in our guide to LLM hallucination.
How RAG works: the two pipelines
A RAG system is really two pipelines.
| Pipeline | When it runs | Steps |
|---|---|---|
| Indexing | ahead of time, and again when documents change | load → chunk → embed → store |
| Query | every time someone asks a question | embed the question → retrieve the top k chunks → augment the prompt → generate with citations |
The indexing pipeline prepares your documents so they can be searched by meaning. The query pipeline uses that index to find the right passages for one question and turns them into an answer.
The indexing pipeline: load, chunk, embed, store
Load. Pull the text out of every source: web pages, PDF files, tables. Keep useful details with it, such as the title, the link, the version and the date it was updated. That extra information is called metadata, and it becomes important later.
Chunk. Cut each document into smaller pieces called chunks, often a few hundred words each. Why not keep whole documents? Because the model will only see a handful of passages. Small, focused chunks let you hand it exactly the part that answers the question.
Embed. Turn each chunk into an embedding (more on this below).
Store. Save each chunk's embedding, its text and its metadata in a database that can search by similarity.
Embeddings and similarity, explained without math
An embedding is a long list of numbers, often hundreds or thousands of them, that captures what a piece of text means. A model called an embedding model produces it.
You do not need the math. Picture a huge map where every chunk is a point. Texts with similar meanings land close together; texts about different things land far apart. On Oakline's map, everything about returns and refunds sits in one neighbourhood, delivery questions in another, warranty in a third.
Here is why that matters. A customer types "Can I send the couch back?" The policy never says "send back" or "couch"; it says "returns" and "sofa". A plain keyword search could miss it. But the embedding of the question lands right next to the returns chunks, because the meaning is the same.
So similarity just means closeness on that map. Tools often measure it with the angle between two arrows, called cosine similarity, but the picture is all you need. Two rules come with embeddings:
- Use the same model on both sides. Questions and chunks must be embedded by the same model. Each model draws its own map, and points from two maps cannot be compared.
- A new embedding model means re-embedding everything. Plan for it from day one.
Vector databases and approximate nearest neighbour search
A vector is that list of numbers. A vector database stores vectors and quickly finds the ones closest to a new vector. Each record keeps the vector, the chunk's text and its metadata:
| id | vector | text | metadata |
|---|---|---|---|
| c-0412 | 0.12, −0.48, 0.07 … | Furniture can be returned within 30 days of delivery. | returns, v3, 2026-09 |
| c-0415 | 0.09, −0.51, 0.11 … | Oakline Plus members get 60 days. | returns, v3, 2026-09 |
| c-1188 | −0.33, 0.20, 0.64 … | We deliver Monday to Saturday. | delivery, v5, 2026-06 |
Metadata lets you filter, for example to search only the current version of a policy. You can use a dedicated vector database, or add vector search to a database you already run; the pgvector extension, for example, adds it to Postgres.
How does it find the closest vectors? The simple way compares the question with every vector: exact nearest neighbour search. It has perfect recall, and with a few thousand chunks it is fine. With hundreds of millions it is far too slow.
So most systems use approximate nearest neighbour (ANN) search. It checks only a small, well chosen part of the collection and still finds almost all of the true best matches. The small loss is measured as recall, the share of the true nearest neighbours the search returns. You trade a little recall for a lot of speed, and you can usually tune that trade.
A popular ANN method is HNSW (hierarchical navigable small world), from a paper by Yury Malkov and Dmitry Yashunin. It links each vector to its near neighbours in a graph with layers: the top layer holds only a few points with long links, the bottom layer holds every point. A search starts at the top, jumps far quickly, then drops down a layer at a time, like driving on highways first, then main roads, then local streets.
The query pipeline: retrieve, augment, generate with citations
When a customer asks a question, four things happen:
- Embed the question with the same embedding model.
- Retrieve the top k chunks: the k closest matches, often a small number such as five.
- Augment the prompt with those chunks.
- Generate the answer, with citations.
The augmented prompt has three parts. First, instructions: answer only from the sources below, cite them, and if they do not contain the answer, say you do not know. Then the retrieved chunks, each numbered with its source. Then the customer's question. The permission to say "I don't know" matters: it gives the model a safe way out instead of a guess.
For Oakline, the answer becomes: "On a standard order, no. Furniture can be returned within 30 days [1]. Oakline Plus members get 60 days [2], so if you're a member, yes." Citations let the customer check the source, and when an answer is wrong, they show you which chunk misled the model.
If you are wondering how much text fits in that prompt, our guide to the LLM context window explains the limits.
Chunking strategies for RAG
Chunk size is a trade-off. Chunks that are too big mix several topics: their embedding becomes a blurry average and they waste space in the prompt. Chunks that are too small lose their context: a chunk that only says "Members get 60 days" does not say 60 days for what. Many teams add a small overlap between neighbouring chunks, so a sentence cut at a boundary still appears whole in one of them.
| Chunking option | How it cuts | Watch out |
|---|---|---|
| Fixed size | every few hundred words, with overlap | can cut an idea in half |
| By structure | headings, sections, list items | sections vary in size |
| Semantic | where the topic changes, by comparing neighbouring sentences | more work to compute |
| Small to find, big to read | search small chunks, send the section around each match | two sizes to keep |
For a help center, structure-based chunking is often the best place to start.
Another fix for chunks that lose their context is what Anthropic calls contextual retrieval. Before a chunk is embedded, a language model writes a short line saying where it sits ("From Oakline's returns policy, the section on time limits for Oakline Plus members"), and that line is stored with the chunk. In Anthropic's tests this cut failed retrievals by 35%, and by 49% when combined with contextual keyword search.
Hybrid search and re-ranking
Vector search is great with meaning, but it has a weak spot: exact terms. A customer writes "drawer stuck on the KX-220". To an embedding, a product code is a vague string, and the search may return general drawer advice for the wrong product.
Keyword search handles this well. The classic method is BM25: it scores a chunk by the words it shares with the question, rare words count more than common ones, and repeating a word helps less and less.
Hybrid search runs both searches at once, keywords for exact terms and vectors for meaning, then merges the two ranked lists into one. A common way to merge them is reciprocal rank fusion: a chunk that ranks high in either list, or in both, rises to the top.
Re-ranking is the last upgrade. The first search is fast but rough, because it compares question and chunk only through embeddings made separately. A re-ranker is a slower, more careful model that reads the question and each candidate chunk together and scores how well that chunk answers it. So you search wide (Anthropic's setup retrieved 150 candidates), then re-rank and keep only the best (the top 20). In their tests, adding re-ranking brought the cut in failed retrievals to 67%.
How to evaluate a RAG system
Test the two halves separately, starting from a test set: real questions, each with the right answer and the chunks that contain it.
| Half | Question it answers | Measures |
|---|---|---|
| Retrieval | Did we find the right chunks? | context recall (was everything needed retrieved?), context precision (are the useful chunks ranked first?) |
| Generation | Did the answer use them well? | faithfulness (is every claim backed by the sources?), answer relevance (does it answer the question?) |
Faithfulness is the key generation measure. Split the answer into its claims and check each one against the retrieved chunks; faithfulness is the share of claims the sources support. If the answer adds "return pickup is free" and no source mentions pickup, that claim is unsupported. Frameworks such as RAGAS compute these scores, often with another LLM as the judge, so check a sample by hand too.
Always look at retrieval first. If the right chunk was never found, no model can write a faithful, correct answer. The same habits as in software testing apply: every bug you find becomes a new question in the test set.
Common RAG failures and how to fix them
| Failure | Fix |
|---|---|
| The right chunk is never retrieved | hybrid search, better chunking, re-ranking |
| Old and new policy both retrieved | store version and date, filter on them, delete replaced documents |
| Tables and PDFs come out scrambled | better loading and parsing; look at what the chunks really contain |
| Too many chunks, the key one buried in the middle | re-rank and send fewer, better chunks |
| The model answers from memory anyway | strict instructions, required citations, faithfulness checks; validate the output in code |
RAG vs fine-tuning vs long context
RAG is not the only way to give a model knowledge.
| Approach | What it changes | Best for | Watch out |
|---|---|---|---|
| RAG | what the model reads, per question | large, changing or private knowledge; citations | retrieval quality is everything |
| Fine-tuning | the model's weights | a style, a format, a narrow task | facts go stale; answers cannot cite a source |
| Long context | the prompt holds everything | small, stable knowledge | cost per question; facts lost in the middle |
Fine-tuning trains the model further on your own examples. It is a poor way to keep facts current: every policy change means training again. Long context skips retrieval and puts all the documents in the prompt. For a small knowledge base that can work well; Anthropic suggests that under about 200,000 tokens (roughly 500 pages) you try exactly that first, with prompt caching to cut cost and latency.
Long prompts have a catch. The 2023 study "Lost in the Middle" (Liu et al.) found that models use information best near the start or the end of a long input, and less reliably in the middle, even models built for long contexts. And every question pays to process the whole prompt. RAG shines when knowledge is large, changes often or needs citations, and the approaches combine: a fine-tuned model can still use RAG.
What is agentic RAG?
In classic RAG, retrieval happens once, before the model answers, and whatever it finds is all the model gets. In agentic RAG, search becomes a tool the model can call as many times as it needs. It decides what to search for, reads the results, and decides whether it has enough; if not, it searches again with new words.
Say a customer asks about returning a sofa and its matching armchair. The agent searches the returns policy, sees that armchairs come from a partner brand, and searches again for that brand's rules before answering. It is more flexible, but slower and harder to test, so use it when questions really need several steps. Our guide to AI agent architecture explains the loop behind it, and MCP is one standard way to expose a search tool to a model.
Oakline's assistant, end to end
- Help center articles and policies are loaded with their version and date.
- They are chunked by heading, and each chunk gets a short context line.
- Each chunk gets an embedding and goes into a keyword index too.
- A question runs hybrid search, then a re-ranker keeps the best few.
- The model answers only from those chunks, with citations.
- A test set of real questions checks retrieval and faithfulness after every change.
A model can only be as good as what it is given. RAG is how you give it the right page at the right moment. More guides like this one are in the article library.
Sources: Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks · Anthropic, Introducing Contextual Retrieval · Malkov and Yashunin, HNSW · pgvector · Robertson and Zaragoza, BM25 and Beyond · Cormack et al., Reciprocal Rank Fusion · Sentence Transformers, Retrieve and Re-Rank · Ragas, faithfulness · Ragas, context recall · Liu et al., Lost in the Middle
FAQ
What is RAG in simple terms?
RAG turns a closed-book exam into an open-book exam. Instead of answering from what it memorised during training, the model first gets the relevant passages from your documents, found by a search step, and answers from them. The answer can cite those passages, so people can check it.
What is a vector database?
A vector database stores embeddings (lists of numbers that capture the meaning of a text) together with the text and its metadata, and quickly finds the stored vectors closest to a new one. Most use approximate nearest neighbour search, such as HNSW graphs, to stay fast at millions of vectors.
What is the difference between RAG and fine-tuning?
Fine-tuning trains the model further and changes its weights; it is good for a style, a format or a narrow task, but facts go stale and answers cannot cite a source. RAG leaves the model unchanged and gives it fresh passages for every question, which suits large, changing or private knowledge. The two can be combined.
Do I still need RAG with long context models?
Not always. If your knowledge base is small, under about 200,000 tokens, putting all of it in the prompt can be simpler. Beyond that, or when cost per question matters, retrieval is still needed, and long prompts have a known weakness: models use facts in the middle of a long input less reliably.
How do you evaluate a RAG system?
Test the two halves separately with a set of real questions. For retrieval, measure context recall (was the needed information retrieved?) and context precision (are the useful chunks ranked first?). For generation, measure faithfulness (is every claim supported by the retrieved chunks?) and answer relevance.
Read next
- LLM Hallucination: 7 Ways to Reduce It with Claude
- LLM Context Window Explained: Claude's Working Memory
- AI Agent Architecture: The Building Blocks, Explained
- Authentication vs Authorization: Sessions, JWT, OAuth, SSO
- Big O Notation Explained Simply, With Everyday Examples
- Software Engineering Unpacked: home
- The CCAR-F video playlist on YouTube