Types of RAG

Retrieval-augmented generation finds the right documents first, then lets a model answer from them. This guide explains fifteen variants, what each adds, what it costs, and how the approach changes at the scale of ten million documents, with a full page for every type.

RAG types in 60 seconds

  • What RAG is: search your documents for the passages that matter to a question, then give those passages to the model along with the question.
  • Why it matters: the answer rests on text you can show and update, not only on what the model remembers.
  • Fifteen types, four families: single-pass types retrieve once; quality-loop types check and repair their own retrieval; multi-step types plan several searches; structure-or-media types change what is searched.
  • The rule of thumb: start with the simplest type, measure where it fails, and add one step at a time.
  • At scale (about ten million documents): most failures are retrieval failures. Permissions, freshness, and a grounding check that can refuse matter more than a bigger model.

The problem RAG solves

A language model is trained on a fixed snapshot of text. Ask it about your company's refund policy, last week's incident report, or a manual released after its training, and it has nothing reliable to draw on. Worse, it may still write a fluent, confident answer. Confidence without grounding is what people call a hallucination.

RAG changes the job. Instead of asking the model to remember, you look up the relevant passages when the question arrives and place them in the prompt. The model's task becomes reading and answering from text in front of it. The answer can cite its sources, so a reader can check it. And when the documents change, you update the index rather than retraining the model.

The basic pipeline

Every RAG system shares the same skeleton, from a weekend prototype to a large enterprise search product. Ingestion happens ahead of time. Answering happens on every question.

  • Ingest (offline): split each document into chunks of a few hundred tokens, turn each chunk into an embedding, and store the embedding with the chunk's text, source, and access rules.
  • Retrieve (per question): turn the question into an embedding and fetch the stored chunks whose embeddings are nearest to it.
  • Augment (per question): build a prompt containing the retrieved chunks, numbered, with an instruction to answer only from them.
  • Generate (per question): the model writes the answer, and the application shows the numbered sources next to it.
The per-question path. Ingestion runs earlier, in the background.
A naive RAG pipeline (illustrative sketch) (python)
# Illustrative sketch of a naive RAG pipeline.
# embed(), split_into_chunks(), vector_store and llm are placeholders for real components.

def ingest(documents):
    for doc in documents:
        for chunk in split_into_chunks(doc.text, max_tokens=400, overlap=50):
            vector = embed(chunk.text)  # a list of numbers that captures meaning
            vector_store.upsert(id=chunk.id, vector=vector,
                                payload={'text': chunk.text, 'source': doc.url})

def answer(question, k=5):
    hits = vector_store.search(embed(question), top_k=k)  # nearest chunks by meaning
    context = '\n\n'.join(f'[{i + 1}] {h.payload["text"]}' for i, h in enumerate(hits))
    prompt = (
        'Answer using only the sources below. Cite them as [n]. '
        'If the sources do not contain the answer, say you do not know.\n\n'
        f'Sources:\n{context}\n\nQuestion: {question}'
    )
    return llm.generate(prompt)

The four families

The fourteen types are easier to remember as four families. The families differ by how much work happens per question and whether the system checks its own retrieval. Each type keeps the basic pipeline and adds one kind of step around it.

  • Single pass: retrieve once, then answer. Fast and cheap, but nothing corrects a poor search.
  • Quality loop: the system inspects its retrieval or its draft and repairs it before answering.
  • Multi-step: the system plans and runs several searches or sub-questions, sometimes in parallel, before it answers.
  • Structure or media: the system changes what it searches over, such as a graph of entities, images, or a document's outline.
Fifteen RAG types and the family each one belongs to.

A guide to each type

Every type has its own in-depth page with a diagram, a worked example, code, design decisions, metrics, and notes for your role. Start with the summaries below, then open the page for the type you need.

Family 1: single pass

Naive RAG

Naive RAG is the bare minimum: whatever search you already have, often keyword matching or a plain top-k lookup, pasted straight into the prompt with no filtering, no reranking, and no check on the answer. Many write-ups treat naive and simple RAG as the same thing. This site separates them, because the shape is the same but the care taken is very different. Naive RAG is the baseline every other type is measured against.

  • Good for: prototypes, demos, and measurement baselines.
  • Strengths: quickest to build; lowest latency and cost.
  • Weaknesses: weak retrieval flows straight into confident answers, and nothing notices.

Read the full guide to naive RAG: how it works, a worked example, code, design decisions, and how to measure it.

