Retrieval-Augmented Generation is an AI architecture pattern that extends a large language model with an external retrieval step so responses are grounded in facts pulled from a knowledge source at query time, not only in data encoded during training. The approach treats the model as a reasoning and language engine while delegating the supply of facts to a separate retrieval system. That division is the whole point: the model writes the answer, and a search layer feeds it the evidence.
Retrieval-Augmented Generation (RAG) became the default way to put a large language model (LLM) to work on information it never saw during training. Instead of fine-tuning a model every time the underlying data shifts, a RAG system queries a knowledge base, retrieves the most relevant passages, and hands them to the model as context. The result is grounded generation: output anchored to specific retrieved text rather than to the model's parametric memory alone.
What Retrieval-Augmented Generation Is
Retrieval-Augmented Generation is the process of connecting a large language model to an authoritative external knowledge base so it can look up facts before it writes its answer. AWS frames it as optimizing the output of a large language model so it references an authoritative knowledge base outside its training data before generating a response (AWS, What Is Retrieval-Augmented Generation?). Google Cloud describes the same architecture as combining traditional information retrieval systems with generative large language models (Google Cloud).

The pattern slots into the wider field of generative AI and how modern AI systems work, where the model handles synthesis and language while a separate retrieval layer manages facts. Three components do the work:
- Retriever: the information retrieval component that takes the user query and pulls relevant passages from the knowledge base. Dense retrieval methods use embedding similarity; sparse methods such as BM25 use term frequency weighting.
- Context assembler: the logic that selects, orders, and formats retrieved passages into the prompt sent to the model. A reranking step is often inserted here to promote the most relevant candidates before assembly.
- Generator: the large language model that reads the assembled context plus the query and writes the final response.
That separation lets retrieval systems own freshness, scale, and provenance while the model focuses on producing fluent, coherent text.
How the RAG Pipeline Works
A RAG system divides its work into two distinct phases: index-time, where a corpus of documents is ingested and stored in a retrieval-ready format, and query-time, where a user question triggers retrieval and context assembly before the model generates a response. Red Hat describes this same split, with index-time covering ingestion, segmentation, embedding, and storage, and query-time covering retrieval, selection, and assembly of context for generation (Red Hat).
The end-to-end flow runs in eight steps:
- Ingest the source documents from files, databases, web pages, or internal systems.
- Chunk each document into smaller passages using a chunking strategy suited to the content type.
- Embed every chunk into a numeric vector using an embedding model that captures semantic meaning.
- Store those vectors, alongside the original text, in a vector database or search index.
- Receive the user query at run time.
- Retrieve the most relevant chunks by matching the query against the stored vectors via approximate nearest neighbor (ANN) search.
- Assemble a prompt that combines the query with the retrieved passages.
- Generate the answer, with the model grounded in the supplied context.
Steps one through four happen once, ahead of time. Steps five through eight repeat on every request. This is why information retrieval, not generation, sets the ceiling on answer quality: the model can only reason over what the retriever surfaces.
Index-Time: Building the Retrieval Store
Index-time work determines retrieval quality: documents are split into chunks, each chunk is converted to an embedding vector, and those vectors are stored in a vector database or search index alongside the original text. Get this phase wrong and no amount of clever prompting at query-time recovers the lost accuracy. The choices made here are durable, because re-indexing a large corpus is expensive.

