<?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 Shashank Shekhar pandey on Medium]]></title>
        <description><![CDATA[Stories by Shashank Shekhar pandey on Medium]]></description>
        <link>https://medium.com/@shashank_shekhar_pandey?source=rss-984826d45cb4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*J5LcIYMTuKzd4oE7IwKb5g.jpeg</url>
            <title>Stories by Shashank Shekhar pandey on Medium</title>
            <link>https://medium.com/@shashank_shekhar_pandey?source=rss-984826d45cb4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:35:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shashank_shekhar_pandey/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[Debugging LangGraph: How to Find Exactly Which Node Broke Your AI Agent]]></title>
            <link>https://medium.com/@shashank_shekhar_pandey/debugging-langgraph-how-to-find-exactly-which-node-broke-your-ai-agent-5a9698180b3d?source=rss-984826d45cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a9698180b3d</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Shashank Shekhar pandey]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 16:36:41 GMT</pubDate>
            <atom:updated>2026-10-04T16:36:41.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIvwt_7yaJ6E4ldwlygMDw.png" /></figure><p>A hands-on tutorial that breaks a LangGraph agent on purpose, then uses logging, streaming, checkpoints, LangSmith, and pytest to find the faulty node and keep it fixed.</p><h3>Table of contents</h3><ol><li>The demo that worked, and the workflow that didn’t</li><li>LangGraph in five minutes</li><li>The project: a customer-support graph with no API key</li><li>The bug</li><li>Watching it fail</li><li>Debugging node by node</li><li>A second kind of bug: conditional routing</li><li>LangSmith: seeing inside the graph</li><li>The fix</li><li>Regression tests</li><li>Checkpointing and production debugging</li><li>Conclusion</li></ol><h3>1. The demo that worked, and the workflow that didn’t</h3><p>The agent worked in the demo. You asked a simple question, the graph ran, and a sensible answer came back. Then it met a real workflow. Maybe the answer was confidently wrong. Maybe it ignored the documents it had just retrieved. Maybe it crashed with a bare KeyError three steps after the real mistake.</p><p>You look at the final output and have no idea which step caused it.</p><p>That is the core difficulty with multi-step agents. The final answer is the last link in a chain, and the bad link is usually somewhere earlier. In my experience, the failure shows up in one node and the cause sits in another.</p><p>So here is the central lesson of this article:</p><blockquote><strong><em>Debugging an AI agent means investigating four things: the execution path, the state each node received, the state each node returned, and the decisions that chose the next node.</em></strong></blockquote><p>In this tutorial you will:</p><ul><li>Build a small LangGraph customer-support workflow that needs no LLM or API key.</li><li>Introduce a realistic state-management bug and watch it fail.</li><li>Locate it with structured logging, graph.stream(), and checkpoint inspection.</li><li>See why LangGraph’s own error message points at the wrong place.</li><li>Fix the root cause, write pytest regression tests, and walk through LangSmith tracing, a troubleshooting table, and a checklist.</li></ul><p>The nodes here are deterministic Python so you can reproduce everything. The same techniques apply when a node calls an LLM, and I’ll point out where the differences matter.</p><h3>2. LangGraph in five minutes</h3><p><strong>LangGraph</strong> is a Python (and JavaScript) library for building stateful, multi-step applications, usually LLM agents, as graphs. You use it when a single prompt-and-response isn’t enough: you need steps, branches, loops, tool calls, or the ability to pause and resume.</p><p>Think of a customer-support department. One person reads the ticket and decides what it’s about. A second looks up the relevant policy. A third writes the reply. Each worker does one job and passes a folder of notes to the next. LangGraph is that department, in code.</p><p>Department LangGraph term What it is The whole workflow <strong>Graph</strong> (StateGraph) The set of steps and how they connect A worker <strong>Node</strong> A Python function that receives state and returns updates The hand-off <strong>Edge</strong> A fixed connection: &quot;after A, run B&quot; A manager&#39;s decision <strong>Conditional edge</strong> A function that looks at state and picks the next node The folder of notes <strong>State</strong> Shared data every node can read and update Where the process starts and finishes <strong>START</strong> / <strong>END</strong> Special markers for entry and exit</p><p><strong>State</strong> is defined by a schema. A TypedDict is the simplest way to declare which keys exist. A node receives the current state and returns a <em>partial update</em>, a dict containing only the keys it wants to change. LangGraph merges that update into the state. Nodes don&#39;t replace the whole state, and that detail matters a lot for debugging.</p><p>The main API calls:</p><ul><li>StateGraph(SupportState) creates a builder tied to your state schema.</li><li>add_node, add_edge, and add_conditional_edges describe the structure.</li><li>compile() validates the structure and returns a runnable graph.</li><li>invoke(input) runs the graph to completion and returns the final state.</li><li>stream(input, stream_mode=...) yields results as the graph runs, so you can watch each step.</li></ul><pre>flowchart LR<br>    S([START]) --&gt; C[classify_node]<br>    C --&gt; R[retrieve_node]<br>    R --&gt; P[respond_node]<br>    P --&gt; E([END])</pre><p><em>Figure 1. The basic customer-support graph. Each node reads shared state and returns a partial update.</em></p><p>With a conditional edge, the path depends on state. After classify_node, a router function might send known intents to retrieve_node and unknown ones to an escalate_node. Two runs of the same graph can then execute different nodes. When debugging, &quot;which path did this run take?&quot; is a real question.</p><h3>Three things that sound alike but aren’t</h3><p>People mix these up constantly:</p><ul><li><strong>Graph state</strong> is the data flowing through one run. It lives in memory while the graph executes.</li><li><strong>Checkpoint persistence</strong> means saving state snapshots (via a <em>checkpointer</em>) after steps, keyed by a thread_id, so a conversation can be resumed or inspected later.</li><li><strong>Trace history</strong> is a record of what happened, such as inputs, outputs, timing, and errors, sent to an observability tool like <strong>LangSmith</strong>. It’s for humans diagnosing behavior, not for the graph to read back.</li></ul><p>State is what the graph <em>uses</em>. Checkpoints are state <em>saved so it can continue</em>. Traces are a <em>record for debugging</em>. We’ll use all three.</p><h3>3. The project: a customer-support graph with no API key</h3><p>The workflow has three nodes:</p><ul><li>classify_node identifies the customer&#39;s intent from the question.</li><li>retrieve_node looks up information in a small in-memory knowledge base.</li><li>respond_node writes the answer using what was retrieved.</li></ul><p>The state schema:</p><p>Field Written by Meaning question caller The customer&#39;s message intent classify_node e.g. order_status, refund, unknown query classify_node The lookup key retrieve_node will use context retrieve_node Text pulled from the knowledge base answer respond_node The final reply error any node A structured problem marker, if any</p><p>The knowledge base holds two invented entries (illustrative data, no real customer information). The sample question throughout is:</p><blockquote><em>“My order has not arrived. Can you check its status?”</em></blockquote><p>Setup:</p><pre>python -m venv .venv<br>source .venv/bin/activate        # Windows: .venv\Scripts\activate<br>pip install langgraph pytest</pre><h3>4. The bug</h3><p>Here is the <strong>complete broken program</strong>. Save it as broken_agent.py.</p><pre># broken_agent.py<br>from typing import TypedDict<br>from langgraph.graph import StateGraph, START, END</pre><pre>KNOWLEDGE_BASE = {<br>    &quot;order_status&quot;: &quot;Order ORD-1042 shipped on 2 Oct and is in transit. Estimated delivery: 6 Oct.&quot;,<br>    &quot;refund&quot;: &quot;Refunds are issued to the original payment method within 5-7 business days.&quot;,<br>}</pre><pre>class SupportState(TypedDict, total=False):<br>    question: str<br>    intent: str<br>    query: str<br>    context: str<br>    answer: str<br>    error: str</pre><pre>def classify_node(state: SupportState) -&gt; dict:<br>    text = state[&quot;question&quot;].lower()<br>    if &quot;order&quot; in text or &quot;arrived&quot; in text:<br>        intent = &quot;order_status&quot;<br>    elif &quot;refund&quot; in text:<br>        intent = &quot;refund&quot;<br>    else:<br>        intent = &quot;unknown&quot;<br>    # BUG: writes &quot;search_query&quot; but the schema (and retrieve_node) use &quot;query&quot;<br>    return {&quot;intent&quot;: intent, &quot;search_query&quot;: intent}</pre><pre>def retrieve_node(state: SupportState) -&gt; dict:<br>    key = state[&quot;query&quot;]          # KeyError: &#39;query&#39;<br>    return {&quot;context&quot;: KNOWLEDGE_BASE.get(key, &quot;&quot;)}</pre><pre>def respond_node(state: SupportState) -&gt; dict:<br>    return {&quot;answer&quot;: f&quot;Here&#39;s what I found: {state[&#39;context&#39;]}&quot;}</pre><pre>builder = StateGraph(SupportState)<br>builder.add_node(&quot;classify_node&quot;, classify_node)<br>builder.add_node(&quot;retrieve_node&quot;, retrieve_node)<br>builder.add_node(&quot;respond_node&quot;, respond_node)<br>builder.add_edge(START, &quot;classify_node&quot;)<br>builder.add_edge(&quot;classify_node&quot;, &quot;retrieve_node&quot;)<br>builder.add_edge(&quot;retrieve_node&quot;, &quot;respond_node&quot;)<br>builder.add_edge(&quot;respond_node&quot;, END)<br>graph = builder.compile()</pre><pre>if __name__ == &quot;__main__&quot;:<br>    result = graph.invoke({&quot;question&quot;: &quot;My order has not arrived. Can you check its status?&quot;})<br>    print(result[&quot;answer&quot;])</pre><p>Read it as a reviewer. Does anything look wrong?</p><p>classify_node returns {&quot;intent&quot;: ..., &quot;search_query&quot;: ...}. But the schema declares the key query, and retrieve_node reads state[&quot;query&quot;]. One node writes a key named search_query; the next node expects query. Easy to miss when the two functions are 20 lines apart. In a real project they&#39;d be in different files, written weeks apart.</p><p>Note what kind of bug this is. A key that is <strong>missing</strong> from state is different from a key that <strong>exists but holds </strong><strong>&quot;&quot; or </strong><strong>None</strong>. Here query is never present at all, so state[&quot;query&quot;] raises KeyError. An empty string would have produced a wrong answer instead of an exception.</p><p><strong>Why it’s hard to spot from the final output:</strong> you only see a KeyError: &#39;query&#39; raised from retrieve_node. That tells you who <em>read</em> the missing key. It says nothing about who was supposed to <em>write</em> it, or why the write didn&#39;t land. The failing node and the faulty node are different nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8MYMEYifKO-0LUhLWTEGQ.png" /></figure><h3>5. Watching it fail</h3><p>Run it:</p><pre>python broken_agent.py</pre><p><strong>Captured output</strong> (trimmed to the last frames; the middle frames are LangGraph internals and will differ across versions):</p><pre>File &quot;.../broken_agent.py&quot;, line 29, in retrieve_node<br>    key = state[&quot;query&quot;]          # KeyError: &#39;query&#39;<br>          ~~~~~^^^^^^^^^<br>KeyError: &#39;query&#39;<br>During task with name &#39;retrieve_node&#39; and id &#39;f55acae8-...&#39;</pre><p>How to read it:</p><ul><li><strong>Which node was executing?</strong> retrieve_node. The line During task with name &#39;retrieve_node&#39; was added by LangGraph in my run. Don&#39;t assume every version or every failure type prints it.</li><li><strong>Which key caused it?</strong> &#39;query&#39;, looked up with state[&quot;query&quot;].</li><li><strong>Why did execution stop?</strong> An unhandled exception inside a node aborts the run. Nothing after retrieve_node executes.</li><li><strong>Why doesn’t it reveal the origin?</strong> The traceback shows the <em>reader</em>. The <em>writer</em>, classify_node, finished successfully and left no trace of its mistake.</li></ul><p>The expected failure message is one thing; the next section shows the clues that actually lead to the cause.</p><h3>6. Debugging node by node</h3><p>Don’t stare at code. Instead, make the execution observable.</p><h3>A. Structured logging</h3><p>Wrap each node so it logs its name, the state keys it received, the keys it returned, and any exception. A decorator does this without touching node logic. Save as logged_broken.py:</p><pre># logged_broken.py<br>import functools, logging<br>from langgraph.graph import StateGraph, START, END<br>import broken_agent as b</pre><pre>logging.basicConfig(level=logging.INFO, format=&quot;%(levelname)s %(name)s | %(message)s&quot;)<br>log = logging.getLogger(&quot;agent&quot;)</pre><pre>def traced(fn):<br>    @functools.wraps(fn)<br>    def wrapper(state):<br>        name = fn.__name__<br>        log.info(&quot;ENTER %s keys=%s&quot;, name, sorted(state.keys()))<br>        try:<br>            update = fn(state)<br>        except Exception:<br>            log.exception(&quot;FAILED %s keys=%s&quot;, name, sorted(state.keys()))<br>            raise<br>        log.info(&quot;EXIT  %s wrote=%s&quot;, name, sorted(update.keys()))<br>        return update<br>    return wrapper</pre><pre>builder = StateGraph(b.SupportState)<br>for f in (b.classify_node, b.retrieve_node, b.respond_node):<br>    builder.add_node(f.__name__, traced(f))<br>builder.add_edge(START, &quot;classify_node&quot;)<br>builder.add_edge(&quot;classify_node&quot;, &quot;retrieve_node&quot;)<br>builder.add_edge(&quot;retrieve_node&quot;, &quot;respond_node&quot;)<br>builder.add_edge(&quot;respond_node&quot;, END)<br>g = builder.compile()<br>try:<br>    g.invoke({&quot;question&quot;: &quot;My order has not arrived. Can you check its status?&quot;})<br>except KeyError as e:<br>    print(&quot;raised KeyError&quot;, e)</pre><p><strong>Captured output</strong> (traceback body trimmed):</p><pre>INFO agent | ENTER classify_node keys=[&#39;question&#39;]<br>INFO agent | EXIT  classify_node wrote=[&#39;intent&#39;, &#39;search_query&#39;]<br>INFO agent | ENTER retrieve_node keys=[&#39;intent&#39;, &#39;question&#39;]<br>ERROR agent | FAILED retrieve_node keys=[&#39;intent&#39;, &#39;question&#39;]<br>KeyError: &#39;query&#39;</pre><p>Read those four lines carefully:</p><ol><li>classify_node <strong>wrote</strong> intent and search_query.</li><li>retrieve_node <strong>received</strong> only intent and question. search_query is not there.</li><li>retrieve_node then failed looking for query.</li></ol><p>Two separate problems are now visible. classify_node wrote a key called search_query, not query, and that key never reached the next node. The second point surprised me: it is not just a naming mismatch. In my run on this version, LangGraph <strong>silently dropped</strong> the undeclared search_query key rather than raising an error. I only tested this one case (a TypedDict schema, with a known key returned alongside the unknown one), so don&#39;t treat it as a rule for all versions or all schemas.</p><p>A few logging guidelines:</p><ul><li>Log <strong>key names and types</strong> by default, not whole values. State can contain customer data, prompts, or tokens.</li><li>Never log API keys, auth headers, or full sensitive prompts. Redact before logging.</li><li>print() is fine for a throwaway local investigation. Switch to logging once the code is shared or runs anywhere other than your laptop, because you get levels, timestamps, and the ability to route output. See the official <a href="https://docs.python.org/3/library/logging.html">Python logging documentation</a>.</li></ul><h3>B. Inspect updates with stream()</h3><p>Logging needs code changes. graph.stream() doesn&#39;t. With stream_mode=&quot;updates&quot;, you receive one event per node, containing only what that node returned. With stream_mode=&quot;values&quot;, you receive the <strong>full state</strong> after each step. Save as debug_stream.py:</p><pre># debug_stream.py<br>from broken_agent import graph</pre><pre>q = {&quot;question&quot;: &quot;My order has not arrived. Can you check its status?&quot;}</pre><pre>print(&quot;---- updates mode&quot;)<br>try:<br>    for step, event in enumerate(graph.stream(q, stream_mode=&quot;updates&quot;), 1):<br>        print(step, event)<br>except Exception as e:<br>    print(&quot;FAILED:&quot;, type(e).__name__, e)</pre><pre>print(&quot;---- values mode&quot;)<br>try:<br>    for s in graph.stream(q, stream_mode=&quot;values&quot;):<br>        print(s)<br>except Exception as e:<br>    print(&quot;FAILED:&quot;, type(e).__name__, e)</pre><p><strong>Captured output:</strong></p><pre>---- updates mode<br>1 {&#39;classify_node&#39;: {&#39;intent&#39;: &#39;order_status&#39;}}<br>FAILED: KeyError &#39;query&#39;<br>---- values mode<br>{&#39;question&#39;: &#39;My order has not arrived. Can you check its status?&#39;}<br>{&#39;question&#39;: &#39;My order has not arrived. Can you check its status?&#39;, &#39;intent&#39;: &#39;order_status&#39;}<br>FAILED: KeyError &#39;query&#39;</pre><p>This is the most revealing output so far. Look at step 1: classify_node <em>returned</em> intent and search_query in our code, but the <strong>update event contains only </strong><strong>intent</strong>. The event shows what LangGraph actually applied, not what your function intended. The values stream tells the same story: after classify_node, the state has no query and no search_query.</p><p>What the events mean, so you can interpret them:</p><ul><li>In updates mode, each event is a dict keyed by node name, holding that node&#39;s applied update. Update events are not the entire state.</li><li>In values mode, each event is the whole state after a step. The first event is the input state.</li><li>The exact event shape depends on the stream mode and LangGraph version. Check the streaming section of the official LangGraph docs for your release.</li></ul><p>You can also inspect the graph structure itself with graph.get_graph().draw_mermaid(), which returned a flowchart of the three nodes and four edges in my run. That confirms the wiring is what you think it is, which matters when you suspect routing.</p><h3>C. Trace the execution order</h3><p>Combine the two techniques to answer the questions that matter:</p><p>Question Where to look Which node ran first? First event in updates mode, or first ENTER log line Which node ran right before the failure? Last successful EXIT log / last updates event What state did each node see? ENTER ... keys= log lines, or values events Did the router pick the expected path? The sequence of node names in updates events Was the failing node reached at all? Presence of its ENTER line</p><p>For this bug:</p><pre>flowchart LR<br>    S([START]) --&gt; C[classify_node&lt;br/&gt;writes intent + search_query]<br>    C --&gt;|&quot;state: question, intent&lt;br/&gt;search_query dropped&quot;| R[retrieve_node&lt;br/&gt;reads state &#39;query&#39;]<br>    R -.-&gt;|KeyError: &#39;query&#39;| X((run aborted))<br>    R --&gt; P[respond_node&lt;br/&gt;never reached]<br>    P --&gt; E([END])<br>    style R fill:#ffd6d6,stroke:#c00,stroke-width:2px<br>    style P fill:#eee,stroke:#999,stroke-dasharray: 4 4</pre><p><em>Figure 2. The broken execution path. The exception surfaces in </em><em>retrieve_node (red), but the state became wrong at the </em><em>classify_node to </em><em>retrieve_node hand-off.</em></p><p>The principle: <strong>the node that exposes the problem is not necessarily the node that introduced it.</strong> Always check the previous node’s output.</p><p>State-flow table for the broken run:</p><p>Step Node Keys in on entry Keys returned Keys applied to state 0 input n/a n/a question 1 classify_node question intent, search_query intent only 2 retrieve_node question, intent n/a (raised) none 3 respond_node not reached not reached not reached</p><h3>D. Exception handling: log, then decide</h3><p>Look again at the logging decorator. It catches the exception, logs it, and <strong>re-raises</strong>. That is deliberate. There are four different things people call “handling an exception”:</p><p>Pattern What it does When it’s right <strong>Catch, log, re-raise</strong> Records diagnostics, the graph still fails Default for unexpected errors. You want visibility without hiding the failure <strong>Recover</strong> Catch a <em>specific</em> error and take an alternate path (retry, fallback) When you know the failure mode and have a sensible response <strong>Return an </strong><strong>error field in state</strong> Node completes and downstream logic branches on the error When failure is an expected business outcome (e.g. &quot;no data found&quot;) <strong>Swallow silently</strong> (except: pass) Hides the failure Almost never. It turns a loud bug into a wrong answer</p><p>Don’t wrap every node in a blanket try/except that continues. That converts crashes into plausible-looking wrong outputs, which are much harder to find than a stack trace.</p><h3>7. A second kind of bug: conditional routing</h3><p>Everything above concerns state. Routing bugs are the other big class. This is a <strong>separate</strong> example from the primary bug.</p><pre># router_bug.py<br>from typing import TypedDict<br>from langgraph.graph import StateGraph, START, END<br>class S(TypedDict, total=False):<br>    intent: str<br>    path: str<br>def classify(state): return {&quot;intent&quot;: state[&quot;intent&quot;]}<br>def retrieve(state): return {&quot;path&quot;: &quot;retrieve&quot;}<br>def escalate(state): return {&quot;path&quot;: &quot;escalate&quot;}</pre><pre>def bad_router(state):<br>    return state[&quot;intent&quot;]          # returns raw value</pre><pre>def good_router(state):<br>    return &quot;retrieve&quot; if state.get(&quot;intent&quot;) in {&quot;order_status&quot;, &quot;refund&quot;} else &quot;escalate&quot;</pre><pre>def build(router, mapping=None):<br>    b = StateGraph(S)<br>    b.add_node(&quot;classify&quot;, classify); b.add_node(&quot;retrieve&quot;, retrieve); b.add_node(&quot;escalate&quot;, escalate)<br>    b.add_edge(START, &quot;classify&quot;)<br>    b.add_conditional_edges(&quot;classify&quot;, router, mapping)<br>    b.add_edge(&quot;retrieve&quot;, END); b.add_edge(&quot;escalate&quot;, END)<br>    return b.compile()</pre><pre>bad = build(bad_router, {&quot;order_status&quot;: &quot;retrieve&quot;, &quot;refund&quot;: &quot;retrieve&quot;})<br>for intent in [&quot;order_status&quot;, &quot;order_staus&quot;]:<br>    try:<br>        print(intent, &quot;-&gt;&quot;, bad.invoke({&quot;intent&quot;: intent}))<br>    except Exception as e:<br>        print(intent, &quot;-&gt; FAILED&quot;, type(e).__name__, str(e)[:120])<br>good = build(good_router, {&quot;retrieve&quot;: &quot;retrieve&quot;, &quot;escalate&quot;: &quot;escalate&quot;})<br>print(&quot;good&quot;, good.invoke({&quot;intent&quot;: &quot;order_staus&quot;}))</pre><p><strong>Captured output:</strong></p><pre>order_status -&gt; {&#39;intent&#39;: &#39;order_status&#39;, &#39;path&#39;: &#39;retrieve&#39;}<br>order_staus -&gt; FAILED KeyError &#39;order_staus&#39;<br>good {&#39;intent&#39;: &#39;order_staus&#39;, &#39;path&#39;: &#39;escalate&#39;}</pre><p>bad_router returns the raw intent string, and the mapping only knows two values. The correct spelling works. A typo, order_staus, an unexpected value, or a new intent added to the classifier but not to the mapping raises KeyError at routing time. In other setups, a router bug may produce no exception at all and just send the run down the wrong branch.</p><p>good_router is total: every input maps to a destination, and unmatched values go to an explicit fallback. When debugging routing, check:</p><ul><li>The exact string your router returns (print it, or log it).</li><li>Whether that string is a key in the mapping, or the name of a real node.</li><li>What happens for values you didn’t anticipate: spelling variants, None, a missing key, new categories.</li><li>Whether state.get(&quot;intent&quot;) could be absent at the moment the router runs.</li></ul><h3>8. LangSmith: seeing inside the graph</h3><p>Logs and stream() are things <em>you</em> wire up. <strong>LangSmith</strong> is LangChain&#39;s observability platform. It records a <strong>trace</strong> for each run: a structured record of the steps your application took from input to output. Each individual step is a <strong>run</strong> (sometimes called a span). See the official <a href="https://docs.langchain.com/oss/python/langgraph/observability">LangSmith observability docs for LangGraph</a>.</p><p>LangSmith is optional. LangGraph works without it, and everything in sections 5 to 7 needs no account.</p><p><strong>Setup</strong> (per the <a href="https://docs.langchain.com/langsmith/trace-with-langgraph">official “Trace LangGraph applications” guide</a>): create a LangSmith account and API key, then set environment variables before running your program:</p><pre>pip install -U langsmith<br>export LANGSMITH_TRACING=true<br>export LANGSMITH_API_KEY=&lt;your-api-key&gt;   # placeholder: never commit a real key</pre><p>Traces go to a project named default unless you configure another one. The docs also describe tracing selectively with the tracing_context context manager, and masking sensitive data before it leaves your machine. Check the current docs for exact options, as these evolve.</p><p><strong>Illustrative trace structure</strong> (not a screenshot, and the exact UI layout will differ):</p><pre>SupportGraph run                      status: error<br>├── classify_node                     status: success<br>│     input : {question: &quot;My order has not arrived...&quot;}<br>│     output: {intent: &quot;order_status&quot;}<br>├── retrieve_node                     status: error<br>│     input : {question: &quot;...&quot;, intent: &quot;order_status&quot;}<br>│     error : KeyError: &#39;query&#39;</pre><p>What to look for in the real interface:</p><ul><li><strong>Tree of runs.</strong> The graph run and its child node runs, in order. This answers “which node ran, and which one errored?”</li><li><strong>Inputs and outputs per node.</strong> Compare one node’s output with the next node’s input. The faulty transition is where they disagree.</li><li><strong>Error details.</strong> Failed runs carry the exception text. Start at the failed node, then walk upward.</li><li><strong>Nested calls.</strong> If a node calls a model or tool through instrumented code, those calls appear as child runs, with their prompts, responses, and latency.</li></ul><p><strong>How tracing differs from logging.</strong> Logging is free-form text you chose to emit. A trace is structured and hierarchical, automatically linked by parent and child, and captures inputs and outputs you didn’t think to log. Logs are better for application-specific events and local work; traces are better for reconstructing one specific run.</p><p><strong>Telling an LLM mistake from a state bug.</strong> In an LLM-backed version of this graph, open the trace and compare, for the suspicious node, (1) the input it received, (2) the prompt actually sent to the model, and (3) the model’s raw output. If the input state was already wrong, or the prompt is missing the retrieved context, it’s a state or wiring bug. If the prompt was correct and complete but the answer is wrong, it’s a model problem. Without the trace you can’t separate the two.</p><p>Redaction matters here: traces may capture customer data and prompts. Use the masking options in the docs, and treat your tracing project as sensitive.</p><h3>9. The fix</h3><p>Summary of the diagnosis:</p><p><strong>Symptom</strong> KeyError: &#39;query&#39; from retrieve_node; no answer returned <strong>Immediate failure</strong> retrieve_node read a key that was not in state <strong>Root cause</strong> classify_node wrote search_query; the schema and reader use query. LangGraph dropped the undeclared key without an error (observed in this version) <strong>Corrective change</strong> Write the declared query key in classify_node <strong>Preventive measure</strong> Validate inputs at node boundaries, make routing total, add tests that assert the exact keys a node writes</p><p>Renaming one key fixes the symptom. The complete fix also hardens the boundaries. Save as support_agent.py:</p><pre># support_agent.py<br>&quot;&quot;&quot;Fixed customer-support graph (no LLM, no API key).&quot;&quot;&quot;<br>from typing import TypedDict<br>from langgraph.graph import StateGraph, START, END</pre><pre># Illustrative, in-memory knowledge base. Not real customer data.<br>KNOWLEDGE_BASE = {<br>    &quot;order_status&quot;: &quot;Order ORD-1042 shipped on 2 Oct and is in transit. Estimated delivery: 6 Oct.&quot;,<br>    &quot;refund&quot;: &quot;Refunds are issued to the original payment method within 5-7 business days.&quot;,<br>}<br>KNOWN_INTENTS = set(KNOWLEDGE_BASE)</pre><pre>class SupportState(TypedDict, total=False):<br>    question: str<br>    intent: str<br>    query: str<br>    context: str<br>    answer: str<br>    error: str</pre><pre>def classify_node(state: SupportState) -&gt; dict:<br>    question = state.get(&quot;question&quot;)<br>    if not isinstance(question, str) or not question.strip():<br>        raise ValueError(&quot;classify_node: &#39;question&#39; must be a non-empty string&quot;)<br>    text = question.lower()<br>    if &quot;order&quot; in text or &quot;arrived&quot; in text:<br>        intent = &quot;order_status&quot;<br>    elif &quot;refund&quot; in text:<br>        intent = &quot;refund&quot;<br>    else:<br>        intent = &quot;unknown&quot;<br>    # FIX: write the key the schema declares (&quot;query&quot;), and always write it.<br>    return {&quot;intent&quot;: intent, &quot;query&quot;: intent if intent in KNOWN_INTENTS else &quot;&quot;}</pre><pre>def route_after_classify(state: SupportState) -&gt; str:<br>    # Explicit, total routing: anything unrecognised goes to escalation.<br>    if state.get(&quot;intent&quot;) in KNOWN_INTENTS:<br>        return &quot;retrieve_node&quot;<br>    return &quot;escalate_node&quot;</pre><pre>def retrieve_node(state: SupportState) -&gt; dict:<br>    query = state.get(&quot;query&quot;)<br>    if not query:<br>        raise ValueError(&quot;retrieve_node: expected a non-empty &#39;query&#39; in state&quot;)<br>    context = KNOWLEDGE_BASE.get(query)<br>    if context is None:<br>        return {&quot;context&quot;: &quot;&quot;, &quot;error&quot;: f&quot;no_context_found:{query}&quot;}<br>    return {&quot;context&quot;: context}</pre><pre>def respond_node(state: SupportState) -&gt; dict:<br>    if state.get(&quot;error&quot;) or not state.get(&quot;context&quot;):<br>        return {&quot;answer&quot;: &quot;I couldn&#39;t find that information. A human agent will follow up.&quot;}<br>    return {&quot;answer&quot;: f&quot;Here&#39;s what I found: {state[&#39;context&#39;]}&quot;}</pre><pre>def escalate_node(state: SupportState) -&gt; dict:<br>    return {<br>        &quot;error&quot;: &quot;unsupported_intent&quot;,<br>        &quot;answer&quot;: &quot;I&#39;m not able to help with that here. Passing you to a human agent.&quot;,<br>    }</pre><pre>def build_graph(checkpointer=None):<br>    b = StateGraph(SupportState)<br>    b.add_node(&quot;classify_node&quot;, classify_node)<br>    b.add_node(&quot;retrieve_node&quot;, retrieve_node)<br>    b.add_node(&quot;respond_node&quot;, respond_node)<br>    b.add_node(&quot;escalate_node&quot;, escalate_node)<br>    b.add_edge(START, &quot;classify_node&quot;)<br>    b.add_conditional_edges(<br>        &quot;classify_node&quot;, route_after_classify,<br>        {&quot;retrieve_node&quot;: &quot;retrieve_node&quot;, &quot;escalate_node&quot;: &quot;escalate_node&quot;},<br>    )<br>    b.add_edge(&quot;retrieve_node&quot;, &quot;respond_node&quot;)<br>    b.add_edge(&quot;respond_node&quot;, END)<br>    b.add_edge(&quot;escalate_node&quot;, END)<br>    return b.compile(checkpointer=checkpointer)</pre><pre>graph = build_graph()</pre><pre>if __name__ == &quot;__main__&quot;:<br>    out = graph.invoke({&quot;question&quot;: &quot;My order has not arrived. Can you check its status?&quot;})<br>    print(out)</pre><p>What changed, and why:</p><ol><li><strong>The key name.</strong> classify_node now returns query, matching the schema. This is the root-cause fix.</li><li><strong>Input validation in </strong><strong>classify_node.</strong> Empty, whitespace-only, or non-string questions raise a clear ValueError naming the node and field. An unclear failure deep in the graph becomes an obvious one at the entry.</li><li><strong>query is always written.</strong> Unknown intents get &quot;&quot;, never a missing key, so downstream readers never face an absent key.</li><li><strong>A total router.</strong> route_after_classify sends known intents to retrieve_node and everything else to escalate_node. No unmatched case exists.</li><li><strong>A guard in </strong><strong>retrieve_node.</strong> Uses state.get, then raises a descriptive ValueError if query is empty. Defense in depth: if upstream code regresses, the message names the missing field rather than only a bare KeyError.</li><li><strong>A structured error for “no data”.</strong> If the knowledge base has no entry, retrieve_node returns error and an empty context. That is an expected business outcome, not a crash.</li><li><strong>No fabricated answers.</strong> respond_node returns a fallback when error is set or context is empty. It never invents information.</li><li><strong>A </strong><strong>build_graph() factory.</strong> This lets tests and later sections pass in a checkpointer.</li></ol><p>Run it:</p><pre>python support_agent.py</pre><p><strong>Captured output:</strong></p><pre>{&#39;question&#39;: &#39;My order has not arrived. Can you check its status?&#39;, &#39;intent&#39;: &#39;order_status&#39;, &#39;query&#39;: &#39;order_status&#39;, &#39;context&#39;: &#39;Order ORD-1042 shipped on 2 Oct and is in transit. Estimated delivery: 6 Oct.&#39;, &#39;answer&#39;: &quot;Here&#39;s what I found: Order ORD-1042 shipped on 2 Oct and is in transit. Estimated delivery: 6 Oct.&quot;}</pre><p>The corrected workflow:</p><pre>flowchart TD<br>    A[Reproduce with minimal input] --&gt; B[Stream updates / read logs]<br>    B --&gt; C{Last node that completed?}<br>    C --&gt; D[Compare its returned keys with next node&#39;s inputs]<br>    D --&gt; E{Mismatch found?}<br>    E --&gt;|yes| F[Fix at the writer: use the schema key]<br>    E --&gt;|no| G[Check router decisions and checkpoint config]<br>    F --&gt; H[Add boundary validation]<br>    G --&gt; H<br>    H --&gt; I[Write regression test]<br>    I --&gt; J[Verify success and failure paths]</pre><p><em>Figure 3. The debugging and recovery workflow used in this article. Fix the node that wrote bad state, not just the node that noticed it.</em></p><p>Before and after:</p><p>Aspect Broken version Fixed version Key written by classify_node search_query (not in schema) query (in schema) Missing query at retrieval Bare KeyError Descriptive ValueError guard Unknown intent Not handled Routed to escalate_node Empty question Not handled ValueError at entry No knowledge-base match Not handled Structured error, safe fallback Testable? No tests Eight pytest cases</p><h3>10. Regression tests</h3><p>A regression test proves a specific bug can’t quietly return. After a refactor, someone may rename a field again, and the tests catch it. Save as test_support_agent.py:</p><pre># test_support_agent.py<br>import pytest<br>import support_agent<br>from support_agent import graph</pre><pre>def test_order_status_happy_path():<br>    out = graph.invoke({&quot;question&quot;: &quot;My order has not arrived. Can you check its status?&quot;})<br>    assert out[&quot;intent&quot;] == &quot;order_status&quot;<br>    assert out[&quot;query&quot;] == &quot;order_status&quot;<br>    assert &quot;ORD-1042&quot; in out[&quot;answer&quot;]<br>    assert &quot;error&quot; not in out</pre><pre>@pytest.mark.parametrize(&quot;bad&quot;, [&quot;&quot;, &quot;   &quot;, None])<br>def test_empty_question_raises(bad):<br>    with pytest.raises(ValueError, match=&quot;non-empty string&quot;):<br>        graph.invoke({&quot;question&quot;: bad})</pre><pre>def test_unknown_intent_is_escalated_not_retrieved():<br>    out = graph.invoke({&quot;question&quot;: &quot;Tell me a joke&quot;})<br>    assert out[&quot;intent&quot;] == &quot;unknown&quot;<br>    assert out[&quot;error&quot;] == &quot;unsupported_intent&quot;<br>    assert &quot;context&quot; not in out          # retrieve_node never ran<br>    assert &quot;human agent&quot; in out[&quot;answer&quot;]</pre><pre>def test_missing_knowledge_returns_structured_error(monkeypatch):<br>    monkeypatch.setattr(support_agent, &quot;KNOWLEDGE_BASE&quot;, {})<br>    out = graph.invoke({&quot;question&quot;: &quot;Where is my order?&quot;})<br>    assert out[&quot;error&quot;] == &quot;no_context_found:order_status&quot;<br>    assert &quot;couldn&#39;t find&quot; in out[&quot;answer&quot;]</pre><pre>def test_classify_writes_query_key():<br>    &quot;&quot;&quot;Regression for the original bug: classify must populate &#39;query&#39;.&quot;&quot;&quot;<br>    update = support_agent.classify_node({&quot;question&quot;: &quot;I want a refund&quot;})<br>    assert update[&quot;query&quot;] == &quot;refund&quot;</pre><pre>def test_execution_path_order():<br>    path = [next(iter(e)) for e in graph.stream(<br>        {&quot;question&quot;: &quot;refund please&quot;}, stream_mode=&quot;updates&quot;)]<br>    assert path == [&quot;classify_node&quot;, &quot;retrieve_node&quot;, &quot;respond_node&quot;]</pre><p>Run them with:</p><pre>pytest -q</pre><p>I ran these against the code above and got 8 passed (six test functions; one is parametrized over three bad inputs). Your run should match on the same versions.</p><p>The expected behavior in each case:</p><p>Test Expected behavior Happy path intent and query are order_status; answer contains ORD-1042; no error key Empty or invalid question Raises ValueError mentioning &quot;non-empty string&quot; Unknown intent intent == &quot;unknown&quot;, error == &quot;unsupported_intent&quot;, no context key (retrieval never ran) Missing knowledge data Structured error string and the fallback answer, no exception Original bug classify_node output must contain query Execution order Updates arrive as classify, retrieve, respond</p><p>Notice that the tests assert exactly what the implementation does: exceptions are asserted with pytest.raises, and structured errors are asserted as values. Tests that disagree with the code are worse than none. The test_classify_writes_query_key test is the true regression test, because it would have failed against the broken code. The test_execution_path_order test also protects the routing.</p><h3>11. Checkpointing and production debugging</h3><h3>How checkpointing differs from passing state</h3><p>Normal state passing happens inside a single run and disappears when it ends. A <strong>checkpointer</strong> saves state snapshots as the graph executes, grouped under a <strong>thread_id</strong>, so you can inspect a run afterward or resume a conversation. Without a checkpointer, none of this exists. InMemorySaver is the simplest option and is fine for learning; it forgets everything when the process exits. Production setups use a durable checkpointer, which needs its own storage setup. See the persistence section of the LangGraph docs.</p><pre># ckpt.py<br>from langgraph.checkpoint.memory import InMemorySaver<br>from support_agent import build_graph</pre><pre>g = build_graph(checkpointer=InMemorySaver())<br>cfg = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;demo-thread-1&quot;}}</pre><pre>g.invoke({&quot;question&quot;: &quot;I want a refund&quot;}, cfg)</pre><pre>snap = g.get_state(cfg)<br>print(&quot;next:&quot;, snap.next)<br>print(&quot;values keys:&quot;, sorted(snap.values))</pre><pre>for s in g.get_state_history(cfg):<br>    print(s.metadata.get(&quot;step&quot;), s.next, sorted(s.values))</pre><p><strong>Captured output:</strong></p><pre>next: ()<br>values keys: [&#39;answer&#39;, &#39;context&#39;, &#39;intent&#39;, &#39;query&#39;, &#39;question&#39;]<br>3 () [&#39;answer&#39;, &#39;context&#39;, &#39;intent&#39;, &#39;query&#39;, &#39;question&#39;]<br>2 (&#39;respond_node&#39;,) [&#39;context&#39;, &#39;intent&#39;, &#39;query&#39;, &#39;question&#39;]<br>1 (&#39;retrieve_node&#39;,) [&#39;intent&#39;, &#39;query&#39;, &#39;question&#39;]<br>0 (&#39;classify_node&#39;,) [&#39;question&#39;]<br>-1 (&#39;__start__&#39;,) []</pre><p>The history prints newest first. Each line is step, the node(s) due to run next, and the state keys at that point.</p><p>Each history entry shows the state at that step and next, the node(s) due to run. That makes checkpoints a time machine for debugging.</p><h3>The checkpoint trick for failed runs</h3><p>This is where checkpoints earn their place. I compiled the <strong>broken</strong> graph with a checkpointer and let it fail. Then I called get_state:</p><pre>next: (&#39;retrieve_node&#39;,)<br>values: {&#39;question&#39;: &#39;My order has not arrived. Can you check its status?&#39;, &#39;intent&#39;: &#39;order_status&#39;}</pre><p>(Captured.) After the crash, the saved state says retrieve_node is next and the state is missing query. You get the failing node and its exact input without re-running anything.</p><h3>Resumed runs and thread gotchas</h3><ul><li><strong>Same </strong><strong>thread_id, same saved state.</strong> A later call on the same thread starts from the saved state, not from nothing. If you reuse a thread in a test or a debugging session, you are not running a fresh graph.</li><li><strong>Stale keys carry over.</strong> I verified this on the fixed graph with a checkpointer: after an unsupported question (error=&quot;unsupported_intent&quot;), a second valid question on the <em>same thread</em> ended with error still set, and the answer was the fallback, not the refund policy. Nothing in the second run overwrote error. Typical mitigations: use a fresh thread_id per independent conversation, or have the entry node reset per-turn fields. I did not test a patch for this, so verify any change you make.</li><li><strong>State depends on the stage.</strong> Reading state means asking “state as of which checkpoint?” A snapshot taken mid-run differs from the final one.</li><li><strong>Pass the same config.</strong> Inspecting with a different thread_id than the run used gives you a different (possibly empty) state.</li></ul><h3>Production considerations</h3><p>This is a checklist-style summary. Each item deserves its own article, so I’ll keep it short:</p><ul><li><strong>Structured logs</strong> (JSON, with node name and a run identifier) so they can be searched.</li><li><strong>Trace correlation:</strong> put a request or trace ID in your logs so you can match a log line to its trace.</li><li><strong>Timeouts and retry limits</strong> on model and tool calls; unbounded loops and retries hide failures and burn money.</li><li><strong>Idempotency</strong> for tools with side effects (refunds, emails). A retry or resume must not do the action twice.</li><li><strong>Input validation</strong> at graph entry and at node boundaries.</li><li><strong>Redaction</strong> of personal data and secrets in logs and traces.</li><li><strong>Monitoring</strong> failure rates and latency per node.</li><li><strong>Versioning</strong> prompts and graph definitions, so you can tell which version produced a bad run.</li><li><strong>Regression tests</strong> that run in CI, including the failure paths.</li></ul><pre>## LangGraph debugging checklist</pre><pre>- [ ] Reproduce the problem with a minimal input<br>- [ ] Record the initial state<br>- [ ] Identify the last successfully completed node<br>- [ ] Inspect the failing node&#39;s input<br>- [ ] Inspect state keys and value types<br>- [ ] Check node return values (and what was actually applied)<br>- [ ] Verify conditional-routing decisions<br>- [ ] Inspect exceptions and relevant trace events<br>- [ ] Check tool and model outputs<br>- [ ] If persistence is enabled: check thread_id and checkpoint state<br>- [ ] Apply a root-cause fix (at the node that wrote the bad state)<br>- [ ] Add a regression test<br>- [ ] Verify both the normal and failure paths</pre><h3>12. Conclusion</h3><p>The failing node and the faulty node are often different. A KeyError in retrieve_node was caused by a one-word mistake in classify_node, and LangGraph had silently dropped the key that would have made it obvious.</p><p>The workflow that finds this kind of bug is repeatable: reproduce with a minimal input, look at what each node received and returned, check the routing decisions, use checkpoints and traces when you need to look back at a run, then fix the writer and lock the fix in with a test.</p><p><strong>Takeaway:</strong> don’t debug the final answer. Debug the path, the inputs, the outputs, and the decisions.</p><p>If you’ve hit a LangGraph failure that took hours to track down, I’d like to hear about it. What was the cause, and what finally revealed it? Share it in the comments.</p><h3>References</h3><ul><li>LangSmith: <a href="https://docs.langchain.com/langsmith/trace-with-langgraph">Trace LangGraph applications</a></li><li>LangGraph: <a href="https://docs.langchain.com/oss/python/langgraph/observability">Observability / tracing</a></li><li>Python: <a href="https://docs.python.org/3/library/logging.html">logging module</a></li></ul><p>For API details on streaming modes, persistence, and StateGraph, consult the current official LangGraph documentation for your installed version. I did not link specific pages there that I hadn&#39;t verified.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a9698180b3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Travel Chatbot That Books Cruises, Flights, Hotels & Gardens — All in One Conversation.]]></title>
            <link>https://medium.com/@shashank_shekhar_pandey/i-built-a-travel-chatbot-that-books-cruises-flights-hotels-gardens-all-in-one-conversation-3555f3b39b2e?source=rss-984826d45cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3555f3b39b2e</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[booking]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Shashank Shekhar pandey]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 14:44:14 GMT</pubDate>
            <atom:updated>2026-06-22T14:44:14.957Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>I Built a Travel Chatbot That Books Cruises, Flights, Hotels &amp; Gardens — All in One Conversation. Here’s How LangGraph Swarm Made It Possible.</strong></p><p><em>A story of multi-agent orchestration, clean handoffs, and why “swarm” is the right mental model for real-world booking flows.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2_IBUPyzEPlNX3D_Ls4RA.png" /></figure><p><strong>The Problem with “One Big Agent”</strong></p><p>When I started building a travel booking assistant, my first instinct was simple: one LLM, one system prompt, one conversation loop. Book a cruise? Sure. Book a flight? Also sure. A garden visit and a hotel together? …now things got messy.</p><p>The system prompt became a wall of instructions. The agent kept confusing cruise APIs with hotel APIs. It hallucinated availability. The code looked like a spaghetti junction.</p><p>That’s when I found <strong>LangGraph Swarm</strong>.</p><p><strong>What Is LangGraph Swarm?</strong></p><p>LangGraph Swarm is a multi-agent architecture pattern built on top of LangGraph where each specialized agent can <strong>hand off control</strong> to another agent mid-conversation — cleanly, with full context — and then resume when the task is done.</p><p>Think of it like a travel agency with specialists:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/72/0*dRLA1GzFlECfa0k1.png" /></figure><ul><li><strong>Cruise Agent</strong> — knows ships, ports, cabin types</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/72/0*Mqv0tBgxY32FeugP.png" /></figure><ul><li><strong>Flight Agent</strong> — handles routes, airlines, seat classes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/72/0*7pJBucPq2ii8EAZB.png" /></figure><ul><li><strong>Hotel Agent</strong> — rooms, check-in/out, amenities</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/72/0*9JZyvO5bYrkpLp4M.png" /></figure><ul><li><strong>Garden/Attraction Agent</strong> — entry tickets, timed slots, tours</li></ul><p>The <strong>Supervisor Agent</strong> sits in the middle — it reads the user’s intent and routes them to the right specialist. The magic? The specialist can <strong>hand back</strong> to the supervisor, or even <strong>hand off to another specialist</strong> without breaking the conversation thread.</p><p><strong>The Architecture</strong></p><pre>User ──► Supervisor Agent<br>              │<br>    ┌─────────┼──────────┬─────────────┐<br>    ▼         ▼          ▼             ▼<br>Cruise    Flight      Hotel       Garden<br>Agent     Agent       Agent       Agent<br>    │         │          │             │<br>    └─────────┴──────────┴─────────────┘<br>              │<br>         [APIs: External Booking Services]</pre><p>Each agent has:</p><ol><li>Its own <strong>system prompt</strong> scoped to its domain</li><li>A set of <strong>tools</strong> (API calls for that booking type)</li><li>A transfer_to_X() function to hand off to other agents</li></ol><p><strong>The Code</strong></p><p><strong>Setting Up the Agents</strong></p><pre>from langgraph_swarm import SwarmAgent, create_swarm<br>from langchain_openai import ChatOpenAI<br>from langchain_core.tools import tool<br>import httpx</pre><pre>llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0)</pre><pre># --- TOOLS ---</pre><pre>@tool<br>def book_cruise(ship_name: str, departure_date: str, cabin_type: str) -&gt; dict:<br>    &quot;&quot;&quot;Book a cruise via API.&quot;&quot;&quot;<br>    response = httpx.post(&quot;https://api.cruiselines.example.com/book&quot;, json={<br>        &quot;ship&quot;: ship_name,<br>        &quot;date&quot;: departure_date,<br>        &quot;cabin&quot;: cabin_type<br>    })<br>    return response.json()</pre><pre>@tool<br>def book_flight(origin: str, destination: str, date: str, seat_class: str) -&gt; dict:<br>    &quot;&quot;&quot;Book a flight via API.&quot;&quot;&quot;<br>    response = httpx.post(&quot;https://api.flights.example.com/reserve&quot;, json={<br>        &quot;from&quot;: origin,<br>        &quot;to&quot;: destination,<br>        &quot;date&quot;: date,<br>        &quot;class&quot;: seat_class<br>    })<br>    return response.json()</pre><pre>@tool<br>def book_hotel(city: str, check_in: str, check_out: str, room_type: str) -&gt; dict:<br>    &quot;&quot;&quot;Book a hotel room via API.&quot;&quot;&quot;<br>    response = httpx.post(&quot;https://api.hotels.example.com/book&quot;, json={<br>        &quot;city&quot;: city,<br>        &quot;check_in&quot;: check_in,<br>        &quot;check_out&quot;: check_out,<br>        &quot;room&quot;: room_type<br>    })<br>    return response.json()</pre><pre>@tool<br>def book_garden(garden_name: str, visit_date: str, num_visitors: int) -&gt; dict:<br>    &quot;&quot;&quot;Book garden / attraction entry via API.&quot;&quot;&quot;<br>    response = httpx.post(&quot;https://api.attractions.example.com/entry&quot;, json={<br>        &quot;garden&quot;: garden_name,<br>        &quot;date&quot;: visit_date,<br>        &quot;visitors&quot;: num_visitors<br>    })<br>    return response.json()</pre><p><strong>Creating Each Specialist Agent</strong></p><pre>from langgraph_swarm import create_handoff_tool</pre><pre># Cruise Agent<br>cruise_agent = SwarmAgent(<br>    name=&quot;cruise_agent&quot;,<br>    llm=llm,<br>    tools=[<br>        book_cruise,<br>        create_handoff_tool(agent_name=&quot;flight_agent&quot;),<br>        create_handoff_tool(agent_name=&quot;hotel_agent&quot;),<br>        create_handoff_tool(agent_name=&quot;supervisor&quot;),<br>    ],<br>    system_prompt=&quot;&quot;&quot;You are a cruise booking specialist.<br>Help users book cruises. If they ask about flights, hotels, or gardens,<br>hand off to the appropriate agent. Once cruise booking is confirmed, <br>return to supervisor.&quot;&quot;&quot;<br>)</pre><pre># Flight Agent<br>flight_agent = SwarmAgent(<br>    name=&quot;flight_agent&quot;,<br>    llm=llm,<br>    tools=[<br>        book_flight,<br>        create_handoff_tool(agent_name=&quot;hotel_agent&quot;),<br>        create_handoff_tool(agent_name=&quot;cruise_agent&quot;),<br>        create_handoff_tool(agent_name=&quot;supervisor&quot;),<br>    ],<br>    system_prompt=&quot;&quot;&quot;You are a flight booking specialist.<br>Help users find and book flights. Hand off to hotel or cruise agents<br>when relevant. Return to supervisor after completion.&quot;&quot;&quot;<br>)</pre><pre># Hotel Agent<br>hotel_agent = SwarmAgent(<br>    name=&quot;hotel_agent&quot;,<br>    llm=llm,<br>    tools=[<br>        book_hotel,<br>        create_handoff_tool(agent_name=&quot;flight_agent&quot;),<br>        create_handoff_tool(agent_name=&quot;garden_agent&quot;),<br>        create_handoff_tool(agent_name=&quot;supervisor&quot;),<br>    ],<br>    system_prompt=&quot;&quot;&quot;You are a hotel booking specialist.<br>Handle room reservations. Cross-sell garden visits when in nature<br>destinations. Return to supervisor on completion.&quot;&quot;&quot;<br>)</pre><pre># Garden/Attraction Agent<br>garden_agent = SwarmAgent(<br>    name=&quot;garden_agent&quot;,<br>    llm=llm,<br>    tools=[<br>        book_garden,<br>        create_handoff_tool(agent_name=&quot;hotel_agent&quot;),<br>        create_handoff_tool(agent_name=&quot;supervisor&quot;),<br>    ],<br>    system_prompt=&quot;&quot;&quot;You are an attractions and garden booking specialist.<br>Book entry tickets, guided tours, and timed visits. Hand off to hotel<br>if user needs accommodation nearby.&quot;&quot;&quot;<br>)</pre><p><strong>The Supervisor + Swarm</strong></p><pre>supervisor_prompt = &quot;&quot;&quot;You are a travel planning supervisor.<br>Understand what the user wants to book and route to the right specialist:<br>- Cruises → cruise_agent<br>- Flights → flight_agent  <br>- Hotels → hotel_agent<br>- Gardens / attractions → garden_agent</pre><pre>If the user wants multiple bookings (e.g. flight + hotel), <br>coordinate sequentially by handing off in logical order.&quot;&quot;&quot;</pre><pre># Build the swarm<br>app = create_swarm(<br>    agents=[cruise_agent, flight_agent, hotel_agent, garden_agent],<br>    default_active_agent=&quot;supervisor&quot;,<br>).compile()</pre><p><strong>Running a Conversation</strong></p><pre>from langchain_core.messages import HumanMessage</pre><pre>config = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;trip-42&quot;}}</pre><pre># Turn 1: User wants a cruise<br>result = app.invoke(<br>    {&quot;messages&quot;: [HumanMessage(content=&quot;I want to book a 7-night Mediterranean cruise departing June 15th, ocean view cabin.&quot;)]},<br>    config=config<br>)<br>print(result[&quot;messages&quot;][-1].content)<br># → Cruise Agent handles it. Confirms booking.</pre><pre># Turn 2: Mid-conversation, user adds a flight<br>result = app.invoke(<br>    {&quot;messages&quot;: [HumanMessage(content=&quot;Great! Now I need a flight from Mumbai to Barcelona on June 14th, business class.&quot;)]},<br>    config=config<br>)<br>print(result[&quot;messages&quot;][-1].content)<br># → Swarm auto-detects. Hands off to Flight Agent. Books flight.<br># → Returns to conversation thread seamlessly.</pre><pre># Turn 3: Hotel + Garden combo<br>result = app.invoke(<br>    {&quot;messages&quot;: [HumanMessage(content=&quot;And can you book me a hotel in Barcelona for June 14-15, and also tickets to Park Güell?&quot;)]},<br>    config=config<br>)<br>print(result[&quot;messages&quot;][-1].content)<br># → Hotel Agent books room.<br># → Hands off to Garden Agent for Park Güell.<br># → Both confirmations returned in one reply.</pre><p><strong>The Moment That Made Me Choose Swarm</strong></p><p>Here’s the conversation that convinced me:</p><blockquote><strong><em>User:</em></strong><em> “Actually, after the cruise, I want to spend a day at the Butchart Gardens in Victoria. Book that too.”</em></blockquote><p>With a monolithic agent, this mid-conversation pivot broke the context. The agent forgot it had already booked the cruise and tried to re-ask.</p><p>With Swarm? The Cruise Agent finished, state was preserved in the LangGraph checkpoint, and it cleanly handed off to the Garden Agent <strong>with full conversation history intact</strong>. The user felt like they were talking to one smart assistant — not a patchwork of bots.</p><p><strong>Why Swarm Over Other Patterns?</strong></p><p>Pattern</p><p>Problem</p><p>Single monolithic agent</p><p>Prompt overload, API confusion, hallucinations</p><p>Sequential pipeline</p><p>Rigid, can’t handle mid-conversation pivots</p><p>Parallel agents</p><p>No shared context, responses out of sync</p><p><strong>Swarm (handoff-based)</strong></p><p>Specialized, context-preserving, flexible routing</p><p>The key insight: <strong>Swarm agents don’t lose context on handoff.</strong> LangGraph’s state graph persists the full message history + any state variables (like confirmed_bookings) across the entire conversation, regardless of which agent is currently active.</p><p><strong>What’s Running in Production</strong></p><ul><li><strong>4 specialist agents</strong> with isolated system prompts</li><li><strong>Real API integrations</strong> (cruise, flight, hotel, attraction booking endpoints)</li><li><strong>LangGraph checkpointing</strong> via Redis for persistent multi-turn sessions</li><li><strong>Fallback logic</strong>: if an API times out, the agent retries and informs the user</li><li><strong>Human-in-the-loop</strong> for high-value bookings (cruise cabins above $2,000 get a confirmation step)</li></ul><p><strong>Key Takeaways</strong></p><ol><li><strong>Domain isolation is powerful.</strong> Each agent only knows what it needs to know. No prompt bloat.</li><li><strong>Handoffs preserve context.</strong> The user never feels the switch — it’s invisible.</li><li><strong>Swarm scales naturally.</strong> Adding a new booking type (car rentals? spa packages?) means adding one new agent and wiring in the handoff tools. Zero changes to existing agents.</li><li><strong>LangGraph’s state graph is the backbone.</strong> Without it, handoffs would lose history. With it, every agent picks up exactly where the last left off.</li></ol><p><strong>What’s Next</strong></p><p>I’m planning to add:</p><ul><li><strong>Budget constraint agent</strong> that enforces a total trip budget across all bookings</li><li><strong>Itinerary summarizer</strong> that compiles everything at the end into a single PDF</li><li><strong>Voice interface</strong> layer so users can book their entire trip conversationally</li></ul><p><em>If you’re building multi-service assistants and fighting with monolithic agent prompts, give LangGraph Swarm a serious look. The “one conversation, many specialists” model is the architecture I wish I’d started with.</em></p><p><em>Follow me for more on production AI systems, voice agents, and LLM-powered backends.</em></p><p><strong>Tags:</strong> #LangGraph #LangChain #AIAgents #SwarmAI #GenerativeAI #Python #MachineLearning #ChatbotDevelopment #MultiAgent #TravelTech</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3555f3b39b2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-Time AI Call Audit System: Speech-to-Text, LLM Evaluation, Compliance Monitoring…]]></title>
            <link>https://medium.com/@shashank_shekhar_pandey/building-a-real-time-ai-call-audit-system-speech-to-text-llm-evaluation-compliance-monitoring-585fb8d53be7?source=rss-984826d45cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/585fb8d53be7</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[agent-calling]]></category>
            <dc:creator><![CDATA[Shashank Shekhar pandey]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 07:28:03 GMT</pubDate>
            <atom:updated>2026-06-10T07:28:03.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzR2FHVsh_c26tqX56-Djw.png" /></figure><h3>Building a Real-Time AI Call Audit System: Speech-to-Text, LLM Evaluation, Compliance Monitoring, and Agent Scoring</h3><p><em>How we built a production-grade system that listens, understands, and grades every customer call — in real time.</em></p><blockquote><strong><em>TL;DR:</em></strong><em> We built a system that ingests live call audio, transcribes it with speaker diarization, runs sentiment analysis and compliance checks, audits agent behaviour using an LLM, and pushes results to a live dashboard — all within seconds of a conversation ending. This post is the full engineering story: architecture, trade-offs, production war stories, and everything we wish someone had told us before we started.</em></blockquote><h3>Table of Contents</h3><ol><li>The Business Problem Nobody Talks About Honestly</li><li>High-Level Architecture</li><li>Call Ingestion Pipeline</li><li>Streaming Transcription</li><li>Speaker Diarization</li><li>Sentiment Analysis</li><li>Compliance Checks</li><li>LLM-Based Auditing</li><li>Real-Time Dashboards</li><li>Latency Optimization</li><li>Production Challenges</li><li>Lessons Learned</li><li>What’s Next</li></ol><h3>1. The Business Problem Nobody Talks About Honestly</h3><p>Every contact centre manager will tell you the same lie with a straight face: <em>“We review 5% of calls for quality.”</em></p><p>What they mean is: a tired QA analyst, headphones on, manually listens to a random sample of recorded calls once a week and fills out a spreadsheet. That’s it. That is the state of quality assurance in most enterprises handling millions of customer interactions every year.</p><p>The consequences are invisible until they’re catastrophic:</p><ul><li>An agent promises a refund that violates policy. Nobody catches it until the customer escalates.</li><li>A compliance script (“This call may be recorded for quality purposes”) gets skipped 40% of the time. You find out during a regulatory audit.</li><li>Your top-performing agent by sales numbers turns out to be using high-pressure tactics that generate churn 60 days later — but the correlation is buried under a mountain of unreviewed recordings.</li><li>A vulnerable customer expresses financial distress. The agent ignores it. The call ends. Nothing is flagged.</li></ul><p><strong>The real business problem is information asymmetry at scale.</strong> Thousands of calls happen every day. Leadership is flying blind.</p><p>The mandate we received was straightforward but technically brutal: <em>“We want to know what’s happening on every single call, in real time, without hiring more QA analysts.”</em></p><p>This is the story of how we built that system.</p><h3>2. High-Level Architecture</h3><p>Before diving into components, let’s establish the full picture. Here’s what the system looks like end to end:</p><pre>┌─────────────────────────────────────────────┐<br>                        │           CALL INGESTION LAYER               │<br>                        │  (Telephony Bridge / SIPREC / WebRTC Tap)   │<br>                        └───────────────────┬─────────────────────────┘<br>                                            │ Raw Audio Streams<br>                                            ▼<br>                        ┌─────────────────────────────────────────────┐<br>                        │         STREAMING TRANSCRIPTION              │<br>                        │    (Deepgram / AssemblyAI / Whisper)         │<br>                        └───────────────────┬─────────────────────────┘<br>                                            │ Partial + Final Transcripts<br>                                            ▼<br>                    ┌───────────────────────────────────────────────────┐<br>                    │              NLP ENRICHMENT LAYER                  │<br>                    │   Speaker Diarization │ Sentiment │ Entity Extract │<br>                    └────────────┬──────────────────────────────────────┘<br>                                 │ Enriched Transcript Chunks<br>                                 ▼<br>                    ┌───────────────────────────────────────────────────┐<br>                    │            RULES ENGINE (Compliance)               │<br>                    │  Regex Patterns │ Keyword Triggers │ Script Checks │<br>                    └────────────┬──────────────────────────────────────┘<br>                                 │ Violations + Flags<br>                                 ▼<br>                    ┌───────────────────────────────────────────────────┐<br>                    │          LLM AUDIT ENGINE (Post-Call)              │<br>                    │   GPT-4 / Claude │ Structured Scoring Rubrics      │<br>                    └────────────┬──────────────────────────────────────┘<br>                                 │ Audit Reports + Scores<br>                                 ▼<br>                    ┌───────────────────────────────────────────────────┐<br>                    │         EVENT STREAMING (Apache Kafka)             │<br>                    └────────────┬──────────────────────────────────────┘<br>                                 │<br>                    ┌────────────┴───────────────┐<br>                    ▼                            ▼<br>        ┌─────────────────────┐     ┌─────────────────────────┐<br>        │  Real-Time Dashboard │     │   Data Warehouse / Lake  │<br>        │  (Manager Console)   │     │  (Snowflake / BigQuery)  │<br>        └─────────────────────┘     └─────────────────────────┘</pre><p><strong>Tech stack choices at a glance:</strong></p><p>Layer Technology Why Audio ingestion SIPREC + WebRTC Carrier-agnostic Streaming STT Deepgram Nova-2 Best latency/accuracy balance Diarization Pyannote.audio Open source, fine-tunable Message bus Apache Kafka Durable, replay-capable NLP enrichment Custom + HuggingFace Cost control Compliance rules Drools + custom engine Explainability LLM auditing GPT-4o + Claude 3.5 Sonnet Complementary strengths Storage S3 + DynamoDB + Snowflake Hot/warm/cold tiers Dashboard React + WebSockets + ClickHouse Sub-second query latency Orchestration Kubernetes + Temporal Reliability at scale</p><h3>3. Call Ingestion Pipeline</h3><h3>The Telephony Tap Problem</h3><p>Getting audio out of a telephony platform sounds trivial. It is not. Every vendor does it differently, and the standards that exist — primarily <strong>SIPREC (SIP Recording)</strong> as defined in RFC 7866 — are implemented inconsistently in the wild.</p><p>We support three ingestion modes:</p><p><strong>Mode 1: SIPREC (for on-premise / carrier-integrated telephony)</strong></p><p>The telephony platform acts as a Session Recording Client (SRC). It forks the media stream and sends it to our Session Recording Server (SRS). The key challenge here is that SIPREC sends two audio streams — one per participant — and you need to handle the metadata XML to map them to agent and customer legs correctly.</p><pre>class SIPRECHandler:<br>    def __init__(self, kafka_producer):<br>        self.kafka_producer = kafka_producer<br>        self.active_sessions = {}</pre><pre>    async def on_session_start(self, session_id: str, metadata: dict):<br>        &quot;&quot;&quot;<br>        Parse SIPREC XML metadata to extract participant info.<br>        Map stream labels to agent vs customer.<br>        &quot;&quot;&quot;<br>        participants = self._parse_participants(metadata)<br>        self.active_sessions[session_id] = {<br>            &quot;agent&quot;: participants.get(&quot;agent&quot;),<br>            &quot;customer&quot;: participants.get(&quot;customer&quot;),<br>            &quot;start_time&quot;: time.time(),<br>            &quot;call_id&quot;: metadata[&quot;call_id&quot;]<br>        }</pre><pre>    async def on_audio_chunk(self, session_id: str, stream_label: str,<br>                              audio: bytes, timestamp: float):<br>        &quot;&quot;&quot;<br>        Route audio chunks to Kafka with participant labelling.<br>        Audio arrives as G.711 μ-law or a-law — needs decoding.<br>        &quot;&quot;&quot;<br>        session = self.active_sessions.get(session_id)<br>        if not session:<br>            logger.warning(f&quot;Audio for unknown session: {session_id}&quot;)<br>            return</pre><pre>        # Decode codec-specific audio to 16kHz PCM for downstream<br>        pcm_audio = self._decode_g711(audio, codec=&quot;ulaw&quot;)</pre><pre>        await self.kafka_producer.send(<br>            topic=&quot;raw_audio&quot;,<br>            key=session_id.encode(),<br>            value={<br>                &quot;session_id&quot;: session_id,<br>                &quot;call_id&quot;: session[&quot;call_id&quot;],<br>                &quot;stream_label&quot;: stream_label,<br>                &quot;participant_type&quot;: self._get_participant_type(<br>                    session, stream_label<br>                ),<br>                &quot;audio_b64&quot;: base64.b64encode(pcm_audio).decode(),<br>                &quot;timestamp&quot;: timestamp,<br>                &quot;sample_rate&quot;: 16000,<br>                &quot;channels&quot;: 1<br>            }<br>        )</pre><p><strong>Mode 2: WebRTC Tap (for cloud-native CCaaS platforms like Twilio, Genesys Cloud)</strong></p><p>Most modern CCaaS platforms expose MediaStreams via WebSocket. Twilio’s Media Streams sends base64-encoded μ-law chunks every 20ms. The challenge is jitter — network hiccups mean chunks arrive out of order. We buffer 200ms and sort by sequence number before forwarding.</p><p><strong>Mode 3: Post-Call Audio Files (for legacy systems)</strong></p><p>Some customers can’t tap live audio. They dump .wav or .mp3 files to an S3 bucket after calls end. We process these nearly identically to live streams — the pipeline is designed so that &quot;streaming&quot; a file is indistinguishable from live audio for downstream components. This means we can offer live <em>or</em> near-real-time modes without forking the codebase.</p><h3>Audio Normalisation</h3><p>Raw telephony audio is nasty:</p><ul><li>Codec artifacts (G.711, G.729, Opus all have different quirks)</li><li>Varying sample rates (8kHz telephony vs. 16kHz ideal for STT models)</li><li>Inconsistent gain levels between channels</li><li>Background noise, hold music bleed-through</li></ul><p>We run every chunk through a lightweight normalisation pipeline before it hits Kafka:</p><pre>import numpy as np<br>import librosa</pre><pre>def normalize_audio(pcm_bytes: bytes, source_sr: int = 8000,<br>                    target_sr: int = 16000) -&gt; bytes:<br>    &quot;&quot;&quot;<br>    Resample to target rate, apply loudness normalisation.<br>    Returns raw PCM bytes at target_sr.<br>    &quot;&quot;&quot;<br>    # Convert bytes to float32 numpy array<br>    audio = np.frombuffer(pcm_bytes, dtype=np.int16).astype(np.float32)<br>    audio = audio / 32768.0  # Normalize to [-1.0, 1.0]</pre><pre>    # Resample<br>    if source_sr != target_sr:<br>        audio = librosa.resample(audio, orig_sr=source_sr, target_sr=target_sr)</pre><pre>    # RMS loudness normalisation<br>    rms = np.sqrt(np.mean(audio**2))<br>    if rms &gt; 0:<br>        target_rms = 0.1<br>        audio = audio * (target_rms / rms)</pre><pre>    # Clip to valid range<br>    audio = np.clip(audio, -1.0, 1.0)</pre><pre>    # Convert back to int16 PCM<br>    return (audio * 32768.0).astype(np.int16).tobytes()</pre><h3>4. Streaming Transcription</h3><h3>Why Not Just Use Whisper?</h3><p>OpenAI’s Whisper is extraordinarily accurate. It’s also batch-only (the base model), computationally expensive, and adds significant latency. For a real-time system, you care about <em>time-to-first-token</em> as much as final accuracy.</p><p>We evaluated four options:</p><p>Provider Latency (p50) WER (contact centre) Cost per hour Streaming Deepgram Nova-2 ~300ms 8.2% $0.0059 ✅ Native AssemblyAI Streaming ~600ms 9.1% $0.0065 ✅ Native Google Cloud STT ~450ms 10.4% $0.016 ✅ Whisper Large v3 (self-hosted) ~2.1s 6.8% ~$0.008 (GPU) ❌</p><p>We went with <strong>Deepgram Nova-2</strong> for live streams and <strong>Whisper Large v3</strong> for post-call verification and disputed transcripts. The dual-model approach costs more but gives us a quality backstop.</p><h3>The Streaming Architecture</h3><p>Deepgram’s WebSocket API is straightforward: open a connection, stream PCM audio, receive partial and final transcripts. The complexity is in what you do with them.</p><pre>import asyncio<br>import websockets<br>import json</pre><pre>class StreamingTranscriber:<br>    DEEPGRAM_URL = &quot;wss://api.deepgram.com/v1/listen&quot;</pre><pre>    def __init__(self, api_key: str, on_transcript_callback):<br>        self.api_key = api_key<br>        self.on_transcript = on_transcript_callback<br>        self.partial_buffer = []</pre><pre>    async def transcribe_stream(self, audio_queue: asyncio.Queue,<br>                                 session_id: str):<br>        params = {<br>            &quot;model&quot;: &quot;nova-2&quot;,<br>            &quot;language&quot;: &quot;en-IN&quot;,       # Indian English for our use case<br>            &quot;punctuate&quot;: True,<br>            &quot;diarize&quot;: True,           # We use Deepgram diarization as a hint<br>            &quot;smart_format&quot;: True,<br>            &quot;interim_results&quot;: True,<br>            &quot;endpointing&quot;: 300,        # 300ms silence = utterance end<br>            &quot;vad_events&quot;: True,<br>            &quot;filler_words&quot;: True       # Capture &quot;uh&quot;, &quot;um&quot; for coaching<br>        }</pre><pre>        headers = {&quot;Authorization&quot;: f&quot;Token {self.api_key}&quot;}<br>        url = f&quot;{self.DEEPGRAM_URL}?&quot; + &quot;&amp;&quot;.join(<br>            f&quot;{k}={v}&quot; for k, v in params.items()<br>        )</pre><pre>        async with websockets.connect(url, extra_headers=headers) as ws:<br>            # Send audio and receive transcripts concurrently<br>            await asyncio.gather(<br>                self._send_audio(ws, audio_queue),<br>                self._receive_transcripts(ws, session_id)<br>            )</pre><pre>    async def _receive_transcripts(self, ws, session_id: str):<br>        async for message in ws:<br>            data = json.loads(message)</pre><pre>            if data.get(&quot;type&quot;) == &quot;Results&quot;:<br>                transcript = data[&quot;channel&quot;][&quot;alternatives&quot;][0]<br>                is_final = data.get(&quot;is_final&quot;, False)<br>                speech_final = data.get(&quot;speech_final&quot;, False)</pre><pre>                words = transcript.get(&quot;words&quot;, [])<br>                text = transcript.get(&quot;transcript&quot;, &quot;&quot;).strip()</pre><pre>                if not text:<br>                    continue</pre><pre>                event = {<br>                    &quot;session_id&quot;: session_id,<br>                    &quot;text&quot;: text,<br>                    &quot;words&quot;: words,          # Word-level timestamps<br>                    &quot;confidence&quot;: transcript.get(&quot;confidence&quot;, 0),<br>                    &quot;is_final&quot;: is_final,<br>                    &quot;speech_final&quot;: speech_final,<br>                    &quot;timestamp&quot;: time.time()<br>                }</pre><pre>                await self.on_transcript(event)</pre><p><strong>The partial vs. final transcript distinction is crucial.</strong> Partials arrive fast and let you detect compliance triggers early. Finals are stable and go to the LLM audit engine. We maintain a sliding buffer of the last 30 seconds of partials and replace them as finals arrive.</p><h3>5. Speaker Diarization</h3><p>Diarization — answering “who spoke when?” — sounds solved. It isn’t, especially for telephone audio where:</p><ul><li>Both speakers are on the same channel (mono audio from some systems)</li><li>There’s significant overlap (interruptions, cross-talk)</li><li>Hold music, IVR prompts, and silence all need to be handled</li></ul><h3>Our Hybrid Approach</h3><p>We run <strong>two</strong> diarization signals and merge them:</p><ol><li><strong>Deepgram’s native diarization</strong> — fast, good for clean audio, occasionally confuses speakers during cross-talk</li><li><strong>Pyannote.audio 3.1</strong> — more accurate, especially for overlapping speech, but runs ~2 seconds behind live audio</li></ol><p>We label each word with speaker confidence from both signals and use a voting mechanism:</p><pre>class DiarizationMerger:<br>    &quot;&quot;&quot;<br>    Merges speaker labels from multiple sources using confidence weighting.<br>    Assigns semantic labels (AGENT / CUSTOMER) based on call metadata.<br>    &quot;&quot;&quot;</pre><pre>    def __init__(self, agent_phone: str, customer_phone: str):<br>        self.agent_phone = agent_phone<br>        self.customer_phone = customer_phone<br>        self.speaker_id_map = {}          # Maps diarization IDs to roles</pre><pre>    def merge(self, deepgram_result: dict, pyannote_result: list) -&gt; list:<br>        words_with_speaker = []</pre><pre>        for word in deepgram_result.get(&quot;words&quot;, []):<br>            dg_speaker = word.get(&quot;speaker&quot;)<br>            dg_confidence = word.get(&quot;speaker_confidence&quot;, 0.5)<br>            word_start = word[&quot;start&quot;]<br>            word_end = word[&quot;end&quot;]</pre><pre>            # Find overlapping Pyannote segment<br>            py_speaker = self._find_pyannote_speaker(<br>                pyannote_result, word_start, word_end<br>            )<br>            py_confidence = 0.8  # Pyannote doesn&#39;t expose confidence per-word</pre><pre>            # Weighted vote<br>            if dg_confidence &gt; 0.75:<br>                final_speaker = dg_speaker<br>            elif py_speaker is not None:<br>                final_speaker = py_speaker<br>            else:<br>                final_speaker = dg_speaker</pre><pre>            # Resolve to semantic role<br>            role = self.speaker_id_map.get(<br>                final_speaker,<br>                self._infer_role(final_speaker)<br>            )</pre><pre>            words_with_speaker.append({<br>                **word,<br>                &quot;speaker_id&quot;: final_speaker,<br>                &quot;speaker_role&quot;: role,   # &quot;AGENT&quot; or &quot;CUSTOMER&quot;<br>                &quot;diarization_confidence&quot;: max(dg_confidence, py_confidence)<br>            })</pre><pre>        return words_with_speaker</pre><p>The _infer_role method uses the first 30 seconds of a call to establish which speaker ID corresponds to which role. In a typical inbound call, the agent speaks first with a greeting — this seeding heuristic works ~93% of the time.</p><h3>6. Sentiment Analysis</h3><p>We track sentiment at three granularities:</p><ul><li><strong>Utterance-level</strong>: How does each sentence score?</li><li><strong>Turn-level</strong>: How does sentiment shift as the conversation progresses?</li><li><strong>Call-level</strong>: Overall emotional arc — did the customer end happier than they started?</li></ul><h3>Why Not Just Use GPT for Sentiment?</h3><p>You could — and we did in the prototype. The cost at production scale is prohibitive. 50,000 utterances/day × average 15 tokens × GPT-4 pricing = eye-watering.</p><p>We use a fine-tuned <strong>RoBERTa-base</strong> model trained on contact centre transcripts for real-time utterance scoring, and reserve the LLM for the holistic end-of-call summary.</p><pre>from transformers import pipeline</pre><pre>class SentimentAnalyser:<br>    &quot;&quot;&quot;<br>    Three-class sentiment (positive / neutral / negative) with<br>    contact-centre domain fine-tuning.<br>    Runs on CPU in ~15ms per utterance.<br>    &quot;&quot;&quot;</pre><pre>    LABELS = {<br>        &quot;LABEL_0&quot;: &quot;negative&quot;,<br>        &quot;LABEL_1&quot;: &quot;neutral&quot;,<br>        &quot;LABEL_2&quot;: &quot;positive&quot;<br>    }</pre><pre>    def __init__(self, model_path: str):<br>        self.pipeline = pipeline(<br>            &quot;text-classification&quot;,<br>            model=model_path,<br>            tokenizer=model_path,<br>            device=-1,  # CPU inference for cost control<br>            top_k=None  # Return all class probabilities<br>        )</pre><pre>    def analyse_utterance(self, text: str, speaker_role: str) -&gt; dict:<br>        results = self.pipeline(text[:512])[0]  # Truncate to model max</pre><pre>        scores = {<br>            self.LABELS[r[&quot;label&quot;]]: r[&quot;score&quot;]<br>            for r in results<br>        }</pre><pre>        dominant = max(scores, key=scores.get)<br>        confidence = scores[dominant]</pre><pre>        # Customer sentiment is weighted differently for alerting<br>        alert_threshold = 0.85 if speaker_role == &quot;CUSTOMER&quot; else 0.92</pre><pre>        return {<br>            &quot;text&quot;: text,<br>            &quot;speaker_role&quot;: speaker_role,<br>            &quot;sentiment&quot;: dominant,<br>            &quot;confidence&quot;: confidence,<br>            &quot;scores&quot;: scores,<br>            &quot;alert&quot;: dominant == &quot;negative&quot; and confidence &gt; alert_threshold<br>        }</pre><p><strong>The Emotional Escalation Detector</strong> is the feature managers love most. We track a rolling 60-second sentiment window per participant. If customer sentiment drops by more than 0.4 points on a -1 to +1 scale in under 90 seconds, the system fires a real-time alert to the supervisor console. This catches escalation before it becomes a formal complaint.</p><h3>7. Compliance Checks</h3><p>Compliance is the highest-stakes piece. False negatives cost money. False positives waste analyst time. The challenge is that compliance rules are:</p><ol><li><strong>Deterministic</strong> (must say specific phrases verbatim)</li><li><strong>Contextual</strong> (a phrase means different things in different parts of a call)</li><li><strong>Jurisdiction-specific</strong> (PCI-DSS, GDPR, FCA, TCPA, sector-specific rules)</li><li><strong>Constantly evolving</strong> (regulations change; so do internal policies)</li></ol><h3>The Rules Engine</h3><p>We built a layered rules engine with three tiers:</p><p><strong>Tier 1: Regex/Pattern Matching</strong> — Fast, cheap, zero latency. For exact required phrases.</p><pre>import re<br>from dataclasses import dataclass<br>from typing import Callable</pre><pre>@dataclass<br>class ComplianceRule:<br>    rule_id: str<br>    name: str<br>    description: str<br>    severity: str          # CRITICAL | HIGH | MEDIUM | LOW<br>    phase: str             # OPENING | ANYTIME | CLOSING<br>    check_fn: Callable<br>    remediation: str</pre><pre>class ComplianceEngine:<br>    def __init__(self, ruleset_config: dict):<br>        self.rules = self._load_rules(ruleset_config)<br>        self.triggered = {}   # rule_id -&gt; first trigger timestamp</pre><pre>    def evaluate(self, utterance: dict, call_phase: str,<br>                 call_transcript_so_far: list) -&gt; list:<br>        violations = []</pre><pre>        for rule in self.rules:<br>            if rule.phase != &quot;ANYTIME&quot; and rule.phase != call_phase:<br>                continue</pre><pre>            result = rule.check_fn(utterance, call_transcript_so_far)</pre><pre>            if result.get(&quot;violated&quot;):<br>                if rule.rule_id not in self.triggered:<br>                    self.triggered[rule.rule_id] = utterance[&quot;timestamp&quot;]</pre><pre>                violations.append({<br>                    &quot;rule_id&quot;: rule.rule_id,<br>                    &quot;rule_name&quot;: rule.name,<br>                    &quot;severity&quot;: rule.severity,<br>                    &quot;detail&quot;: result.get(&quot;detail&quot;),<br>                    &quot;utterance_ref&quot;: utterance[&quot;utterance_id&quot;],<br>                    &quot;first_occurrence&quot;: self.triggered[rule.rule_id],<br>                    &quot;remediation&quot;: rule.remediation<br>                })</pre><pre>        return violations</pre><pre># Example rule definitions<br>RULES = [<br>    ComplianceRule(<br>        rule_id=&quot;OPEN_001&quot;,<br>        name=&quot;Call Recording Disclosure&quot;,<br>        description=&quot;Agent must disclose call recording at call start&quot;,<br>        severity=&quot;CRITICAL&quot;,<br>        phase=&quot;OPENING&quot;,<br>        check_fn=lambda utt, hist: {<br>            &quot;violated&quot;: not any(<br>                re.search(<br>                    r&quot;(may be recorded|is being recorded|recorded for quality)&quot;,<br>                    h[&quot;text&quot;], re.IGNORECASE<br>                )<br>                for h in hist[:10]  # Must appear in first 10 utterances<br>                if h[&quot;speaker_role&quot;] == &quot;AGENT&quot;<br>            )<br>        },<br>        remediation=&quot;Agent must state recording disclosure within first 30 seconds&quot;<br>    ),<br>    ComplianceRule(<br>        rule_id=&quot;PCI_001&quot;,<br>        name=&quot;PCI Card Number Prohibition&quot;,<br>        description=&quot;Agent must never read or confirm full card numbers verbally&quot;,<br>        severity=&quot;CRITICAL&quot;,<br>        phase=&quot;ANYTIME&quot;,<br>        check_fn=lambda utt, hist: {<br>            &quot;violated&quot;: bool(<br>                re.search(r&quot;\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b&quot;,<br>                          utt[&quot;text&quot;])<br>            ) and utt[&quot;speaker_role&quot;] == &quot;AGENT&quot;,<br>            &quot;detail&quot;: &quot;Potential card number detected in agent speech&quot;<br>        },<br>        remediation=&quot;Never verbalize card numbers. Use payment IVR for card capture.&quot;<br>    ),<br>]</pre><p><strong>Tier 2: Semantic Matching with Embeddings</strong> — For rules that allow paraphrasing. “You must inform the customer of their right to cancel” doesn’t have to use those exact words.</p><p>We embed the required concept and compute cosine similarity against utterance embeddings. Threshold tuning is an art — too low and you miss violations, too high and you flag compliant agents.</p><p><strong>Tier 3: LLM Judgment</strong> — For ambiguous, context-dependent situations. We do not use LLMs for real-time compliance checks (latency is too high). We flag potential issues in real time with Tiers 1 and 2, then use the LLM in post-call review to make the final determination.</p><h3>8. LLM-Based Auditing</h3><h3>What the LLM is Actually Doing</h3><p>Every completed call generates an audit request. The LLM receives:</p><ol><li>The full transcript (with speaker labels and timestamps)</li><li>Call metadata (agent ID, queue, call type, duration)</li><li>Sentiment trajectory</li><li>Pre-computed compliance flags</li><li>A structured scoring rubric</li></ol><p>The LLM’s job is to fill out the rubric, provide evidence citations (exact quotes and timestamps), and write a coaching narrative.</p><h3>Prompt Engineering for Structured Audit Output</h3><p>The most important lesson we learned: <strong>treat the LLM as a structured data generator, not a free-form reasoner.</strong> Ask for JSON. Validate it. Retry on malformed output.</p><pre>AUDIT_SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are an expert contact centre quality assurance auditor.<br>Your role is to evaluate agent performance against a defined rubric.<br>Be precise, cite specific transcript moments, and be fair.<br>Do not infer intent — evaluate only what was said and done.<br>Return ONLY valid JSON matching the schema provided. No preamble, no markdown.<br>&quot;&quot;&quot;</pre><pre>AUDIT_USER_PROMPT_TEMPLATE = &quot;&quot;&quot;<br>## Call Information<br>- Call ID: {call_id}<br>- Date/Time: {call_datetime}<br>- Duration: {duration_seconds}s<br>- Agent ID: {agent_id}<br>- Queue: {queue_name}<br>- Call Type: {call_type}</pre><pre>## Transcript<br>{formatted_transcript}</pre><pre>## Pre-flagged Compliance Events<br>{compliance_flags_json}</pre><pre>## Sentiment Summary<br>{sentiment_summary_json}</pre><pre>## Scoring Rubric<br>Evaluate the agent on each dimension below. For each:<br>- Score 1-5 (1=Poor, 3=Meets Standard, 5=Exceptional)<br>- Provide a single sentence justification<br>- Cite specific timestamp range(s) as evidence</pre><pre>Dimensions:<br>1. Greeting &amp; Introduction (Was the opening professional and complete?)<br>2. Active Listening (Did the agent demonstrate understanding and empathy?)<br>3. Problem Resolution (Was the issue handled competently and thoroughly?)<br>4. Compliance Adherence (Were all mandatory statements made correctly?)<br>5. Communication Clarity (Was the agent easy to understand and professional?)<br>6. Objection Handling (How well did the agent handle pushback or complaints?)<br>7. Closing (Was the call wrapped up professionally with next steps?)</pre><pre>## Required JSON Output Schema<br>{{<br>  &quot;call_id&quot;: &quot;string&quot;,<br>  &quot;audit_timestamp&quot;: &quot;ISO8601 string&quot;,<br>  &quot;overall_score&quot;: &quot;float (1.0-5.0, weighted average)&quot;,<br>  &quot;pass_fail&quot;: &quot;PASS | FAIL | NEEDS_REVIEW&quot;,<br>  &quot;dimensions&quot;: [<br>    {{<br>      &quot;name&quot;: &quot;string&quot;,<br>      &quot;score&quot;: &quot;integer (1-5)&quot;,<br>      &quot;justification&quot;: &quot;string (max 100 words)&quot;,<br>      &quot;evidence_timestamps&quot;: [&quot;HH:MM:SS-HH:MM:SS&quot;, ...]<br>    }}<br>  ],<br>  &quot;compliance_summary&quot;: {{<br>    &quot;critical_violations&quot;: [&quot;string&quot;, ...],<br>    &quot;warnings&quot;: [&quot;string&quot;, ...],<br>    &quot;all_clear_items&quot;: [&quot;string&quot;, ...]<br>  }},<br>  &quot;coaching_narrative&quot;: &quot;string (150-300 words, constructive tone)&quot;,<br>  &quot;highlights&quot;: [&quot;string&quot;, ...],<br>  &quot;improvement_areas&quot;: [&quot;string&quot;, ...]<br>}}<br>&quot;&quot;&quot;</pre><h3>Handling LLM Reliability at Scale</h3><p>LLMs fail. They produce malformed JSON, hallucinate timestamps, or occasionally confidently score a call that was actually silence. Our reliability layer:</p><pre>import json<br>from tenacity import retry, stop_after_attempt, wait_exponential</pre><pre>class LLMAuditEngine:<br>    def __init__(self, primary_client, fallback_client):<br>        self.primary = primary_client    # GPT-4o<br>        self.fallback = fallback_client  # Claude 3.5 Sonnet</pre><pre>    @retry(<br>        stop=stop_after_attempt(3),<br>        wait=wait_exponential(multiplier=1, min=2, max=10)<br>    )<br>    async def audit_call(self, call_data: dict) -&gt; dict:<br>        prompt = self._build_prompt(call_data)</pre><pre>        try:<br>            response = await self.primary.complete(<br>                system=AUDIT_SYSTEM_PROMPT,<br>                user=prompt,<br>                temperature=0.1,       # Low temperature for consistency<br>                max_tokens=2000,<br>                response_format={&quot;type&quot;: &quot;json_object&quot;}<br>            )<br>            return self._validate_and_parse(response)</pre><pre>        except (json.JSONDecodeError, ValidationError) as e:<br>            logger.warning(f&quot;Primary LLM output invalid, trying fallback: {e}&quot;)<br>            response = await self.fallback.complete(<br>                system=AUDIT_SYSTEM_PROMPT,<br>                user=prompt + &quot;\n\nIMPORTANT: Previous attempt returned invalid JSON. Ensure output is valid JSON only.&quot;,<br>                temperature=0.05<br>            )<br>            return self._validate_and_parse(response)</pre><pre>    def _validate_and_parse(self, raw_response: str) -&gt; dict:<br>        # Strip markdown fences if present<br>        cleaned = raw_response.strip()<br>        if cleaned.startswith(&quot;```&quot;):<br>            cleaned = re.sub(r&quot;```(?:json)?\n?&quot;, &quot;&quot;, cleaned).strip()</pre><pre>        parsed = json.loads(cleaned)</pre><pre>        # Schema validation<br>        assert &quot;overall_score&quot; in parsed<br>        assert 1.0 &lt;= float(parsed[&quot;overall_score&quot;]) &lt;= 5.0<br>        assert parsed[&quot;pass_fail&quot;] in [&quot;PASS&quot;, &quot;FAIL&quot;, &quot;NEEDS_REVIEW&quot;]<br>        assert len(parsed.get(&quot;dimensions&quot;, [])) == 7</pre><pre>        return parsed</pre><p>We run both GPT-4o and Claude 3.5 Sonnet on a 5% sample of calls and compare scores. The inter-rater agreement calibration caught a systematic bias in one model’s empathy scoring early on.</p><h3>9. Real-Time Dashboards</h3><p>The dashboard has three audiences with different needs:</p><p><strong>1. Supervisors (Live View)</strong> — Need to see what’s happening right now. Which calls are in progress? Any active escalations? Who needs intervention?</p><p><strong>2. QA Analysts (Review Queue)</strong> — Need a list of audited calls sorted by risk. Easy playback, side-by-side transcript, ability to override LLM scores.</p><p><strong>3. Management (Trends)</strong> — Weekly compliance rates, agent score distributions, common failure patterns, correlation with CSAT.</p><h3>Real-Time Data Flow</h3><p>The key insight is separating the <strong>live signal</strong> from the <strong>historical query</strong> plane:</p><pre>LIVE SIGNAL PATH (sub-second latency):<br>  Compliance Event → Kafka → WebSocket → Supervisor Console</pre><pre>AUDIT COMPLETION PATH (2-5 minutes after call end):<br>  LLM Audit Result → Kafka → ClickHouse + S3 → QA Dashboard</pre><pre>ANALYTICS PATH (batch):<br>  ClickHouse → dbt models → BI Dashboard</pre><p>We use <strong>ClickHouse</strong> for the query layer instead of the obvious choice (Elasticsearch or Postgres) because aggregation queries over millions of calls with complex filters run in sub-second time. The schema is append-only, which plays to ClickHouse’s strengths perfectly.</p><pre>-- ClickHouse table for call audit results<br>CREATE TABLE call_audits<br>(<br>    call_id           String,<br>    audit_timestamp   DateTime64(3),<br>    agent_id          String,<br>    queue_name        String,<br>    call_duration_sec UInt32,<br>    overall_score     Float32,<br>    pass_fail         Enum8(&#39;PASS&#39;=1, &#39;FAIL&#39;=2, &#39;NEEDS_REVIEW&#39;=3),<br>    -- Dimension scores<br>    score_greeting    UInt8,<br>    score_listening   UInt8,<br>    score_resolution  UInt8,<br>    score_compliance  UInt8,<br>    score_clarity     UInt8,<br>    score_objection   UInt8,<br>    score_closing     UInt8,<br>    -- Compliance<br>    critical_violations_count UInt8,<br>    warning_count     UInt8,<br>    -- Sentiment<br>    customer_sentiment_start Float32,<br>    customer_sentiment_end   Float32,<br>    sentiment_delta          Float32,<br>    -- Full JSON for drill-down<br>    audit_json        String<br>)<br>ENGINE = MergeTree()<br>ORDER BY (agent_id, audit_timestamp)<br>PARTITION BY toYYYYMM(audit_timestamp);</pre><p>This schema lets us answer questions like “Show me all calls where customer sentiment dropped and the compliance score was below 3” in under 200ms over 90 days of data.</p><h3>10. Latency Optimization</h3><p>Here’s where the rubber meets the road. Our SLA targets:</p><ul><li>First compliance flag to supervisor: <strong>&lt; 1 second</strong> from utterance completion</li><li>Sentiment alert: <strong>&lt; 500ms</strong> from utterance completion</li><li>Full LLM audit report: <strong>&lt; 3 minutes</strong> from call end</li><li>Dashboard refresh: <strong>&lt; 200ms</strong> for live view</li></ul><h3>What Actually Moves the Needle</h3><p><strong>1. Chunk size vs. latency trade-off in STT</strong></p><p>Deepgram’s VAD (Voice Activity Detection) with endpointing=300 means we fire on 300ms of silence. Lower values give faster results but produce more fragmented utterances, which hurts sentiment accuracy. We settled on 300ms after testing 100ms through 800ms.</p><p><strong>2. Parallel processing, not sequential pipelines</strong></p><p>Our naive first implementation was sequential: transcribe → diarize → sentiment → compliance. Each step waited for the previous. We refactored to a fan-out pattern on Kafka: the enriched transcript chunk is published once, and sentiment analysis, compliance checking, and database writes all consume it independently.</p><p><strong>3. Model warm-up and pre-loading</strong></p><p>Cold-starting a PyTorch model kills your latency. We keep sentiment and embedding models loaded in memory on a pool of workers with health-checked process managers. Workers are pre-warmed by running dummy inference on startup.</p><p><strong>4. LLM prompt compression</strong></p><p>Long transcripts hit token limits and increase cost and latency. We apply a transcript compression step for calls over 30 minutes:</p><pre>def compress_transcript(transcript: list, max_tokens: int = 6000) -&gt; str:<br>    &quot;&quot;&quot;<br>    Progressively compress long transcripts while preserving:<br>    - Opening and closing (always kept verbatim)<br>    - Moments with compliance flags (always kept verbatim)<br>    - Moments with high sentiment variance<br>    - Otherwise: summarise middle segments<br>    &quot;&quot;&quot;<br>    protected_utterances = set()</pre><pre>    # Always protect first/last 5 utterances<br>    for i in list(range(5)) + list(range(-5, 0)):<br>        protected_utterances.add(i)</pre><pre>    # Protect compliance-flagged utterances<br>    for i, utt in enumerate(transcript):<br>        if utt.get(&quot;compliance_flags&quot;):<br>            protected_utterances.add(i)</pre><pre>    # Estimate token count<br>    full_text = format_transcript(transcript)<br>    if estimate_tokens(full_text) &lt;= max_tokens:<br>        return full_text  # No compression needed</pre><pre>    # Summarise non-protected segments using a cheaper model<br>    # ... (implementation continues)</pre><p><strong>5. Speculative compliance checking</strong></p><p>We don’t wait for a complete utterance to check for PCI violations. We run the regex tier on partial transcripts every 2 seconds. This means we can alert a supervisor mid-utterance if an agent starts reading out card numbers.</p><h3>11. Production Challenges</h3><h3>Challenge 1: Transcript Drift in Long Calls</h3><p>Streaming transcription is stateless. Each utterance is transcribed in isolation. For long calls (60+ minutes), accumulated diarization drift means Speaker 1 might silently flip to Speaker 2 mid-call without any model signal. We detected this only when QA analysts flagged audits where the agent appeared to have said things clearly said by the customer.</p><p><strong>Fix:</strong> We run a full-call re-diarization pass using Pyannote on the complete audio after the call ends, and reconcile it against the streaming transcript. Any speaker label conflicts trigger a recomputation flag on the audit.</p><h3>Challenge 2: LLM Score Consistency</h3><p>We discovered our LLM audit scores had a ~15% variance when we ran the same call through the same prompt twice. Temperature=0 helped but didn’t eliminate it. More alarming: when we rotated between GPT-4o and Claude for load balancing, we got systematically different scores on the same calls.</p><p><strong>Fix:</strong> We defined a “calibration call set” of 500 calls that human QA analysts had manually scored. We adjusted our prompts and scoring anchors until both models produced scores within 0.3 points of the human baseline on 90% of calibration calls. We now run monthly calibration checks.</p><h3>Challenge 3: Audio Quality Degradation</h3><p>Real telephony audio is often worse than your test data. We encountered:</p><ul><li><strong>Echo cancellation artifacts</strong> — making both speakers sound like they’re in a tunnel</li><li><strong>Codec transcoding chains</strong> — audio passed through 3 codec conversions, each adding artifacts</li><li><strong>Half-duplex mode</strong> — some legacy systems cut off one speaker when the other is speaking</li></ul><p><strong>Fix:</strong> We built an audio quality scoring module that flags calls with low estimated SNR (Signal-to-Noise Ratio). These calls go to Whisper for transcription (better at noisy audio) and have their audit results marked with a “low audio quality — reduced confidence” flag.</p><h3>Challenge 4: Handling Silence, Hold Music, and IVR</h3><p>Our compliance rules had a “window of opportunity” — phrases must appear within N seconds of call start. Hold music and IVR navigation at the beginning of calls kept eating into that window.</p><p><strong>Fix:</strong> We added silence/hold/IVR detection using a lightweight audio classifier. These segments are excluded from the compliance window calculation.</p><h3>Challenge 5: Scale — Kafka Consumer Lag</h3><p>At peak hours (11am-2pm for our customer), we were processing 800 concurrent calls. Our Kafka consumers fell behind, creating a 4-minute lag in compliance alerts.</p><p><strong>Fix:</strong> Horizontal scaling of consumers alone wasn’t enough. We partitioned the Kafka topic by call_id (ensuring all chunks for a call go to the same partition and consumer), then scaled to 48 consumer pods. We also added a priority lane for compliance-critical events that bypasses the main topic.</p><h3>12. Lessons Learned</h3><h3>1. Build for the Analyst, Not the Algorithm</h3><p>The most sophisticated ML model in the world is worthless if a QA analyst can’t understand why it flagged something. We invested heavily in <strong>explainability</strong> — every audit result includes exact transcript citations, timestamps, and reasoning. Analysts adopted the tool because they could trust it.</p><h3>2. Compliance is Binary; Quality is a Spectrum</h3><p>Your compliance rules engine needs to be deterministic and auditable. You must be able to explain every flag to a regulator. Your quality scoring can be probabilistic and LLM-driven. Don’t conflate them.</p><h3>3. The Cold Start Problem is Real</h3><p>Your first LLM audit prompt will not be good enough for production. Plan for at least 6 weeks of calibration with real QA analysts reviewing LLM outputs, providing feedback, and helping you refine rubrics.</p><h3>4. Telephony is a Wild West</h3><p>Every telephony vendor has quirks. SIPREC implementations differ from the spec. Audio codec chains introduce unexpected artifacts. Build an audio quality pipeline early and make it a first-class citizen, not an afterthought.</p><h3>5. Start with Post-Call, Then Go Real-Time</h3><p>We built the streaming architecture first because it was technically exciting. In hindsight, building the post-call pipeline first would have let us validate the LLM auditing and compliance logic at low cost before committing to the complex streaming infrastructure.</p><h3>6. Cost Spirals Fast</h3><p>At 50,000 calls/day × 5 minutes average × GPT-4o pricing for audit prompts, you’re looking at significant monthly LLM spend. Model the cost before you commit to an architecture. We ended up using GPT-4o only for calls flagged as high-risk or above a duration threshold, and a fine-tuned smaller model for everything else.</p><h3>7. Human Override is Not Optional</h3><p>Every audit score must be overrideable by a human analyst. The system’s feedback loop depends on it. These overrides become your training data for prompt improvement and, eventually, fine-tuning.</p><h3>13. What’s Next</h3><p>We’re actively working on:</p><ul><li><strong>Proactive coaching prompts</strong> — Real-time suggestions to agents during the call (“The customer seems frustrated — try acknowledging their wait time”)</li><li><strong>Fine-tuned audit model</strong> — Training a domain-specific model on our accumulated human-verified audit data to reduce LLM costs by ~70%</li><li><strong>Multi-language support</strong> — Extending to Hindi, Tamil, and Telugu for our Indian market clients</li><li><strong>Predictive escalation</strong> — Using the first 90 seconds of a call to predict likelihood of escalation, enabling proactive supervisor intervention</li><li><strong>Voice biometrics integration</strong> — Detecting agent substitution fraud (one agent logging in, another handling the call)</li></ul><h3>14. Security, Privacy &amp; Data Governance</h3><p>This section is the one most engineering blog posts skip. Don’t skip it in real life — it will find you during procurement, a security audit, or a regulatory review at the worst possible moment.</p><h3>The Privacy Paradox of Call Auditing</h3><p>You’re building a system whose entire purpose is to listen to conversations. That is, by definition, a system with enormous privacy implications. Every design decision has a privacy dimension.</p><p>Here are the questions you’ll be asked, and the answers we baked into the architecture:</p><p><strong>Q: Where does call audio get stored? For how long?</strong></p><p>We store raw audio in S3 with a 90-day retention policy, enforced by S3 lifecycle rules. After 90 days, audio is deleted. Transcripts are retained for 2 years (regulatory requirement in our sector). Audit results are retained indefinitely. Audio is never used for model training without explicit customer consent and a separate DPA amendment.</p><pre># S3 lifecycle policy applied programmatically at bucket creation<br>AUDIO_LIFECYCLE_POLICY = {<br>    &quot;Rules&quot;: [<br>        {<br>            &quot;ID&quot;: &quot;AudioRetention90Days&quot;,<br>            &quot;Status&quot;: &quot;Enabled&quot;,<br>            &quot;Filter&quot;: {&quot;Prefix&quot;: &quot;raw-audio/&quot;},<br>            &quot;Expiration&quot;: {&quot;Days&quot;: 90},<br>            &quot;Transitions&quot;: [<br>                {<br>                    &quot;Days&quot;: 30,<br>                    &quot;StorageClass&quot;: &quot;STANDARD_IA&quot;  # Cost optimisation<br>                }<br>            ]<br>        }<br>    ]<br>}</pre><p><strong>Q: Is call audio sent to third-party STT providers?</strong></p><p>Yes — and this is a significant vendor risk item. Deepgram’s enterprise agreement includes a data processing addendum (DPA) with zero data retention on their side. Audio is streamed, transcribed, and not stored by the vendor. Verify this contractually for every provider you use — the free-tier terms are very different.</p><p><strong>Q: How is PII handled in transcripts?</strong></p><p>We run a PII redaction pass on all final transcripts before they enter long-term storage. This uses a combination of:</p><ul><li>Regex patterns for card numbers, sort codes, NI numbers, dates of birth</li><li>Named entity recognition (NER) for person names, addresses</li><li>Custom entity detection for domain-specific sensitive identifiers</li></ul><pre>import re<br>from presidio_analyzer import AnalyzerEngine<br>from presidio_anonymizer import AnonymizerEngine</pre><pre>class PIIRedactor:<br>    &quot;&quot;&quot;<br>    Two-pass PII redaction:<br>    Pass 1: Fast regex for structured PII (card numbers, NI, phone)<br>    Pass 2: Presidio NER for unstructured PII (names, addresses)<br>    Applied to transcripts before long-term storage.<br>    &quot;&quot;&quot;</pre><pre>    def __init__(self):<br>        self.analyzer = AnalyzerEngine()<br>        self.anonymizer = AnonymizerEngine()</pre><pre>        self.regex_patterns = [<br>            # UK card numbers<br>            (r&#39;\b\d{4}[\s\-]?\d{4}[\s\-]?\d{4}[\s\-]?\d{4}\b&#39;, &#39;[CARD_NUMBER]&#39;),<br>            # UK National Insurance<br>            (r&#39;\b[A-Z]{2}\d{6}[A-D]\b&#39;, &#39;[NI_NUMBER]&#39;),<br>            # UK sort codes<br>            (r&#39;\b\d{2}[\s\-]\d{2}[\s\-]\d{2}\b&#39;, &#39;[SORT_CODE]&#39;),<br>            # UK phone numbers<br>            (r&#39;\b(?:07\d{9}|0[1-9]\d{8,9}|\+44\d{10})\b&#39;, &#39;[PHONE_NUMBER]&#39;),<br>            # Dates of birth<br>            (r&#39;\b(?:\d{1,2}[\/\-\.]\d{1,2}[\/\-\.]\d{2,4})\b&#39;, &#39;[DATE]&#39;),<br>        ]</pre><pre>    def redact(self, text: str) -&gt; tuple[str, list]:<br>        &quot;&quot;&quot;Returns (redacted_text, list_of_redactions)&quot;&quot;&quot;<br>        redactions = []</pre><pre>        # Pass 1: Regex<br>        for pattern, replacement in self.regex_patterns:<br>            matches = list(re.finditer(pattern, text, re.IGNORECASE))<br>            for match in reversed(matches):  # Reverse to preserve indices<br>                redactions.append({<br>                    &quot;original&quot;: match.group(),<br>                    &quot;replacement&quot;: replacement,<br>                    &quot;start&quot;: match.start(),<br>                    &quot;end&quot;: match.end(),<br>                    &quot;method&quot;: &quot;regex&quot;<br>                })<br>                text = text[:match.start()] + replacement + text[match.end():]</pre><pre>        # Pass 2: Presidio NER<br>        results = self.analyzer.analyze(<br>            text=text,<br>            language=&quot;en&quot;,<br>            entities=[&quot;PERSON&quot;, &quot;LOCATION&quot;, &quot;EMAIL_ADDRESS&quot;, &quot;UK_NHS&quot;]<br>        )</pre><pre>        anonymized = self.anonymizer.anonymize(<br>            text=text,<br>            analyzer_results=results<br>        )</pre><pre>        return anonymized.text, redactions</pre><p><strong>Q: Who can access what?</strong></p><p>We implement RBAC with four roles:</p><p>Role Access Agent Own call scores only (no raw audio) Team Leader Team member scores + flagged calls QA Analyst All calls + raw audio + override ability Compliance Officer Compliance flags + exports + full audit trail Admin Full system access + configuration</p><p>Every access event — who opened which call recording, when — is logged immutably to a separate audit table. This is non-negotiable when handling regulated financial services calls.</p><h3>Encryption at Every Layer</h3><ul><li><strong>In transit:</strong> TLS 1.3 for all API calls and WebSocket connections. No TLS 1.0/1.1.</li><li><strong>At rest:</strong> S3 server-side encryption (SSE-S3 for transcripts, SSE-KMS with CMK for audio). DynamoDB encryption at rest enabled. ClickHouse volumes encrypted at the block level.</li><li><strong>In memory:</strong> Audio chunks are never written to disk unencrypted. We use mlock for sensitive Python processes to prevent swap-to-disk.</li><li><strong>In transit between internal services:</strong> mTLS enforced by Istio service mesh. No cleartext service-to-service communication.</li></ul><h3>15. The Complete Data Model</h3><p>One thing no engineering post ever shows is the actual data model. Here’s ours, simplified but accurate:</p><pre>┌─────────────────┐         ┌──────────────────────┐<br>│     calls        │         │  call_audio_segments  │<br>│─────────────────│         │──────────────────────│<br>│ call_id (PK)    │────────►│ segment_id (PK)       │<br>│ agent_id        │         │ call_id (FK)           │<br>│ customer_id     │         │ s3_key                 │<br>│ queue_id        │         │ start_offset_ms        │<br>│ start_time      │         │ end_offset_ms          │<br>│ end_time        │         │ codec                  │<br>│ duration_sec    │         │ sample_rate            │<br>│ telephony_ref   │         │ channel (AGENT|CUST)   │<br>│ call_type       │         │ created_at             │<br>│ disposition     │         └──────────────────────┘<br>│ audio_quality   │<br>│ status          │         ┌──────────────────────┐<br>└─────────────────┘         │     utterances        │<br>         │                  │──────────────────────│<br>         └─────────────────►│ utterance_id (PK)     │<br>                            │ call_id (FK)           │<br>                            │ speaker_role           │<br>                            │ speaker_id             │<br>                            │ text_original          │<br>                            │ text_redacted          │<br>                            │ start_ms               │<br>                            │ end_ms                 │<br>                            │ confidence             │<br>                            │ sentiment              │<br>                            │ sentiment_score        │<br>                            │ is_final               │<br>                            │ word_data (JSONB)      │<br>                            └──────────────────────┘<br>                                       │<br>                            ┌──────────────────────┐<br>                            │  compliance_events    │<br>                            │──────────────────────│<br>                            │ event_id (PK)         │<br>                            │ call_id (FK)          │<br>                            │ utterance_id (FK)     │<br>                            │ rule_id               │<br>                            │ rule_name             │<br>                            │ severity              │<br>                            │ detected_at           │<br>                            │ detail                │<br>                            │ analyst_override      │<br>                            │ override_by           │<br>                            │ override_reason       │<br>                            └──────────────────────┘</pre><pre>┌─────────────────────────────────────────┐<br>│              call_audits                 │<br>│─────────────────────────────────────────│<br>│ audit_id (PK)                           │<br>│ call_id (FK)                            │<br>│ audit_version                           │<br>│ model_used                              │<br>│ prompt_version                          │<br>│ overall_score (1.0-5.0)                 │<br>│ pass_fail                               │<br>│ dimension_scores (JSONB)                │<br>│ compliance_summary (JSONB)              │<br>│ coaching_narrative                      │<br>│ highlights (JSONB array)                │<br>│ improvement_areas (JSONB array)         │<br>│ llm_tokens_used                         │<br>│ llm_cost_usd                            │<br>│ processing_time_ms                      │<br>│ human_reviewed                          │<br>│ human_score_override                    │<br>│ human_reviewer_id                       │<br>│ human_review_notes                      │<br>│ created_at                              │<br>└─────────────────────────────────────────┘</pre><p>The audit_version and prompt_version columns are critical. When you improve your LLM prompt, old audits shouldn&#39;t be compared to new ones without this context. We version every prompt change and store the version with every audit result.</p><h3>16. Testing Strategy</h3><p>Production AI systems need a testing philosophy that goes beyond unit tests. Here’s our full testing pyramid:</p><h3>Level 1: Unit Tests — Component Isolation</h3><p>Test each component with known inputs and expected outputs.</p><pre>import pytest</pre><pre>class TestComplianceEngine:<br>    @pytest.fixture<br>    def engine(self):<br>        return ComplianceEngine(ruleset_config=TEST_RULESET)</pre><pre>    def test_recording_disclosure_detected(self, engine):<br>        &quot;&quot;&quot;<br>        Agent says the recording phrase — should NOT trigger violation.<br>        &quot;&quot;&quot;<br>        history = [<br>            {&quot;speaker_role&quot;: &quot;AGENT&quot;,<br>             &quot;text&quot;: &quot;This call may be recorded for quality purposes.&quot;,<br>             &quot;utterance_id&quot;: &quot;u001&quot;}<br>        ]<br>        utterance = {&quot;speaker_role&quot;: &quot;AGENT&quot;,<br>                     &quot;text&quot;: &quot;How can I help you today?&quot;,<br>                     &quot;utterance_id&quot;: &quot;u002&quot;}</pre><pre>        violations = engine.evaluate(utterance, &quot;OPENING&quot;, history)<br>        compliance_violations = [v for v in violations<br>                                  if v[&quot;rule_id&quot;] == &quot;OPEN_001&quot;]<br>        assert len(compliance_violations) == 0</pre><pre>    def test_recording_disclosure_missing(self, engine):<br>        &quot;&quot;&quot;<br>        Agent skips disclosure — MUST trigger violation.<br>        &quot;&quot;&quot;<br>        history = [<br>            {&quot;speaker_role&quot;: &quot;AGENT&quot;,<br>             &quot;text&quot;: &quot;Hello, thank you for calling. How can I help?&quot;,<br>             &quot;utterance_id&quot;: &quot;u001&quot;}<br>        ]<br>        # Simulate 10 utterances passing without disclosure<br>        full_history = history * 10</pre><pre>        violations = engine.evaluate(<br>            full_history[-1], &quot;OPENING&quot;, full_history<br>        )<br>        rule_hit = any(v[&quot;rule_id&quot;] == &quot;OPEN_001&quot; for v in violations)<br>        assert rule_hit, &quot;Should flag missing recording disclosure&quot;</pre><pre>    def test_pci_card_number_detected(self, engine):<br>        utterance = {<br>            &quot;speaker_role&quot;: &quot;AGENT&quot;,<br>            &quot;text&quot;: &quot;Your card ending in 4532 1234 5678 9010 has been verified.&quot;,<br>            &quot;utterance_id&quot;: &quot;u010&quot;<br>        }<br>        violations = engine.evaluate(utterance, &quot;ANYTIME&quot;, [])<br>        pci_violations = [v for v in violations if v[&quot;rule_id&quot;] == &quot;PCI_001&quot;]<br>        assert len(pci_violations) == 1<br>        assert pci_violations[0][&quot;severity&quot;] == &quot;CRITICAL&quot;</pre><h3>Level 2: Integration Tests — Pipeline Flows</h3><p>Test that components work correctly when wired together. We use a test Kafka cluster (via testcontainers) and mock STT responses.</p><pre>@pytest.mark.asyncio<br>async def test_end_to_end_transcript_pipeline():<br>    &quot;&quot;&quot;<br>    Simulate a call session: audio in → transcript out → compliance flags.<br>    &quot;&quot;&quot;<br>    async with TestKafkaCluster() as kafka:<br>        producer = await kafka.get_producer()<br>        consumer = await kafka.get_consumer(&quot;compliance_events&quot;)</pre><pre>        # Simulate an audio chunk from SIPREC<br>        test_audio_event = {<br>            &quot;session_id&quot;: &quot;test-session-001&quot;,<br>            &quot;call_id&quot;: &quot;call-test-001&quot;,<br>            &quot;participant_type&quot;: &quot;AGENT&quot;,<br>            &quot;audio_b64&quot;: load_test_audio(&quot;greeting_no_disclosure.wav&quot;),<br>            &quot;timestamp&quot;: time.time()<br>        }</pre><pre>        await producer.send(&quot;raw_audio&quot;, value=test_audio_event)</pre><pre>        # Wait for compliance event<br>        event = await asyncio.wait_for(consumer.receive(), timeout=10.0)<br>        assert event[&quot;call_id&quot;] == &quot;call-test-001&quot;<br>        assert any(e[&quot;rule_id&quot;] == &quot;OPEN_001&quot; for e in event[&quot;violations&quot;])</pre><h3>Level 3: LLM Evaluation Tests — The Hardest Part</h3><p>Testing LLM outputs is fundamentally different from testing deterministic code. We use three approaches:</p><p><strong>3a. Golden Set Regression Tests</strong></p><p>A curated set of 100 calls with known “correct” audit scores (human-verified). On every prompt change, we run the full set and require:</p><ul><li>Mean score deviation &lt; 0.3 points vs. baseline</li><li>No regression in compliance detection recall</li><li>Pass/fail classification accuracy &gt; 92%</li></ul><pre>def run_golden_set_evaluation(prompt_version: str) -&gt; EvalReport:<br>    golden_calls = load_golden_set()  # 100 pre-scored calls<br>    results = []</pre><pre>    for call in golden_calls:<br>        audit = run_llm_audit(call, prompt_version=prompt_version)<br>        results.append({<br>            &quot;call_id&quot;: call.call_id,<br>            &quot;human_score&quot;: call.human_score,<br>            &quot;llm_score&quot;: audit.overall_score,<br>            &quot;delta&quot;: abs(call.human_score - audit.overall_score),<br>            &quot;pass_fail_match&quot;: call.pass_fail == audit.pass_fail<br>        })</pre><pre>    return EvalReport(<br>        prompt_version=prompt_version,<br>        mean_delta=statistics.mean(r[&quot;delta&quot;] for r in results),<br>        pass_fail_accuracy=sum(r[&quot;pass_fail_match&quot;] for r in results) / len(results),<br>        p95_delta=statistics.quantiles([r[&quot;delta&quot;] for r in results], n=20)[18]<br>    )</pre><p><strong>3b. Adversarial Test Cases</strong></p><p>We maintain a set of “trick” calls designed to fool the LLM — calls where a compliant-sounding agent is actually violating policy, and calls where a rule-breaking-sounding agent is actually fine. These probe for hallucination and false confidence.</p><p><strong>3c. Model vs. Model Disagreement Monitoring</strong></p><p>In production, we log cases where GPT-4o and Claude disagree by more than 1 point on the same call. These disagreements are surfaced weekly for manual review — they’re almost always the most interesting edge cases and become the next round of golden set additions.</p><h3>Level 4: Load Tests</h3><p>We simulate peak load with real call audio and measure:</p><ul><li>Kafka consumer lag under 800 concurrent sessions</li><li>p99 STT latency</li><li>LLM audit queue depth</li><li>Dashboard refresh latency under 1000 concurrent viewers</li></ul><p>We run these tests in a staging environment that mirrors production at 1:10 scale every two weeks.</p><h3>17. CI/CD and Deployment</h3><h3>The Multi-Model Deployment Problem</h3><p>Unlike a traditional microservice, our system has <strong>model weights</strong> as part of its deployment artifact. When we update the sentiment model or the embedding model, that’s a deployment event that needs to be treated as carefully as a code deployment.</p><p>We have separate versioning and release pipelines for:</p><ol><li><strong>Application code</strong> — Standard GitOps with ArgoCD</li><li><strong>ML models</strong> — Model registry (MLflow) with canary deployment</li><li><strong>LLM prompt versions</strong> — Prompt registry with A/B testing framework</li><li><strong>Compliance rulesets</strong> — Versioned JSON configs, hot-reloadable without restart</li></ol><pre># ArgoCD Application for the transcription worker<br># Canary deployment: 10% traffic to new model version first<br>apiVersion: argoproj.io/v1alpha1<br>kind: Rollout<br>metadata:<br>  name: transcription-worker<br>spec:<br>  replicas: 48<br>  strategy:<br>    canary:<br>      steps:<br>        - setWeight: 10    # 10% to new version<br>        - pause: {duration: 15m}<br>        - analysis:<br>            templates:<br>              - templateName: transcription-quality-check<br>        - setWeight: 50<br>        - pause: {duration: 30m}<br>        - setWeight: 100<br>  selector:<br>    matchLabels:<br>      app: transcription-worker<br>  template:<br>    spec:<br>      containers:<br>        - name: transcription-worker<br>          image: our-registry/transcription-worker:${VERSION}<br>          env:<br>            - name: MODEL_VERSION<br>              value: &quot;${MODEL_VERSION}&quot;<br>            - name: SENTIMENT_MODEL_PATH<br>              value: &quot;s3://models/sentiment/${SENTIMENT_MODEL_VERSION}&quot;</pre><h3>The Prompt Deployment Pipeline</h3><p>Changing an LLM prompt is not a trivial code change. A one-word difference can shift scores by 0.5 points across thousands of calls. Our prompt deployment process:</p><ol><li><strong>Draft</strong> — Prompt engineer writes the new prompt version</li><li><strong>Golden set evaluation</strong> — Automated regression on 100-call golden set</li><li><strong>Shadow mode</strong> — New prompt runs in parallel with current; results logged but not shown to users</li><li><strong>A/B test</strong> — 10% of calls get new prompt; human QA analysts review flagged disagreements</li><li><strong>Promote</strong> — After 48 hours of A/B with no regression, new prompt becomes default</li><li><strong>Archive</strong> — Old prompt version stored permanently; all audits reference the prompt version used</li></ol><h3>18. Observability and Monitoring</h3><p>A real-time AI system without deep observability is a liability. Here’s what we track:</p><h3>Three Layers of Metrics</h3><p><strong>Layer 1: Infrastructure Metrics (Prometheus + Grafana)</strong></p><ul><li>Kafka consumer lag per topic and partition</li><li>Audio ingestion rate (calls/minute)</li><li>STT API error rate and latency percentiles</li><li>Pod CPU/memory for all workers</li><li>DynamoDB read/write capacity units consumed</li></ul><p><strong>Layer 2: Application Metrics (Custom + OpenTelemetry)</strong></p><pre>from opentelemetry import metrics</pre><pre>meter = metrics.get_meter(&quot;call_audit_system&quot;)</pre><pre># Business-critical counters<br>calls_ingested = meter.create_counter(<br>    &quot;calls_ingested_total&quot;,<br>    description=&quot;Total calls received by the ingestion layer&quot;<br>)</pre><pre>compliance_violations_detected = meter.create_counter(<br>    &quot;compliance_violations_total&quot;,<br>    description=&quot;Compliance violations by rule and severity&quot;,<br>)</pre><pre>llm_audit_duration = meter.create_histogram(<br>    &quot;llm_audit_duration_seconds&quot;,<br>    description=&quot;LLM audit processing time distribution&quot;<br>)</pre><pre># Usage in code<br>async def process_call_end(call_id: str):<br>    with tracer.start_as_current_span(&quot;llm_audit&quot;) as span:<br>        span.set_attribute(&quot;call.id&quot;, call_id)<br>        span.set_attribute(&quot;call.duration_sec&quot;, call_duration)</pre><pre>        start = time.time()<br>        audit_result = await llm_audit_engine.audit_call(call_data)<br>        elapsed = time.time() - start</pre><pre>        llm_audit_duration.record(<br>            elapsed,<br>            attributes={<br>                &quot;model&quot;: audit_result.model_used,<br>                &quot;pass_fail&quot;: audit_result.pass_fail<br>            }<br>        )</pre><p><strong>Layer 3: AI/ML Quality Metrics (Custom Dashboard)</strong></p><p>This is the layer most teams miss. Infrastructure being green doesn’t mean the AI is working well.</p><p>Metric Alert Threshold Meaning LLM score mean drift (7-day) &gt; 0.2 points Possible prompt regression or model update Compliance false positive rate &gt; 8% Rules engine too sensitive Compliance false negative rate &gt; 2% Rules engine missing real violations Sentiment model confidence &lt; 0.6 &gt; 15% of utterances Audio quality issue or domain drift LLM JSON parse failure rate &gt; 0.5% Prompt or model instability Inter-model score disagreement &gt; 20% of calls Model inconsistency, needs investigation Diarization error rate &gt; 5% Audio quality or new call pattern</p><p>We compute these metrics nightly from sampled human-reviewed audits and plot them on a dedicated “AI Health” dashboard. A degradation here, even if Grafana is all green, means the system is producing wrong answers — which is worse than being down.</p><h3>Alerting Philosophy</h3><p>We learned the hard way that too many alerts create alert fatigue and get ignored. We have exactly three tiers:</p><ul><li><strong>P1 (PagerDuty, 24/7):</strong> Kafka consumer lag &gt; 5 minutes; STT API error rate &gt; 5%; compliance engine down. These mean calls are not being audited.</li><li><strong>P2 (Slack, business hours):</strong> LLM audit queue depth &gt; 500; audio quality degradation &gt; 10% of calls; AI metric drift.</li><li><strong>P3 (Weekly digest email):</strong> Score distribution shifts; new compliance rule coverage gaps.</li></ul><h3>19. Cost Architecture and Unit Economics</h3><p>Let’s talk money. This is the conversation that happens in every architecture review and almost never appears in blog posts.</p><h3>Cost Breakdown at 50,000 Calls/Day</h3><p>Assume: 5-minute average call duration, 8-hour operational window.</p><p>Component Unit Cost Daily Volume Daily Cost Deepgram Nova-2 STT $0.0059/min 250,000 min <strong>$1,475</strong> GPT-4o Audit (high-risk calls, ~30%) ~$0.022/call 15,000 calls <strong>$330</strong> Fine-tuned audit model (70% of calls) ~$0.004/call 35,000 calls <strong>$140</strong> S3 audio storage (90-day retention) $0.023/GB ~2TB/day new <strong>$46</strong> Pyannote (self-hosted GPU) EC2 p3.xlarge 1 instance <strong>$28</strong> Kafka (MSK 3-broker) Fixed — <strong>$42</strong> ClickHouse (3-node cluster) Fixed — <strong>$65</strong> Kubernetes workers (EKS) Variable ~40 pods <strong>$120</strong> <strong>Total</strong> <strong>~$2,246/day</strong></p><p>That’s approximately <strong>$67,000/month</strong> for 1.5 million calls. At $0.044 per call audited end-to-end.</p><p>Compare that to the manual alternative: a QA analyst reviewing 60 calls/day at a fully-loaded cost of $45,000/year reviews ~15,000 calls/year, costing <strong>$3.00 per call reviewed</strong> — and that’s only 1% coverage, not 100%.</p><p><strong>The system pays for itself when it catches a single regulatory fine</strong> (which in financial services typically starts at £50,000).</p><h3>20. The Human Layer: Team Structure and Workflows</h3><p>The technology is table stakes. The workflows that make it useful are what actually deliver value.</p><h3>The New QA Workflow</h3><p>Before this system, a QA analyst’s day looked like:</p><ol><li>Open call recording platform</li><li>Search for calls from specific agents</li><li>Randomly pick 3–5 calls</li><li>Listen in real time (1x speed)</li><li>Fill out a paper-equivalent scoring form</li><li>File a report</li></ol><p>With the system, a QA analyst’s day looks like:</p><ol><li>Open the QA dashboard</li><li>Review AI-sorted queue (highest risk calls at the top)</li><li>Click a call — transcript is already there with flagged moments highlighted</li><li>Jump directly to flagged moments (no full playback needed for most calls)</li><li>Accept or override AI score with one click</li><li>Add coaching notes</li><li>Coaching plan auto-generated and sent to agent’s supervisor</li></ol><p>A QA analyst now reviews <strong>35–40 calls per day</strong> (up from 5–8) at <strong>higher consistency</strong> because the AI does the first-pass triage. The analyst’s job shifts from “find the problem” to “judge the finding” — a much more valuable use of their expertise.</p><h3>The Supervisor Real-Time Console</h3><p>The live supervisor view shows, for each active call:</p><ul><li>A waveform with live sentiment colouring (green → red gradient)</li><li>Active compliance status (green checkmark or flashing warning)</li><li>Agent score from their most recent completed calls</li><li>A one-click “whisper coach” button (allows supervisor to speak to agent without customer hearing)</li></ul><p>The whisper coach integration with escalation alerting was the feature that got us buy-in from every team lead we demoed to. It makes the data actionable in the moment.</p><h3>Agent Self-Service Portal</h3><p>Agents have access to their own portal showing:</p><ul><li>Their call scores over time (trend view)</li><li>Specific feedback on their last 10 audited calls</li><li>Comparison to team average (anonymised)</li><li>Mandatory compliance checklist for their call types</li><li>Coaching notes from their team lead</li></ul><p>When agents can see their own data transparently, resistance to the system drops dramatically. The framing matters enormously: this is a coaching tool, not a surveillance tool. We worked with HR to develop the communication strategy before launch.</p><h3>21. Talking About This in Interviews</h3><p>If you’re a software engineer who worked on a system like this, here’s how to talk about it clearly and impressively in technical interviews. This section is for you.</p><h3>The System Design Question</h3><p>When asked “Design a real-time call audit system,” structure your answer in three moves:</p><p><strong>Move 1: Clarify requirements (2 minutes)</strong></p><ul><li>What’s the scale? (calls/day, average duration)</li><li>What’s the latency requirement? (alerts in 1 second vs. post-call within 5 minutes)</li><li>What compliance rules? (deterministic vs. judgment-based)</li><li>What’s the output? (dashboard, reports, real-time alerts)</li></ul><p><strong>Move 2: Draw the architecture (5 minutes)</strong></p><ul><li>Audio ingestion → Kafka → STT → NLP enrichment → Rules engine → LLM audit → Storage + Dashboard</li><li>Explain why each component exists and what problem it solves</li></ul><p><strong>Move 3: Go deep on one area (10 minutes)</strong> Pick the part you actually built. Interviewers can tell when you’re reciting something you read vs. something you built. Go deep on the trade-offs you personally navigated.</p><h3>Specific Questions You’ll Be Asked</h3><p><strong>“How did you handle LLM hallucinations in a compliance context?”</strong></p><p>Answer: We separated compliance checking from LLM judging. The rules engine is deterministic — pattern matching, semantic similarity, no hallucination risk. The LLM only handles qualitative scoring, where a score of 3.2 vs. 3.4 doesn’t have regulatory consequences. For compliance-critical findings, the LLM provides supporting evidence but a human must confirm before the finding is formally recorded.</p><p><strong>“How do you evaluate whether your system is working?”</strong></p><p>Answer: Three ways. First, a golden set of 100 human-verified calls we run against every model and prompt version. Second, tracking the human override rate — if analysts are overriding &gt; 15% of our scores, something is wrong. Third, downstream business metrics: are compliance violations actually decreasing over time? Are agent scores correlating with customer satisfaction scores?</p><p><strong>“How would you scale this to 10x the current load?”</strong></p><p>Answer: The bottleneck at 10x is the LLM audit tier. We’d push harder on the fine-tuned smaller model to handle 80% of volume, use GPT-4o only for the riskiest 10%, and shard the Kafka topic more aggressively. The STT tier scales linearly (just add Deepgram API capacity). The real challenge is the human review loop — at 10x volume, you need to ruthlessly triage which calls a human ever sees.</p><p><strong>“What would you do differently if you started over?”</strong></p><p>Answer: Build the post-call pipeline first. We spent three months on the streaming infrastructure before our LLM audit logic was solid. Post-call is far simpler to build and validate, and 90% of the value lives in the audit result, not whether you got it 3 minutes vs. 30 seconds after call end. Start simple, prove the value, then add complexity.</p><h3>22. Open Source Tools and Resources Referenced</h3><p>For those who want to go deeper, here are the key open-source tools and papers that underpinned this system:</p><p><strong>Speech and Audio</strong></p><ul><li><a href="https://github.com/pyannote/pyannote-audio">Pyannote.audio</a> — Speaker diarization; the paper by Bredin et al. on End-to-End Speaker Segmentation is essential reading</li><li><a href="https://github.com/snakers4/silero-vad">Silero VAD</a> — Lightweight voice activity detection; excellent for filtering silence</li><li><a href="https://librosa.org/">LibROSA</a> — Audio analysis and feature extraction in Python</li></ul><p><strong>NLP and ML</strong></p><ul><li><a href="https://huggingface.co/docs/transformers">HuggingFace Transformers</a> — The backbone of our sentiment and embedding models</li><li><a href="https://github.com/microsoft/presidio">Presidio</a> — Microsoft’s PII detection and anonymisation toolkit; excellent for transcript redaction</li><li><a href="https://www.sbert.net/">sentence-transformers</a> — Sentence embeddings for semantic compliance matching</li></ul><p><strong>Infrastructure</strong></p><ul><li><a href="https://kafka.apache.org/">Apache Kafka</a> — The event backbone; Confluent’s documentation on consumer group design is gold</li><li><a href="https://clickhouse.com/">ClickHouse</a> — For analytical queries over audit data; the MergeTree engine deep-dive in their docs is mandatory reading</li><li><a href="https://temporal.io/">Temporal</a> — Workflow orchestration for the post-call audit pipeline; handles retries and long-running processes elegantly</li></ul><p><strong>LLM Engineering</strong></p><ul><li><a href="https://smith.langchain.com/">LangSmith</a> — Prompt versioning, tracing, and evaluation</li><li><a href="https://wandb.ai/">Weights &amp; Biases</a> — ML experiment tracking and model evaluation</li><li><a href="https://microsoft.github.io/promptflow/">PromptFlow</a> — Alternative for LLM pipeline orchestration</li></ul><p><strong>Papers Worth Reading</strong></p><ul><li>“Whisper: Robust Speech Recognition via Large-Scale Weak Supervision” (Radford et al., 2022)</li><li>“pyannote.audio 2.1 speaker diarization pipeline” (Bredin, 2023)</li><li>“Constitutional AI: Harmlessness from AI Feedback” (Anthropic, 2022) — for understanding LLM evaluation frameworks</li><li>“COLM: Using Language Models for Automated Call Centre Monitoring” — Search for this; multiple academic groups have published on it</li></ul><h3>Final Thoughts</h3><p>Building this system taught us that real-time AI in production is 20% machine learning and 80% systems engineering, data quality, and human factors. The models are the easy part. Making them reliable, explainable, cost-effective, and genuinely trusted by the humans who use them — that is the real work.</p><p>The most important design decision we made wasn’t a technical one. It was choosing to build the analyst workflow and the agent portal before we optimised a single latency metric. Technology that people don’t trust or don’t use is technology that doesn’t exist. Get the human layer right first.</p><p>If you’re building something similar, I hope the depth here — the security sections, the cost models, the testing philosophy, the team workflows — saves you months of hard-won discovery. The field is moving fast, but the fundamentals are stable: clean data pipelines, thoughtful latency budgets, rigorous evaluation, and a human-in-the-loop that makes the whole thing better over time.</p><p>The most rewarding moment in this entire project wasn’t a technical milestone. It was when a supervisor told us, six weeks after launch: <em>“For the first time, I actually know what’s happening on my team’s calls.”</em></p><p>That’s the whole point.</p><p><em>Did this article help you? Working on something similar? Drop a comment below — I respond to everything. For questions about specific architecture choices or code details, tag them with the relevant section number so I can give a precise answer.</em></p><p><em>If this was useful, share it with one person who is building AI systems in production. That’s all I ask.</em></p><p><strong>Tags:</strong> #AI #MachineLearning #LLM #SystemDesign #SoftwareEngineering #SpeechRecognition #NLP #ContactCenter #Python #ProductionAI #MLOps #DataEngineering #Kafka #GPT4 #Claude #ClickHouse #Deepgram #Compliance #AIEngineering</p><p><em>Author is a Senior AI Engineer specialising in real-time NLP systems and LLM integration at scale. The opinions expressed are personal and do not represent any employer.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=585fb8d53be7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Won’t Replace You. But the Attention Economy Might.]]></title>
            <link>https://medium.com/@shashank_shekhar_pandey/ai-wont-replace-you-but-the-attention-economy-might-0fb4bad94bfa?source=rss-984826d45cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fb4bad94bfa</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[digital-distraction]]></category>
            <category><![CDATA[dopamine-detox]]></category>
            <category><![CDATA[brain-fog]]></category>
            <dc:creator><![CDATA[Shashank Shekhar pandey]]></dc:creator>
            <pubDate>Sat, 16 May 2026 16:45:13 GMT</pubDate>
            <atom:updated>2026-05-16T16:45:13.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zaQucji9pTsS0-XM61QiQ.png" /></figure><p><strong>AI Won’t Replace You. But the Attention Economy Might.</strong></p><p><em>By Shashank Pandey</em></p><p>AI won’t replace most people.</p><p>Distraction will.</p><p>That sounds dramatic until you look around carefully.</p><p>Millions of intelligent people wake up every morning with access to tools that previous generations would have considered supernatural. You can learn almost anything instantly. Build products faster. Write code with assistance. Analyze data. Generate ideas. Compress years of friction into hours.</p><p>And yet most people feel mentally weaker than ever.</p><p>Not less informed.</p><p>Less capable of sustained thought.</p><p>That distinction matters.</p><p>Because the defining crisis of the AI era may not be intellectual scarcity.</p><p>It may be cognitive fragmentation.</p><p><strong>The Strange Contradiction of the AI Era</strong></p><p>We are entering a period where intelligence is becoming increasingly abundant.</p><p>AI can already summarize books, generate strategies, explain complex concepts, write software, create images, draft business plans, and simulate expertise across domains.</p><p>Knowledge is no longer the bottleneck it once was.</p><p>Attention is.</p><p>That changes the entire equation.</p><p>The people who thrive over the next decade may not be the people with the highest IQs, elite credentials, or perfect résumés.</p><p>They may simply be the people who can still think clearly for extended periods of time.</p><p>While everyone else scrolls.</p><p><strong>The Attention Economy Was Never Designed to Help You Think</strong></p><p>The modern internet does not compete for your satisfaction.</p><p>It competes for your attention.</p><p>That is an important difference.</p><p>Most platforms are not optimized to improve your life. They are optimized to maximize engagement duration, behavioral predictability, emotional reactivity, and return frequency.</p><p>Your focus is the product.</p><p>Every swipe, refresh, autoplay recommendation, push notification, and infinite feed exists because attention became one of the most profitable commodities in human history.</p><p>And algorithms learned something uncomfortable about human psychology:</p><p>The brain is highly vulnerable to variable rewards.</p><p>Not knowing what comes next keeps people hooked longer than certainty ever could.</p><p>That is why short-form platforms feel psychologically adhesive. The next video <em>might</em> be funny. Insightful. Outrageous. Emotional. Socially relevant. Identity-confirming.</p><p>So the thumb keeps moving.</p><p>Again.</p><p>Again.</p><p>Again.</p><p>The frightening part is not that this wastes time.</p><p>The frightening part is that it quietly changes cognition itself.</p><p><strong>Your Brain Is Adapting to Fragmentation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbS_HjOYMIAH57VxytBSNQ.jpeg" /></figure><p>Human attention is trainable.</p><p>That means the way you consume information eventually becomes the way you think.</p><p>If you spend years conditioning your brain for novelty, interruption, speed, and stimulation, deep concentration starts feeling uncomfortable.</p><p>Boredom begins to feel intolerable.</p><p>Silence feels unnatural.</p><p>Long-form reading becomes cognitively heavy.</p><p>You stop noticing the shift because the transition is gradual.</p><p>But the symptoms appear everywhere:</p><ul><li>Opening your phone without intention</li><li>Switching tabs every few minutes</li><li>Watching videos while checking messages simultaneously</li><li>Feeling restless during difficult work</li><li>Reading without retention</li><li>Needing stimulation during every idle moment</li><li>Losing the ability to stay with one difficult thought</li></ul><p>Modern media environments reward reaction, not reflection.</p><p>And eventually, people become excellent at consuming fragments while losing the ability to synthesize depth.</p><p>This is not a moral failure.</p><p>It is conditioning.</p><p>The architecture of modern platforms is shaping mental behavior at scale.</p><p><strong>The Death of Boredom Is Not a Small Problem</strong></p><p>For most of human history, boredom was unavoidable.</p><p>People waited in silence. Walked without stimulation. Sat with unresolved thoughts. Reflected unintentionally.</p><p>Now every empty second gets filled instantly.</p><p>Queue. Scroll. Refresh. Swipe.</p><p>The problem is that boredom is not merely dead time.</p><p>Boredom is often the doorway to deeper cognition.</p><p>It is the transition layer between stimulation and original thought.</p><p>Some of the most important mental processes require uninterrupted cognitive space:</p><ul><li>integration</li><li>reflection</li><li>pattern recognition</li><li>strategic thinking</li><li>emotional processing</li><li>creativity</li><li>long-horizon planning</li></ul><p>But if every moment of friction gets anesthetized with content, the brain loses its tolerance for cognitive stillness.</p><p>And without stillness, depth becomes harder to access.</p><p>A distracted brain eventually starts preferring shallow rewards over meaningful effort.</p><p>Not because it is lazy.</p><p>Because it has been trained to.</p><p><strong>Context Switching Is Quietly Destroying Cognitive Quality</strong></p><p>One of the biggest myths of modern work culture is multitasking.</p><p>Most people are not multitasking.</p><p>They are rapidly degrading cognitive performance.</p><p>Every notification, message, tab switch, and interruption leaves behind what psychologists often call <em>attention residue</em> — part of your mind remains attached to the previous task even after moving to the next one.</p><p>The brain does not instantly reset.</p><p>It drags fragments forward.</p><p>So people spend entire days in partial attention states:<br>half-working,<br>half-scrolling,<br>half-thinking,<br>half-reacting.</p><p>This creates a dangerous illusion of productivity.</p><p>You feel busy.</p><p>But busyness and cognitive depth are not the same thing.</p><p>A person who spends four uninterrupted hours solving meaningful problems will usually outperform someone who spends twelve hours switching contexts continuously.</p><p>Deep work compounds.</p><p>Fragmented attention decays.</p><p>And modern digital environments are aggressively optimized for fragmentation.</p><p>Notifications interrupt thought before it fully forms.</p><p>Infinite feeds collapse intentionality.</p><p>Algorithmic media rewards immediacy over complexity.</p><p>The result is a population with unprecedented access to information and decreasing ability to process it deeply.</p><p><strong>AI Changes the Rules Completely</strong></p><p>This is where things become extremely important.</p><p>AI dramatically increases leverage.</p><p>A focused individual can now produce work that previously required entire teams.</p><p>One person with clarity and strong execution can:</p><ul><li>build products faster,</li><li>learn faster,</li><li>automate repetitive tasks,</li><li>generate creative iterations rapidly,</li><li>analyze information at scale,</li><li>compress years of experimentation.</li></ul><p>But AI only amplifies the direction of the user.</p><p>It does not replace thinking.</p><p>It accelerates it.</p><p>And that creates a sharp divide.</p><p>Distracted people use AI reactively.</p><p>Focused people use AI strategically.</p><p>One group endlessly consumes generated content.</p><p>The other compounds output, learning, and execution.</p><p>One group asks AI for stimulation.</p><p>The other asks AI for leverage.</p><p>That difference may define enormous economic and creative gaps over the next decade.</p><p>Because as intelligence becomes cheaper and more accessible, the scarce resource becomes something else entirely:</p><p>Sustained cognitive depth.</p><p><strong>The New Divide Will Not Be Intelligence</strong></p><p>It will be attention.</p><p>This is already visible.</p><p>Some people use AI to generate ten shallow ideas a minute and forget all of them by tomorrow.</p><p>Others use AI to accelerate years of focused work.</p><p>Same tools.</p><p>Different minds.</p><p>The future may not separate people by raw intelligence nearly as much as by cognitive discipline.</p><p>Can you stay with a difficult problem long enough to produce something meaningful?</p><p>Can you think independently without constant stimulation?</p><p>Can you read deeply in a world optimized for skimming?</p><p>Can you resist algorithmic emotional manipulation long enough to maintain clarity?</p><p>Can you use technology intentionally instead of compulsively?</p><p>These questions are becoming economically relevant.</p><p>Because the ability to direct attention may soon matter more than access to information.</p><p>Everyone has information now.</p><p>Very few people have uninterrupted thought.</p><p><strong>Focus Is Becoming a Form of Economic Leverage</strong></p><p>For years, productivity culture treated focus like a personal optimization hobby.</p><p>Something adjacent to self-improvement.</p><p>That framing is outdated.</p><p>Focus is increasingly strategic.</p><p>In an AI-enhanced economy, people who can maintain clarity and sustained concentration gain disproportionate advantages because AI amplifies coherent thinking exceptionally well.</p><p>A distracted mind produces scattered outputs.</p><p>A focused mind compounds.</p><p>That compounding effect matters more now because execution cycles are accelerating.</p><p>The ability to learn quickly, iterate deeply, and sustain momentum is becoming more valuable than static knowledge itself.</p><p>And none of that works without attention.</p><p>Focus is no longer just about getting work done.</p><p>It is becoming a form of cognitive infrastructure.</p><p>A modern competitive advantage.</p><p>Possibly one of the most valuable skills of this decade.</p><p><strong>Rebuild Your Attention Architecture</strong></p><p>Most people do not need more information.</p><p>They need better mental environments.</p><p>The goal is not to become anti-technology or digitally ascetic.</p><p>The goal is to stop outsourcing your attention to systems designed to fragment it.</p><p>You rebuild attention the same way you rebuild physical fitness:<br>through environment, repetition, friction reduction, and intentional practice.</p><p><strong>1. Reduce Unnecessary Cognitive Entry Points</strong></p><p>Most distraction begins before conscious choice.</p><p>Notifications create external control over internal attention.</p><p>Disable non-essential notifications aggressively.</p><p>Especially:</p><ul><li>social media alerts</li><li>recommendation prompts</li><li>engagement reminders</li><li>unnecessary email pings</li><li>algorithmic reactivation systems</li></ul><p>Every interruption has a cognitive cost.</p><p>Protecting attention starts with reducing attack surfaces.</p><p><strong>2. Create Low-Stimulation Mornings</strong></p><p>The first hour of the day matters disproportionately.</p><p>If your brain begins every morning with rapid novelty consumption, emotional stimulation, and fragmented inputs, you train reactivity before intentionality.</p><p>Avoid immediate scrolling after waking.</p><p>Delay algorithmic feeds.</p><p>Give your mind space to stabilize before the internet starts shaping your mental state.</p><p>Even thirty minutes of low-input time changes cognitive texture throughout the day.</p><p><strong>3. Use AI Intentionally, Not Compulsively</strong></p><p>AI can either sharpen cognition or weaken it.</p><p>That depends entirely on usage patterns.</p><p>Use AI to:</p><ul><li>accelerate learning</li><li>clarify difficult concepts</li><li>expand thinking</li><li>automate repetitive work</li><li>pressure-test ideas</li><li>improve execution speed</li></ul><p>Do not use it merely to avoid thinking.</p><p>There is a difference between assistance and dependency.</p><p>The people who benefit most from AI will likely remain highly engaged thinkers.</p><p>Not passive operators.</p><p><strong>4. Train Deep Work Capacity Gradually</strong></p><p>Most people cannot sustain long concentration anymore because they rarely practice it.</p><p>Attention stamina works like a muscle.</p><p>Start rebuilding depth intentionally:</p><ul><li>30 minutes uninterrupted</li><li>then 45</li><li>then 60</li><li>then longer</li></ul><p>Single-task during these blocks.</p><p>No tab switching.</p><p>No background media.</p><p>No checking messages “for a second.”</p><p>At first, it feels uncomfortable.</p><p>That discomfort is diagnostic.</p><p>It reveals how fragmented attention has become.</p><p><strong>5. Relearn Boredom</strong></p><p>This sounds trivial until you try it.</p><p>Walk without consuming content.</p><p>Wait in silence occasionally.</p><p>Sit without reaching for your phone instantly.</p><p>Allow unresolved thoughts to exist without immediate stimulation.</p><p>Boredom recovery is cognitive recovery.</p><p>The brain needs moments without external input to reconnect deeper processing systems.</p><p><strong>6. Shift Toward Long-Form Inputs</strong></p><p>Short-form content changes attentional rhythm.</p><p>Long-form content rebuilds it.</p><p>Read books again.</p><p>Read long essays.</p><p>Listen to extended conversations.</p><p>Study ideas slowly enough to wrestle with them.</p><p>Depth requires duration.</p><p>Skimming trains recognition.</p><p>Sustained reading trains reasoning.</p><p>That distinction matters more than ever.</p><p><strong>7. Design Your Digital Environment Like an Architect</strong></p><p>Environment often beats willpower.</p><p>Move distracting apps off primary screens.</p><p>Separate creation devices from consumption devices when possible.</p><p>Use friction intentionally.</p><p>Make deep work easier to enter.</p><p>Make impulsive distraction slightly harder.</p><p>Small environmental shifts compound surprisingly fast.</p><p><strong>The Future Belongs to Clear Thinkers</strong></p><p>There is something deeply ironic happening right now.</p><p>At the exact moment humanity gains tools capable of dramatically amplifying intelligence, millions of people are losing the ability to sustain attention long enough to use those tools meaningfully.</p><p>That tension may define the next era.</p><p>Not human versus AI.</p><p>But focused minds versus fragmented ones.</p><p>The future probably will not belong exclusively to the smartest people.</p><p>Or the loudest.</p><p>Or the most chronically online.</p><p>It may belong to the people who can still sit with complexity while everyone else reaches for stimulation.</p><p>People who can think clearly without constant interruption.</p><p>People who can direct technology instead of being directed by it.</p><p>Because in a world where intelligence becomes increasingly accessible, depth becomes rare.</p><p>And rare things become valuable.</p><p>Protect your attention carefully.</p><p>It may become one of the most important economic and psychological assets you ever own.</p><p>—</p><p><strong>Shashank Pandey</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fb4bad94bfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Obsessing Over the LLM: Hard Lessons from Building a RAG System on 800 Books.]]></title>
            <link>https://medium.com/@shashank_shekhar_pandey/stop-obsessing-over-the-llm-hard-lessons-from-building-a-rag-system-on-800-books-c5f17a9a56a2?source=rss-984826d45cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5f17a9a56a2</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Shashank Shekhar pandey]]></dc:creator>
            <pubDate>Sat, 02 May 2026 16:36:56 GMT</pubDate>
            <atom:updated>2026-05-02T16:36:56.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYijAo8J_uwQ-4fy7Mq1tQ.png" /></figure><p>A RAG system built on 800 books sounds simple in one sentence.</p><p>In practice, it taught me much more about the brutal reality of retrieval systems than it did about language models.</p><p>When people first hear “800 books,” the immediate assumption is scale — that the system must be slow, expensive, or a nightmare to query. I made the same assumption. But as I built out the pipeline, my entire perspective on production-grade AI shifted.</p><p>The biggest bottleneck wasn’t the sheer volume of text. It was engineering a retrieval pipeline that could consistently pull the needle out of the haystack, in milliseconds, without pulling the hay along with it.</p><p>Here is the exact logic, architecture, and code I used to push RAG to this scale, and why your obsession with the LLM is probably holding your system back.</p><h3>The Model is a Commodity. Retrieval is the Product.</h3><p>Initially, I thought the LLM would be the beating heart of the system. I was wrong.</p><p>If your retrieved context is garbage, even the most advanced frontier model will hallucinate beautifully formatted garbage. If your retrieval is surgically accurate, even a heavily quantized local model can perform like an absolute genius.</p><p>I stopped using simple, linear chains and moved to an agentic workflow using <strong>LangGraph</strong>. Instead of blindly sending every user query to the vector database, I built a routing layer. The graph first analyzes the query: <em>Does this need a vector search? Does it need a summary of a specific author? Is it just a greeting?</em> This single logical step — routing before retrieving — cut my average latency and API costs drastically because the system stopped doing expensive vector searches for basic questions.</p><h3>The Chunking Fallacy &amp; The Parent Document Strategy</h3><p>One of the earliest, most painful lessons was that chunking is not just a preprocessing chore — it is the foundational geometry of your entire system.</p><p>If your chunks are too large, retrieval becomes noisy; you dilute the semantic meaning and confuse the LLM. If chunks are too small, you shatter the narrative context. Books are inherently difficult because they rely on long-form narrative arcs.</p><p><strong>The Solution:</strong> I implemented a <strong>Parent Document Retrieval</strong> pattern.</p><p>The logic is simple but powerful: You split the text into <em>tiny</em> chunks for the vector database to search against (the needle), but you map those tiny chunks back to a <em>large</em> parent chunk (the haystack) to pass to the LLM.</p><p>Here is how that looks in practice:</p><p>Python</p><pre>from langchain.retrievers import ParentDocumentRetriever<br>from langchain.storage import InMemoryStore<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.vectorstores import Qdrant 1. The Strategy: Big chunks for the LLM context, small chunks for precise vector search<br>parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=200)<br>child_splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=50)<br><br><br> vectorstore = Qdrant.from_documents(<br>    [], <br>    OpenAIEmbeddings(model=&quot;text-embedding-3-large&quot;), <br>    url=&quot; &quot;<br>)<br># 3. Initialize the Docstore (Stores the 2000-token parent documents)<br>store = InMemoryStore()<br># 4. Bind them together<br>retriever = ParentDocumentRetriever(<br>    vectorstore=vectorstore,<br>    docstore=store,<br>    child_splitter=child_splitter,<br>    parent_splitter=parent_splitter,<br>)<br></pre><h3>The Latency Playbook: How We Actually Made It Fast</h3><p>A common assumption is that querying hundreds of books automatically creates high latency. But the heavy lifting happens entirely offline during ingestion. At query time, the system needs to be lightning-fast.</p><p>When you are querying 800 books, you can’t just brute-force the LLM and hope for the best. Stop throwing money at larger GPUs; fix your pipeline. To get this system under a 1-second response time, I optimized across three distinct layers:</p><h4>Layer 1: The “Don’t Do It” Hacks (Caching)</h4><p>The absolute fastest LLM generation is the one you don’t actually run.</p><ul><li><strong>Semantic Caching:</strong> I implemented GPTCache backed by Redis. If a user asks <em>&quot;What are the main themes of Book X?&quot;</em> and someone else asked <em>&quot;Can you summarize the themes in Book X?&quot;</em> 10 minutes ago, the vector math realizes the intent is 98% similar and returns the cached answer instantly. <strong>Latency: ~50ms.</strong></li><li><strong>Prompt Caching:</strong> If you are using API models, structure your system prompt and the static instructions at the <em>beginning</em> of the context window. This allows the API to cache those prefix tokens, cutting Time To First Token (TTFT) in half.</li></ul><h4>Layer 2: Retrieval &amp; Embedding Speed</h4><ul><li><strong>Quantized Embeddings:</strong> Instead of storing massive float32 embeddings, quantize the vector space. Switching to int8 or binary embeddings shrinks the memory footprint drastically. The database fits entirely in RAM, and distance calculations become lightning-fast bitwise operations.</li><li><strong>Two-Stage Retrieval (Cross-Encoder Reranking):</strong> Vector math (Cosine Similarity) is fast but semantically blunt. It finds words that are close but sometimes misses the context. I used an asynchronous two-stage pipeline: grab 20 “okay” chunks incredibly fast using HNSW indexing and metadata filtering, then use a Cross-Encoder (BAAI/bge-reranker-large) to deeply score and rerank those 20 down to the top 3.</li></ul><h4>Layer 3: Model Inference Optimization</h4><p>If you are hosting the model yourself instead of using an API, your inference server is your biggest bottleneck.</p><ul><li><strong>Serving with vLLM:</strong> Never use standard HuggingFace transformers in production for generation. Using vLLM with PagedAttention eliminates memory fragmentation in the KV cache, boosting throughput by 3x-5x out of the box.</li><li><strong>Model Quantization (AWQ / GGUF):</strong> Applying AWQ (Activation-aware Weight Quantization) allows the model to run entirely in 4-bit precision. It drops the VRAM requirement massively and speeds up token generation without a noticeable drop in output quality.</li></ul><h3>Latency is a UX Metric, Not Just an Engineering One</h3><p>All of these speed optimizations matter because latency changes how users <em>feel</em> about the AI. They don’t just evaluate the factual correctness of the answer; they evaluate the system’s “confidence.”</p><p>If the system hangs for 15 seconds to return a brilliant answer, the user has already lost trust. If it returns a sharp, focused answer in 800ms, the system feels dependable. A technically brilliant RAG pipeline is practically useless if the retrieval is too slow or too noisy for a human to tolerate.</p><h3>The Takeaway for AI Engineers</h3><p>Building a RAG system over 800 books rewired my approach to applied GenAI. Pushing a system like this to production isn’t about knowing a magic prompt or paying for the biggest API tier.</p><p>It requires the self-belief to tear down your architecture when it isn’t working, and the consistency to relentlessly refine your pipeline, shaving off 50 milliseconds at a time. There is an obsession in the AI community with massive models and flashy demos. But in the trenches of production, those things take a backseat. Production systems live and die by <strong>clean data pipelines, agentic routing, and retrieval architecture.</strong></p><p>The best answer rarely comes from the biggest model. It comes from finding the exact right piece of information at the exact right millisecond.</p><p>If you are building RAG systems in production right now, I’m curious: <strong>What gave you the biggest bump in performance? Was it semantic chunking, embedding selection, reranking, or caching?</strong> Let’s discuss in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5f17a9a56a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangGraph vs. CrewAI: Which Framework Should You Choose for Your Next AI Agent Project?]]></title>
            <link>https://medium.com/@shashank_shekhar_pandey/langgraph-vs-crewai-which-framework-should-you-choose-for-your-next-ai-agent-project-aa55dba5bbbf?source=rss-984826d45cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa55dba5bbbf</guid>
            <category><![CDATA[crew-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Shashank Shekhar pandey]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 17:47:31 GMT</pubDate>
            <atom:updated>2025-12-25T17:47:31.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQKxU1gkdMcUfrH30PptVg.png" /></figure><p>I’ve been building AI agents for a while now, ever since the early days of LangChain experiments turned into full-blown multi-agent systems. Lately, as we head into 2026, two frameworks keep coming up in conversations: LangGraph and CrewAI. Both are fantastic for orchestrating multiple agents that can collaborate on complex tasks, but they approach things quite differently.</p><p>If you’re like me someone who loves prototyping ideas quickly but also needs reliability when things go to production you’ve probably wondered which one to pick. I recently built the same beginner-friendly project in both: an autonomous research agent that delegates tasks to specialized sub-agents. One handles web research, another summarizes findings, and a third writes a final report. It’s a classic multi-agent setup that mimics a small research team.</p><p>Through that hands-on experience (and a lot of debugging at 2 a.m.), I learned a ton about their strengths, weaknesses, and when each shines. Let’s break it down.</p><h4>What Are These Frameworks, Anyway?</h4><p>First, a quick overview so we’re on the same page.</p><p>CrewAI is all about simplicity and role-playing. You define agents with clear roles, goals, and backstories like casting actors in a play. Then you assign tasks, and the “crew” works together, either sequentially or hierarchically (with a manager agent overseeing things). It’s intuitive if you’ve ever managed a team: researcher finds info, writer drafts content, editor polishes it.</p><p>LangGraph, on the other hand, comes from the LangChain team and treats workflows like graphs. Nodes are actions or agents, edges define how control flows (including loops and branches). It’s stateful by design, meaning it keeps track of shared memory across steps, and you have fine-grained control over routing decisions. Think of it as drawing a flowchart where agents pass messages along precise paths.</p><p>Both let you build multi-agent systems, integrate tools (like search APIs), and use any LLM (OpenAI, Grok, local models via Ollama, etc.). But the philosophy differs: CrewAI prioritizes speed and ease, while LangGraph emphasizes control and robustness.</p><h4>Pros and Cons: A Real Talk Comparison</h4><p>From building dozens of agents and reading community feedback in late 2025, here’s how they stack up.</p><p><em>CrewAI pros:</em><br>- Super fast to get started. You can have a working multi-agent crew in under an hour.<br>- Role-based design feels natural great for brainstorming team-like collaborations.<br>- Excellent docs, tons of examples, and YAML configs for agents/tasks make it beginner-friendly.<br>- Built-in support for hierarchical processes (one agent manages others) and easy task delegation.</p><p><em>CrewAI cons:</em><br>- Less flexible for truly complex flows. Loops and conditional branching can feel hacked together.<br>- State management is mostly through task outputs; it doesn’t have native checkpointing for resuming mid-flow.<br>- Sometimes struggles with very chatty agents leading to context bloat or infinite loops.</p><p>LangGraph pros:<br>- Incredible control. Conditional edges, cycles (perfect for iteration like “revise until good”), and persistent state make it production-ready.<br>- Seamless integration with LangSmith for debugging visualize graphs, inspect states, even time-travel to fix issues.<br>- Handles branching logic effortlessly, ideal for dynamic workflows where paths depend on runtime decisions.<br>- Scales well for intricate systems with many interacting agents.</p><p>LangGraph cons:<br>- Steeper learning curve. You need to think in graphs, nodes, and state schemas.<br>- More boilerplate code upfront; prototyping takes longer than CrewAI.<br>- Docs are good but can feel technical if you’re new to LangChain concepts.</p><p>In short: If you want velocity for MVPs or POCs, go CrewAI. If you need precision, reliability, and scalability for real-world deployment, LangGraph wins.</p><h4>Use Cases: When to Pick Which</h4><p>CrewAI shines in:<br>- Content creation pipelines (research + writing + editing crews).<br>- Quick automations like customer support bots or social media managers.<br>- Team simulations where roles are clear and linear.</p><p>LangGraph is better for:<br>- Iterative tasks (e.g., code generation with testing loops).<br>- Adaptive workflows (routing based on confidence scores or external data).<br>- Enterprise apps needing observability, human-in-the-loop, or long-running processes.</p><p>Many folks start with CrewAI for prototypes, then migrate logic to LangGraph for production.</p><h4>Hands-On: Building an Autonomous Research Agent</h4><p>Let’s make this concrete. We’ll build a simple multi-agent research system that takes a topic, researches it online, summarizes key findings, and produces a report.</p><p>You’ll need an OpenAI API key (or any provider) and a search tool. I’ll use SerpAPI for real web search — grab a free key if you want to run this.</p><h4>First, with CrewAI</h4><p>Install: `pip install crewai crewai-tools langchain-openai`</p><pre><br>import os<br>from crewai import Agent, Task, Crew, Process<br>from crewai_tools import SerperDevTool<br>from langchain_openai import ChatOpenAI<br>os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;your-key&quot;<br>os.environ[&quot;SERPER_API_KEY&quot;] = &quot;your-serper-key&quot;<br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br>search_tool = SerperDevTool()<br>researcher = Agent(<br> role=&quot;Senior Researcher&quot;,<br> goal=&quot;Uncover groundbreaking information on the topic&quot;,<br> backstory=&quot;You&#39;re a seasoned analyst with a knack for deep dives&quot;,<br> tools=[search_tool],<br> llm=llm,<br> verbose=True<br>)<br>writer = Agent(<br> role=&quot;Report Writer&quot;,<br> goal=&quot;Craft compelling reports from research&quot;,<br> backstory=&quot;You&#39;re a skilled writer who turns data into stories&quot;,<br> llm=llm,<br> verbose=True<br>)<br>research_task = Task(<br> description=&quot;Search the web for the latest developments in {topic} as of 2025&quot;,<br> expected_output=&quot;A bullet list of 10 key findings with sources&quot;,<br> agent=researcher<br>)<br>write_task = Task(<br> description=&quot;Write a 500-word report based on the research findings&quot;,<br> expected_output=&quot;A well-structured markdown report&quot;,<br> agent=writer,<br> context=[research_task]<br>)<br>crew = Crew(<br> agents=[researcher, writer],<br> tasks=[research_task, write_task],<br> process=Process.sequential,<br> verbose=2<br>)<br>result = crew.kickoff(inputs={&quot;topic&quot;: &quot;Agentic AI trends in 2025&quot;})<br>print(result)</pre><p>Run this, and boom — the researcher searches, passes findings to the writer, and you get a report. Super straightforward. Delegation happens automatically.</p><h4>Now, with LangGraph</h4><p>Install: `pip install langgraph langchain-openai langchain-community`</p><p>This one’s a bit more involved, but you get explicit control.</p><pre><br>import os<br>from typing import TypedDict, Annotated<br>from langgraph.graph import StateGraph, END<br>from langgraph.checkpoint.memory import MemorySaver<br>from langchain_openai import ChatOpenAI<br>from langchain_community.tools import TavilySearchResults # Alternative search, or use SerpAPI wrapper<br>from langchain_core.messages import HumanMessage, AIMessage<br>os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;your-key&quot;<br>os.environ[&quot;TAVILY_API_KEY&quot;] = &quot;your-tavily-key&quot; # Free alternative to Serp<br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br>search_tool = TavilySearchResults(max_results=5)<br>class AgentState(TypedDict):<br> messages: Annotated[list, lambda a, b: a + b]<br> next: str<br>def research_node(state):<br> messages = state[&quot;messages&quot;]<br> response = llm.bind_tools([search_tool]).invoke(messages)<br> return {&quot;messages&quot;: [response]}<br>def write_node(state):<br> messages = state[&quot;messages&quot;]<br> prompt = &quot;Write a 500-word report based on these findings: &quot; + str(messages[-2:])<br> response = llm.invoke([HumanMessage(content=prompt)])<br> return {&quot;messages&quot;: [response], &quot;next&quot;: END}<br>def router(state):<br> last_message = state[&quot;messages&quot;][-1]<br> if last_message.tool_calls:<br> return &quot;research&quot;<br> return &quot;write&quot;<br>graph = StateGraph(AgentState)<br>graph.add_node(&quot;research&quot;, research_node)<br>graph.add_node(&quot;write&quot;, write_node)<br>graph.set_entry_point(&quot;research&quot;)<br>graph.add_conditional_edges(&quot;research&quot;, router, {&quot;research&quot;: &quot;research&quot;, &quot;write&quot;: &quot;write&quot;})<br>graph.add_edge(&quot;write&quot;, END)<br>memory = MemorySaver()<br>app = graph.compile(checkpointer=memory)<br>config = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;1&quot;}}<br>input = {&quot;messages&quot;: [HumanMessage(content=&quot;Research Agentic AI trends in 2025 and write a report&quot;)]}<br>for chunk in app.stream(input, config):<br> print(chunk)<br></pre><p>Here, the graph starts with research, calls tools as needed (looping if more search is required), then routes to writing. State persists, and you can resume or inspect easily.</p><p>Notice how LangGraph makes the loop explicit no risk of runaway conversations.</p><h4>Key Takeaways from Building Both</h4><p>Orchestration: CrewAI handles delegation magically; LangGraph requires you to define it.</p><p>State Management: LangGraph’s shared state and checkpoints are a game-changer for debugging.</p><p>When to Choose: For my research agent prototype, CrewAI won for speed. But if I wanted to add fact-checking loops or human approval steps, I’d switch to LangGraph.</p><h4>Wrapping Up: Your Next Move</h4><p>Both frameworks are evolving fast in this agentic AI boom. CrewAI is perfect if you’re experimenting or need something up quickly. LangGraph is the go-to for anything headed to production or involving real complexity.</p><p>Try the code above tweak the topic to something you’re curious about. Start with CrewAI to feel the magic, then port it to LangGraph to see the control difference. You’ll learn orchestration, state handling, and tool integration along the way.</p><p>Whichever you pick, you’re building the future of AI workflows. What’s your next agent idea? Drop a comment I’d love to hear!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa55dba5bbbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic AI and Autonomous Agents: The Dawn of Smarter Machines]]></title>
            <link>https://medium.com/@shashank_shekhar_pandey/agentic-ai-and-autonomous-agents-the-dawn-of-smarter-machines-af9421d81222?source=rss-984826d45cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/af9421d81222</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai-agentic-workflow]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Shashank Shekhar pandey]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 17:01:02 GMT</pubDate>
            <atom:updated>2025-12-25T17:01:02.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmfvFBLg38q-dpbhGefRRg.jpeg" /></figure><p>Picture this: It’s a hectic Friday afternoon, and you’re staring at your calendar, realizing your long-overdue family vacation is just weeks away. Instead of spending hours juggling flight searches, hotel bookings, and restaurant reservations, you simply tell your AI companion, “Plan a week in Hawaii for four budget under $5,000, focus on beaches and hikes.” Within minutes, it scans deals, cross-checks your preferences from past trips, books everything seamlessly, and even adjusts for a sudden weather forecast change. No endless tabs open, no forgotten details. Sound like sci-fi? Welcome to 2025, where agentic AI isn’t just a buzzword it’s the engine powering this kind of effortless intelligence. As someone who’s been chronicling tech’s wild ride for over a decade, from the early days of clunky chatbots to today’s mind-bending advancements, I can tell you: agentic AI and autonomous agents are the next big leap, promising to transform how we interact with machines from passive tools into proactive partners.</p><p>But let’s back up a second. What exactly are we talking about here? Agentic AI refers to systems that don’t just respond to commands they take initiative. These AIs can plan, reason, and act on their own to achieve goals, adapting to new information along the way. Think of them as digital butlers with brains, capable of breaking down complex tasks into steps and executing them without constant hand-holding. Autonomous agents, a subset of this, crank it up a notch: they’re fully self-sufficient entities that operate in dynamic environments, learning from interactions and making decisions independently. The key difference? While agentic AI might still loop in humans for oversight, autonomous agents hum along solo, like a self-driving car navigating traffic without a backseat driver.</p><p>To put it in everyday terms, contrast this with traditional AI. Remember those old-school chatbots on customer service sites? They’re reactive poking them with a question gets a canned response, but they can’t improvise or follow through on multi-step problems. Proactive AI, on the other hand, anticipates needs. Imagine a thermostat that not only adjusts the temperature but predicts your schedule, factors in energy costs, and even orders filters when they’re due. That’s agentic in action. It’s the shift from “tell me what to do” to “I’ve got this here’s how I’ll handle it.” I’ve seen this evolution firsthand; back in 2015, writing about early machine learning felt revolutionary, but now? It’s like comparing a flip phone to a smartphone ecosystem.</p><p>So, how do these clever systems actually tick? At their core, agentic AI and autonomous agents rely on a few powerhouse components: planning, reasoning, acting, and tool integration. Planning is the blueprint phase the AI breaks a goal into subtasks, like mapping out a road trip with stops for gas and sights. Reasoning kicks in next, where it evaluates options using logic, past data, or even ethical guidelines (more on that later). Acting is the execution: interfacing with the real world via APIs, databases, or even physical robots. And tool integration? That’s the magic sauce, allowing the agent to pull in external resources like querying a weather API or updating a calendar.</p><p>Let’s walk through a simple real-world workflow to make this concrete. Say you’re building an agent to manage your email inbox. It starts by planning: scan for urgent messages, categorize them (bills, work, spam), and prioritize based on deadlines. Reasoning: If an email’s from your boss about a meeting, cross-reference your calendar for conflicts. Acting: Draft a response, attach files if needed, and send it. Tools: It might integrate with Gmail’s API for reading emails and a natural language processor to understand context. In practice, this could save hours a week — I’ve tinkered with similar setups myself, and it’s oddly satisfying watching the AI tidy up my digital mess while I sip coffee.</p><p>Of course, theory is one thing; seeing it in the wild is another. Real implementations are exploding across the tech landscape. Take LangChain, an open-source framework that’s become a go-to for developers building agents. It lets you chain together language models with tools for everything from web searches to data analysis. Then there’s AWS Bedrock’s AgentCore, which hit general availability in 2025 and is making waves with its serverless runtime for deploying agents at scale think secure code execution and built-in observability. I’ve pored over their GitHub samples, and they’re a godsend for turning prototypes into production beasts.</p><p>On the company front, OpenAI is leading the charge with advancements like their ChatGPT Agent, launched mid-2025, which proactively uses tools to complete tasks on its own “computer.” They’ve even co-founded the Agentic AI Foundation to standardize open-source practices, adopted by over 60,000 projects already. Startups are disrupting too Ema and SuperAGI are automating enterprise workflows, slashing operational costs by 30–50% according to recent reports. And don’t overlook players like Anthropic and Google DeepMind, whose agents are tackling everything from vibe-based coding to deep research. One case study that sticks with me: In healthcare, Flobotics deployed agentic AI for revenue cycle management, automating prior authorizations for medications and cutting processing time from days to hours. It’s not just efficiency; it’s life-changing for overworked admins.</p><p>Now, if you’re itching to get your hands dirty — and trust me, as a blogger who’s coded more late-night experiments than I care to admit, this is where the fun begins let’s build a basic autonomous agent in Python using LangChain. We’ll keep it beginner-friendly: an agent that researches a topic online and summarizes findings. First, you’ll need to install LangChain and a few dependencies. Assuming you have Python set up, run `pip install langchain langchain-openai duckduckgo-search` in your terminal. (You’ll also need an OpenAI API key grab one from their dashboard.)</p><h4>Here’s the code, broken down step by step so you can follow along:</h4><pre><br>from langchain_openai import ChatOpenAI<br>from langchain.agents import initialize_agent, Tool, AgentType<br>from langchain.tools import DuckDuckGoSearchRun<br># Step 1: Set up your language model (we&#39;re using OpenAI&#39;s GPT-4o for reasoning)<br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0, openai_api_key=&quot;your-api-key-here&quot;)<br># Step 2: Define tools the agent can use - in this case, a web search tool<br>search = DuckDuckGoSearchRun()<br>tools = [<br> Tool(<br> name=&quot;Web Search&quot;,<br> func=search.run,<br> description=&quot;Useful for searching the internet for current information.&quot;<br> )<br>]<br># Step 3: Initialize the agent with ReAct (Reasoning + Acting) logic<br>agent = initialize_agent(<br> tools,<br> llm,<br> agent=AgentType.REACT_DESCRIPTION,<br> verbose=True # This prints out the agent&#39;s thought process for debugging<br>)<br># Step 4: Run the agent with a goal<br>result = agent.run(&quot;What&#39;s the latest on agentic AI trends in 2025?&quot;)<br>print(result)<br></pre><p>Let’s unpack this. In Step 1, we hook up a large language model (LLM) like GPT-4o, which handles the brains — reasoning through problems. Temperature=0 keeps responses deterministic, less creative but more reliable for tasks. Step 2 adds tools: Here, DuckDuckGo for safe, privacy-focused searches, wrapped as a Tool with a clear description so the agent knows when to use it. Step 3 sets up the agent itself using ReAct, a pattern where the AI alternates between thinking (“What do I need?”) and acting (“Let’s search that”). Verbose mode is gold for learning watch it log its steps. Finally, Step 4 gives it a mission. Run this, and it’ll query the web, reason over results, and spit out a summary. Tweak the input for your own experiments; maybe ask about stock trends or recipe ideas. Pro tip: If errors pop up, check your API key or internet connection — common newbie snags. This is just a starter; scale it by adding more tools, like database queries or email senders.</p><p>Diving deeper, it’s worth comparing agentic AI to other paradigms to see why it’s a game-changer. Standalone LLMs, like basic GPT models, are fantastic for generating text but falter on execution — they can’t “do” things without external help. Agentic systems bridge that by embedding action loops. Multi-agent setups take it further: Imagine a team of specialized agents collaborating, one for research, another for analysis, like a virtual task force. Pros? Massive efficiency and scalability — Deloitte’s 2025 report notes many firms are reimagining operations around agents as “silicon workers.” Cons? Complexity breeds bugs; safety risks loom if an agent misinterprets goals (hello, unintended consequences). And let’s be real — hallucinations or biased decisions can amplify in autonomous loops, demanding robust guardrails.</p><p>In the real world, these technologies are already reshaping industries. In business, agentic AI automates workflows like sales forecasting; Kodexo Labs cites cases where personalized customer engagement boosted conversions by 25%. Healthcare sees patient monitoring agents that flag anomalies in real-time, per Flobotics’ implementations, potentially saving lives amid staffing shortages. Creative fields? Content pipelines where agents draft, edit, and optimize articles — I’ve used similar for brainstorming, though nothing beats human flair. Stats from 2025 back this: SuperAGI reports 60% of companies adopting agentic AI, with McKinsey highlighting vertical use cases like retail personalization cutting costs by up to 40%. Even cybersecurity benefits, as Exabeam deploys agents for threat detection, adapting faster than rule-based systems.</p><p>Looking ahead, the future of agentic AI feels electric yet cautious. By 2030, I predict multi-agent collaborations becoming standard, with advancements in human-in-the-loop designs to mitigate ethics pitfalls — like ensuring transparency in decision-making or preventing job displacement. OpenAI’s push for standardized frameworks addresses this, but we must grapple with questions: Who owns the data agents learn from? How do we audit autonomous actions? On the bright side, integrations with APIs and edge computing will make agents ubiquitous, from smart homes to global supply chains. If you’re eager to dive in, start small: Check out free resources like LangChain’s docs, IBM’s agent tutorials, or OpenAI’s developer platform. Courses on Coursera or freeCodeCamp offer hands-on paths I recommend “Building AI Agents” tracks for that aha moment.</p><p>Wrapping this up, agentic AI and autonomous agents aren’t just tech trends; they’re the blueprint for intelligent systems that amplify human potential. From demystifying their mechanics to spotting real-world wins, we’ve seen how they evolve beyond reactive tools into proactive allies. The code example? That’s your invitation to experiment — copy it, tweak it, and watch the magic unfold. Stay curious, keep building, and follow the buzz on platforms like TechCrunch or xAI’s updates. Who knows? Your next big idea might just spring from a clever agent you whip up tonight. What’s stopping you?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af9421d81222" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agents vs. MCP: What’s the Difference and Why It Matters]]></title>
            <link>https://medium.com/@shashank_shekhar_pandey/agents-vs-mcp-whats-the-difference-and-why-it-matters-ae4ca704c16b?source=rss-984826d45cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae4ca704c16b</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shashank Shekhar pandey]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 15:14:16 GMT</pubDate>
            <atom:updated>2025-03-22T15:14:16.269Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re at a bustling café, and two helpers are vying to assist you. One’s a savvy personal assistant who can plan your day, fetch your coffee, and even chat about the weather. The other’s a quiet delivery worker who doesn’t talk much but reliably brings you whatever you need, from milk to newspapers, whenever you ask. In the world of artificial intelligence, these two helpers have names: agents and the Model Context Protocol, or MCP. They both make AI better, but they do it in wildly different ways. So, what’s the difference? And why should you care? Let’s break it down with some real-world flavor and a few examples to chew on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08O8Rx39rz-rWcMMJO9X3w.jpeg" /></figure><h4>Agents: The Doers with Brains</h4><p>Picture an agent as that personal assistant who doesn’t just follow orders but figures things out. Agents are built around large language models, those clever AI systems like ChatGPT or Claude that can churn out text like a human. But agents take it further. They’re not content to sit there waiting for your next question. They’re proactive, piecing together plans, making decisions, and getting stuff done.</p><p>Take a task like planning a weekend getaway. You tell an agent, “I want a fun weekend,” and it springs into action. First, it might ask itself what “fun” means to you, maybe recalling you like hiking from a past chat. Then it searches for trails near your city, checks the weather to avoid rain, books a cozy cabin, and drafts an itinerary. It’s not just answering a question, it’s solving a problem from start to finish. To do this, it uses the language model as its core, but layers on extras: memory to track what it’s done, logic to decide the next step, and tools like web searches or booking apps to act in the real world.</p><p>Here’s a concrete example. Let’s say you’re a small business owner who says, “Handle my customer emails today.” An agent could read your inbox, spot a complaint about a late delivery, draft a polite apology with a discount code, and send it after double-checking your usual tone. It might even flag a tricky email for you to review later. This isn’t a one-off response, it’s a mini workflow, handled step-by-step. The catch? Agents need custom setups to talk to your email or pull discounts from your system, which can get messy if every developer builds it differently.</p><p>Agents shine when you need an AI to think and act independently. They’re like a sous-chef who can whip up a meal without you hovering over their shoulder. But that independence comes with complexity. Building an agent means coding its brain to reason, its hands to use tools, and its memory to not forget the recipe halfway through.</p><h4>MCP: The Quiet Connector</h4><p>Now meet MCP, the Model Context Protocol. It’s not a doer, it’s a bridge. Think of it as that delivery worker who doesn’t plan your day or chat about life, but always shows up with exactly what you need. MCP is a standardized way for language models to reach out and grab fresh info or trigger actions, without all the fuss of custom-built connections. It’s less about thinking and more about linking.</p><p>Here’s how it works. A language model, or an app using one, sends a request through MCP, like “Get me the latest weather.” Somewhere out there, an MCP server, maybe tied to a weather service, hears the call and sends back, “It’s 70 degrees and sunny in Chicago.” The model takes that info and runs with it, maybe saying, “Looks like a great day for a walk!” MCP doesn’t care what the model does next, it just delivers the goods. It’s a client-server setup, where the model’s the client asking questions, and MCP servers are the helpers fetching answers.</p><p>Let’s try an example. Imagine you’re a student using an AI study buddy. You ask, “What’s in my notes from last week?” Without MCP, the AI’s stuck, blind to your files. But with MCP, it pings a server linked to your note-taking app, grabs the text, and says, “You wrote about photosynthesis — want a summary?” The server doesn’t summarize, it just hands over the raw notes. MCP’s job is done once the data’s delivered. This simplicity is its strength: it’s reusable, works with any model, and doesn’t need to understand your whole life story to help.</p><p>MCP excels at giving language models access to the world, whether it’s your calendar, a news feed, or a company database. It’s like a power strip, plugging the AI into whatever it needs, without the AI having to grow extra arms. But it’s passive, it won’t plan your study session or decide what to summarize unless something else tells it to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0b07SviHBykYgSkCXv2f3A.jpeg" /></figure><h4>How They Differ: A Side-by-Side Look</h4><p>So, agents are the thinkers, MCP’s the fetcher. Agents tackle big tasks, breaking them into steps and acting on their own. MCP sits back, waiting for a specific request, then connects the dots. An agent might use MCP to get info, but MCP won’t use an agent, it doesn’t have the brains for that. Agents are complex, custom beasts, while MCP is a lean, universal standard.</p><p>Think of it this way. If you’re cooking dinner, an agent is the friend who shops for ingredients, picks a recipe, and cooks it all. MCP is the pantry door, letting you grab spices or flour whenever you ask, but it won’t chop an onion. Agents need MCP, or something like it, to reach the pantry, but MCP doesn’t need agents to work its magic.</p><p>Let’s compare with examples. For agents, picture a travel buddy AI. You say, “Book me a trip to Paris,” and it searches flights, finds a hotel, checks your budget, and reserves everything, emailing you the details. It’s a full-service deal. For MCP, imagine a chatbot on your phone. You ask, “What’s my next meeting?” It queries an MCP server tied to your calendar and replies, “Team sync at 2 p.m.” No planning, just the facts. The agent builds the whole experience, MCP supplies one piece.</p><h4>Real-World Examples in Action</h4><p>Let’s paint some pictures to see how they play out.</p><p>For agents, consider a freelance writer’s helper. You say, “Finish my article by tomorrow.” The agent scans your draft, researches missing stats online, writes a conclusion in your style, and submits it to your editor via email. It’s juggling multiple tools, web searches, and your past work to pull it off. Without that autonomy, you’d be micromanaging every step, which defeats the point.</p><p>For MCP, picture a fitness app with an AI coach. You ask, “How many steps did I take today?” The model sends a request through MCP to a server linked to your smartwatch. The server returns “8,452 steps,” and the AI says, “Nice job, you’re close to 10,000!” MCP doesn’t track your goals or suggest a workout, it just grabs the number. The app might use that data for more, but MCP’s role ends at delivery.</p><p>Here’s where they overlap. That freelance agent might use MCP to fetch your draft from a server tied to Google Docs, then take over to finish the job. MCP feeds the agent, but the agent runs the show. This teamwork is why they’re not rivals, they’re partners with different skills.</p><h4>A Generic Example: The Home Office</h4><p>Let’s tie it together with a everyday scenario: managing your home office. You’re a remote worker with a to-do list, emails, and a messy desk. How do agents and MCP help?</p><p>First, the agent. You say, “Get me ready for Monday.” It wakes up, checks your calendar for meetings, pulls tasks from your project app, drafts replies to urgent emails, and orders a new notebook from Amazon because it remembers you’re out of paper. It’s your Monday morning hero, weaving through your life to prep everything. It needs custom links to your calendar, email, and shopping accounts, but once set up, it’s a one-woman show.</p><p>Now, MCP. You ask your AI, “What’s my schedule today?” It sends a request through MCP to a server tied to your calendar app. The server returns, “Meeting at 10 a.m., lunch at noon.” The AI relays that, clean and simple. Later, you ask, “Any updates from my team?” MCP fetches the latest Slack messages from another server, and the AI reads them aloud. It’s not planning your day, just bringing you the pieces when you need them.In this office, the agent’s your manager, orchestrating the chaos. MCP’s the mailroom, delivering updates on demand. Together, they could rule the place: the agent uses MCP to grab your schedule, then builds your day around it. Alone, they each shine in their lane.</p><h4>Why It Matters to You</h4><p>Agents and MCP aren’t just tech buzzwords, they’re shaping how AI fits into our lives. Agents promise a future where AI handles whole jobs, not just questions, perfect for busy folks or big projects. MCP offers a world where AI stays current and connected, without needing a PhD to plug it in. Whether you’re a coder building the next big thing, a boss streamlining your team, or just someone who loves a smart chatbot, these tools change the game.</p><p>Think about your day. Want an AI to run your errands? That’s an agent. Want it to peek at your inbox or weather without a fuss? That’s MCP. They’re not fighting for the crown, they’re teaming up to make AI less of a toy and more of a teammate. So next time you talk to an AI, ask yourself: Is it thinking for me, or just fetching what I need? The answer might just be both.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae4ca704c16b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Context Protocol (MCP): The Unsung Hero Powering the Next Wave of AI]]></title>
            <link>https://medium.com/@shashank_shekhar_pandey/model-context-protocol-mcp-the-unsung-hero-powering-the-next-wave-of-ai-b038588415f9?source=rss-984826d45cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b038588415f9</guid>
            <dc:creator><![CDATA[Shashank Shekhar pandey]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 06:38:52 GMT</pubDate>
            <atom:updated>2025-03-22T06:38:52.210Z</atom:updated>
            <content:encoded><![CDATA[<h4>How a simple protocol could change the way we use large language models — and why you should care.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSHsEiUm2vVkt8HApu94uA.jpeg" /></figure><p>Imagine you’re at a coffee shop, and the barista is a genius at making lattes — but they’re stuck behind the counter with no way to grab fresh milk from the fridge or check the weather to suggest an iced coffee on a hot day. That’s what large language models (LLMs) like ChatGPT, Claude, or even xAI’s creations have been like for years: brilliant minds trapped in a box, limited to whatever they learned during training. Enter the **Model Context Protocol (MCP)** — a quiet revolution that’s like handing that barista a key to the fridge, the internet, and beyond.</p><p>As of March 2025, MCP is starting to buzz in AI circles, especially on platforms like X, where developers and enthusiasts are calling it a game-changer. But what exactly is it? Why does it matter to you — whether you’re a coder, a business owner, or just someone who chats with AI daily? And how does it stack up against flashier concepts like AI agents? Let’s dive in.</p><h4>The Problem: LLMs Are Stuck in the Past</h4><p>First, let’s set the stage. Large language models are incredible — they can write essays, explain quantum physics, or even roast your bad ideas with uncanny wit. But they have a Achilles’ heel: their knowledge is static. Train an LLM on data up to December 2024, and it’ll never know what happened in 2025 unless you retrain it (which is crazy expensive) or spoon-feed it updates.</p><p>Worse, LLMs can’t *do* much on their own. Want an AI to check your email, pull the latest stock prices, or read a PDF you just uploaded? Tough luck — out of the box, they’re blind to the world beyond their training data. Developers have hacked around this for years, building custom integrations to connect LLMs to APIs, databases, or file systems. But those solutions are like duct tape fixes: messy, fragile, and tied to one specific model or app.</p><p>This is where MCP steps in — not as a flashy new AI, but as a simple, elegant solution to a problem we’ve all felt.</p><h4>What Is MCP? A Bridge to the Real World</h4><p>The <strong>Model Context Protocol</strong> is an open-source standard that lets LLMs connect to external tools, data sources, and systems in a consistent, reusable way. Think of it as a universal USB port for AI. Instead of every developer reinventing the wheel to hook an LLM to, say, your Google Drive, MCP provides a blueprint: the LLM (or an app using it) acts as a “client,” and external resources — like your Drive, a weather API, or even a company database — run as “servers” that talk back.</p><p>Here’s the gist:<br>- <strong>How It Works</strong>: The LLM sends a request through MCP (e.g., “Fetch my latest emails”). An MCP server — say, one tied to your email account — processes it and sends back the data (e.g., “Here’s your inbox”). The LLM then uses that fresh info to respond or act.<br>- <strong>Why It’s Different</strong>: Unlike custom integrations, MCP is *model-agnostic* — it works with any LLM, from open-source gems like LLaMA to proprietary beasts like GPT. And it’s *open*, so anyone can build an MCP server for their own tools.<br>- <strong>The Result</strong>: LLMs go from being stuck-in-time geniuses to dynamic helpers that can see and interact with the world in real time.</p><p><em>It’s not about making the AI smarter — it’s about giving it better access to the raw materials it needs to shine.</em></p><h4>MCP vs. Agents: Plumbing vs. Chefs</h4><p>You might be thinking, “Wait, isn’t this what AI agents do?” Not quite. Agents and MCP often get lumped together because they both extend what LLMs can do, but they’re more like apples and oranges — or, better yet, chefs and delivery drivers.</p><p>- <strong>Agents</strong> are proactive mini-brains. They’re built around an LLM but add layers of reasoning, memory, and decision-making. Give an agent a task like “Plan my weekend,” and it’ll figure out steps — search for events, check your calendar, book a dinner — all while calling tools as needed. Agents are cool, but they’re complex and often rely on custom code to talk to the outside world.<br>- <strong>MCP</strong> is passive plumbing. It doesn’t think or plan — it just connects. It’s a standardized way for an LLM (or an agent!) to fetch data or trigger actions, like “Get me the weather” or “Save this to my notes.” No reasoning, just reliable pipes.</p><p>Here’s the kicker: agents can<strong> use </strong>MCP to do their jobs better. An agent planning your weekend might tap an MCP server to grab your calendar instead of wrestling with a one-off API call. MCP makes agents’ lives easier, but it’s not an agent itself — it’s the infrastructure beneath.</p><h4>Why MCP Matters: Everyday Examples</h4><p>Still sounds abstract? Let’s ground it in real life. Here’s how MCP could change things for different people:</p><p>1. <strong>For Coders</strong>: Imagine you’re using an AI-powered IDE like Cursor. With MCP, the LLM could query an MCP server tied to your GitHub repos, pulling your latest code to suggest fixes or write tests — all without leaving the editor. No more copy-pasting files into a chat window.<br>2. <strong>For Businesses:</strong> Picture a customer service AI. An MCP server linked to your CRM could feed it real-time customer data (“This guy’s been waiting 10 minutes!”), letting it tailor responses on the fly. No expensive retraining required.<br>3. <strong>For You and Me</strong>: Chatting with an AI on your phone? An MCP server hooked to your photo gallery could let it analyze your latest vacation pics and write captions — or warn you that your dog’s in every shot (again).</p><p><em>The beauty is in the simplicity: MCP doesn’t care who’s using it or why. It just delivers the goods.</em></p><h4>The Bigger Picture: A More Open AI Future</h4><p>MCP isn’t just a tech trick — it’s a shift in how we think about AI. Right now, big players like OpenAI or Google control the LLM game with closed ecosystems. Want ChatGPT to read your files? You’re stuck with their plugins or nothing. MCP flips that script. Because it’s open-source and universal, it levels the playing field — small devs, startups, or even hobbyists can build MCP servers and plug them into any model.</p><p>This could spark an explosion of creativity. Imagine MCP servers for everything: your smart home, your fitness tracker, your favorite obscure database. Suddenly, LLMs aren’t just corporate toys — they’re tools anyone can customize. It’s like the early internet days, when open standards like HTTP turned a nerdy network into a global phenomenon.</p><h3>A Code Example: MCP in Action</h3><p>Enough talk — let’s see MCP at work. Below is a simplified Python example of an MCP client (the LLM side) and server (a fake weather service). This isn’t production-ready, but it shows the concept. You’ll need flask for the server and requests for the client — install them with pip install flask requests.</p><pre>from flask import Flask, request, jsonify<br><br>app = Flask(__name__)<br><br># Fake weather data<br>weather_data = {&quot;city&quot;: &quot;New York&quot;, &quot;temp&quot;: 65, &quot;condition&quot;: &quot;Sunny&quot;}<br><br>@app.route(&#39;/mcp/weather&#39;, methods=[&#39;POST&#39;])<br>def get_weather():<br>    # MCP expects a JSON request with a &quot;query&quot; field<br>    data = request.get_json()<br>    query = data.get(&quot;query&quot;, &quot;&quot;)<br>    <br>    if &quot;weather&quot; in query.lower():<br>        return jsonify({<br>            &quot;status&quot;: &quot;success&quot;,<br>            &quot;data&quot;: weather_data,<br>            &quot;message&quot;: f&quot;Current weather in {weather_data[&#39;city&#39;]}&quot;<br>        })<br>    return jsonify({&quot;status&quot;: &quot;error&quot;, &quot;message&quot;: &quot;Invalid query&quot;})<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(port=5000)</pre><p><strong>MCP Client (LLM Side)</strong></p><pre>import requests<br>import json<br><br># Simulate an LLM sending a request to the MCP server<br>def ask_mcp_server(query):<br>    url = &quot;http://localhost:5000/mcp/weather&quot;<br>    payload = {&quot;query&quot;: query}<br>    <br>    try:<br>        response = requests.post(url, json=payload)<br>        result = response.json()<br>        <br>        if result[&quot;status&quot;] == &quot;success&quot;:<br>            return f&quot;AI says: {result[&#39;message&#39;]} - Temp: {result[&#39;data&#39;][&#39;temp&#39;]}°F, {result[&#39;data&#39;][&#39;condition&#39;]}&quot;<br>        return f&quot;AI says: Oops, something went wrong - {result[&#39;message&#39;]}&quot;<br>    except Exception as e:<br>        return f&quot;AI says: Connection failed - {str(e)}&quot;<br><br># Test it<br>query = &quot;What’s the weather like today?&quot;<br>print(ask_mcp_server(query))</pre><h3>What’s Happening?</h3><ol><li>Run the server first (python server.py).</li><li>Then run the client (python client.py).</li><li>The client sends a query (“What’s the weather like today?”) to the server via MCP’s JSON format.</li><li>The server checks the query, responds with fake weather data, and the client formats it into a human-friendly response.</li></ol><p>Output might look like:<br> AI says: Current weather in New York — Temp: 65°F, Sunny</p><p>This is bare-bones, but real MCP servers could connect to live APIs, files, or databases. The protocol’s power lies in its consistency — swap the weather server for one reading your emails, and the client barely changes.</p><h3>The Road Ahead: MCP’s Potential and Pitfalls</h3><p>MCP is still young as of March 2025, but its trajectory is exciting. Developers are already experimenting with servers for everything from Slack integrations to personal knowledge bases. If it takes off, we could see a Cambrian explosion of AI tools — each LLM becoming a hub for a constellation of MCP-powered connections.</p><p>But there are hurdles:</p><ul><li><strong>Adoption</strong>: Will enough devs build MCP servers to make it a standard?</li><li><strong>Security</strong>: Open connections mean risks — imagine an MCP server leaking your data if poorly coded.</li><li><strong>Complexity</strong>: While MCP itself is simple, managing a web of servers could get messy.</li></ul><p>Still, the promise outweighs the perils. A world where LLMs can seamlessly tap into our lives — without being locked into one company’s ecosystem — feels like a step toward a more democratic, creative AI future.</p><h3>Why You Should Care</h3><p>Whether you’re a techie or not, MCP matters because it’s about freedom and flexibility. It’s the difference between an AI that’s a walled garden and one that’s a Swiss Army knife. For developers, it’s a chance to build once and reuse everywhere. For users, it’s AI that feels less like a distant oracle and more like a partner in the room.</p><p>So next time you chat with an AI, ask yourself: Could it do more if it weren’t stuck behind the counter? MCP might just be the key to setting it free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b038588415f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Chat-GPT?]]></title>
            <link>https://medium.com/@shashank_shekhar_pandey/what-is-chat-gpt-a15b08b9d95e?source=rss-984826d45cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15b08b9d95e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Shashank Shekhar pandey]]></dc:creator>
            <pubDate>Thu, 08 Dec 2022 06:21:09 GMT</pubDate>
            <atom:updated>2022-12-08T06:28:19.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvpmD3u8d4I6__CQgtNbRQ.jpeg" /></figure><p>Today, I want to demystify ChatGPT — a fascinating new application of GANs (Generative Adversarial Networks) that has been generating a lot of buzz in the AI community.</p><p>For those unfamiliar with GANs, they are a type of neural network that uses two competing networks — a generator and a discriminator — to create realistic-looking outputs. The generator creates fake outputs, and the discriminator tries to tell the difference between the fake outputs and real-world data. Through this back-and-forth process, the GAN is able to produce outputs that are indistinguishable from real data.</p><p>ChatGPT takes this concept and applies it to text-based conversation. It uses GANs to generate responses to input text, allowing it to engage in natural-sounding conversations with humans.</p><p>But here’s the catch — ChatGPT’s responses only touch reality at a tangent. While they may sound convincing, they are ultimately fictional creations of the GAN.</p><p>This might sound like a drawback, but it actually makes ChatGPT incredibly useful. Because it isn’t tied to the constraints of reality, ChatGPT can engage in completely imaginary conversations and provide creative, out-of-the-box responses.</p><p>For example, you could ask ChatGPT what it would do if it could fly, and it might respond with something like “I would soar through the skies like a majestic eagle, feeling the wind beneath my wings and the freedom of flight.” This type of response would be impossible for a human to come up with, but it’s perfectly within the realm of possibility for ChatGPT.</p><p>So, why use ChatGPT if its responses only touch reality at a tangent? Because sometimes, it’s exactly this type of creative, imaginative thinking that we need to solve complex problems and generate new ideas. ChatGPT allows us to explore possibilities that are beyond the constraints of our everyday reality, and that can be incredibly powerful.</p><p>So, there you have it — ChatGPT demystified! While its responses may not always be rooted in reality, they are still incredibly useful for generating creative ideas and engaging in imaginative conversations. I hope you’ll give it a try and see what new possibilities it can unlock for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15b08b9d95e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>