Simple RAG (the original)

Simple RAG is the version the pipeline above describes. One retrieval, one generation, no feedback. It is the most predictable form of RAG, which makes it the right starting point for any new system. Its weakness is that it has no way to notice a bad search. If the nearest chunks are about the wrong thing, the model will still try to answer from them.

  • Good for: FAQ answering and chatbots where questions are predictable and sources are clean.
  • Strengths: fast, cheap, easy to build, easy to test.
  • Weaknesses: a question that needs two sources is often answered from only one; a poor search is never caught.

Read the full guide to simple RAG: how it works, a worked example, code, design decisions, and how to measure it.

Simple RAG with memory

Users rarely ask self-contained questions. After 'What is the capital of France?' someone may ask 'What about its population?'. A search for 'its population' finds nothing useful. Memory fixes this by keeping recent turns and rewriting each follow-up into a standalone question before retrieval. The retrieval step then sees 'population of Paris', which it can match.

Memory adds three risks. The stored history can be wrong, so a bad answer can influence every later one. Old context can override a new fact. And a stored conversation is personal data, so it needs retention limits and access control. Keep memory short and explicit, and give users a way to clear it.

Rewriting a follow-up into a standalone question (illustrative) (python)
# Illustrative: make a follow-up question searchable before retrieval.
# llm is a placeholder for a chat model.

def standalone_question(history, follow_up):
    if not history:
        return follow_up
    recent = history[-6:]  # keep the memory short
    transcript = '\n'.join(f'{turn.role}: {turn.text}' for turn in recent)
    prompt = (
        'Rewrite the last user message as a complete question that makes sense on its own. '
        'Use only facts from the conversation. Do not answer it.\n\n'
        f'Conversation:\n{transcript}\n\nLast message: {follow_up}\n\nStandalone question:'
    )
    return llm.generate(prompt).strip()

# The rewritten question, not the raw follow-up, goes to retrieval.
query = standalone_question(session.history, 'What about its population?')

Read the full guide to RAG with memory: how it works, a worked example, code, design decisions, and how to measure it.

Family 2: quality loop

Advanced RAG

Advanced RAG is the everyday upgrade over simple RAG. It layers standard improvements around retrieval: the question is cleaned up, filters narrow the search (a date range, a product line, a region), candidates are retrieved with more than one method, and a reranker scores the top candidates against the question. Reranking matters because a vector search returns text that is close in meaning, which is not always the text that answers the question.

  • Good for: production search over large, messy document sets.
  • Strengths: handles harder questions, and each layer can be measured and tuned separately.
  • Weaknesses: many knobs to tune, more latency and cost, and more components to monitor.

Read the full guide to advanced RAG: how it works, a worked example, code, design decisions, and how to measure it.

Corrective RAG

Corrective RAG adds a quality gate between retrieval and generation. After retrieval, a grader checks whether each passage is relevant and whether the set as a whole can answer the question. If the results are weak, the system drops the weak passages, rewrites the query, and searches again, or it uses a fallback source. Only then does it generate. The gate stops a weak search from becoming a confident wrong answer.

The risk is the loop itself. A grader that is never satisfied keeps the system searching forever. Always cap the number of attempts, and decide in advance what the system returns when it gives up.

A retrieval quality gate with a retry cap (illustrative) (python)
# Illustrative: grade retrieval, retry a limited number of times, then say what we know.
# grade_relevance(), rewrite_query() and fallback_search() are placeholders.

MAX_ATTEMPTS = 2

def corrective_retrieve(question):
    query = question
    for attempt in range(MAX_ATTEMPTS):
        hits = vector_store.search(embed(query), top_k=8)
        good = [h for h in hits if grade_relevance(question, h.payload['text']) == 'relevant']
        if good:
            return good[:5]
        query = rewrite_query(question, attempt=attempt)
    return fallback_search(question)  # a different source, or an empty result

Read the full guide to corrective RAG: how it works, a worked example, code, design decisions, and how to measure it.

Self-RAG

Self-RAG makes the model part of the control flow. It first decides whether a question needs retrieval at all; a greeting or a general-knowledge question does not. When retrieval happens, the model checks its own draft against the passages, marking which claims are supported and which are not, and revises or withholds the unsupported ones. Research on this approach trains models to produce these checks. You can approximate it with prompting and a separate verification step, which is what most teams do.

  • Good for: mixed workloads where many questions need no search, and accuracy matters.
  • Strengths: fewer unnecessary searches, and an explicit check on each claim.
  • Weaknesses: extra model calls on every answer, and the model can become too cautious and refuse answers it could safely give.

