Skip to content
AI & Machine LearningAll explainers

What is RAG? How retrieval-augmented generation works

Retrieval-augmented generation (RAG) retrieves relevant documents at query time and feeds them to a language model as context, so answers stay grounded in current, private data without retraining. This explainer covers the RAG pipeline, embeddings, chunking, and evaluation.

Published: Updated: Reading time: 6 min
On this page

Retrieval-augmented generation (RAG) is a pattern for grounding a large language model in data it was never trained on. Instead of fine-tuning the model, you retrieve relevant content at query time and pass it to the model as context. The model answers from that supplied text, so its output reflects current, private information without a new training run.

What is RAG and why it exists

RAG stands for retrieval-augmented generation. The idea comes from a 2020 paper by Patrick Lewis and colleagues led by Facebook AI Research, with co-authors from UCL and NYU, presented at NeurIPS that year. It combined a sequence-to-sequence generator (BART) with a dense retriever over a vector index of Wikipedia. The core idea still holds: a model's weights are a frozen snapshot, but the world keeps moving. Retrieval gives the model a current, citable source at the moment it answers. That reduces hallucination (it doesn't eliminate it) and lets you update knowledge by changing the index rather than retraining.

How a RAG pipeline works

A production RAG pipeline runs in four stages.

  1. Ingest. Split source documents into chunks and store them, usually as embeddings in a vector database, alongside metadata like source and section.
  2. Retrieve. Embed the user's question, run a similarity search for the closest chunks, and optionally re-rank the shortlist with a stronger model.
  3. Augment. Assemble the retrieved chunks into the prompt alongside the question and any system instructions.
  4. Generate. The model answers using the supplied context, ideally citing which chunks it used so the answer stays traceable.

The first stage happens offline as you index a corpus. The last three happen on every request, so retrieval latency and quality shape the whole experience.

Here's a short walk-through. A customer asks "can I change my billing date?" The pipeline embeds that question, pulls the three closest chunks from the billing section of the help center, and places them in the prompt under an instruction to answer only from the supplied text. The model replies and links the help article it used. If the help center changes next week, you re-index it and the next answer follows.

Embeddings and vector search

An embedding is a numeric vector that captures the meaning of a piece of text. Similar ideas land near each other in that vector space, so "how do I reset my password" sits close to a help article about account recovery even when they share no keywords. That's the difference from classic keyword search: lexical matching looks for the same words, while vector search compares meaning.

Retrieval measures closeness with a score like cosine similarity or dot product, then uses approximate nearest neighbor (ANN) algorithms such as HNSW to search millions of vectors in milliseconds. Vector databases that ship this in production include Pinecone, Weaviate, Qdrant, Milvus, and Chroma. Teams that want to stay inside Postgres can use pgvector, a Postgres extension. If you're choosing between two of them, see Pinecone vs Qdrant. Many systems run hybrid search, blending a keyword score like BM25 with dense vectors so rare terms and exact matches aren't lost.

Chunking and retrieval quality

You rarely embed a whole document. You split it into chunks, and where you draw those boundaries decides what retrieval can find. Chunks that are too small scatter a single fact across several pieces; chunks that are too large bury the relevant sentence inside noise the model has to wade through.

A common starting point is chunks of roughly 200 to 1,000 tokens with about 10 to 30 percent overlap, so a fact that straddles a boundary still appears whole in at least one chunk. Treat that as a rule of thumb and tune it on your own corpus. Structure-aware splitting, which respects headings, lists, and paragraphs, tends to beat a blind fixed-size cut on real documents. A cross-encoder re-ranker after the first search often lifts the precision of what reaches the prompt, though it adds latency and can't recover a passage the first search missed.

RAG vs fine-tuning

These are complementary tools, not rivals, and teams often use both. Fine-tuning trains new behavior into the weights, so it suits tone and task-specific skills that stay stable. RAG injects knowledge at inference, so it fits facts that change and answers you need to trace to a source.

Prompting aloneRAGFine-tuning
What it changesThe instructionsThe context the model readsThe model weights
Updating knowledgeEdit the promptRe-index documentsRetrain
Best forSmall, stable contextDynamic or private factsTone, format, behavior
Audit trailNone beyond the promptCited source chunksNone per answer

A support assistant that has to sound on-brand and cite a constantly changing help center usually wants both. For the full decision, see the RAG vs fine-tuning decision guide.

Failure modes and evaluation

Retrieval quality decides most outcomes. Bad chunking, weak embeddings, or no re-ranking produce confident answers built on the wrong context. The recurring failure modes are retrieval misses where the right passage never surfaces, hallucination even when the context is present, a stale index that faithfully serves outdated content, and context-window limits that truncate the evidence before the model sees it. Security is its own category: the OWASP Top 10 for LLM Applications 2025 lists prompt injection, including instructions hidden in retrieved documents, and sensitive information disclosure among the main risks.

Production RAG needs an evaluation harness because these failures are silent. Tools like RAGAS score a pipeline on dimensions such as faithfulness, answer relevance, and context precision and recall. That lets you tell a retrieval problem apart from a generation problem instead of guessing. For help wiring this into a product, see generative AI development.

Where retrieval-augmented generation is heading

Two approaches extend basic retrieval-augmented generation. GraphRAG builds a knowledge graph of entities and relationships to guide retrieval, which helps with multi-hop questions that a flat similarity search struggles to answer. Agentic RAG combines RAG with ai-agents so the model decides when to retrieve, rewrites its own queries, retrieves in several passes, and checks whether it has enough evidence before it commits to an answer. Agentic RAG is an architectural label, not a single algorithm. For a wider view of the surrounding techniques, see generative-ai.

Frequently asked questions

  • RAG stands for retrieval-augmented generation. It pairs a language model with a search step, so the model pulls relevant text from an external source at query time and answers from that context instead of memorized training data alone.

  • RAG works in four moves: it splits your documents into chunks and stores them as embeddings, embeds the user's question, finds the closest chunks by similarity, and pastes those chunks into the prompt. The model then answers using that supplied context, ideally citing the sources it drew from.

  • RAG and fine-tuning solve different problems: RAG injects fresh knowledge at query time and is easy to update by re-indexing, while fine-tuning trains behavior and format into the weights. Use RAG for facts that change and sources you need to audit. Use fine-tuning for how the model should respond.

  • Usually, but not always. A vector database stores embeddings and runs fast similarity search over millions of chunks, which is what most production RAG relies on. For small corpora you can search in memory, and keyword engines can carry part of the load through hybrid search that blends lexical and vector matching.

  • Agentic RAG lets the model decide when and how to retrieve instead of running one fixed search per question. An agent can rewrite the query, retrieve in several passes, call other tools, and check whether it has enough evidence before it answers. Plain RAG relies on one lookup, which breaks down on multi-hop questions that need evidence from several places. The trade is more moving parts and higher latency.

Still unanswered
Ask us directly

A senior engineer replies under 4 hours.

Related expertise