Zero Labs
Industry News / AI

Beyond Context Windows: Why AI Still Needs RAG

Source · Towards AI By Bassem Essameldin Omar

From the publisher’s feed, collected in the ZeroLabs newsroom.

Humans tend to give wrong answers when they lack information; likewise, AI models hallucinate when they are missing context. One of the dominant patterns for building context is Retrieval-Augmented Generation (RAG). RAG allows the model to retrieve relevant information from external data sources. Another form of context retrieval is AI agents, which use tools such as web search and database access to gather information.Photo by Clayton Robbins on UnsplashIn this blog, we will go through the main components of RAG systems and will dive deeper into the retrieval part, its algorithms, and the best practices in production applications.Why do we need RAG?With RAG, the most relevant information to the query is determined by the retriever and input into the model with the query to give the model more context, which helps the model respond with better answers without hallucinations. For example, given the query “Which mobile phone X or Y is better with respect to the battery lifetime?”, the model can give more accurate advice if it has the specification sheets for both phones.Think about RAG as a context contraction tool for foundation models, which is equivalent to feature engineering for classical machine learning models. Both have the same purpose: giving the model the information they need as an input to process.The context window for the new AI models such as Opus 5.5 is 1 million tokens, which is equivalent to 750,000 English words. This huge amount of context information that can be fed into the model can be enough to give the model the proper context to generate precise answers. Unfortunately, this is not true. We still need RAG for the following reasons. First, we still need longer context windows for many applications. Also, for many applications, the context length is expanding over time. Second, a long context window does not mean better performance. The longer the context, the more likely the model is to focus on the wrong part of the context. Third, a long context window means extra cost, and this implies higher latency.RAG ArchitectureAny RAG system consists of two main components: a retriever that extracts the important information from external resources and a generator that generates responses based on the retrieved information. In classical RAG systems, the retriever and the generative model are trained together. In today’s RAG systems, the two components are trained separately, and they are built using off-the-shelf retrievers and models. The generation component depends completely on the LLM model used in the system, while the retriever is the main component that influences the overall performance.A retriever has two main functions: indexing and querying. Indexing is to process the data in a way to be retrieved quickly. On the other hand, querying means sending a query to the retriever to get the most relevant data for the query.Now, let’s have an example of how RAG components work together. Assume that we have a database of documents. First, each document is split into smaller chunks. The size of the chunks is a crucial parameter to optimise the RAG system. Then, these chunks are indexed in a database to be accessed easily and efficiently. When a query comes to the RAG system, it retrieves the most relevant chunks using one or a mix of the retrieval algorithms. Finally, the retrieved chunks are combined with the original query to the system and sent to the generative model.We went through the main general concepts of RAG systems. Let’s dive deep into the retrieval techniques and how to evaluate them and optimize them.Retrieval AlgorithmsInformation retrieval is an old task in NLP, not unique to RAG. Information retrieval systems are widely used in search engines and recommendation systems. They are adopted in the retriever component in the RAG system. The retrieval algorithms can be categorised into two main categories: term-based retrieval and embedding-based retrieval.You might encounter different categories: sparse and dense retrieval. Sparse vectors are vectors where the majority of the values are 0. Term-based retrieval is considered sparse as it uses one-hot encoding vectors. The token is represented by 1 in the vector, while the other values are zeros, and the length of the vector is the vocabulary size. On the other hand, embedding-based retrieval is based on text embeddings, where each token is represented by a vector based on the semantic meaning, and the values are not zeros. Embedding-based retrieval is considered dense.Term-based RetrievalThe simplest way to retrieve the relevant document based on a query is to find all documents that contain query terms. For example, if we have a query containing “Artificial Intelligence”, we will get all documents that have “Artificial Intelligence”. This approach has many problems. First, the document might have the query terms in it but still lack the necessary information for the model to get the correct context. Second, this approach does not focus on the important tokens in the query that have the most informative content. Words like “the”, “at”, and “in” will distort the retrieval algorithm.Term Frequency — Inverse Document Frequency (TF-IDF) is an algorithm that combines two metrics: term frequency and inverse document frequency. The score of a document D for a query Q is computed, and the documents with the highest scores are retrieved. Two common term-based retrieval solutions are Elasticsearch and BM25.The main advantage of term-based retrieval algorithms is that they are fast and cheap, but they tend to work better when the query and the documents have similar lengths. If the documents are much longer than the query, the likelihood of them containing the query terms is higher, which leads to many documents having similarly high overlap scores.Embedding-based retrievalOne of the main problems in term-based retrieval techniques is that they lose the semantic similarity between the query and the document. For example, if the query contains the word “Transformers”, the retrieved documents might be about the electrical device, the movie, or the attention transformers. Embedding-based retrieval is based on vector embeddings that already carry the semantic meaning of the token. This makes the retrieval process more efficient. It captures “Transformers” documents that are more relevant to the context, whether it’s an electrical-related document, movie reviews, or AI-related documents.The embedding model converts the query first into an embedding using the same embedding model used during indexing. Then, the retriever fetches top-k chunks whose embeddings are closest to the query embedding. The retrieved chunks are sent to the generative model along with the query.Vector DatabaseA vector database simply stores the embedding vectors, but the hardest part is the vector search. The vectors have to be stored in a way that makes vector search fast and efficient.Vector search is typically a nearest-neighbour search problem. The classical k-nearest neighbours (k-NN), which works as follows:1- Compute the similarity scores between the query embedding and all vectors in the database using cosine similarity, for example.2- Return all vectors by their similarity scores.3- Return top-k vectors with the highest similarity scores.For large vector databases, the search is done using approximate matching with the Approximate Nearest Neighbour (ANN) algorithm. Some vector search algorithms are Facebook AI Similarity Search (FAISS), Google’s ScaNN (Scalable Nearest Neighbours), and Spotify’s Annoy. The vector databases are organised in a way that makes similar vectors close to each other.There are always trade-offs between indexing and querying. More details in the index mean better retrieval, but the indexing will be slower.High-Level Block Diagram of RAG system with Embedding-based RetrieverRetrieval Quality MetricsThe performance of the retrieval algorithm can be evaluated using the following metrics:Recall: The percentage of the nearest neighbours found by the algorithm.Query per second (QPS): The number of queries that the algorithm can handle per second.Build Time: The time required for building the index. This is important when the index is updated frequently.Index Size: The size of the index created by the algorithm.A practical approach in building real-world applications is to combine term-based retrieval and embedding-based retrieval. For example, a cheaper term-based retriever can get less precise candidates, and the more accurate ANN algorithm can get the most accurate relevant documents.Retrieval OptimizationSome techniques can be used based on the task at hand to improve the quality of the retrieval. There are mainly four techniques that optimise the retrieval quality.Chunking SizeThe simplest approach is to chunk the documents into equal lengths. Specific documents might need different chunking strategies. For example, Q&A documents can be split by question or answer pair, where each pair is a chunk.Overlapping chunks ensure that important information is included in at least one chunk. As a rule of thumb, the chunk size should not exceed the maximum context window of the model. Smaller chunks allow more diverse information for the model to generate better answers, while too small chunks can lead to the loss of important information. There is no standard for chunk sizes and overlapping. You should experiment with the RAG performance and choose the best for your use case.RerankingReranking the retrieved documents is useful when you need to reduce the context for the model. The order of the documents is important since the models tend to understand the documents at the beginning and end of the context.Query rewritingOne of the techniques that proved better results is to rephrase the query with different queries. Usually, a cheaper generative model can be used to rewrite the query and pass it to the model with the context. Also, it is crucial when the new query from the user is based on the older conversation. For example, if the query is “What about X?”, the query has to be written with the full question based on the old query.Contextual retrievalThe idea of contextual retrieval is to enrich each chunk with metadata or tags that help the model to retrieve the relevant information easily. In addition to that, you can generate a 50–100 token summary of the document and attach it to the chunks to prevent the chunks from losing the overall context of the document.ConclusionAs AI models continue to evolve, providing them with the exact right context remains the cornerstone of generating accurate, hallucination-free responses. While massive context windows offer exciting new possibilities, the precision, efficiency, and cost-effectiveness of Retrieval-Augmented Generation make it an indispensable architecture for production systems. By thoughtfully designing your retrieval strategy. From balancing sparse and dense search to fine-tuning chunk sizes and leveraging contextual metadata. You can transform raw data into highly actionable intelligence, ensuring your AI applications deliver reliable and relevant insights every time.ReferencesHuyen, C. (2024). AI Engineering: Building applications with foundation models. O’Reilly MediaBeyond Context Windows: Why AI Still Needs RAG was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.