Read the full guide to Self-RAG: how it works, a worked example, code, design decisions, and how to measure it.

HyDE (hypothetical document embeddings)

Short or technical questions often embed poorly. 'Why does the lease timeout keep firing?' is far from the document that explains lease renewal, even though the two are about the same thing. HyDE asks the model to write a plausible answer first, then embeds that answer and searches with it. A made-up answer is often closer, in meaning, to the real document than the question is. The guess can be wrong, so HyDE works best as one signal among several, not as the only search.

  • Good for: short, specialised questions in technical, legal, or medical domains.
  • Strengths: bridges the gap between how users ask and how documents are written.
  • Weaknesses: an extra model call, and a wrong guess can send the search in the wrong direction.

Read the full guide to HyDE: how it works, a worked example, code, design decisions, and how to measure it.

Family 3: multi-step

Agentic RAG

In agentic RAG a model acts as a researcher. It breaks the task into steps, chooses a tool for each step (a search index, a database, an API), reads the results, and decides whether it has enough to answer or needs another search. The number of searches is not fixed in advance. That flexibility is the point, and it is also the main operational risk, so a step limit, a budget, and a log of every search are required.

  • Good for: questions that need facts from several sources combined, such as a legal case analysis or a market study.
  • Strengths: can plan, notice gaps, and search again.
  • Weaknesses: higher cost, slower answers, and harder testing because each run can differ.

Read the full guide to agentic RAG: how it works, a worked example, code, design decisions, and how to measure it.

Branched RAG

Branched RAG handles open-ended questions by exploring several readings at once. The system generates a few sub-questions or interpretations, retrieves for each branch in parallel, answers each branch from its own passages, and then merges the branch answers into one response. Branching widens coverage. The hard part is the merge: two branches may disagree, and the merge step must say so rather than average them into a false middle.

  • Good for: broad questions such as a market overview that needs technical, pricing, and customer evidence together.
  • Strengths: covers more of the question, and the branches are easy to inspect.
  • Weaknesses: merging conflicting answers is difficult, and a long merged answer can overwhelm the reader.

Read the full guide to branched RAG: how it works, a worked example, code, design decisions, and how to measure it.

Adaptive RAG

Not every question deserves the same effort. Adaptive RAG puts a router in front of the pipeline. The router classifies the incoming question (simple, multi-part, broad, or narrow) and sends it to the cheapest pipeline likely to answer it well. A simple lookup goes to simple RAG; a comparison goes to a multi-step path. The router can be rules, a small classifier, or a model. Over time, logged outcomes show which routes were right, and the routing rules can be updated from them.

  • Good for: systems with mixed traffic, such as a support bot that gets both 'what are your hours?' and 'why was I charged twice?'.
  • Strengths: saves cost on easy questions, and spends effort where it is needed.
  • Weaknesses: a wrong route gives a weaker answer, and the router needs labelled examples to improve.

Read the full guide to adaptive RAG: how it works, a worked example, code, design decisions, and how to measure it.

Speculative RAG

Speculative RAG spends idle time on likely next questions. While the user reads the current answer, the system predicts two or three follow-ups from the conversation and retrieves for them in the background, storing the results in a short-lived cache. If the user asks one of the predicted follow-ups, the answer is already prepared. If not, the cache expires and the compute is wasted. The technique is useful only where follow-ups are predictable and waiting is noticeable.

  • Good for: real-time assistants and guided exploration of a document set.
  • Strengths: lower perceived latency on predicted questions.
  • Weaknesses: wasted compute, and a stale prefetch can answer from outdated sources unless the cache has a time limit.

Read the full guide to speculative RAG: how it works, a worked example, code, design decisions, and how to measure it.

Family 4: structure or media

GraphRAG

Plain similarity search finds passages about a topic. It is weak at questions about how things connect, such as 'which suppliers are affected by the plant closure, and which of their customers are in Germany?'. GraphRAG builds a graph during ingestion: entities (companies, people, components) become nodes, and the relationships found in the text become edges. At query time, the system walks the graph from the entities named in the question and gathers the connected text. Some implementations also summarise clusters of related nodes, which helps with questions that span a whole collection.

  • Good for: investigative and relationship-heavy questions across many documents.
  • Strengths: connects facts that never appear together in one passage.
  • Weaknesses: expensive to build, and answers are only as good as the extracted entities and relationships.

