<?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 Plaban Roy on Medium]]></title>
        <description><![CDATA[Stories by Plaban Roy on Medium]]></description>
        <link>https://medium.com/@plabroy?source=rss-972489c2d916------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aLBku41BUsi65jth.jpg</url>
            <title>Stories by Plaban Roy on Medium</title>
            <link>https://medium.com/@plabroy?source=rss-972489c2d916------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:06:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@plabroy/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[How to Build RAG That Handles 1M PDFs: The 2026 Production Playbook]]></title>
            <link>https://medium.com/@plabroy/how-to-build-rag-that-handles-1m-pdfs-the-2026-production-playbook-f4b995bcf26c?source=rss-972489c2d916------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4b995bcf26c</guid>
            <category><![CDATA[agentic-rag]]></category>
            <dc:creator><![CDATA[Plaban Roy]]></dc:creator>
            <pubDate>Sat, 16 May 2026 00:19:48 GMT</pubDate>
            <atom:updated>2026-05-16T00:19:48.779Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Everyone thinks RAG fails at scale. Actually — your architecture fails first.</em></p><p>In 2024, it was enough to shove some PDFs into a vector database, run a cosine similarity search, and call it a day. In 2026, that approach — Naive RAG — is a prototype at best and a liability at worst.</p><p>Here’s the uncomfortable truth: <strong>when RAG fails in production, the retrieval step is the culprit 73% of the time</strong> — not generation. The LLM generates confident, well-structured answers grounded in the wrong documents. Your users never know the answer is wrong until they act on it.</p><p>The generation side isn’t the bottleneck anymore. Models like Claude 4.6, GPT-5.4, and Gemini 3.1 Pro are hyper-intelligent. The failure point is almost always the retrieval. If you’ve ever watched a model hallucinate because your retriever pulled in three irrelevant paragraphs and missed the one critical sentence buried in a table, this guide is for you.</p><p>This article presents a <strong>6-layer production architecture</strong> for building RAG systems that scale to millions of documents — with specific tools, benchmarks, and metrics from 2026.</p><h3>The 2026 Shift: Agentic RAG Is the New Default</h3><p>Before diving into the layers, let’s address the paradigm shift that changed everything.</p><p><strong>Static retrieve-then-generate pipelines are dead.</strong></p><p>The dominant pattern in 2026 is <strong>Agentic RAG</strong> — systems where specialized agents handle retrieval and validation in parallel, making autonomous decisions about what to retrieve, how to evaluate it, and when to re-retrieve.</p><p>An agentic RAG system doesn’t just retrieve information. It <strong>decides</strong> to retrieve information, evaluates whether that information is sufficient, identifies gaps, pulls additional context, synthesizes findings, and presents results. The agent can loop, branch, and adapt its strategy based on what it finds along the way.</p><p>Here’s what this looks like in practice. Imagine a user asks an internal assistant: <em>“What’s our refund policy for enterprise customers in Germany, and has it changed since last quarter?”</em></p><p>A classic RAG pipeline would embed the whole question and hope the top chunks cover both parts. An agentic system instead:</p><ol><li><strong>Plans:</strong> Identifies two sub-questions — current policy and changes over time</li><li><strong>Retrieves #1:</strong> Vector search for “enterprise refund policy Germany” → finds the current policy document</li><li><strong>Evaluates:</strong> Checks if the retrieved context answers the temporal component — it doesn’t</li><li><strong>Retrieves #2:</strong> Targeted search for policy changelog or version history</li><li><strong>Synthesizes:</strong> Combines both retrievals into a grounded, cited answer</li></ol><p>This is the single biggest quality unlock over classic pipelines. And it’s powered by several converging innovations:</p><ul><li><strong>Self-RAG and Corrective RAG</strong> validate retrieval quality before generation. After each retrieval, the agent evaluates whether results are relevant and complete. If not, it rewrites the query and tries again.</li><li><strong>Graph-augmented RAG (GraphRAG)</strong> structures knowledge as a graph, enabling multi-hop reasoning and cross-document relationship queries. Context-graph-grounded RAG achieves up to 5× improvements in AI analyst response accuracy over raw schemas.</li><li><strong>Model Context Protocol (MCP)</strong> became the standard retrieval-tool surface after Anthropic donated it to the Linux Foundation’s Agentic AI Foundation in late 2025, and OpenAI plus Google adopted it. It provides a universal interface for agents to interact with retrieval tools.</li><li><strong>The strongest 2026 stacks combine both:</strong> agentic orchestration (via LangGraph or LlamaIndex Workflows) over a graph-backed knowledge base.</li></ul><p>The takeaway: if you’re still building linear pipelines, you’re building yesterday’s architecture.</p><h3>Layer 1 — Ingestion Pipeline: Stop Chunking Blindly</h3><h3>The Chunk Explosion Problem</h3><p>Most teams blindly chunk PDFs and flood the vector database. This is where RAG pipelines silently fail.</p><p>A Vectara study published at NAACL 2025 tested 25 chunking configurations with 48 embedding models and found that <strong>chunking configuration had as much or more influence on retrieval quality as the choice of embedding model.</strong> In Chroma’s evaluation, the gap between the best and worst chunking strategy on the same corpus reached 9% in recall.</p><p>Two failure modes dominate:</p><ul><li><strong>Chunks too small</strong> lose context. In the FloTorch 2026 benchmark, semantic chunking produced fragments averaging 43 tokens that scored only 54% accuracy on end-to-end questions.</li><li><strong>Chunks too large</strong> dilute relevance signals. The embedding vector shifts toward noisy centroids, reducing retrieval discriminability.</li></ul><h3>The 2026 Chunking Stack</h3><p><strong>Semantic chunking</strong> splits documents based on meaning rather than fixed character counts. It uses embedding similarity to detect topic boundaries — when the cosine similarity between consecutive sentences drops below a threshold, it creates a new chunk. Semantic chunking typically improves retrieval accuracy by 10–20% over fixed-size methods.</p><p><strong>Agentic chunking</strong> takes this further. An LLM “reads” the document and creates a logical outline before indexing — treating it like a human writing study notes. For legal documents, this means converting each clause into self-contained factual propositions with metadata (contract ID, section number, clause type, effective date).</p><p><strong>Practical defaults:</strong></p><ul><li>Start with 512–1024 tokens with 10–20% overlap as a baseline</li><li>For technical documentation, use 256–512 tokens to keep concepts focused</li><li>For narrative content, use 1024–2048 tokens to preserve context</li><li>One January 2026 study using SPLADE retrieval found overlap provided no measurable benefit for sparse retrieval — always benchmark with your data</li></ul><p><strong>The complete ingestion pipeline:</strong></p><ol><li><strong>PDF parser</strong> (pdfplumber or PyMuPDF) → extract raw text + metadata</li><li><strong>Semantic chunker</strong> → split on paragraph/section boundaries, not fixed tokens</li><li><strong>Deduplicator</strong> → SHA-256 hash per chunk before insert. This alone cuts index size by 40%+</li><li><strong>Metadata enricher</strong> → attach doc_id, section, date, type, page_num to every chunk</li></ol><p><strong>Payoff: 3× better relevance · 50% fewer embeddings</strong></p><h3>Layer 2 — Embedding &amp; Storage</h3><p>Your embedding model determines how well your retrieval captures semantic meaning. A bad embedding model means the right chunks are never retrieved in the first place — no amount of reranking downstream can fix a fundamentally flawed vector space.</p><h3>The 2026 Embedding Leaderboard</h3><p>The open-source embedding landscape has matured dramatically. Open-source models now surpass commercial APIs on benchmark quality:</p><p><strong>Voyage AI voyage-3-large</strong> — The highest retrieval quality at production scale among commercial options. Optimized specifically for query-document asymmetry (queries are short, documents are long), making it ideal for RAG.</p><p><strong>Qwen3-Embedding-8B</strong> — Scoring 70.6 on MTEB, this open-source model surpasses all API models including OpenAI (64.6) and Google (68.3). The gap reversed in 2025–2026. For organizations with GPU infrastructure, open source is now the optimal choice for pure quality.</p><p><strong>Cohere Embed v4</strong> — The only production-ready multimodal embedding model. If you process visual documents (PDFs with charts, catalogs, slides), it eliminates the need for complex OCR pipelines. For pure text at high volume, cheaper alternatives are preferable.</p><p><strong>BGE-M3</strong> — The best self-hosted option that matches commercial API quality. Supports 100+ languages and provides dense, sparse, and ColBERT representations in a single model.</p><p><strong>The Matryoshka technique</strong> — A game-changer for storage costs. You can reduce embedding dimensions from 1024 to 256 with only 2–3% precision loss, cutting storage costs by 4×. At scale, this translates to tens of thousands of dollars in vector database savings.</p><h3>Storage Architecture</h3><ul><li><strong>Batch embed offline</strong> — never at query time. This eliminates runtime spikes and decouples ingestion from serving.</li><li><strong>Store in partitioned vector databases</strong> — Qdrant, Weaviate, or Pinecone namespaces. Partition by domain, tenant, or document type for query isolation.</li><li><strong>Keep a relational store</strong> (PostgreSQL) alongside the vector DB for full-text search and metadata queries. This becomes critical for hybrid retrieval in Layer 3.</li><li><strong>Target throughput:</strong> 500–1000 docs/min with parallel ingest workers.</li></ul><p><strong>Payoff: No runtime spikes · Scalable ingest throughput</strong></p><h3>Layer 3 — Hybrid Retrieval: Single Vector Search Won’t Survive 1M Documents</h3><h3>The Retrieval Bottleneck Trap</h3><p>Single vector search won’t survive a million PDFs. The cosine distance between query embedding and document embedding is a blunt instrument for fine-grained relevance scoring. Dense embeddings capture meaning but miss exact terms, part numbers, and rare entities. Sparse methods (BM25) capture those exact terms but miss semantic relationships.</p><p>The answer is hybrid — and in 2026, this is non-negotiable for production.</p><h3>The 4-Step Hybrid Retrieval Pipeline</h3><p><strong>Step 1: Metadata pre-filter.</strong> Before any search happens, narrow the candidate set using structured metadata — doc_type, date range, tenant_id, access controls. This alone reduces the search space by 10×.</p><p><strong>Step 2: BM25 sparse retrieval</strong> on keyword candidates. This catches exact matches, acronyms, product codes, and rare terminology that dense embeddings frequently miss.</p><p><strong>Step 3: Dense ANN search</strong> on the filtered namespace. This captures semantic relationships — questions phrased differently than the answer, paraphrases, conceptual matches.</p><p><strong>Step 4: Reciprocal Rank Fusion (RRF)</strong> to merge both result sets. RRF is elegant: it assigns scores based on rank position rather than raw similarity scores, making it robust to different scoring scales between BM25 and dense search.</p><h3>Governance First</h3><p>Enterprise RAG fails without governance. <strong>Access controls and context must precede retrieval</strong>, not follow it. If a junior analyst can retrieve board-level financial projections because your vector DB has no permission layer, you have a compliance incident waiting to happen.</p><p>Implement row-level security at the metadata filter stage. Every chunk should carry permission metadata inherited from its source document.</p><p><strong>Payoff: 10× smaller search space · 2× answer quality · same latency</strong></p><h3>Layer 4 — Reranking: The Highest-ROI Addition to Any RAG Pipeline</h3><h3>Why Reranking Matters</h3><p>Your top-20 vector search results are probably all semantically relevant. Their order, though, is noise. The model that produced those embeddings encoded each one independently — it had no idea, while encoding your document, what query it would eventually need to match against.</p><p>This fundamental mismatch is what reranking solves. It leads directly to the <strong>two-stage retrieval paradigm</strong> that is now the correct mental model for production RAG:</p><ul><li><strong>Stage 1 (Retrieve broadly):</strong> Cast a wide net. Retrieve 50–100 candidates using hybrid search.</li><li><strong>Stage 2 (Rank precisely):</strong> Use a cross-encoder model to score each candidate against the specific query and reorder them. Output: top 5, ranked by true relevance.</li></ul><p>Databricks research shows reranking can improve retrieval quality by up to 48%. Reranking was consistently identified as a higher-ROI improvement than swapping embedding models.</p><h3>The 2026 Reranker Leaderboard</h3><p><strong>Cohere Rerank 4 Pro</strong> — Ranked among the top worldwide with 1627 ELO on the BEIR leaderboard. It offers a 32K context window and strong performance on business and finance tasks.</p><p><strong>Voyage rerank-2.5</strong> — Offers the best balance between quality and latency, with approximately 2× lower latency than competitors. For production systems where speed and quality both matter, this is the go-to.</p><p><strong>ZeroEntropy zerank-1</strong> — Delivers +28% NDCG@10 improvements over baseline retrievers. Its key differentiator: calibrated scores out-of-the-box, meaning you don’t need to tune relevance thresholds manually.</p><p><strong>BGE-reranker-v2-m3</strong> — The open-source champion. Supports 100+ languages with Apache 2.0 licensing. If you need to self-host for data sovereignty or cost reasons, this is production-ready.</p><h3>Implementation Tips</h3><ul><li>Cross-encoder rerankers run on <strong>CPU</strong> — they’re cheap, fast, and high-impact. No GPU required.</li><li>Rerank 50–75 candidates for optimal NDCG@10. Beyond 100, quality improvements plateau while costs increase linearly.</li><li><strong>Log reranker scores</strong> for every request. These scores become your offline evaluation dataset and your early warning system for retrieval drift.</li></ul><p><strong>Payoff: +20–40% top-5 accuracy · modest latency cost (50–400ms)</strong></p><h3>Layer 5 — Context Assembly: Less Context = Better Answers</h3><h3>The Context Overload Illusion</h3><p>More context ≠ better answers. It kills signal and inflates cost.</p><p>Context window pollution is the silent quality killer in production RAG. Retrieving 10 chunks when only 2 are relevant dilutes the signal. The LLM averages across all context, producing a mediocre answer instead of a precise one.</p><p>Even with 1M-token context windows available in 2026, the problem isn’t capacity — it’s relevance density. A 200K-token context stuffed with marginally related paragraphs performs worse than a 4K-token context with exactly the right information.</p><h3>The Context Assembly Pipeline</h3><ol><li><strong>Retrieve top 5–10 chunks only.</strong> Larger k does not mean better answers — it means more noise. Start with 5 and increase only if recall metrics demand it.</li><li><strong>Compress chunks over 300 tokens</strong> using extractive summarization. This preserves key facts while reducing token count.</li><li><strong>Pack the context window</strong> at 60–70% fill. Never exceed the model’s limit, and leave room for the system prompt and generation.</li><li><strong>Apply MMR (Max Marginal Relevance)</strong> to remove redundant chunks. If three chunks all say the same thing, you’re wasting context budget and confusing the model.</li><li><strong>Attach citation metadata</strong> — [source, page, section] per chunk. This enables the LLM to ground its response in specific sources.</li><li><strong>Use Anthropic’s Citations API</strong> for guaranteed source pointers. The cited text doesn’t count against output tokens, making citation essentially free.</li></ol><p><strong>Payoff: 25% fewer hallucinations · cleaner, auditable outputs</strong></p><h3>Layer 6 — Caching, Latency &amp; Observability</h3><h3>The Latency Death Spiral</h3><p>More data = slower queries unless you architect for it from day one. At million-document scale, every unnecessary millisecond compounds into user abandonment and infrastructure cost.</p><h3>Speed Optimizations</h3><p><strong>Semantic query cache (Redis):</strong> Cache the embedding + top retrieval results per query hash. Semantically similar queries should hit the same cache entry. Set TTL at 1 hour for volatile data, 24 hours for stable corpora. This alone saves 30–60% of inference cost.</p><p><strong>Partition indexes by domain or tenant:</strong> Instead of searching one massive index, route queries to the relevant partition. This cuts query time from 2 seconds to 200ms — a 10× improvement that users immediately feel.</p><p><strong>Adaptive RAG:</strong> Not every query needs retrieval. If the LLM already knows the answer (common knowledge, simple definitions), skip retrieval entirely. Adaptive RAG systems dynamically decide whether to retrieve based on query analysis, saving compute on the 20–30% of queries that don’t need external context.</p><h3>Observability Stack</h3><p>You can’t improve what you can’t measure. The RAG evaluation landscape matured significantly in 2026:</p><p><strong>RAGAS</strong> (Retrieval Augmented Generation Assessment) is the standard open-source framework for reference-free RAG evaluation. Four core metrics that every production system should track:</p><ul><li><strong>Faithfulness ≥ 0.9</strong> — Is the answer factually consistent with the retrieved context?</li><li><strong>Answer relevancy ≥ 0.85</strong> — Does the answer actually address the question?</li><li><strong>Context precision ≥ 0.8</strong> — Are the retrieved chunks actually relevant to the question?</li><li><strong>Context recall</strong> — Did we retrieve all the chunks needed to answer the question?</li></ul><p><strong>Arize Phoenix</strong> — Open-source observability platform. Takes high-dimensional embeddings from your RAG application, reduces dimensionality, and clusters them into semantically meaningful groups. You can then inspect performance across specific data clusters — finding the exact types of queries where retrieval fails.</p><p><strong>Langfuse</strong> — Lightweight tracing for trajectory analysis. Track every request through the full pipeline: retrieval latency, rerank scores, LLM tokens used, and user feedback signals.</p><p><strong>TruLens</strong> — Combines OpenTelemetry-based tracing with evaluation metrics attached to individual spans. This gives a complete picture of where a pipeline is failing — at the planning step, retrieval step, or generation step.</p><p><strong>Drift monitoring:</strong> Run weekly regression tests on a frozen golden set of question-answer pairs. If faithfulness drops below your threshold, you know something changed — new data, model drift, or infrastructure issues.</p><p><strong>Payoff: Sub-second responses at million-scale · 30–60% inference cost savings · continuous quality tracking</strong></p><h3>Quick Reference Checklist</h3><p>Layer Tool / Pattern Win Chunking Semantic split + SHA-256 dedup +40% index efficiency Embedding Batch offline, partitioned (Voyage/Qwen3/BGE-M3) No runtime spikes Retrieval BM25 + ANN + metadata filter + RRF 10× smaller search space Reranking Cross-encoder (top 50 → 5) +20–40% top-5 accuracy Context Compress + cite + MMR 25% fewer hallucinations Caching Semantic query cache (Redis) 30–60% cost reduction Eval RAGAS faithfulness loop Continuous quality tracking</p><p><strong>The retrieval pipeline in one line:</strong></p><pre>Query → Meta Filter → BM25 + ANN → RRF Merge → Rerank → LLM</pre><h3>The Bottom Line</h3><p>RAG at scale in 2026 isn’t about more data. It’s about <strong>controlled, governed, agentic retrieval.</strong></p><p>The teams winning aren’t the ones with the biggest vector databases. They’re the ones who treat retrieval as an engineering discipline — with the same rigor they’d apply to a database query optimizer or a distributed systems design.</p><p>Six layers. Each one independently measurable. Each one independently improvable.</p><p>Fix the architecture first. The scale takes care of itself.</p><p><em>If you found this useful, follow me for more deep dives on AI architecture, data engineering, and building production-grade AI systems in regulated industries.</em></p><p><em>What’s the hardest RAG scaling challenge you’ve hit? Drop it in the comments — I read every one.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4b995bcf26c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polypharmacy Is a Network Problem — So Why Are We Still Checking Drugs in Pairs?]]></title>
            <link>https://medium.com/@plabroy/polypharmacy-is-a-network-problem-so-why-are-we-still-checking-drugs-in-pairs-8b8ffe717e41?source=rss-972489c2d916------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b8ffe717e41</guid>
            <dc:creator><![CDATA[Plaban Roy]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 03:04:41 GMT</pubDate>
            <atom:updated>2026-03-01T03:04:41.720Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beyond Pairwise: Why Nobody Is Building Multi-Drug Cascade Detection for Polypharmacy — And Why We Did</h3><p><strong>Plaban Roy</strong><br>Founder, OmCareRx<br>Independent Research | Clinical Decision Support</p><p>Polypharmacy is not a corner case in modern medicine.</p><p>It is the default.</p><p>More than 40% of hospitalized adults over 65 take five or more medications. Many take eight. Some take twelve. And while clinicians work heroically to manage these regimens, the tools we give them to detect harm are fundamentally incomplete.</p><p>Here is the uncomfortable truth:</p><p><strong>Almost every clinical decision support system on the market today checks drug interactions in pairs.</strong></p><p>Drug A + Drug B → interaction.<br>Drug B + Drug C → interaction.</p><p>That’s it.</p><p>But patients don’t take medications in pairs.<br>They take them in networks.</p><p>And nobody — not the legacy vendors, not the startups, not the LLM crowd — is detecting multi-drug cascades at the point of care.</p><p>Until now.</p><h3>The Structural Blind Spot in Pairwise Interaction Checking</h3><p>Let’s make this concrete.</p><p>Consider a hospitalized older adult taking:</p><ul><li>Simvastatin</li><li>Amiodarone</li><li>Warfarin</li><li>Amlodipine</li></ul><p>A traditional interaction checker will flag:</p><ul><li>Simvastatin + Amiodarone → ↑ rhabdomyolysis risk</li><li>Amiodarone + Warfarin → ↑ bleeding risk</li><li>Amlodipine + Simvastatin → ↑ statin levels</li></ul><p>Three alerts. All separate.</p><p>But what it cannot see is the cascade:</p><ol><li>Amlodipine inhibits CYP3A4 → raises Simvastatin</li><li>Amiodarone further inhibits CYP3A4 and P-gp → compounding statin elevation</li><li>Rhabdomyolysis → renal injury</li><li>Impaired renal function → worsened Warfarin clearance</li><li>Bleeding risk escalates non-linearly</li></ol><p>That’s not three pairwise interactions.</p><p>That’s a <strong>4-drug cascade with compounding lethality</strong>.</p><p>No pairwise system is architected to detect that structure.</p><p>Not because vendors don’t care.</p><p>Because their entire data model is wrong.</p><h3>The Research Already Proved This — But No One Operationalized It</h3><p>In 2025, the HODDI dataset (High-Order Drug-Drug Interactions) analyzed over 100,000 FDA adverse event reports and confirmed what clinicians already suspect:</p><blockquote><em>Higher-order drug interactions are real, measurable, and clinically significant.</em></blockquote><p>Similarly, the HyperADRs framework showed hypergraph models outperform traditional pairwise graph approaches in capturing complex drug interaction structures.</p><p>But here’s the gap:</p><p>These are research papers.</p><p>They are not point-of-care tools.<br>They do not ingest FHIR data.<br>They do not generate actionable deprescribing plans.<br>They do not run in under one second inside an EHR.</p><p>The research community validated the problem.</p><p>Nobody built the clinical engine.</p><h3>Why LLMs Are Not the Answer</h3><p>There’s a growing belief that large language models will “solve” drug safety.</p><p>The data does not support that claim.</p><p>Recent 2025 benchmarks evaluating GPT-4o-mini, MedGemma-27B, and LLaMA3–70B across 750 clinician-annotated DDI scenarios showed:</p><ul><li>Best model accuracy: ~70%</li><li>Self-consistency drops as complexity increases</li><li>Reliability is not uniform across formats</li></ul><p>When complexity increases — exactly when cascade detection matters — performance degrades.</p><p>LLMs are probabilistic.<br>Clinical safety must be deterministic.</p><p>We don’t need “creative reasoning” in drug interaction detection.</p><p>We need:</p><ul><li>Reproducibility</li><li>Audit trails</li><li>Explainability</li><li>Zero stochastic variation</li></ul><h3>Introducing OmCareRx</h3><p>OmCareRx is a multi-agent clinical decision support system built around one core principle:</p><blockquote><strong><em>Patients are networks. Interaction detection must be network-aware.</em></strong></blockquote><p>It is the first system — to our knowledge — that integrates:</p><ol><li>FHIR R4 native patient ingestion</li><li>Pairwise drug interaction detection</li><li><strong>N-way cascade detection (3–5 drugs)</strong></li><li>Drug-food screening</li><li>Drug-lab cross-referencing against actual patient labs</li><li>Beers 2023, STOPP/START v2, KDIGO, ADA cross-checks</li><li>Automated deprescribing recommendations</li><li>Full audit trail with citation chains</li></ol><p>In a single orchestrated pipeline.</p><p>Nobody else is doing all of this together.</p><h3>The Architecture</h3><p>OmCareRx is built as a six-agent system:</p><pre>FHIR R4 Bundle<br>   ↓<br>Patient Context Agent<br>   ↓<br>Drug Interaction Agent (Pairwise + Cascade Engine)<br>   ↓<br>Drug-Food Agent<br>   ↓<br>Drug-Lab Agent<br>   ↓<br>Guidelines Agent<br>   ↓<br>Deprescribing Agent<br>   ↓<br>Unified Safety Report</pre><p>Each agent is deterministic.<br>Each step is logged.<br>Each finding is traceable.</p><p>This is not a chatbot.<br>This is a clinical engine.</p><h3>The Core Innovation: N-Way Cascade Detection</h3><h3>1. Directed Interaction Graph</h3><p>We convert detected pairwise interactions into a directed graph:</p><ul><li>Nodes → drugs</li><li>Edges → interactions</li><li>Edge annotations → mechanism, severity, endpoint</li></ul><p>From that graph, we detect:</p><ul><li>Linear cascades (A → B → C → D)</li><li>Convergent cascades (multiple drugs → same endpoint)</li><li>Patient-amplified cascades (CKD, age ≥75, hyperkalemia, INR elevation)</li></ul><h3>2. Real Example: Triple QT Convergence</h3><p>Imagine a patient on:</p><ul><li>Azithromycin</li><li>Haloperidol</li><li>Amiodarone</li></ul><p>Each drug independently prolongs QT.</p><p>Pairwise systems generate three moderate alerts.</p><p>Our cascade engine detects:</p><blockquote><em>Three independent QT-prolonging pathways converging on torsades de pointes.</em></blockquote><p>This becomes a <strong>critical convergent cascade</strong>.</p><p>That is structurally invisible to pairwise logic.</p><h3>3. Real Example: Triple CNS / Respiratory Depression</h3><p>Patient on:</p><ul><li>Diazepam</li><li>Oxycodone</li><li>Gabapentin</li></ul><p>Each contributes sedation.</p><p>No single pair produces a “respiratory arrest” flag.</p><p>But three together?</p><p>That is a convergent cascade on the respiratory depression endpoint.</p><p>Detected. Ranked. Elevated.</p><h3>Validation: 18 FHIR R4 Patients</h3><p>We validated across:</p><ul><li>12 live SMART Health IT FHIR R4 sandbox patients</li><li>6 Synthea-generated high-acuity patients</li></ul><p>Average medications: 6.3<br>Range: 3–9</p><h3>Results</h3><ul><li>20 pairwise DDIs detected</li><li>15 multi-drug cascades detected</li><li>14 cascades rated CRITICAL</li><li>23 drug-food interactions</li><li>34 drug-lab cross-references</li><li>4 clinically concerning lab amplifications</li><li>16 deprescribing recommendations</li></ul><p>All under 2 milliseconds of computation per patient (excluding network latency).</p><p>Most importantly:</p><ul><li>4/6 high-acuity patients had cascades</li><li>0/12 naturalistic FHIR patients triggered false cascade alerts</li></ul><p>Sensitivity without alert explosion.</p><h3>What Makes This Different</h3><h3>1. Deterministic</h3><p>Identical input → identical output.</p><p>100% reproducible.</p><p>No prompt variation.<br>No temperature tuning.<br>No hallucinations.</p><h3>2. Fully Auditable</h3><p>Every finding traces to:</p><ul><li>Structured knowledge base entry</li><li>Evidence level (Established / Probable / Suspected)</li><li>Mechanism (CYP3A4, CYP2C9, P-gp, etc.)</li><li>Clinical endpoint</li><li>Citation chain</li></ul><p>This aligns with FDA draft guidance on clinical decision support requiring proportional evidence for clinical impact.</p><h3>3. Patient-Specific Contextualization</h3><p>Pairwise systems treat:</p><p>Ciprofloxacin + Theophylline<br>the same in:</p><ul><li>eGFR 90</li><li>eGFR 28</li></ul><p>We don’t.</p><p>Renal impairment amplifies risk.<br>Elevated potassium amplifies RAAS interactions.<br>INR &gt;3 amplifies warfarin cascades.</p><p>Interaction severity is patient-specific.</p><h3>4. Integrated Safety Model</h3><p>Most hospitals use separate systems for:</p><ul><li>Drug interactions</li><li>Lab monitoring</li><li>Dietary alerts</li><li>Guideline compliance</li><li>Deprescribing</li></ul><p>We integrated all of it.</p><p>Nobody else has unified cascade detection, drug-food, drug-lab, guideline cross-checks, and automated alternatives in a single deterministic engine.</p><h3>The Hard Truth</h3><p>Polypharmacy is a network problem.</p><p>Healthcare built a pairwise solution.</p><p>We kept asking:</p><p>Why is no one doing N-way detection in production?</p><p>The answer was sobering:</p><ul><li>Legacy vendors are built on decades-old pairwise databases</li><li>LLM companies rely on probabilistic reasoning</li><li>Research papers stop at validation, not deployment</li><li>Deprescribing tools don’t integrate interaction graphs</li></ul><p>There was no technical reason it couldn’t be done.</p><p>It just hadn’t been engineered.</p><p>So we engineered it.</p><h3>Limitations (Because Real Systems Have Them)</h3><ul><li>Current KB: 80 DDIs (expanding to 300+)</li><li>Retrospective validation only</li><li>No prospective hospital RCT yet</li><li>Rule-based → no discovery of unknown interactions</li><li>Single research team</li></ul><p>We are not claiming solved medicine.</p><p>We are claiming:</p><p><strong>The structural problem is now addressed.</strong></p><h3>Why This Matters</h3><p>In hospitalized older adults:</p><ul><li>84% have at least one potentially inappropriate medication</li><li>ADEs cause ~125,000 deaths annually in the U.S.</li><li>Multi-drug cascades are under-recognized</li></ul><p>If we only detect interactions two at a time,<br>we will always underestimate risk.</p><p>OmCareRx reframes the question from:</p><p>“Does Drug A interact with Drug B?”</p><p>to:</p><p>“What network risk structure does this entire medication graph create for this specific patient?”</p><p>That’s a different paradigm.</p><p>And as far as we can tell —</p><p><strong>Nobody else is deploying it this way.</strong></p><h3>What Comes Next</h3><ul><li>Knowledge base expansion (300+ DDIs)</li><li>Multi-institutional pharmacist validation</li><li>CDS Hooks integration inside EHR workflows</li><li>Prospective hospital study</li><li>LLM narrative layer (explanation only, not detection)</li></ul><p>The detection engine stays deterministic.</p><h3>Final Thought</h3><p>Healthcare digitized the chart.</p><p>It digitized prescriptions.</p><p>It digitized alerts.</p><p>But it never digitized the interaction network.</p><p>Polypharmacy is not pairwise.</p><p>It is graph-structured.</p><p>And until interaction detection becomes graph-structured at the point of care,</p><p>we will keep missing the cascades.</p><p>OmCareRx is our attempt to close that gap.</p><p>— <br>Plaban Roy<br>Founder, OmCareRx</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b8ffe717e41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecting Persistent Multi-Turn Conversations on Stateless NL-to-SQL APIs]]></title>
            <link>https://medium.com/@plabroy/architecting-persistent-multi-turn-conversations-on-stateless-nl-to-sql-apis-c4632ab535d4?source=rss-972489c2d916------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4632ab535d4</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[fastap]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[enterprise-ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Plaban Roy]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 02:31:56 GMT</pubDate>
            <atom:updated>2026-02-18T02:31:56.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Production-Tested Enterprise Architecture Built on Snowflake Cortex Analyst</h3><p><em>By Plaban Roy · Senior Data Engineer · Architecting AI Systems for Enterprise Analytics · February 2026</em></p><p>Conversational analytics is easy in a demo.<br>It is extremely difficult in a regulated enterprise.</p><p>This is the architecture we built to make it work.</p><blockquote><strong><em>TL;DR:</em></strong><em> LLM APIs are stateless — every call forgets everything. Building real conversational analytics on top of a stateless NL-to-SQL API in a regulated enterprise environment requires a deliberate Session Management Layer.</em></blockquote><blockquote><em>This paper presents a </em><strong><em>production-tested architecture</em></strong><em> for enabling persistent multi-turn analytics on top of stateless NL-to-SQL APIs — without modifying the underlying model infrastructure.</em></blockquote><h3>The Problem: LLMs Don’t Remember</h3><p>Large language model APIs are inherently stateless. Each API call is processed independently with no memory of prior interactions.</p><p>This is well understood.</p><p>But building <strong>persistent multi-turn conversational analytics</strong> on top of a stateless NL-to-SQL API — inside a regulated enterprise environment — introduces a distinct and underexplored set of engineering challenges.</p><p>This paper presents the architecture we designed for enabling multi-turn conversation on <strong>Snowflake Cortex Analyst</strong>, Snowflake’s stateless REST API for natural language to SQL translation.</p><p>We’ll cover:</p><ul><li>The core architectural problem</li><li>The Session Management Layer design</li><li>Token budget strategy</li><li>Result-set state handling</li><li>Enterprise security considerations</li><li>Production learnings</li></ul><p>Our implementation demonstrates that meaningful conversational analytics experiences can be built on fully stateless APIs — <strong>without modification to the underlying model infrastructure</strong>.</p><h3>Why Conversational Analytics Needs Memory</h3><p>The promise of conversational analytics — where business users explore data through dialogue — depends critically on one capability:</p><blockquote><strong><em>Memory.</em></strong></blockquote><p>A user who asks:</p><blockquote><em>“What were total sales last quarter?”</em></blockquote><p>followed by:</p><blockquote><em>“Break that down by region”</em></blockquote><p>expects contextual understanding.</p><p>Modern NL-to-SQL systems like Snowflake Cortex Analyst deliver impressive single-turn accuracy. But they expose a <strong>stateless REST API</strong>. Every request must include the full conversation context. There is no server-side session. There is no hidden memory.</p><p>For generic chatbots, the solution is simple: send the full message history every time.</p><p>In enterprise NL-to-SQL systems, that naive approach breaks down.</p><h3>Four Constraints That Make This Hard</h3><h3>1. SQL Result Statefulness</h3><p>The API cannot access prior query results.</p><p>If turn 1 returns a list of products and turn 2 refers to “the second product,” the API has no knowledge of that result set.</p><h3>2. Regulated Environment Constraints</h3><p>Enterprise deployments operate under:</p><ul><li>SSO authentication</li><li>Role-based data access</li><li>Network perimeter restrictions</li><li>Audit requirements</li></ul><p>Many third-party memory services are not permitted.</p><h3>3. Token Budget Explosion</h3><p>In NL-to-SQL:</p><ul><li>Responses include SQL statements</li><li>SQL may be 50–100+ lines</li><li>Explanations add verbosity</li></ul><p>Each turn can be <strong>300–800 tokens</strong>.</p><p>Full-history injection becomes unsustainable quickly.</p><h3>4. Multi-User Isolation</h3><p>Concurrent users must have:</p><ul><li>Guaranteed session isolation</li><li>Zero cross-contamination</li><li>Strict user-scoped memory access</li></ul><h3>The Naive Approach vs. The Production Approach</h3><p>ApproachProblemSend full history every timeToken explosionNo history injectionNo multi-turn capabilityPersist full SQL payloadsSevere token inefficiencyIgnore result setsFollow-up questions fail<strong>Session Management Layer (ours)</strong>Controlled context + scalable memory</p><h3>The Architecture</h3><h3>High-Level System Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*xka4er3BMV_NQb9t.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/0*waYmpp3O75lLSTfy.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XUTEuSNApofpK9lA.png" /></figure><p>The architecture introduces a <strong>Session Management Layer (SML)</strong> between the client and Snowflake Cortex Analyst.</p><pre>CLIENT APPLICATION<br>       ↓<br>   /chat/query POST (FastAPI)<br>       ↓<br>SESSION MANAGEMENT LAYER<br>   - Session Store<br>   - Context Builder<br>   - Token Budget Manager<br>   - Result Context Injector<br>       ↓<br>SNOWFLAKE CORTEX ANALYST (Stateless)<br>       ↓<br>SQL Execution Layer</pre><h3>Session Lifecycle</h3><p>Each conversation begins with a UUID-based session_id.</p><pre>session = {<br>    &#39;session_id&#39;: str(uuid4()),<br>    &#39;user_id&#39;: authenticated_user_id,<br>    &#39;messages&#39;: [],<br>    &#39;created_at&#39;: datetime,<br>    &#39;last_accessed&#39;: datetime,<br>    &#39;token_count&#39;: int,<br>    &#39;semantic_model&#39;: str<br>}</pre><p>Sessions expire after <strong>30 minutes of inactivity</strong>.</p><p>Sessions are strictly user-scoped via JWT validation.</p><h3>Context Window Strategy (Core Innovation)</h3><p>Instead of injecting full history blindly, we use:</p><h3>1. Recency-First Injection</h3><p>Always include the most recent N turns (default: 6).</p><h3>2. Token Budget Enforcement</h3><p>Max history budget: <strong>4,000 tokens</strong>.</p><p>Older turns are dropped once budget is exceeded.</p><h3>3. SQL Payload Compression</h3><p>For older turns:</p><ul><li>Strip raw SQL</li><li>Retain explanation</li><li>Insert placeholder indicating SQL was generated</li></ul><p>This reduces history payload by ~60%.</p><h3>Solving Result-Set Statefulness</h3><p>Stateless APIs cannot access prior result sets.</p><p>We introduce <strong>result context injection</strong>.</p><p>After executing SQL:</p><pre>result_summary = {<br>    &#39;row_count&#39;: len(df),<br>    &#39;columns&#39;: list(df.columns),<br>    &#39;preview&#39;: df.head(3).to_dict(&#39;records&#39;)<br>}</pre><p>This summary is injected into the next turn’s context as structured metadata.</p><p>This enables references like:</p><blockquote><em>“Tell me more about the second one.”</em></blockquote><p>Without modifying the underlying API.</p><h3>Memory Abstraction Layer</h3><p>We use Mem0 configured for in-memory operation inside the enterprise perimeter.</p><p>It enables:</p><ul><li>Structured conversation storage</li><li>Optional semantic retrieval of older turns</li><li>Enterprise-safe deployment without external persistence</li></ul><h3>Enterprise Deployment Considerations</h3><h3>Security &amp; Compliance</h3><ul><li>All session data stored in-memory</li><li>No external persistence</li><li>JWT-based user scoping</li><li>Audit logging without storing content</li><li>TTL-based session purge</li></ul><h3>Token Cost Management</h3><p>In production:</p><p>10-turn NL-to-SQL sessions can exceed <strong>10,000 tokens</strong> per request without optimization.</p><p>With compression + windowing:</p><ul><li>History payload capped &lt; 4,000 tokens</li><li>No measurable accuracy loss up to 20 turns</li></ul><h3>Scalability</h3><p>Single instance → in-memory store<br>Horizontal scaling → Redis-backed shared session store</p><p>FastAPI layer remains stateless.</p><h3>Production Results</h3><p>Deployed in a regulated enterprise analytics environment.</p><p>MetricResultConversation continuity5–8 average turnsToken efficiency~60% reductionSession isolationZero cross-contaminationAdded latency50–100ms</p><h3>Why This Matters for Data Engineers</h3><p>This architecture shifts conversational AI from:</p><blockquote><em>Demo capability<br>to<br>Production-grade enterprise system</em></blockquote><p>It represents:</p><ul><li>A blueprint for layering state over stateless AI services</li><li>A governance-compliant conversational analytics pattern</li><li>A way to extend Snowflake investments without waiting for native memory features</li></ul><p>As LLM systems mature, <strong>application-layer state management</strong> will become a core competency for data engineers — just as API orchestration became foundational in the cloud era.</p><h3>Limitations &amp; Future Work</h3><h3>Result-set reasoning is partial</h3><p>Deep reasoning over large result sets still requires re-querying.</p><h3>Long-session degradation</h3><p>Beyond ~25 turns, ambiguity increases.</p><p><strong>Future direction:</strong><br>Periodic conversation summarization and adaptive semantic compression.</p><h3>Multi-agent systems</h3><p>Future Snowflake Cortex Agents may require new orchestration layers.</p><h3>Conclusion</h3><p>Stateless LLM APIs are foundational to the modern AI stack.</p><p>Building persistent, contextually coherent multi-turn analytics experiences requires deliberate engineering — particularly in regulated enterprise environments.</p><p>The <strong>Session Management Layer pattern</strong> — combining:</p><ul><li>Recency-first injection</li><li>Token budget enforcement</li><li>SQL compression</li><li>Result context injection</li></ul><p>provides a scalable blueprint for conversational analytics on stateless NL-to-SQL APIs.</p><p>This pattern is extensible to any stateless AI system where context persistence must be engineered at the application layer.</p><h3>References</h3><ol><li>Snowflake Inc. (2024). <em>Cortex Analyst: Multi-Turn Conversations Support.</em></li><li>Redis Ltd. (2024). <em>LLM Session Memory — RedisVL.</em></li><li>Mem0 AI. (2024). <em>Mem0: The Memory Layer for AI Applications.</em></li></ol><p>© 2026 Plaban Roy</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4632ab535d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>