<?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 Anaghaa Patil on Medium]]></title>
        <description><![CDATA[Stories by Anaghaa Patil on Medium]]></description>
        <link>https://medium.com/@anaghaavpatil?source=rss-5ca81b2c4d10------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NjK2uDnQAZqV2LH_9uG18w.png</url>
            <title>Stories by Anaghaa Patil on Medium</title>
            <link>https://medium.com/@anaghaavpatil?source=rss-5ca81b2c4d10------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:04:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anaghaavpatil/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[Beyond the Tutorial: Architecting a Production-Grade Hybrid RAG System]]></title>
            <link>https://medium.com/@anaghaavpatil/beyond-the-tutorial-architecting-a-production-grade-hybrid-rag-system-a791e3fd3b00?source=rss-5ca81b2c4d10------2</link>
            <guid isPermaLink="false">https://medium.com/p/a791e3fd3b00</guid>
            <category><![CDATA[retrival]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[pre-processing]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Anaghaa Patil]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 17:28:03 GMT</pubDate>
            <atom:updated>2026-03-12T17:29:04.915Z</atom:updated>
            <content:encoded><![CDATA[<h4>Designing ingestion pipelines and hybrid retrieval architectures for messy real-world documents.</h4><p>Most RAG tutorials stop at the basics: ingest text, embed it, search it. And honestly that&#39;s fine for a weekend project or a proof of concept you&#39;re showing a friend. But when you&#39;re dealing with real government policy documents scanned, fragmented, visually dense, full of tables and footnotes and inconsistent formatting those simple pipelines fall apart pretty quickly. What works in a Jupyter notebook does not hold up when the data starts fighting back.</p><p>This is what my collaborators and I ran into during a recent project. We were building a document ingestion and retrieval system for complex, multi-format government policy documents and the gap between &quot;tutorial RAG&quot; and &quot;production RAG&quot; became very obvious very fast. We worked on the data preprocessing pipelines together, while I focused on architecting the core hybrid retrieval logic. This article is my attempt to document the actual engineering decisions behind it ,not just what we built but why we built it the way we did.</p><h3>1. The Ingestion Engine: Handling Data Entropy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQnlkVAi1Tf8q-Bo55pA3A.png" /><figcaption>Preprocessing Pipeline</figcaption></figure><p>The first thing you learn when working with real documents is that data entropy is the enemy. Data in the wild is not clean. It does not arrive as nicely formatted text files. It arrives fragmented, partially scanned, rotated, packed with visual structure that plain text pipelines completely ignore. Tables, headers, multi-column layouts ,all of it gets flattened into noise the moment a naive parser touches it.</p><p>We designed our ingestion engine with two separate specialized paths to handle this reality.</p><h3>The Deterministic Path (Digital-Native PDFs)</h3><p>For standard, digitally-native PDFs we avoided the trap that catches most people early: character-based splitting. It feels intuitive to say &quot;split every 500 characters&quot; but the problem shows up downstream when your retrieval starts returning weirdly incomplete results.</p><p>The reason comes down to how embedding models actually work under the hood. Most use sub-word tokenization, meaning the model has its own internal sense of where meaningful units begin and end. If you blindly chop text at a fixed character count you regularly sever the semantic connection between words mid-thought. You end up with chunks that are syntactically broken and semantically ambiguous.</p><p>Our solution was <strong>NLTK-based sentence boundary detection</strong>. Instead of splitting by character count we split by sentence, then validated each chunk against the AutoTokenizer of the BGE-Small model we were using for embeddings. This ensured that every chunk going into the vector database was a self-contained, semantically intact unit. It sounds like a small detail but it meaningfully improved retrieval quality because the model was never trying to make sense of half a sentence.</p><h3>The Vision-AI Path (Scanned and Non-Textual Data)</h3><p>My collaborator led most of the work on this path and honestly it ended up being one of the most technically interesting parts of the entire project.</p><p>The problem with scanned documents is that standard OCR, even decent OCR, is fundamentally brittle. It treats a document as a flat grid of characters and has no real understanding of the structure underneath. For plain paragraphs this is fine. For anything more complex it starts breaking down fast.</p><p>Tables were the primary failure point. When traditional OCR processes a table it typically returns something that looks like the table got fed through a blender. Column headers end up separated from their values. Row relationships get scrambled. Numbers that were clearly associated with specific policies or departments come back as floating, context-free strings. Feeding that into a retrieval system and expecting the LLM to reason over it correctly is asking for trouble.</p><p>To handle this we built a custom Vision-AI pipeline using <strong>GPT-4o-mini</strong> and <strong>Llama 3.2 Vision</strong>. Rather than trying to extract raw text from these documents we sent them through vision models that could actually see the layout. The key engineering decision here was in how we structured the prompts. We specifically engineered the vision prompts to return output in <strong>Markdown format</strong>, forcing the model to preserve the spatial relationships between table headers and row values. That structure then carries through into the chunks that get embedded, which means the LLM querying the system later actually has the context it needs to perform logical reasoning on the data.</p><p>The other challenge was speed. Hitting a vision API for every image in a large document set adds up fast and we needed this pipeline to perform well enough for a live demo environment. The solution was parallelization. We wrapped the processing in a ThreadPoolExecutor which let us fire off multiple vision API calls concurrently rather than waiting for each one to resolve before starting the next. The reduction in ingestion time was significant enough that it went from being a bottleneck to being a non-issue.</p><h3>2. The Retrieval Architecture: Beyond Simple Vectors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyVKPpY9AlZZWK0wop4OCg.png" /><figcaption>RAG Pipeline</figcaption></figure><p>If the ingestion engine is about getting data in cleanly, the retrieval architecture is where you decide how intelligently the system can find it again. This is the part that I think most RAG tutorials genuinely underserve because vector search alone sounds like it should be enough. It isn&#39;t.</p><p>The core issue is that a single vector space cannot capture every nuance of a query. Semantic similarity is powerful but it is also lossy. It is great at understanding intent and finding conceptually related content. It is not great at precision. Ask it for a specific policy number and it will return things that are semantically close to that policy rather than things that actually contain that exact identifier.</p><p>For a system dealing with government documents where exact IDs, order numbers and regulatory references matter enormously, that is a serious problem. So I moved away from vector-only search and designed a <strong>Hybrid Retrieval Architecture</strong> built around three distinct retrieval signals.</p><h3>The Triple-Index Strategy</h3><p>The idea was to create three different &quot;views&quot; of the same underlying data, each optimized for a different kind of query:</p><p><strong>Semantic Similarity via BGE-Small</strong> handles the broad, intent-driven queries. When a user asks something like &quot;what are the conditions for exemption&quot; this index understands what they mean even if the exact phrasing doesn&#39;t appear in the documents. It captures conceptual relevance.</p><p><strong>Paraphrase Matching via MiniLM-L12</strong> acts as a secondary signal. Government and policy documents are full of domain-specific jargon and terminology that doesn&#39;t always map cleanly onto the language a user might use when querying. This model was specifically selected for its strength in recognizing paraphrased or reworded versions of the same idea, which provides a meaningful second opinion on relevance that the primary vector model sometimes misses.</p><p><strong>Lexical Precision via BM25 through Elasticsearch</strong> is the anchor of the whole system. BM25 is old technology by machine learning standards but it is exact. When a user queries a specific order number, a policy ID, a named regulation BM25 finds it if it exists. Vectors will fuzz around the right answer. BM25 will return the right document or tell you it isn&#39;t there. For a retrieval system where precision on identifiers matters this is non-negotiable.</p><p>Running all three in parallel gives the system a much more complete picture of what the user is actually looking for.</p><h3>The Reranking Layer</h3><p>Pulling results from three separate indexes generates a lot of candidate passages and not all of them deserve to make it to the LLM. Without a filtering step you end up flooding the context window with marginally relevant content which degrades the quality of the final answer.</p><p>To address this I implemented a <strong>Cross-Encoder Reranker using BGE-Reranker-Base</strong>. The distinction between a bi-encoder (which is what most embedding models are) and a cross-encoder is important here. A bi-encoder embeds the query and the document separately and compares the resulting vectors. A cross-encoder takes the query and the document together as a single input and scores their relevance jointly. This is computationally more expensive but significantly more accurate because the model can attend to the relationship between the query and the passage rather than treating them as independent objects.</p><p>The reranker processes every candidate passage from all three indexes, re-scores them based on actual relevance to the query and surfaces the top 24. This is the layer where the system transitions from &quot;retrieving documents&quot; to &quot;identifying answers.&quot; Everything below that threshold gets dropped before the LLM ever sees it.</p><h3>3. Engineering Lessons from the Trenches</h3><p>Some of the most important decisions in this system were not about model selection or architecture patterns. They were about reliability and what happens when things go wrong under pressure.</p><h3>Metadata-Aware Filtering</h3><p>Most discussions of RAG focus entirely on the retrieval layer but one of the most effective optimizations we made happened before retrieval even started. We stored rich metadata alongside every embedding: document type, issuing department, date, geographic scope and several other attributes depending on the document category.</p><p>Before the retrieval engine queries the vector database at all, it applies metadata filters to eliminate entire categories of irrelevant documents from the search space. If a query is clearly about a specific department&#39;s regulations there is no reason to search through documents from every other department. Narrowing the search space this way does two things. It makes retrieval faster. More importantly it reduces the chance of semantically similar but contextually irrelevant documents making it into the context window and causing the LLM to hallucinate or confuse details across documents.</p><p>Treating metadata as a first-class citizen in your retrieval design is one of the highest-leverage improvements you can make to a RAG system and it is one of the most commonly overlooked.</p><h3>The Fail-Safe Design</h3><p>The other lesson was about what happens when your infrastructure decides to stop cooperating at the worst possible moment. APIs hit rate limits. Network calls time out. Cloud services have their moments. In a controlled demo environment any of these failures can kill the whole presentation.</p><p>I built the system with a local fallback baked in from the start. If the primary cloud-based LLM encountered a rate limit or an error the system automatically detected the failure and rerouted the request to a locally running <strong>Ollama</strong> instance. The response quality changes slightly but the pipeline stays alive. For a demo context staying alive is more important than marginal quality differences.</p><p>This kind of defensive design gets deprioritized when you&#39;re moving fast but it is worth the time to build it in early. Failure modes are much easier to handle when you&#39;ve anticipated them than when you&#39;re debugging them live in front of an audience.</p><h3>Conclusion</h3><p>The thing this project reinforced most clearly for me is that RAG is fundamentally a <strong>data engineering problem</strong> dressed up in machine learning clothing. The retrieval pipeline, the ingestion quality, the metadata structure ,these determine the ceiling of what your system can actually do. The most capable LLM available cannot compensate for a retrieval layer that is returning the wrong context. Garbage in, garbage out applies at every stage of the stack.</p><p>By combining deterministic ingestion with vision-based processing for non-textual data and layering semantic, paraphrase and lexical retrieval signals under a cross-encoder reranking layer, we built a system that treats documents the way they actually exist in the real world: messy, visual, inconsistently formatted and full of structured data that naive pipelines destroy.</p><p>The full stack we used: GPT-4o-mini and Llama 3.2 Vision via Groq for vision processing, ChromaDB and Elasticsearch for storage, BGE-Small and MiniLM-L12 for embeddings, BGE-Reranker-Base for reranking, BM25 for lexical search and Python throughout with LangChain, Tenacity and Concurrent Futures handling the orchestration layer.</p><p>If you are currently building RAG systems that deal with complex PDFs or scanned documents I would genuinely love to hear how you are approaching table extraction and reranking in your own pipelines. These are the two areas where I think the field still has a lot of interesting unsolved problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a791e3fd3b00" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>