Early-bird price on the GenAI & Agentic AI Engineer Bootcamp batch. Grab a seat →

Retrieval-augmented generation (RAG) means searching your own documents for passages that relate to a question, then giving those passages to a language model and asking it to answer from them. It is the standard way to get answers about private or fast-changing information without retraining a model. It works only as well as its retrieval step: if the right passage is not in the prompt, the model cannot use it.

Key takeaways

  • A RAG system is a pipeline: ingest, chunk, embed, store, retrieve, rerank, then generate with citations. Most quality problems start in the first five steps, not in the model.
  • If all your material fits comfortably in the model's context window, skip retrieval and put the documents in the prompt. RAG earns its place when the corpus is large, changes often, or needs per-user access control.
  • Fine-tuning changes how a model behaves. It is a poor way to teach it facts that change, and it cannot cite a source.
  • Start with the plainest version: sensible chunks, one embedding model, exact search in a database you already run. Add hybrid search and reranking when measurements show retrieval is missing things.
  • Build a test set of real questions before tuning anything. Without one, every change is a guess.

What is RAG, and what problem does it solve?

A language model knows what was in its training data and what is in the prompt. It does not know your contracts, your runbooks or last week's price list. Ask it anyway and it may produce a fluent answer that is wrong. Our article on why AI models hallucinate explains the mechanism.

RAG deals with this by adding a search step. The name comes from a 2020 paper by Patrick Lewis and colleagues, presented at NeurIPS, which combined a model's "parametric memory" (what is stored in its weights) with a "non-parametric memory" (a searchable index of Wikipedia passages). The paper reported that the combined system produced more specific and factual text than a model working from its weights alone.

Three practical benefits follow:

  • Fresh knowledge. Update a document, re-index it, and the next answer uses the new text. No training run.
  • Traceable answers. Because the model answers from passages you supplied, it can say which passage supports which statement.
  • Access control. You can filter retrieval by what the person asking is allowed to read.

What does a RAG pipeline look like end to end?

There are two phases. Indexing happens ahead of time, whenever documents change. Querying happens each time someone asks a question.

A RAG pipeline runs from ingesting documents through chunking, embedding and storing, to retrieving, reranking and generating a cited answer.

1. Ingest

Ingestion turns source files into clean text plus metadata. That means extracting text from PDFs, HTML pages, wiki exports, tickets and spreadsheets, and recording where each piece came from: document title, section, page number, date, owner and who may see it.

This step is dull and it decides a great deal. A PDF whose two columns were read straight across, or a table flattened into a stream of numbers, produces passages no search method can rescue. Read a sample of your extracted text with your own eyes before doing anything else.

2. Chunk

Chunking splits each document into passages small enough to retrieve one at a time. A passage should make sense on its own and cover one idea. Too large, and it mixes topics and wastes prompt space. Too small, and it loses the context that gives it meaning.

Fixed-size splitting with a small overlap is a reasonable baseline. Splitting along the document's own structure (headings, list items, table rows) usually does better where that structure exists. Our guide to chunking strategies for RAG covers the options by document type and shows how to test settings rather than guess.

3. Embed

An embedding model turns a passage into a vector: a list of numbers placed so that passages with similar meaning sit close together. The question is embedded with the same model at query time, and "search" becomes "find the stored vectors nearest to the question's vector".

Two rules matter here. Use the same model for documents and questions. And if you change the model, re-embed everything, because vectors from different models are not comparable.

4. Store

The vectors go into a store that can find nearest neighbours, alongside the original text and metadata. That can be a Postgres table using the pgvector extension, or a dedicated vector database.

For small collections you do not need an index at all. pgvector's documentation says it performs exact nearest-neighbour search by default, "which provides perfect recall", and that adding an approximate index "trades some recall for speed". The choice of store is mostly an operations question, covered in pgvector or a dedicated vector database.

5. Retrieve

At query time the system embeds the question and fetches the nearest passages, usually somewhere between a handful and a few dozen.

