<?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 Neha Sharma on Medium]]></title>
        <description><![CDATA[Stories by Neha Sharma on Medium]]></description>
        <link>https://medium.com/@nehasharma_1486?source=rss-1c91b151ba70------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f9m6EM0HqhD5EHZjvBlXjw.png</url>
            <title>Stories by Neha Sharma on Medium</title>
            <link>https://medium.com/@nehasharma_1486?source=rss-1c91b151ba70------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:43:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nehasharma_1486/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[Monitoring AI Agents in Production on Azure: The 6 Layers You Know and the 7th You Need]]></title>
            <link>https://medium.com/@nehasharma_1486/monitoring-ai-agents-in-production-on-azure-the-6-layers-you-know-and-the-7th-you-need-72adf6e7f3b0?source=rss-1c91b151ba70------2</link>
            <guid isPermaLink="false">https://medium.com/p/72adf6e7f3b0</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Neha Sharma]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 08:49:31 GMT</pubDate>
            <atom:updated>2026-11-23T09:46:54.784Z</atom:updated>
            <content:encoded><![CDATA[<h3>A practical observability stack, from network packets to agent reasoning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxjCcXD5jktoqrsOt4YX4A.png" /></figure><p>Your dashboards are green. CPU is fine, pods are healthy, the API returns 200 on every request. And yet users are complaining that the agent gave a wrong answer, took eleven seconds, or quietly burned through a week’s token budget in a day.</p><p>This is the gap between monitoring an application and monitoring an <em>agent</em>. Traditional DevOps monitoring tells you whether the system is running. It cannot tell you whether the agent is <em>right</em>.</p><p>In this article I’ll use a standard Azure architecture as the example. First I’ll walk through the six levels of monitoring that a DevOps or SRE team applies to a Kubernetes application on Azure, a framework commonly used in most production environment in the industry. Then I’ll add the <strong>agentic AI layer</strong>, with the metrics, tools and Azure services you need once an AI agent is running in production.</p><h3>The reference architecture</h3><p>Here is the application we’ll monitor: an agentic AI app running on Azure Kubernetes Service (AKS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTWfqMFzC12WA0uWTVah1w.png" /></figure><p>Traffic enters through Front Door and a WAF, passes through API Management acting as an AI gateway, and reaches agents running on AKS: an orchestrator, worker agents, and tool or MCP servers. The agents call models in Microsoft Foundry or Azure OpenAI, retrieve from AI Search, and keep state and memory in Cosmos DB or Postgres. Everything emits telemetry through an OpenTelemetry collector to the backends that need it.</p><p>Now let’s monitor it, layer by layer.</p><h3>The six classic levels</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9ThsysBson12ICgx_Tgyw.png" /></figure><p>Think of these as a stack. Problems at the bottom surface as symptoms higher up, so when something breaks you debug from the top down but you need visibility at every level.</p><h3>Level 1: Network</h3><p><strong>What to watch:</strong> latency, packet loss, DNS failures, blocked flows, connectivity between components.</p><p><strong>Azure tools:</strong> Network Watcher provides connection monitoring, topology, diagnostics and flow logs, with Traffic Analytics on top. Use <strong>VNet flow logs</strong>: NSG flow logs are being retired on September 30, 2027, and new ones can no longer be created. One caveat from Microsoft’s docs is that Network Watcher is built for IaaS resources, not PaaS monitoring.</p><p><strong>The agent angle:</strong> an agent makes many outbound calls per task: model endpoints, tool APIs, search. A DNS failure or a firewall rule blocking one egress path doesn’t crash the app. It makes one tool fail intermittently and the agent improvises around it.</p><h3>Level 2: Nodes and node pools</h3><p><strong>What to watch:</strong> CPU, memory, disk, node pressure, autoscaler behavior.</p><p><strong>Azure tools:</strong> Container insights and Azure Monitor managed Prometheus collect node metrics. On AKS Automatic clusters, a monitoring baseline of managed Prometheus, Container insights and Azure Monitor dashboards with Grafana comes preconfigured.</p><p><strong>The agent angle:</strong> agent workers can be memory-hungry because of long contexts, embeddings and document processing. Node memory pressure leads to evictions, and an eviction in the middle of a 40-second agent run loses the run.</p><h3>Level 3: Kubernetes control plane</h3><p><strong>What to watch:</strong> API server latency and errors, etcd health, scheduler behavior.</p><p><strong>Azure tools:</strong> AKS exposes a subset of API server and etcd metrics for free as platform metrics. For fuller coverage, enable control plane metrics on the managed Prometheus add-on (documented as a preview feature, so check its current status, and note the docs list limitations such as no private link support). Control plane <em>logs</em> are a separate thing, collected through diagnostic settings.</p><p><strong>The agent angle:</strong> if your platform spawns a pod or job per task, a burst of agent runs becomes a burst of API server calls. The control plane is where that pressure first shows.</p><h3>Level 4: Workloads (the data plane)</h3><p><strong>What to watch:</strong> pod restarts, OOMKilled containers, CrashLoopBackOff, pending pods, replica counts and autoscaling.</p><p><strong>Azure tools:</strong> managed Prometheus for metrics, Managed Grafana for dashboards, Container insights for container logs.</p><p><strong>The agent angle:</strong> scale agent workers on queue depth, not just CPU, because an agent waiting on an LLM response uses almost no CPU. And handle rollouts carefully: a deployment that kills pods mid-run needs checkpointed state so the run can resume.</p><h3>Level 5: Application and its dependencies (APM)</h3><p><strong>What to watch:</strong> request rate, error rate, latency percentiles, distributed traces, and the health of every dependency your app calls.</p><p><strong>Azure tools:</strong> Application Insights, instrumented with OpenTelemetry. Application Map shows how your services and dependencies connect, and distributed tracing follows one request across all of them.</p><p><strong>The agent angle:</strong> this is where the “other applications” live: the vector store, Postgres, Redis, the ERP or CRM API your tool calls. Each tool call is a dependency, so a slow downstream system shows up here as a slow dependency, and as a slow agent to the user.</p><h3>Level 6: Azure resources</h3><p><strong>What to watch:</strong> throttling, quotas, resource health, cost.</p><p><strong>Azure tools:</strong> platform metrics and resource logs for each service, plus Resource Health, Service Health and the Activity log.</p><p><strong>The agent angle:</strong> this level now includes your AI services. Watch for <strong>429 throttling</strong> on model deployments, token-per-minute quota utilization, AI Search query latency, and Cosmos DB request-unit consumption. A throttled model deployment looks exactly like a slow agent until you look here.</p><h3>Why six layers are not enough</h3><p>Here’s the uncomfortable truth. An agent can pass all six levels and still fail the user:</p><ul><li>It returns HTTP 200 with a <strong>hallucinated answer</strong>.</li><li>It enters a <strong>reasoning loop</strong>, calling the same tool six times.</li><li>It picks the <strong>wrong tool</strong> and succeeds technically.</li><li>It leaks <strong>sensitive data</strong> or follows a prompt injection.</li><li>It costs <strong>ten times more</strong> per task after a prompt change.</li></ul><p>None of these trigger an infrastructure alert. They need a seventh layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxVADjixBiflyNRErEyMqg.png" /></figure><h3>Layer 7: The agentic AI layer</h3><p>Six things to observe.</p><h3>7.1 Traces: see every step of the agent’s reasoning</h3><p>A trace follows one request through the agent: the run, each LLM call, each tool call, each retrieval. It’s the single most useful artifact when debugging an agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ilhb06q4KBPfjRK4ZMexVg.png" /></figure><p>In the illustrative trace above, the LLM calls look fine. The real delay is a 1.2-second ERP call in the middle. A dashboard that only watches model latency would never show it.</p><p>Instrument with <strong>OpenTelemetry</strong>. It has been defining semantic conventions for generative AI spans (model, token counts, tool calls). They are still evolving, so pin your instrumentation library versions. Be deliberate about capturing prompt and response <em>content</em>: it is the most useful data for debugging and also the most sensitive, so sample it and redact PII before it leaves your cluster.</p><h3>7.2 Tokens, cost and latency</h3><p>Track tokens per request, <strong>cost per completed task</strong> (not just per call), time to first token, and tokens per second.</p><p>On Azure, API Management as an AI gateway gives you much of this without touching agent code. The llm-emit-token-metric policy sends token metrics to Application Insights, split by dimensions such as API, user or subscription (up to five custom dimensions per policy). The token limit policy enforces tokens-per-minute quotas per consumer, which is useful for chargeback and for stopping one runaway agent from starving the rest. You can also log token usage, prompts and completions to Log Analytics through a diagnostic setting.</p><h3>7.3 Quality evaluations</h3><p>This is the part with no equivalent in classic monitoring. You need to measure whether answers are <em>good</em>.</p><ul><li><strong>Offline evaluation:</strong> run a golden dataset through the agent in CI and block the release if scores drop.</li><li><strong>Online evaluation:</strong> sample live traffic and score it continuously for groundedness, relevance, task completion and tool-call accuracy, often using an LLM as judge.</li></ul><p>Microsoft Foundry made evaluations, monitoring and tracing generally available in March 2026. Its design point is useful: the same evaluators run in CI and in production, so a score means the same thing in both places. Score a <em>sample</em> of production traffic, not all of it, because evaluation calls cost money too.</p><h3>7.4 Safety and guardrails</h3><p>Track blocked prompt injection attempts, content filter hits, PII detections and jailbreak patterns. Services such as Azure AI Content Safety, or your model’s built-in content filters, produce these signals. The point is to turn them into metrics and alerts. A sudden spike in blocked injection attempts is an attack signal, and a sudden drop to zero may mean the guardrail itself broke.</p><h3>7.5 Agent behavior</h3><p>These are the metrics unique to autonomous systems:</p><ul><li><strong>Steps per task</strong>, and outliers that signal loops</li><li><strong>Retry rate</strong> and tool error rate</li><li><strong>Handoffs</strong> between agents</li><li><strong>Escalation rate</strong> to a human</li><li><strong>Memory reads and writes</strong>, if you use long-term memory</li></ul><p>Set hard limits (maximum steps, maximum tokens, maximum wall-clock time) and alert when agents hit them. A limit that triggers silently is just a hidden failure.</p><h3>7.6 Feedback and business outcomes</h3><p>Technical metrics are proxies. The real question is whether the agent did its job: thumbs up or down, how often users edit the output, how often a human takes over, and the business result. For a finance agent that might be the first-pass invoice match rate. Tie these back to trace IDs so a bad outcome leads you straight to the trace that caused it.</p><h3>Choosing the tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_wgH5HjilPVnMmnB0SFug.png" /></figure><p><strong>Foundry Observability with Application Insights.</strong> The Azure-native route. Tracing is built on OpenTelemetry and backed by Application Insights, and the Agent Monitoring Dashboard in the Foundry portal shows evaluation trends, safety status and latency, all backed by Azure Monitor data so SRE teams can drill deeper. Microsoft has also extended this to agents built outside Foundry: you instrument them to send compatible traces to Application Insights and register them with Foundry, even if they’re hosted on other clouds.</p><p><strong>Langfuse.</strong> Open source (MIT) and framework-agnostic, with tracing, prompt management and evaluations. You can self-host it inside your own AKS cluster, which matters when data can’t leave your tenant. The trade-off is operations: a production deployment runs web and worker containers plus Postgres, ClickHouse, Redis and object storage, and you own all of it.</p><p><strong>LangSmith.</strong> The natural fit if you build on LangChain or LangGraph, with deep graph tracing, evaluations and managed agent deployment. It accepts OpenTelemetry traces, so it is no longer limited to LangChain apps. It runs as SaaS, hybrid, or self-hosted on the Enterprise tier, so check that your hosting and data requirements match your plan.</p><p><strong>Prompt Flow.</strong> Don’t start here. Prompt flow in Foundry and Azure Machine Learning will be retired on April 20, 2027, and Microsoft recommends Microsoft Agent Framework (generally available since April 3, 2026) as the path forward. If you have existing flows, plan the migration now.</p><p>A note on sources: most Langfuse versus LangSmith comparisons online are written by one vendor or the other. Run both against your own traces before committing.</p><h3>My recommendation: instrument once</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WfQ_Mx8Oh4wTU_A8uaa1Bw.png" /></figure><p>Whichever tool you pick, instrument your agents with OpenTelemetry and put a collector in front. The collector handles sampling, PII redaction and routing, so you can send traces to Application Insights for operations and alerting, and to Langfuse or LangSmith for the prompt-and-evaluation loop, without changing agent code. If you later switch or add a backend, it is a collector change, not a rewrite.</p><p>A reasonable default for a regulated enterprise: Application Insights and Foundry as the operational system of record, plus a self-hosted Langfuse if you need deeper prompt iteration with data staying in your tenant.</p><h3>Alerts that matter, by layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*Y77-tu1o_QkLFUhoczDs6Q.png" /></figure><h3>A rollout order that works</h3><ol><li><strong>Turn on platform monitoring.</strong> Managed Prometheus, Container insights, Managed Grafana and Application Insights for the cluster and the app.</li><li><strong>Add OpenTelemetry tracing to the agents</strong>, so every run produces a trace.</li><li><strong>Measure tokens and cost</strong> at the API Management gateway.</li><li><strong>Add evaluations</strong>: a golden dataset in CI first, then sampled online scoring.</li><li><strong>Define SLOs for quality and cost</strong>, not just uptime, and alert on them.</li></ol><p>Steps 1 and 2 give you most of the debugging value. Steps 3 to 5 are what make the system <em>governable</em>.</p><h3>The takeaway</h3><p>Classic monitoring answers “is the system up?” Agent observability has to answer “is the system right, and is it affordable?” The six levels from the DevOps playbook stay essential, since an agent is still an application running on nodes, pods and networks. But production agents need a seventh layer on top that sees reasoning, quality, cost and safety.</p><p>Start with traces. Once you can see what the agent actually did, every other layer becomes easier to build.</p><h3>Sources</h3><ul><li><a href="https://learn.microsoft.com/azure/aks/monitor-aks">Monitor Azure Kubernetes Service (Microsoft Learn)</a></li><li><a href="https://learn.microsoft.com/en-us/azure/aks/control-plane-metrics-monitor">AKS control plane metrics (Microsoft Learn)</a></li><li><a href="https://learn.microsoft.com/en-us/azure/network-watcher/network-watcher-overview">What is Azure Network Watcher? (Microsoft Learn)</a></li><li><a href="https://learn.microsoft.com/en-us/azure/network-watcher/nsg-flow-logs-overview">NSG flow logs overview and retirement (Microsoft Learn)</a></li><li><a href="https://techcommunity.microsoft.com/t5/microsoft-foundry-blog/generally-available-evaluations-monitoring-and-tracing-in/ba-p/4502760">Generally Available: Evaluations, Monitoring, and Tracing in Microsoft Foundry</a></li><li><a href="https://techcommunity.microsoft.com/blog/azureobservabilityblog/agent-observability-in-azure-monitor-at-ignite-2026/4573966">Agent observability in Azure Monitor at Ignite 2026</a></li><li><a href="https://learn.microsoft.com/azure/api-management/genai-gateway-capabilities">AI gateway capabilities in Azure API Management</a></li><li><a href="https://learn.microsoft.com/en-us/azure/api-management/llm-emit-token-metric-policy">Emit metrics for LLM token consumption (API Management)</a></li><li><a href="https://learn.microsoft.com/azure/api-management/api-management-howto-llm-logs">Log token usage, prompts and completions for LLM APIs (API Management)</a></li><li><a href="https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/prompt-flow-is-being-retired/4513587">Prompt flow is being retired (Microsoft Foundry Blog)</a></li><li><a href="https://langfuse.com/compare/langsmith">Langfuse vs. LangSmith (Langfuse)</a> and <a href="https://www.langchain.com/articles/langsmith-vs-langfuse">LangSmith vs. Langfuse (LangChain)</a>, both vendor-authored</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72adf6e7f3b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Voice Agent Feels Slow and Rude]]></title>
            <link>https://medium.com/@nehasharma_1486/why-your-voice-agent-feels-slow-and-rude-ae2e050f266f?source=rss-1c91b151ba70------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae2e050f266f</guid>
            <dc:creator><![CDATA[Neha Sharma]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 13:22:23 GMT</pubDate>
            <atom:updated>2026-10-29T13:22:23.295Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fixing the 4–5 second lag and the “can’t be interrupted” problem in conversational AI</h3><p><em>System Design for Agentic AI, Part 1</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOQXKr6k_mzHePlpOTytkQ.png" /></figure><p>Voice agents are everywhere: customer support, collections, appointment booking, internal helpdesks. And most of them fail the same two tests within the first ten seconds of a real call.</p><ol><li><strong>The awkward pause.</strong> You finish your sentence, and the agent takes 4–5 seconds to respond.</li><li><strong>The agent that won’t stop talking.</strong> You try to interrupt, or there’s noise in your background, and the agent barrels on as if you weren’t there.</li></ol><p>Neither is a “bad model” problem. You can plug in the best LLM available and still have both. They are <strong>system design</strong> problems, and that is good news, because system design problems have known fixes.</p><p>In this first part of the series, I’ll break down why they happen and the architecture that solves them.</p><h3>Problem 1: The 4–5 second gap</h3><h3>Why it happens</h3><p>Most first-generation voice agents are built as a <strong>sequential pipeline</strong>:</p><ol><li><strong>Speech-to-text (STT):</strong> the user’s audio is transcribed.</li><li><strong>LLM:</strong> the transcript is sent to the model, which generates the <em>entire</em> response.</li><li><strong>Text-to-speech (TTS):</strong> once the LLM is completely done, the text is converted to audio.</li><li><strong>Playback:</strong> the agent finally speaks.</li></ol><p>Every stage waits for the previous one to fully complete. The LLM alone can take 2–3 seconds to produce a full paragraph, and TTS then has to synthesize all of it before a single sound plays. Add the stages up and you land at 4–5 seconds of dead air.</p><p>In a chat window, that’s tolerable. On a phone call, humans expect a reply in roughly 200–500 ms. Anything beyond a second feels broken, and beyond three seconds, people start saying “hello? are you there?”, which makes things worse.</p><h3>The fix: streaming with full-duplex WebRTC</h3><p>The insight is simple: <strong>the agent doesn’t need the whole answer to start speaking.</strong></p><p>Instead of a relay race, build an overlapping pipeline:</p><ul><li>STT streams partial transcripts as the user speaks.</li><li>The LLM streams tokens as soon as it begins generating.</li><li>TTS starts synthesizing as soon as the first few tokens (usually the first clause or short sentence) arrive, and streams audio chunks out immediately.</li><li>Transport runs over <strong>WebRTC</strong>, which is designed for low-latency, two-way (full-duplex) audio, so audio flows in both directions at the same time instead of taking turns.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQZ-DwjRCfkRMwxSOEVAgw.png" /></figure><p>The same work happens, but the stages overlap instead of queueing. The time to first audio drops from 4–5 seconds to a few hundred milliseconds.</p><blockquote><strong><em>A realistic expectation:</em></strong><em> around 300 ms is achievable in the best case. Most production systems land between 500 and 800 ms, because there is also </em>endpointing<em> to account for: the system has to decide that the user has actually finished their sentence, not just paused to think. Tuning that decision is its own art, and I’ll cover it in a later part.</em></blockquote><p>A rough latency budget for a streaming setup:</p><p>Stage Typical contribution Network (WebRTC) 20–80 ms Endpointing (deciding the user is done) 100–300 ms LLM time to first token 150–400 ms TTS time to first audio 80–200 ms</p><p>These vary by provider and region, so measure your own stack, but the shape holds: every stage now contributes its <em>first-byte</em> latency instead of its <em>total</em> latency.</p><h3>Problem 2: The agent that talks over you</h3><h3>Why it happens</h3><p>In a basic setup, the agent behaves like a walkie-talkie. While it is speaking, nobody is really listening. Two things go wrong:</p><ul><li><strong>It can’t hear you interrupt.</strong> You say “no, wait, that’s not what I meant” and the agent finishes its entire paragraph anyway.</li><li><strong>It reacts to noise.</strong> If it <em>is</em> listening naively, a passing truck, a barking dog or a colleague’s conversation gets treated as user input, and the flow derails.</li></ul><p>Real conversation is not turn-based. People interrupt, say “uh-huh,” correct themselves and talk over each other. An agent that can’t handle this feels robotic and, frankly, rude.</p><h3>The fix: barge-in architecture</h3><p>The principle: <strong>the microphone never stops listening, even while the agent is talking.</strong> Three components work together.</p><p><strong>1. Voice Activity Detection (VAD).</strong> A small neural model, such as <strong>Silero VAD</strong>, classifies each slice of audio as “human speech” or “not speech.” It is lightweight enough to run in real time on every audio frame.</p><p><strong>2. Noise suppression.</strong> Before audio reaches the VAD, a neural noise suppressor strips out steady background sounds (traffic, fans, crowd murmur), so they don’t register as speech.</p><p><strong>3. Echo cancellation (AEC).</strong> This is the one people forget. If the user is on speakerphone, the agent’s own voice comes back through the microphone. Without echo cancellation, the agent hears itself, thinks the user is interrupting, and cuts itself off. WebRTC ships with AEC built in, which is another reason to use it.</p><h3>What happens on an interruption</h3><p>When the VAD detects sustained human speech, typically <strong>more than about 150 ms</strong>, the system fires an instant interrupt signal and does three things:</p><ol><li><strong>Flushes the outgoing audio buffer.</strong> The agent stops speaking immediately, not at the end of the sentence.</li><li><strong>Cancels the LLM generation.</strong> No point generating (and paying for) tokens nobody will hear.</li><li><strong>Switches to listening.</strong> The user’s new speech goes straight to STT and the agent responds to <em>that</em>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmqGgfgwhhqhGx7fsi1ZFQ.png" /></figure><p>Short sounds like a cough or a door slam don’t last long enough to cross the threshold, so the agent keeps talking.</p><h3>Details that separate a demo from production</h3><ul><li><strong>Tune the threshold.</strong> Around 150 ms is a common starting point, not a universal constant. Too low and every cough interrupts the agent. Too high and it talks over people.</li><li><strong>Handle backchannels.</strong> A quick “hmm” or “okay” from the user usually should <em>not</em> stop the agent. Some teams add a short transcript check (or a small classifier) before committing to the interruption.</li><li><strong>Trim the conversation history.</strong> After an interruption, the LLM’s context should contain only what the agent <em>actually said</em> before being cut off, not the full response it had planned. Otherwise the agent will refer to things the user never heard.</li><li><strong>Use jitter buffers and small audio chunks.</strong> The smaller the TTS chunks you queue, the less audio there is to flush, and the faster the agent goes quiet.</li></ul><h3>Putting it together</h3><p>A production-grade voice agent has this shape:</p><ul><li>Full-duplex <strong>WebRTC</strong> transport</li><li><strong>Streaming</strong> STT, LLM and TTS, all overlapping</li><li>Always-on <strong>VAD + noise suppression + echo cancellation</strong></li><li>An <strong>interrupt controller</strong> that can flush audio and cancel generation in one move</li></ul><p>The lesson that applies well beyond voice: <strong>in agentic systems, architecture decides user experience as much as model quality does.</strong> Sequential pipelines are simple to build and painful to use. Streaming, event-driven designs are harder to build and feel natural.</p><h3>What’s next in this series</h3><p>This is Part 1 of my series on system design for AI and agentic systems. I’ll keep covering the unglamorous design decisions that make or break real deployments.</p><p>If you’ve built or used a voice agent, I’d love to hear which of these two problems bit you harder. Drop a comment.</p><p><em>Neha Sharma leads the Generative AI and Agentic AI portfolio within the Finance &amp; Accounting practice, where she works on multi-agent system architecture and AI governance for global enterprises.</em></p><p><em>Tags: Voice AI, Conversational AI, System Design, Agentic AI, Generative AI</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2e050f266f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Readiness Over Models: Why F&A AI Programmes Fail Before They Start]]></title>
            <link>https://medium.com/@nehasharma_1486/readiness-over-models-why-f-a-ai-programmes-fail-before-they-start-722cf4dab2da?source=rss-1c91b151ba70------2</link>
            <guid isPermaLink="false">https://medium.com/p/722cf4dab2da</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[finance-transformation]]></category>
            <dc:creator><![CDATA[Neha Sharma]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 15:58:18 GMT</pubDate>
            <atom:updated>2026-04-19T15:58:18.069Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Most enterprise Finance AI programmes are solving the wrong problem. They’re asking “which model?” before they’ve answered “are we ready?” — introducing FARA, the Finance AI Readiness Assessment, and why structured readiness evaluation changes everything.</em></p><p>There’s a pattern I keep seeing across enterprise Finance &amp; Accounting AI programmes, and it’s costing organisations far more than they realise.</p><p>A CFO sees a compelling demo. A transformation lead runs a pilot on invoice processing. The AI team ships something in eight weeks. Everyone calls it a success. Then, six months later, the same organisation is back at square one — wondering why nothing is scaling, why the model “keeps hallucinating,” why the finance team still doesn’t trust the outputs.</p><p>The problem is never the model.</p><p>It’s almost never the model.</p><p>The problem is that these organisations deployed AI before they understood whether they were ready for it. They skipped the uncomfortable diagnostic and went straight to the exciting part. And now they’re stuck — not because the technology failed them, but because they had no framework to understand what “ready” even meant.</p><p>That’s exactly why I built FARA — the Finance AI Readiness Assessment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZy8w8_2XKcrffPbiy70KQ.png" /><figcaption>FARA — Financial AI Readiness Assessment</figcaption></figure><h3>The Question Nobody Wants to Ask</h3><p>When a client asks me “which LLM should we use for our accounts payable automation?”, my first response is almost always another question: “Tell me about your data quality in SAP.”</p><p>The silence that follows is diagnostic in itself.</p><p>Most enterprise F&amp;A functions have been running on a combination of legacy ERP configurations, manual reconciliation workarounds, and tribal knowledge that lives entirely in the heads of people who’ve been there fifteen years. You cannot drop an agentic AI system on top of that and expect it to perform.</p><p>And yet, this is exactly what happens — repeatedly, across organisations of every size, in every geography. The AI gets blamed for problems that were baked into the foundation long before the first API call was made.</p><p>FARA exists to surface those problems before they become expensive failures. It’s a structured assessment instrument that gives you a weighted, scored view of your organisation’s actual readiness to deploy, scale, and operate agentic AI within F&amp;A — across eight dimensions that matter.</p><h3>What FARA Measures</h3><p>The Finance AI Readiness Assessment scores your organisation across eight dimensions, each weighted by its criticality to agentic F&amp;A deployment. The scoring runs from L0 (no activity) to L5 (fully autonomous and self-optimising), with a weighted composite score that maps to one of three readiness zones.</p><p>Here’s what each dimension is actually assessing — and why it’s in the framework.</p><p><strong>1. Data Readiness (18% weight)</strong></p><p>This is the highest-weighted dimension because it’s the single most common failure point. Can your agents actually access clean, structured, timely financial data? Is your ERP data in a state where it can be queried programmatically without a human cleaning it first? L0 here means no usable data layer. L5 means real-time, self-healing data pipelines that agents can trust without validation loops.</p><p><strong>2. Agent Architecture (16% weight)</strong></p><p>Are you still thinking in terms of single-task bots, or have you architected for multi-agent orchestration? This dimension assesses whether your technical infrastructure supports the kind of memory, tool-calling, and inter-agent communication that agentic F&amp;A requires at scale. Most organisations I work with are sitting at L1 or L2 here — a single agent doing one thing reasonably well, nothing more.</p><p><strong>3. Process Design (15% weight)</strong></p><p>AI cannot standardise what hasn’t been standardised. If your month-end close process has seventeen variations across business units, an agent will faithfully replicate the chaos. This dimension looks at whether your F&amp;A processes are documented, consistent, and designed in a way that agents can actually operate within — not just augment.</p><p><strong>4. AI Governance (14% weight)</strong></p><p>Who owns the outputs when an agent makes a wrong journal entry? What’s your escalation path when an anomaly detection agent flags something it doesn’t understand? This dimension is about whether you’ve built the policy infrastructure — CoEs, control frameworks, accountability structures — that lets AI operate in a regulated financial environment without creating audit nightmares.</p><p><strong>5. Talent &amp; Change Readiness (12% weight)</strong></p><p>The most underrated dimension in every AI programme. Technology deployment is ten percent of the problem. The other ninety percent is whether your finance team understands what agents are doing, trusts the outputs enough to act on them, and has the capability to maintain and improve the system over time. L5 here means AI-native roles embedded into the F&amp;A org structure itself.</p><p><strong>6. Use Case Clarity (10% weight)</strong></p><p>This one seems obvious and yet it’s where most programmes are weakest. “We want AI in finance” is not a use case. This dimension assesses whether you have a prioritised, ROI-mapped, sequenced backlog of specific F&amp;A use cases — from reconciliation automation to cash flow forecasting to anomaly detection in GL postings. Without this, your AI programme is an answer in search of a question.</p><p><strong>7. Risk &amp; Compliance Controls (9% weight)</strong></p><p>Particularly critical in regulated markets and GCC contexts. This dimension asks whether you have automated controls that can detect when an AI agent is about to do something it shouldn’t — and whether those controls are integrated into the workflow rather than bolted on after the fact.</p><p><strong>8. Technology Infrastructure (6% weight)</strong></p><p>Weighted lowest not because it’s unimportant, but because it’s the most addressable. Legacy ERP on-premises with no API layer is an L0. A cloud-native, API-enabled, Azure OpenAI-integrated stack with vector search is approaching L4. The reason this is last in the weighting is that organisations can move on infrastructure faster than they can move on culture, data, or process.</p><h3>The Scoring Model</h3><p>Each dimension is scored from 0 to 100. The composite score is calculated as:</p><p><strong>Composite Score = Σ (Dimension Score × Weight)</strong></p><p>Maximum weighted score: 500 points.</p><p>The three readiness zones map as follows:</p><p><strong>Zone 1 — Foundational (0–150)</strong> You have pockets of AI curiosity but no systemic readiness. The right move here is not to deploy agents — it’s to invest in data infrastructure, process standardisation, and building a governance baseline. Deploying AI in this zone produces pilots that never scale.</p><p><strong>Zone 2 — Operational (151–300)</strong> You have real AI deployments delivering real value, but they’re typically siloed, department-specific, and dependent on significant human oversight. This is where most large enterprises actually sit today. The work in this zone is integration — connecting your AI investments to each other and to the broader F&amp;A operating model.</p><p><strong>Zone 3 — Agentic (301–500)</strong> You’re running multi-agent systems with persistent memory, tool-calling capabilities, and meaningful automation of end-to-end F&amp;A workflows. At this level, the conversation shifts from “how do we deploy AI” to “how do we govern a function that is increasingly AI-operated.”</p><h3>How to Run the Assessment</h3><p>FARA is designed to be conducted as a structured stakeholder workshop — not a survey that gets filled out in ten minutes and filed away.</p><p>The most useful inputs come from three groups:</p><p>The CFO and Finance Leadership team, who own the use case backlog and governance posture. The IT and Data Architecture team, who can speak honestly to the actual state of ERP data quality and infrastructure readiness. And the AI and Transformation team, who can assess the technical architecture and change management capability.</p><p>Running the assessment with only one of these groups gives you a partial picture — and it’s usually the most optimistic one.</p><p>The output is a scored radar view across the eight dimensions, with a composite score and a set of prioritised interventions mapped to the gap between current and target state. FARA intentionally produces a roadmap, not just a diagnosis.</p><h3>What I’ve Learned Running This in the Field</h3><p>A few patterns that have consistently shown up across the programmes I’ve delivered.</p><p><strong>Most organisations overestimate their data readiness by two levels.</strong> There’s a consistent gap between what IT believes about data quality and what the finance team experiences every day in practice. FARA surfaces this gap explicitly, often for the first time.</p><p><strong>Governance is the bottleneck nobody talks about.</strong> Companies invest heavily in technology and talent, then get stuck because nobody has made a decision about who’s accountable when an agent makes a wrong call. You need that decision before you deploy at scale — not after your first incident.</p><p><strong>Use case prioritisation is driven by excitement rather than feasibility.</strong> The most commonly requested F&amp;A AI use cases — cash flow forecasting, intelligent FP&amp;A, autonomous close — are also among the hardest to deploy well. They require L4 or above on data readiness and process design. Starting there is almost always the wrong call. FARA helps organisations sequence their use case roadmap against their actual readiness profile.</p><p><strong>The jump from Zone 2 to Zone 3 is qualitatively different from any prior jump.</strong> Moving from Foundational to Operational is largely a technology and process problem. Moving from Operational to Agentic requires a fundamental rethinking of how the F&amp;A function is organised and governed. Organisations that don’t treat this as an operating model change — not just a technology upgrade — consistently struggle at this transition.</p><h3>Why Readiness Matters More Than Your Model Choice</h3><p>The LLM landscape is evolving fast. The model you choose today will be superseded within twelve to eighteen months. What won’t be superseded is your data layer. Your governance framework. Your process architecture. Your team’s ability to work alongside agents rather than just tolerate them.</p><p>The organisations that are going to win at Finance AI over the next five years are not the ones that picked the best model in 2024. They’re the ones that invested in the foundations that make AI actually work in a regulated, high-stakes financial environment.</p><p>FARA — the Finance AI Readiness Assessment — is a tool for building those foundations deliberately, and for knowing with precision where you stand and what needs to happen next.</p><p>If you’re leading an F&amp;A AI programme and you haven’t done a structured readiness assessment, you’re flying blind. Not because the technology doesn’t work — but because you don’t yet know what it would take for it to work for you.</p><p>That’s the question worth answering first.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=722cf4dab2da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your AI Agent Has No Manager. That’s Why It’s Failing.]]></title>
            <link>https://medium.com/@nehasharma_1486/your-ai-agent-has-no-manager-thats-why-it-s-failing-ea30da1d0963?source=rss-1c91b151ba70------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea30da1d0963</guid>
            <category><![CDATA[ai-governance]]></category>
            <dc:creator><![CDATA[Neha Sharma]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 12:54:11 GMT</pubDate>
            <atom:updated>2026-04-12T12:54:11.854Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Everyone’s building agents. Almost nobody’s governing them. Here’s what that actually costs you.</em></p><p>There’s a number that should stop every enterprise AI leader cold: <strong>11%</strong>.</p><p>That’s how many organizations currently have agentic AI actually running in production, according to Deloitte’s 2025 Emerging Technology Trends study. Meanwhile, 42% are still figuring out their strategy, and 35% don’t have one at all.</p><p>We have a pipeline full of pilots. We have a graveyard full of proof-of-concepts.</p><p>And yet — Gartner recorded a 1,445% surge in multi-agent system inquiries between Q1 2024 and Q2 2025. The appetite is real. The execution gap is massive.</p><p>So what’s actually breaking?</p><p><strong>The Agent You Built Has No Chain of Command</strong></p><h3>The Agent You Built Has No Chain of Command</h3><p>Here’s the uncomfortable analogy I keep coming back to: we’re building AI employees, then refusing to give them a reporting structure.</p><p>When you hire someone, you don’t just hand them a laptop and a mandate. You define their scope. You establish escalation paths. You set the conditions under which they make a call independently versus when they come back to a human. You give them a manager.</p><p>Most enterprise agent deployments skip all of that.</p><p>I’ve seen it across F&amp;A, supply chain, and operations: a beautifully architected agent — right tools, right RAG pipeline, right model — deployed without a clear answer to the question <em>“what happens when this agent hits a decision it shouldn’t make alone?”</em></p><p>The agent either stalls, hallucinates a decision, or, worst case, executes something it had no business touching.</p><p>That’s not a model problem. That’s a governance problem.</p><h3>Multi-Agent Is the New Normal. Chaos Is the Default.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*lrjOgmjbjlpVPFOhNh9J6Q.png" /><figcaption>From solo agents to orchestrated teams — the architecture has shifted, but the management layer hasn’t caught up.</figcaption></figure><p>The architecture conversation has already shifted. Single all-purpose agents are out. Orchestrated teams of specialized agents are in.</p><p>A researcher agent. A coder agent. An analyst agent. A validator. An orchestrator sitting on top, routing work between them. This mirrors how high-functioning human teams actually operate.</p><p>The problem? When you go from one agent to many, your failure modes don’t just add up — they multiply.</p><p>Inter-agent communication breaks down. The orchestrator misroutes. Agent A hands off a hallucinated output as ground truth to Agent B, who builds on it, who hands it to Agent C — and by the time a human reviews the output, you’re three layers deep into a compounding error.</p><p>I call this <strong>agentic drift</strong> — not a single failure, but a slow, compounding divergence from intended behavior across an agent network. By the time you catch it, you’ve lost trust in the entire system.</p><h3>The Governance Flip Nobody’s Talking About</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIY68ECMXjih1X0GAL71qw.png" /><figcaption>Governance isn’t the finish line — it’s the foundation. The 11% in production figured this out first.</figcaption></figure><p>Here’s the shift that separates the 11% who make it to production from everyone else:</p><p>They stopped treating governance as a compliance checkbox. They built it into the architecture.</p><p>That means a few specific things:</p><p><strong>1. Confidence thresholds as first-class citizens.</strong> Every agent action should have a confidence score. Below a threshold? Human-in-the-loop is triggered — not as a fallback, but as a designed workflow step. This isn’t acknowledging AI limitations. It’s good system design.</p><p><strong>2. Governance agents, not governance documents.</strong> Some of the most mature deployments I’ve seen now run dedicated “monitor agents” — agents whose only job is to watch other agents for policy violations, scope creep, and anomalous behavior. Governance-as-code, not governance-as-a-PDF.</p><p><strong>3. Deterministic guardrails around non-negotiable decisions.</strong> Not everything should be LLM-driven. The smartest agentic architectures define a set of actions that are <em>always</em> deterministic — hardcoded rules that no amount of model reasoning can override. Journal entries above a threshold. Regulatory filings. Anything touching cash movement. These get a hard wall, not a soft prompt.</p><h3>The Human-in-the-Loop Reframe</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*MsDGWV8ZU8SeYKDp0Qz0JA.jpeg" /><figcaption>HITL isn’t a limitation — it’s a design choice. The best agentic systems treat human judgment as a workflow step, not a fallback.</figcaption></figure><p>Here’s the narrative shift that matters: full automation was never the goal. <strong>Optimal automation is.</strong></p><p>The enterprises winning with agentic AI right now are the ones who started with the <em>smallest possible autonomous scope</em> and expanded trust incrementally. They didn’t deploy broadly and hope governance would catch up.</p><p>It’s a mindset shift: <strong>earn autonomy, don’t grant it.</strong></p><p>Toyota is a useful benchmark. Their teams deployed an agentic tool to manage supply chain visibility — a process that previously required navigating 50 to 100 mainframe screens with significant manual effort. It worked. But notice <em>what</em> they solved: a defined, bounded, high-repetition workflow with clear success criteria. Not “give the agent access to everything and see what it figures out.”</p><h3>What Actually Needs to Change</h3><p>If you’re sitting in a room right now looking at an agentic pilot that isn’t scaling, here’s my honest take on what’s missing:</p><p><strong>An agent operating model, not just an agent.</strong> Who owns the agent’s behavior in production? Who reviews its outputs? What’s the escalation path? If you can’t answer these in two sentences, you’re not ready to deploy.</p><p><strong>Observability built in from day one.</strong> You should be able to trace every decision an agent made, what data it used, what tool it called, and what it returned — end to end, auditable, exportable. This isn’t optional in a regulated environment. It barely feels optional anywhere.</p><p><strong>A trust ladder.</strong> Start with agents that recommend. Then agents that act on low-risk tasks with human review. Then agents that act autonomously within a tightly scoped domain. You climb the ladder as the agent earns it — not as a calendar event.</p><h3>The Uncomfortable Truth</h3><p>Full automation was never the goal. Optimal automation is.</p><p>The organizations that understand this are the ones who will actually close the gap between the 1,445% of interest and the 11% in production. They’re not trying to remove humans. They’re redesigning the human’s role in the loop — from doing the work to supervising a system that does the work.</p><p>That’s a harder design problem. It requires understanding the domain, the failure modes, the regulatory context, and the risk appetite — not just the model.</p><p>Which means the builders who will matter most in the agentic era aren’t just AI engineers. They’re people who understand both the technology <em>and</em> the terrain.</p><p>That’s the job. And most orgs haven’t hired for it yet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea30da1d0963" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Memory Leak You’re Not Watching — and Why It Will Break Your Agentic System]]></title>
            <link>https://medium.com/@nehasharma_1486/the-memory-leak-youre-not-watching-and-why-it-will-break-your-agentic-system-4eb3e0d77277?source=rss-1c91b151ba70------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eb3e0d77277</guid>
            <dc:creator><![CDATA[Neha Sharma]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 08:06:13 GMT</pubDate>
            <atom:updated>2026-04-03T08:10:31.375Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Embeddings that never expire. Scratchpads that grow forever. Sub-agents that quietly hold state across workflows. This is the underestimated challenge in production-grade agentic AI — and most teams discover it at 3AM.</em></h4><p>We spend a lot of time optimizing prompt design, retrieval strategies, and agent orchestration logic. We rarely talk about what happens to memory <em>between</em> steps — and across workflows. Yet in production, unbounded memory growth is often the first thing that silently degrades performance, inflates inference costs, and eventually crashes your system entirely.</p><p>I’ve worked across large-scale Finance &amp; Accounting AI deployments — multi-agent pipelines processing thousands of documents, running overnight reconciliation workflows, handling regulatory intelligence across jurisdictions. Memory management is never glamorous work. But it is foundational work. Here’s what I’ve learned the hard way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*Zo6drvsktWd_5_owfbPP4w.png" /></figure><h3>The Four Leak Vectors You Need to Know</h3><p>Before you can fix a memory leak, you need to know where it enters. In agentic systems, there are four primary entry points — and each one requires a different mitigation strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*pZ1zhinYww_SPVi98upOEQ.png" /></figure><h4>1. Embedding Accumulation</h4><p>Every document you ingest generates embeddings. Without eviction policies or TTL on your vector store, those embeddings grow indefinitely. In enterprise systems processing regulatory filings, financial reports, or audit documents on a recurring basis, you’ll quietly end up with duplicate embeddings for the same content — and a ballooning index that degrades retrieval performance over time.</p><h4>2. Context Window Bloat</h4><p>The intermediate steps that make an agentic system powerful — tool call results, scratchpad reasoning, chain-of-thought traces — are also the primary source of context window explosion. Each step appends to a growing history. Without trimming logic, a 10-step workflow can push 80K+ tokens into context, spiking inference costs and eventually hitting hard limits.</p><h4>3. Stateful Agent Objects</h4><p>When you reuse AgentExecutor instances, LangGraph nodes, or custom agent classes across multiple workflow runs without resetting state, prior run data lingers in memory. This is especially dangerous in serverless or long-lived worker deployments where agent objects are pooled.</p><h4>4. Orphaned Async Tasks</h4><p>In multi-agent setups with parallel tool execution, sub-agents spawned asynchronously that aren’t properly awaited or cancelled hold references in memory indefinitely — until garbage collection (or never, in the case of event loop leaks). The more agents you parallelize, the worse this compounds.</p><h3>The Mental Model: Three Memory Tiers</h3><p>The cleanest way to reason about agentic memory is in three tiers — and the core principle is that each tier needs its own management discipline. Leaks happen when you allow data to bleed from a lower tier into a higher one without the appropriate cleanup mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*NPJqzlvU0eTFGkKQV-dVlw.png" /></figure><p>The key insight here is directional discipline. Hot memory is fast and expensive — it lives in your LLM’s context window. Warm memory is structured and session-scoped — it lives in your orchestration layer. Cold memory is persistent and queryable — it lives in your vector store or database. Each transition downward should be deliberate, typed, and size-bounded.</p><h3>Strategy 1: Fix the Embedding Layer First</h3><p>The most common production issue I encounter is embedding accumulation — not because it causes immediate failures, but because it causes <em>slow degradation</em>. Retrieval latency creeps up. Duplicate chunks surface in context. Index costs compound. By the time you notice, you’re 3 months into a bloated store.</p><h4>Hash-check before you embed</h4><p>The single most effective measure is deduplication at ingest time. Before embedding any document chunk, compute its hash and check it against the store. If it already exists, skip it.</p><pre>import hashlib<br>from typing import Optional<br><br>def safe_upsert(<br>    index,<br>    chunk_text: str,<br>    metadata: dict,<br>    existing_hashes: set<br>) -&gt; Optional[str]:<br>    &quot;&quot;&quot;Upsert only if the chunk hasn&#39;t been seen before.&quot;&quot;&quot;<br>    content_hash = hashlib.sha256(chunk_text.encode()).hexdigest()<br>    if content_hash in existing_hashes:<br>        return None  # skip - already indexed<br>    doc_id = f&quot;doc_{content_hash[:16]}&quot;<br>    index.upsert(<br>        id=doc_id,<br>        text=chunk_text,<br>        metadata={**metadata, &quot;hash&quot;: content_hash}<br>    )<br>    existing_hashes.add(content_hash)<br>    return doc_id</pre><h4>Stream your chunks — never load the corpus into memory</h4><p>This is the single most impactful code change for embedding pipelines. Generators process one chunk at a time. Lists load everything before processing anything.</p><pre># ❌ Bad — entire corpus in memory before any embedding happens<br>chunks = load_all_chunks(document_paths)  # could be 50K+ items<br>for chunk in chunks:<br>    index.upsert(chunk)<br><br># ✅ Good - generator processes one chunk at a time, constant memory<br>def stream_chunks(paths: list[str]):<br>    for path in paths:<br>        for chunk in chunk_document(path):  # yields one chunk at a time<br>            yield chunk<br>for chunk in stream_chunks(document_paths):<br>    safe_upsert(index, chunk.text, chunk.metadata, seen_hashes)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*6a96vOwH5TT_LAtqFkQjkg.png" /></figure><h4>Strategy 2: Control the Context Window Aggressively</h4><p>The context window is where the most visible cost explosions happen. Every tool call result, every reasoning trace, every retrieved document chunk gets appended to the conversation history. Without deliberate management, you’re essentially building an ever-growing log that gets sent to the LLM on every inference.</p><h4>Define state with strict TypedDict — not open dicts</h4><p>The single most effective architectural decision is using a typed state schema in LangGraph. It forces you to decide, at design time, exactly what state is necessary. Anything not in the schema doesn’t accumulate.</p><pre>from typing import TypedDict, List, Optional, Annotated<br>from langgraph.graph.message import add_messages<br><br># ❌ This is a trap - everything accumulates<br>class BadState(TypedDict):<br>    messages: list<br>    agent_trace: list  # grows with every node<br>    raw_tool_outputs: list  # often 10K+ tokens per call<br>    retrieved_docs_full: list  # entire documents, not summaries<br>    # ... and anything else anyone added over time<br><br># ✅ Minimal, typed, intentional<br>class WorkflowState(TypedDict):<br>    query: str<br>    retrieved_excerpts: List[str]   # trimmed excerpts only, max 500 tokens<br>    risk_score: Optional[float]<br>    summary: Optional[str]<br>    messages: Annotated[list, add_messages]  # windowed, not raw<br>    # NOT: full agent trace, raw LLM outputs, embedding vectors</pre><h4>Summarize before persisting, always</h4><p>When an agent produces a long output — a full document analysis, a detailed sub-report — don’t pass it raw to the next node. Write a compression step into your graph that summarizes before writing to state.</p><pre>async def compress_agent_result(state: WorkflowState, raw_output: str) -&gt; str:<br>    &quot;&quot;&quot;Summarize sub-agent output before it touches shared state.&quot;&quot;&quot;<br>    if len(raw_output) &lt; 500:<br>        return raw_output  # short enough, pass through<br><br>response = await llm.ainvoke([<br>        SystemMessage(content=&quot;Summarize the following in under 150 words.&quot;),<br>        HumanMessage(content=raw_output)<br>    ])<br>    return response.content<br><br># In your supervisor node:<br>async def supervisor_node(state: WorkflowState):<br>    sub_results = await asyncio.gather(<br>        agent_a.invoke(state),<br>        agent_b.invoke(state),<br>        agent_c.invoke(state)<br>    )<br>    # Compress BEFORE writing to shared state<br>    compressed = [<br>        await compress_agent_result(state, r) for r in sub_results<br>    ]<br>    return {&quot;agent_summaries&quot;: compressed}  # not: sub_results· · ·<br></pre><h4>Strategy 3: Design Stateless Agents by Default</h4><p>This is the architectural principle with the largest blast radius. The default design posture for any agent in your system should be stateless — context arrives through function input, results leave through function output, nothing persists on the agent object itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*u3HCCCZ4sVf0h42mMZ5nmQ.png" /></figure><h4>Use LangGraph checkpointers to externalize state</h4><p>LangGraph’s checkpointer pattern is the right answer here. Instead of holding workflow state in-process between node executions, checkpointers serialize it to an external store — SQLite for dev, Postgres for production — and deserialize on demand. Memory footprint per run is bounded regardless of workflow length.</p><p>python — LangGraph with external checkpointer</p><pre>from langgraph.checkpoint.postgres import PostgresSaver<br>from langgraph.graph import StateGraph<br><br># State lives in Postgres, not in the process heap<br>checkpointer = PostgresSaver.from_conn_string(<br>    connection_string=os.getenv(&quot;DATABASE_URL&quot;)<br>)<br>workflow = StateGraph(WorkflowState)<br>workflow.add_node(&quot;extract&quot;, extract_node)<br>workflow.add_node(&quot;analyse&quot;, analyse_node)<br>workflow.add_node(&quot;summarise&quot;, summarise_node)<br><br>app = workflow.compile(checkpointer=checkpointer)<br><br># Each invocation uses a thread_id for isolation<br># State for thread A never contaminates thread B<br>config = {&quot;configurable&quot;: {&quot;thread_id&quot;: run_id}}<br>result = await app.ainvoke(initial_state, config=config)</pre><h4>Strategy 4: Instrument Everything — Memory Is Invisible Until It Isn’t</h4><p>The most underrated dimension of memory management is observability. You cannot fix what you cannot see, and memory growth in agentic systems is almost always slow and silent before it becomes catastrophic.</p><p>There are three things you should be measuring in every production agentic system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*BB0jjwvddBJInA1b_67pMQ.png" /></figure><pre>import tracemalloc<br>import psutil<br>import os<br>from contextlib import contextmanager<br><br>@contextmanager<br>def memory_guard(label: str, warn_mb: float = 200):<br>    &quot;&quot;&quot;Context manager that measures memory delta across a workflow run.&quot;&quot;&quot;<br>    process = psutil.Process(os.getpid())<br>    rss_before = process.memory_info().rss / 1e6  # MB<br>    tracemalloc.start()<br>    try:<br>        yield<br>    finally:<br>        current, peak = tracemalloc.get_traced_memory()<br>        tracemalloc.stop()<br>        rss_after = process.memory_info().rss / 1e6<br>        delta = rss_after - rss_before<br>        if delta &gt; warn_mb:<br>            logger.warning(<br>                f&quot;[{label}] memory delta={delta:.1f}MB peak={peak/1e6:.1f}MB&quot;<br>                &quot; - possible leak, review state schema&quot;<br>            )<br>        else:<br>            logger.info(f&quot;[{label}] memory delta={delta:.1f}MB ✓&quot;)<br><br># Usage<br>async with memory_guard(&quot;reconciliation_workflow&quot;, warn_mb=150):<br>    result = await app.ainvoke(state, config=config)</pre><p>Add this as a standard wrapper around every workflow invocation in your integration test suite. Set a hard memory delta threshold as an assertion — if any workflow run grows heap by more than your budget, the test fails. This catches leaks before they reach production.</p><h3>The Production Checklist</h3><p>Before any agentic workflow goes to production, I run through this list. Not all items apply to every system, but missing any one of them in the wrong context has cost me — or my clients — significant incident time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*xs0AvGiv4WAnq6dITmoUMA.png" /></figure><h3>Closing Thought</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*RgiPu2j1gOB1yrHnMvB7UQ.png" /></figure><p>The shift from proof-of-concept to production-grade agentic systems is, in large part, a shift in how seriously you take the invisible work — memory management, state governance, lifecycle discipline. None of this makes a good demo. All of it determines whether your system is still running reliably six months after deployment.</p><p>Build the state schema before you build the graph. Define your tier boundaries before you pick your vector store. Measure memory before you hit a 3AM incident. That’s the unglamorous, foundational work that separates agentic systems that scale from ones that quietly degrade.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eb3e0d77277" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Embeddings: PageIndex — Vectorless, Reasoning-First RAG for Enterprise Documents]]></title>
            <link>https://medium.com/@nehasharma_1486/beyond-embeddings-pageindex-vectorless-reasoning-first-rag-for-enterprise-documents-6d236c0bf209?source=rss-1c91b151ba70------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d236c0bf209</guid>
            <dc:creator><![CDATA[Neha Sharma]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 14:06:16 GMT</pubDate>
            <atom:updated>2026-03-23T14:06:16.315Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Reasoning-based RAG ◦ No Vector DB ◦ No Chunking ◦ Human-like Retrieval</em></strong></p><p>The retrieval problem in enterprise AI is not compute. It is architecture.</p><p>Most RAG implementations were designed for short, uniform content. They perform adequately on FAQs and knowledge bases. They break down on the documents that drive real business decisions — 10-Ks, regulatory filings, master service agreements, clinical protocols. Long, structured, cross-referenced. Documents where the answer to a critical question lives across sections, not in a single chunk.</p><p>The industry has responded by optimizing the wrong thing: better embeddings, larger context windows, smarter rerankers. These are incremental improvements on a fundamentally flawed retrieval paradigm. They still ask, <em>which chunk looks similar?</em> — when the right question is, <em>where in this document would an expert look, and why?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ekgUl53xAIOhIoT_" /></figure><p>PageIndex offers a structurally different answer.</p><h3>The Architecture Shift</h3><p>Rather than fragmenting a document into fixed-size chunks and searching an embedding space, PageIndex ingests a document and converts it into a hierarchical tree — essentially, a machine-readable table of contents with summaries at every node. Retrieval is then driven not by vector similarity but by LLM reasoning over that tree: the model decides which nodes to visit, returns node IDs, and the extracted content is used to generate an answer with a full trace.</p><p>The practical implications are significant:</p><p><strong>No chunking artifacts.</strong> Arbitrary chunk boundaries are one of the leading causes of retrieval failure on structured documents. The tree preserves section integrity.</p><p><strong>Cross-reference awareness.</strong> Long documents are internally linked — appendices, schedules, defined terms. A tree-based approach can follow those references in a way nearest-neighbor retrieval cannot.</p><p><strong>Auditability by design.</strong> Every answer is grounded in specific, named nodes. For regulated industries — finance, healthcare, legal — this is not a nice-to-have. It is a compliance requirement.</p><h3>Architectural flow</h3><p>Three stages, cleanly separated:</p><ol><li><strong>Index generation</strong> — The document (PDF or HTML) is parsed into a hierarchical node tree. Each node carries a title, summary, and text content.</li><li><strong>Reasoning-driven search</strong> — An LLM receives the tree structure (titles and summaries only, to keep the prompt tractable) and reasons about which nodes are likely to contain the answer. It returns a ranked node list with explicit reasoning.</li><li><strong>Answer synthesis</strong> — Text is extracted from the selected nodes and passed to a final generation step, which produces a grounded answer with node-level citations.</li></ol><h3>When to Deploy It</h3><p>PageIndex earns its place in the stack on structured, long-form documents where correctness and traceability matter. Annual reports, regulatory filings, legal contracts, compliance manuals, technical specifications.</p><p>It is not the right tool for high-throughput, low-latency retrieval over short content where a cached vector lookup is sufficient. The right architecture for most enterprises is hybrid: use semantic filters for breadth, tree search for depth on the documents that matter.</p><h3>Working Implementation</h3><p>The following is a complete, runnable implementation adapted from the official PageIndex cookbook. It covers the full flow — document ingestion, tree generation, LLM-directed search, node extraction, and answer generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AEjhXkDXIFVtuZ1b" /></figure><p><strong>Prerequisites:</strong> pip install pageindex openai requests — plus PageIndex and OpenAI API keys. The async calls require Python 3.10+ in a Jupyter environment or an async script entry point.</p><p>python</p><pre># simple_pageindex_rag.py  (run with Python 3.10+)<br># pip install pageindex openai requests<br><br><br>import os<br>import time<br>import json<br>import asyncio<br>import requests<br>from pageindex import PageIndexClient<br>import pageindex.utils as utils<br>import openai<br># -------------------------<br># CONFIG: set these<br># -------------------------<br>PAGEINDEX_API_KEY = os.getenv(&quot;PAGEINDEX_API_KEY&quot;, &quot;YOUR_PAGEINDEX_API_KEY&quot;)<br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;, &quot;YOUR_OPENAI_API_KEY&quot;)<br># PDF to test with (example from the cookbook)<br>PDF_URL = &quot;https://arxiv.org/pdf/2501.12948.pdf&quot;<br>DOWNLOAD_DIR = &quot;./data&quot;<br>os.makedirs(DOWNLOAD_DIR, exist_ok=True)<br># -------------------------<br># Initialize clients<br># -------------------------<br>pi_client = PageIndexClient(api_key=PAGEINDEX_API_KEY)<br>openai.api_key = OPENAI_API_KEY<br># Async helper to call OpenAI (async API client)<br>async def call_llm(prompt: str, model: str = &quot;gpt-4.1&quot;, temperature: float = 0.0) -&gt; str:<br>    client = openai.AsyncOpenAI(api_key=OPENAI_API_KEY)<br>    response = await client.chat.completions.create(<br>        model=model,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>        temperature=temperature<br>    )<br>    return response.choices[0].message.content.strip()<br># -------------------------<br># Main async flow<br># -------------------------<br>async def main():<br>    # Step 0: Download a PDF<br>    pdf_path = os.path.join(DOWNLOAD_DIR, PDF_URL.split(&quot;/&quot;)[-1])<br>    if not os.path.exists(pdf_path):<br>        print(&quot;Downloading&quot;, PDF_URL)<br>        r = requests.get(PDF_URL, timeout=30)<br>        r.raise_for_status()<br>        with open(pdf_path, &quot;wb&quot;) as f:<br>            f.write(r.content)<br>        print(&quot;Saved to&quot;, pdf_path)<br>    else:<br>        print(&quot;PDF already present:&quot;, pdf_path)<br>    # Step 1: Submit to PageIndex for tree generation<br>    print(&quot;Submitting document to PageIndex...&quot;)<br>    submit_resp = pi_client.submit_document(pdf_path)<br>    doc_id = submit_resp.get(&quot;doc_id&quot;) or submit_resp.get(&quot;id&quot;) or submit_resp<br>    print(&quot;Submitted. doc_id:&quot;, doc_id)<br>    # Step 1.1: Poll until retrieval is ready<br>    print(&quot;Waiting for PageIndex tree generation (polling)...&quot;)<br>    for i in range(60):  # up to ~10 minutes depending on doc + service<br>        ready = pi_client.is_retrieval_ready(doc_id)<br>        if ready:<br>            print(&quot;Tree ready&quot;)<br>            break<br>        print(f&quot;Not ready yet... sleeping 5s ({i+1}/60)&quot;)<br>        time.sleep(5)<br>    else:<br>        raise RuntimeError(&quot;Timed out waiting for PageIndex tree generation&quot;)<br>    # Step 1.2: Get the tree (with node summaries)<br>    tree_resp = pi_client.get_tree(doc_id, node_summary=True)<br>    tree = tree_resp.get(&quot;result&quot;) if isinstance(tree_resp, dict) and &quot;result&quot; in tree_resp else tree_resp<br>    print(&quot;Fetched tree. Top-level nodes:&quot;, len(tree))<br>    # Build a node map for easy lookup<br>    node_map = utils.create_node_mapping(tree)<br>    # Step 2: LLM-directed tree search<br>    query = &quot;What are the conclusions in this document?&quot;<br>    # Strip text fields to keep the prompt tractable<br>    tree_without_text = utils.remove_fields(tree.copy(), fields=[&quot;text&quot;])<br>    search_prompt = f&quot;&quot;&quot;<br>You are given a question and a tree structure of a document.<br>Each node contains a node id, node title, and a corresponding summary.<br>Your task is to find all nodes that are likely to contain the answer to the question.<br>Question: {query}<br>Document tree structure:<br>{json.dumps(tree_without_text, indent=2)}<br>Please reply in the following JSON format:<br>{{<br>    &quot;thinking&quot;: &quot;&lt;Your thinking process on which nodes are relevant to the question&gt;&quot;,<br>    &quot;node_list&quot;: [&quot;node_id_1&quot;, &quot;node_id_2&quot;]<br>}}<br>Directly return the final JSON structure. Do not output anything else.<br>&quot;&quot;&quot;<br>    print(&quot;Asking LLM to search the tree for relevant nodes...&quot;)<br>    tree_search_result_text = await call_llm(search_prompt)<br>    tree_search_result = json.loads(tree_search_result_text)<br>    print(&quot;\n=== LLM reasoning (condensed) ===&quot;)<br>    print(tree_search_result.get(&quot;thinking&quot;, &quot;&quot;)[:1000], &quot;\n&quot;)<br>    print(&quot;Node IDs returned:&quot;, tree_search_result.get(&quot;node_list&quot;))<br>    # Step 3: Extract text from selected nodes<br>    retrieved_node_ids = tree_search_result.get(&quot;node_list&quot;, [])<br>    retrieved_texts = []<br>    for nid in retrieved_node_ids:<br>        node = node_map.get(nid)<br>        if not node:<br>            continue<br>        node_text = node.get(&quot;text&quot;) or &quot;&quot;<br>        if isinstance(node_text, list):<br>            node_text = &quot;\n\n&quot;.join(node_text)<br>        retrieved_texts.append(f&quot;--- Node {nid}: {node.get(&#39;title&#39;)} ---\n{node_text}&quot;)<br>    combined_context = &quot;\n\n&quot;.join(retrieved_texts) or &quot;No context retrieved.&quot;<br>    # Step 4: Answer generation<br>    answer_prompt = f&quot;&quot;&quot;<br>Answer the question based only on the context below.<br>Question: {query}<br>Context:<br>{combined_context}<br>Provide a concise, grounded answer and include the node IDs you used.<br>&quot;&quot;&quot;<br>    final_answer = await call_llm(answer_prompt)<br>    print(&quot;\n=== Final answer ===\n&quot;)<br>    print(final_answer)<br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><h3>The Maturity and Ecosystem Context</h3><p>PageIndex is open-source, with a published SDK and cookbook. The team offers a cloud product and a Chat API currently in beta, designed for conversational, multi-turn document workflows. If you are evaluating it for production, verify SLA coverage and regional availability of the Chat API before committing.</p><p>For enterprise pilots, the recommended approach is focused: select 50 canonical documents, generate trees, and inspect node granularity — too coarse and you lose precision, too fine and reasoning overhead increases. Tune parsing heuristics before scaling.</p><h3>The Strategic Takeaway</h3><p>Vector search is not going away. For high-QPS, cost-sensitive retrieval on short, uniform content, it remains the right tool. But the enterprise AI stack increasingly needs to reason over complex documents where correctness and traceability are non-negotiable — regulatory filings, audit trails, legal agreements, financial disclosures.</p><p>For those use cases, retrieval that asks <em>where would an expert look?</em> will consistently outperform retrieval that asks <em>what looks similar?</em></p><p>The architectural shift from embedding-based similarity to reasoning-first tree search is not a marginal optimization. It is a different philosophy of what retrieval should do — and for the documents that drive consequential decisions, it is the more defensible foundation to build on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d236c0bf209" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle Hallucinations in Generative AI and Agentic AI Applications]]></title>
            <link>https://medium.com/@nehasharma_1486/how-to-handle-hallucinations-in-generative-ai-and-agentic-ai-applications-274afab16389?source=rss-1c91b151ba70------2</link>
            <guid isPermaLink="false">https://medium.com/p/274afab16389</guid>
            <dc:creator><![CDATA[Neha Sharma]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 15:49:19 GMT</pubDate>
            <atom:updated>2026-03-16T15:49:19.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFf_h4YK81X0e87u9Lb7ow.png" /></figure><p><strong>Hallucinations are not a bug you can patch. They are a fundamental property of probabilistic systems — and the engineers who understand that build better products.</strong></p><p>Every Large Language Model generates text by predicting the next most probable token. It does not “know” facts. It does not “check” sources. It interpolates patterns from training data — brilliantly, at scale, but without any internal truth-verification mechanism. That is why hallucinations are not an edge case. They are the default behaviour of an unconstrained LLM.</p><p>The real question is not <em>“can we eliminate hallucinations?”</em> — we cannot. The question is: <em>“how do we architect systems that contain, detect, and correct them before they cause damage?”</em></p><p>This article covers eight production-grade techniques I’ve seen work in enterprise GenAI and Agentic AI deployments — from financial services to compliance intelligence systems.</p><h3>1. Strict Prompting &amp; Contextual Grounding</h3><p>The cheapest hallucination mitigation is also the most underused: disciplined prompting.</p><p>Vague prompts invite invention. When you ask an LLM an open-ended question without boundaries, it fills the gaps with plausible-sounding fabrication. Strict prompting closes those gaps before generation begins.</p><p><strong>What this looks like in practice:</strong></p><ul><li>Explicitly scoping what the model <em>should</em> and <em>should not</em> answer</li><li>Injecting source documents directly into the prompt context (RAG — Retrieval-Augmented Generation)</li><li>Instructing the model to cite the source for every claim</li><li>Adding explicit fallback instructions: <em>“If the answer is not in the provided context, respond: I do not have sufficient information.”</em></li></ul><p>RAG architectures are the backbone of contextual grounding. Instead of relying on parametric memory baked into the model at training time, RAG retrieves live, relevant documents and grounds the response to those specific sources. This alone reduces hallucination rates dramatically in knowledge-intensive domains.</p><p><strong>The principle:</strong> You cannot hold an LLM accountable for what it doesn’t know. But you can make sure it always has what it needs — and penalise it for going beyond it.</p><h3>2. Tool Usage and Function Calling via MCPs</h3><p>Agentic AI systems should not be guessing. They should be <em>computing</em>.</p><p>When an LLM is asked a quantitative or real-time question — <em>“What is the current DSCR on this loan portfolio?”</em> or <em>“Has this entity filed its VAT return?”</em> — the correct answer is not a probabilistic text generation. It is a database query, an API call, or a calculation.</p><p>This is where <strong>tool use and function calling</strong> fundamentally change the hallucination profile of a system. Instead of the model hallucinating an answer, the agent calls a tool to retrieve or compute the correct one.</p><p>Model Context Protocol (MCP) standardizes how agents interact with external tools — databases, APIs, calculators, document stores, compliance registries. The LLM’s role shifts from <em>answer generator</em> to <em>orchestrator and reasoner</em>, while ground truth comes from deterministic systems.</p><p><strong>Why this matters in high-stakes domains:</strong> In finance and compliance, a confidently wrong answer is worse than no answer. Tool-calling architectures enforce a separation between reasoning (LLM) and fact retrieval (external systems) — which is where that separation belongs.</p><h3>3. Confidence Scoring &amp; Guardrails</h3><p>Not all generated responses carry the same risk. Enterprise systems need a way to quantify uncertainty before surfacing an answer to a user or triggering a downstream action.</p><p>Confidence scoring adds a verification layer <em>alongside</em> the generated response. Four methods are commonly used in production:</p><p><strong>1. Retrieval Relevance Score</strong> Measures semantic similarity between the user query and the retrieved source chunks. A low relevance score signals that the model may be generating outside the bounds of reliable context.</p><p><strong>2. Self-Consistency</strong> The model generates multiple responses to the same prompt independently, then compares them. High variance across responses is a hallucination signal. High consistency increases confidence.</p><p><strong>3. Cross-Model Verification</strong> A secondary (often smaller, faster) model independently evaluates the primary model’s output against the source. Disagreement between models flags the response for review.</p><p><strong>4. Rule-Based Verification</strong> Domain-specific guardrails — regex checks, entity validation, regulatory reference matching — catch factual inconsistencies that semantic models might miss.</p><p>These scoring layers feed into guardrail thresholds: below a certain confidence score, the system routes the response to a human reviewer or triggers a regeneration loop rather than returning the output directly.</p><h3>4. Structured Output Verification</h3><p>Free-text generation is the highest-risk output format in production systems. When an LLM returns unstructured prose, verification is labour-intensive and inconsistent.</p><p>Enforcing structured outputs — JSON schemas, typed fields, constrained enumerations — makes hallucination detection programmatic.</p><p>If your system expects a regulatory classification and receives a value outside the allowed taxonomy, that is detectable. If it expects a numeric confidence score and receives narrative text, that is detectable. Structured output transforms a fuzzy problem into a schema validation problem.</p><p>Libraries like <strong>Instructor</strong>, <strong>Outlines</strong>, and native function-calling schemas in OpenAI and Azure OpenAI enforce output structure at generation time. Pydantic validation on the output layer catches deviations before they propagate.</p><p><strong>The rule of thumb:</strong> Wherever the downstream system needs to <em>act</em> on a generated output, that output must be structured. Free text is for humans. Structured output is for systems.</p><h3>5. Post-Generation Fact-Checking via Evaluation Loop</h3><p>High-risk domains — legal, financial, medical, regulatory — require a verification step <em>after</em> generation, not just before.</p><p>A post-generation evaluation loop works as follows:</p><pre>User Query<br>    → LLM generates response<br>        → Retrieval: source documents pulled<br>            → Fact-Checker Agent: claims extracted from response<br>                → Claims compared against retrieved evidence<br>                    → Verdict: Approve / Reject / Regenerate</pre><p>The fact-checker agent does not regenerate the response — it evaluates it. It extracts specific claims from the generated text, maps each claim to a source document, and flags unsupported assertions.</p><p>This pattern is particularly powerful in agentic workflows where a hallucination mid-chain can propagate and compound across subsequent agent steps. Catching it at the generation layer prevents cascading failures downstream.</p><p>In practice, this adds latency — which is a genuine trade-off. The calibration question is: <em>what is the cost of a hallucinated output in this domain?</em> In most enterprise compliance contexts, the latency cost is trivially small compared to the risk cost.</p><h3>6. Human-in-the-Loop Approval Gateways</h3><p>For the highest-risk use cases, automated verification is necessary but not sufficient. Human oversight remains the most reliable hallucination backstop — and regulators increasingly expect it.</p><p>Human-in-the-loop (HITL) approval gateways insert a review checkpoint before high-consequence actions are executed. The LLM proposes; the human approves.</p><p>This is not a failure of AI capability. It is a deliberate architectural choice that reflects a mature understanding of where LLM confidence and business risk intersect.</p><p>HITL is particularly important in:</p><ul><li>Regulatory filings and compliance sign-offs</li><li>Contract generation and legal document review</li><li>Credit decisions and risk assessments</li><li>Any output that will be communicated externally or acted upon irreversibly</li></ul><p>The design principle: <strong>automate the generation, supervise the consequence.</strong> HITL does not slow down the process — it de-risks the output.</p><h3>7. Observability &amp; Continuous Monitoring</h3><p>Hallucination is not a one-time problem you solve at deployment. Models drift. Data distributions shift. Edge cases emerge in production that never appeared in testing. Without observability, you are flying blind.</p><p>Production-grade GenAI systems instrument every inference step and track metrics that surface hallucination signals over time.</p><p><strong>Key metrics to monitor:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*azgdpaLbEGfEBexTN5iYvQ.png" /></figure><p><strong>Tooling:</strong> LangSmith for LLM-specific tracing and evaluation, OpenTelemetry for infrastructure-level observability, PromptLayer for prompt versioning and performance tracking.</p><p>Observability closes the feedback loop. It tells you not just whether your system is hallucinating today, but whether it is getting better or worse over time — and why.</p><h3>Closing: Engineering for Trust, Not Just Performance</h3><p>The enterprises that will build durable AI products are not the ones chasing benchmark scores. They are the ones building systems that users and regulators can trust.</p><p>Hallucination management is not a single feature. It is an architectural discipline — a stack of techniques applied in layers, calibrated to the risk profile of the domain, and monitored continuously in production.</p><p>The techniques covered here are not theoretical. They are production patterns I’ve seen deployed in financial services, compliance intelligence, and regulated enterprise environments. The right combination depends on your use case, your risk tolerance, and how much your users have to lose when the system is wrong.</p><p>Start with grounding. Add structure. Layer in scoring. Build the evaluation loop. And never deploy in a high-stakes domain without the ability to see what your system is doing — and why.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=274afab16389" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“How do you select which Gen AI model to use for a given task? What are the criteria?”]]></title>
            <link>https://medium.com/@nehasharma_1486/how-do-you-select-which-gen-ai-model-to-use-for-a-given-task-what-are-the-criteria-63e9d0e6672d?source=rss-1c91b151ba70------2</link>
            <guid isPermaLink="false">https://medium.com/p/63e9d0e6672d</guid>
            <dc:creator><![CDATA[Neha Sharma]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 06:43:29 GMT</pubDate>
            <atom:updated>2025-07-17T06:43:29.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*uEbRlH6RG_AggHNW_ffFaQ.png" /></figure><p>I select Gen AI models based on a combination of functional requirements, performance, cost, latency, and deployment constraints. My selection process typically includes the following criteria:</p><ol><li>Nature &amp; complexity of the task : For text summarization, question answering, or creative writing, I may use large foundation models like GPT-4 or Claude. For classification, entity extraction, or simpler NLP tasks, a smaller model like BERT, DistilBERT, or fine-tuned T5 often suffices. For multimodal tasks, I consider models like GPT-4V, Gemini, or LLaVA.</li><li>Speed &amp; Accuracy requirements — In tasks such as contract compliance, auditing, decision making, where high accuracy and reasoning are of importance, I prefer larger models. But if the task is of higher volume and low latency , then faster cheaper model- even the fine-tuned smaller models can be used.</li><li>Context Window: The size of the context window required plays an important role in selection of generative AI model. If the task require a larger context window then GPT- 4o models or Claude would perform better</li><li>Cost considerations — Usage of larger models such as Claude and GPT 4o models can be a costly. to keep a tab on the model cost, in the POC stage, I generally use open source models like Mistral and LLaMa 2, While in production, larger models in Claude API and self hosted models can be implemented with correct balance</li><li>Fine tuning and Customization needs- If the task require domain -specific knowledge , then finetuning requirement would affect the choice of the model.</li><li>Deployment Strategy- Depending on the deployment strategy adopted by the company, one can choose self hosted/on premise deployment model like llama or falcon. If the organization chooses to go with a generative AI partner platform then, Azure Open ai, Open AI Anthropic can be good choice</li><li>Evaluation &amp; Bench marking — I generally conduct A/B testing to evaluate the performance of models with the same prompt. I also use the metrics such as BLEU , ROUGE, Meteor, Perplexity, accuracy, hallucination, latency, etc. to measure the performance of the model.</li></ol><p>Ultimately, the goal is to right-size the model to the use case — ensuring performance without overspending</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63e9d0e6672d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do you manage cost attached with Generative AI solution implementation?]]></title>
            <link>https://medium.com/@nehasharma_1486/how-do-you-manage-cost-attached-with-generative-ai-solution-implementation-3e81d4479b92?source=rss-1c91b151ba70------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e81d4479b92</guid>
            <dc:creator><![CDATA[Neha Sharma]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 10:58:15 GMT</pubDate>
            <atom:updated>2025-07-16T10:58:15.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*nD9cuUUHhGvXJKJrky5_6A.jpeg" /><figcaption>How to control cost attached with generative AI solution implementation?</figcaption></figure><p>Recently I was asked by a Corporate VP on what measures do I take to control the cost of generative AI application implementation for a client.</p><p>Implementing a generative AI solution comes with the cost of licensing and operation. Pricing model for various foundation model varies with the accuracy , latency , performance, context window, input and output of the model.</p><p>Although there are some open source models like Llama , Hugging face, Groq and Mistral, these are trained on open source data and provide limited support for fine-tuning and customization. These models might be good for experimentation and getting fast feedback and results, in enterprise settings, the free models might not be ideal to be used .</p><p>PAAS services like Open AI, Azure Open AI , Anthropic Claude are widely used as generative AI partners in most service based companies.</p><p>Here are some measures that needs that can be utilized to optimize the cost element. Managing cost element of a generative AI Solution is a multi-pronged strategy that needs to be undertaken during design, development, deployment and post production monitoring . Here’s how I typically approach this -</p><ol><li>Use case Prioritization — I start with prioritizing the AI use cases to ensure that generative AI solution create substantial value to justify the generative AI cost.</li><li>Model Selection Strategy — Not every problem need to GPT-4 call or similar large language model. Using a lightweight LLM for simpler calls can contribute toward cost saving while not compromising on the performance. Implementing a multi-level LLM solution to optimize the cost.</li><li>Prompt Engineering and Token Window Optimization — I optimize prompts to reduce token usage, avoid verbose output and reuse system prompts. This directly lowers the token usage while using Open AI and Azure Open AI.</li><li>Caching and Reusability — I implement caching for repeated queries using vector stores or response cache while sorting out technical aspects of the process workflow.</li><li>Architectural Strategy — I use serverless architecture or event driven architecture using cloud-native component, scaling resources only when required.</li><li>Monitoring &amp; Tracking — I monitor the generative AI call usage by tracking metrics like cost/call/user, failure rate, accuracy, performance consistently using a dashboard. I also utilize triggers and alerts for unusual activities, ensuring cost and compliance controls are in place</li><li>Hybrid deployment strategy — For enterprise clients, I also explore hybrid setups — combining cloud APIs for complex tasks and on-premise models for routine workloads to control ongoing expenses.</li><li>Experimental Control — While in development phase , I try to use open source or light weight LLMs or mocked responses to avoid unnecessary call to to paid API</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e81d4479b92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Responsible AI]]></title>
            <link>https://medium.com/@nehasharma_1486/responsible-ai-003a089643d9?source=rss-1c91b151ba70------2</link>
            <guid isPermaLink="false">https://medium.com/p/003a089643d9</guid>
            <dc:creator><![CDATA[Neha Sharma]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 08:45:27 GMT</pubDate>
            <atom:updated>2025-07-15T08:45:44.731Z</atom:updated>
            <content:encoded><![CDATA[<p>In contrast to how it is commonly perceived, Responsible AI is not an afterthought, it is not a feature or a PR mechanism. Responsible AI is the necessity of the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzNZuGIU-RPIgRIv5qmjOA.png" /></figure><p>It is the core of scalable, sustainable AI Maturity.</p><p>Responsible AI Is a framework using which you design, develop, deploy and manage AI systems that are -</p><ul><li>Ethical</li><li>Transparent</li><li>Fair or without bias</li><li>Accountable</li><li>Secure</li><li>Human Centered</li><li>Compliant with Legal &amp; Regulatory requirements</li></ul><p>Responsible AI (RAI) sits at the intersection of Business, Technology, Society, Law, Ethics, philosophy &amp; human rights.</p><p>The Key pillar of Responsible AI includes -</p><ol><li>Fairness or Bias Prevention: The AI model/system should bot discriminate on the basis on race, age or gender etc.</li><li>Explainability or Transparency: AI system should be able to to humans how it arrived at a certain output</li><li>Privacy &amp; Data Protection: The data privacy should be respected and the AI systems should comply with all data regulations including GDPR, HIPPA, PCI etc.</li><li>Robustness and Scalability: AI system should be robust and capable enough to handle edge cases</li><li>Accountability: AI system should follow human’s expected output. human remain ultimately accountable</li><li>Human Centeredness: AI systems, should augment human’s agency rather than replace it.</li><li>Security: AI system should be capable enough to handle prevent data misuse, prompt injection attacks etc.</li><li>Sustainability: AI System operations should be sustainable for a long time and should leave minimal carbon footprint</li></ol><p>An organization with a responsible AI program in place must have the following -</p><ul><li>AI Ethics Board including representative across teams including legal, business, technical, sales, &amp; compliance</li><li>Responsible AI Policies and Playbook</li><li>An independent audit team to evaluate the AI systems thoroughly from regulatory and legal compliance</li><li>AN Model Development life Cycle with Responsible AI Gates</li><li>A continuous monitoring post deployment</li><li>An skilled team trained on Responsible AI requirements</li></ul><p>Business Drivers to have a Responsible AI Practice —</p><ul><li>Trust &amp; Adoption</li><li>Regulatory Requirements</li><li>Avoid Legal Fees &amp; huge fines</li><li>Risk Management : Avoid Bad PR</li><li>Market Differentiators</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=003a089643d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>