Read the full guide to GraphRAG: how it works, a worked example, code, design decisions, and how to measure it.

Multimodal RAG

Many documents hold information in charts, scanned forms, diagrams, and recordings. Multimodal RAG indexes these alongside text. A chart can be stored with a generated description and its underlying table; an image can be embedded with a model that understands pictures; an audio file can be transcribed with timestamps. A query searches across these representations, and the matching item, not just its caption, is passed to a model that can read it.

  • Good for: technical manuals, scanned records, and reports rich in tables and figures.
  • Strengths: answers questions whose answer lives in a picture or a table.
  • Weaknesses: heavier storage, more expensive ingestion, and quality depends on the image or audio model.

Read the full guide to multimodal RAG: how it works, a worked example, code, design decisions, and how to measure it.

Modular RAG

Modular RAG is less a single pattern than a design principle. Retriever, reranker, query rewriter, and generator sit behind agreed interfaces, so each can be replaced without rebuilding the rest. A team can move from one vector database to another, or swap in a better reranker, and measure the change in isolation. The price is coordination: the interfaces must be designed well, and each module needs its own tests.

  • Good for: teams that expect to change components and need to measure each change.
  • Strengths: swap and test one part at a time.
  • Weaknesses: upfront interface design, and integration bugs at the seams.

Read the full guide to modular RAG: how it works, a worked example, code, design decisions, and how to measure it.

Vectorless RAG (tree-index RAG)

Vectorless RAG skips embeddings for retrieval. It builds a tree that mirrors the document's structure: chapters, sections, and a short summary for each. To answer a question, a model reads the top of the tree, chooses the most promising branch, and descends until it reaches the relevant section. This works well when documents are long and well organised, because the structure carries the meaning. It is weaker on loose text without headings, where there is no tree to walk.

  • Good for: long, structured documents such as manuals, contracts, and annual reports.
  • Strengths: explainable (you can see which section was chosen) and no vector index to maintain.
  • Weaknesses: depends on good headings, and needs an extra model read at each level of the tree.

Read the full guide to vectorless RAG: how it works, a worked example, code, design decisions, and how to measure it.

Hybrid search, the technique behind most advanced systems

Vector search is weak on exact tokens. An embedding of 'ERR-4031' may sit close to other error codes in meaning space, so the exact match can be missed. A keyword index is good at exact matches. Running both and merging the rankings keeps the strengths of each. A common merge method is reciprocal rank fusion: a document scores higher the better it ranks in each list, and the scores are added together. It needs no tuning of score scales, which is why it is popular.

Hybrid search with reciprocal rank fusion (illustrative sketch) (python)
# Illustrative: merge a keyword ranking and a vector ranking.
# keyword_index, vector_store, chunk_store and embed() are placeholders.

def hybrid_search(question, k=5, rrf_k=60):
    keyword_hits = keyword_index.search(question, top_k=20)        # exact terms
    vector_hits = vector_store.search(embed(question), top_k=20)  # meaning

    scores = {}
    for ranking in (keyword_hits, vector_hits):
        for rank, hit in enumerate(ranking, start=1):
            scores[hit.id] = scores.get(hit.id, 0.0) + 1.0 / (rrf_k + rank)

    best_ids = sorted(scores, key=scores.get, reverse=True)[:k]
    return [chunk_store.get(chunk_id) for chunk_id in best_ids]

Case study: a RAG pipeline for ten million documents

At ten million documents the system stops being a retrieval demo and becomes a data platform. Three things change. First, the failure modes multiply: near-duplicate documents crowd out the right answer, old versions of a policy compete with the new one, and a search that was fast at a thousand documents becomes slow. Second, the cost of a wrong answer rises with the audience. Third, you can no longer assume every user may see every document.

Ingest in batches offline; answer each question through permission filtering, retrieval, reranking, and a grounding check.