- Chunking strategy: fixed-size chunks are simple and predictable, while semantic chunking splits on meaning boundaries to keep related ideas together. The trade is consistency against relevance; a sliding-window overlap helps avoid splitting a key sentence across two chunks.
- Embedding model: a neural encoder converts each chunk into a dense vector. The chosen embedding model fixes the semantic space, so the same model must embed both documents and queries at inference time.
- Vector store: a vector database or search index holds the dense vectors and supports fast approximate nearest neighbor (ANN) similarity lookups. ANN methods such as HNSW graph indexes and inverted-file (IVF) indexes make that search scale, and transformer-based embedding models map each chunk to its dense vector. The store also keeps the original text so retrieved passages can be returned verbatim.
- Metadata: source, timestamp, and access tags travel with each chunk, which supports filtering and provenance at query-time.
The internals of how a vector store organizes and searches embeddings are a topic in their own right, covered in a dedicated explainer on vector databases. For this pipeline, the operative point is that index-time produces a searchable representation of the knowledge base, ready for the retriever to query.
Query-Time: Retrieval and Grounded Generation
At query time the user's question is converted to an embedding, matched against the vector store via cosine similarity or dot-product scoring, and the top-ranked passages are inserted into the model's context window before generation begins. AWS describes this directly: the user query is converted to a vector representation and matched with the vector databases (AWS). The query and the retrieved information are then both handed to the model.
- Embed the incoming query with the same embedding model used at index-time.
- Run ANN vector search over the store, ranking passages by cosine similarity or dot product.
- Optionally run a reranking step: a cross-encoder reranker scores each candidate passage against the query and reorders the list so the highest-signal passages reach the model first.
- Assemble the prompt, combining the original query with the selected passages inside the context window.
- Generate the answer, with the model instructed to ground its response in the supplied passages.
This is where grounded generation earns its name. Google Cloud frames RAG as retrieval and pre-processing followed by grounded generation, and notes that providing relevant facts to the model as part of the prompt can mitigate hallucinations by ensuring the output is grounded on those facts (Google Cloud). The mechanism rests on how large language models generate output: the model still predicts text, but the retrieved passages weight that prediction toward the supplied evidence rather than its training-data priors.
RAG vs Fine-Tuning vs Prompt Engineering
RAG, fine-tuning, and prompt engineering each solve a different problem: RAG surfaces external knowledge the model never saw; fine-tuning adjusts model behavior and style through additional training; prompt engineering guides outputs using only the base model's existing capabilities. They are not interchangeable, and many production systems combine them. The table below isolates where each one fits.
| Approach | When to use | Key trade-off |
|---|---|---|
| Retrieval-Augmented Generation | The model needs facts from proprietary, internal, or frequently changing sources it never learned. | Adds a retrieval step and an index to maintain; answer quality depends on retrieval quality. |
| Fine-tuning | You need to shift the model's style, format, or task behavior through additional training. | Requires a training run whenever the underlying knowledge changes; knowledge is baked into weights. |
| Prompt engineering | The base model already holds the relevant knowledge and only needs better instructions. | Cannot add facts the model never learned; limited by the base model's existing capabilities. |
The distinction that matters most: RAG and fine-tuning are often framed as rivals, but they answer different questions. RAG supplies knowledge without retraining, which is why AWS positions it as a way to extend a model to specific domains or an organization's internal knowledge base without the need to retrain the model (AWS). Fine-tuning changes how the model behaves. A deeper side-by-side treatment lives in the dedicated fine-tuning vs RAG vs prompt engineering compared explainer.
When RAG Is the Right Choice
RAG is the right architecture when the application needs to answer questions from proprietary, internal, or frequently updated information that the model could not have learned during training. Red Hat singles out exactly these conditions, noting RAG is particularly valuable when applications require access to proprietary or internal knowledge and data that changes frequently (Red Hat). The canonical use cases follow from that:
- Enterprise knowledge bases: answering staff questions from internal wikis, policies, and runbooks the public model never ingested. Dense retrieval over a private vector index makes keyword gaps irrelevant.
- Support ticket resolution: surfacing the right help-center article or past resolution for an incoming customer issue.
- Document Q&A: letting users ask natural-language questions against contracts, manuals, or research libraries.
- Product catalog search: matching a shopper's intent to current inventory and specifications that change often.
- Regulatory and compliance querying: grounding answers in the exact current text of rules rather than a stale training snapshot.
The common thread is freshness and ownership. When the authoritative answer lives in a source the model was never trained on, or in one that changes faster than any training cycle, retrieval is the cheaper and more accurate path than retraining.
Limitations and When to Look Elsewhere
RAG does not eliminate hallucinations, because if the retriever returns the wrong passages, or if the model overrides retrieved context, the output can still be incorrect. Google Cloud and AWS both present RAG as a way to mitigate and ground, not as a correctness guarantee. The honest framing is a mitigation layer, and the failure modes are worth naming:
- Retrieval miss: the search returns the wrong passages, so the model grounds its answer in irrelevant or misleading text. BM25 sparse retrieval fails on synonyms; dense retrieval fails when the query falls outside the embedding model's training distribution.
- Context-length pressure: stuffing too many chunks into the context window crowds out the signal and can degrade the response.
- Latency and cost: a two-step pipeline adds a retrieval round trip before every generation, which raises both response time and per-query cost.
- Maintenance burden: the index must be kept fresh as the source data changes, or retrieval quietly drifts out of date.
When the knowledge the application needs is stable and already inside the base model, prompt engineering alone is simpler. When the requirement is a change in tone, format, or task behavior rather than new facts, fine-tuning is the better tool.
Building a RAG System: Key Components
A production RAG system needs four components working together: a document ingestion pipeline, an embedding model, a retrieval store, and an LLM with prompt-assembly logic. Each maps to a clear role in the pipeline, and the quality of the weakest link caps the whole system. Common quality levers include query rewriting, hybrid search, semantic chunking, reranking, and evaluation with retrieval metrics like recall and precision.

