Language models have a problem. They are trained on enormous corpora of text, acquiring broad knowledge and impressive generative ability. But that knowledge is frozen at the training cutoff. Ask a model about events after that date and it will either say it does not know or, more dangerously, hallucinate plausible-sounding answers.
Ask it about your company's internal documents and it has never seen them. Ask it about your product's current pricing and it will either apologize or invent something.
The obvious engineering solution: give the model access to current, specific, or proprietary information at the time it answers. Not by retraining it - that is expensive and slow.
Relevant documents go into the model along with the query as input, so the model can ground its answer in verified content instead of building from statistical inference alone.
This is called Retrieval Augmented Generation or RAG. It was formalized in a 2020 paper, though the idea behind it is simple.[1] Combine a retrieval system with a language model so that instead of drawing only on learned parameters, the model produces answers grounded in what is retrieved.
Production apps calling for factual accuracy, up-to-date info or access to specific knowledge bases like enterprise knowledge management, customer support, research tools and document Q&A now use RAG as the main pattern for deploying language models. Gao et al.'s 2023 survey of 162 RAG research papers found that RAG had moved from being a niche retrieval method to becoming the base architecture for knowledge-intensive AI apps across almost every industry vertical.
"Retrieval augmented generation addresses the fundamental challenge of parametric memory in language models: it's not efficient to encode every fact the world needs into model parameters.
Retrieval provides access to a virtually unlimited, updatable knowledge store."
Patrick Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020)
Key Definitions
Retrieval Augmented Generation (RAG). This is an AI system architecture that brings together a language model and a retrieval system.
When a query goes in, relevant documents come out of the knowledge base and get passed to the language model along with the query. Grounded in the content that was retrieved, the model then produces a response.
RAG reduces hallucinations and enables models to access current or proprietary information without retraining.
Retriever. This is the part of a RAG system that looks through the knowledge base to find relevant documents for a given query. Retrievers can work by sparse methods such as keyword-based search, by dense methods like embedding-based semantic search or by hybrid methods that combine both.
Generator. This is the language model part of a RAG system that makes the final response. It takes both the query and the retrieved documents as its condition. How well the generator uses the given context to produce accurate and grounded answers depends on the quality of the generator.
Vector embedding - A numerical vector representation of text that captures its semantic meaning. Similar texts have embeddings that are geometrically close (high cosine similarity); dissimilar texts have embeddings that are far apart.
Embeddings are produced by embedding models trained specifically for this purpose. They are the foundation of semantic search in modern RAG systems.
Vector database - A database optimized for storing and querying high-dimensional vector embeddings. Enables similarity search: finding documents whose embeddings are closest to a query embedding. Used as the retrieval backend in most production RAG systems. Examples: Pinecone, Weaviate, Chroma, Milvus, pgvector.
Chunking - The process of dividing documents into smaller segments for indexing and retrieval. Because language models have limited context windows, documents too large to fit must be split.
How large each chunk is, whether chunks overlap and whether chunks respect document structure all have a big effect on how well retrieval works and that is the chunking strategy.
Semantic search. Documents are found by meaning instead of by an exact keyword match. When someone searches semantically for "car maintenance", the result may be documents on "vehicle upkeep" or "automobile service" even if the precise words do not appear in the search query.
Semantic search in RAG systems is enabled by embedding-based similarity search.
Sparse retrieval. Retrieval that comes down to term frequency or keyword overlap most often uses algorithms like BM25 (Best Match 25).[5] When keywords count, as they do for technical terms, proper nouns and specific phrases, sparse retrieval is quick and effective. It does not pick up semantic similarity.
Dense retrieval. Retrieval that works by embedding similarity. Both the query and all documents get turned into embeddings. The ones most semantically similar come out of retrieval.[4] Natural language queries do better with dense retrieval than with sparse retrieval at capturing meaning but dense retrieval may miss exact keyword matches.
Hybrid retrieval. By interleaving or reranking results from both methods, hybrid retrieval brings together sparse and dense retrieval. When either method on its own is put up against it, hybrid retrieval most often performs better and it captures both keyword specificity and semantic similarity.
Reranking - A post-retrieval step that uses a separate, typically more powerful model to reorder retrieved documents by relevance to the query. Rerankers are typically cross-encoders (considering query and document jointly) and are more accurate than the initial retriever but too slow to apply to the full knowledge base.
Context window. That is the maximum amount of text a language model can handle in one forward pass. How many documents get sent to the generator is limited by context windows and larger context windows make less demand on aggressive chunking and let in more documents.
Grounding - The property of an AI-generated response that can be traced back to and verified against specific source documents. Grounded responses reduce hallucination risk and enable citation. RAG is the primary technique for achieving grounding in deployed systems.
The RAG Architecture: How It Works
A standard RAG system has two phases: indexing (offline) and querying (online).
Indexing Phase (Offline)
Before the system can answer queries, the knowledge base must be indexed:
Document ingestion. Source documents including PDFs, web pages, databases and internal documents get collected and preprocessed by extracting text from different formats and getting rid of formatting artifacts.
Chunking. Documents get divided into segments sized to fit in the context window along with the query and other chunks. Most often, chunks are 256 to 1,024 tokens in size.
Fixed-size chunking, sentence-aware chunking that splits at sentence boundaries, paragraph-level chunking and recursive chunking that tries to keep document structure are among the strategies used.
Embedding: Each chunk is converted to a vector embedding using an embedding model. This is the most computationally expensive part of indexing and is done once per document, then reused for all queries.
Storage. A vector database (or combined storage system) that supports efficient similarity search is where chunk text and embeddings get stored.
Query Phase (Online)
When a user submits a query:
Query embedding: The query is converted to an embedding using the same embedding model used during indexing.
Retrieval. The vector database returns the top-K chunks whose embeddings are closest to the query embedding. K is most often 3 to 10, depending on the context window size and chunk size.
Optional reranking. A cross-encoder model reranks the chunks that have been retrieved to make the relevance order better.
Context construction. The retrieved chunks go together into a context string that most often has their source information as well, including document title, page number and URL.
Generation. The language model gets a prompt that has the query and the retrieved context along with instructions to answer using what the documents supply. From that retrieved material, the model generates a grounded response.
Optional citation: The response may include references to the specific source documents from which information was drawn.
The Original 2020 Paper: What Lewis et al. Proved
The foundational RAG paper - Lewis, P., Perez, E., Piktus, A., Petroni, F., Karpukhin, V., Goyal, N., Kuettler, H., Lewis, M., Yih, W., Rocktaeschel, T., Riedel, S., and Kiela, D. - was published at NeurIPS 2020 and demonstrated that retrieval augmentation systematically outperforms pure parametric models on knowledge-intensive tasks.[1]
The team tested two RAG formulations: RAG-Sequence (retrieving one set of documents for the entire answer) and RAG-Token (potentially retrieving different documents for each generated token). They compared against state-of-the-art closed-book models on several benchmarks:
- On Natural Questions, RAG achieved 44.5% exact match, compared to 29.8% for the best closed-book model at the time - a 49% relative improvement
- On TriviaQA, RAG matched or exceeded retrieval-augmented specialists despite being a general-purpose architecture
- On WebQuestions and CuratedTrec, RAG set new state-of-the-art results in the open-domain question answering category
Human evaluators rated RAG-generated responses as more specific, more diverse and more factually grounded than those from pure generative models and the study also found this. That set up the empirical baseline that drove the huge investment in RAG infrastructure that came next.
Chunking Strategies and Their Tradeoffs
Chunking is one of the most consequential design decisions in a RAG system. Poor chunking degrades retrieval quality even when the underlying documents are comprehensive.
| Strategy | Description | Strengths | Weaknesses |
|---|---|---|---|
| Fixed-size | Chunks of equal token count | Simple; predictable size | May split mid-sentence or mid-argument |
| Sentence-aware | Split at sentence boundaries | Preserves linguistic units | Variable chunk size |
| Paragraph-level | One chunk per paragraph | Preserves thematic coherence | Paragraphs vary widely in length |
| Hierarchical | Multiple granularities (paragraph, sentence) | Flexible retrieval at different granularities | More complex infrastructure |
| Semantic | Split where topic changes | Preserves semantic coherence | Requires semantic segmentation model |
| Sliding window | Fixed-size with overlap between chunks | Reduces boundary artifacts | More chunks to store and retrieve |
When adjacent chunks share some tokens, overlapping chunks help keep context that would otherwise get cut at where the chunks end. Overlap most often amounts to 10 to 20 percent of the chunk size.
LlamaIndex's 2023 performance benchmarks showed that overlapping chunking cut "split context" failures by about 15 to 20 percent compared to hard boundaries though this came at the price of more storage and retrieval latency.
The Chunk Size Dilemma
Chunk size is a fundamental tension in RAG design. Smaller chunks:
- Are more precisely matched to narrow queries
- May lack sufficient context to answer multi-part questions
- Result in more chunks to retrieve and more noise
Larger chunks:
- Contain more context per retrieval unit
- May be semantically diluted, reducing retrieval precision
- Consume more of the limited context window
Both practical experience and published benchmarks point to 512 tokens as a reasonable default to begin with and fine-tuning comes from the specific characteristics of the knowledge base and query distribution.
RAG vs. Fine-Tuning vs. Prompt Engineering
These three approaches are often considered as alternatives but are more complementary than competing:
Prompt engineering modifies the model's behavior through the instructions and context provided at inference time. It is the fastest to implement and requires no training, but it is limited to what can fit in the context window and cannot teach the model new information.
Fine-tuning. The model's weights get modified through extra training on particular data. New reasoning patterns can be taught, the response style can be adjusted or performance in specific domains can be improved by fine-tuning.
It is not well-suited for providing access to large, changing knowledge bases: fine-tuning is expensive, cannot easily be updated as the knowledge base changes, and does not support attribution.
RAG provides specific documents at inference time. It is well-suited for large, changing, or proprietary knowledge bases; it supports attribution; it does not require modifying model weights; and it can be updated by adding new documents to the knowledge base without retraining.
Ovadia et al. published a 2023 comparison study titled "Fine-Tuning or Retrieval. Comparing Knowledge Injection in LLMs"[10]. The study directly tested these methods on factual knowledge tasks.
RAG consistently outperformed fine-tuning for knowledge retrieval tasks. Fine-tuning did show advantages mainly in stylistic and behavioral adaptation.
Critically, fine-tuning degraded on knowledge that changed after the fine-tuning data cutoff - a problem RAG does not have by design.
"For applications where the core requirement is factual grounding in a specific knowledge base, RAG is usually the right starting point.
For applications where the core requirement is behavioral modification (a different tone, domain-specific reasoning patterns, specialized task formats), fine-tuning is the right starting point."
Ovadia et al., Fine-Tuning or Retrieval? Comparing Knowledge Injection in LLMs (2023)
Many production systems use both: RAG for knowledge grounding, fine-tuning for behavioral alignment.
Advanced RAG Techniques
The basic retrieve-then-generate pipeline has been substantially extended by the research community.[2] These techniques address specific failure modes or improve performance for particular use cases.
Query Transformation
How relevant information appears in source documents varies a lot from what raw user queries contain. Query transformation handles that by rewriting or expanding the query before anything gets retrieved.
- Hypothetical Document Embeddings (HyDE) This was proposed by Gao et al.[8] in 2022. HyDE gives a hypothetical answer to the query and then uses the embedding of that hypothetical answer for retrieval instead of using the query's embedding. The reasoning is that the hypothetical answer comes in the same style and vocabulary as the documents being retrieved and this makes embedding similarity more reliable.
- Multi-query retrieval: Generate multiple reformulations of the query and retrieve for each, then merge and deduplicate results. Reduces the brittleness of any single query formulation.
- Step-back prompting. Ask the model to find a more general principle behind the complex query first and then get documents that match that principle. Specialized or technical questions get better retrieval from this approach.
Self-RAG: Adaptive Retrieval
Asai et al. (2023) introduced Self-RAG, a framework that trains models to decide when to retrieve (rather than always retrieving) and to critically evaluate the relevance and support quality of retrieved passages.[7]
Special reflection tokens come out of the model that show whether retrieval is needed, whether retrieved passages are relevant and whether the final answer has support from the retrieved evidence.
On several benchmarks, Self-RAG showed large gains over standard RAG and especially for questions that do not need retrieval (questions where standard RAG adds noise by bringing in irrelevant context).
GraphRAG
Microsoft Research brought out GraphRAG (Edge et al., 2024). The system makes a knowledge graph from the source documents and brings together graph traversal with vector retrieval.[9]
On queries that need synthesis across multiple documents or understanding of relationships between entities what the paper calls global queries rather than local fact lookups, GraphRAG performs much better than naive RAG.
On a large corpus of news articles and academic papers, GraphRAG scored substantially better on comprehensiveness and diversity than vector-only RAG did for question answering but at the price of much longer indexing time and more computation.
Common Failure Modes
Retrieval Failures
Getting accurate responses depends on the retriever finding the right documents. The generator can only produce them and common retrieval failures are as follows.
- False negatives: Relevant documents are in the knowledge base but are not retrieved, either because the embedding model does not capture the semantic relationship or because the chunks are too small or too large to match the query.
- False positives. Irrelevant documents get pulled in and go into context. They may mislead the generator or eat up context window capacity.
- Query-document mismatch. Users often phrase queries very differently from how information appears in documents. Embedding models that handle this translation imperfectly give poor retrieval.
Model Faithfulness Failures
Even with relevant documents retrieved, the generator may not use them faithfully:
- Hallucinating beyond the retrieved context. The model comes up with claims that are not backed by what was given and it goes back to using parametric memory.
- Ignoring contradictions. Contradictions in retrieved documents get ignored by the model as it produces responses.
- Lost-in-the-middle: Language models perform worse on information located in the middle of a long context compared to information at the beginning or end (2023) - important for RAG systems providing many retrieved documents. In experiments with GPT-3.5-Turbo and Claude, performance dropped by as much as 20 percentage points when relevant information was placed in the middle of a 20-document context versus at the beginning or end.[3]
Chunking and Context Problems
- Context fragmentation. A coherent argument or explanation that spans multiple paragraphs gets broken up into chunks and no single chunk gives the retriever enough context to match it to queries that need the whole argument.
- Context window overflow. When there are more retrieved documents than will fit in the context window and truncation follows and potentially relevant content gets lost.
Evaluating RAG Systems: The RAGAS Framework
A major advance in RAG engineering practice was the introduction of systematic evaluation systems and RAGAS (Retrieval Augmented Generation Assessment) is one that Es et al. (2023) brought in. This gives automated metrics to assess RAG pipeline quality across four dimensions.[6]
| RAGAS Metric | What It Measures | How It Works |
|---|---|---|
| Faithfulness | Does the answer stick to the retrieved context? | Checks if all claims in the answer can be attributed to the context |
| Answer Relevancy | Does the answer address the question? | Measures semantic similarity between answer and question |
| Context Precision | Are retrieved documents relevant? | Checks if retrieved documents actually contain information for the answer |
| Context Recall | Were all relevant documents retrieved? | Compares retrieved context against ground truth answers |
Context precision and faithfulness turn out to be the binding constraints in most production RAG systems as per RAGAS-based evaluation. The system brings back too many low-quality documents and the generator does not hold itself strictly to the retrieved context.
Building Production RAG Systems
The gap between a prototype RAG system (query, retrieve, generate) and a production RAG system is substantial. Production systems require:
Evaluation pipelines. These measure retrieval quality systematically through precision, recall and mean reciprocal rank and response quality by faithfulness to what was retrieved, answer relevance and groundedness. Automated evaluation systems come built into tools such as RAGAS.
Monitoring: Tracking retrieval latency, response quality metrics, and failure modes in production traffic.
Document update handling: Strategies for re-embedding and re-indexing documents when they change, without requiring full re-indexing of the knowledge base.
Access control. It is critical for enterprise deployments that have many user roles and sensitive document categories and making sure users get only the documents they have permission to see.
Real-World Deployment Scale
RAG had become a standard enterprise architecture at scale by 2024. Over 70% of enterprise AI deployments that got knowledge from retrieval were using some form of RAG pipeline, analysts at Gartner estimated.
Vector database vendors reported substantial growth: Pinecone reported over 100,000 developers using its platform by early 2024, and Weaviate, Chroma, and pgvector (the open-source PostgreSQL extension for vector similarity search) saw similarly rapid adoption curves.
RAG's production value is measured in part by Microsoft's Copilot, Salesforce's Einstein AI and ServiceNow's Now Assist all having RAG architectures at their core that combine proprietary enterprise data retrieval with large language model generation.
Latency Optimization
Retrieval quality has to be balanced against latency in Production RAG. Compared to direct model inference, the full pipeline that includes query embedding, vector search, optional reranking, context assembly and generation adds overhead. Optimization strategies include.
- Approximate nearest neighbor (ANN) search: Vector databases use ANN algorithms (HNSW, IVF, PQ) to find approximate matches much faster than exact search, with negligible quality loss at practical scales
- Embedding caching: Cache embeddings for frequently queried terms to avoid redundant embedding computation
- Asynchronous retrieval: Initiate retrieval while beginning to stream the initial response, updating it with retrieved context
- Tiered retrieval: Fast sparse retrieval for an initial candidate set, followed by dense reranking only on candidates
The Future of RAG
Long Context vs. RAG
Whether advances in language model context windows will eventually render RAG unnecessary is an active question in research. Models including Claude 3 (with a 200K token context window) and Gemini 1.5 Pro (up to 1 million tokens) have the capability in principle to take in whole knowledge bases directly as context without needing retrieval.
The research points to a nuanced relationship and RAG and long-context models are complementary, not competing.[11] When knowledge bases are very large (millions of documents), RAG stays essential for this reason. Even a 1M token window cannot hold everything.
Medium-sized knowledge bases that need precise information get retrieval errors reduced by long-context models. Even at smaller scales, RAG's ability to be updated keeps being an advantage for knowledge bases that change frequently.
"We find that both long-context models and RAG are imperfect at different failure modes. Long-context models can attend to any content they receive, but retrieving relevantly is still needed for very large corpora. RAG is efficient but relies entirely on retrieval quality.
The best systems combine both."
Xu et al., Retrieval Meets Long Context Large Language Models (2023)
Multimodal RAG
Beyond text, retrieval augmentation is spreading. Multimodal RAG systems pull in images, audio, diagrams and structured data along with text and give the generator richer evidence to work from. Applications include these.
- Medical imaging AI that retrieves similar cases from radiology archives before generating reports
- Legal research systems that retrieve and reason across case documents, statutes, and precedent together
- Manufacturing quality control systems that retrieve historical failure images alongside written specifications
Sources & Further Reading
- Lewis, P., Perez, E., Piktus, A., Petroni, F., Karpukhin, V., Goyal, N., Kuettler, H., Lewis, M., Yih, W., Rocktaeschel, T., Riedel, S., & Kiela, D. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. Advances in Neural Information Processing Systems, 33. View source
- Gao, Y., Xiong, Y., Gao, X., Jia, K., Pan, J., Bi, Y., Dai, Y., Sun, J., & Wang, H. (2023). Retrieval-Augmented Generation for Large Language Models: A Survey. arXiv preprint arXiv:2312.10997. View source
- Liu, N. F., Lin, K., Hewitt, J., Paranjape, A., Bevilacqua, M., Petroni, F., & Liang, P. (2023). Lost in the Middle: How Language Models Use Long Contexts. arXiv preprint arXiv:2307.03172. View source
- Karpukhin, V., Oguz, B., Min, S., Lewis, P., Wu, L., Edunov, S., Chen, D., & Yih, W. (2020). Dense Passage Retrieval for Open-Domain Question Answering. Proceedings of EMNLP 2020. View source
- Robertson, S., & Zaragoza, H. (2009). The Probabilistic Relevance Framework: BM25 and Beyond. Foundations and Trends in Information Retrieval, 3(4), 333-389. View source
- Es, S., James, J., Anke, L. E., & Schockaert, S. (2023). RAGAS: Automated Evaluation of Retrieval Augmented Generation. arXiv preprint arXiv:2309.15217. View source
- Asai, A., Wu, Z., Wang, Y., Sil, A., & Hajishirzi, H. (2023). Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection. arXiv preprint arXiv:2310.11511. View source
- Gao, L., Ma, X., Lin, J., & Callan, J. (2022). Precise Zero-Shot Dense Retrieval without Relevance Labels. arXiv preprint arXiv:2212.10496. View source
- Edge, D., Trinh, H., Cheng, N., Bradley, J., Chao, A., Mody, A., Truitt, S., & Larson, J. (2024). From Local to Global: A Graph RAG Approach to Query-Focused Summarization. arXiv preprint arXiv:2404.16130. View source
- Ovadia, O., Brief, M., Mishaeli, M., & Elisha, O. (2023). Fine-Tuning or Retrieval? Comparing Knowledge Injection in LLMs. arXiv preprint arXiv:2312.05934. View source
- Xu, P., Ping, W., Wu, X., McAfee, L., Zhu, C., Liu, Z., Subramanian, S., Bakhturina, E., Shoeybi, M., & Catanzaro, B. (2023). Retrieval Meets Long Context Large Language Models. arXiv preprint arXiv:2310.03025. View source






