Building with LLMs › RAG and vector search
What is RAG? A plain guide to retrieval-augmented generation
What RAG means, why language models need to look things up before they answer, how search and generation fit together, and a small example you can run.
If you read about chatbots that answer from a company’s own documents, or browse the docs of an LLM API, you’ll keep running into three letters: RAG. But when you look it up, many explanations start with vector databases and frameworks, so the simple idea underneath can be hard to see.
RAG, short for retrieval-augmented generation, is a way of finding material related to a question before a language model answers, and putting that material into the prompt. So the model doesn’t need to have memorized the answer. It only has to read what was found and answer from it. That’s also why you hear the term so often these days, since the major LLM services now build it in. As of October 2026, OpenAI’s file search and the Gemini API’s File Search both search your uploaded files and use what they find in the answer. Claude Projects, too, switch to a RAG mode when the uploaded material nears the limit of the context window, the amount of text a model can read at once.
The paper behind the name and what it means now
In a paper posted in May 2020 and accepted at NeurIPS 2020, Patrick Lewis and colleagues at Facebook AI Research called their approach retrieval-augmented generation, or RAG. Their RAG added an outside collection of searchable text to the knowledge stored in a model’s weights. A retriever called DPR searched about 21 million passages, made by cutting Wikipedia into 100-word chunks, and BART-large wrote the answer. The two parts were fine-tuned together.
Today the word is used more broadly, and it often means any setup that searches for relevant text and puts it into an LLM’s prompt without any extra training. Anthropic’s Contextual Retrieval post, for example, describes RAG as splitting material into chunks, embedding them, and adding the most relevant chunks to the prompt. Of course, pairing search with a language model was an idea that existed before, and the paper itself discusses earlier models such as REALM.
Why a model needs things looked up for it
A language model learns from data collected up to a certain date, often called its knowledge cutoff, so it doesn’t know what happened after that. The Lewis paper built separate indexes from 2016 and 2018 Wikipedia and asked about 82 world leaders who had changed in between. With the matching index, RAG got 70% and 68% right, but with the mismatched one only 12% and 4%. In other words, swapping the documents changed what the system knew, with no retraining.
Company policies or meeting notes that were never public are the same, since a model can’t know them unless someone shows them. And because you know which passages went into the prompt, you can show them as sources. It also helps with hallucination, a model’s habit of saying plausible but false things. In 2021, Shuster and colleagues reported that, by human evaluation, retrieval substantially reduced knowledge hallucination in chatbots. It doesn’t disappear entirely, though, as the example below will show.
How RAG works, step by step
A RAG system prepares its documents before any question arrives, then searches and answers each time a question comes in. In order, it goes like this.
- Split the documents into small pieces called chunks.
- Turn each chunk into an embedding, a list of numbers that captures its meaning.
- Store the chunks and their embeddings in an index.
- Turn the question into an embedding too, and find the closest chunks.
- Put the chunks you found into the prompt along with the question.
- Let the model read that prompt and write the answer.
Embeddings deserve a post of their own, so just a paragraph here. An embedding model turns a text into a fixed-length list of numbers, and the lists for texts with similar meanings point in similar directions. Cosine similarity measures how alike two directions are, and it’s 1 when they point the same way and closer to 0 the less related the texts are.
Vector databases get a single paragraph too. With millions of chunks, comparing the question against every one is too slow, so a vector database builds an index that finds nearly the closest vectors much faster. The Lewis paper, for its part, used the FAISS library to search its passages.
Trying it with five made-up policies
The documents are five short policies for a company I made up, so no model could have seen them in training. Each one is short enough to be a chunk on its own, so I skipped the splitting step, and for embeddings I used all-MiniLM-L6-v2, which turns each text into 384 numbers. You’ll need the sentence-transformers and transformers packages.
from sentence_transformers import SentenceTransformer
docs = [
"Remote work: up to three days a week from home. Tuesdays are office days.",
"Pets: dogs may come to the office on Fridays only. Register them at the front desk.",
"Equipment: everyone gets a laptop, replaced every four years.",
"Travel: meals on business trips are covered up to 60 dollars a day.",
"Leave: new employees get 18 days of paid leave a year.",
]
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
doc_vecs = embedder.encode(docs) # one vector of 384 numbers per chunk
def search(question, k=3):
scores = embedder.similarity(embedder.encode(question), doc_vecs)[0]
best = scores.argsort(descending=True)[:k]
return [(float(scores[i]), docs[i]) for i in best]
question = "When can I bring my puppy to work?"
for score, doc in search(question):
print(f"{score:.3f} {doc.split(':')[0]}")
search() embeds the question, measures its cosine similarity to the five chunks, and returns the three highest.
0.590 Pets
0.337 Remote work
0.241 Leave
The question says puppy, the policy says dogs, and the word “work” doesn’t even appear in the pet policy, yet it came first at 0.590. The search matched on meaning. Now let’s put that chunk into a prompt for Qwen2.5-0.5B-Instruct, a small instruction-tuned model with 0.49 billion parameters.
from transformers import pipeline
chat = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct")
def ask(prompt):
messages = [{"role": "user", "content": prompt}]
reply = chat(messages, max_new_tokens=40, do_sample=False)
return reply[0]["generated_text"][-1]["content"]
def rag_answer(question):
score, context = search(question, k=1)[0]
prompt = (f"Here is our company policy:\n{context}\n\n"
f"Question: {question}\nAnswer in one or two sentences. "
"If the policy does not say, answer I don't know.")
return ask(prompt)
print("Without retrieval:", ask(question))
print("With retrieval:", rag_answer(question))
With do_sample=False, the model always picks its most likely next token, so the same machine gives the same answer every time. I capped answers at 40 tokens.
Without retrieval: As an AI language model, I don't have personal preferences or emotions like humans do, but I can provide you with some general information about bringing your puppy to work.
Puppies are generally not allowed
With retrieval: You can bring your puppy to work on Fridays only.
Asked on its own, the model drifted into general advice and even started to say puppies are generally not allowed, which is wrong for this company. With the policy in the prompt, it answered correctly, so the model stayed the same and only the prompt changed.
Keyword search, vector search, and reranking
Keyword search ranks documents by how well their words match the question’s words. The well-known BM25 weighs how often a word appears in a document and how rare it is across the collection. When I ran a plain BM25 on the example above, the remote work policy came first, since it’s the only one containing “work”, and the pet policy came third. On the other hand, keyword search is strong when you need an exact name or code. Anthropic’s example is the error code TS-999, where an embedding model may bring back documents about error codes in general while BM25 finds that exact string.
So the two are sometimes run together and their results merged, which is called hybrid search. Reciprocal Rank Fusion, a simple way to merge them, gives each document more points the higher it ranks in each list and adds them up, so the two kinds of scores never need to be on the same scale. Reranking then rescores the shortlist with a more careful model. A cross-encoder reads the question and a passage together, which makes it accurate but slow, so it runs after a fast search (Retrieve & Re-Rank).
When retrieval goes wrong, so does the answer
RAG often goes wrong quietly, because search always returns something, even when the documents hold no answer. I asked two questions that none of the five policies answer.
for question in ["Do we get a bonus at the end of the year?", "What time does the office open?"]:
score, doc = search(question, k=1)[0]
print(f"{question}\n {score:.3f} {doc.split(':')[0]} | {rag_answer(question)}")
Do we get a bonus at the end of the year?
0.332 Leave | I don't know.
What time does the office open?
0.393 Pets | The office opens at 8 AM.
For the bonus, the model said it didn’t know. For the opening time, though, search brought back the pet policy, which happens to mention the office, and the model made up 8 AM even though it was told to say I don’t know. That’s why it’s safer to set a minimum score and skip the model when no chunk clears it. Here, 0.45 would stop both questions and keep the puppy search (0.590), but the right number depends on your model and documents.
Chunk size matters as well. Chunks that are too big mix topics, which blurs their embeddings, and they can run past the input limit. By default, all-MiniLM-L6-v2 truncates input longer than 256 word pieces, the sub-word tokens it reads. Chunks that are too small lose their context, as in Anthropic’s example of a chunk saying only that revenue grew by 3% over the previous quarter, with no way to tell which company it means. For reference, Anthropic says chunks are usually no more than a few hundred tokens.
How to check whether it works
So it helps to measure search and answers separately. For search, note which chunk answers each question and count how often it lands in the top results, mixing in questions the documents can’t answer. For answers, the Ragas paper (2023) looks at whether the answer is grounded in the retrieved text (faithfulness), whether it fits the question (answer relevance), and whether the retrieved text stays focused on the question (context relevance). Still, perhaps the best start is a few dozen questions you’ve checked by hand.
How RAG differs from fine-tuning and long context
Besides RAG, two other ways of giving a model knowledge it lacks come up often.
| Approach | Where the new knowledge lives | When documents change |
|---|---|---|
| RAG | Outside documents, searched per question | Edit and re-index |
| Fine-tuning | The model’s weights, after more training | Train again |
| Long context | The prompt, all of it, every time | Edit the documents |
Fine-tuning trains an existing model further on your own data, which changes its weights, and it’s often used to shape how a model behaves, such as its format or tone. For adding facts, though, the evidence leans toward RAG. In a 2023 study by Ovadia and colleagues, RAG consistently beat unsupervised fine-tuning, which keeps training a model on raw text, for both previously seen and new knowledge.
Long context means putting the whole document set into the prompt, and Anthropic says a knowledge base under 200,000 tokens (about 500 pages) can simply all go in, with no need for RAG. Even so, every question then carries every document, and models don’t always read long inputs evenly. Lost in the Middle (2023) reported that performance often drops significantly when the relevant information sits in the middle of the input rather than at the beginning or end.
When RAG fits and when it doesn’t
RAG tends to fit when the answers live in documents that change often, or when you need to show sources, and help centers, internal policies, and product manuals are the usual examples. It fits less well when a question needs the whole collection, like “what themes keep coming up across all our meeting notes,” and if your documents fit in the prompt, long context may simply be easier. If what you want to change is tone or behavior, fine-tuning or a better prompt is the more natural tool.
Where to start
If you’re new to RAG, I’d suggest running the example above, swapping the five policies for your own documents, and checking which chunk each of ten or so questions retrieves before reading the answers. For the search side, the Sentence Transformers semantic search guide is a good next step. Scores and wording may differ slightly on other hardware. I got these results on October 27, 2026, on a Mac with Apple silicon, with Python 3.13.12, sentence-transformers 6.2.0, transformers 5.20.2, and PyTorch 2.14.1.
AI tools helped with the research for this post.