- Document ingestion pipeline: loads source content, cleans it, and applies a chunking strategy to divide it into retrieval-sized passages with metadata attached.
- Embedding model: turns each chunk and each incoming query into a dense vector, defining the semantic space that ANN vector search operates over. These models are built on Transformer encoders such as BERT, and hybrid retrieval can combine them with classic BM25 and TF-IDF term scoring.
- Retrieval store: a vector database or hybrid search index that holds the dense vectors plus original text and serves cosine similarity lookups for information retrieval. Hybrid indexes pair dense retrieval with BM25 sparse scoring and merge results via Reciprocal Rank Fusion (RRF).
- LLM with prompt-assembly logic: the generator, wrapped in code that selects retrieved passages, applies a reranking pass if needed, builds the prompt, and instructs the model to ground its answer.
In practice these components are wired together with an orchestration framework that handles chunking, retrieval calls, and prompt assembly so teams do not rebuild the plumbing for every project. Framework choice, covered in a separate comparison of LangChain, LlamaIndex, and the direct API, mostly affects developer ergonomics rather than the underlying architecture, which stays the four-part pipeline described here.
References
- AWS: What Is Retrieval-Augmented Generation?
- Google Cloud: Retrieval-Augmented Generation Use Cases
- Red Hat: A Practical Look at Retrieval-Augmented Generation
- Databricks: What Is Retrieval-Augmented Generation
- Retrieval-Augmented Generation for Large Language Models: A Survey (arXiv:2312.10997)
- A Survey on Knowledge-Oriented Retrieval-Augmented Generation (arXiv:2503.10677, 2025)
Further reading
- AI customer service
- Fine-Tuning vs RAG vs Prompt Engineering: When to Use Each
- Vector Databases Explained: How AI Apps Store and Search Embeddings
- Prompt Engineering: Techniques That Actually Improve Output
- LLMOps Explained: Deploying and Monitoring AI in Production
- AI App Frameworks Compared: LangChain vs LlamaIndex vs Direct API
- Perplexity Deep Research parallel search architecture
Frequently Asked Questions
How does RAG differ from fine-tuning a language model?
RAG retrieves information at query time and injects it into the prompt; fine-tuning bakes new knowledge directly into model weights through additional training. RAG keeps the base model unchanged and lets you update the knowledge source without retraining, while fine-tuning changes model behavior permanently and requires a training run every time the underlying data changes.
What is a vector database and why do RAG systems use one?
A vector database stores embeddings, which are numeric representations of text chunks that capture semantic meaning. RAG systems use one because similarity search over embeddings lets the retriever find passages that are conceptually relevant to the query, not just keyword matches, making retrieval more accurate for natural-language questions.
Does RAG eliminate AI hallucinations?
RAG reduces hallucinations by grounding model output in retrieved facts, but it does not eliminate them. If the retriever pulls the wrong passage, or if the model ignores the retrieved context, the output can still be incorrect. Treating RAG as a mitigation layer rather than a guarantee is the honest framing supported by the AWS and Google documentation.
When should I choose RAG over prompt engineering alone?
Prompt engineering alone works when the model already has the relevant knowledge in its training data. Choose RAG when your application needs access to proprietary, internal, or frequently updated information that the model was not trained on, such as product documentation, support tickets, or live inventory data.









