Retrieval-augmented generation (RAG) lets a language model answer from documents that you give it, so its answers can be more accurate, more up to date, and backed by sources.
The motivation
Autoregressive LLMs have three well-known limitations. They sometimes state made-up information with full confidence. They can't point to the sources of their answers, because they are trained to predict the next token from huge amounts of unstructured, unindexed text. And their knowledge stops at a training cutoff date, so they know nothing about later events.
Retrieval-augmented generation, or RAG, was introduced in 2020 to deal with these problems. It combines traditional indexing and search with an autoregressive model. The model answers from the documents that the search finds, so its answers are more accurate and can cite sources, and you can give it new or private information without retraining the LLM.
You could also fine-tune the LLM on your documents, but apart from needing powerful hardware, fine-tuning has other drawbacks:
LLMs typically struggle to learn new factual information through unsupervised fine-tuning
RAG, on average, produces better results than fine-tuning for incorporating new information.
For example, say your organization's documents are scattered across GitLab, ReadTheDocs, Word files, and Notion. You want one interface where an LLM can search these documents, summarize them, suggest improvements, or fix errors in them. This is a typical use case for RAG.
The naive RAG
The most basic RAG setup is called the naive RAG:
It has three main steps: indexing, retrieval, and generation.
The indexing step starts by converting the data into plain text. The data often comes in many formats: mostly text formats, but sometimes also images or other non-text data, which take more work. Then the plain text is chunked, that is, split into pieces that are typically 256 to 512 tokens long. There are two reasons for chunking:
Smaller pieces make retrieval more precise: the search can return only the relevant part of a document and collect relevant parts from several documents.
An LLM has a context window that limits how much text it can take in at once, and an embedding model has a maximum input length. Chunks fit within both limits.
Each chunk is then passed to an embedding model, which turns it into a vector (an embedding), and the embeddings are loaded into a vector database.
The indexing phase looks like this:
During retrieval, the user's query is turned into an embedding by the same model that indexed the documents. The vector database computes the similarity (a measure of distance) between the query embedding and the stored embeddings and returns the k most similar chunks, where k is a small number, often 5.
During the generation step, the original query and the most similar chunks are combined into a prompt, which is sent to the LLM. The prompt can tell the model to answer only from the retrieved chunks or let it also use its own knowledge.
The advanced RAG
The naive approach has weak spots. Real-world queries can be convoluted, with several distinct questions in one query. The broader the query, the harder it is to match it to the relevant chunks, so the naive RAG doesn't handle such queries well.
For example, the following query:
What are the environmental and economic impacts of electric vehicles compared to traditional cars, considering both manufacturing and long-term usage, and how does this vary across different countries?
is likely to fail with the naive RAG. It covers five aspects (environment, economy, manufacturing, usage, and differences between countries), and the answer may need several sources.
Another problem is relevance: the naive RAG can't tell which details of a query matter most. A query like this one:
What are the side effects of ibuprofen?
might match many different side effects and mix common and rare ones in a single response, skip how severe and frequent they are, or include irrelevant or contradictory information.
The advanced RAG deals with these problems by improving retrieval with pre-retrieval and post-retrieval optimizations.
Pre-retrieval optimizations
Pre-retrieval optimizations are of two types. Query-side optimizations turn the original query into one or more search queries that are more likely to find relevant information in the vector database. Index-side optimizations change how documents are processed, chunked, embedded, and organized in the database. This topic covers only the query side.
One query-side approach is query rewriting, which converts the query into a form that works better for search. You can rewrite queries with a prompt to an LLM, either zero-shot (just ask for reformulations) or few-shot (show examples of queries and their rewritten forms), or with a separate model fine-tuned for this task.
The electric vehicle query from the previous section can be split into several questions ('What are the environmental impacts of manufacturing EVs?', 'What are the environmental impacts of manufacturing traditional cars?', and so on). This strategy is called multi-query RAG, and the requests to the database can run in parallel.
Multi-hop RAG is for queries that break down into a chain of steps, where each answer leads to the next query. The following query takes two hops: first, find out who created Python (Guido van Rossum), and then, where he studied:
Which university did the creator of the Python programming language graduate from?
Post-retrieval optimizations
Post-retrieval optimizations also come in two kinds: chunk re-ranking and context processing.
Chunk re-ranking scores the retrieved chunks again, more carefully, by how relevant they are to the query. The first retrieval usually relies on vector similarity, while re-ranking uses methods such as cross-encoders or hybrid scoring, which you'll meet in later topics. All major RAG frameworks support re-ranking (here is an example from LangChain).
Context processing deals with the limited context window. If all relevant chunks go into the prompt, the less relevant ones can distract the model. The usual fix is to keep only the most important information and shorten the context, for example, by summarizing it.
Conclusion
RAG gives an LLM documents to answer from. This reduces hallucinations, makes sources traceable, and brings in information that the model wasn't trained on.
The naive RAG has three steps: indexing (chunk the documents and store their embeddings), retrieval (find the chunks closest to the query), and generation (answer from those chunks).
The advanced RAG adds optimizations before retrieval, such as query rewriting, multi-query, and multi-hop RAG, and after it, such as re-ranking and context processing.