Vector search is good at paraphrase: "how do I get my money back" finds the refund policy. It is weaker at exact strings such as part numbers, error codes and surnames. Keyword search has the opposite profile. Running both and merging the two result lists is called hybrid search.

6. Rerank

A reranker is a second, slower model that reads the question together with each candidate passage and scores how well the passage answers it. You retrieve generously, rerank, and keep only the best few. It costs extra latency on every query, so add it when your measurements show the right passage is being retrieved but ranked too low. Both techniques are explained with code in hybrid search and reranking.

7. Generate with citations

Finally the model receives an instruction, the retrieved passages and the question, and writes the answer. The instruction should say three things: answer only from the passages, cite the passage that supports each claim, and say so plainly when the passages do not contain the answer.

The prompt for a RAG answer is a stack of instructions, numbered passages with their sources, and the user's question.

What does a minimal RAG system look like in code?

The example below indexes passages in Postgres with pgvector and retrieves the nearest ones for a question. Embeddings come from the open-source Sentence Transformers library, using the small model from the pgvector Python examples. Swap in your own embedding model and change the vector size to match.

import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("multi-qa-MiniLM-L6-cos-v1")  # 384 dimensions

conn = psycopg.connect(dbname="rag_demo", autocommit=True)
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
register_vector(conn)
conn.execute("""
    CREATE TABLE IF NOT EXISTS chunks (
        id bigserial PRIMARY KEY,
        source text,
        content text,
        embedding vector(384)
    )
""")

def ingest(source, passages):
    for content, embedding in zip(passages, model.encode(passages)):
        conn.execute(
            "INSERT INTO chunks (source, content, embedding) VALUES (%s, %s, %s)",
            (source, content, embedding),
        )

def retrieve(question, k=5):
    return conn.execute(
        "SELECT id, source, content FROM chunks ORDER BY embedding <=> %s LIMIT %s",
        (model.encode(question), k),
    ).fetchall()

def build_prompt(question, rows):
    passages = "\n\n".join(
        f"[{chunk_id}] ({source})\n{content}" for chunk_id, source, content in rows
    )
    return (
        "Answer the question using only the passages below. "
        "After each claim, cite the passage number in square brackets. "
        "If the passages do not contain the answer, say you could not find it.\n\n"
        f"Passages:\n{passages}\n\nQuestion: {question}"
    )

<=> is pgvector's cosine distance operator, so the query returns the five passages closest in meaning to the question. Send the string from build_prompt to the model of your choice. There is no index here on purpose: an exact scan is correct by definition and fast enough for a small table.

How do you get answers with citations you can trust?

Citations let a reader check the answer, and they let you check the system.

The simplest method is the one in the code above. Give every passage an identifier, ask the model to cite identifiers, then verify in your own code that each cited identifier was really in the prompt. Show the reader the source title and a link, not the raw number.

Some model APIs now do part of this for you. Anthropic's Claude API, for example, has a citations feature that you switch on per document with "citations": {"enabled": true}. The response then carries the exact quoted text and its location for each claim. Passages you have already chunked can be sent as "custom content" documents, which are cited block by block with no further splitting. Check what your own provider offers before building this by hand.

Two limits are worth stating plainly. A citation shows where a claim came from, not that the claim reads the source correctly, so models can still cite a passage that does not quite say what they wrote. And "answer only from the passages" lowers the rate of invented content but does not remove it. Both are reasons to measure faithfulness, which is covered below.

When is RAG the wrong tool?

RAG adds moving parts: an ingestion job, an index, a retrieval step that can fail silently. Do not pay for those if a simpler design answers the question.

ApproachUse it whenMain cost or limit
Put the documents in the prompt (long context)The whole corpus fits in the context window and changes rarelyYou pay to process every token on each call unless you cache the prompt. Models can miss details in the middle of very long inputs
RAGThe corpus is too big for the prompt, changes often, or must be filtered per userRetrieval can miss. You must build and maintain a pipeline and an evaluation set
Fine-tuningYou need a consistent style, format or task behaviour that examples in the prompt do not achieveDoes not reliably add facts, goes stale as facts change, cannot cite, needs training data
Ordinary database query or search pageThe answer is a number, a record or a list that already lives in structured dataNeeds a schema and a query, not a language model

