RAG

Also known as: Retrieval-Augmented Generation

On this page 7

Retrieval-augmented generation (RAG) is a technique in which a system retrieves relevant passages from an external knowledge source and inserts them into the prompt of a language model, which then generates an answer grounded in that material. RAG separates what the model knows from what the system can look up, so answers can reflect private, specialized or recently updated information without retraining the model.

In artificial intelligence, RAG has become the default architecture for question answering over company documents, support knowledge bases, legal and technical archives and product catalogs. Its quality depends far more on the retrieval step than on the size of the generating model: a model cannot ground its answer in a passage that was never retrieved.

How a RAG pipeline works

A RAG system runs in two phases: an offline indexing phase that prepares the knowledge source, and an online query phase that runs for every user question. The indexing phase is done once and refreshed when documents change; the query phase must be fast, usually well under a few seconds end to end.

The table walks through both phases in order.

PhaseStageWhat happens
IndexingIngestion and parsingDocuments are converted to clean text with structure and metadata
IndexingChunkingText is split into passages small enough to retrieve precisely
IndexingEmbedding and storageEach chunk becomes a vector stored in a vector index with its metadata
QueryRetrievalThe question is embedded and the most similar chunks are found
QueryRerankingA stronger model reorders candidates and keeps the best few
QueryAugmented generationSelected chunks and the question go into the prompt; the model answers with references
Stages of a typical RAG pipeline

The prompt typically instructs the model to answer only from the supplied context and to say when the context does not contain the answer. That instruction, combined with references to the retrieved chunks, lets users verify each claim.

Retrieval methods used in RAG

The retriever decides which evidence the model ever sees, so retrieval quality sets the ceiling for answer quality. Production systems rarely rely on a single method.

MethodHow it matchesBest atWeak at
Dense vector searchSimilarity of embeddings, usually cosineParaphrases and conceptual questionsExact codes, rare names, numbers
Sparse keyword search (BM25)Weighted term overlapProduct codes, error messages, namesSynonyms and reworded questions
Hybrid searchCombines dense and sparse results, often by rank fusionMixed real-world queriesNeeds tuning of two indexes
Cross-encoder rerankingScores each question and chunk pair jointlyPrecision in the final top resultsToo slow for the full corpus
Metadata filteringRestricts search by date, product, language or access rightsScoped and permission-aware answersDepends on clean metadata
Retrieval methods and where each performs best

A common and robust pattern is hybrid retrieval of 20 to 50 candidates followed by reranking down to 3 to 10 chunks. Reranking is affordable here because it scores only the shortlist, not the whole index.

Key design parameters

Most RAG quality problems trace back to a few tunable parameters. Their best values depend on the documents and questions, so they should be set by measurement on a test set rather than copied from defaults.

ParameterTypical rangeEffect of increasing it
Chunk size200 to 1,000 tokensMore context per hit, less precise matching
Chunk overlapAbout 10 to 20 percent of chunk sizeFewer facts cut at boundaries, larger index
Top-k retrieved3 to 50 candidatesHigher recall, more noise and token cost
Embedding dimensionAbout 384 to 3,072Richer representation, more storage and slower search
Similarity thresholdModel-specific cutoff scoreFewer irrelevant chunks, more unanswered questions
Common RAG parameters and their trade-offs

Structure-aware chunking, which splits at headings, paragraphs or table boundaries instead of at a fixed token count, usually beats naive splitting. Storing the document title and section path with each chunk also helps both retrieval and the citations shown to users.

RAG compared with fine-tuning and long context

RAG, fine-tuning and very long context windows are often presented as alternatives, but they solve different problems. RAG supplies knowledge, fine-tuning shapes behavior and style, and a long context window simply raises how much text one request can hold.

ApproachBest forUpdate costMain limitation
RAGLarge, changing or access-controlled knowledgeRe-index changed documents onlyFails when retrieval misses the evidence
Fine-tuningConsistent format, tone or domain skillNew training run per updatePoor at memorizing exact, changing facts
Long contextAnalysis of a few known documents at onceNone, documents sent per requestCost and latency grow with every token
Choosing between RAG, fine-tuning and long context

The approaches combine well. A fine-tuned model can be better at using retrieved passages faithfully, and a long context window lets RAG pass more candidates when a question needs broad evidence.

Failure modes and evaluation

A RAG answer can go wrong at retrieval or at generation, and the two must be measured separately to know what to fix. Typical failures include:

  • Retrieval miss: the relevant passage exists but is not in the top results, often because of vocabulary mismatch.
  • Broken context: chunking separated a fact from the heading or table that gives it meaning.
  • Stale or conflicting sources: the index holds outdated versions next to current ones.
  • Unfaithful generation: the model ignores the context or adds unsupported details.
  • Indirect prompt injection: a retrieved document contains instructions that the model follows.

Good teams build a labeled evaluation set of real questions and track retrieval recall at k, context precision, answer faithfulness to the retrieved text and answer relevance. Access rights must also be enforced at retrieval time, because a model cannot be trusted to hide a passage it has already been given.

Put simply

RAG is like letting a knowledgeable assistant look things up before answering. Instead of replying from memory alone, the system first searches a trusted collection of documents, picks the most relevant pages and hands them to the AI together with the question.

The AI then writes its answer from those pages and can point to where each fact came from. The answer is only as good as the pages it finds, so the search step matters as much as the AI itself.

In practice

A manufacturing company with about 8,000 pages of maintenance manuals wants technicians to get answers on a tablet at the machine. A first RAG prototype uses fixed 1,000-token chunks and dense vector search only, and on a test set of 300 real technician questions it finds the right passage in the top five results for about 70 percent of them.

The team makes three changes. It chunks the manuals by section at about 500 tokens with a 50-token overlap, adds keyword search for part numbers and error codes, and reranks the top 30 hybrid results down to five. Each chunk now carries the machine model as metadata, so a question about one press never retrieves the manual for another.

Retrieval of the correct passage in the top five rises to about 90 percent, and every answer shows the manual page it came from. Technicians trust the tool because they can check the source in one tap, and the company updates answers simply by re-indexing revised manuals.