Retrieval-Augmented Generation (RAG)
At a glance
Definition
Retrieval-Augmented Generation (RAG) is a pattern for building AI applications where relevant documents are retrieved from a knowledge source and inserted into an LLM's prompt at query time. The model then generates its response based on the retrieved context — grounding its answer in your data rather than relying only on what it learned during pretraining.
The pattern was introduced by Patrick Lewis, Ethan Perez, and colleagues in their 2020 paper Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. The insight was elegant: LLMs are excellent at synthesizing information but limited by what's in their weights. Retrieval systems are excellent at finding relevant documents but can't synthesize. Combine them, and you get grounded generation.
By 2026, RAG has become the most widely deployed pattern for LLM applications. Every customer-support bot backed by a knowledge base, every 'chat with your documents' feature, every research assistant that cites sources — they're all variations of RAG. The pattern has evolved: modern RAG systems use embeddings and vector databases for semantic retrieval, rerankers for quality, hybrid search for robustness, and agentic RAG patterns where the model decides what to retrieve.
RAG is often compared with fine-tuning, but they solve different problems. RAG is best for injecting up-to-date knowledge that changes frequently and for citation. Fine-tuning is best for consistent style, format, or reasoning patterns that don't change. In practice, most production systems use both — see our RAG vs Fine-tuning comparison.
Real-world example
Building a "chat with your docs" feature
You have 500 support articles and want users to ask questions in natural language. Without RAG, you'd need to fine-tune a model (expensive, brittle when docs change) or paste all 500 articles into every prompt (way over context window). With RAG: at indexing time, split each article into chunks, embed each chunk into a vector, store in a vector database. At query time, embed the user's question, find the 5 most similar chunks by cosine similarity, feed them to the LLM as context, and ask it to answer based only on those chunks. Result: grounded answers that cite specific articles, with your knowledge base staying easy to update.
# Minimal RAG in Python
from anthropic import Anthropic
from openai import OpenAI # for embeddings
client = Anthropic()
embedder = OpenAI()
# 1. Retrieve — find relevant chunks
def retrieve(question, k=5):
q_embedding = embedder.embeddings.create(
input=question, model="text-embedding-3-large"
).data[0].embedding
# Assume `vector_db.search()` returns k most similar chunks
chunks = vector_db.search(q_embedding, k=k)
return chunks
# 2. Augment — build the prompt
def build_prompt(question, chunks):
context = "\n\n".join([f"[Doc {i+1}]\n{c.text}" for i, c in enumerate(chunks)])
return f"""Use only the documents below to answer.
Cite sources by [Doc N].
DOCUMENTS:
{context}
QUESTION: {question}"""
# 3. Generate — pass to LLM
def rag_answer(question):
chunks = retrieve(question)
prompt = build_prompt(question, chunks)
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].textWhen you'll encounter this
- You need the model to answer from a specific document set — company docs, product manuals, legal contracts, research papers.
- You need citations and sources — RAG naturally produces answers you can trace back to specific documents.
- Your knowledge base changes frequently — retrieval means updates are as simple as re-indexing; no retraining required.
- You want to reduce hallucination — grounding the model in retrieved context dramatically cuts made-up answers.
- Your data is too big for the context window — even with long contexts, retrieval is often cheaper and faster than stuffing everything.
How it works
Prepare documents
Split documents into chunks (usually 200-800 tokens with some overlap). Chunking strategy dramatically affects RAG quality — bad chunks tank the whole system.
Embed and store
Convert each chunk into a dense vector using an embedding model (OpenAI text-embedding-3, Cohere embed-v3, BGE, etc.). Store vectors in a vector database (Pinecone, Weaviate, Qdrant, pgvector).
Query embedding
When a user asks a question, embed the question using the same model. Similar questions produce similar vectors.
Retrieve relevant chunks
Find the top-k chunks with the highest similarity to the query embedding (usually cosine similarity). Modern systems often use hybrid search combining semantic and keyword retrieval.
Optional: rerank
Feed the retrieved candidates through a reranker — a cross-encoder that scores query-document pairs directly. Improves quality significantly at modest cost.
Build the augmented prompt
Insert the retrieved chunks into the prompt with clear formatting. Tell the model to answer using only the provided context, and to cite sources.
Generate the answer
Pass the augmented prompt to the LLM. The model synthesizes an answer grounded in the retrieved chunks, ideally with citations.
Evaluate and iterate
RAG quality depends on many stages. Instrument each stage (retrieval hit rate, faithfulness, answer quality) with RAG evaluation to know where to improve.
Common misconceptions
Very long contexts (200K-2M+ tokens) reduce the need for RAG on small document sets. But for large corpora, updates-anytime knowledge, or citation requirements, RAG remains essential. And even with long contexts, retrieval is often cheaper and lower-latency than stuffing 500 documents into every prompt.
Empirically, chunking strategy has more impact than embedding choice for most systems. Bad chunks (too big, split mid-idea, no overlap) hurt more than a mediocre embedding model. Second-highest impact: adding a reranker. Only after those two are dialed in does embedding model choice matter much.
It reduces hallucination but doesn't eliminate it. Models can still misinterpret retrieved chunks, combine them incorrectly, or produce plausible-sounding answers that go beyond what the context actually says. Structured prompting, citation requirements, and evaluation are still necessary.
Related terms
Related in Vector Databases & RAG
Broader concepts
Narrower / specific concepts
Head-to-head comparisons
Where you'll see this in practice
Related tools
Related models
Learn more
- Read the deep-dive: How RAG Works (End-to-End)
- Take the Master RAG in 10 Lessons path
- Compare RAG vs Fine-tuning
- Browse Vector Databases & RAG category
Sources & further reading
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks — Lewis et al., 2020 (original RAG paper). Read →
- Dense Passage Retrieval for Open-Domain QA — Karpukhin et al., 2020 (DPR — foundation for dense retrieval). Read →
- Lost in the Middle: How Language Models Use Long Contexts — Liu et al., 2023. Read →
- RAGAS: Automated Evaluation of Retrieval Augmented Generation — Es et al., 2023. Read →
Frequently asked about Retrieval-Augmented Generation (RAG)
RAG injects external context at query time. Fine-tuning updates the model's weights on your data. RAG is better for changing knowledge and citation; fine-tuning is better for consistent style and format. Most production systems use both. See our detailed comparison.
For most production RAG systems, yes. For small document sets (under ~100K docs), pgvector on PostgreSQL is usually fine. Above that, dedicated vector databases (Pinecone, Weaviate, Qdrant, Milvus) offer better query speed, metadata filtering, and update handling.
Usually chunking. Chunks that are too big overload the model, too small lack context, or split mid-idea confuse retrieval. Second-biggest is not using a reranker. Embedding model choice matters less than most people expect.
Instrument each stage separately: retrieval hit rate (did we retrieve the right chunks?), answer faithfulness (did the model stick to the context?), answer quality (was the answer actually good?). Tools like RAGAS automate this. See our evaluation category.
Yes. RAG is a pattern, not a model feature. Any LLM that accepts text input can do RAG. Models with longer context windows (Claude, Gemini, GPT with long context) let you pass more retrieved chunks per query. Models with strong instruction following tend to be better at staying grounded in the context.
Technically reviewed by the AI Terms Guide editorial team on August 6, 2026. Last updated: August 6, 2026. Spotted an error? Let us know — corrections ship within 24 hours.
Building with AI? Try our sister sites
Deep coverage of AI errors, code patterns, and pricing you won't find in the reference.
AI Terms Weekly
One deep term, three new models, one comparison — every Tuesday.