<?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 Venu Thottempudi on Medium]]></title>
        <description><![CDATA[Stories by Venu Thottempudi on Medium]]></description>
        <link>https://medium.com/@vthottempudi1?source=rss-63881e1e0761------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tfEQDhH2kNZlzHiEcE8j6w.png</url>
            <title>Stories by Venu Thottempudi on Medium</title>
            <link>https://medium.com/@vthottempudi1?source=rss-63881e1e0761------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:08:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vthottempudi1/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[Enterprise Advanced RAG · Article 5 of 5]]></title>
            <link>https://ai.plainenglish.io/enterprise-advanced-rag-article-5-of-5-22eaeeb42c59?source=rss-63881e1e0761------2</link>
            <guid isPermaLink="false">https://medium.com/p/22eaeeb42c59</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Venu Thottempudi]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 19:20:06 GMT</pubDate>
            <atom:updated>2026-09-11T19:20:06.734Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyIAzUiZgfwZ3zUAe0vATg.png" /><figcaption>Diagram created with Claude.ai (Anthropic)</figcaption></figure><p><strong>Enterprise Advanced RAG · Article 5 of 5</strong></p><h3>Beyond Top-K: Evidence-Family Retrieval for Complete RAG Answers</h3><p><em>When five relevant chunks still cannot answer the whole question</em></p><p>A RAG system can retrieve five relevant chunks and still lack the evidence needed to answer the whole question.</p><p>That sounds contradictory — until the question contains several separate evidence obligations.</p><p>Consider:</p><blockquote><em>How should application configuration, credentials, and workload permissions be managed together?</em></blockquote><p>A retriever might return five excellent passages about configuration. Every passage is relevant. The context is still incomplete if it contains nothing about credentials or permissions.</p><p>This is a weakness of ordinary top-k retrieval: <strong>it optimizes the rank of individual chunks, not coverage of the answer’s required concepts.</strong></p><p>In Enterprise Advanced RAG, I addressed this with <strong>evidence-family planning</strong>. Instead of asking only “Which chunks score highest?”, the retrieval pipeline also asks:</p><blockquote><em>Which distinct kinds of evidence must survive into the final context?</em></blockquote><p><strong>Scope note:</strong> The case study uses a Kubernetes and incident-operations corpus. The reusable idea is family-aware evidence coverage. The source patterns and domain vocabulary must be redesigned for each corpus.</p><h3>Top-K Relevance Is Not Evidence Completeness</h3><p>A conventional retrieval pipeline produces a ranked list and keeps the first k chunks. That works well when one evidence type can answer the question. It becomes fragile when the question requires comparison, synthesis, or several sources of truth.</p><p>Suppose all five top-ranked chunks discuss Secrets, but the answer requires Secret handling, ServiceAccount identity, and RBAC authorization. The ranking is locally reasonable and globally incomplete.</p><p>Increasing top_k may help, but it is not a reliable solution. A larger context can add duplicates, noise, latency, and cost without guaranteeing that the missing concept appears. If one source family dominates the candidate distribution, it may occupy the first 20 positions.</p><p>The retrieval objective needs a coverage constraint:</p><pre>Useful context = relevance + required-family coverage + trusted provenance - noise</pre><p>Evidence-family retrieval adds that constraint without discarding ordinary relevance ranking.</p><h3>What Is an Evidence Family?</h3><p>An evidence family is a group of sources or passages capable of satisfying one evidence obligation in a question. It is not necessarily one file, one topic label, one embedding cluster, one retrieval strategy, or one chunk.</p><p>For a question about exposing an application safely, the families might be Ingress routing, Service discovery, and Readiness behavior. Several documents may be acceptable members of the Service family. A single document may even support more than one family if its metadata and content justify that classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JXMJl4cDq1W-QwLmfBzjw.png" /><figcaption>These three identities must remain separate. Confusing them causes subtle retrieval errors — deduplication bugs, context flooding, and trust failures.</figcaption></figure><h3>Evidence Planning Comes Before Final Selection</h3><p>The project uses a deterministic evidence planner for recognized composite question shapes. Conceptually, the planner returns a list of (source_pattern, rescue_query) pairs — one per required family:</p><pre>def evidence_plan(question: str):<br>    # Returns list of (family_pattern, rescue_query) tuples<br>    # for recognized composite question shapes<br>    if asks_about_workload_identity(question):<br>        return [<br>            (SECRET_SOURCE_PATTERN,      &quot;Kubernetes Secret credentials Pod&quot;),<br>            (SERVICE_ACCOUNT_PATTERN,    &quot;Pod ServiceAccount workload identity&quot;),<br>            (RBAC_SOURCE_PATTERN,        &quot;RBAC least privilege RoleBinding&quot;),<br>        ]<br>    return []  # unknown shapes continue through normal retrieval</pre><p>This is deliberately narrower than open-ended autonomous planning. Known high-value question shapes get predictable coverage rules. Questions outside those shapes continue through normal retrieval.</p><p><strong>Key operational property:</strong> a plan can be inspected and tested. When a family is missing, the team can determine whether the problem came from question detection, source classification, candidate retrieval, reranking, filtering, or final truncation.</p><h3>How Family Membership Is Recognized</h3><p>The case-study implementation identifies family membership by matching a regular expression against the chunk’s source name:</p><pre>pattern.search(str(chunk.source))</pre><p>This is not semantic clustering — it is a deterministic source contract. The benefit is precision and auditability: a document either matches the declared family or it does not. The limitation is maintenance: renamed files or new document collections require updated mappings.</p><p>A reusable platform should prefer explicit metadata over filename patterns:</p><pre>{<br>  &quot;source&quot;: &quot;security-policy.pdf&quot;,<br>  &quot;document_id&quot;: &quot;doc-123&quot;,<br>  &quot;chunk_index&quot;: 17,<br>  &quot;evidence_family&quot;: &quot;access-control&quot;,<br>  &quot;authority_tier&quot;: &quot;official&quot;,<br>  &quot;version&quot;: &quot;2026-07&quot;<br>}</pre><p>Family membership then becomes a simple metadata lookup: chunk.metadata[&quot;evidence_family&quot;] == required_family</p><h3>Missing Families Trigger Targeted Rescue</h3><p>After initial retrieval, the pipeline counts matching candidates for each planned family. When a family falls below the desired candidate count, a targeted sparse search fires using the family’s rescue query:</p><pre>for family_pattern, rescue_query in plan:<br>    matches = [c for c in candidates if family_pattern.search(c.source)]<br><br>    if len(matches) &lt; desired_candidate_count:<br>        # Targeted rescue — bounded, not an open retry loop<br>        rescued = sparse_search(rescue_query, top_k=wide_limit)<br>        candidates.extend(<br>            c for c in rescued if family_pattern.search(c.source)<br>        )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9tKI0LmAucreIb_VW5YXw.png" /><figcaption>Rescue fires only for missing families, using a focused query tied to the family contract. Multiple candidates are retrieved so the reranker can select the strongest — not the first available passage.</figcaption></figure><h3>Reranking Chooses the Best Passage, Not the Family</h3><p>Evidence planning answers which families must be represented. Reranking answers which available chunks best address the question. Those are complementary decisions.</p><p>The project’s reranker blends:</p><pre>0.4 × normalized cross-encoder score<br>+ 0.3 × normalized retrieval score<br>+ 0.3 × lexical overlap<br>+ conditional exact-token bonus</pre><p>Once candidates are ranked, family-aware selection reserves the highest-ranked matching chunk from every required family. Remaining context slots are filled by global rank:</p><pre>selected = []<br><br># Step 1: reserve best chunk per required family<br>for family in required_families:<br>    best_match = first_ranked_match(family, ranked_chunks)<br>    if best_match:<br>        selected.append(best_match)<br><br># Step 2: fill remaining slots by global rank<br>selected.extend(c for c in ranked_chunks if c not in selected)<br><br>final_chunks = selected[:top_k]  # constrained top-k, not an alternative to ranking</pre><h3>Why Same-Source Chunks Sometimes Need to Survive Together</h3><p>Early family-aware selection can make a mistake: deduplicating by filename. Suppose one NetworkPolicy document contains separate passages for default-deny behavior, ingress rules, and egress rules. A composite question may need all three. If selection permits only one chunk per filename family, two required passages disappear.</p><p>The correct deduplication policy depends on the evidence obligation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avMpG6Tr8Gwjc_yfQWpD-w.png" /><figcaption>Deduplication should reduce redundancy without destroying coverage. The same source can contribute multiple complementary passages when each satisfies a distinct obligation.</figcaption></figure><h3>Authority and Relevance Are Different Signals</h3><p>A noisy research paper can be semantically similar to a production question. A generic dashboard guide can share many query terms. Neither should displace an approved operational runbook when the runbook directly answers the question.</p><pre>Relevance:  Does this passage discuss the question?<br>Authority:  Is this an approved source of truth?<br>Coverage:   Which required evidence obligation does it satisfy?</pre><p><strong>One score should not silently stand in for all three.</strong> Authority metadata must survive ingestion, retrieval, fusion, reranking, caching, and API serialization — not just be stored in the vector database.</p><h3>CRAG Should Correct Retrieval Without Breaking Coverage</h3><p>Corrective RAG grades retrieved chunks and can retry when evidence looks weak. That improves precision, but it can conflict with evidence planning. An individually narrow passage may look only somewhat relevant in isolation while remaining essential to a multi-document synthesis. If CRAG removes it, the final answer loses a required family.</p><p>The implementation resolves this by treating a validated evidence plan as a domain policy. After CRAG filtering, it performs a fresh wide search for each planned family and selects the strongest authoritative passage. The order matters:</p><pre>Retrieve broadly<br>→ shape and rerank candidates<br>→ reserve family coverage<br>→ grade evidence (CRAG)<br>→ restore validated required families<br>→ build context</pre><h3>A General Architecture for Other RAG Projects</h3><p>A mature design can use multiple planning levels — choose based on how well the question shape is known:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxs0YfLjw90ynpuOKzx4fg.png" /><figcaption>Level 1 deterministic rules handle high-risk or regulated shapes with full auditability. Levels 2 and 3 add flexibility for broader domains and novel composite questions — always validated against a controlled taxonomy.</figcaption></figure><h3>The Full Evidence-Family Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kthVAkUE1eZq84BPLVTogg.png" /><figcaption>Seven stages, each with a distinct objective. Planning and rescue add coverage; reranking and authority enforcement add precision and trust. None of the stages replaces the others.</figcaption></figure><h3>The Pattern Transfers Across Domains</h3><p>Evidence families are not specific to Kubernetes. Any domain where a complete answer requires contributions from distinct source types can benefit from this architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBm7apPoN4xjXTsBcrOX4g.png" /><figcaption>Consider a financial assistant asked “Is this transfer allowed, and what approval is required?” Five relevant policy passages cannot compensate for missing account data. Evidence-family planning makes those obligations explicit.</figcaption></figure><h3>Evaluation Must Measure Family Coverage</h3><p>Chunk relevance alone cannot verify a family-aware retriever. A simple family-recall metric makes the gap visible:</p><pre>Evidence-family recall = covered required families / total required families<br><br># Example: Secret + RBAC covered, ServiceAccount missing<br>Evidence-family recall = 2/3 = 0.67<br><br># This failure is invisible to standard chunk-relevance metrics</pre><p>Tests should also cover: missing-family rescue, preservation through reranking, preservation through CRAG, acceptable alternative sources, complementary chunks from one document, authority filtering, top-k smaller than the number of required families, and questions that should not trigger a plan.</p><h3>Failure Modes to Expect</h3><ul><li><strong>Planner triggers too broadly</strong> — A generic keyword activates an unrelated family plan. Use phrase combinations and negative cases.</li><li><strong>Plan is incomplete</strong> — System retrieves declared families but still cannot answer. The missing concept belongs in the plan and regression coverage.</li><li><strong>Source naming changes</strong> — Regex-based membership silently stops matching. Corpus-contract tests should verify planned families resolve to existing sources.</li><li><strong>Rescue queries overfit evaluation questions</strong> — Write queries around domain concepts; validate with paraphrases and sealed holdouts.</li><li><strong>Family reservation preserves weak evidence</strong> — Retrieve multiple candidates per family and rerank before reservation. Authority and minimum-relevance checks still apply.</li><li><strong>Too many families exceed the context budget</strong> — The planner must prioritize, merge compatible evidence, or ask for clarification.</li><li><strong>Model ignores part of the evidence</strong> — Complete retrieval does not guarantee complete synthesis. Generation prompts and faithfulness checks must reflect the evidence plan.</li></ul><h3>What I Would Improve Next</h3><ol><li>Move family identity from filename patterns into versioned chunk metadata</li><li>Define a domain evidence taxonomy with owners and authority rules</li><li>Add a constrained structured planner for novel composite questions</li><li>Calibrate minimum relevance separately for each family</li><li>Optimize selection jointly for relevance, coverage, redundancy, and token budget</li><li>Expose the evidence plan and family coverage in tracing metadata</li><li>Evaluate planner precision as well as family recall</li><li>Test corpus drift and renamed-source failures automatically</li><li>Compare deterministic, classifier-based, and LLM-based planning on sealed holdouts</li><li>Add explicit uncertainty when a required family cannot be found</li></ol><p>The goal is not to make retrieval more complicated for every query. It is to spend additional work only when a question genuinely requires several kinds of evidence.</p><h3>Final Takeaway</h3><p>Top-k retrieval answers: <em>Which chunks appear most relevant?</em></p><p>Evidence-family retrieval adds a second question: <em>Does the final context contain every kind of evidence required for a complete answer?</em></p><p>That distinction matters whenever a user asks for comparison, policy application, diagnosis, or synthesis across sources.</p><blockquote><strong><em>Relevance</em></strong><em> determines whether a chunk is useful.<br></em><strong><em>Authority</em></strong><em> determines whether it should be trusted.<br></em><strong><em>Evidence-family coverage</em></strong><em> determines whether the answer can be complete.</em></blockquote><blockquote><em>A production RAG system needs all three.</em></blockquote><h3>Project Links</h3><ul><li>Repository: [<a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT">GitHub repository URL</a>]</li><li>Video: [<a href="https://www.youtube.com/watch?v=HrO3jyu4EYw&amp;t=400s">Evidence-family retrieval walkthrough URL</a>]</li><li>Project overview: [<a href="https://medium.com/ai-in-plain-english/building-an-enterprise-grade-advanced-rag-system-what-it-took-beyond-the-demo-3f30e2025dad">Enterprise Advanced RAG overview URL</a>]</li><li>Article 2 — Routing RAG, SQL, and Hybrid: [<a href="https://medium.com/ai-in-plain-english/most-enterprise-ai-assistants-begin-with-a-deceptively-simple-interface-one-text-box-94aa92106767">URL</a>]</li><li>Article 3 — Retrieval Pipeline, Chunking, Reranking: [<a href="https://medium.com/ai-in-plain-english/retrieval-is-a-pipeline-sentence-aware-chunking-hybrid-search-and-reranking-43a289c9c41f">URL</a>]</li><li>Article 4 — Evaluating RAG Without Fooling Yourself: [<a href="https://medium.com/ai-in-plain-english/evaluating-rag-without-fooling-yourself-article-4-of-5-d29c80231aff">URL</a>]</li></ul><p>#RAG#InformationRetrieval#LLM #AIEngineering#MLOps#EnterpriseAI#Python</p><p>Venu Thottempudi</p><p>AI Engineer | AI Architect | Enterprise RAG &amp; Multiagent Systems</p><p>Connect on LinkedIn: <a href="https://www.linkedin.com/in/venu-thottempudi-34014ba3/">linkedin.com/in/venu-</a>thottempudi</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22eaeeb42c59" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/enterprise-advanced-rag-article-5-of-5-22eaeeb42c59">Enterprise Advanced RAG · Article 5 of 5</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating RAG Without Fooling Yourself · Article 4 of 5]]></title>
            <link>https://ai.plainenglish.io/evaluating-rag-without-fooling-yourself-article-4-of-5-d29c80231aff?source=rss-63881e1e0761------2</link>
            <guid isPermaLink="false">https://medium.com/p/d29c80231aff</guid>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Venu Thottempudi]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 23:29:49 GMT</pubDate>
            <atom:updated>2026-08-25T23:29:49.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlS_Z6jkFoIyfFJ_1slJgA.png" /><figcaption>Diagram created with Claude.ai (Anthropic)</figcaption></figure><p><strong>Enterprise Advanced RAG · Article 4 of 5</strong></p><h3>Evaluating RAG Without Fooling Yourself</h3><p><em>Source Precision, Source Recall, and Sealed Holdouts</em></p><p>A RAG system can produce a correct-looking answer while retrieving the wrong evidence.</p><p>It can also retrieve one excellent source and still miss another source required to answer the whole question.</p><p>Those two failures may look similar in a demo. They are very different in evaluation.</p><p>This was one of the most important lessons from building Enterprise Advanced RAG. Early scorecards could hide several problems:</p><ul><li>a noisy chunk accompanied a correct source</li><li>a required complementary source was missing</li><li>fuzzy filename matching credited the wrong document</li><li>a cached response made a changed retriever look better than it was</li><li>an LLM judge varied across equivalent evidence</li><li>a repeatedly inspected “holdout” was no longer unseen</li></ul><p>The solution was not one more judge prompt. It was a layered evaluation contract combining deterministic source precision and recall, expected-route checks, forbidden-answer and forbidden-source checks, LLM-judged faithfulness, versioned datasets, sealed-holdout discipline, and per-question failure review.</p><blockquote><em>The goal was not to make a dashboard display all ones. The goal was to make the results harder to misinterpret.</em></blockquote><p><strong>Scope note:</strong> The evaluated implementation uses a Kubernetes and incident-operations corpus. Source precision, source recall, holdout discipline, route checks, and cache-safe evaluation apply to any RAG system with known evidence sources — including legal, healthcare, finance, support, research, and internal enterprise search.</p><h3>Document Ratio and Chunk Ratio Measure Different Difficulty</h3><p>Calling a corpus “noisy” is incomplete unless the unit of measurement is stated. A collection may contain one authoritative document for every six distracting documents, yet those distracting documents may be much longer and generate many more chunks. Retrieval operates over chunks, so the effective competition can be substantially harder than the document count suggests.</p><p>In the audited case-study corpus, 49 authoritative and 314 noisy sources produced 1,471 authoritative chunks and 32,949 noisy chunks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7s2grnF2qZvpg2bgYJ3vlw.png" /><figcaption>The chunk view reveals 3.5× harder competition than the document count implies. Always publish both ratios.</figcaption></figure><p>These numbers are properties of this corpus version, not a universal benchmark. Their broader value is methodological: publish both ratios. Document counts describe governance; chunk counts describe the candidate space faced by retrieval.</p><p>The noisy material represents conditions that appear unintentionally in real systems: obsolete procedures, near-duplicates, unapproved drafts, generic vendor documentation, and unrelated content from shared repositories. A clean demo corpus shows that retrieval works. A distractor-heavy corpus tests whether it fails safely.</p><h3>Answer Quality and Retrieval Quality Are Different</h3><p>Suppose a question asks:</p><blockquote><em>“An employee works in a region with a statutory carryover exception. How many unused vacation days can be carried forward, and which exception applies?”</em></blockquote><p>A generated answer might correctly state the standard carryover limit, the regional exception, and which rule takes precedence — receiving a strong answer-relevancy score. But what if the retrieved context contained one leave-policy document, two generic benefits documents, and one unrelated payroll dashboard document?</p><p>The answer may still be correct because the model knew the topic or extracted enough from one chunk. The retrieval pipeline nevertheless supplied noisy evidence that could harm another question.</p><p>Conversely, the system could retrieve only the readiness document and miss a second source needed for a broader multi-part question. Every returned source might be relevant, but the evidence set could be incomplete.</p><p><strong>That is why precision and recall must be measured separately.</strong></p><h3>Source Precision</h3><p>Source precision asks: <em>Of the sources returned by the system, how many belong to the expected evidence set?</em></p><pre>Source Precision = |R ∩ G| / |R|<br><br>Expected:   regional-leave-policy.html<br>Returned:   regional-leave-policy.html<br>            payroll-dashboard.pdf       ← noise<br>Source Precision = 1/2 = 0.50</pre><p>Low source precision means the final evidence contains distractors. Extra context is not free — it can confuse generation, introduce unsupported claims, increase tokens and latency, make citations look authoritative when they are not, and reduce the visibility of the strongest evidence.</p><h3>Source Recall</h3><p>Source recall asks: <em>How much of the required source evidence did the system recover?</em></p><pre>Source Recall = |R ∩ G| / |G|<br><br>Expected:   employee-leave-policy.pdf<br>            regional-exceptions.html    ← required but missing<br>Returned:   employee-leave-policy.pdf<br><br>Source Precision = 1/1 = 1.00<br>Source Recall    = 1/2 = 0.50</pre><p>This is why perfect precision can coexist with incomplete evidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4npgYa-vLQnrRYwHS3uk0Q.png" /><figcaption>Left: precision failure — a noisy source dilutes the evidence set. Right: recall failure — a required source was never returned. Both cases need separate measurement.</figcaption></figure><h3>Acceptable Alternatives Complicate the Formula</h3><p>Real documentation often contains more than one authoritative source capable of supporting a claim. The evaluator schema supports acceptable_source_groups, allowing alternative authoritative files to satisfy the same evidence obligation:</p><pre>acceptable_source_groups:<br>  - [employee-leave-policy.pdf, benefits-handbook.html]<br>  - [regional-exceptions.html, statutory-rules.pdf]<br><br>Source recall = covered required groups / total required groups</pre><p>This prevents two opposite errors: requiring one exact filename when another source is equally authoritative, and accepting any vaguely related file as a valid substitute.</p><h3>Exact Source Identity Is Harder Than It Looks</h3><p>Source evaluation initially appears to be a set comparison. Filenames make it more complicated.</p><pre>Expected: leave-policy.html<br>Returned: medical-leave-policy.html   ← substring match, different document</pre><p>A loose substring rule could treat those as equivalent. They may be completely different documents. Overly fuzzy matching creates false confidence; overly strict matching rejects valid path or extension variants.</p><p><strong>Evaluation code is production code.</strong> A bug in source matching can invalidate every downstream conclusion while the application itself remains unchanged. Normalization policy must be explicit, tested, and documented.</p><h3>Source Metrics vs Context Metrics</h3><p>The project reports both deterministic source metrics and LLM-judged context metrics. They answer related but different questions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kG2Hli0eMpHiPL-6BHipyA.png" /><figcaption>Each failure mode has a metric best positioned to expose it. No single metric describes total system quality.</figcaption></figure><p>A source can be correct while a selected chunk from that source is weak. A chunk can be useful even when the dataset permits several equivalent source files. Keeping both metric families visible provides a more complete diagnosis.</p><h3>Deterministic Gates and LLM Judges Have Different Jobs</h3><p>Some evaluation questions should have deterministic answers: Did the route equal sql? Was a forbidden source returned? Did the system retrieve an expected source family? These are appropriate CI gates because they are reproducible, fast, inexpensive, and easy to diagnose.</p><p>Other qualities require semantic judgment — whether a claim is supported by a passage, whether the answer addresses the question. LLM judges help scale those reviews, but their scores can change with the judge model, prompt, temperature, evidence ordering, context formatting, and transient failures.</p><p>LLM-as-judge is not the sole definition of correctness. It complements deterministic gates and human failure review.</p><h3>Route Checks Belong in RAG Evaluation</h3><p>Retrieval metrics are meaningless if the question entered the wrong workflow.</p><blockquote><em>“How many claims were approved last quarter?”</em></blockquote><p>If the system routes that to document RAG, it may retrieve an annual claims report with excellent context precision — but it still used the wrong source of truth. Each evaluation row therefore records expected route, actual route, and whether the route check passed.</p><h3>Cache Contamination Can Fake an Improvement</h3><p>RAG evaluation is unusually vulnerable to stale caches. Consider this sequence:</p><ol><li>Configuration A produces an answer and it is cached.</li><li>Reranking code changes to configuration B.</li><li>The same question is evaluated and the old answer is returned from cache.</li><li>Configuration B receives credit for work it never performed.</li></ol><p><strong>Cache invalidation is part of AI correctness, not merely application performance.</strong> The project addresses this through cache-context fields that include retrieval features, cache-schema versioning when policy changes, and execution provenance recording corpus, configuration, models, and code revision.</p><h3>A Holdout Stops Being Unseen After You Inspect It</h3><p>One of the easiest ways to overstate RAG quality is to keep tuning against the same “test” questions. The score rises, but the dataset has become development data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oorlqP0o2Wx39FBKcUFo3g.png" /><figcaption>The 8-step evaluation lifecycle. The first run answers an unbiased generalization question; later runs answer whether known failures were fixed without regressions. A new sealed holdout is required for each major release.</figcaption></figure><h3>How the Metrics Changed the Retrieval Work</h3><p>Metrics do not improve software by themselves. A more accurate causal statement is:</p><blockquote><em>“Source precision and source recall </em><strong><em>exposed</em></strong><em> different retrieval failures. Those findings </em><strong><em>guided</em></strong><em> changes that improved evaluated retrieval behavior.”</em></blockquote><p>The failure analysis motivated work such as preserving authoritative source metadata across every transformation, removing noisy dashboard evidence when stronger sources existed, retaining complementary evidence families, supporting acceptable authoritative alternatives, and adding regression tests for policy, readiness, rollout, security, and troubleshooting cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9ObEZwmEqeUCT9IFJpmgg.png" /><figcaption>The correct causal chain: metric fires → diagnose failure → bounded change → regression test → new evaluation. Skipping diagnosis and jumping straight to tuning produces arbitrary changes.</figcaption></figure><h3>Aggregate Scores Can Hide Important Failures</h3><p>A mean score of 0.97 can contain many perfect cases alongside one severe route error, one missing security source, one unsupported answer, and one recurring noisy document. Release review therefore needs aggregate metrics, per-question thresholds, route and safety violations, failure clustering, residual-case documentation, and raw-result provenance.</p><p>The project’s final Cloud-v2 evidence reported strong aggregate results while still documenting residual retrieval cases. That is more credible than repeatedly tuning until one stochastic run shows all ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uVUR0TMVL5qhNud_hU_rA.png" /><figcaption>Cloud-v2 release evaluation results — Kubernetes/incident-operations corpus, July 2026. These values belong to this named release configuration; they are not permanent properties of the repository or guarantees for future questions.</figcaption></figure><p>Cloud-v2 release evaluation results — Kubernetes/incident-operations corpus, July 2026. These values belong to this named release configuration; they are not permanent properties of the repository or guarantees for future questions.</p><h3>10 Common Evaluation Mistakes</h3><ol><li><strong>Evaluating only the final answer</strong> — A knowledgeable model can produce the right answer from weak context. Retrieval problems remain hidden.</li><li><strong>Evaluating only retrieval</strong> — Excellent evidence does not guarantee faithful generation.</li><li><strong>Treating every expected source as mandatory</strong> — Equivalent authoritative alternatives may exist. Model them explicitly.</li><li><strong>Using fuzzy source matching without tests</strong> — Similar filenames can produce false positives.</li><li><strong>Reusing a consumed holdout</strong> — After failures influence code changes, the dataset is regression data.</li><li><strong>Leaving caches enabled unintentionally</strong> — The evaluated configuration may not have generated the response.</li><li><strong>Reporting only averages</strong> — One dangerous route or safety failure can matter more than a small average improvement.</li><li><strong>Changing several variables at once</strong> — If corpus, prompt, model, retriever, and Top K all change, attribution becomes impossible.</li><li><strong>Hiding evaluator variance</strong> — Probabilistic judge disagreement is evidence to investigate, not an inconvenience to delete.</li><li><strong>Tuning until the dashboard is green</strong> — A perfect score on familiar cases says little about future queries.</li></ol><h3>A Practical Evaluation Contract</h3><p>For each evaluation run, record inputs (dataset version, question ID, golden answer and sources, acceptable alternatives, expected route, forbidden content, feature configuration), runtime provenance (Git commit, environment, corpus version, cache-schema version, all model versions, prompt version, timestamp), outputs (answer, actual route, actual sources, retrieved chunks, retrieval and reranker scores, cache status, latency and cost metadata), and metrics and gates (source precision and recall, context precision and recall, faithfulness, answer relevancy, route check, forbidden checks, threshold failures).</p><p>This makes a run reproducible enough to review and compare across releases.</p><h3>What I Would Improve Next</h3><ol><li>Bootstrap confidence intervals for aggregate metrics</li><li>Inter-judge or human-versus-judge agreement studies</li><li>Route-specific thresholds rather than one global threshold</li><li>Latency and cost frontiers alongside quality</li><li>Statistically controlled retrieval ablations</li><li>Richer adversarial and multi-hop evidence cases</li><li>Tenant-isolation and authorization evaluation</li><li>Automated drift checks for corpus and source authority</li><li>Clearer calibration of application “confidence” values</li><li>A new sealed holdout for every major retrieval-policy release</li></ol><p>The goal is not a larger metric catalog. It is faster, more reliable diagnosis.</p><h3>Final Takeaway</h3><p>RAG evaluation becomes trustworthy when it distinguishes relevant evidence from complete evidence, source identity from chunk usefulness, retrieval quality from answer quality, deterministic contracts from probabilistic judgments, regression coverage from unbiased holdout evidence, and cached output from newly executed behavior.</p><blockquote><em>A polished demo shows that a system works once. A disciplined evaluation lifecycle shows what it means for the system to improve.</em></blockquote><h3>Project Links</h3><ul><li>Repository: [<a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT">GitHub repository URL</a>]</li><li>Video: [<a href="https://www.youtube.com/watch?v=HrO3jyu4EYw&amp;t=400s">FUll Advance RAG Demo URL</a>]</li><li>Project overview: [<a href="https://medium.com/@vthottempudi1/building-an-enterprise-grade-advanced-rag-system-what-it-took-beyond-the-demo-3f30e2025dad">Enterprise Advanced RAG overview URL</a>]</li><li>Article 2 — Routing RAG, SQL, and Hybrid: [<a href="https://medium.com/ai-in-plain-english/most-enterprise-ai-assistants-begin-with-a-deceptively-simple-interface-one-text-box-94aa92106767">URL</a>]</li><li>Article 3 — Retrieval Pipeline, Chunking, Reranking: [<a href="https://medium.com/ai-in-plain-english/retrieval-is-a-pipeline-sentence-aware-chunking-hybrid-search-and-reranking-43a289c9c41f">URL</a>]</li><li>Next article: <em>[Beyond Top-K: Evidence Family Retrieval]</em></li><li>Portfolio: <em>[</em><a href="https://vthottempudi1.github.io/"><em>Portfolio Website URL</em></a><em>]</em></li></ul><p>#RAG#LLMEvaluation#MLOps #AIEngineering#MachineLearning#EnterpriseAI#Python</p><p>Venu Thottempudi</p><p>AI Engineer | AI Architect | Enterprise RAG &amp; Multiagent Systems</p><p>Connect on LinkedIn: <a href="https://www.linkedin.com/in/venu-thottempudi-34014ba3/">linkedin.com/in/VENUTHOTTEMPUDI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d29c80231aff" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/evaluating-rag-without-fooling-yourself-article-4-of-5-d29c80231aff">Evaluating RAG Without Fooling Yourself · Article 4 of 5</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval Is a Pipeline: Sentence-Aware Chunking, Hybrid Search, and Reranking]]></title>
            <link>https://ai.plainenglish.io/retrieval-is-a-pipeline-sentence-aware-chunking-hybrid-search-and-reranking-43a289c9c41f?source=rss-63881e1e0761------2</link>
            <guid isPermaLink="false">https://medium.com/p/43a289c9c41f</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Venu Thottempudi]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 15:27:02 GMT</pubDate>
            <atom:updated>2026-08-20T17:29:13.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynFmF6solD6H3tAtOV_yEw.png" /><figcaption>Diagram created with Claude.ai (Anthropic)</figcaption></figure><p><em>Enterprise Advanced RAG — Article 3 of 5</em></p><p>When a RAG answer retrieves the wrong evidence, the reranker is an easy place to look.</p><p>Sometimes the failure happened much earlier.</p><p>The parser may have dropped a table. A fixed-size splitter may have cut a claim in half. The embedding search may have missed an exact error code. Sparse search may have found the token but not its meaning. The candidate pool may never have contained the correct passage.</p><p><strong>A reranker cannot recover evidence that never reached it.</strong></p><p>That is why I treat retrieval as a pipeline:</p><pre>Document extraction<br>    → sentence-aware chunks with provenance<br>    → dense and sparse candidate retrieval<br>    → hybrid rank fusion<br>    → cross-encoder reranking<br>    → evidence filtering<br>    → grounded generation</pre><p>Each stage has a different objective. Chunking preserves evidence. First-stage retrieval favors recall. Reranking favors precision. Final filtering controls noise and prompt size.</p><p>This article explains how those stages work in my Enterprise Advanced RAG project, why I combined semantic and lexical signals, and where the current implementation still needs systematic tuning.</p><blockquote><strong><em>Scope note:</em></strong><em> The concrete implementation uses Kubernetes and incident-operations documents, but the retrieval principles apply to legal clauses, medical codes, financial symbols, product SKUs, customer ticket IDs, software stack traces, and other terminology-heavy enterprise corpora.</em></blockquote><h3>Chunking Is an Information-Preservation Decision</h3><p>The ingestion pipeline supports plain text, Markdown, HTML, PDF, DOCX, and Docling-backed fallback processing.</p><p>Every extracted passage eventually becomes a retrieval unit. If that unit is poorly formed, every downstream score is operating on damaged evidence.</p><p>A simple fixed-character splitter might produce this:</p><pre>Chunk 1:<br>Employees may carry over up to five unused vacation days into</pre><pre>Chunk 2:<br>the next calendar year, subject to regional employment rules.</pre><p>Both chunks contain part of the answer, but neither is a clean, self-contained statement.</p><p>The current processor uses a maximum window of approximately 1,000 characters with about 100 characters of overlap. Before cutting at the hard limit, it searches the final portion of the window for a sentence boundary. If no sentence boundary is available, it falls back to a word boundary and then to the hard limit.</p><p>Conceptually:</p><pre>hard_end = min(start + chunk_size, len(text))<br><br># Search near the end of the window for the best split point:<br>#   1. Sentence boundary (period, ?, !)  — preferred<br>#   2. Word boundary (whitespace)        — fallback<br>#   3. Hard character limit              — last resort<br><br>next_start = end - overlap<br># Snap the next start toward a sentence boundary when possible</pre><p>The implementation also processes PDFs page by page so each resulting chunk retains an accurate page number.</p><h3>What “Sentence-Aware” Means Here</h3><p>“Sentence-aware” can describe several levels of sophistication. In this project, it means:</p><ul><li>a character-bounded window</li><li>a preference for punctuation-based sentence endings near the end of that window</li><li>word-boundary fallback</li><li>overlapping context</li><li>an attempt to begin the next chunk after a sentence boundary</li><li>per-page PDF chunking for provenance</li></ul><p>It does <strong>not</strong> mean that the chunker performs full discourse analysis or understands every heading, table, code block, and semantic section.</p><p>Known limitations: abbreviations can look like sentence endings; headings and lists may not end with punctuation; a sentence may exceed the maximum size; HTML tag stripping loses layout structure; DOCX paragraph joining loses some document hierarchy; tables need layout-aware extraction; a page boundary may split a concept.</p><p>For complex formats, Docling’s conversion and hybrid chunking can preserve more structure, but every fallback path still requires corpus auditing.</p><h3>Overlap Is Useful but Not Free</h3><p>Overlap preserves context across adjacent chunks. Without overlap, a chunk beginning with “this behavior” may lose the noun introduced at the end of the previous chunk. With too much overlap, the vector store contains near-duplicates that consume storage, crowd the top results, repeat evidence in the prompt, inflate apparent recall, and reduce source diversity.</p><p><strong>Chunk size and overlap are hyperparameters. They should be evaluated, not inherited uncritically from a tutorial.</strong></p><h3>Provenance Is Part of the Chunk</h3><p>A text string alone is insufficient for enterprise retrieval. The ingestion and vector-storage paths preserve: source name and path, page number, chunk index and total count, document identity, authority tier, and ingestion/audit metadata.</p><p>S3 stores original uploaded documents. Qdrant stores derived chunks, vectors, and retrieval metadata. Replacing an ECS task should not remove either.</p><h3>Authority Is a Trust Signal, Not a Relevance Score</h3><p>Real enterprise knowledge bases accumulate old policies, drafts, duplicate exports, vendor manuals, and archived pages. A passage may be semantically similar to a question without being approved evidence for the answer.</p><p>One useful pattern is to attach a trust classification during ingestion. Retrieval still searches a difficult mixed corpus, but the answer stage prefers approved or uploaded enterprise evidence and abstains when every surviving candidate is explicitly classified as noise.</p><blockquote>Even if this passage is relevant, is this source allowed to support the answer?</blockquote><p>The production lesson: attaching metadata at ingestion is not enough. Every transformation must preserve it:</p><pre>vector database<br>    → dense or sparse result<br>    → hybrid rank fusion<br>    → reranker<br>    → corrective filtering<br>    → API evidence preview</pre><p>If rank fusion constructs a new chunk object but copies only text and score, the trust label silently disappears. Regression tests should verify provenance continuity across the complete retrieval path.</p><h3>First-Stage Retrieval Should Favor Recall</h3><h3>Dense Retrieval</h3><p>Dense embeddings bridge vocabulary gaps. A user might ask <em>“How do I keep my application available if a machine fails?”</em> The documentation may discuss replicas, scheduling, controllers, and node failure without using the same wording. Dense retrieval can bridge that gap.</p><h3>Sparse Retrieval</h3><p>Sparse retrieval protects literal and rare terms: legal clause numbers, medical or billing codes, financial instrument symbols, product SKUs, customer ticket IDs, configuration keys, stack-trace tokens, and operational errors such as ErrImagePull or OOMKilled.</p><p>A semantic model may understand that two passages are generally about container failures while still underweighting the one containing the exact operational identifier.</p><p><strong>Neither approach dominates every question.</strong></p><h3>Hybrid Retrieval Combines Rankings, Not Raw Confidence</h3><p>Dense and sparse scores do not naturally share a calibrated numeric scale. Adding their raw values can cause whichever system produces larger numbers to dominate.</p><p>The project’s hybrid path uses reciprocal-rank-style fusion:</p><pre>fused contribution = weight / (k + rank)</pre><p>Candidates appearing in both lists accumulate contributions and are deduplicated using their source and text identity. The benefit: fusion uses rank position without pretending dense and sparse raw scores are directly comparable.</p><h3>Why Rerank a Wider Candidate Pool?</h3><p>If the final answer needs five chunks, retrieving only five candidates leaves the reranker no room to recover a relevant passage ranked sixth or seventh by the cheaper first stage. The pipeline therefore follows:</p><pre>retrieve a wider pool for recall<br>    → rerank that smaller-than-corpus pool for precision<br>    → send only the best evidence to generation</pre><p>The cross-encoder evaluates each (query, chunk) pair jointly — it can model the interaction between the exact question and passage, providing better precision at a higher cost. The model instance is cached per worker so transformer weights are not reloaded for every request.</p><h3>The Blended Reranking Score</h3><p>For each candidate, the pipeline calculates: (1) cross-encoder relevance, (2) original retrieval score, (3) keyword overlap, and (4) a conditional troubleshooting exact-token bonus.</p><p>Cross-encoder and retrieval values are min-max normalized across the candidate batch:</p><pre>normalized(x) = (x - minimum) / (maximum - minimum)</pre><p>The blended score:</p><pre>0.4 × normalized cross-encoder score    # strongest semantic signal<br>+ 0.3 × normalized retrieval score      # preserves broad-recall evidence<br>+ 0.3 × keyword overlap                 # protects exact identifiers<br>+ conditional troubleshooting bonus     # guards exact operational errors</pre><p>These weights are <strong>reasoned, empirically checked baselines — not universal constants produced by a global mathematical optimizer.</strong> That is the honest answer I would give in an interview.</p><h3>Protecting Exact Operational Errors</h3><p>Consider the query: <em>“What does </em><em>ErrImagePull mean and how do I fix it?&quot;</em> A relevant chunk may use the related state ImagePullBackOff and explain invalid image names, missing registry credentials, inaccessible registries, and repeated pull attempts.</p><p>The query-term logic expands known identifiers into related terms. The troubleshooting bonus rewards exact query-term coverage, runbook and incident sources, and known error strings such as ErrImagePull, ImagePullBackOff, OOMKilled, and CrashLoopBackOff.</p><p>The generalized pattern across domains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2pQEhU3lsFF8dtXhaihnpw.png" /><figcaption>Exact-identity signals worth protecting, by industry domain.</figcaption></figure><h3>Regression Tests Matter More Than an Attractive Formula</h3><p>The unit tests deliberately use a fake cross-encoder that gives misleading scores. Protected behaviors include: preserving a strong P1 escalation-policy match; preserving an exact image-pull error match; boosting an OOMKilled runbook source; reusing the cross-encoder instance within a worker.</p><blockquote><em>A ranking test should protect the behavior the user needs, not merely reproduce the current arithmetic.</em></blockquote><h3>The Ablation I Would Run Next</h3><p>I would freeze the corpus version, query dataset, embedding model, generator model, prompt version, cache schema, and candidate and final Top-K. Then compare:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKESzk4Hq6QMsBlnoDA_tg.png" /><figcaption>Proposed ablation: retrieval configuration comparison. Dashes indicate a proposed experiment, not missing results.</figcaption></figure><p>For chunking:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aRhS6_v9zTkt4x-r3JRLA.png" /><figcaption>Proposed ablation: chunking strategy comparison. Weights should be tuned on dev data, then verified on a sealed holdout.</figcaption></figure><p>Publishing the experimental design without invented before-and-after results is more credible than implying an ablation has already been run.</p><h3>When I Would Disable Advanced Retrieval</h3><p>More RAG stages are not automatically better. I would consider disabling reranking or expansion when: latency requirements are strict; the corpus is small and exact; the query already contains a unique identifier; evaluation shows no quality improvement; the cross-encoder cost exceeds the expected benefit; or an offline or constrained environment cannot load the model.</p><p><strong>The best default is the least expensive pipeline that meets the quality target.</strong></p><h3>Final Takeaway</h3><p>RAG retrieval quality is not one vector-search setting. It is the result of several contracts: extraction must preserve content; chunks must preserve claims and provenance; dense retrieval must bridge semantics; sparse retrieval must preserve exact terms; hybrid fusion must combine incompatible rankings; every retrieval transformation must preserve provenance and trust metadata; reranking must improve precision without erasing decisive lexical evidence; evaluation must reveal missing and noisy sources.</p><p>A sophisticated reranker cannot repair a missing candidate. A perfect chunk cannot help if retrieval never returns it. A high-scoring result is not useful if it lacks the complete evidence required by the question.</p><blockquote><em>Combine semantic relevance with exact identity when the domain contains terms whose literal value changes the answer.</em></blockquote><h3>Project Links</h3><ul><li>Repository: <em>[</em><a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT"><em>GitHub repository URL</em></a><em>]</em></li><li>Video demo: <em>[</em><a href="https://www.youtube.com/watch?v=HrO3jyu4EYw&amp;t=400s"><em>Full Demo URL</em></a><em>]</em></li><li>Full article: <em>[</em><a href="https://medium.com/ai-in-plain-english/building-an-enterprise-grade-advanced-rag-system-what-it-took-beyond-the-demo-3f30e2025dad"><em>Full RAG Article URL</em></a><em>]</em></li><li>Previous article: <em>[</em><a href="https://medium.com/ai-in-plain-english/most-enterprise-ai-assistants-begin-with-a-deceptively-simple-interface-one-text-box-94aa92106767"><em>Routing RAG, SQL, and Hybrid URL</em></a><em>]</em></li><li>Next article: <em>[Evaluating RAG Without Fooling Yourself URL]</em></li><li>Portfolio: <em>[</em><a href="https://vthottempudi1.github.io/"><em>Portfolio Website URL</em></a><em>]</em></li><li>Connect with me on LinkedIn → <a href="https://www.linkedin.com/in/venu-thottempudi-34014ba3/">linkedin.com</a></li></ul><p><em>Venu Thottempudi — AI Engineer | AI Architect | Enterprise RAG &amp; Multiagent Systems</em></p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43a289c9c41f" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/retrieval-is-a-pipeline-sentence-aware-chunking-hybrid-search-and-reranking-43a289c9c41f">Retrieval Is a Pipeline: Sentence-Aware Chunking, Hybrid Search, and Reranking</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One chat interface and three sources of truth (Article 2 of 5)]]></title>
            <link>https://ai.plainenglish.io/most-enterprise-ai-assistants-begin-with-a-deceptively-simple-interface-one-text-box-94aa92106767?source=rss-63881e1e0761------2</link>
            <guid isPermaLink="false">https://medium.com/p/94aa92106767</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[text-to-sql]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Venu Thottempudi]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 00:48:41 GMT</pubDate>
            <atom:updated>2026-09-12T01:03:15.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKFtpWI1zpgghgi-0lMyEA.png" /><figcaption>Diagram created with Claude.ai (Anthropic)</figcaption></figure><p>Article 2 of 5:</p><p>Most enterprise AI assistants begin with a deceptively simple interface: one text box.</p><p>The interface may be simple, but the questions are not:</p><ul><li>“What does our escalation policy require?”</li><li>“How many priority-one cases were resolved last quarter?”</li><li>“How many were resolved, and what does the policy require?”</li><li>“Can you restore the previous one?”</li></ul><p>Those four questions should not follow the same data path.</p><p>The first belongs to enterprise documents. The second belongs to a relational database. The third needs both. The fourth is too ambiguous to answer safely without another question.</p><p>This distinction became one of the most important architectural decisions in my Enterprise Advanced RAG project:</p><blockquote><strong><em>Routing decides which evidence system should answer. Retrieval planning decides how evidence is found inside the document path.</em></strong></blockquote><p>Those are separate decisions, and treating them as the same problem leads to plausible but unreliable systems.</p><p><strong>Scope note:</strong> The implementation examples in this article come from a Kubernetes and incident-operations corpus. The architecture applies equally to customer support, finance, healthcare, legal research, retail, and other enterprise domains that combine structured records with unstructured policies or guidance.</p><h3>Why Vector Search Cannot Be the Universal Answer</h3><p>A vector database is well suited to semantic document retrieval. It can locate a policy passage even when the user’s wording differs from the document.</p><p>It is not an authoritative analytical database.</p><p>Suppose a user asks:</p><blockquote><em>“How many priority-one cases were resolved last quarter?”</em></blockquote><p>An embedding search might retrieve a report that mentions P1 incidents. That report might be old, partial, or written before the quarter closed. Asking a language model to infer a count from those chunks would produce an answer that sounds analytical without being authoritative.</p><p><strong>The count belongs in PostgreSQL.</strong></p><p>The inverse is also true. If the user asks what an escalation policy requires, generating SQL against an incident table will not recover the policy language. That answer belongs in enterprise documents.</p><p>The problem is therefore not simply “retrieve relevant text.” The system must first identify the appropriate source of truth.</p><h3>The Three Executable Routes</h3><p>The deterministic classifier in this project returns three executable intents:</p><pre>Intent = Literal[&quot;sql&quot;, &quot;rag&quot;, &quot;hybrid&quot;]</pre><h3>RAG Document Retrieval</h3><p>For questions such as:</p><blockquote><em>“What does our escalation policy require for priority-one cases?”</em></blockquote><p>The system retrieves from Qdrant using dense, sparse, or hybrid search and can conditionally apply reranking, HyDE, CRAG, or self-reflection.</p><h3>SQL Governed Text-to-SQL</h3><p>For questions such as:</p><blockquote><em>“How many priority-one cases were resolved last quarter?”</em></blockquote><p>The model may propose a query, but it does not receive direct database authority. The query is parsed, validated, bounded, stored as a pending action, and presented for approval before execution.</p><h3>Hybrid Both Evidence Systems</h3><p>For compound questions such as:</p><blockquote><em>“How many priority-one cases were resolved last quarter, and what does our escalation policy require?”</em></blockquote><p>The count comes from PostgreSQL. The policy explanation comes from retrieved documents. The workflow merges the two evidence types only after each branch has completed its own controls.</p><p><strong>Design phrase:</strong> Two claims, two sources of truth.</p><h3>The Pattern Is Domain-Independent</h3><p>The route is determined by the evidence contract, not by the industry:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*mX9BaxqUg9XGpznvBDrP1A.png" /></figure><p>The database schema and document corpus change across domains. The architectural question remains:</p><blockquote><strong><em>Which system is authorized and qualified to answer each claim?</em></strong></blockquote><h3>Clarification Is a Safety Outcome, Not a Data Store</h3><p>What about:</p><blockquote><em>“How do I scale?”</em></blockquote><p>Scale could mean:</p><ul><li>Kubernetes replicas</li><li>cluster nodes</li><li>database capacity</li><li>request throughput</li><li>organizational processes</li><li>cost efficiency</li></ul><p>Returning the first scaling document found by vector search would be fluent but arbitrary.</p><p>In this project, clarification is handled as a safety and product outcome around the request and retrieval policy. It is intentionally distinct from the three values returned by the deterministic classify_intent function.</p><p><strong>Implementation detail that matters:</strong> It would be inaccurate to describe clarification as a fourth database route. It is a decision not to enter an evidence workflow until the request contains enough information. An abstention or targeted follow-up is not a failed AI response. For an underspecified request, it is often the most accurate response available.</p><h3>Why I Used a Deterministic Router</h3><p>The current classifier is rule-based. It combines two kinds of SQL signals:</p><ol><li>an analytical operation — “how many,” “count,” “average,” “total”</li><li>a known structured entity — incidents, alerts, users, accounts, orders, SLA records</li></ol><p>Conceptually:</p><pre>has_sql = has_analytical_keyword and has_structured_entity<br><br>if has_sql and (has_document_signal or has_hybrid_connector):<br>    return &quot;hybrid&quot;<br>if has_sql:<br>    return &quot;sql&quot;<br>return &quot;rag&quot;</pre><p>The hybrid route has priority because it contains both structured and document-oriented signals.</p><p>This design provides several benefits:</p><ul><li>deterministic results</li><li>no model cost at routing time</li><li>negligible routing latency</li><li>easy unit and integration testing</li><li>explicit failure analysis</li><li>a bounded list of downstream capabilities</li></ul><p>It also has limitations:</p><ul><li>new business entities require updated patterns</li><li>natural language can express analytics without using a known phrase</li><li>a rule can be too broad or too narrow</li><li>domain expansion creates maintenance work</li><li>deterministic does not mean correct</li></ul><p>I chose interpretability and bounded behavior for the current scope. A learned or LLM-based router could improve linguistic coverage, but I would not introduce it without a labeled routing dataset, confidence calibration, cost and latency measurements, and a deterministic fallback.</p><h3>The Graph Is the Control Plane</h3><p>After routing, LangGraph controls the allowed workflow transitions. Here is the control flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEu35P2nyzrJIcJ3avf5nQ.png" /></figure><p>The most important boundary in the SQL route is the separation between proposing a query and running it.</p><p>The workflow applies multiple controls:</p><ol><li>authenticated identity and request validation</li><li>natural-language-to-SQL generation</li><li>SQL parsing and AST inspection</li><li>read-only statement restrictions</li><li>result and execution bounds</li><li>pending-action persistence</li><li>explicit human approval</li><li>least-privileged database credentials</li><li>controlled error mapping and audit metadata</li></ol><p>The user can inspect the pending SQL in the frontend before approving it.</p><p><strong>Why require approval for a SELECT?</strong> Because read-only does not automatically mean harmless. A query can still scan an expensive amount of data, expose rows the user should not see, create operational load, or represent a broader question than the user intended. In a mature deployment, a narrow class of allowlisted aggregates could eventually be auto-approved. The policy should follow measured risk, not the assumption that all SELECT statements are equivalent.</p><h3>Hybrid Questions Need Evidence Separation</h3><p>A hybrid response can easily become misleading if the system blends its inputs too early.</p><p>Consider:</p><blockquote><em>“How many P1 incidents were resolved last quarter, and what does the escalation policy require?”</em></blockquote><p>The system should preserve the provenance of each claim:</p><h3>Number of resolved incidents</h3><ul><li><strong>Source of truth: </strong>PostgreSQL query result</li></ul><h3>Escalation obligation</h3><ul><li><strong>Source of truth: </strong>Retrieved policy document</li></ul><p>The database result should not be represented as a document citation. The policy statement should not be implied by the incident table.</p><p>In the evaluation pipeline, context entries retain source labels so mixed evidence can be scored and inspected. In the frontend, route, source, chunk, and metadata tabs let a reviewer see how the final answer was assembled. A fluent combined answer is insufficient if nobody can tell which system supported which statement.</p><h3>Follow-Up Questions Must Preserve Evidence Identity</h3><p>Routing and retrieval become more subtle in a conversation. A user may begin with “What does the P1 policy require?” and then ask “What happens if it is not acknowledged?” followed by “What should the team document afterward?” The later questions may contain neither the policy name nor the vocabulary needed to retrieve it reliably.</p><p>Passing only the previous answer is fragile. A stronger conversation record retains the prior question, answer, and cited source identity. The backend can then rewrite an ambiguous continuation into a self-contained retrieval question while preserving details such as incident severity.</p><p>This does not require sending unlimited chat history. A bounded rolling window can work when each successful turn carries its evidence provenance forward. The important contract is that source identity survives between turns. Multi-turn regression tests should cover a chain of at least three questions; testing only one follow-up can hide a context implementation that expires after a single exchange.</p><h3>Routing and Retrieval Planning Are Independent</h3><p>After a question enters the RAG route, the system still needs another decision:</p><ul><li>dense retrieval for semantic similarity</li><li>sparse retrieval for exact terminology</li><li>hybrid retrieval for both</li><li>reranking for higher-precision ordering</li><li>HyDE for a vocabulary gap</li><li>CRAG for weak evidence</li><li>self-reflection for a complex draft</li></ul><p>These features do not determine whether PostgreSQL or documents own the answer. They operate inside the document evidence path.</p><p><strong>Why this separation matters:</strong> Keeping the layers separate prevents a common architecture problem — a single opaque “agent” that simultaneously decides the source of truth, retrieval method, tool permissions, and final answer. Explicit layers make it possible to evaluate routing accuracy, retrieval accuracy, answer groundedness, SQL safety, latency and cost, and failure behavior independently.</p><h3>How I Test the Router</h3><p>Routing tests use questions with expected outcomes. Examples:</p><pre>&quot;How many P1 incidents were resolved last quarter?&quot;    → SQL<br><br>&quot;What does our escalation policy require?&quot;             → RAG<br><br>&quot;How many incidents breached SLA, and what does<br> our policy say?&quot;                                      → Hybrid</pre><p>The integration suite also verifies that the chosen route leads to the expected workflow behavior, including pending SQL approval and hybrid evidence.</p><p>A useful routing evaluation should report more than average accuracy. The error types have different costs:</p><h3>SQL routed to RAG</h3><ul><li><strong>Failure mode: </strong>Can invent an analytical fact</li></ul><h3>RAG routed to SQL</h3><ul><li><strong>Failure mode: </strong>Can query an irrelevant schema</li></ul><h3>Hybrid routed to one branch</h3><ul><li><strong>Failure mode: </strong>Can omit half the answer</li></ul><h3>Ambiguous routed confidently</h3><ul><li><strong>Failure mode: </strong>Can create false certainty</li></ul><p>I examine a confusion matrix and weight high-risk misroutes more heavily than benign ones.</p><h3>Why I Did Not Start With a Fully Autonomous Agent</h3><p>A general agent with access to retrieval, SQL, web search, and administrative tools sounds attractive. It can also make tool choice, retries, permissions, and termination harder to predict.</p><p>For this project, bounded routing provides:</p><ul><li>route-specific authorization</li><li>explicit approval boundaries</li><li>predictable evaluation contracts</li><li>controlled costs</li><li>finite graph transitions</li><li>clearer failure handling</li></ul><blockquote><em>Use the least autonomy necessary to solve the product problem.</em></blockquote><h3>What I Would Improve Next</h3><p>The current rule-based router is a deliberate baseline. My next improvements would be:</p><ol><li>Build a larger labeled routing dataset with adversarial paraphrases</li><li>Report per-intent precision, recall, and a cost-weighted confusion matrix</li><li>Add explicit confidence and abstention thresholds</li><li>Compare rules with a small classifier and an LLM router</li><li>Measure routing latency and cost alongside accuracy</li><li>Verify tenant and authorization context before every route</li><li>Support atomic, expiring approval state across multiple backend instances</li></ol><p>I would not replace the deterministic router simply because a model is available. The replacement would need to improve measured coverage without weakening predictability or safety.</p><h3>Final Takeaway</h3><p>The hardest question in an enterprise assistant is often not:</p><blockquote><em>“Which chunk is most similar?”</em></blockquote><p>It is:</p><blockquote><strong><em>“Which system is authorized and qualified to answer this claim?”</em></strong></blockquote><p>Document policies belong in retrieval. Exact operational aggregates belong in a relational database. Compound questions need both. Ambiguous requests may need clarification before either.</p><p>Once the source of truth is explicit, retrieval, SQL governance, evaluation, and observability become much easier to reason about.</p><p><strong>One chat box does not imply one evidence path.</strong></p><h3>Project Links</h3><p>📁 Repository: <a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT">GitHub repository URL</a></p><p>🎥 Video demo: <a href="https://www.youtube.com/watch?v=HrO3jyu4EYw&amp;t=400s">Full Demonstration URL</a></p><p>📄 Previous article: <a href="https://medium.com/@vthottempudi1/building-an-enterprise-grade-advanced-rag-system-what-it-took-beyond-the-demo-3f30e2025dad">Enterprise Advanced RAG — Project Overview</a></p><p>➡️ Next article: Retrieval Is a Pipeline — Dense, Sparse, HyDE, CRAG, and Reranking</p><p>🌐 Portfolio: <a href="https://vthottempudi1.github.io/">Portfolio URL</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94aa92106767" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/most-enterprise-ai-assistants-begin-with-a-deceptively-simple-interface-one-text-box-94aa92106767">One chat interface and three sources of truth (Article 2 of 5)</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Enterprise-Grade Advanced RAG System: What It Took Beyond the Demo(Full Article &…]]></title>
            <link>https://ai.plainenglish.io/building-an-enterprise-grade-advanced-rag-system-what-it-took-beyond-the-demo-3f30e2025dad?source=rss-63881e1e0761------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f30e2025dad</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm-engineering]]></category>
            <category><![CDATA[ai-architecture]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Venu Thottempudi]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 19:30:20 GMT</pubDate>
            <atom:updated>2026-09-12T01:04:42.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XF6rkYZbZO3wgaXqcdSZg.png" /><figcaption>Diagram created with Claude.ai (Anthropic)</figcaption></figure><p>Most Retrieval-Augmented Generation tutorials end when a model can answer a question from a PDF. That is a useful milestone, but it is only the beginning of a reliable enterprise system.</p><p>Real applications must work across structured and unstructured data, reject unsafe operations, survive noisy corpora, preserve conversation context, expose evidence, control cost, and produce repeatable quality measurements. They also need deployment, monitoring, security controls, and honest documentation of what still fails.</p><p>I built <strong>Enterprise Advanced RAG</strong> to solve that broader problem. It is a production-grade AI assistant with three primary answer paths — RAG, SQL, and combined SQL + RAG — backed by advanced retrieval, human approval for database writes, multi-tier caching, AWS deployment, and a rigorous evaluation lifecycle.</p><p>This article describes the project as it exists today, including the failures that changed its design and the final evidence used to judge it.</p><blockquote><strong><em>Release status:</em></strong> The system is deployed and has strong production-candidate validation. I describe it as production-grade in architecture and engineering practice — not as perfect or universally proven. Two retrieval edge cases remain documented regression targets.</blockquote><blockquote><strong><em>Code:</em></strong> Full implementation, evaluation datasets, and deployment assets are on <a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT">GitHub → vthottempudi1/NEW-ADV-RAG-IMPLEMENT</a></blockquote><h3>The Problem Was Larger Than Document Search</h3><p>Enterprise questions do not all belong to the same data path.</p><ul><li><em>“What is the escalation policy for a P1 incident?”</em> — requires document evidence.</li><li><em>“How many P1 incidents were resolved last quarter?”</em> — requires structured database data.</li><li><em>“How many were resolved, and what does the policy require?”</em> — requires both.</li><li><em>“How do I scale?”</em> — too ambiguous to retrieve confidently; should trigger clarification.</li></ul><p>Sending every question through vector search creates plausible but unreliable behavior. Sending every question to SQL is equally wrong. The first architectural decision was therefore to separate <strong>answer routing</strong> from <strong>retrieval strategy</strong>.</p><p>The top-level router selects one of four outcomes:</p><ol><li><strong>RAG</strong> — for document-grounded questions.</li><li><strong>SQL</strong> — for structured analytical questions.</li><li><strong>SQL + RAG</strong> — for questions requiring both evidence types.</li><li><strong>Clarification</strong> — when the request lacks enough intent to answer safely.</li></ol><p>Clarification is an internal control outcome, not a fourth data system. The user-facing product centers on the three answer paths.</p><p>Within the RAG path, the backend selects dense, sparse, or hybrid retrieval and optionally applies reranking, HyDE, CRAG, or self-reflective RAG. This separation matters: <strong>routing decides where the answer must come from; retrieval planning decides how to find the best document evidence.</strong></p><h3>Architecture at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wJeTWVG8q7KlPo9FqCGxA.png" /><figcaption><em>Six-layer architecture: requests flow from the UI through the FastAPI gateway and LangGraph router into one of three pipelines, each backed by its own storage system, with Redis cache, S3, CloudWatch, and Secrets Manager as shared supporting services.</em></figcaption></figure><p>The backend is organized by responsibility, not as one large chatbot module:</p><ul><li><a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT/tree/main/app/api/v1">app/api/v1</a> — versioned HTTP contracts.</li><li><a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT/tree/main/app/rag">app/rag</a> — retrieval planning, grounding, and advanced RAG behavior.</li><li><a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT/tree/main/app/sql">app/sql</a> — query generation, validation, approval workflow, and execution.</li><li><a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT/tree/main/app/security">app/security</a> and app/middleware — cross-cutting controls.</li><li><a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT/tree/main/app/caching">app/caching</a>, app/storage, and app/ingestion — isolated infrastructure concerns.</li><li>app/observability — application telemetry.</li><li><a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT/tree/main/evals">evals/</a> — datasets, runners, scoring, and curated evidence.</li><li>infra/, deploy/, and .github/workflows/ — delivery assets.</li></ul><p>The UI is intentionally thin. Retrieval decisions belong to the backend so that API clients and the frontend receive identical behavior.</p><h3>Retrieval Is a Pipeline, Not a Single Vector Query</h3><p>Different question shapes reward different retrieval methods.</p><p><strong>Dense and Sparse Retrieval</strong></p><p>Dense embeddings capture semantic similarity. Sparse retrieval preserves exact operational terms — CrashLoopBackOff, ErrImagePull, configuration keys, policy names — that embeddings can dilute. Hybrid retrieval combines both signals, giving the system semantic coverage without sacrificing exact-match precision.</p><p><strong>Reranking</strong></p><p>First-stage retrieval favors recall: it casts a wide net. A cross-encoder reranker then reorders candidates using the full question text, not just embedding proximity. The reranker model instance is shared per worker rather than reloaded per request, keeping latency and memory pressure low.</p><p><strong>HyDE, CRAG, and Self-Reflection</strong></p><ul><li><strong>HyDE</strong> generates a hypothetical answer and uses that representation as the retrieval query — improving recall for underspecified or abstract questions where the user’s wording is far from the document’s phrasing.</li><li><strong>CRAG</strong> evaluates the retrieved evidence after the first retrieval pass and triggers a corrective retry when relevance scores are weak.</li><li><strong>Self-reflective RAG</strong> checks whether the evidence and the draft answer are mutually adequate before returning the result to the user.</li></ul><p>These features are not enabled blindly. In auto mode, the system resolves a bounded retrieval plan from the question’s characteristics. Manual mode remains available for diagnosis and demonstrations.</p><p><strong>Evidence-Family Planning</strong></p><p>The largest retrieval improvement did not come from tuning familiar test questions — it came from testing new ones. Some answers require multiple complementary sources. A Kubernetes rollout question may need evidence from the Deployment strategy document, the readiness probe guide, and the Service routing spec. A single high-scoring chunk from only one of those families produces an incomplete answer even when its relevance score looks excellent.</p><p>The retrieval service now models <strong>semantic evidence families</strong> for supported operational concepts. A retrieval plan can require complementary authoritative families, recognize valid alternative sources, and protect required evidence from being discarded by CRAG filtering. Deterministic synthesis is only permitted when the complete authoritative family is present.</p><p>The key lesson: retrieval quality is not simply “did the top chunk look relevant?” It is also “did the system retrieve <em>all</em> the evidence needed to support the answer?”</p><h3>Why “How Do I Scale?” Exposed a Real Weakness</h3><p>One early auto-mode result treated <em>“How do I scale?”</em> as a confident RAG query. It returned a Kubernetes scaling tutorial alongside unrelated scientific and infrastructure papers. Each source was individually similar to the word <em>scale</em>, but the question gave no indication whether the user meant Pods, nodes, databases, application architecture, or something else entirely.</p><p>That result exposed three problems:</p><ol><li>Ambiguous intent was being converted into retrieval too early.</li><li>Broad semantic matches could outrank domain-specific evidence.</li><li>CRAG relevance checks alone could not prove the system understood the intended task.</li></ol><p>The fix was not a hard-coded answer for one ambiguous sentence. The router gained a clarification outcome. Retrieval gained semantic evidence plans. Source authority became explicit metadata. Evaluation datasets gained adversarial paraphrases. The system now has a correct option: ask the user what they want to scale before committing to an answer.</p><h3>Ingestion Quality Determined Retrieval Quality</h3><p>The corpus deliberately mixes 49 authoritative Kubernetes and operational documents with 314 noisy technical documents. A retriever that works only in a clean 50-document collection demonstrates little resilience to real-world distractor content.</p><p>The first ingestion pass stored only source and text. That minimal metadata was insufficient to reason reliably about authority, document position, ingestion version, or partial failures. Fixed-size chunking also cut some ideas at structurally weak boundaries.</p><p>The version-two ingestion pipeline introduced:</p><ul><li>sentence-aware chunk boundaries that keep claims intact;</li><li>configurable overlap that preserves continuity without duplicating entire sections;</li><li>authority labels distinguishing curated, uploaded, and noisy corpus members;</li><li>content and document hashes for deduplication and change detection;</li><li>source path, page number, chunk index, and total chunk count per vector point;</li><li>ingestion-version metadata for collection lineage;</li><li>manifest-driven, resumable processing;</li><li>duplicate detection and post-ingestion corpus auditing.</li></ul><p>Sentence-aware chunking is a meaningful improvement, but it is not sufficient on its own. Layout-aware parsing, heading extraction, table handling, page provenance, overlap policy, embedding choice, metadata filtering, and query-time evidence planning all affect the quality of what eventually reaches the reranker.</p><p><strong>The Finalized Qdrant Cloud v2 Corpus</strong></p><p>The production-candidate collection, new_adv_rag_documents_v2, was rebuilt directly in Qdrant Cloud rather than promoted from a local volume. Its audited state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uu0Xzj1dJwfU0AtqmMQ7Ow.png" /></figure><p>At the document level, that is roughly one authoritative source for every 6.4 noisy sources. At the retrieval level, it is approximately one authoritative chunk for every 22.4 noisy chunks. Both ratios matter: governance operates on documents while retrieval competes over chunks.</p><p>Two large noisy PDFs failed during the 121-minute ingestion run. One left partial points, which were removed. I accepted those exclusions because all 49 authoritative sources were intact and the failed files were intentional distractors — but the difference was recorded rather than papered over. An ingestion log showing zero new chunks could mean every source was already indexed. It does not prove that a fresh ingestion completed. The corpus audit is the source of truth, not a cache entry or a summary log line</p><h3>Trust Metadata Must Survive the Whole Pipeline</h3><p>The corpus tags each vector point with an authority label: curated evidence, uploaded enterprise document, or known distractor. That label is not a substitute for semantic relevance — retrieval, reranking, and CRAG still determine whether a passage can actually answer the question. The label provides a separate trust signal so that a high-scoring noisy source cannot silently become the final evidence.</p><p>One failure exposed a subtle implementation risk. Qdrant stored the correct authority label, but sparse retrieval, hybrid fusion, and reranking each created new chunk objects internally — without copying all payload metadata. The label existed at rest and disappeared in motion.</p><p>The fix propagates provenance through every pipeline transformation and exposes the authority field in query diagnostics. The general lesson: test metadata continuity end to end, not just storage correctness at write time.</p><h3>Multi-Turn Retrieval Needs Source-Aware Memory</h3><p>Conversational context needs evidence provenance, not just conversation history. In early testing, a first follow-up question retrieved correctly while the second failed — because the immediately preceding answer no longer named the original runbook, and the retrieval query was reconstructed from incomplete context.</p><p>The corrected design scans a bounded rolling window of prior turns and builds a self-contained retrieval question that carries the original query, prior answers, cited sources, and important qualifiers forward. This is targeted retrieval state — not general conversation memory. A robust multi-turn test should include an opening question plus at least two consecutive follow-ups, verifying both the answer and the cited source at every turn.</p><h3>Safe Text-to-SQL Required Its Own Trust Boundary</h3><p>The SQL path converts natural language into a database query, but generated SQL is never treated as trusted code.</p><p>The workflow enforces:</p><ul><li>authenticated user identity and tenant context;</li><li>read-only query restrictions;</li><li>SQL parsing and AST validation via sqlglot;</li><li>table and operation allowlists;</li><li>row limits and execution timeouts;</li><li><strong>human approval before execution</strong> — the generated query is displayed to the user, who must explicitly confirm before any database call is made;</li><li>approval-context validation to prevent stale approvals from executing against a changed query;</li><li>audit metadata attached to every generated and approved operation.</li></ul><p>For hybrid questions, the system pauses at the approval step, executes the validated query, retrieves document evidence in parallel, and synthesizes the two evidence types in a single grounded response. This prevents a common design mistake: allowing the LLM to blur a database fact and a policy statement into one answer without distinguishing where either came from.</p><h3>Security and Caching Are Implemented as Layers</h3><p>The application applies defense in depth: authentication, authorization, tenant isolation, input validation, prompt-injection controls, safe SQL enforcement, rate limiting, secret handling via AWS Secrets Manager, response content checks, and audit-friendly metadata on every answer. The number of layers matters less than whether each control has a defined threat model and a testable enforcement point.</p><p>Five query-time cache responsibilities reduce cost and latency:</p><ol><li>RAG answers.</li><li>SQL query generation output.</li><li>SQL execution results.</li><li>Approved SQL and hybrid answers.</li><li>Embeddings.</li></ol><p>Cache keys capture all inputs and feature flags that can change an answer. Critically, retrieval-policy releases advance a <strong>cache schema version</strong>. The finalized release uses RAG_CACHE_SCHEMA_VERSION = 52, which invalidates all prior cached answers and prevents stale evidence decisions from contaminating new evaluation runs.</p><p>This versioning policy came from a concrete failure. Upstash reached its free-tier storage limit mid-project, and later its connection URL changed after an account reset. Both incidents reinforced the same principle: cache availability must affect performance, never correctness. Cache state must never be treated as proof that vectors exist in Qdrant, and a stale cached answer must never be accepted as evidence for a new retrieval implementation.</p><h3>Evaluation Had to Become More Trustworthy Than the Demo</h3><p>The most important work in this project was not raising a metric score. It was making the score harder to fake accidentally.</p><p>Early evaluations exposed several traps:</p><ul><li>familiar questions made a narrowly tuned system look general;</li><li>fuzzy filename matching awarded credit to the wrong source document;</li><li>high recall scores hid distracting noisy chunks alongside correct ones;</li><li>LLM judges varied across semantically equivalent evidence;</li><li>cached responses made a changed retriever appear better than it was;</li><li>a perfect aggregate over a small focused set concealed failures elsewhere.</li></ul><p>The evaluation framework now separates two distinct responsibilities.</p><p><strong>Deterministic Gates (CI/CD)</strong></p><p>Continuous integration runs reproducible checks for route correctness, forbidden behavior, exact source identity, source precision, and source recall. These checks require no LLM API call and are fast enough to block a pull request. A PR cannot merge if it regresses a known source citation or triggers a forbidden answer.</p><p><strong>LLM-Judged Quality (Release Validation)</strong></p><p>Faithfulness, context precision, context recall, and answer relevancy are evaluated using RAGAS on curated regression and challenge datasets. These metrics add real signal, but their probabilistic variance is recorded and tracked — not hidden behind an averaged aggregate. LLM-based judging is reserved for regression runs and pre-release validation, not used as the sole definition of correctness.</p><p>Datasets follow a strict lifecycle: a new <strong>sealed holdout</strong> is run exactly once to produce an unbiased measurement, then moved into the regression set before any fixes are developed. Subsequent tuning uses development and regression questions. Calling a repeatedly inspected dataset “unseen” is an evaluation integrity failure. Raw evaluation reports are excluded from Git; curated summaries that record the evidence trail are committed instead.</p><p><strong>Final Cloud-v2 Results</strong></p><p>Both complete evaluation runs used Qdrant Cloud v2, cache schema 52, gpt-4o for answer generation, and gpt-4o-mini for judging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0ZTkOcmF3Zbp5iGALkOWg.png" /></figure><p>Both runs recorded zero forbidden-answer, forbidden-source, and route violations. A focused schema-52 closure run also achieved 1.000 across all six metrics with zero unsupported claims.</p><p>These are strong results. The focused closure score is evidence that known regressions were resolved — not a claim that every future query will be perfect.</p><p><strong>Documented Residual Cases</strong></p><p>Two findings remain open:</p><ul><li><strong>q-106:</strong> Can retrieve Pod priority/preemption documentation instead of the more specific node-pressure eviction source for a memory-pressure question.</li><li><strong>q-126:</strong> Can correctly explain maxSurge and maxUnavailable while omitting a second expected API-reference source and adding broader rollout context.</li></ul><p>Both are accepted release exceptions and active regression targets. Publishing them is more credible than tuning until one stochastic run displays all ones.</p><h3>Testing, Delivery, and Operations</h3><p>The repository validates more than answer quality. The finalized local verification suite passed:</p><ul><li>178 Pytest unit and integration tests;</li><li>Ruff linting with zero violations;</li><li>Python compilation checks across all modules;</li><li>documentation enforcement (docstring coverage);</li><li>whitespace and repository-diff checks.</li></ul><p>GitHub Actions runs all of the above on every PR, plus deterministic evaluation smoke jobs, dependency auditing with pip-audit, Git-history secret scanning with Gitleaks, and container image vulnerability scanning with Trivy. Full RAGAS evaluations remain a release-time workflow — they cost money, consume LLM quota, and are probabilistic by design.</p><p>Docker Compose provides local backend, frontend, PostgreSQL, Redis, and Qdrant services for development and integration testing. Load tests use k6 across health-check, authenticated RAG, and mixed-workload scenarios. Rate-limit behavior (HTTP 429) is interpreted separately from capacity failures: a throttle response from an intentional per-user policy is not counted as a backend error.</p><p>The AWS production deployment uses:</p><ul><li><strong>ECS Fargate</strong> for the FastAPI backend and Streamlit frontend (no EC2 instance management);</li><li><strong>Application Load Balancer</strong> with ACM-managed TLS termination;</li><li><strong>Route 53</strong> for DNS and health-check routing;</li><li><strong>RDS PostgreSQL</strong> for structured incident and operational data;</li><li><strong>Qdrant Cloud</strong> for vector storage;</li><li><strong>Upstash Redis</strong> for distributed query caching;</li><li><strong>S3</strong> for document storage and ingestion staging;</li><li><strong>AWS Secrets Manager</strong> for all runtime secrets;</li><li><strong>CloudWatch</strong> for logs, dashboards, and operational alarms.</li></ul><p>Deployment verification covers: service rollout health, direct endpoint checks, authentication flow, frontend preset loading, RAG response with source citation, SQL approval and execution, hybrid answer synthesis, cache hit behavior, cost reporting, and multi-turn follow-up correctness.</p><h3>What “Production-Grade” Means Here</h3><p>This project demonstrates production-grade engineering practices:</p><ul><li>clear service boundaries and versioned HTTP APIs;</li><li>defense-in-depth security with testable enforcement points;</li><li>safe SQL execution gated by human approval;</li><li>stress-testing against an intentionally noisy corpus;</li><li>metadata-rich, auditable ingestion with corpus verification;</li><li>deterministic CI gates plus LLM-based release validation;</li><li>containerized local and cloud deployment;</li><li>observability, rate limiting, cost reporting, and operational runbooks;</li><li>explicit rollback guidance and blue/green collection management;</li><li>documented limitations rather than hidden failures.</li></ul><p>There is also work that a larger organization would continue before declaring a universal production platform: Terraform coverage is import-first rather than fully authoritative; database migrations need a mature Alembic history and rollback discipline; distributed tracing and application-level SLO instrumentation should expand beyond current CloudWatch coverage; higher concurrency loads would benefit from more load testing around SQL approval state and connection pooling.</p><p>Production readiness is not a badge earned by adding more folders. It is evidence that a system behaves safely under its declared scope, that failures are observable and recoverable, and that limitations are known and tracked.</p><h3>Six Engineering Lessons</h3><p><strong>1. A strong retriever starts with corpus understanding.</strong><br>Subject-matter knowledge is not optional. The engineer must know which documents are authoritative, which evidence families are complementary, which sources are valid alternatives, and what constitutes a dangerous omission. Generic similarity tuning cannot substitute for that understanding.</p><p><strong>2. Chunking is necessary but not sufficient.</strong><br>Sentence-aware boundaries improved evidence integrity measurably. But parsing quality, metadata richness, authority labeling, retrieval planning, reranking, and synthesis constraints each contributed independently. Improving only chunking while ignoring the others would have left most of the gains on the table.</p><p><strong>3. New questions are more valuable than repeated perfect scores.</strong><br>The system’s most significant weaknesses appeared on unseen, ambiguous, and adversarial questions — not on familiar ones. A dataset stops being a holdout the moment it informs a fix.</p><p><strong>4. Evaluation code is production code.</strong><br>Incorrect source matching, loose filename comparison, and impossible metric combinations can all create false confidence. Evaluators require schemas, validation tests, and code review with the same rigor as the application itself.</p><p><strong>5. Cache invalidation is part of AI correctness.</strong><br>When retrieval policy or synthesis behavior changes, a stale cached answer is not merely old data — it is invalid experimental evidence. Versioning the cache schema became a required step in every release.</p><p><strong>6. Honest residuals make the result stronger.</strong><br>No serious retrieval system should claim perfection from a single run. Strong aggregate evidence paired with explicit regression targets is a more credible engineering outcome than a polished but irreproducible scorecard.</p><h3>Closing Thoughts</h3><p>Enterprise Advanced RAG began as a document question-answering project and evolved into a complete evidence system: intelligent routing, advanced retrieval, safe SQL with human oversight, conversational memory, metadata-rich ingestion, layered security, distributed caching, cloud deployment, observability, load testing, and evaluation governance.</p><p>The hardest part was not connecting an LLM to a vector database. It was recognizing where confidence could be misleading — a relevant but incomplete chunk, a noisy source with a high score, a stale cached answer, an evaluator crediting the wrong filename, or a sealed dataset that had been inspected one too many times.</p><p>The final system is one I can present confidently because its strengths are supported by 178 tests, deterministic CI gates, and live Cloud-v2 RAGAS evidence — and its remaining limitations are documented, not hidden. That combination of capability, measurement, and honesty is what separates a RAG demo from credible production engineering.</p><p><em>Full implementation, evaluation reports, CI/CD configuration, and deployment documentation are available on </em><a href="https://github.com/vthottempudi1/NEW-ADV-RAG-IMPLEMENT"><em>GitHub → vthottempudi1/NEW-ADV-RAG-IMPLEMENT</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f30e2025dad" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/building-an-enterprise-grade-advanced-rag-system-what-it-took-beyond-the-demo-3f30e2025dad">Building an Enterprise-Grade Advanced RAG System: What It Took Beyond the Demo(Full Article &amp;…</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>