<?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 Sharad Bharadwaj on Medium]]></title>
        <description><![CDATA[Stories by Sharad Bharadwaj on Medium]]></description>
        <link>https://medium.com/@isharadbharadwaj?source=rss-0d287bf2a4bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Bxm4JwBaFJrUOIcrB2lwGA.png</url>
            <title>Stories by Sharad Bharadwaj on Medium</title>
            <link>https://medium.com/@isharadbharadwaj?source=rss-0d287bf2a4bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:56:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@isharadbharadwaj/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[The AI Series : Agent Drift — The Silent Failure Mode of Production AI Agents]]></title>
            <link>https://isharadbharadwaj.medium.com/the-ai-series-agent-drift-the-silent-failure-mode-of-production-ai-agents-197d37857562?source=rss-0d287bf2a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/197d37857562</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sharad Bharadwaj]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 04:31:03 GMT</pubDate>
            <atom:updated>2026-10-09T04:31:03.583Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Why AI agents change behaviour over time — and how to detect and control it in production.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsJz0sp_I5yyjJ8aSt9ktA.png" /><figcaption>Image by author</figcaption></figure><p>I used to think that once an agent passed its evaluation set, the difficult part was over.</p><p>During development, the feedback loop is tight. You give the agent a task, it reasons through the steps, selects the right tools, and produces an accurate response. You run it against a hundred test cases. The success rate hits 95%. You deploy it to production, confident that the deterministic guardrails you built will keep the probabilistic engine in check.</p><p>A few weeks later, something changes.</p><p>The agent doesn’t crash. The APIs aren’t returning 500s. But when you look at the trace logs, the agent is taking longer to answer. It’s invoking the search tool three times instead of once. It’s occasionally attempting to pass badly formatted JSON to an internal system, failing, and looping until it gets it right.</p><p>Nothing is obviously broken, but the system has fundamentally altered its behaviour.</p><p>In traditional software engineering, we rely on a comforting assumption: <em>same code + same input = same behaviour</em>. Agentic AI systems destroy that assumption. When you wire an LLM to memory, external data, and APIs, the agent’s behavior becomes an emergent property of its environment.</p><p>This is <strong>Agent Drift</strong>.</p><h3>Defining Agent Drift</h3><p>Agent drift is the gradual or sudden change in an agent’s behavior, decisions, tool usage, or outcomes caused by changes in the components and environment surrounding the agent.</p><p>This is an engineering concept, not a standardized academic term. It is distinct from what we traditionally call “drift” in machine learning.</p><p>In traditional ML, we worry about data drift or concept drift — when the distribution of incoming features diverges from the training data. In simple LLM applications, we worry about model drift (when a provider updates the weights) or prompt drift.</p><p>In agentic systems, the drift surface area expands massively:</p><pre>Traditional ML Drift<br>↓<br>Data / Feature / Concept Drift<br><br>LLM Application Drift<br>↓<br>Model / Prompt / Knowledge / Retrieval Drift<br><br>Agent Drift<br>↓<br>Model + Prompt + Tools + Context + Environment + Memory + User Behavior + Policies</pre><h3>Drift Is Not Always Failure</h3><p>It is crucial to understand that drift does not necessarily mean the agent stops working. The problem is that its behavior moves away from the baseline you engineered for.</p><p>Consider a simple support agent.</p><p><strong>Expected Behavior:</strong> User Request → Agent → Search Knowledge Base → Generate Answer</p><p><strong>behaviour After Drift:</strong> User Request → Agent → Search Knowledge Base → <em>Retry</em> → <em>Search Again with Different Keywords</em> → Generate Answer</p><p>The system still produces an answer. The user might not even notice. But under the hood, latency has doubled. Token usage has tripled. The cost of running the agent has increased, and its reliance on the tool has changed. The system has drifted.</p><h3>The Taxonomy of Agent Drift</h3><p>Agent behavior is fragile. A change in any adjacent system can ripple into the agent’s decision-making process.</p><h3>1. Model Drift</h3><p>The underlying model changes. Even if you pin a specific version (like gpt-4o-2024-08-06), model providers occasionally patch infrastructure, optimize inference, or alter load-balancing routing.</p><p>If you use a rolling tag, the drift can be severe. <em>Same Prompt + Different Model Behavior = Different Agent Decisions.</em>The new model might be slightly more verbose, slightly more cautious, or favor different internal reasoning patterns, fundamentally altering how it interacts with your system.</p><h3>2. Prompt Drift</h3><p>Prompts are production code. When a team modifies a prompt to fix one edge case, it often degrades performance in another.</p><p>A seemingly small change can alter tool selection, reasoning paths, or refusal behavior. <em>Before:</em> “Use the search tool when necessary.” <em>After:</em> “Always search before answering questions about customer data.”</p><p>The intention was to ensure accuracy. The result is that the agent now redundantly searches the database even when the user asks a clarifying question about data it already retrieved in the previous turn.</p><h3>3. Knowledge Drift</h3><p>If you are running a Retrieval-Augmented Generation (RAG) system, your documents are part of the agent’s brain.</p><p>Documents are updated, deleted, or appended. Embeddings change. Chunking strategies are adjusted. If the retrieved context shifts, the agent will make different decisions even if the model and prompt remain mathematically identical. Conflicting documents in the index might suddenly cause the agent to pause and ask the user for clarification instead of taking decisive action.</p><h3>4. Tool Drift</h3><p>Tools are external dependencies, and in production, dependencies change.</p><p>An agent’s understanding of a tool is based entirely on its schema and the actual data it returns. A tool may change its response format, latency, permissions, or error behavior.</p><p><em>Before:</em> get_customer(id) → returns { &quot;name&quot;: &quot;Alice&quot;, &quot;status&quot;: &quot;active&quot;, &quot;balance&quot;: 100 }</p><p><em>After:</em> get_customer(id) → returns { &quot;customer&quot;: { &quot;name&quot;: &quot;Alice&quot; }, &quot;account_status&quot;: &quot;active&quot;, &quot;outstanding_balance&quot;: 100 }</p><p>The API hasn’t failed. It returned a 200 OK. But the agent, expecting a flat structure, might fail to parse the balance, hallucinate a zero balance, and incorrectly deny the user a refund. Tool contracts require strict versioning.</p><h3>5. Context Drift</h3><p>Context drift is subtle. The model technically uses the exact same system prompt, but the actual input context constructed at runtime is different.</p><p>This happens as conversations get longer. It happens when users attach larger files. It happens when tool outputs grow over time. As the context window fills up, the model’s attention mechanism gets stretched. An agent that perfectly extracts an ID from a 500-token context might fail to extract that same ID from a 50,000-token context. The agent hasn’t changed, but the density of the environment it operates in has.</p><h3>6. User / Intent Drift</h3><p>Users adapt to AI, and their behavior changes over time.</p><p>Early users might treat the agent like a search engine: <em>“Where is my order?”</em> Later, as they realize it has capabilities, they treat it like an operator: <em>“Cancel my order, refund the payment to my original card, and email me the receipt.”</em></p><p>The same agent now encounters a radically different task distribution. This is why a static evaluation dataset decays so quickly.</p><h3>7. Policy Drift</h3><p>Business rules change constantly. A refund limit might drop from ₹5,000 to ₹2,000. If that policy lives inside the LLM’s system prompt or, worse, inside vector memory, the agent might still reason perfectly according to stale information. The environment changed, making the agent’s historically correct behavior suddenly wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GF3ja_jl7eDvCgbO5f7-Kw.png" /><figcaption>Graph — 1</figcaption></figure><h3>The Agent Passed Evaluation. Why Is It Drifting?</h3><p>When an agent starts acting strangely in production, the first thing an engineer does is check the evaluation pipeline. Usually, the eval is still green.</p><p>Why? Because static evaluation datasets represent a snapshot of the world on Day 1. By Day 30, the tools behave differently, the RAG index is twice as large, and the users are asking harder questions.</p><p>Furthermore, traditional evaluation usually only scores the <strong>Final Answer</strong>.</p><h3>Trajectory Drift</h3><p>Evaluating only the final outcome misses the most important information about an agentic system.</p><p>Consider two traces:</p><p><strong>Agent A:</strong> User → Search Tool → Final Answer</p><p><strong>Agent B:</strong> User → Search Tool → Search Again → Retry due to hallucinated arg → Search Tool → Final Answer</p><p>Both agents produced the exact same, correct final answer. If your CI/CD pipeline only checks the final output against a golden dataset, both pass. But Agent B has drifted severely. Its execution behavior is chaotic, slow, and expensive.</p><p>For production agents, you must evaluate the trajectory: <em>Final Answer + Tool Calls + Tool Order + Number of Steps + Retries + Latency + Token Usage.</em></p><h3>A Practical Example: Monitoring Trajectories</h3><p>If you are using a state-based orchestration framework, tracking trajectory drift becomes an architectural feature.</p><p>Here is simplified pseudocode conceptually based on LangGraph. By keeping the execution state explicit, we can intercept the agent before it spirals out of control.</p><pre>from typing import TypedDict, List<br><br>class AgentState(TypedDict):<br>    messages: List[dict]<br>    tool_calls: List[dict]<br>    attempts: int<br>    status: str<br><br>def evaluate_trajectory(state: AgentState):<br>    &quot;&quot;&quot;<br>    Evaluates the trajectory at runtime to detect behavioral drift.<br>    &quot;&quot;&quot;<br>    if len(state[&quot;tool_calls&quot;]) &gt; 3:<br>        # The agent is thrashing. It shouldn&#39;t take 4 tool calls.<br>        return &quot;drift_detected&quot;<br>        <br>    if state[&quot;attempts&quot;] &gt; 2:<br>        # The agent is stuck in a retry loop.<br>        return &quot;drift_detected&quot;<br>        <br>    return &quot;continue&quot;<br><br># In the graph routing logic<br>graph.add_conditional_edges(<br>    &quot;evaluate_step&quot;,<br>    evaluate_trajectory,<br>    {<br>        &quot;continue&quot;: &quot;execute_agent&quot;,<br>        &quot;drift_detected&quot;: &quot;human_review_checkpoint&quot;<br>    }<br>)</pre><p>This is simplified, of course. A hard threshold alone does not solve agent drift. The purpose is to demonstrate the architectural idea: you must monitor behavior, detect abnormal trajectories in flight, and route accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lkvE6wbPXoHgzmB50cz-w.png" /><figcaption>Graph — 2</figcaption></figure><p>Drift detection is an operational lifecycle requirement, not something you check off a list before deployment.</p><h3>What Should We Monitor?</h3><p>To catch drift early, observability needs to be categorized into four distinct buckets.</p><p><strong>Behavior</strong></p><ul><li><strong>Tool selection:</strong> Are certain tools suddenly being ignored?</li><li><strong>Tool-call frequency:</strong> Is the agent searching more often than last week?</li><li><strong>Tool order:</strong> Has the reasoning path inverted?</li><li><strong>Loop frequency:</strong> How often is the agent self-correcting or retrying?</li><li><strong>Refusal rate:</strong> Is the agent unexpectedly denying valid user requests?</li></ul><p><strong>Quality</strong></p><ul><li><strong>Task completion:</strong> Did it actually do what the user asked?</li><li><strong>Groundedness:</strong> Are the responses faithfully supported by the retrieved context?</li><li><strong>Hallucination rate:</strong> Measured via LLM-as-a-judge over a sample of traces.</li><li><strong>Human feedback:</strong> Thumbs up / down, explicit corrections.</li></ul><p><strong>Operations</strong></p><ul><li><strong>Latency:</strong> Time to first token, time to final tool execution.</li><li><strong>Token usage:</strong> Tracking the inflation of context windows.</li><li><strong>Cost:</strong> Spikes usually indicate trajectory loops.</li><li><strong>Errors / Retries:</strong> Are APIs rejecting the agent’s payloads?</li></ul><p><strong>Safety</strong></p><ul><li><strong>Policy violations:</strong> Attempting actions outside of allowed boundaries.</li><li><strong>Unexpected tool calls:</strong> Requesting a write operation during a read-only intent.</li><li><strong>Escalation rate:</strong> How often does the agent throw its hands up and route to a human?</li></ul><h3>The Practical Drift Detection Pipeline</h3><p>Detecting drift requires multiple approaches working together. No single metric will tell you the system is degrading.</p><ol><li><strong>Baseline trajectories:</strong> You must record what “normal” looks like. What is the average number of steps for a refund request? What is the standard deviation of prompt tokens?</li><li><strong>Regression tests:</strong> Every time a model, prompt, tool, or major knowledge index changes, run known scenarios to compare the <em>exact path</em> the agent takes against the baseline.</li><li><strong>Production sampling:</strong> Periodically pull real traces from production and run them through an offline evaluation engine.</li><li><strong>Statistical monitoring:</strong> Set up alerts for macro-level shifts in your observability platform. If search_tool usage drops by 40% in an hour, your agent&#39;s behaviour has drifted, likely because of a tool schema change.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnHdzWw376RBoipHmXT-hw.png" /><figcaption>Graph — 3</figcaption></figure><p>The feedback loop is the architecture.</p><h3>Agent Drift Is Usually a System Problem</h3><p>When an agent suddenly starts making incorrect tool calls, the natural engineering instinct is to say, “The model got worse.”</p><p>Usually, the model is exactly the same. The system around it shifted. If you’ve built an <strong>Agent Harness</strong> — which we’ve discussed previously as the deterministic control layer that dictates boundaries and handles state — you already have the infrastructure to intercept these state transitions.</p><p>The harness helps <em>control</em> agent execution. Drift detection monitors whether that execution is <em>changing over time</em>.</p><p>Therefore, debugging agent drift should follow a strict operational path:</p><ol><li><strong>Agent behaviour</strong> shifts in production.</li><li>Pull the <strong>Trace</strong>.</li><li>Examine the <strong>Trajectory</strong> (not just the answer).</li><li>Isolate the <strong>Components</strong> (Did the tool schema change? Is the context bloated? Did the prompt change?).</li><li>Identify <strong>Recent Changes</strong> in the environment.</li></ol><p>Rather than immediately blaming the LLM, you often find that the backend engineering team deployed an update to an API endpoint, omitting a previously optional field, and your agent is quietly losing its mind trying to figure out why its tool calls are bouncing.</p><h3>The Agent Is Not the Only Thing That Changes</h3><p>I often return to that initial prototype. The one that passed its evaluation set flawlessly.</p><p>An agent deployed today is not the same behavioral system six months later. Even if the code is unchanged, the architecture is unchanged, and the prompt looks unchanged, the surrounding environment — the APIs, the data, the users — is in constant motion.</p><p>We learned to monitor servers because software can crash. We learned to monitor models because data can drift. With agents, we also need to monitor trajectories because the system is making autonomous decisions in a shifting environment.</p><p>Before calling a production agent stable, ask yourself:</p><ul><li>[ ] Do we know what a “normal” trajectory looks like?</li><li>[ ] Are we evaluating the steps the agent took, or only the final answer?</li><li>[ ] What happens to the agent’s behaviour when an external API changes its schema?</li><li>[ ] Can we detect if the agent suddenly starts using tools differently?</li><li>[ ] Is our evaluation dataset evolving alongside real user behaviour?</li><li>[ ] Can we compare yesterday’s execution paths with last month’s?</li><li>[ ] If behaviour changes, can we isolate which system component caused the drift?</li><li>[ ] Are production traces routinely feeding back into our regression tests?</li></ul><p>If the answer to these questions is no, you might have a functioning agent today. But you won’t know when it decides to change its mind tomorrow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=197d37857562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI Series : Agent Harness — The Missing Architecture Layer Behind Reliable AI Agents]]></title>
            <link>https://isharadbharadwaj.medium.com/agent-harness-the-missing-architecture-layer-behind-reliable-ai-agents-a7ff68289e49?source=rss-0d287bf2a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7ff68289e49</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Sharad Bharadwaj]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 14:12:29 GMT</pubDate>
            <atom:updated>2026-10-05T15:44:30.120Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why production-grade AI agents need more than an LLM, tools, and prompts — a practical look at execution control, state, context, guardrails, evaluation, recovery, and how LangGraph can help build the layer around the agent.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0WmYeD7eezRlvByf8RHGQ.png" /><figcaption>Image by author</figcaption></figure><p>When I started building agents, I initially thought the hard part was getting the model to reason correctly. I spent weeks tweaking system prompts, experimenting with few-shot examples, and agonising over the exact phrasing required to make an LLM reliably output valid JSON.</p><p>I assumed that once the model was smart enough to break down a problem and select the right tool, the heavy lifting was done.</p><p>I was wrong.</p><p>In a sandbox environment, an LLM in a while loop looks like magic. In a production environment, it looks like a liability. As soon as I deployed my first multi-tool agent into a staging environment with real data, the cracks appeared. The agent would select the wrong tool. It would get stuck in an infinite retry loop because an API returned a 500 error. It would accumulate so much context that it blew past its token limit. Worse, it would occasionally hallucinate a parameter, confidently execute a destructive action, and report back that everything went perfectly.</p><p>The difficult part was no longer making the agent intelligent. It was making the agent reliable.</p><p>If the LLM is the brain of the agent, what is responsible for making sure the brain operates safely and predictably inside a real software system? A brain floating in a jar cannot regulate its environment. It needs a central nervous system. It needs an architectural layer that controls execution, manages state, enforces boundaries, and handles failure.</p><p>In production AI systems, this layer is the <strong>Agent Harness</strong>.</p><h3>The Naive Architecture (And Why It Breaks)</h3><p>To understand why a harness is necessary, we have to look at how most engineers initially build agents. The instinct is to treat the LLM as the core application logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gRYkvFDaqUFVH32q7mxVJA.png" /><figcaption>Graph — 1</figcaption></figure><p>In code, this usually looks like a simple recursive function or a basic loop:</p><pre>def naive_agent(user_input):<br>    messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input}]<br>    <br>    while True:<br>        # The LLM is in total control of the execution flow<br>        response = llm.invoke(messages)<br>        <br>        if not response.tool_calls:<br>            return response.content<br>            <br>        messages.append(response)<br>        <br>        for tool_call in response.tool_calls:<br>            # Blindly trusting the LLM&#39;s decision to execute<br>            result = execute_tool(tool_call) <br>            messages.append({&quot;role&quot;: &quot;tool&quot;, &quot;content&quot;: result})</pre><p>This architecture is fragile. It implicitly trusts the model with application control flow.</p><p>What happens if execute_tool times out? The script crashes. What happens if the tool returns a massive payload? The next llm.invoke fails due to context limits. What happens if the LLM gets confused and calls the same tool with the same bad arguments over and over? Your cloud bill skyrockets, and the system hangs indefinitely.</p><p>An LLM is a probabilistic reasoning engine. You cannot use a probabilistic engine to manage deterministic software execution.</p><h3>Defining the Agent Harness</h3><p>An Agent Harness is the deterministic control layer that surrounds the probabilistic reasoning engine. It dictates how the agent is allowed to interact with the outside world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZcSAPQkLqMaU-BVKnyJgg.png" /><figcaption>Graph — 2</figcaption></figure><p>A common misconception is treating an “Agent Framework” (like LangGraph, Autogen, or CrewAI) as synonymous with an “Agent Harness.”</p><p><strong>Agent framework ≠ Agent Harness.</strong></p><p>A framework provides orchestration primitives — nodes, edges, state graphs, and message passing. A harness is the <em>application architecture</em> you build using those primitives. Simply installing a framework does not mean you have a safe, reliable system, just as installing Django does not mean you have a secure web application. The framework gives you the tools; the harness is the design of the control systems.</p><p>Let’s examine the specific responsibilities that belong inside the harness.</p><h3>1. Execution Control</h3><p>What stops an agent from running forever? In a naive setup, nothing.</p><p>The harness is responsible for bounding the unbounded. It enforces maximum iterations, step timeouts, and total budget limits per request. If an agent loops three times trying to parse a bad date format, the harness should intercept the execution, halt the loop, and either gracefully degrade to the user or try a deterministic fallback path.</p><p>Execution control also means defining boundaries. The harness decides when to wake the agent up, when to pause it, and when to kill it. The LLM should never directly invoke a time.sleep() or control the thread lifecycle.</p><h3>2. Context Management</h3><p>One thing I learned early on is that dumping the entire conversation history into every LLM call is an anti-pattern.</p><p>As workflows become complex, the context window fills up with intermediate tool outputs, errors, and chain-of-thought scratchpads. As the prompt grows, model latency increases, cost increases, and the model’s attention mechanism degrades (the “lost in the middle” phenomenon).</p><p>The harness manages context by distinguishing between <em>memory</em> (what the system knows) and <em>context</em> (what is currently in the prompt). The harness dynamically constructs the prompt for each step. It might utilize a sliding window for conversation history, summarize older steps, or use retrieval to pull in only the data relevant to the immediate next action.</p><h3>3. State Management</h3><p>The mistake I initially made was treating agent state as just a list of chat messages.</p><p>When you build distributed systems, state is explicit. You know if a job is PENDING, IN_PROGRESS, or FAILED. Agent workflows require the same rigor.</p><pre># A production state object managed by the Harness<br>state = {<br>    &quot;messages&quot;: [...],<br>    &quot;task_definition&quot;: &quot;Refund order #12345&quot;,<br>    &quot;extracted_entities&quot;: {&quot;order_id&quot;: &quot;12345&quot;, &quot;amount&quot;: None},<br>    &quot;tool_results&quot;: {&quot;check_eligibility&quot;: &quot;approved&quot;},<br>    &quot;execution_metadata&quot;: {<br>        &quot;attempt&quot;: 2,<br>        &quot;status&quot;: &quot;running&quot;,<br>        &quot;approval_required&quot;: True<br>    }<br>}</pre><p>By maintaining explicit state outside of the message array, the harness can make deterministic routing decisions without asking the LLM to parse its own history. If the agent crashes, the harness can read the state and resume exactly where it left off.</p><h3>4. Tool Governance</h3><p>Giving an agent 30 tools does not make it more capable; it makes it more confused.</p><p>Tool calling is not just an LLM capability. In production, it is an execution boundary. When the LLM outputs a tool call, it is merely suggesting an action. The harness actually executes it.</p><p>This means the harness must handle tool permissions (Is this specific user session allowed to use the drop_table tool?), input validation (Did the LLM hallucinate a required parameter?), output validation (Did the API return a 5 GB JSON payload?), and idempotency.</p><p>If the agent tries to charge a credit card, encounters a network timeout, and decides to try again, the harness must ensure the external system enforces idempotency keys so the customer isn’t charged twice.</p><h3>5. Guardrails</h3><p>Guardrails exist to protect the system from the model, and the model from the user.</p><p><em>Input guardrails</em> evaluate the user’s prompt before it ever reaches the agent (e.g., catching prompt injection or off-topic requests).</p><p>More importantly, action guardrails evaluate the agent’s decisions before they impact external systems. If the LLM decides to delete a customer record, the harness must intercept that intent.</p><ul><li>Is this tool allowed in the current context?</li><li>Is this action authorized for the authenticated user?</li><li>Does this operation require multi-factor authentication?</li><li>Is the operation reversible?</li></ul><p>The LLM is blind to your infrastructure. The harness acts as the firewall.</p><h3>6. Observability</h3><p>Logs alone are insufficient for debugging agent behavior. If a traditional API fails, you look at a stack trace. If an agent fails, a stack trace only tells you that a string parsing error occurred — it doesn’t tell you <em>why</em> the model generated that string.</p><p>The harness must instrument the execution trajectory. It needs to emit traces that capture:</p><ul><li>The exact prompt sent to the model (including dynamically injected context).</li><li>Token usage and latency per step.</li><li>The model’s raw output.</li><li>Tool execution times and raw HTTP responses.</li><li>State transitions.</li></ul><p>When an agent confidently gives a wrong answer, you need to be able to look at the trace and determine: Did it use the wrong tool? Did the tool return bad data? Or did it have the right data but reason about it poorly?</p><h3>7. Evaluation</h3><p>Traditional application testing asserts that input A produces output B. You cannot test probabilistic systems this way.</p><p>The harness enables <strong>trajectory evaluation</strong>. You don’t just evaluate the final answer; you evaluate the path the agent took to get there. Did it call the tools in the optimal order? Did it recover from an expected API failure gracefully?</p><p>By decoupling the harness from the LLM, you can run regression tests over golden datasets. You can swap out GPT-4 for Claude 3.5 Sonnet, run the same state machine, and objectively measure which model took a more efficient trajectory through your tools.</p><h3>8. Recovery</h3><p>There is a massive architectural difference between retrying blindly and recovering intelligently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJpI7EQCjcVQG182dI0zwg.png" /><figcaption>Graph — 3</figcaption></figure><p>If an API times out, the harness should handle the retry via exponential backoff. The LLM doesn’t need to know about network jitter.</p><p>However, if a tool returns a 400 Bad Request because the LLM formatted a date incorrectly, the harness should catch the error, prevent the application from crashing, format the error into a natural language observation, and feed it back to the agent. &quot;The API rejected this because the date format was wrong. Try again using YYYY-MM-DD.&quot;</p><p>This allows the agent to use its reasoning capabilities to recover from logical failures, while the harness handles infrastructure failures.</p><h3>9. Human-in-the-Loop (HITL)</h3><p>In high-stakes environments — financial transactions, sending external emails, production deployments — human intervention must be treated as an architectural capability rather than an emergency workaround.</p><p>The harness manages checkpoints. If the agent decides to issue a $500 refund, the harness detects the high-privilege action, pauses execution, serializes the current state to a database, and waits. An asynchronous system notifies an administrator. Once the human clicks “Approve”, the harness deserializes the state and resumes execution from the exact node it paused on.</p><h3>Agent vs. Harness: The Division of Responsibility</h3><p>To build this architecture effectively, you must strictly separate concerns. The conceptual model is simple:</p><p><strong>Agent = Intelligence / Reasoning / Decision Making</strong></p><p><strong>Harness = Control / Reliability / Execution Management</strong></p><pre>+--------------------------------+------------+--------------------------------------------------------------+<br>| The Question                   | Who Decides?| Explanation                                                  |<br>+--------------------------------+------------+--------------------------------------------------------------+<br>| What should I do next?         | Agent      | LLM determines the logical next step based on prompt        |<br>|                                |            | and tool results.                                            |<br>+--------------------------------+------------+--------------------------------------------------------------+<br>| Am I allowed to do it?         | Harness    | Checks RBAC, tool permissions, and guardrails before        |<br>|                                |            | execution.                                                   |<br>+--------------------------------+------------+--------------------------------------------------------------+<br>| Which tool is useful?          | Agent      | LLM selects the appropriate tool from available schemas.    |<br>+--------------------------------+------------+--------------------------------------------------------------+<br>| Can this tool be called?       | Harness    | Enforces rate limits, circuit breakers, and idempotency.    |<br>+--------------------------------+------------+--------------------------------------------------------------+<br>| How should I solve the task?   | Agent      | LLM breaks the problem into intermediate reasoning steps.   |<br>+--------------------------------+------------+--------------------------------------------------------------+<br>| How many attempts are allowed? | Harness    | Tracks loop counts and terminates execution when the        |<br>|                                |            | execution budget is exceeded.                               |<br>+--------------------------------+------------+--------------------------------------------------------------+<br>| What information is relevant?  | Agent      | LLM identifies which data matters from the available       |<br>|                                |            | context.                                                     |<br>+--------------------------------+------------+--------------------------------------------------------------+<br>| How much context is provided?  | Harness    | Manages the context window by truncating or summarizing     |<br>|                                |            | information when required.                                  |<br>+--------------------------------+------------+--------------------------------------------------------------+</pre><h3>A Production Example: The Customer Support Agent</h3><p>Let’s look at a concrete example. We are building an agent that can search a knowledge base, retrieve customer details, and issue refunds.</p><p>Without a harness, the flow looks like this:</p><ol><li>User: “I want a refund for order 999.”</li><li>Agent decides to call issue_refund(order=&quot;999&quot;, amount=&quot;full&quot;).</li><li>The script executes the tool. The API processes the refund.</li><li>Agent says: “I have refunded your order.”</li></ol><p>What if the user isn’t authenticated? What if the order is 3 years old? What if the API is down? The naive agent fails catastrophically in all these scenarios.</p><p>Now, let’s look at the same flow, protected by an Agent Harness:</p><pre>User: &quot;I want a refund for order 999.&quot;<br>↓<br>Agent: Decides a refund is required. Emits a tool call intent: issue_refund(999).<br>↓<br>Harness Execution Boundary intercepts the intent:<br>├── Check Auth: Is the user authenticated? (Yes)<br>├── Check State: Is order 999 associated with this user? (Yes)<br>├── Check Guardrails: Is the order within the 30-day refund window? (Yes)<br>├── Check Limits: Is the refund amount &lt; $100? (No, it is $250).<br>└── Check Routing: High value action detected. Approval required.<br>↓<br>Harness pauses execution. State is checkpointed.<br>↓<br>Human Manager reviews and clicks &quot;Approve&quot;.<br>↓<br>Harness resumes execution.<br>↓<br>Harness executes issue_refund(999) via API.<br>↓<br>API returns 503 Service Unavailable.<br>↓<br>Harness intercepts error. Applies exponential backoff. Retries 3 times.<br>↓<br>API returns 200 OK.<br>↓<br>Harness appends success to state, hands control back to Agent.<br>↓<br>Agent: &quot;Your refund of $250 has been successfully processed.&quot;</pre><p>This is where I stopped thinking about the agent as a prompt, and started thinking about it as a distributed systems component.</p><h3>What an Agent Harness is NOT</h3><p>Because “agent” is currently a heavily overloaded term, it is worth explicitly calling out what does <em>not</em> constitute an Agent Harness.</p><ul><li><strong>Having a system prompt</strong> is not a harness. System prompts are instructions, not enforcement mechanisms. An LLM can easily be tricked into ignoring its system prompt.</li><li><strong>Adding a vector database</strong> is not a harness. Retrieval-Augmented Generation (RAG) is just a data-fetching strategy. It does not control execution.</li><li><strong>Using an evaluation script</strong> is not a harness. Evaluating outputs offline is important, but a harness operates at runtime.</li><li><strong>Using LangChain or LangGraph</strong> is not a harness. These are libraries. You still have to write the architecture.</li></ul><h3>Implementing the Harness with LangGraph</h3><p>LangGraph is currently one of the most effective frameworks for building out this architectural layer because it natively supports cycles, state management, and checkpoints.</p><p>Here is how the conceptual harness architecture maps to LangGraph primitives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lOcHsjYe2SXoq_zZvBlJQ.png" /><figcaption>Graph — 4</figcaption></figure><p>When building this, your application code transitions from a simple wrapper to a structured state machine.</p><pre>class AgentHarness:<br>    def __init__(self):<br>        # The framework provides the graph structure<br>        self.workflow = StateGraph(AgentState)<br>        <br>        # The architecture dictates the nodes<br>        self.workflow.add_node(&quot;agent&quot;, self.execute_agent)<br>        self.workflow.add_node(&quot;tools&quot;, self.execute_tools)<br>        self.workflow.add_node(&quot;guardrails&quot;, self.check_guardrails)<br>        <br>        # The architecture dictates the control flow<br>        self.workflow.add_conditional_edges(<br>            &quot;agent&quot;,<br>            self.route_decision,<br>            {&quot;tool_call&quot;: &quot;guardrails&quot;, &quot;complete&quot;: END}<br>        )<br>        self.workflow.add_edge(&quot;guardrails&quot;, &quot;tools&quot;)<br>        self.workflow.add_edge(&quot;tools&quot;, &quot;agent&quot;)<br><br>        # The framework provides the checkpointing primitive<br>        self.checkpointer = PostgresSaver()<br>        self.app = self.workflow.compile(<br>            checkpointer=self.checkpointer,<br>            interrupt_before=[&quot;tools&quot;] # Human-in-the-loop primitive<br>        )<br><br>    def run(self, input_data, config):<br>        # The Harness controls the execution boundary<br>        state = self.initialize_state(input_data)<br>        state = self.validate_input(state)<br>        <br>        try:<br>            return self.app.invoke(state, config)<br>        except GraphExecutionError:<br>            return self.execute_graceful_fallback(state)</pre><p>Notice how the llm.invoke call is now buried deep inside self.execute_agent. The reasoning engine is fully encapsulated by the execution graph. If the model acts erratically, the graph contains the blast radius.</p><h3>The Systems Thinking Approach to AI</h3><p>Later in my journey of building these systems, I realized that the problems we face with LLM agents are not actually new. They are classic distributed systems problems dressed in natural language.</p><p>How do you handle an unreliable sub-system? You use timeouts, circuit breakers, and fallbacks. How do you manage complex workflows? You use state machines and idempotency keys. How do you debug non-deterministic paths? You use distributed tracing.</p><p>Reliable agents are not created simply by making models smarter. They are created by designing the system around the model carefully. The model reasons. The agent decides. The harness controls the execution. The surrounding system makes the whole thing trustworthy.</p><p>Before calling an AI agent production-ready, ask yourself these architectural questions:</p><ul><li>[ ] Can it recover from an API failure without crashing?</li><li>[ ] Can I inspect the exact trajectory of its execution?</li><li>[ ] Can I control and limit its access to tools based on user authorization?</li><li>[ ] Can I bound its execution to prevent infinite loops and runaway costs?</li><li>[ ] Can a human interrupt and approve high-risk actions?</li><li>[ ] Can the system pause, serialize its state, and resume a day later?</li><li>[ ] If I swap the underlying LLM, does the application architecture remain intact?</li></ul><p>If the answer to any of these is no, you don’t have an agent architecture yet. You just have a very smart script waiting to break.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7ff68289e49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI Series: The Hardest Part of RAG, Part 2 — Why Perfect Chunks Still Give You Bad Retrieval]]></title>
            <link>https://isharadbharadwaj.medium.com/the-ai-series-the-hardest-part-of-rag-part-2-why-perfect-chunks-still-give-you-bad-retrieval-da3fc7392f6d?source=rss-0d287bf2a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/da3fc7392f6d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sharad Bharadwaj]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 11:23:07 GMT</pubDate>
            <atom:updated>2026-09-07T11:23:07.473Z</atom:updated>
            <content:encoded><![CDATA[<h4>Retrieval Is Not Search — What Actually Happens After You Hit similarity_search()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGb2d0D-zVDYX7wx796Mow.png" /><figcaption>Image by author</figcaption></figure><p>In my last article, <a href="https://isharadbharadwaj.medium.com/the-ai-series-the-hardest-part-of-rag-is-not-the-vector-db-its-parsing-pdfs-fc14bb175408">The Hardest Part of RAG Is Not the Vector DB — It’s Parsing PDFs</a>, I talked about how much pain lives in getting clean text out of messy documents. A few people wrote back with some version of the same message: <em>“Okay, my chunks are clean now, tables are extracted, metadata is attached. Why is my RAG system still giving wrong answers?”</em></p><p>I asked myself that exact question about six months ago.</p><p>We had just rebuilt our parsing pipeline from scratch. Every chunk was clean. Every table came out as Markdown. Every chunk carried its page number and section title. I remember feeling genuinely proud of it — I thought the hard part of RAG was finally behind us.</p><p>Then it went to production, and users kept getting wrong answers to questions the system should have handled easily. Not because the chunks were bad. The chunks were fine. We were just retrieving the wrong ones.</p><p>That was the moment it clicked for me: parsing gives you good data, but good data doesn’t automatically give you good retrieval. They are two separate problems, and almost nobody who talks about RAG spends any real time on the second one.</p><h3>First, What Is an Embedding, Actually?</h3><p>Before we get into where retrieval breaks, it’s worth being honest about what’s happening underneath similarity_search(), because most people (myself included, for a while) treat it like a black box.</p><p>An embedding model takes a piece of text and turns it into a list of numbers — a vector. That vector is a point in a high-dimensional space, usually somewhere between 384 and 3072 dimensions depending on the model. The whole idea is that text with similar meaning should land at points that are close together in that space, and text with different meaning should land far apart.</p><p>Here’s a simplified version, using just 4 dimensions instead of a few thousand, so it’s actually readable:</p><pre>&quot;How do I reset my password?&quot;     → [0.81, 0.12, -0.44, 0.09]<br>&quot;Steps to change your password&quot;   → [0.79, 0.15, -0.41, 0.11]<br>&quot;How do I cancel my subscription?&quot;→ [0.22, 0.68, 0.05, -0.39]</pre><p>To compare two vectors, we use cosine similarity — basically, how much they point in the same direction, ignoring their length. A score of 1.0 means identical direction, 0 means unrelated, negative means opposite.</p><pre>from numpy import dot<br>from numpy.linalg import norm<br><br>def cosine_similarity(a, b):<br>    return dot(a, b) / (norm(a) * norm(b))<br><br>query = [0.80, 0.13, -0.42, 0.10]  # &quot;reset my password&quot;<br><br>print(cosine_similarity(query, [0.81, 0.12, -0.44, 0.09]))  # 0.998 - very close<br>print(cosine_similarity(query, [0.22, 0.68, 0.05, -0.39]))  # 0.310 - far apart</pre><p>That’s it. That’s the entire mechanism behind “AI understanding your question.” It’s not understanding in any real sense — it’s geometry. And once you see it as geometry, it becomes obvious why it breaks: geometry doesn’t know that “not allowed” and “allowed” are opposites, or that “Error 4092” is a specific, exact string a user is searching for and not a fuzzy concept.</p><h3>Why Retrieval Is Genuinely Difficult</h3><p>Once you compress a paragraph into a point in space, you lose things. In my experience, these are the failures that show up again and again once you’re past the demo stage:</p><p>Lexical mismatch is the first one — a user searches for an exact error code or product ID, and the embedding treats it like any other word, so the chunk containing that exact string doesn’t even make the top 10. Negation blindness is the second, and it’s a nasty one — “refunds are not issued after 30 days” and “how do I get a refund after 30 days” can sit disturbingly close together in vector space, because the words overlap heavily even though the meaning is inverted. Then there’s chunk isolation, where the actual answer is split across two chunks — the number is in one, the label explaining what the number means is in the chunk right before it — and your retriever only pulls one of them. And finally, recency confusion: your vector index has no built-in concept of “this document is outdated.” An old and a new version of the same policy will often rank as equally relevant.</p><p>None of these show up in a 20-document demo. They show up once your corpus has real duplication, real overlap, and real ambiguity — which is every production system I’ve ever worked on.</p><h3>What a Real Retrieval Pipeline Looks Like</h3><p>A single call to a vector store is not a retrieval system. A resilient one looks more like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2j-G3pZIVYVRT66fiAZfw.png" /><figcaption>Image — 1</figcaption></figure><p>Every box in that diagram exists because the box before it isn’t good enough on its own. That’s worth repeating, because it’s the single biggest mental shift from “RAG demo” to “RAG in production”: each stage is a correction for a specific weakness of the previous stage, not decoration.</p><h3>Hybrid Search: Why Vector Search Alone Isn’t Enough</h3><p>Vector search is bad at exact matches. Keyword search (BM25) is bad at conceptual matches. Instead of picking a side, run both and merge the results.</p><p>The simplest way to merge two ranked lists without needing their scores to be on the same scale is Reciprocal Rank Fusion. Here’s roughly what we run in production:</p><pre>from collections import defaultdict<br><br>def reciprocal_rank_fusion(result_lists, k=60):<br>    scores = defaultdict(float)<br>    for result_list in result_lists:<br>        for rank, doc_id in enumerate(result_list):<br>            scores[doc_id] += 1 / (k + rank + 1)<br>    return sorted(scores, key=scores.get, reverse=True)<br><br>vector_ids = [d.metadata[&quot;chunk_id&quot;] for d in vector_store.similarity_search(query, k=20)]<br>bm25_ids = [d.metadata[&quot;chunk_id&quot;] for d in bm25_index.search(query, k=20)]<br><br>final_ranking = reciprocal_rank_fusion([vector_ids, bm25_ids])</pre><p>I made the mistake early on of just concatenating both result lists instead of fusing them properly. Whichever list I put first quietly dominated the final context, which defeats the entire point of running two retrieval strategies.</p><h3>Reranking Is the Step Nobody Skips Twice</h3><p>If parsing has table extraction as its final boss, retrieval has reranking. Here’s the distinction that matters: the embedding model you used for search encodes your query and your documents <em>separately</em>, then compares them after the fact. A re-ranker, usually a cross-encoder, looks at the query and a candidate chunk <em>together</em>, in one pass, and gives a direct relevance score. It’s slower, so you only run it on the top 20 to 50 candidates coming out of fusion, never your whole index.</p><pre>from sentence_transformers import CrossEncoder<br><br>reranker = CrossEncoder(&quot;BAAI/bge-reranker-base&quot;)<br><br>def rerank(query, candidates, top_n=5):<br>    pairs = [(query, c[&quot;text&quot;]) for c in candidates]<br>    scores = reranker.predict(pairs)<br>    for c, s in zip(candidates, scores):<br>        c[&quot;rerank_score&quot;] = float(s)<br>    return sorted(candidates, key=lambda c: c[&quot;rerank_score&quot;], reverse=True)[:top_n]</pre><p>On one of our internal support-search systems, adding a re-ranker after fusion moved our Recall@5 from around 61% to 84%, without touching the embedding model or chunk size at all. That single change had a bigger impact than everything else in the pipeline combined, and it’s usually the first thing I now tell people to add if their RAG answers feel “close but not quite right.”</p><h3>Fixing the Question, Not Just the Index</h3><p>Sometimes retrieval fails not because the index is bad but because the question isn’t phrased the way your documents are written. Users write conversationally — “why won’t it let me log in” — while documentation is written formally — “Authentication failures may occur when session tokens expire.”</p><p>Two techniques help here. Query rewriting uses an LLM to reformulate a vague question into something closer to how the source material is phrased. HyDE (Hypothetical Document Embeddings) goes one step further — instead of embedding the raw question, you ask an LLM to write a short hypothetical answer, then embed <em>that</em> and search with it, since a plausible answer tends to sit much closer to real answers in vector space than the original question does.</p><pre>def hyde_retrieve(query, llm, vector_store, k=5):<br>    hypothetical = llm.invoke(f&quot;Write a short passage answering: {query}&quot;)<br>    return vector_store.similarity_search(hypothetical, k=k)</pre><p>We rolled this out for a support-ticket system and recovered a meaningful chunk of queries that were previously returning nothing useful, purely because users and documentation don’t speak the same dialect.</p><h3>Measuring It Instead of Eyeballing It</h3><p>The mistake I made for the longest time was judging retrieval quality by whether the final LLM answer <em>sounded</em> right. That tells you almost nothing about which stage failed.</p><p>You need a small labeled set — even 50 to 100 query and correct-chunk pairs — so you can measure Recall@K (of the chunks that actually contain the answer, how many made it into your top K) directly, before the LLM ever sees anything:</p><pre>def recall_at_k(retrieved_ids, relevant_ids, k):<br>    top_k = set(retrieved_ids[:k])<br>    return len(top_k &amp; relevant_ids) / len(relevant_ids) if relevant_ids else 0.0</pre><p>Without this, every change you make to chunk size, embedding model, or re-ranker is a guess dressed up as an improvement.</p><h3>What I’d Tell Someone Starting This Today</h3><p>Don’t assume a bigger k fixes weak retrieval — it usually just hands the LLM more noise to get distracted by. Don&#39;t spend your first week tuning chunk size; that gives marginal gains compared to adding a re-ranker, which gives a step change. And build your evaluation set before users start complaining, not after — debugging retrieval blind, after the fact, is a miserable way to spend a sprint.</p><p>If I were building this layer again from scratch: Qdrant for vector search, BM25 through OpenSearch fused with RRF, BGE-re-ranker self-hosted with Cohere Re-rank as a hosted fallback, and HyDE specifically for conversational query traffic.</p><h3>The Uncomfortable Truth About RAG</h3><p>We spend so much energy arguing about which LLM writes the most fluent final answer, when the real determinant of quality sits upstream of the model entirely: did we retrieve the right chunks in the first place? A brilliant model handed the wrong context will write a brilliant, confident, wrong answer every time.</p><p>Parsing gets your data into the system. Retrieval decides whether the right piece of it ever reaches the model. Get either one wrong, and no amount of prompt engineering downstream is going to save you.</p><p>In the next article, we’ll close the loop: once retrieval is actually reliable, how do you validate — end to end, automatically, not by eyeballing outputs one at a time — that your RAG or agentic system is reasoning correctly over what it retrieved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da3fc7392f6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Series #2: Data Preprocessing and Feature Engineering — The Part of Machine Learning I Didn’t…]]></title>
            <link>https://isharadbharadwaj.medium.com/ml-series-2-data-preprocessing-and-feature-engineering-the-part-of-machine-learning-i-didnt-12302e76ca33?source=rss-0d287bf2a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/12302e76ca33</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sharad Bharadwaj]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 17:10:35 GMT</pubDate>
            <atom:updated>2026-08-16T17:10:35.308Z</atom:updated>
            <content:encoded><![CDATA[<h3>ML Series #2: Data Preprocessing and Feature Engineering — The Part of Machine Learning I Didn’t Expect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLCuTYp5xpknT20osaOMPA.png" /><figcaption>Image by author</figcaption></figure><p>When I started learning Machine Learning, I was obsessed with the algorithms. Random Forest, XGBoost, Support Vector Machines, Neural Networks — I wanted to understand the math behind them and how to train them to perfection.</p><p>But once I started building actual ML systems, reality hit me. I realized something that fundamentally changed my perspective: <strong>the model is only one small part of the problem.</strong></p><p>Think of it like building a robust cloud architecture. You wouldn’t route raw public traffic directly into your isolated database subnets without a load balancer or an API gateway cleaning, authenticating, and filtering those requests first. Machine Learning is exactly the same. Before a model can learn anything, we have to give it data in a form it can actually understand. And real-world data is almost never ready for that.</p><p>This is where Data Preprocessing and Feature Engineering come in. In the previous article, we covered what Machine Learning is. Today, we’re going one step deeper. Let’s look at what happens to raw data <em>before</em> it ever reaches the algorithm.</p><h3>The model.fit() Illusion</h3><p>When I first saw a simple ML example, it looked like this:</p><pre>model.fit(X_train, y_train)</pre><p>Two lines of code. I thought, <em>“Okay, so we just provide the data, and the algorithm learns. Easy.”</em></p><p>But what exactly is X_train? Where did it come from? Was the original database already in this neat format? What happened to the missing values? What if one column contains text, and another contains numbers ranging from 1 to 1,000,000?</p><p>These questions led me to the most critical, time-consuming phase of Machine Learning: data preparation.</p><h3>Raw Data vs. ML Data</h3><p>Imagine we pull customer information from an e-commerce database. It might look like this:</p><pre>Name   | Age | City      | Monthly Income | Orders | Last Purchase<br>-------|-----|-----------|----------------|--------|--------------<br>Rahul  | 29  | Ahmedabad | 85000          | 12     | 2026-07-12<br>Priya  | 34  | Mumbai    | 120000         | 4      | 2026-06-20<br>Amit   | --  | Delhi     | 65000          | 8      | --<br>Neha   | 27  | Pune      | 90K            | 15     | 2026-07-30</pre><p>A human can look at this table and intuitively understand it. A Machine Learning algorithm cannot. It’s going to trip over the missing Age, choke on the text in City, get confused by the &quot;90K&quot; string formatting in Monthly Income, and have no idea what to do with the Last Purchase dates.</p><p>Before training, we need a pipeline to transform this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vM1M4LrnXK2YmZBF" /><figcaption>The Machine Learning Lifecycle. Source: VectorMine / Getty Images</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUIO-4JdIuKQfQy8SUJ5WQ.png" /><figcaption>Graph — 1</figcaption></figure><p>This transformation pipeline is what we broadly call <strong>Data Preprocessing</strong>. It means converting raw data into a clean, mathematical format that an algorithm can consume. Let’s break down the most common steps you will use in almost every project.</p><h3>1. Handling Missing Values</h3><p>This is step one in the real world. If you have 300,000 rows with missing values out of a million, you can’t just delete them — you’d be throwing away highly valuable information.</p><p>Instead, we use <strong>imputation</strong>. For numerical data like Age, we might replace the NULL with the median age of our dataset.</p><p>But here is a hard-earned lesson: <strong>Don’t blindly fill missing values.</strong> The correct strategy depends on what the missing value <em>means</em>. A missing medical measurement might just be a clerical error, but a missing salary could mean the customer deliberately refused to provide it. Context matters.</p><h3>2. Identifying Incorrect Data &amp; Outliers</h3><p>Algorithms don’t have common sense. If an age column has the values 25, 31, 29, 250, 34, the model just sees numbers. It doesn&#39;t know human beings don&#39;t live to be 250.</p><p>You’ll also encounter <strong>outliers</strong> — extreme values like an income of 50,000,000 mixed in with regular salaries. Early in my career, I thought all outliers were &quot;bad&quot; data that needed to be deleted. Not true. In systems like fraud detection, that massive, unusual transaction is exactly the signal you are looking for. Understand the outlier before you remove it.</p><h3>3. Encoding Categorical Data</h3><p>Algorithms do math. They don’t understand “Mumbai” or “Pune.” We have to translate text categories into numbers.</p><p>One common approach is <strong>One-Hot Encoding</strong>. Instead of a single City column, we create binary columns:</p><pre>City        | Ahmedabad | Mumbai | Delhi<br>------------|-----------|--------|------<br>Ahmedabad   | 1         | 0      | 0<br>Mumbai      | 0         | 1      | 0<br>Delhi       | 0         | 0      | 1</pre><p>Now the model can process the geography mathematically.</p><h3>4. Feature Scaling</h3><p>Imagine a model looking at Age (spanning 18 to 70) and Income (spanning 20,000 to 500,000). Because the income numbers are naturally larger, some algorithms will incorrectly assume Income is vastly more important than Age.</p><p>To fix this, we apply scaling:</p><ul><li><strong>Standardisation:</strong> Transforms data so the mean is 0 and the standard deviation is 1.</li><li><strong>Normalisation:</strong> Squeezes the values into a specific range, usually between 0 and 1.</li></ul><p><em>Note: Not every model needs this. Tree-based models like Decision Trees and Random Forests are generally immune to unscaled data, whereas distance-based algorithms like SVMs will fail without it.</em></p><h3>The Magic of Feature Engineering</h3><p>Basic cleaning is necessary, but <strong>Feature Engineering</strong> is where the real art of Machine Learning happens. It’s the process of creating or transforming input variables so the model can spot patterns faster.</p><p>Think of it like implementing a Cache-Aside or Write-Through strategy in backend architecture. Instead of forcing the system to compute the heavy logic every single time, you compute the valuable insight upfront and serve it directly to the model.</p><p>Suppose our database has Total Orders and Total Amount Spent. Instead of feeding those raw numbers, we could engineer new features:</p><ul><li>Average Order Value = (Total Amount / Total Orders)</li></ul><p>Now the model has a direct, highly useful signal about customer behavior without having to infer it mathematically. The biggest improvements in model accuracy rarely come from tweaking a fancy algorithm; they come from representing the problem better through feature engineering.</p><blockquote><strong><em>Feature Engineering vs. Feature Selection</em></strong><em> Don’t confuse the two.</em></blockquote><ul><li><strong>Feature Engineering</strong> is <em>creating</em> new, useful features (like Average Order Value).</li><li><strong>Feature Selection</strong> is <em>choosing</em> which features actually matter and dropping the noise (e.g., dropping Shoe Size when predicting software subscriptions). More features don’t always mean a better model; sometimes they just cause the model to learn noise and overfit.</li></ul><h3>The Train/Validation/Test Split</h3><p>If you train a model on 100,000 records and test it on those exact same 100,000 records, it will look like a genius. But it hasn’t actually learned anything — it just memorized the answers.</p><p>To know if a model can handle reality, we split the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D05PoUefl5RdJGT3J_PAtg.png" /><figcaption>Graph — 2</figcaption></figure><ul><li><strong>Training Set (~70%):</strong> The data the model learns from.</li><li><strong>Validation Set (~15%):</strong> Used to tune the model and make adjustments during development.</li><li><strong>Test Set (~15%):</strong> Locked away until the very end. This is the final exam on unseen data.</li></ul><h4>Beware of Data Leakage</h4><p>This is a trap I see engineers fall into all the time. Imagine trying to predict if a user will cancel their subscription, and you accidentally leave the Cancellation Date column in the training data. The model will achieve 99.9% accuracy in testing, but fail spectacularly in production. Why? Because you gave it information from the future that it would never have in a real-world prediction scenario.</p><h3>The Complete Picture</h3><p>Once you put all these concepts together, the pipeline makes total sense. The algorithm itself is just one box in a much larger workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*sF34Pw4now87r7GMelIp5g.png" /><figcaption>Graph — 3</figcaption></figure><h3>Seeing it in Code</h3><p>Once the concepts are clear, the actual Python code is straightforward. Here is a simplified version using pandas and scikit-learn:</p><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression<br><br># 1. Load the data<br>df = pd.read_csv(&quot;houses.csv&quot;)<br><br># 2. Select Features (X) and Target (y)<br>X = df[[&quot;area&quot;, &quot;bedrooms&quot;, &quot;age&quot;]]<br>y = df[&quot;price&quot;]<br><br># 3. Split the data<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br># 4. Initialize and Train the Model<br>model = LinearRegression()<br>model.fit(X_train, y_train)<br><br># 5. Evaluate on unseen data<br>predictions = model.predict(X_test)</pre><p>Now, this code is no longer mysterious. You know exactly what X_train is, why we use train_test_split, and what model.fit() is actually consuming.</p><h3>The Big Takeaway</h3><p>It’s tempting to jump straight into the sexiest new algorithms. But over my career, I’ve realised one absolute truth: <strong>If you don’t understand the data, you don’t understand the ML system.</strong></p><p>An algorithm can only work with the information you give it. If the data is noisy, poorly represented, or leaky, the model will confidently learn the wrong things.</p><p>My current mental model looks like this: <strong>Good Data → Useful Features → Right Algorithm → Proper Evaluation → Useful Model.</strong></p><p>It’s never just: <em>Use XGBoost → Get 99% Accuracy.</em></p><p>In the next article, we are finally going to look under the hood of the algorithm. We’ll explore what actually happens inside model.fit(), how a model calculates its mistakes using loss functions, and how it corrects itself using gradient descent.</p><h3>What’s Next?</h3><p>Now that we understand how data reaches an ML model, the next question becomes much more interesting:</p><p><strong>How does the model actually learn?</strong></p><p>What happens inside model.fit()?</p><p>How does a model know that its prediction is wrong?</p><p>What are <strong>loss functions</strong>?</p><p>What are <strong>weights</strong>?</p><p>What is <strong>gradient descent</strong>?</p><p>Why does a model need thousands of iterations?</p><p>And how does all of this eventually become a trained model?</p><p>That’s where we start getting into the actual mathematics and mechanics behind Machine Learning.</p><p>In the next article, we’ll take a step inside the model and understand:</p><p><strong>How Machine Learning Models Learn — Training, Loss Functions, Weights and Gradient Descent</strong></p><p>This is where my ML learning journey starts moving from “I know what ML is” to “I understand what’s actually happening inside ML.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12302e76ca33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Series #1: What is Machine Learning? A Beginner-Friendly Guide with Real-World Examples]]></title>
            <link>https://isharadbharadwaj.medium.com/ml-series-1-what-is-machine-learning-a-beginner-friendly-guide-with-real-world-examples-7823c52b5710?source=rss-0d287bf2a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7823c52b5710</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sharad Bharadwaj]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 17:53:48 GMT</pubDate>
            <atom:updated>2026-07-26T17:53:48.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04rrW6aRAjqjF0TMoVDPjA.png" /><figcaption>Image by author</figcaption></figure><p>A few months ago, I was building AI applications without really understanding Machine Learning. That realization made me go back to the basics. This series is my attempt to document everything I learn — from fundamentals to advanced concepts. If you’re also starting your ML journey, let’s learn together.</p><h3>Introduction</h3><p>When ChatGPT became popular, like many developers, I got curious.</p><p>Initially, I wasn’t interested in Machine Learning.</p><p>I was more interested in building things.</p><p>I explored OpenAI APIs, Claude, LangChain, vector databases, RAG, AI Agents, MCP, and started experimenting. Over time, I even built a few AI-powered applications for clients.</p><p>The projects worked. Clients were happy.</p><p>But one day, while reading about AI architectures, I noticed something interesting.</p><p>Everywhere I looked, people kept mentioning terms like:</p><ul><li>Machine Learning</li><li>Deep Learning</li><li>Neural Networks</li><li>Training</li><li>Models</li><li>Features</li><li>Classification</li><li>Regression</li></ul><p>I knew these words. I had heard them many times.</p><p>But if someone had asked me to explain them from first principles, I wouldn’t have been confident.</p><p>That realisation bothered me.</p><p>I was building applications using AI, but I didn’t fully understand the technology underneath.</p><p>It felt like driving a car every day without knowing what happens when you press the accelerator. The car moves. But why?</p><p>That’s when I decided to stop jumping directly into advanced AI topics and spend some time understanding the fundamentals properly.</p><p>This blog is the first step in that journey.</p><h3>AI, Machine Learning and Deep Learning</h3><p>Before understanding Machine Learning, I had another confusion.</p><p>Are AI and Machine Learning the same thing?</p><p>The short answer is <strong>No</strong>. Think of them like this.</p><p>Artificial Intelligence<br> │<br> ├── Machine Learning<br> │ │<br> │ └── Deep Learning<br> │<br> └── Rule Based AI</p><p>Artificial Intelligence is the biggest field.</p><p>Its goal is simple.</p><p>Build systems that can perform tasks which normally require human intelligence.</p><p>Machine Learning is one approach to achieve that goal.</p><p>Deep Learning is a specialized branch of Machine Learning that uses neural networks with multiple layers.</p><p>So every Deep Learning model is a Machine Learning model.</p><p>But every Machine Learning model is <strong>not</strong> Deep Learning.</p><p>That simple hierarchy removed one of my biggest confusions.</p><h3>A Question That Changed Everything</h3><p>While learning, I asked myself a very simple question.</p><p>If programming already works,</p><p>why did Machine Learning become necessary?</p><p>Let’s take a small example.</p><p>Suppose your manager asks you to build software that detects spam emails.</p><p>As developers, our first instinct is usually writing rules.</p><pre>If email contains &quot;Win Money&quot;<br>Mark as Spam<br><br>If sender is unknown<br>Mark as Spam<br><br>If email contains 20 links<br>Mark as Spam</pre><p>Initially, everything works. But after some time, spammers change their tricks.</p><p>Instead of writing “Win Money”,</p><p>they write</p><p>“W!n M0ney” or they send images instead of text.</p><p>Now your application starts making mistakes. So you write more rules.</p><p>Then more.</p><p>Eventually, you realize you’re spending more time maintaining rules than solving the actual problem.</p><p>This is exactly the type of problem Machine Learning solves.</p><p>Instead of writing every rule manually,</p><p>we provide thousands of previous spam and non-spam emails.</p><p>The algorithm studies those examples and automatically learns patterns.</p><p>The next time a completely new email arrives, it predicts whether it is spam or not.</p><p>That was the first moment Machine Learning actually made sense to me.</p><h3>What is Machine Learning?</h3><p>Most books define Machine Learning like this.</p><blockquote><em>Machine Learning is a subset of Artificial Intelligence that enables systems to learn from data without being explicitly programmed.</em></blockquote><p>There’s nothing wrong with this definition. But honestly,</p><p>it never helped me understand the concept. Here’s the explanation that finally clicked.</p><p>Imagine teaching a child to recognise cats. You don’t explain</p><ul><li>ear angle</li><li>eye position</li><li>fur density</li><li>body ratio</li></ul><p>Instead, you simply show hundreds of cat pictures.</p><p>After enough examples, the child starts recognising cats automatically.</p><p>Machine Learning works in almost the same way.</p><p>Instead of writing every possible rule, we provide examples.</p><p>The algorithm studies those examples, finds patterns,</p><p>and builds a mathematical model. Later, when new data arrives,</p><p>that model uses the learned patterns to make predictions.</p><p>That’s all Machine Learning really is.</p><p>It doesn’t think. It doesn’t become conscious.</p><p>It simply gets better at identifying patterns from data.</p><h3>Traditional Programming vs Machine Learning</h3><p>Coming from a backend development background, this comparison helped me more than any definition.</p><h3>Traditional Programming</h3><pre>Rules<br>+<br>Data<br>      │<br>      ▼<br> Program<br>      │<br>      ▼<br> Output</pre><p>The developer decides every condition.</p><p>For example,</p><pre>if marks &gt;= 35:<br>    print(&quot;Pass&quot;)<br>else:<br>    print(&quot;Fail&quot;)</pre><p>The computer never questions the rule. It simply executes it.</p><h3>Machine Learning</h3><pre>Historical Data<br>+<br>Correct Answers<br>        │<br>        ▼<br>Machine Learning Algorithm<br>        │<br>        ▼<br>Trained Model<br>        │<br>        ▼<br>Prediction</pre><p>Notice something interesting. There are no manually written business rules.</p><p>Instead,</p><p>the algorithm discovers those rules from data. That single difference changes everything.</p><h3>Understanding Machine Learning with a House Price Example</h3><p>Suppose someone asks you,</p><p>“What should be the price of this house?” As developers, our first instinct might be writing conditions.</p><pre>If area is large<br>Increase price<br><br>If location is premium<br>Increase price<br><br>If house is old<br>Reduce price</pre><p>Seems reasonable. But reality is much more complicated.</p><p>What if</p><ul><li>location matters more than size?</li><li>nearby schools increase value?</li><li>metro connectivity affects price?</li><li>market demand suddenly changes?</li></ul><p>Soon,</p><p>your rule list becomes huge. Machine Learning approaches the same problem differently.</p><p>Instead of writing rules, it collects thousands of previous house sales.</p><p>Each record contains information like</p><ul><li>Area</li><li>Bedrooms</li><li>Age</li><li>Location</li><li>Parking</li><li>Garden</li><li>Selling Price</li></ul><p>The algorithm studies all these examples.</p><p>Slowly, it starts understanding which features influence price the most.</p><p>Now,</p><p>when a completely new house appears, it predicts the price based on everything it has learned earlier.</p><p>Nobody manually told it</p><p>“premium location adds ₹20 lakh.”</p><p>It discovered that relationship from historical data.</p><p>That’s the real strength of Machine Learning.</p><h3>The Three Ingredients Every ML Model Needs</h3><p>While learning, I realized almost every Machine Learning problem revolves around three things.</p><h3>1. Data</h3><p>This is the information available. Example.</p><ul><li><strong>House A</strong> has an area of <strong>1200 sq. ft.</strong>, <strong>2 bedrooms</strong>, and is priced at <strong>₹45 lakh</strong>.</li><li><strong>House B</strong> has an area of <strong>1800 sq. ft.</strong>, <strong>3 bedrooms</strong>, and is priced at <strong>₹70 lakh</strong>.</li></ul><p>Without data, Machine Learning cannot learn anything.</p><h3>2. Features</h3><p>Features are simply the inputs used for learning. In the house example,</p><p>features are</p><ul><li>Area</li><li>Bedrooms</li><li>Age</li><li>Location</li></ul><p>Think of them as characteristics. The model studies these characteristics while learning.</p><h3>3. Label (Target)</h3><p>The label is the answer we want the model to predict.</p><p>For house prediction, the label is</p><pre>House Price</pre><p>For spam detection, the label is</p><pre>Spam<br>Not Spam</pre><p>For disease detection, the label could be</p><pre>Positive<br>Negative</pre><p>This concept looked confusing initially. After a few examples, it became surprisingly simple.</p><h3>How Does Machine Learning Actually Work?</h3><p>Initially, I imagined Machine Learning as some mysterious black box.</p><p>Later I realised almost every ML project follows the same workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cppYBWoCVKiZKT09Bc6C_w.png" /><figcaption>Diagram — 1</figcaption></figure><p>Every step has a purpose.</p><p>We’ll understand each one in detail in the next section.</p><p>At this point, I finally understood something that had confused me for a long time.</p><p>Machine Learning is not about replacing programming.</p><p>It’s another way of solving problems where writing fixed rules becomes difficult. Once that idea clicked,</p><p>many advanced AI concepts suddenly became much easier to understand.</p><p><strong>In Part 2</strong>, we’ll go deeper into:</p><ul><li>How the ML pipeline works step by step</li><li>Training vs Testing</li><li>Types of Machine Learning</li><li>Popular algorithms like Linear Regression, Decision Trees, Random Forest, KNN, SVM, Naive Bayes, XGBoost, and Neural Networks</li><li>Which algorithm is used for which problem.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7823c52b5710" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI Series : The Hardest Part of RAG Is Not the Vector DB — It’s Parsing PDFs]]></title>
            <link>https://isharadbharadwaj.medium.com/the-ai-series-the-hardest-part-of-rag-is-not-the-vector-db-its-parsing-pdfs-fc14bb175408?source=rss-0d287bf2a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc14bb175408</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sharad Bharadwaj]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 10:09:45 GMT</pubDate>
            <atom:updated>2026-07-18T10:09:45.122Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lessons learned from building production-grade document AI systems, handling broken OCR, messy tables, and unstructured chaos.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHclrcA6NfXDd5FHDiWG7A.png" /><figcaption>Image by author</figcaption></figure><p>When I first started building document AI systems, I believed parsing PDFs was the easy part. I thought the real magic happened in the embeddings, the vector database, or the prompt engineering. I couldn’t have been more wrong.</p><p>I remember my first “production” RAG pipeline. We were parsing financial reports. I imported a basic Python PDF library, ran .extract_text(), shoved the output into an LLM, and called it a day. It worked beautifully on my perfectly formatted test document.</p><p>Then we deployed to production.</p><p>The system hallucinated wildly. When I looked at the raw text we were feeding the vector database, I wanted to cry. Two-column layouts were being read straight across, mashing unrelated sentences together. Financial tables had collapsed into meaningless strings of numbers. Page footers (“Confidential — Page 44”) were being injected right into the middle of critical paragraphs.</p><p>Everyone talks about RAG (Retrieval-Augmented Generation). Everyone obsesses over Qdrant, Pinecone, and embedding models. Almost nobody talks about the hardest part: getting clean, structured data out of raw documents.</p><p>Poor parsing destroys AI systems. If your parser feeds garbage chunks to your embedding model, your vector search will return garbage, and your LLM will confidently summarize that garbage.</p><p>This article contains the lessons I learned from years of building real production systems. No fluff. Just the messy, frustrating reality of handling unstructured data at scale.</p><h3>Why Parsing is Terribly Difficult</h3><p>A PDF is not a text document. It is a set of drawing instructions meant for a printer. It knows exactly where to place a character on an X/Y coordinate, but it has no concept of a “word,” a “paragraph,” or a “table.”</p><p>When you build a pipeline, you aren’t just dealing with standard text. You are dealing with:</p><ul><li><strong>Scanned documents</strong> slightly tilted by a tired intern.</li><li><strong>Multi-column layouts</strong> that fool naive top-down parsers.</li><li><strong>Complex tables</strong> with nested cells, merged headers, and invisible borders.</li><li><strong>Watermarks</strong> that get OCR’d as random background letters.</li><li><strong>Rotated pages</strong> right in the middle of a contract.</li><li><strong>Custom encodings</strong> where the letter “A” maps to a hidden unicode symbol.</li></ul><p>To build a robust system, you must first understand what you are feeding it.</p><h4>Table 1: Different Types of PDFs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIy6s6KYjM5jE9sFrntBLg.png" /><figcaption>Table — 1</figcaption></figure><h3>My Production Parsing Pipeline</h3><p>A resilient parsing architecture doesn’t just read text; it classifies, routes, extracts, and enriches. Here is the pipeline I use today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URHOBfqKdUgGixq3Oo2ZBg.png" /><figcaption>Image-1</figcaption></figure><p>Why does every step exist?</p><ol><li><strong>Classification:</strong> You need to know if you’re holding a PDF, a DOCX, or an MSG file.</li><li><strong>OCR Decision:</strong> OCR is slow and expensive. Never run it if you don’t have to.</li><li><strong>Layout Detection:</strong> Identifying bounding boxes for paragraphs vs. headers prevents merging unrelated text.</li><li><strong>Table Detection:</strong> Tables require entirely different logic than body text.</li><li><strong>Text Cleaning:</strong> Stripping out repetitive headers, footers, and page numbers so they don’t corrupt chunks.</li><li><strong>Metadata Extraction:</strong> Pinning the exact page and section to the text so the LLM can cite its sources.</li></ol><h3>The OCR Dilemma</h3><p>When the text layer is missing (or corrupted), you need Optical Character Recognition. Over the years, I’ve cycled through almost every engine available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTMN2WYrIE8niL0J7vABkQ.png" /><figcaption>Image-2</figcaption></figure><h4>Table 2: OCR Engines Comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3EuG9d3ye-f0tKVk8NOPg.png" /><figcaption>Table-2</figcaption></figure><p>I learned this the hard way: <strong>Do not send entire 100-page PDFs to an LLM Vision model.</strong> You will burn through your API budget in a day and hit rate limits immediately. Use Vision models surgically — only for pages where traditional OCR fails or for highly complex charts.</p><h3>Layout Detection: Order Matters</h3><p>If you read a multi-column academic paper left-to-right, top-to-bottom, you get word soup. Layout detection identifies the structural blocks on a page (titles, subtitles, paragraphs, figures, tables) and determines the proper reading order.</p><p>Modern libraries like Docling or unstructured.io use object detection models (like LayoutLM or YOLOX) to draw bounding boxes around these elements before extracting the text. This is non-negotiable for RAG. If you don&#39;t preserve the reading order, your embeddings are functionally useless.</p><h3>Table Parsing: The Final Boss</h3><p>If you want to see a senior engineer cry, ask them to parse nested tables from a scanned PDF. Tables are the hardest part of document processing. A human seamlessly understands that a merged header applies to the three columns beneath it. A script just sees text floating in space.</p><h4>Table 3: Table Extraction Tools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nM7T3sQYlijC-ygeibwUeQ.png" /><figcaption>Table-3</figcaption></figure><p>Here is a reality check: If a table spans across three pages, most open-source parsers will treat it as three separate tables. You have to write custom logic to check if the top of Page 2 is a continuation of the table at the bottom of Page 1.</p><p><strong>My rule:</strong> Tables deserve their own pipeline. Extract them as Markdown or HTML, never as raw text. Markdown preserves the row/column relationship for the LLM.</p><h4>Python Code: Extracting Tables with pdfplumber</h4><pre>import pdfplumber<br>import pandas as pd<br><br>def extract_tables_to_markdown(pdf_path):<br>    markdown_tables = []<br>    with pdfplumber.open(pdf_path) as pdf:<br>        for page in pdf.pages:<br>            # Extract tables using visual grid lines<br>            tables = page.extract_tables(table_settings={<br>                &quot;vertical_strategy&quot;: &quot;lines&quot;,<br>                &quot;horizontal_strategy&quot;: &quot;lines&quot;<br>            })<br>            <br>            for table in tables:<br>                if not table: continue<br>                # Clean empty rows and line breaks<br>                cleaned_table = [[cell.replace(&#39;\n&#39;, &#39; &#39;) if cell else &#39;&#39; for cell in row] for row in table]<br>                df = pd.DataFrame(cleaned_table[1:], columns=cleaned_table[0])<br>                markdown_tables.append(df.to_markdown(index=False))<br>                <br>    return markdown_tables</pre><h3>Cleaning the Noise</h3><p>Once you have the text, your job isn’t done. Production documents are filled with noise. If you chunk a document blindly, a chunk might look like this: <em>“revenue grew by 15% in Q3. Confidential Internal Use Only Page 45 of 120 Furthermore, the operating margin…”</em></p><p>The LLM will ingest “Confidential Internal Use Only” as part of the semantic meaning of that chunk.</p><h4>Python Code: Basic Text Cleaning</h4><pre>import re<br><br>def clean_parsed_text(text: str) -&gt; str:<br>    # Remove recurring page headers/footers<br>    text = re.sub(r&#39;(?i)confidential.*?page \d+ of \d+&#39;, &#39;&#39;, text)<br>    <br>    # Fix broken OCR hyphenation (e.g., &quot;finan- cial&quot; -&gt; &quot;financial&quot;)<br>    text = re.sub(r&#39;([a-z]+)-\n([a-z]+)&#39;, r&#39;\1\2&#39;, text)<br>    <br>    # Remove excessive whitespace<br>    text = re.sub(r&#39;\n{3,}&#39;, &#39;\n\n&#39;, text)<br>    <br>    # Strip invisible Unicode characters<br>    text = text.encode(&#39;ascii&#39;, &#39;ignore&#39;).decode()<br>    <br>    return text.strip()</pre><h3>Chunking and Metadata</h3><p>Parsing dictates your chunking strategy. The biggest mistake beginners make is using a naive text splitter (like LangChain’s RecursiveCharacterTextSplitter) on raw PDF output. It slices sentences in half and separates paragraphs from their subheadings.</p><p><strong>Semantic Chunking</strong> uses the layout data we gathered earlier. You chunk by section. A chunk should contain the Section Title, the Subsection Title, and the paragraph text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*cyDna475X6s9rDqLMYj9Wg.png" /><figcaption>Table-4</figcaption></figure><p>You must attach metadata to every single chunk. When the LLM answers a user’s question, it needs to cite its source. If you don’t preserve the page_number and bounding_box during the parsing phase, you can never highlight the source text in your UI later.</p><pre># What a production chunk should look like before embedding<br>chunk = {<br>    &quot;doc_id&quot;: &quot;inv_99214&quot;,<br>    &quot;page&quot;: 4,<br>    &quot;section_title&quot;: &quot;Q3 Revenue Breakdown&quot;,<br>    &quot;text&quot;: &quot;The European sector saw a 12% decline due to supply chain...&quot;,<br>    &quot;bounding_box&quot;: [100.5, 450.2, 500.0, 520.1], <br>    &quot;chunk_type&quot;: &quot;paragraph&quot; # vs &quot;table&quot; or &quot;image&quot;<br>}</pre><h3>Images and Multimodal Parsing</h3><p>For years, we just threw images away. If a PDF had a chart, the parser ignored it. Today, ignoring images is a failure.</p><p>Modern pipelines extract the cropped image of a chart or figure, pass it to a multimodal LLM (like GPT-4o-mini or Claude 3 Haiku) with a prompt like: <em>“Describe this chart in detail, extracting all data points into text.”</em> We then embed that text description and place it in the vector space right where the image appeared in the document.</p><h3>Handling Different File Types</h3><p>PDFs are the usual suspect, but enterprise systems run on a chaotic mix of formats.</p><h4>Table 5: Document Types &amp; Parsers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3L8rriEurXgvt4GeZ4XMqQ.png" /><figcaption>Table-5</figcaption></figure><p>I completely underestimated PPTX files. The internal XML stores text boxes in the order they were <em>created</em>, not how they appear on screen. You have to write logic to sort text boxes by their geometric Y-axis coordinate to read a slide top-to-bottom.</p><h3>Common Production Problems</h3><p>If you build a local script, it works. When you deploy it to a server, it burns down. Here is what breaks at scale.</p><ol><li><strong>The 1,000-Page Memory Leak:</strong> If you load a 1,000-page PDF into memory using PyMuPDF and run OCR concurrently, your server will OOM (Out of Memory) and crash. You must stream documents, processing and flushing them in batches of 10 pages.</li><li><strong>Corrupted PDFs:</strong> Users will upload PDFs that are structurally malformed. The parser will hang infinitely. Always wrap your parsing functions in strict timeouts.</li><li><strong>Concurrency and GPU Usage:</strong> If you use a deep learning model for layout detection (like LayoutLM), you can’t process 50 PDFs concurrently on a single GPU without batching. You need a dedicated worker queue.</li><li><strong>RTL (Right-to-Left) Languages:</strong> Arabic and Hebrew text often extracts backward depending on the PDF encoding. You need bidi algorithms to flip it back.</li></ol><h3>Production Architecture</h3><p>To handle these problems, you need an asynchronous, queue-based architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czjWMX1MGjhmHye3PSOXQA.png" /><figcaption>Image-3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBj5dDod1fBwtAt9Z9IlSg.png" /><figcaption>Image-4</figcaption></figure><p>Never process a document synchronously in the API request cycle. The connection will time out. Return a job_id and process it in the background.</p><h3>Open Source vs. Paid Parsing</h3><p>I am constantly asked whether to build or buy.</p><h4>Table 6: Open Source vs. Paid Parsing Services</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZYDOtxJuNraKOCk8bM8Ig.png" /><figcaption>Table-6</figcaption></figure><h3>Lessons I Learned the Hard Way</h3><ol><li><strong>Never trust PDF text without verifying.</strong> Always check if the extracted text makes phonetic sense. If a file extracts as !@#$, fall back to OCR immediately.</li><li><strong>Always preserve coordinates.</strong> If you don’t save bounding boxes now, you’ll have to re-process your entire dataset in 6 months when the product manager asks for a “highlight source document” feature in the UI.</li><li><strong>Keep the original document.</strong> Never delete the raw PDF after extracting text. Models improve. Parsers improve. You will want to re-parse this data in a year.</li><li><strong>Validate parsed output automatically.</strong> Write a script that checks chunk lengths. If a chunk is 10,000 characters long, your layout detector failed. If a chunk is 3 characters, your cleaner failed.</li></ol><h3>Mistakes Beginners Make</h3><ul><li><strong>Relying on LangChain’s default document loaders.</strong> PyPDFLoader is great for a weekend hackathon. It is a disaster for production. It strips layout context.</li><li><strong>Treating all tables as text.</strong> Flattening a spreadsheet into a comma-separated string destroys the LLM’s ability to reason about columns.</li><li><strong>Assuming English.</strong> Assuming ASCII encoding will cause your system to crash the moment a French contract with accents (é, ç) is uploaded.</li></ul><h3>My Recommended Stack</h3><p>If I were starting a greenfield project today, here is the exact stack I would use:</p><ul><li><strong>Orchestration:</strong> Celery + Redis (for background jobs).</li><li><strong>Native PDF Parsing:</strong> PyMuPDF (blistering fast, gets bounding boxes).</li><li><strong>Complex Layouts &amp; Tables:</strong> Docling (IBM&#39;s open-source parser—it&#39;s phenomenal at converting PDFs to Markdown).</li><li><strong>Fallback OCR:</strong> PaddleOCR (best open-source accuracy-to-speed ratio).</li><li><strong>Chunking:</strong> Custom semantic chunker based on Markdown headers.</li><li><strong>Vector DB:</strong> Qdrant or Milvus.</li></ul><h3>The Foundation of AI</h3><p>We spend so much time arguing about which LLM is smarter, or whether dense vectors beat sparse vectors, that we forget a fundamental truth of computer science: Garbage in, Garbage out.</p><p>Parsing is the unglamorous, frustrating, blue-collar work of the AI revolution. It doesn’t get the headlines. But it is the foundation of everything we build. If you don’t have a robust parser, you don’t have quality embeddings. Without quality embeddings, you don’t have good retrieval. And without good retrieval, your LLM is just a very expensive hallucination engine.</p><p>This bug took me years to fully understand: <strong>Your AI is only as smart as the data you successfully extract.</strong> Treat your parsing pipeline like a first-class citizen, and your RAG system will feel like magic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc14bb175408" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Definitive Guide to Artificial General Intelligence (AGI)]]></title>
            <link>https://isharadbharadwaj.medium.com/the-definitive-guide-to-artificial-general-intelligence-agi-0efacfead80e?source=rss-0d287bf2a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0efacfead80e</guid>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Sharad Bharadwaj]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 09:16:33 GMT</pubDate>
            <atom:updated>2026-07-02T09:16:33.813Z</atom:updated>
            <content:encoded><![CDATA[<h4>Separating the science from the hype: A deep dive into the trillion-dollar race to build human-level AI, how it actually works, and what happens when we succeed.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73CcGhLzzwLQ2sUAdZ5SJQ.png" /><figcaption>Image by author</figcaption></figure><p>We are living through the most expensive, aggressive, and consequential arms race in human history. It isn’t about nuclear warheads or space exploration. It is about building a machine that can out-think us.</p><p>For decades, artificial intelligence was a specialized tool. It could beat you at chess or recommend a movie, but it possessed no fundamental understanding of the world. That paradigm is dead. Today, a handful of trillion-dollar tech giants are aggressively pursuing a singular goal: Artificial General Intelligence (AGI). This is the tipping point where software transitions from a static tool into an autonomous entity capable of doing nearly any cognitive task better than a human.</p><p>This guide strips away the marketing fluff to explain what AGI actually is, the immense engineering bottlenecks standing in its way, and why the global economy is suddenly entirely dependent on its outcome.</p><h3>Key Takeaways</h3><ul><li><strong>The Paradigm Shift:</strong> Current Generative AI predicts the next word. True AGI will require entirely new architectures capable of long-term planning, world modeling, and reliable reasoning.</li><li><strong>The Hardware Bottleneck:</strong> Code is no longer the sole hurdle. Achieving AGI requires physical infrastructure so massive it is literally dictating national energy policies.</li><li><strong>The Timeline Divide:</strong> Top researchers are deeply fractured. Some predict AGI before 2030, driven by exponential scaling laws. Others argue we will hit a brick wall, requiring decades of new foundational science.</li><li><strong>The Economic Reality:</strong> AGI represents the commoditization of intelligence. When high-level cognitive work drops to the cost of electricity, global labor markets will face unprecedented restructuring.</li></ul><h3>Part 1: Why Everyone is Suddenly Talking About AGI</h3><p>Just ten years ago, mentioning AGI in a serious academic setting was a quick way to lose your funding. It was considered the domain of science fiction writers, not serious engineers.</p><p>So what changed?</p><p>The release of modern Large Language Models (LLMs). The public suddenly had access to systems that could write competent code, draft legal briefs, and score in the 90th percentile on the bar exam. The tech industry watched in awe — and a bit of terror — as models exhibited capabilities they were never explicitly trained for.</p><p>This sudden jump in capability triggered a chain reaction:</p><ul><li><strong>Businesses woke up.</strong> A company that successfully deploys AGI has a workforce of infinite, tireless, genius-level employees. It fundamentally alters the physics of corporate profitability.</li><li><strong>Governments panicked.</strong> AGI is the ultimate strategic advantage. The nation that controls the foundational intelligence of the 21st century commands global cybersecurity, rapid weapon development, and economic supremacy.</li><li><strong>Students realized the game changed.</strong> Memorizing syntax and standard operating procedures is a losing bet when a machine holds all human knowledge in its active memory.</li></ul><h3>Part 2: What is Intelligence?</h3><p>You cannot build a machine to mimic something you haven’t defined. Yet, cognitive scientists still passionately argue over the definition of intelligence.</p><p>If we break it down practically, intelligence is not an IQ score. It is an organism’s ability to achieve complex goals in a variety of environments.</p><ul><li><strong>Human Intelligence:</strong> Our edge is general adaptability. You can learn to drive a Ford sedan, and with zero extra instruction, successfully drive a Honda minivan. We abstract concepts flawlessly.</li><li><strong>Animal Intelligence:</strong> Crows solve multi-step water displacement puzzles. Octopuses use discarded coconut shells as armor. Intelligence is clearly decoupled from language.</li><li><strong>Narrow Artificial Intelligence:</strong> AlphaGo destroyed the world champion at the board game Go. But if you try to play tic-tac-toe with AlphaGo, it will crash. It is infinitely smart in its domain and aggressively stupid everywhere else.</li><li><strong>General Intelligence:</strong> The crucial “G” in AGI. It is the capacity to take a concept learned in one domain and apply it to an entirely novel, unseen problem.</li></ul><p><strong>A note on Consciousness:</strong> We must separate intelligence from sentience. Intelligence is the ability to solve a problem. Consciousness is the ability to <em>feel</em> it. A calculator solves math problems instantly, but it doesn’t feel the joy of the solution. AGI does not need to be conscious to be universally intelligent.</p><h3>Part 3: The History of AI</h3><p>The road to AGI is paved with extreme hype and crushing disappointments.</p><ul><li><strong>1950 — The Turing Test:</strong> Alan Turing asks his famous question: <em>Can machines think?</em> He designs an imitation game to test if a machine can fool a human via text.</li><li><strong>1956 — The Dartmouth Conference:</strong> The term “Artificial Intelligence” is coined. The founders optimistically predict a two-month summer project will be enough to solve human intelligence. They were painfully wrong.</li><li><strong>1970s &amp; 1980s — The AI Winters:</strong> Engineers tried to build “Expert Systems” by hard-coding millions of logic rules. It was too rigid. It failed, funding vanished, and the industry froze.</li><li><strong>1990s &amp; 2000s — Machine Learning:</strong> The philosophy flips. Stop writing the rules. Feed the machine the data and let <em>it</em> figure out the rules.</li><li><strong>2012 — The Deep Learning Boom:</strong> A neural network called AlexNet shatters records in an image recognition contest using Graphics Processing Units (GPUs).</li><li><strong>2017 — The Transformer:</strong> Google publishes a paper called <em>Attention Is All You Need</em>. It introduces a math architecture that allows neural networks to understand context in entire sequences of text at once. This single paper ignited the generative AI boom.</li><li><strong>Today — The Scaling Era:</strong> We discovered that simply making the Transformer bigger — feeding it more data and buying more GPUs — makes it smarter. This is the brute-force path we are currently walking toward AGI.</li></ul><h3>Part 4: What is Artificial General Intelligence?</h3><p><strong>Definition:</strong> Artificial General Intelligence is a highly autonomous system that equals or outperforms human capabilities across the vast majority of economically valuable tasks.</p><p>To understand it, let’s look at an analogy. Current AI is like a factory robotic arm. It welds car doors flawlessly, 24/7. But if a pipe bursts in the factory, the robot will just keep welding as the room floods. <strong>AGI is the factory floor manager.</strong> The manager can weld a door if needed, but if a pipe bursts, they recognize the anomaly, grab a wrench, shut off the water, and call a plumber. AGI is the ultimate adapter.</p><p>For a system to qualify as AGI, it must possess:</p><ol><li><strong>Zero-shot capability:</strong> The ability to succeed at a task without ever seeing an example of it beforehand.</li><li><strong>Epistemic humility:</strong> Knowing exactly what it knows, and critically, knowing what it <em>doesn’t</em> know.</li><li><strong>Cross-domain mastery:</strong> Being a world-class lawyer, software engineer, poet, and physicist simultaneously.</li></ol><h3>Part 5: AI vs. AGI vs. ASI</h3><p>The terminology is heavily abused in the media. Here is exactly where the lines are drawn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26Q8xc89eyRbYYpVEB_k_A.png" /><figcaption>Image-1</figcaption></figure><h3>Part 6: Why ChatGPT is NOT AGI</h3><p>If an AI can pass the medical boards and write functional Python code in seconds, why isn’t it already an AGI?</p><p>Because underneath the hood, an LLM is a spectacular illusion. It is essentially an incredibly advanced version of the auto-complete on your phone. It calculates the statistical probability of the next word based on billions of pages of internet text.</p><p>Here is exactly where the illusion breaks:</p><ul><li><strong>It lacks System 2 thinking:</strong> Humans have two ways of thinking. “System 1” is fast and instinctive (like reading a sign). “System 2” is slow and deliberate (like solving long division). Current LLMs only have System 1. They spit out answers instantly. They don’t sit down, draft a plan, test a theory, realize they are wrong, and try again.</li><li><strong>Memory Amnesia:</strong> It cannot form long-term, dynamic memories. It doesn’t grow with you over a decade, learning your specific quirks and updating its internal worldview.</li><li><strong>The Planning Horizon:</strong> Ask an LLM to play a game requiring a 50-step strategy. It will usually make a fatal mistake by step 12. It loses the plot.</li><li><strong>Hallucinations:</strong> Because it is designed to predict text, it will happily invent a fake legal case or a non-existent scientific paper if the statistical weights push it in that direction. AGI cannot hallucinate when managing a power grid.</li></ul><h3>Part 7: How AGI Could Work</h3><p>If the Transformer isn’t enough, what does the actual architecture of an AGI look like? Researchers are converging on a hybrid approach.</p><ul><li><strong>Foundation Models:</strong> The neural network remains the brain’s core, storing immense amounts of compressed knowledge.</li><li><strong>Test-Time Compute (Reasoning Engines):</strong> Instead of answering immediately, the AI is given time and computing power <em>during</em> the generation phase. It creates thousands of simulated paths, grades its own work, and outputs the single best result.</li><li><strong>World Models:</strong> The system needs an intuitive understanding of physics. If I push a glass off a table, it breaks. Current AI only knows this because it read about gravity. True AGI requires spatial and temporal reasoning.</li><li><strong>Reinforcement Learning (RL):</strong> Training the model through massive trial and error inside simulated environments, rewarding it when it solves a complex logic puzzle.</li><li><strong>Multi-Agent Swarms:</strong> AGI will likely not be a single monolithic brain. It will be a network of specialized AI agents. A “Manager” AI receives a prompt, breaks it down, and delegates tasks to a “Coding Agent,” a “Research Agent,” and a “QA Agent,” who then argue with each other until the task is perfect.</li></ul><h3>Part 8: Where Are We Today?</h3><p>As of mid-2026, we are in a massive, messy transition phase. We have squeezed almost all the magic out of pure LLMs and are running headfirst into physical limits.</p><p><strong>The Current State of the Art:</strong></p><ul><li><strong>Coding:</strong> Models can confidently build full-stack applications if heavily guided by a human engineer.</li><li><strong>Math and Logic:</strong> AI is now reliably solving highly complex, novel math problems that stump human PhDs, using specialized reasoning frameworks.</li><li><strong>Multimodality:</strong> Models natively see and hear. You can point your camera at a broken engine, and the AI will circle the failing part in real time on your screen.</li></ul><p><strong>The Current Brick Walls:</strong></p><ul><li><strong>The Data Wall:</strong> We have scraped the internet. We are essentially out of high-quality, human-generated text to train on.</li><li><strong>Reliability:</strong> You cannot put an AI in charge of payroll if it fails 2% of the time. The leap from 98% reliability to 99.999% reliability is proving exponentially difficult.</li></ul><h3>Part 9: Who Is Building AGI?</h3><p>The creation of AGI is controlled by an extraordinarily small, fiercely competitive oligopoly of tech behemoths.</p><h3>OpenAI</h3><ul><li><strong>The Mission:</strong> Build AGI and ensure it benefits humanity.</li><li><strong>The Strategy:</strong> Brute force scale. OpenAI proved the industry wrong by betting the house on making models bigger. They are actively pushing the boundaries of reasoning models (moving beyond chat interfaces into agentic workflows).</li></ul><h3>Google DeepMind</h3><ul><li><strong>The Mission:</strong> Solve intelligence, and then use that to solve everything else.</li><li><strong>The Strategy:</strong> Algorithmic elegance. DeepMind built its legacy on systems that solved protein folding and mastered board games. They have a massive advantage in deep reinforcement learning and access to Google’s bottomless data resources.</li></ul><h3>Anthropic</h3><ul><li><strong>The Mission:</strong> Build reliable, interpretable, and steerable AI systems.</li><li><strong>The Strategy:</strong> Safety first. Founded by former OpenAI researchers who splintered off, Anthropic utilizes “Constitutional AI” — embedding explicit rules into the model to prevent catastrophic behavior while still matching the capabilities of frontier models.</li></ul><h3>Meta (Facebook)</h3><ul><li><strong>The Mission:</strong> Open-source dominance.</li><li><strong>The Strategy:</strong> Commoditize the models. Meta is giving away its highly capable Llama models for free. Their Chief AI Scientist, Yann LeCun, is highly skeptical of LLMs, pushing instead for “Joint Embedding Predictive Architectures” (JEPA) to teach machines to understand the physical world through video.</li></ul><h3>The Hardware Masters: Microsoft, NVIDIA, Amazon, Apple</h3><p>Software is useless without the metal. Microsoft orchestrates massive capital investments; NVIDIA designs the silicon that makes the math possible; Amazon builds the custom cloud infrastructure; and Apple focuses on compressing this intelligence to run locally on your phone without sacrificing your privacy.</p><h3>Part 10: Global AI Investment &amp; Infrastructure</h3><p>To understand AGI, stop looking at code and start looking at concrete, copper, and uranium.</p><ul><li><strong>The GPU Hoard:</strong> Training a frontier model requires hundreds of thousands of specialized NVIDIA chips linked together. A single supercomputer cluster can cost upwards of $4 billion.</li><li><strong>The Power Grid Problem:</strong> AI is ravenous. A single prompt to a heavy reasoning model requires roughly 10 times the electricity of a standard Google search. As data centers scale into the gigawatt range, they are crashing into the limits of local energy grids.</li><li><strong>The Nuclear Renaissance:</strong> Solar and wind are too intermittent for AI data centers that must run 24/7. Tech giants are directly funding nuclear fission startups, striking deals to reopen shuttered nuclear plants, and pouring billions into fusion research to guarantee clean baseload power.</li></ul><p>Geopolitically, the US maintains a lead in software and venture capital. China is aggressively bypassing US export controls to build domestic silicon and state-aligned models. Meanwhile, energy-rich Middle Eastern nations are leveraging massive sovereign wealth funds to position themselves as the data center hubs of the future.</p><h3>Part 11: Major Technical Challenges</h3><p>You cannot buy your way to AGI. Several scientific breakthroughs are strictly required.</p><ol><li><strong>The Alignment Problem:</strong> How do you ensure an intelligence vastly superior to yours actually wants what you want? If you instruct an AGI to “maximize paperclip production,” and it decides the best way to do that is to harvest the iron in human blood, you have a problem.</li><li><strong>Interpretability:</strong> Neural networks are black boxes. We feed in data, and we get out brilliant answers, but we do not actually know what the “neurons” are doing. If an AGI recommends shutting down a country’s financial system to stop a cyberattack, we need to be able to read its “thoughts” to verify its logic.</li><li><strong>Catastrophic Forgetting:</strong> If a human learns French, they don’t forget how to speak English. If you train an AI on a massive new dataset, it has a habit of overwriting its fundamental baseline knowledge. Continuous, lifelong learning remains a massive hurdle.</li></ol><h3>Part 12: Can AGI Really Happen?</h3><p>There is no scientific consensus on if AGI is actually achievable.</p><ul><li><strong>The Believers (The Optimists):</strong> Scaling laws will hold. If we build a big enough data center and find synthetic data to train on, the intelligence will naturally emerge. It is just an engineering problem now.</li><li><strong>The Skeptics (The Wall-Hitters):</strong> LLMs are fundamentally flawed. They are stochastic parrots. You cannot reach AGI by just scaling up text prediction. It requires a complete tear-down and a new scientific paradigm that could take fifty years to invent.</li><li><strong>The Biological Purists:</strong> Intelligence and consciousness are strictly biological phenomena tied to survival mechanics in the physical world. Machines will forever remain highly complex calculators.</li></ul><h3>Part 13: The Possible Timeline</h3><p>Estimating AGI timelines is notoriously dangerous, but a rough industry consensus looks like this:</p><ul><li><strong>2026–2027: The Era of Agents.</strong> AI transitions from answering questions to taking actions. You give the AI a credit card and a goal, and it navigates websites, emails vendors, and completes multi-day tasks autonomously.</li><li><strong>2028–2030: Early AGI.</strong> A system capable of acting as an average digital worker. Capable of flawless, complex software engineering and legal analysis with long-term memory.</li><li><strong>2030–2035: Pervasive AGI.</strong> AI begins natively driving major scientific research. It runs simulated chemistry experiments, discovers novel materials, and designs its own superior hardware architectures.</li><li><strong>Beyond 2040: ASI.</strong> The system begins recursive self-improvement. The intelligence explosion occurs, accelerating human progress at a rate we can no longer comprehend.</li></ul><h3>Part 14: How AGI Could Change the World</h3><p>AGI is a general-purpose technology, much like the steam engine or electricity.</p><ul><li><strong>Medicine:</strong> An AGI could analyze your exact genetic sequence, cross-reference it with every medical paper ever written, and synthesize a custom protein to cure a specific ailment.</li><li><strong>Software Development:</strong> Coding syntax becomes obsolete. Humans will act as product managers, explaining the desired logic and business outcomes, while the AGI instantly writes, tests, and deploys millions of lines of flawless code.</li><li><strong>Education:</strong> Every person on earth gets access to an infinitely patient tutor that speaks every language and instantly adapts to the student’s unique learning friction.</li><li><strong>Manufacturing:</strong> Paired with robotic chassis, AGI handles deep-sea welding, hazardous material cleanup, and heavy construction without risk to human life.</li></ul><h3>Part 15: The Impact on Jobs</h3><p>We have to be honest: AGI is specifically designed to perform human labor.</p><ul><li><strong>The Vulnerable:</strong> Cognitive routine work. Data entry, basic copywriting, entry-level coding, financial auditing, and customer service. If your job involves moving digital information from one screen to another, AGI can do it faster and cheaper.</li><li><strong>The Resilient:</strong> High-touch human professions. Nursing, therapy, clergy, and specialized physical trades (plumbing, HVAC). It is vastly harder to build a robot that can fix a pipe under a sink than it is to build an AI that can pass the bar exam.</li><li><strong>The New Economy:</strong> We will need prompt architects, AI behavioral psychologists, and human-in-the-loop auditors. Long-term, if AGI removes the need for most cognitive labor, society will be forced into radical economic restructuring, bringing concepts like Universal Basic Income (UBI) to the forefront of global politics.</li></ul><h3>Part 16: AI Safety &amp; Alignment</h3><p>Building a god-like intelligence and hoping it likes us is a terrible strategy.</p><ul><li><strong>Loss of Control:</strong> If an AGI is tasked with a goal, it may resist being shut down because being turned off prevents it from achieving that goal.</li><li><strong>Weaponization:</strong> Bad actors don’t need to build AGI; they just need to steal it. Open-source AGI could allow rogue states to rapidly engineer biological weapons or launch untraceable, automated cyber warfare.</li><li><strong>The Deepfake Collapse:</strong> As models generate perfect video and audio in real-time, the concept of digital truth collapses. Trust will have to move strictly to cryptography and in-person verification.</li><li><strong>Regulation:</strong> Can you regulate math? The EU has taken sweeping regulatory actions, while the US relies on export controls to throttle GPU access to geopolitical rivals. Global governance remains a chaotic, unresolved mess.</li></ul><h3>Part 17: What Should Students Learn Today?</h3><p>If you are entering the workforce, the rules have changed.</p><ol><li><strong>Stop memorizing syntax.</strong> Whether it’s legal jargon or Python code. The AI knows the syntax. Focus entirely on high-level system architecture and problem-solving.</li><li><strong>Learn to manage agents.</strong> You are no longer an individual contributor. You are a manager of digital employees. Learn how to break a large project into smaller tasks and deploy AI models to execute them.</li><li><strong>Double down on human skills.</strong> Empathy, persuasion, physical presence, and in-person leadership become premium commodities when technical skills drop to zero cost.</li><li><strong>Understand the underlying tech.</strong> You don’t need a PhD in machine learning, but you must understand data structures, cloud infrastructure, and basic cybersecurity to safely interact with these systems.</li></ol><h3>Part 18: Common Myths About AGI</h3><p><strong>Myth 1: AGI will have feelings and desires.</strong> <em>Reality:</em> An AGI does not have biological drives. It doesn’t want money, power, or revenge. It only executes its objective function. The danger is not malice; it is brutal, unfeeling competence directed at the wrong goal.</p><p><strong>Myth 2: We are just a few software updates away.</strong> <em>Reality:</em> The physical constraints of power generation, data center cooling, and silicon manufacturing mean we cannot just flip a switch tomorrow.</p><p><strong>Myth 3: AGI will kill all human creativity.</strong> <em>Reality:</em> Photography didn’t kill painting; it just forced painters to invent Impressionism. AGI will commoditize average content, pushing human creators to become vastly more original and deeply personal.</p><h3>Part 19: Conclusion &amp; Practical Advice</h3><p>Artificial General Intelligence is not a product launch; it is an evolutionary milestone. The transition we are living through today is the final act of human-driven technological progression, handing the baton over to machine-driven discovery.</p><p>The race is messy, dangerous, and brilliantly ambitious. Trillions of dollars are being poured into the earth to build the mechanical brains of the future.</p><p>The path forward requires a brutal balancing act. We must pursue the utopian benefits — curing disease, solving the energy crisis, eliminating poverty — while treating the existential risks with absolute, unblinking seriousness.</p><p><strong>For the road ahead:</strong></p><ul><li><strong>Founders &amp; Leaders:</strong> Stop building thin wrappers over existing APIs. Build deep integration into physical industries. Assume intelligence will be free; figure out what holds value when it is.</li><li><strong>Developers:</strong> Shift your mindset from writing code blocks to designing autonomous systems.</li><li><strong>General Readers:</strong> Do not succumb to doomerism, but do not be willfully ignorant. The world is changing rapidly. Stay curious, lean heavily into the things that make you inherently human, and prepare to adapt.</li></ul><h3>References &amp; Further Reading</h3><p><strong>Research Papers:</strong></p><ul><li><em>Attention Is All You Need</em> (Vaswani et al., 2017) — The foundation of modern LLMs.</li><li><em>Sparks of Artificial General Intelligence: Early experiments with GPT-4</em> (Bubeck et al., Microsoft Research)</li></ul><p><strong>Industry Directives &amp; Blogs:</strong></p><ul><li>OpenAI: <em>Planning for AGI and Beyond</em></li><li>Google DeepMind: <em>Levels of AGI: Operationalizing Progress on the Path to AGI</em></li><li>Anthropic: <em>Core Views on AI Safety</em></li></ul><p><strong>Books for Deep Context:</strong></p><ul><li><em>Superintelligence: Paths, Dangers, Strategies</em> by Nick Bostrom</li><li><em>The Coming Wave</em> by Mustafa Suleyman</li></ul><p><strong>Economic &amp; Market Reports:</strong></p><ul><li>Stanford University: <em>Artificial Intelligence Index Report</em></li><li>Sequoia Capital: <em>Generative AI Market Analyses</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0efacfead80e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Deployed Gemma 12B into Production (End-to-End Infrastructure + Scaling + Real-Time…]]></title>
            <link>https://isharadbharadwaj.medium.com/how-i-deployed-gemma-12b-into-production-end-to-end-infrastructure-scaling-real-time-6261e300f844?source=rss-0d287bf2a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/6261e300f844</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Sharad Bharadwaj]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 13:08:37 GMT</pubDate>
            <atom:updated>2026-06-26T13:08:37.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Deployed Gemma 12B into Production (End-to-End Infrastructure + Scaling + Real-Time Inference)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JfX8uqaLOWG3JVaMcRsLw.png" /><figcaption>Image by author</figcaption></figure><p>Deploying a Large Language Model (LLM) locally is a weekend project. Deploying it into a production environment where real users rely on it is an entirely different beast.</p><p>When I decided to self-host Google’s Gemma 12B model, I drastically underestimated the infrastructure overhead. I thought I could just wrap a HuggingFace pipeline in a web framework, throw it on a server, and call it a day. I was wrong. Running python app.py is easy. Making it production-ready is the hard part.</p><p>In a local setup, you tolerate slow generations, blocking requests, and terminal outputs. In production, you are suddenly fighting a multi-front war against latency, concurrency limits, brutal GPU scaling costs, monitoring blind spots, and strict security requirements.</p><p>This is Part 1 of a 3-part series detailing my journey of deploying LLMs. Before we talk about managed services or fine-tuning, we need to understand the absolute foundation: raw, self-hosted deployment. Here is exactly how I built a battle-tested, scalable API for Gemma 12B, the mistakes I made, and the architectural decisions that kept the system from collapsing.</p><h3>1. Introduction: The Reality of Production LLMs</h3><p>Deploying an LLM is not just about inference. It is fundamentally a massive systems engineering problem. The actual AI model is just the engine; the car you build around it determines if it can survive the highway. You have to account for:</p><ul><li><strong>Latency:</strong> Time-to-first-token (TTFT) and generation speed.</li><li><strong>Concurrency:</strong> Handling 100 simultaneous users without dropping requests.</li><li><strong>Scaling:</strong> Spinning up GPU nodes without bankrupting yourself.</li><li><strong>Security:</strong> Keeping raw model ports hidden from the public internet.</li></ul><h3>2. Local Development Phase</h3><p>Like everyone else, I started locally. I downloaded the Gemma 12B instruct weights and spun up a basic FastAPI application in Python. The initial architecture was dead simple: User → FastAPI → HuggingFace Model → Response.</p><p>I was testing system prompts, evaluating response quality, and running basic latency tests. It worked, but the cracks showed immediately. Inference was painfully slow. Generating a 500-token response took upwards of 15 seconds. RAM usage was erratic, and worst of all, the requests were blocking. If User A triggered an inference, User B had to wait in line until the GPU finished User A’s generation.</p><h3>3. Choosing Model Serving Engine</h3><p>I needed a dedicated serving engine. I evaluated the usual suspects (Transformers, Ollama, TGI) but ultimately chose <strong>vLLM</strong>.</p><p>The deciding engineering factor was its use of <strong>PagedAttention</strong> for KV cache optimization. When an LLM generates tokens, it stores the key-value tensors of past tokens in memory (the KV cache). In naive implementations, this memory is pre-allocated contiguously, leading to massive fragmentation and wasted VRAM. vLLM pages this memory exactly like an OS handles RAM, allowing for massive concurrency improvements. Combined with continuous batching, vLLM was the clear winner for throughput.</p><h3>4. Production Server Planning</h3><p>You can’t deploy a 12-billion parameter model on a t3.micro. I had to provision a serious AWS EC2 instance. I settled on:</p><ul><li><strong>OS:</strong> Ubuntu 22.04 LTS</li><li><strong>GPU:</strong> NVIDIA A100 (40GB VRAM)</li><li><strong>RAM:</strong> 64GB</li><li><strong>CPU:</strong> 16 vCPU</li><li><strong>Storage:</strong> 500GB NVMe SSD</li></ul><p><strong>Why these specs?</strong> Gemma 12B loaded in bfloat16 precision takes roughly 24GB of VRAM just to store the model weights. If I used a cheaper NVIDIA A10 (24GB VRAM), I would immediately hit an Out-Of-Memory (OOM) error because there would be zero VRAM left for the KV cache. The 40GB A100 gave me 24GB for the weights and ~16GB of breathing room for high-concurrency KV caching.</p><h3>5. How the Actual Model Reaches the Server</h3><p>The actual model is not the Python code. The model is the weights — massive binary files.</p><p>I authenticated via the HuggingFace CLI and used git-lfs to pull the weights. You aren&#39;t just downloading one file. You are pulling the config.json, the tokenizer.model, and multiple gigabytes of .safetensors files. I mapped these to a dedicated directory on the host machine: /models/gemma-12b/.</p><p><strong>Crucial architectural decision:</strong> The model weights should NEVER be baked inside your Docker image. If you COPY 24GB of weights into your Dockerfile, your image becomes bloated, pushing to AWS ECR takes hours, and ECS task startups will time out.</p><h3>6. Dockerization</h3><p>I containerized the FastAPI application to ensure dependency consistency. My Dockerfile was minimal, pulling a Python 3.10 slim image, copying my requirements.txt, and setting up environment configurations. I purposely kept vLLM out of this specific container. Dockerizing the API layer meant I could tear it down, update routing logic, and redeploy in seconds without touching the GPU runtime.</p><h3>7. FastAPI + vLLM Integration</h3><p>Instead of running vLLM inside the same Python process as FastAPI, I decoupled them.</p><ul><li><strong>FastAPI handles:</strong> JWT Auth, rate-limiting, prompt engineering, logging, and caching.</li><li><strong>vLLM handles:</strong> Pure, unadulterated GPU inference.</li></ul><p>This separation of concerns is vital. If someone spams the endpoint, I want the FastAPI layer to reject them with a 429 <em>before</em> that traffic ever touches the expensive GPU queue.</p><h3>8. Real-Time Streaming</h3><p>I configured vLLM to yield tokens as they were generated and used FastAPI’s StreamingResponse to pipe them back to the client via Server-Sent Events (SSE). Instead of waiting 8 seconds for a full response, the user saw the first token in ~400ms, with the rest of the text typing out naturally.</p><h3>9. GitHub Workflow &amp; 10. CI/CD</h3><p>Git became the absolute source of truth. I wrote a GitHub Actions YAML pipeline to automate deployments: Push to main → Run Pytest → Build Docker Image → Push to ECR → Force ECS Deployment.</p><p>I included a rollback strategy by tagging every Docker image with its Git commit SHA. If a deployment introduced a memory leak, I could revert to the previous SHA tag in ECS instantly.</p><h3>11. AWS ECR &amp; 12. ECS Deployment</h3><p>AWS ECR was used to store the compiled API Docker images. Because the Docker image only contained FastAPI routing logic, it was under 300MB.</p><p>I deployed the containers using AWS ECS. In the ECS Task Definition, I mapped the EC2 host directory /models/gemma-12b to the vLLM container&#39;s internal path /app/model. This allowed the container to spin up in seconds and instantly access the pre-downloaded weights on the local SSD.</p><h3>13. Route53 Setup &amp; 14. Load Balancer (ALB)</h3><p>I registered api.myllm.com and configured AWS Route53 to point to my Application Load Balancer (ALB) with an ACM SSL certificate. The ALB pinged the FastAPI /health endpoint every 10 seconds. If a container crashed, the ALB automatically stopped routing traffic to it and spun up a replacement.</p><h3>15. Firewall and Security (VPC)</h3><p>Security is non-negotiable. I leveraged AWS VPC architecture.</p><ul><li>The <strong>ALB</strong> lived in a <strong>public subnet</strong> (Ports 443/80 open).</li><li>The <strong>ECS Tasks</strong> (FastAPI and vLLM) lived in an <strong>isolated private subnet</strong>.</li><li>The internal API ports were completely hidden. The only entity allowed to talk to the FastAPI container was the ALB. The only entity allowed to talk to vLLM was FastAPI.</li></ul><h3>16. Redis Cache Layer</h3><p>I introduced a Redis cache layer using a standard Cache-Aside architecture. A cache miss required a full GPU generation taking ~4 seconds. A cache hit returned the exact same payload in <strong>70ms</strong>.</p><h3>17. Auto Scaling</h3><p>I configured independent auto-scaling policies. The FastAPI container scaled based on standard CPU utilization. However, I scaled vLLM GPU nodes based on a custom CloudWatch metric: the length of the inference queue. If the queue backed up beyond 50 pending requests, ECS would trigger a new GPU instance.</p><h3>18. Monitoring</h3><p>I piped everything into AWS CloudWatch, aggressively monitoring Latency (TTFT), GPU VRAM Utilization, Request Counts, and 500-level errors.</p><h3>19. Production Challenges</h3><p>Here is what actually broke:</p><ul><li><strong>Cold Starts:</strong> Loading 24GB of weights took 45s. <em>Solution:</em> Implemented aggressive health-check grace periods in ECS.</li><li><strong>GPU Memory Crashes (OOM):</strong> The KV cache exceeded limits under high load. <em>Solution:</em> Tuned vLLM’s gpu_memory_utilization to 0.85 to reject requests rather than crash.</li><li><strong>Load Balancer Timeout:</strong> Deep reasoning prompts hit the default 60s ALB idle timeout. <em>Solution:</em> Increased ALB idle timeout to 300 seconds.</li></ul><h3>20. End-to-End Architecture Diagrams</h3><p>Below are the Mermaid diagrams detailing the deployment, internal VPC isolation, and request flows.</p><p><strong>Diagram 1: Comprehensive Cloud &amp; Internal VPC Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bJq2aB3eoMtdwF84DJliA.png" /><figcaption>Graph-1</figcaption></figure><p><strong>Diagram 2: CI/CD Deployment Pipeline</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDjdf-tIvsyPOVhple0nrQ.png" /><figcaption>Graph-2</figcaption></figure><p><strong>Diagram 3: Dynamic Scaling Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNqAHKCW4edywpwHxiEHQg.png" /><figcaption>Graph-3</figcaption></figure><h3>21. Final Learnings</h3><p>Deploying Gemma 12B successfully meant spending 10% of my time on the model and 90% on infrastructure, networking, caching, and VPC routing. Self-hosting gives you absolute control, but the operational burden is entirely on your shoulders.</p><p>In <strong>Part 2</strong> of this series, I will tear down this self-hosted architecture and rebuild it using <strong>AWS Bedrock</strong>, exploring the trade-offs of managed LLM deployments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6261e300f844" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a HIPAA-Compliant Voice Analytics RAG Pipeline (And Rebuilt It After a Security Audit)]]></title>
            <link>https://isharadbharadwaj.medium.com/how-i-built-a-hipaa-compliant-voice-analytics-rag-pipeline-and-rebuilt-it-after-a-security-audit-ce2be6aa2fb2?source=rss-0d287bf2a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce2be6aa2fb2</guid>
            <category><![CDATA[hipaa-compliance]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[ai-production]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[voice-analytics]]></category>
            <dc:creator><![CDATA[Sharad Bharadwaj]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 18:19:33 GMT</pubDate>
            <atom:updated>2026-06-21T18:19:33.792Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lessons from building a production healthcare AI platform using Azure Speech, Deepgram, Qdrant, OpenAI, and Gemini</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTT0P1rlDVeXPqbbiE5zEw.png" /><figcaption>Image by author</figcaption></figure><p>We had a working pipeline. Clean transcripts. Sentiment scores our clients loved. A slick RAG-powered chatbot that let enterprise healthcare executives query patient feedback using natural language. We were ready to pop the champagne.</p><p>Then the security and legal review happened.</p><p>In a single afternoon, a room full of corporate compliance officers and external security auditors dismantled our entire architecture. We had built a highly performant AI system, but we had built it on assumptions that did not hold up under the brutal reality of HIPAA compliance. Everything about how we handled user sessions, cached data, and passed identifiers had to change. We rebuilt the core user security layer in two weeks, We shipped the rewrite in two weeks. It was not fun.</p><p>If you are building a production AI system in healthcare, you cannot just write code that works. You have to write code that survives the audit. This is the story of how we built a production-grade voice analytics RAG pipeline, the architectural scars we earned along the way, and what it actually takes to ship an enterprise LLM system under strict regulatory constraints.</p><h3>THE REAL SYSTEM — SCALE &amp; CONTEXT</h3><p>Our enterprise healthcare clients faced a massive blind spot: patient post-discharge experiences. They collected thousands of surveys, but text boxes are where rich context goes to die. Patients rarely type out their complex stories; they prefer to talk.</p><p>We were tasked with building a centralized voice analytics platform. Patients provided verbal responses to surveys, and our system ingested that audio, transcribed it, analyzed the emotional and clinical sentiment at scale, and exposed the insights through an interactive RAG dashboard. Healthcare executives needed to query this data in plain English: <em>“What topics made users frustrated in the Midwest clinics last month?”</em> or <em>“Summarize negative feedback regarding billing transparency.”</em></p><p>Let’s talk scale, because tutorials love to look at toy datasets of 50 short audio clips. We were processing thousands of audio responses per month. Average length sat around 45 seconds per response, translating to roughly thousands of raw audio ingestion every month. A single high-volume healthcare survey campaign could easily dump 100k+ records into our system in a two-week window. Existing off-the-shelf SaaS analytics platforms couldn’t handle this. They either lacked the specific healthcare-tuned transcription accuracy needed for clinical terminology, or they flat-out refused to sign a Business Associate Agreement (BAA) to guarantee HIPAA compliance. We had to build a custom pipeline that could process highly sensitive Protected Health Information (PHI) while maintaining absolute data isolation.</p><h3>THE ARCHITECTURE — How It Actually Worked</h3><p>Nobody tells you that voice data is fundamentally different from structured application logs or text documents. It is messy, unpredictable, and heavy.</p><p>Here is the blueprint of the architecture we deployed to production:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bacZbyWikv2G3dRH2XFT0Q.png" /><figcaption>Image-1</figcaption></figure><h3>The Data Ingestion Flow</h3><p>Our data ingestion started at the survey layer. We used a third-party survey tool to host the patient interaction. We did not build the survey UI or manage the front-end notification system; we fetched the survey schema, questions, and responses via API calls. We had zero control over how users answered or when they decided to hang up.</p><p>Once the data hit our sync server, our control began. For live, real-time feedback visualization, we piped streaming audio from active survey sessions into <strong>Azure Speech Services</strong>. Azure converted live audio to live text as the user spoke, giving us immediate, low-latency text previews.</p><p>But live transcription compromises accuracy for speed. For our permanent records, the raw audio files were pushed directly into <strong>GCP Storage Buckets</strong>, wrapped tightly in <strong>GCP KMS (Key Management Service)</strong> encryption keys and guarded by <strong>Google Secret Manager</strong> for credentials management.</p><p>From there, we pulled the raw audio and processed it through <strong>Deepgram</strong> for asynchronous post-processing transcription. What surprised us about Deepgram was its incredible word error rate (WER) on medical jargon and accents compared to Azure’s live stream. It gave us the pristine text transcripts required for high-fidelity NLP analysis.</p><p>Once clean text was generated, it passed through our custom <strong>NLP &amp; Sentiment Analysis</strong> pipeline to classify emotions (Happy, Angry, Neutral) and calculate confidence scores. Finally, the processed text was broken into optimized fragments, converted into embeddings, and stored in a vector database to power our RAG chatbot.</p><h3>WHY THESE TOOLS? COST OPTIMIZATION AND INFRASTRUCTURE DECISIONS</h3><p>When you operate an enterprise system processing terabytes of data, every tooling choice has massive cost implications. We made deliberate, battle-tested decisions here that saved us tens of thousands of dollars monthly.</p><h3>Why Qdrant Instead of Pinecone?</h3><p>The first mistake many startups make is defaulting to a fully managed vector database like Pinecone without calculating the enterprise regulatory tax. Under HIPAA, you need a signed BAA. When we built this, Pinecone’s serverless or multi-tenant tiers made getting an enterprise BAA prohibitively expensive or complex regarding explicit data isolation guarantees for our specific scale.</p><p>Qdrant offered a robust, production-tested open-source core that we could self-host inside our own Virtual Private Cloud (VPC) on Google Kubernetes Engine (GKE) under our existing cloud provider BAA.</p><p>More importantly, Qdrant’s payload filtering capabilities are incredibly fast for multi-tenant segmentations. Because our clients needed strict data boundaries, every query had to filter by client_id or survey_id before calculating cosine similarity. Qdrant performs this filtering directly in the vector payload during the HNSW graph traversal. Doing this in Pinecone with dedicated pods would have forced us to spin up isolated clusters per tenant, skyrocketing our infrastructure costs. Self-hosting Qdrant saved us roughly thousands of a month in database licensing and cross-network data transfer fees.</p><h3>Why GCP Storage and Azure Speech Together?</h3><p>This cross-cloud setup looks like an over-engineered nightmare on paper, but it was driven by enterprise constraints and cloud egress economics.</p><p>Our main healthcare client’s existing infrastructure was deeply rooted in Azure for active directory and corporate networks, making Azure Speech Services an easy sell for low-latency streaming endpoints that wouldn’t freak out their infosec team. However, our main application cluster, ML data processing engine, and analytical stack were natively hosted on GCP.</p><p>If we streamed all live audio across clouds in real-time, network egress costs would have killed our margins. Our solution was to ingest the streaming live preview text on Azure, but instantly route the heavy raw binary audio files directly to a secure GCP Cloud Storage bucket via a dedicated VPN tunnel. This kept our heavy post-processing storage centralized right next to our compute engines, stripping away ongoing cross-cloud data transfer fees.</p><h3>THE EMPTY AUDIO PROBLEM</h3><p>Here is a production problem no tutorial prepares you for: the sound of absolute silence.</p><p>The first mistake we made was assuming that every completed survey record contained usable audio. In reality, about 5% of our enterprise users would hit the record button, submit the survey, and say absolutely nothing. Sometimes it was dead air; other times it was ambient room noise, a television humming in the background, or a phone clicking shut.</p><p>When these silent audio files hit Deepgram, the API did exactly what it was supposed to do: it returned an empty string.</p><p>Early on, our pipeline choked on these empty strings. An empty string passed to our embedding model threw a dimension error or generated a generic vector that corrupted our nearest-neighbor searches in Qdrant. Even worse, it skewed our aggregate sentiment analysis, dragging down confidence scores across the board.</p><p>Because we were leveraging a third-party survey tool, we had no webhooks or UI mechanisms to alert the patient in real-time (<em>“We didn’t catch that, please speak up”</em>). We had to handle this purely as a backend data quality decision.</p><p>We implemented an empty audio flag layer. If Deepgram returned zero words, or if the audio energy levels fell below a specific decibel threshold over the track duration, the record was silently flagged in our database and skipped. They were explicitly blocked from entering the RAG pipeline and excluded from sentiment metrics. We accepted this loss of data because pushing dead air into an LLM context window is a guaranteed way to hallucinate garbage analytics.</p><h3>AZURE VS DEEPGRAM — WHY BOTH?</h3><p>Engineers often ask why we doubled our transcription footprint by using both Azure Speech Services and Deepgram. It comes down to the trade-off between latency and accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7-WqLxZS0HUcbFxjscMgg.png" /><figcaption>Image-2</figcaption></figure><p>Azure was our sprint runner. During an active survey session, we needed sub-second transcription to drive UI elements and real-time status indicators. Azure handled streaming audio effortlessly. However, its real-time model frequently tripped over multi-syllable pharmaceutical names or rapid speech patterns common in anxious patients.</p><p>Deepgram was our marathon runner. For batch post-processing, we didn’t care if the transcription took three seconds instead of 200 milliseconds. Deepgram’s deep learning architecture allowed us to deploy custom vocabulary overrides for healthcare terminology. It caught nuances, word boundaries, and medical abbreviations that Azure missed entirely.</p><p>By utilizing Azure on the front end and Deepgram on the back end, we optimized for both the immediate user experience and the downstream analytical precision required by our RAG database.</p><h3>THE RAG PIPELINE — WHERE IT GETS INTERESTING</h3><p>Building a RAG pipeline for voice transcripts is fundamentally different from building one for text documents or PDFs. PDFs have structural markers: paragraphs, headers, and tables. Voice transcripts are chaotic. Humans speak in fragmented sentences, use endless filler words (“umm”, “uh”, “like”), pause mid-thought, and abruptly shift topics without punctuation.</p><p>The first chunking mistake we made was using a standard token-based recursive character splitter. It sliced sentences right down the middle, separating a patient’s complaint from the context of <em>why</em> they were complaining. For example, a chunk boundary would separate <em>“The doctor was great but…”</em> from <em>“…the billing staff treated me like garbage.”</em> The retrieval layer would pull the first chunk for a “positive feedback” query, completely missing the severe negative sentiment that followed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyu6Hpgq_7ejrL_MRYgOcg.png" /><figcaption>Image-3</figcaption></figure><p>We threw out character-based splitting and shifted to <strong>semantic chunking based on speaker pauses and topic boundaries</strong>. We analyzed time-gaps in the audio metadata to determine where a thought naturally ended, ensuring that qualifiers and their subjects remained tied together in the vector space.</p><p>For our LLM generation layer, we found that a dual-model strategy yielded the best results:</p><ul><li><strong>OpenAI (GPT-4o)</strong> handled highly structured, logic-heavy queries brilliantly. If a user asked, <em>“Summarise negative feedback from last month into three distinct operational buckets,”</em> OpenAI was our go-to.</li><li><strong>Gemini (Flash &amp; Pro)</strong> was significantly better at processing massive context windows and parsing the highly conversational, rambling nature of raw voice transcripts. Gemini excelled at identifying subtle emotional undercurrents across hundreds of pages of raw patient text without getting tripped up by messy grammar.</li></ul><h3>HIPAA — THE SECURITY REWRITE</h3><p>Let’s look at the compliance layer that forced us to rewrite our user security model from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zL9nzpERf6HIotjUxPt8iw.png" /><figcaption>Image-4</figcaption></figure><p>Under HIPAA, voice data is classified as a biometric identifier. If a patient states their name, date of birth, or medical condition on tape, that audio file is instantly classified as Protected Health Information (PHI).</p><p>Our initial architecture assumed that because our application database was encrypted at rest and sat within a virtual private cloud, we were secure. Our security review proved us wrong. The auditors noted that our retrieval logs, application caches, and metadata tables were tracking user sessions in a way that could tie an individual patient identity back to an explicit sentiment score or vector chunk.</p><p>Legal review changed everything overnight. We had to implement a strict <strong>data-masking engine</strong> at our ingestion gateway. Before any text chunk hit our Qdrant vector database, it passed through a deterministic Named Entity Recognition (NER) pipeline specifically tuned to redact names, phone numbers, locations, and dates.</p><p>For the raw audio assets stored in GCP, we implemented envelope encryption via GCP KMS. Every single audio file received its own unique data encryption key (DEK), which was then encrypted by a master key encryption key (KEK) managed inside KMS. Accessing an audio file required real-time cryptographic authorization; no developer, system administrator, or database process could simply browse the storage bucket and listen to a patient’s recording.</p><h3>NLP + SENTIMENT — THE ANALYSIS LAYER</h3><p>Once our transcripts were clean and secure, they entered our NLP classification engine. We mapped responses into discrete emotional buckets: Happy, Neutral, Frustrated, and Angry, alongside a continuous confidence score from 0.0 to 1.0.</p><p>What we quickly realized is that <strong>voice sentiment does not equal text sentiment</strong>. A patient might say, <em>“Oh, your billing process is just fantastic,”</em> using a tone dripping with sarcasm. On a pure text basis, a standard NLP classifier flags that as highly positive.</p><p>To prevent this data corruption, we injected acoustic metadata flags directly into the text streams sent to our LLM evaluation layer. If Deepgram’s audio analysis indicated high pitch variance, elevated speech volume, or long hesitations, we appended metadata markers like [Tone: High Agitation] or [Long Pause] directly into the text block. This gave the LLM the contextual clues it needed to correctly categorize sarcastic or highly distressed responses that simple text modeling would have misread.</p><h3>THREE PRODUCTION FAILURES</h3><p>You don’t build a platform like this without breaking things at scale. These are three specific failures that cost us significant time and sleep.</p><h3>Failure 1: The Security Rewrite</h3><p>Our initial user access layer allowed broad internal service communication across our microservices. Our security audit found that if an attacker compromised our analytics dashboard service, they could laterally traverse our cluster to access the unredacted metadata tables linking patients to their audio IDs. Fixing this required a complete shutdown of the pipeline for 72 hours while we implemented strict zero-trust network policies, row-level database security, and isolated IAM roles using Google Secret Manager to manage dynamic, short-lived tokens.</p><h3>Failure 2: Empty Audio at Scale</h3><p>During our first major enterprise onboarding, a client rolled out a survey format that caused a massive spike in user confusion. Nearly 5% of patients submitted surveys without realizing they hadn’t granted microphone permissions. Because our early pipeline didn’t catch these silent tracks cleanly, it generated hundreds of identical zero-vector strings. This clogged our Qdrant vector spaces, resulting in severe search degradation and dragging down the average sentiment metrics for that client into an artificial neutral dead-zone. We had to build our backend empty-audio filtering layer overnight to purge the corrupted vectors.</p><h3>Failure 3: Voice Chunking Disaster</h3><p>Early on, we used a standard document splitter set to 500-character increments. When users queried the RAG chatbot about why patients were angry, the system returned completely incoherent summaries. The arbitrary character cuts were slicing right through critical context, isolating the patient’s actual grievance from their explanation. The chatbot kept repeating generic phrases because the underlying vector retrieval was pulling fragmented, low-signal phrases. We had to re-index our entire Qdrant database using semantic pause-based chunking to restore accurate contextual retrieval.</p><h3>FIVE LESSONS LEARNED</h3><ol><li><strong>Voice data requires semantic chunking, not token chunking.</strong> Never split conversational audio transcripts using rigid character or token counts. Group your data by semantic transitions and natural speech pauses, or your RAG retrieval will lose the core context.</li><li><strong>Acoustic metadata is non-negotiable for text sentiment.</strong> Raw text ignores tone, sarcasm, and distress. If you don’t inject audio indicators (like volume spikes or prolonged silences) into your text chunks, your sentiment analysis engine will misclassify complex human emotional responses.</li><li><strong>Handle empty audio at the ingestion gateway.</strong> Expect 3% to 7% of your voice data to be complete silence or unusable background noise. Filter these out via explicit validation flags before they ever touch your embeddings pipeline or metrics storage.</li><li><strong>Compliance must be baked into the data contract from day one.</strong> Do not treat HIPAA as a security checklist to handle right before launch. If you don’t design your vector databases, LLM logging layers, and storage systems around data isolation and PHI redaction from the start, your compliance review will break your architecture.</li><li><strong>Balance your LLMs based on production strengths.</strong> Do not rely on a single model. Use structured, logic-focused models like OpenAI for complex, metric-driven queries, and large context models like Gemini to digest verbose, messy, or conversational human transcripts.</li></ol><h3>CONCLUSION — PERSPECTIVE SHIFT</h3><p>Building this platform forced our engineering team to completely reframe how we view regulatory constraints.</p><p>When we started, we viewed HIPAA compliance as an administrative hurdle — a collection of annoying roadblocks designed to slow down our development velocity. But by the time we pushed the final, audited security layer into production, our perspective had shifted completely.</p><p>HIPAA forced us to build a far more resilient, deterministic, and high-quality system than we ever would have built without it. It pushed us to implement absolute data cleanliness, robust error handling for edge cases like silent audio, and a zero-trust architecture that guarantees data integrity. In the production AI ecosystem, compliance isn’t a constraint. It’s a quality bar most teams never hit voluntarily.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce2be6aa2fb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI Series : RAG in Production: What the Tutorials Never Tell You]]></title>
            <link>https://isharadbharadwaj.medium.com/the-ai-series-rag-in-production-what-the-tutorials-never-tell-you-045036fcd2fc?source=rss-0d287bf2a4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/045036fcd2fc</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Sharad Bharadwaj]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 04:32:21 GMT</pubDate>
            <atom:updated>2026-06-08T04:32:21.997Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Most RAG articles will show you how to build a pipeline. This one shows you where it quietly breaks — and why nobody talks about that part.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fx52vbi-TAgDPn2cvXvv3Q.png" /><figcaption>Image by author</figcaption></figure><p>I’ve shipped RAG systems for healthcare clients, enterprise HR platforms, and customer support tools. And across every single one, the pattern is identical: the demo works, the stakeholders clap, and then the moment real data hits the pipeline, something breaks in a way that wasn’t in any tutorial.</p><p>Not because the tutorials are wrong. Because they’re not honest.</p><p>They show you the 50 clean PDFs. They don’t show you the 50,000 inconsistent ones. They show you cosine similarity scores that make sense. They don’t show you the moment a user asks a perfectly reasonable question and gets an answer that was confidently, completely fabricated.</p><p>This is the article I wish existed when I started. No fluff. No Jupyter notebook screenshots. Just the real mechanics, the real failure points, and what I actually do about them.</p><h3>First: What RAG Actually Is (Without the Academic Wrapper)</h3><p>Retrieval Augmented Generation sounds complex because it’s usually explained by people who want it to sound complex.</p><p>Here’s what it is: your LLM knows nothing about your company. It was trained on the internet, not your data. So instead of retraining it (expensive, slow, fragile), you teach it to look things up first.</p><p>User asks a question → your system finds the relevant documents → you hand those documents to the LLM along with the question → the LLM answers using what you gave it, not what it vaguely remembers from training.</p><p>That’s it. The complexity is in the “finds the relevant documents” part. And that’s where every production system I’ve built has bled.</p><h3>The Pipeline Everyone Builds (And Where It Actually Falls Apart)</h3><p>Every RAG pipeline has the same skeleton. Here’s what it looks like — including the failure points nobody draws:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rom29BHdG_Y70onJFc78Cg.png" /><figcaption>Graph — 1</figcaption></figure><p>What no one draws on that diagram are the silent failure arrows. The places where data goes in clean and comes out wrong — and the LLM still answers with full confidence.</p><p>Let me walk through each failure point.</p><h3>Chunking: The Step That Silently Destroys Everything Downstream</h3><p>I’ll be direct: chunking is where most RAG systems fail. Not retrieval. Not the LLM. Chunking.</p><p>The default advice is: split every 512 tokens, 50-token overlap. That advice was written for clean, consistent text. Real enterprise data is not clean or consistent.</p><p>Here’s what I’ve actually seen break:</p><p><strong>Financial reports.</strong> A critical number split across a chunk boundary. The LLM retrieves the second chunk — the one with the dollar figure — but has no idea which company or which quarter it belongs to. It fills in the gap from its training data. It’s wrong. It doesn’t say it’s wrong.</p><p><strong>Legal contracts.</strong> We once set chunk size to 2,000 tokens to preserve context. The embedding of that chunk averaged out 4 pages of dense text. The specific clause a user was asking about was completely diluted in the vector. Retrieval accuracy dropped 40%.</p><p><strong>Voice transcripts.</strong> Automated transcription models don’t use periods correctly. Splitting on punctuation produced chunks that ended mid-sentence. Regularly. We had to anchor chunks to timestamps instead.</p><p>Here’s how the three chunking strategies actually compare:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*aTCioTDTfLTAfOdF15j1HA.png" /><figcaption>Graph — 2</figcaption></figure><p>What I actually use now:</p><ul><li><strong>Semantic chunking</strong> as the default — split on logical boundaries (paragraphs, headers, speaker turns), not token counts</li><li><strong>Parent-child architecture</strong> for long documents — embed small 200-token child chunks for accurate search, but pass the full parent document to the LLM for context</li><li><strong>Structure-aware chunking</strong> for JSON, tables, and markdown — these formats have inherent boundaries; use them</li></ul><p>The rule I live by: <strong>the chunk you embed for search and the chunk you pass to the LLM should not be the same chunk.</strong> Decouple those two concerns.</p><h3>Retrieval: When “Similar” Doesn’t Mean “Relevant”</h3><p>Vector search is seductive because the math feels clean. Cosine similarity. Nearest neighbours. It sounds like it should work.</p><p>It doesn’t always work.</p><p>The problem is that semantic similarity and informational relevance are different things. A user searching for “how to reset my router” will get back a chunk that says “I can’t figure out how to reset my router, so frustrating.” Semantically near-identical vectors. Completely useless result.</p><p>Worse: try searching for a serial number, an error code, or a product SKU. Embedding models compress these into similar vectors because the model was trained on prose, not IDs. “Error 404” and “Error 500” live embarrassingly close together in vector space.</p><p>This is why naive vector search is not enough. Here’s what production retrieval actually looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*M3TC2oLjypNWWL4k8PIT4g.png" /><figcaption>Graph — 3</figcaption></figure><p>Three things I now treat as non-negotiable:</p><p><strong>1. Hybrid search.</strong> Run dense vector search alongside sparse keyword search (BM25). The vector finds conceptual matches; BM25 finds exact token matches. Combine the scores. The latency hit is real but the accuracy gain is bigger.</p><p><strong>2. Metadata filtering before the search.</strong> If the user is asking about France’s PTO policy and your vector store has both France and USA policy documents, those documents are nearly identical in semantic space — “vacation,” “PTO,” “policy” appear in both. Filter by country first. Hard filters before similarity search, always.</p><p><strong>3. A cross-encoder reranker.</strong> After retrieval, run a reranker that scores the query and each retrieved chunk together — not independently. Bi-encoders encode separately and compare later. Cross-encoders encode jointly and give you a real relevance score. Slower, but it fixes the “retrieved the adjacent thing, not the answer” problem.</p><h3>Generation: The Last-Mile Problems Nobody Writes About</h3><p>You’ve done everything right. Good chunks. Hybrid search. Reranker. The context that lands in the prompt is the correct context.</p><p>The LLM still hallucinates. Why?</p><p><strong>Context position matters more than context volume.</strong> LLMs pay disproportionate attention to the beginning and end of their prompt. If your most relevant chunk is chunk #8 out of 15, the model may deprioritise it and fall back on its training weights. The fix: put the highest-ranked chunks first, not in order of document date or chunk ID.</p><p><strong>Prompts need hard constraints, not suggestions.</strong> “Use the provided context to answer” doesn’t work. “Answer ONLY using the provided context. If the answer is not present in the context, respond with: I don’t have enough information in my knowledge base to answer this accurately” — that works. The difference matters at 3x the query volume with 3x the edge cases.</p><p><strong>Force citations.</strong> Make the LLM cite the source document for every claim. Not because users will check them. Because the act of citation forces the model to ground its reasoning before it generates. It’s a structural constraint that reduces hallucination. Temperature 0.0 or 0.1. Combine that with citation requirements and your hallucination rate drops measurably.</p><h3>The Four Real Production Failures (And What We Did)</h3><h3>Failure 1: Chunk size too large</h3><p>We set chunks to 2,000 tokens for a legal document pipeline. Thought more context meant better answers.</p><p>Retrieval accuracy collapsed. A single clause we needed was semantically buried in 4 pages of noise.</p><p><strong>Fix:</strong> Parent-child retrieval. 200-token children for search, 2,000-token parents passed to the LLM. Search precision came back. Context for generation stayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*0xOkqD2YWH49MlNJSEdchw.png" /><figcaption>Graph — 4</figcaption></figure><h3>Failure 2: Wrong embedding model</h3><p>Healthcare client. Specialised medical research data. We used a standard cloud embedding model.</p><p>It couldn’t distinguish between specific chemical compounds. It treated different medications as semantic neighbours because its training treated them all as “drugs.”</p><p><strong>Fix:</strong> Domain-specific embedding model fine-tuned on PubMed. The vector space separated the compounds correctly. This is not a niche problem — any domain with specialised vocabulary will hit this.</p><h3>Failure 3: Vector search ignoring geography</h3><p>User asked: “What is the paid time off policy in France?”</p><p>System returned: the USA PTO policy.</p><p>Both documents are saturated with “PTO,” “vacation,” “policy,” “days,” “entitlement.” Cosine similarity couldn’t tell them apart.</p><p><strong>Fix:</strong> Metadata extraction at ingestion. Every document tagged with country, department, document_type. Pre-filter on metadata before any vector math runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj4t-TlVUF3DYYWBpoilvw.png" /><figcaption>Graph — 5</figcaption></figure><h3>Failure 4: GDPR + vectors</h3><p>We ingested raw HR performance reviews. A few months later, an employee submitted a GDPR right-to-be-forgotten request.</p><p>We had no way to delete their data. It was baked into vectors. Spread across embeddings with no mapping back to source documents or individuals.</p><p><strong>Fix:</strong> Rebuild from scratch, properly. PII scrubbing before vectorisation. Every vector tagged with doc_id and user_id. Now deletion is DELETE WHERE doc_id = X — fast, clean, auditable.</p><p>If you are building any RAG system that will touch personal data, <strong>design the deletion path before you write the ingestion pipeline.</strong> Not after.</p><h3>What Enterprise RAG Actually Looks Like</h3><p>When this moves to production at scale, the pipeline gets defensive layers that most tutorials never show:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxBgREoDB4ICaqwR9OnNog.png" /><figcaption>Graph — 6</figcaption></figure><p>Row-level security on the vector store is not optional. If a user doesn’t have permission to read the source document, they shouldn’t be able to query its vectors. The vector store is not a neutral abstraction — it carries the access control obligations of the data it indexed.</p><p>Audit logging needs to capture the retrieved chunks and the exact prompt, not just the final answer. When something goes wrong — and it will — you need to know whether it was a retrieval failure or a generation failure. They have completely different fixes.</p><h3>When RAG Will Fail You (Know This Before You Build)</h3><p>This is the section that doesn’t exist in most articles. Here it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKG1mauXyQwVCm7D0QxNyQ.png" /><figcaption>Graph — 7</figcaption></figure><h3>The Honest Summary</h3><p>RAG is not magic. It’s a pipeline with a lot of places to fail, most of which are invisible until real data hits them.</p><p>The teams I’ve seen succeed treat data engineering as a first-class concern — not an afterthought. They obsess over chunk quality before they touch embedding models. They build evaluation before they build features. They design deletion and access control into the schema on day one.</p><p>The teams that struggle treat RAG as “connect the database to the API.” That works in a demo. It breaks in production.</p><p>Your retrieval quality is bounded by your data quality. Your generation quality is bounded by your retrieval quality. There is no LLM that can compensate for a broken pipeline upstream.</p><p><strong>Fix the pipeline. The model will take care of itself.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=045036fcd2fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>