<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rebai Mohamed on Medium]]></title>
        <description><![CDATA[Stories by Rebai Mohamed on Medium]]></description>
        <link>https://medium.com/@mohamedrebai748?source=rss-dc81b71d862d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0AEnsLTopSiWO7PEB7Thww.jpeg</url>
            <title>Stories by Rebai Mohamed on Medium</title>
            <link>https://medium.com/@mohamedrebai748?source=rss-dc81b71d862d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:19:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohamedrebai748/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unraveling RAG: How to build better systems?]]></title>
            <link>https://medium.com/@mohamedrebai748/unraveling-rag-how-to-build-better-systems-737731f924c4?source=rss-dc81b71d862d------2</link>
            <guid isPermaLink="false">https://medium.com/p/737731f924c4</guid>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rebai Mohamed]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 17:49:04 GMT</pubDate>
            <atom:updated>2025-04-13T18:01:42.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*f-Cps0LI4IMPCmdB1Oc2Ug.png" /></figure><p>With everything changing so fast in the AI landscape and new trends popping up every few days, RAG (Retrieval Augmented Generation) remains one of the most prevalent topics since its introduction in 2020 in the paper “Retrieval-augmented generation for knowledge-intensive NLP tasks”.</p><p>I believe that’s because RAG draws most of its principles from techniques that have been long used and battle tested in production.</p><p>Moreover, the beauty of RAG is in its modularity, each component is decoupled from the others in a way that makes it easily customisable. This allows us to easily build increasingly complex systems based on our needs.</p><p>But what is RAG really? Today we see some frameworks that offer you the possibility to write a RAG workflow in a matter of 10 lines of code. That is great for demonstration purposes but when faced with a real world challenge, many people get discouraged when it doesn’t work out of the box and may even abandon the idea altogether.</p><p>This technique, however, requires careful experimentation and tuning to our data and use cases to work properly. But before we do that, we need to demystify what is happening inside to build better RAG systems.</p><p>In this blog post, I try to demystify RAG and share some of my insights after exploring and implementing this technique on several occasions. Moreover I try to justify this using a series of controlled experiments I performed back when I was exploring RAG.</p><h3><strong>What is Retrieval Augmented Generation?</strong></h3><p>RAG is a very simple yet powerful idea. It’s a technique to ground LLM responses in your documents in order to reduce hallucinations by selectively injecting chunks of your data that are relevant to the query in the context.</p><p>RAG is basically composed of two main workflows: the indexation and the querying.</p><h4><strong>The Indexation workflow</strong></h4><p>This is where our documents get indexed to efficiently retrieve the most relevant chunks of data later. The documents first get pre-processed, then chunked, indexed then stored in a database. The database is usually a <strong>Vector Store </strong>(but it doesn’t have to be if we’re doing simple keyword retrieval)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ci8vDdpGcza79wmO5xPNaQ.png" /><figcaption>Indexation workflow</figcaption></figure><h4><strong>The querying workflow</strong></h4><p>This is how our system handles user queries. First, our system retrieves the most relevant chunks to the user query from the database, injects them in the prompt with the user query then gives the final payload to the Large Language Model which generates the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wBgr_f1EVsRa0NvmYDZxg.png" /><figcaption>Querying Workflow</figcaption></figure><h3>Experimental setup</h3><p>This section just details the context and tools used for the experiments that I’m about to use in the later section. If you’re unfamiliar with RAG, I suggest you skip this for now and come back to it later.</p><p>For the experiments I am using:</p><ul><li><a href="https://huggingface.co/sentence-transformers/all-MiniLM-L12-v2">all-MiniLM-L12-v2</a> the an embedding model.</li><li><a href="https://huggingface.co/cross-encoder/ms-marco-MiniLM-L6-v2">ms-marco-MiniLM-L6-v2</a> as the reranker.</li><li>PostgreSQL as the vector store with the <strong>pgvector</strong> extension enabled</li><li><a href="https://rajpurkar.github.io/SQuAD-explorer/">The Stanford Question Answering Dataset</a> which is comprehensive QA dataset on several Wikipedia articles. It covers several topics, within each topic there are several paragraphs (documents). For each document, there are several questions pertaining to it as well as the position of the answer in the document.</li><li>For chunking I used the <a href="https://python.langchain.com/v0.1/docs/modules/data_connection/document_transformers/recursive_text_splitter/">Recursive Text Splitter algorithm</a>.</li><li>For evaluation, I used a very simple metric commonly used in retrieval: <strong>MRR (mean reciprocal rank). </strong>This metric is only concerned with the rank of the first relevant chunk to the query. The metric is closer to one if, on average, the right document is the first search result and is less in the opposite case.</li></ul><h3>Some Insights</h3><h4>Processing data</h4><p>One of the most common pitfalls people fall into when first trying to implement RAG is that they usually do not give much importance to the first step which is processing the documents for later indexation. In my opinion, this is the most important step.</p><p>We first need to understand our data and our use cases:</p><ul><li>What is the data about?</li><li>Are the contents relevant to the use cases of the system?</li><li>What is the format of the data? Is it in Markdown, HTML?</li><li>What modalities does it contain? Does it contain images, tables?</li><li>How should I chunk my data?</li><li>How will the queries look like?</li></ul><p>All of these questions actually lead to several techniques we can implement that can <strong>significantly</strong> enhance the performance of our system. I could talk about this all day (maybe I’ll even write an article about this) but let me give you a simple example of what I’m talking about.</p><p>The example I’m about to show is about chunking. <strong>Chunking</strong> is the process of dividing our data into sections that are <strong>syntactically sound </strong>and<strong> semantically coherent.</strong></p><p>We explore the effect of two parameters: <strong>chunk size</strong> and <strong>chunk overlap</strong> described in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*oJcY77WVPLqzplnhCk0irA.png" /></figure><p>We first compare the retrieval accuracy using chunk overlap vs no overlap. It is apparent that overlap increases the accuracy of our retrieval since our chunks are now more contextualized which helps with some of the queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*mo1c90nR-bJ2iWt5WIF1NQ.png" /><figcaption>Effect of overlap on retrieval accuracy</figcaption></figure><p>We then vary the size of chunks (in number of characters) while monitoring retrieval accuracy (MRR). We find the following results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*6lfsvywhUSF8R1DYThTorw.png" /><figcaption>Effect of chunk size on retrieval accuracy</figcaption></figure><p>This behavior is consistent across most vector retrieval tasks. Small chunks lack relevant context to the queries while very big chunks are too general to be directly useful to the query. When chunking your data, you need to find that sweet spot.</p><p><strong>Important note:</strong> the actual values (for the best chunk size) might vary depending on your data and your queries.</p><p>This is just an example with generic results. However, when implementing a RAG system in a real life scenario, understanding your data and how to process it is one of the most crucial tasks. Experimenting with different techniques and choices is very important to adapt the system to your particular use case.</p><h4>Retrieval</h4><p>The indexation usually happens using an <strong>embedding model</strong>, this turns the chunks into <strong>embeddings. </strong>An embedding is simply a vector (a big array of numbers) which encodes the semantic meaning of the data.</p><p>To put it simply, if the meaning of two documents is close then the distance between their vectors will be small. I’ll leave the details of this to another article. For now, this is all we need to know.</p><p>These embeddings are then stored in a vector database which manages the space of our vector (called <strong>the latent space</strong>) for efficient retrieval.</p><p>However, if you think about it, using embeddings and vector based search is optional. In fact, at a high level, we just need a retrieval mechanism. This could be anything from simple keyword search to vector search to combinations of the two (hybrid search).</p><p>We also use a <strong>reranker model</strong> sometimes to further refine the ranking of the search results after getting candidates from our preferred search mechanism.</p><p><strong>Note : </strong>You might ask, if this model can rank results in a better way, why don’t we just use it in the first place. Well it’s because of the computational complexity of this model compared to the other search mechanisms. If you have a lot of data (which is usually the case for RAG systems), it would take forever to retrieve the relevant chunks if we use a reranker.</p><p>We explore the effects of different retrieval mechanisms on our use case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*-YI4awtDS2JorvCgUxTw4w.png" /></figure><p><strong>Important: </strong>I want to stress that the takeaway of this experiment is not that this retrieval mechanism is definitely better that the other. In some other usecases, keyword search might even perform better than vector search.</p><p>All of the choices we make are trade-offs, <strong>there are no free gains.</strong> Adding a reranker or several search mechanisms might give you better accuracy but will significantly impact your search latency.</p><p>One such trade-off is the number of candidate results to fetch from your search mechanism to later be reranked. Getting more candidate results gives us better accuracy but it impacts the performance of the system due to the computational complexity of the reranker. If you value latency, this might be a bad idea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*XPFDqWV_ukMt90yJjfv9qg.png" /></figure><h4>Generation</h4><p>After having retrieved our documents, now it’s time to generate a response for our end user using those documents. There are several things we need to keep in mind when working on this step.</p><p>First, it’s important to understand that the retrieval step and the generation step are <strong>entirely decoupled</strong>. In some cases, the retrieved content and injected content are entirely different things.</p><p>One example that comes to mind is when working on RAG in the context of FAQs. Instead of embedding the documents, we can use an LLM to generate questions about the document chunks and embed these instead with a link to the original document which we inject in the generation step.</p><p>Another example is enriching the retrieved chunks with context from before and after the chunk to give it more context.</p><p>Second, several considerations arise when choosing which model to use:</p><ul><li>Will I be using a third party provider? Is data privacy going to be an issue?</li><li>Will I host the model myself on the cloud or run it on an edge device? In that case, what are my computational constraints and how can I get the best of my RAG system?</li></ul><p>Moreover, we need to make sure that our model behaves well when:</p><ul><li>We ask it something that it does not know and could not figure out from the documents. The model should not hallucinate an answer</li><li>We ask it to do something off topic. We need to make sure that it simply apologizes and does not reply to something outside the confines of our usecase.</li></ul><p>Finally, some queries might need the model to reason or look at multiple documents to synthesize an answer. In some cases, we might give the LLM the agency to request and query the data whenever it needs it as a tool.</p><h4><strong>Conclusion</strong></h4><p>Whatever it is you’re doing with your RAG system, you’re going to be facing difficult choices and trade-offs and you should have a basis for making these decisions when you’re designing and experimenting with your system.</p><p>That is why <strong>evaluation</strong> is one of the most important phases of working on a RAG system. The evaluation of these systems is tricky, since there isn’t a single measure that’ll tell you if what you’re doing is working or not.</p><p>Instead, you need to define the <strong>metrics</strong> that you care about and evaluate different parts of your systems (retrieval accuracy, latency, answer quality…) in order to make justifiable choices. This evaluation should also continue in your production environment so make sure to have some monitoring ready in order to understand how your system is being used to be able to iterate and make your system better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=737731f924c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>