Design principles at this scale

  • Deduplicate and version at ingestion. Hash each document's content, keep one current version per document, and mark superseded versions so they are never retrieved as current.
  • Filter permissions before ranking. Attach access rules to every chunk and apply them inside the search query. A post-filter that removes documents after ranking can still leak their existence through timing and counts.
  • Use hybrid retrieval and rerank. At this size, the number of plausible but wrong chunks grows quickly. Keyword matches for exact identifiers and a reranker for the final order keep precision high.
  • Index in batches, and track freshness. Embed in batches to control cost, record the index version and ingestion time on each chunk, and expose a freshness value to the answer.
  • Add a grounding check that can refuse. Before answering, verify that each claim in the draft is supported by a retrieved passage. If it is not, return the supported part and say what is missing, rather than guessing.
  • Log every retrieval. Store the query, the filters applied, the chunk ids returned, and the final answer. Most production debugging starts from this log.
Permission filter inside the query, and a grounding gate (illustrative) (python)
# Illustrative: enforce access inside retrieval, then refuse unsupported answers.
# vector_store, keyword_index, reranker, llm and supports_claim() are placeholders.

def answer_at_scale(question, user):
    acl_filter = {'allowed_groups': {'any_of': user.groups}, 'is_current': True}
    candidates = vector_store.search(embed(question), top_k=50, filter=acl_filter)
    candidates += keyword_index.search(question, top_k=50, filter=acl_filter)
    top = reranker.rerank(question, dedupe_by_id(candidates))[:6]

    draft = llm.generate(build_prompt(question, top))
    claims = split_into_claims(draft)
    unsupported = [c for c in claims if not supports_claim(c, top)]

    if not unsupported:
        return {'answer': draft, 'sources': [c.id for c in top]}
    return {'answer': remove_claims(draft, unsupported),
            'note': 'Some details could not be confirmed from the documents.',
            'sources': [c.id for c in top]}

The second principle matters most for a company's own data. A user who is not allowed to read a document must not learn its contents, and the safest place to enforce that is inside the search, before ranking. The grounding gate matters most for the answer itself: a fluent answer with no source behind one of its sentences is the failure users remember. Both checks cost time, so measure their latency and decide where to spend it.

The fifteen types compared

TypeFamilyExtra work per questionChoose it whenMain risk
Naive RAGSingle passNone, and no care in retrievalPrototypes and baselinesWeak retrieval goes unnoticed
Simple RAGSingle passNonePredictable questions, clean sourcesA bad search is never caught
Simple RAG + memorySingle passRewrite follow-upsConversations with follow-up questionsStale or wrong memory
Advanced RAGQuality loopFilters, hybrid search, rerankingProduction search over messy dataMany tuning knobs
Corrective RAGQuality loopGrading and possible retryA wrong source is costlyLoops that never end
Self-RAGQuality loopDecide to retrieve, check claimsMixed traffic where accuracy mattersOver-cautious refusals
HyDEQuality loopGenerate a hypothetical answer firstShort, specialised questionsA wrong guess misdirects search
Agentic RAGMulti-stepSeveral planned searchesResearch across sourcesCost and unpredictable runs
Branched RAGMulti-stepParallel branches, then mergeBroad, open-ended questionsMerging conflicting answers
Adaptive RAGMulti-stepRouting decisionMixed traffic with easy and hard questionsWrong routes
Speculative RAGMulti-stepBackground prefetchPredictable follow-ups, low-latency needsWasted compute, stale cache
GraphRAGStructure or mediaGraph walkRelationships across documentsExpensive graph construction
Multimodal RAGStructure or mediaSearch across images, tables, audioFigures and scans carry the answerStorage and model cost
Modular RAGStructure or mediaDepends on modulesComponents will changeIntegration at the seams
Vectorless RAGStructure or mediaTree descent with model readsLong, well-structured documentsNeeds clear headings

How to choose

  • Start with simple RAG and a small set of real questions with known answers. This gives you a baseline and a way to measure every change.
  • If the right passage is missed because of wording, add query rewriting or HyDE.
  • If exact identifiers are missed, add hybrid search.
  • If the right passage is retrieved but ranked low, add reranking.
  • If a wrong answer is costly, add grading (corrective RAG), a grounding check, and an explicit 'I do not know' response.
  • If questions need several sources combined, consider agentic or branched RAG, after the simpler steps are measured.
  • If questions are about relationships, consider GraphRAG.
  • If the answer lives in figures or scans, consider multimodal RAG.

What this means for your role

Common mistakes

Further reading

The per-type deep-dive pages are being written as separate pages in this section, and this guide will link to them as each one is published. Retrieval is the foundation under most other AI topics on this site: the caching pages explain how to reuse retrieval results, and the agent pages explain how an agent decides what to search.

Search topics

↑↓ to move · Enter to open · Esc to close