Retrieval-Augmented Generation (RAG) — Complete Guide with Examples | AI Terms Guide
Category: RetrievalDifficulty: IntermediateFirst widely used: 2020 (Lewis et al.)Last updated: Aug 6, 2026

Retrieval-Augmented Generation (RAG)

RAG gives a language model access to external documents at inference time — retrieve relevant passages first, then let the model generate an answer grounded in them.
Introduced by Lewis et al. at Facebook AI Research in 2020, RAG addresses the core limitations of LLMs: they can hallucinate, they can't cite sources, and they don't know anything past their training cutoff. By retrieving relevant documents from your own knowledge base at query time and injecting them into the prompt, RAG grounds the model's answer in real data — turning general-purpose LLMs into domain-specific experts.

At a glance

Also known as
RAG
Category
Retrieval Pattern
First introduced
2020 (Lewis et al.)
Difficulty
Intermediate

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.

PYTHON
# 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].text
Notice: This is the minimum viable RAG. Production systems add chunking strategy, rerankers, hybrid search, query rewriting, evaluation, and caching. See our How RAG Works deep-dive.

When 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

1

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.

2

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).

3

Query embedding

When a user asks a question, embed the question using the same model. Similar questions produce similar vectors.

4

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.

5

Optional: rerank

Feed the retrieved candidates through a reranker — a cross-encoder that scores query-document pairs directly. Improves quality significantly at modest cost.

6

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.

7

Generate the answer

Pass the augmented prompt to the LLM. The model synthesizes an answer grounded in the retrieved chunks, ideally with citations.

8

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

Misconception #1: RAG is being replaced by long-context models.
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.
Misconception #2: Better embeddings are the main way to improve RAG.
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.
Misconception #3: RAG eliminates hallucination.
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.

Where you'll see this in practice

Learn more

Sources & further reading

  1. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks — Lewis et al., 2020 (original RAG paper). Read →
  2. Dense Passage Retrieval for Open-Domain QA — Karpukhin et al., 2020 (DPR — foundation for dense retrieval). Read →
  3. Lost in the Middle: How Language Models Use Long Contexts — Liu et al., 2023. Read →
  4. RAGAS: Automated Evaluation of Retrieval Augmented Generation — Es et al., 2023. Read →
FAQ

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.

Share with