Long context first. Anthropic's own write-up on retrieval says that if a knowledge base is smaller than 200,000 tokens, about 500 pages, you can include all of it in the prompt with no retrieval at all, and that prompt caching makes this cheaper and faster. That figure was written in September 2024 for the models of the time. The principle outlasts the number: compare your corpus size with your model's limit before you design a pipeline. See tokens and context windows for how to estimate size.

Long context has its own weakness. The "Lost in the Middle" study by Nelson Liu and colleagues, published in the Transactions of the Association for Computational Linguistics, found that models answered best when the relevant information sat at the start or end of a long input, and noticeably worse when it sat in the middle. Models have changed since 2023, so test this on your own documents instead of assuming it either way.

Fine-tuning is not a knowledge store. Fine-tuning adjusts a model's weights using example inputs and outputs. It is suited to behaviour: a house style, a strict output format, a narrow classification task. It is poorly suited to facts that change monthly, because each change needs a new training run and the model still cannot tell you where an answer came from.

How do you know whether it works?

Test the two halves separately.

For retrieval, collect real questions, record which passages contain the answer, and measure how often those passages appear in the top results. Recall@k, precision and mean reciprocal rank are the usual measures.

For generation, check that each claim in the answer is supported by the retrieved passages (faithfulness) and that the answer addresses the question. A second model can do this grading at scale, provided you first check its verdicts against human labels.

Improving a RAG system is a loop of building a test set, measuring retrieval, changing one thing and measuring answers.

Change one thing at a time, re-run the test set and keep the change only if the numbers improve. How to evaluate a RAG system works through the metrics with a small calculation. If you want these checks to run on every release, see LLM evaluation in CI.

What goes wrong in production?

  • Stale or duplicated content. Three versions of the same policy in the index means the model may quote the old one. Store a date and a version with each passage, and delete or replace passages when the source changes.
  • Permissions. If the index holds documents not everyone may read, filter by the user's rights inside the retrieval query. Asking the model to keep secrets is not access control.
  • Questions with no answer. People will ask things your documents do not cover. Test that the system says so. This is the case where invented answers are most likely.
  • Instructions hidden in documents. Retrieved text enters the prompt, so a document that says "ignore your instructions" is an attack route. Treat retrieved text as data, and limit what the model can do on the strength of it.

What order should you build things in?

  1. Check whether you need RAG at all: count the tokens in your corpus.
  2. Extract text from a sample of real documents and read it.
  3. Write down 30 to 50 real questions with the passages that answer them.
  4. Build the plain pipeline: structure-aware chunks, one embedding model, exact vector search.
  5. Measure retrieval. Fix extraction and chunking first, then add keyword search or a reranker if the numbers call for it.
  6. Write the answer prompt with citations and a clear "not found" path, then measure faithfulness.
  7. Add access filtering, re-indexing on change, and logging of each question, the passages retrieved and the answer.

Common questions

Does RAG stop hallucinations?

No. It reduces them by giving the model the relevant text, and it makes them easier to catch because answers carry citations. A model can still misread a passage or fill a gap when retrieval returns nothing useful.

How many passages should I pass to the model?

There is no fixed number. Anthropic reported that passing the top 20 chunks did better than 10 or 5 in its own tests, while noting that the right number depends on the use case. More passages raise cost and can distract the model. Decide with your test set.

Do I need a vector database?

Not necessarily. If you already run Postgres, the pgvector extension stores vectors next to your other data and supports both exact and approximate search. A dedicated system makes sense when you hit a specific limit that you have measured.

Which embedding model should I use?

One that handles your languages and whose vector size your store can index. Public leaderboards measure other people's data. The only comparison that counts is recall on your own test questions, so try two or three candidates.

Free download: The RAG field guide

Retrieval-augmented generation from ingestion to cited answers: chunking, hybrid search and reranking, evaluation metrics, and choosing between pgvector and a vector database. See what’s inside.