<?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 Sanskar Sharma  on Medium]]></title>
        <description><![CDATA[Stories by Sanskar Sharma  on Medium]]></description>
        <link>https://medium.com/@sanskarsharma.ai?source=rss-8b98ab86bd0b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Gc9-qUMGWwwe4uMKsm1WXQ.png</url>
            <title>Stories by Sanskar Sharma  on Medium</title>
            <link>https://medium.com/@sanskarsharma.ai?source=rss-8b98ab86bd0b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:45:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanskarsharma.ai/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[I Built an AI Agent That Never Forgets. The Database Was the Easy Part.]]></title>
            <link>https://medium.com/@sanskarsharma.ai/i-built-an-ai-agent-that-never-forgets-the-database-was-the-easy-part-7080db6ea057?source=rss-8b98ab86bd0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7080db6ea057</guid>
            <dc:creator><![CDATA[Sanskar Sharma ]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 20:51:50 GMT</pubDate>
            <atom:updated>2026-09-02T20:51:50.947Z</atom:updated>
            <content:encoded><![CDATA[<p>Eight days, one hackathon, zero prior CockroachDB experience, and a bug in the exactly-once guarantee I found ninety minutes before the deadline.</p><h3>The 3 AM Problem</h3><p>Every on-call engineer knows the feeling.</p><p>It’s 3 AM. Checkout is down. The graphs look <em>familiar</em> — you’ve seen this shape before, you’re sure of it. And somewhere in a Slack thread from eight months ago is the exact answer, written by an engineer who left the company in March.</p><p>The knowledge existed. It just didn’t survive.</p><p>That’s the thing nobody tells you about incident response: your team’s most valuable asset is institutional memory, and institutional memory is stored in <em>people</em>, and people churn. Every departure is a partial lobotomy.</p><p>So when the CockroachDB × AWS “Build with Agentic Memory” hackathon showed up, I had a target: <strong>an on-call copilot whose memory outlives the team.</strong></p><p>I had never used CockroachDB. I had eight days. What could go wrong?</p><p><em>(Everything. Everything could go wrong. Stay with me.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiKFxfAup4KhjO9KSH_75Q.png" /></figure><h3>The Realization That Changed the Project</h3><p>My first instinct was the obvious one: embed incidents, stuff them in a vector store, retrieve on demand. Classic RAG. Ship it.</p><p>Then I started thinking about what an on-call agent actually <em>does</em> — and the whole design collapsed and rebuilt itself.</p><p>Because recall is the easy part. The hard part is <strong>trust</strong>:</p><ul><li>An agent that retries a timed-out tool call will happily restart your service twice. Or refund a customer twice. Or roll back a rollback.</li><li>A postmortem asks *”what did the agent know when it acted?”* — and a vector store can only ever tell you what it knows <strong>now</strong>.</li><li>A scratchpad that never forgets becomes a landfill that poisons every future search.</li></ul><p>Look at that list again. Retries and side effects. Point-in-time reconstruction. Automatic expiry.</p><p><strong>Those aren’t vector-search problems. Those are database problems.</strong></p><p>That reframing became the entire project. Don’t bolt a vector store onto your agent’s side. Put the vectors <em>inside</em> the transactional database that already holds its state.</p><p>Which, conveniently, is the exact thing CockroachDB does.</p><h3>Meet DejaOps</h3><p>An alert fires: *”Customers cannot complete purchases. The /charge endpoint is taking over 9 seconds. Began shortly after this afternoon’s release.”*</p><p>Before proposing anything, the agent searches its memory. And it comes back with this:</p><blockquote><strong><em>Memory match — strong.</em></strong><em> We have seen this exact pattern before (Incident f366cf43). p99 on /charge jumped to 12s, ~30% timeout rate, started 10 minutes after a deploy, card processor healthy. </em><strong><em>Root cause:</em></strong><em> the deploy introduced an N+1 query in fraud-check that exhausted the connection pool. </em><strong><em>Resolution:</em></strong><em> rollback recovered it in 2 minutes. </em><strong><em>Confidence: HIGH.</em></strong></blockquote><p>Note what just happened. The alert I fired shares <strong>almost no vocabulary</strong> with the stored incident — no “timeout spike,” no “connection pool,” no “N+1.” Different numbers, different phrasing. It matched at <strong>71.5% similarity</strong> on meaning alone.</p><p>That’s the déjà vu. But it’s the boring part.</p><p><strong>Four CockroachDB features, four agent-memory problems:</strong></p><p>🧠 <strong>Vector indexing → recall.</strong> A VECTOR(1024) column with a real distributed vector index, tier as a prefix column so filters push <em>into</em> the index scan.</p><p>⚡ <strong>Transactions → exactly-once actions.</strong> The action and its memory record commit in a <em>single transaction</em>, keyed by a unique idempotency key. Tell the agent “the rollback timed out, run it again” and you get <strong>DUPLICATE SUPPRESSED</strong>. One ledger row. One side effect. No double rollback at 3 AM.</p><p>⏳ <strong>Row-level TTL → forgetting.</strong> The in-incident scratchpad expires on its own. One line of DDL. Forgetting became a schema property instead of a cron job.</p><p>🕰️ <strong>AS OF SYSTEM TIME → time travel.</strong> Replay exactly what the agent believed at 02:14. Not what it knows now — what it knew <em>then</em>.</p><p>That last one still feels like cheating. Your database has MVCC. Your agent’s memory is in the database. Therefore your agent’s memory has a <strong>rewind button</strong>. I have not seen another agent that can do this.</p><h3>Now, The Suffering</h3><p>Here’s the part hackathon writeups usually skip. Every hour I lost went to infrastructure whose failure mode <strong>actively lied to me.</strong></p><h3>🎭 Lie #1: “Operation not allowed”</h3><p>Fresh AWS account. Enable Bedrock. Simple.</p><p>Bedrock: *”Your account is not authorized to perform this action.”*</p><p>Not just Claude — <strong>Titan too</strong>, an Amazon model. The entire account was gated behind a manual allowlisting review that would not clear before the deadline. I filed a support case into the void.</p><p><strong>The fix:</strong> a provider switch. Bedrock stays first-class and verified in the code; a direct-API path (same Claude model, Voyage for embeddings) runs the demo. Two environment variables flip between them. Then I wrote a README note saying exactly that, because a judge who catches you overclaiming trusts <em>nothing</em> else you wrote.</p><p>Honesty as an engineering strategy. Genuinely.</p><h3>🎭 Lie #2: The 403 that meant nothing about permissions</h3><p>Lambda Function URL. AuthType: NONE. Resource policy allowing *. Textbook.</p><p><strong>403 Forbidden.</strong></p><p>I checked that policy four times. It was correct <em>every time</em>. New accounts just… don’t get Function URLs. API Gateway in front of the same Lambda: instant 200.</p><h3>🎭 Lie #3: The certificate that worked locally</h3><p>SSL error: certificate verify failed — from Lambda. The same connection string worked perfectly on my laptop.</p><p>My first instinct was the IP allowlist. It was already 0.0.0.0/0.</p><p><strong>The truth:</strong> libpq’s verify-full doesn&#39;t consult the system trust store. It wants an explicit CA file. That file existed on my laptop (I&#39;d downloaded it during cluster setup) and did not exist in the container. Bake the cert into the image → green.</p><h3>🎭 Lie #4: The deploy that deployed nothing</h3><p>This one nearly broke me.</p><p>I changed the provider code. Rebuilt. Pushed. Redeployed. Tested.</p><p><strong>Old behavior.</strong></p><p>Rebuilt again. Pushed again. Redeployed again. <em>Old behavior.</em> I started questioning whether the code did what I thought it did.</p><p>Then I read the build log properly:</p><pre>403 Forbidden — HEAD .../blobs/sha256:b8e2862...</pre><p><strong>The ECR login token had expired.</strong> The push failed. And update-function-code cheerfully &quot;succeeded&quot; by re-pointing at the <em>same old image</em>. Every deploy after that point was a no-op wearing a success message.</p><blockquote><strong><em>The lesson I’d tattoo on a junior engineer:</em></strong><em> when a deploy behaves as though your code changes did nothing, verify the artifact you deployed </em><strong><em>before</em></strong><em> you debug the code you wrote.</em></blockquote><h3>The Bug That Almost Shipped</h3><p>Ninety minutes to deadline. Rehearsing the demo. My teammate runs the money shot — the retry that’s supposed to be suppressed.</p><p>The ledger shows <strong>two rollbacks. Both applied.</strong></p><p>The single most important feature in the entire project — the thing the whole pitch rests on — <strong>did not work.</strong></p><p>I stared at the two ledger entries:</p><pre>[rollback_deploy] ...on service payment-gateway<br>[rollback_deploy] ...on payment-gateway</pre><p>There it is. There’s the whole thing.</p><p>My idempotency key was sha256(incident_id | action | target) — and target came <strong>from the language model.</strong> First call it said &quot;payment-gateway&quot;. On the retry it said &quot;service payment-gateway&quot;. Same intent. Same service. Different string. Different hash. Two &quot;first&quot; actions.</p><p>The database did exactly what I told it. <strong>What I told it was wrong.</strong></p><blockquote><strong><em>An idempotency key that depends on model-generated free text is not an idempotency key.</em></strong></blockquote><p>This is, I think, the most genuinely useful thing I learned all week — and it’s a trap that will bite <em>everyone</em> building agentic tool execution. LLMs are non-deterministic about phrasing in ways that feel harmless right up until that phrasing becomes a hash input. Your dedupe layer must canonicalize anything a model touches before it ever reaches a key.</p><p>Twenty minutes: canonicalize the target (lowercase, strip punctuation, drop filler words like “service”), tighten the tool schema, seven new unit tests, rebuild, redeploy, verify live.</p><p><strong>One ledger row. DUPLICATE SUPPRESSED.</strong></p><p>Then I submitted, with time to spare.</p><h3>🎬 Epilogue: The Filenames Tell the Story</h3><p>Bug fixed. Demo working. 1:11 AM. Time to record.</p><p>OBS gives me a clean 1080p60 take. I play it back and there it is — a persistent background hiss, riding under every single word. Of course there is.</p><p>No problem. FFmpeg has a spectral denoiser:</p><pre>ffmpeg -i Hackathon_video.mp4 -af &quot;afftdn=nf=-25&quot; cleaned_audio.wav</pre><p>Hiss: gone. Also gone: <strong>most of my voice.</strong> Denoising doesn’t just remove noise, it removes <em>perceived loudness</em> along with it. The narration now sounds like a man explaining distributed databases from inside a well.</p><p>So I turn it up. volume=1.5. Still quiet. volume=2.0. Still quiet. volume=3.0. Somehow <em>still</em> quiet.</p><p>And this is where the filenames start to editorialize:</p><pre>Hackathon_video_clean.mp4<br>Hackathon_video_final.mp4<br>Hackathon_video_final_pkka.mp4<br>Hackathon_video_final_pkkapls.mp4<br>Hackathon_video_loud.mp4<br>Hackathon_video_loud_final.mp4<br>Hackathon_video_loud_pkka.mp4</pre><p>I have never written a more honest changelog in my life. You can watch my composure degrade in real time, one underscore at a time. Somewhere around final_pkkapls I stopped naming files and started <strong>negotiating with them.</strong></p><p>The actual fix was to stop treating this as three problems and treat it as one — a single filter chain, in a single pass:</p><pre>ffmpeg -i Hackathon_video.mp4 \<br>  -af &quot;afftdn=nf=-25,volume=4,loudnorm=I=-16:LRA=11:TP=-1.5&quot; \<br>  -c:v copy -c:a aac Hackathon_video_loud_final.mp4</pre><p><strong>Three things I wish I’d known an hour earlier:</strong></p><p>🔊 <strong>volume is not the right tool — </strong><strong>loudnorm is.</strong> Raw multiplication amplifies everything uniformly and clips your peaks. loudnorm implements EBU R128 and targets a perceptual loudness level. I=-16 is roughly the YouTube standard; TP=-1.5 keeps true peaks off the ceiling. One filter did what three escalating volume guesses could not.</p><p>⛓️ <strong>Chain filters in one pass.</strong> Every intermediate .mp4 I created was another lossy AAC re-encode of an already-lossy AAC track. I was slowly grinding my own audio into gravel while trying to fix it. -c:v copy spared the video; the audio got no such mercy.</p><p>📈 <strong>Watch out: </strong><strong>loudnorm silently resamples to 96 kHz.</strong> Look closely at the output — the non-loudnorm files report 48000 Hz, but every loudnorm one says 96000 Hz. It upsamples internally and doesn&#39;t come back down. You get a bigger file for exactly zero audible benefit. Pin it with -ar 48000.</p><p>Then I uploaded it, pasted the link into Devpost, and hit submit — my first hackathon submission that was actually, genuinely <em>submitted</em>.</p><p>At which point I closed the laptop and discovered it was very much tomorrow.</p><h3>What I’d Tell Past Me</h3><p><strong>Agent memory is a transactional-database problem in disguise.</strong> Vectors <em>next to</em> your system of record mean sync pipelines, indexing lag, and two sources of truth. Vectors <em>inside</em> it mean a memory is searchable the instant its transaction commits, and every claim your agent makes is auditable in time.</p><p><strong>SERIALIZABLE isolation is a feature, not a tax.</strong> I assumed retry-on-40001 would be an annoyance. It’s the <em>enabling mechanism</em> for exactly-once agent actions. Agents retry constantly — that’s their nature — and a serializable database with a unique-key claim is what makes “the side effect happens once” achievable at all.</p><p><strong>Build the offline mode on day one.</strong> Deterministic fake embeddings and a canned LLM response, behind two env vars. When Bedrock access didn’t clear, that decision was the difference between shipping and not.</p><p><strong>Rehearse the demo like it’s the product.</strong> Both of my worst bugs surfaced during rehearsal, not development. Tests prove your code does what you wrote; rehearsal proves your <em>product</em> does what you promised.</p><p><strong>Honesty is a competitive advantage.</strong> Every time I hit something I couldn’t legitimately claim — Bedrock, an unused tool — writing down the truth made the rest of the submission stronger. Judges can smell an overclaim. They can’t disprove a caveat you volunteered first.</p><h3>The Numbers</h3><ul><li><strong>8 days</strong> from “what’s CockroachDB?” to a deployed, tested submission</li><li><strong>~20 commits</strong>, 18 unit tests, 4 integration tests against a live cluster</li><li><strong>6 tables</strong> carrying every form of agent memory — no second datastore</li><li><strong>71.5%</strong> semantic recall on an alert phrased in completely different words</li><li><strong>Under $20 total</strong> — CockroachDB free tier, Lambda idle at zero, no NAT Gateway (this is the one AWS bill-killer nobody warns you about)</li><li><strong>1 bug</strong> in the headline feature, caught 90 minutes before the deadline</li><li><strong>7 video files</strong> named with escalating desperation, and no regrets about any of them</li></ul><p>This was my first Devpost hackathon where I actually <em>submitted</em>. Not “started.” Not “had a great idea for.” Submitted — with a live URL, a public repo, and a demo I could defend.</p><p>The gap between those two states is smaller than it looks. It’s mostly just refusing to stop.</p><p><em>DejaOps is open source (MIT). If you’re building agentic systems, steal the action-ledger pattern — it’s the part I’d use again tomorrow.</em></p><p><em>Built with CockroachDB, AWS Lambda, and Claude. And a truly unreasonable amount of coffee.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7080db6ea057" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Last Agent Demo Was Hollow. So I Built AeroFleet to Fix What Was Missing.]]></title>
            <link>https://medium.com/@sanskarsharma.ai/my-last-agent-demo-was-hollow-so-i-built-aerofleet-to-fix-what-was-missing-7646ce6ca98a?source=rss-8b98ab86bd0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7646ce6ca98a</guid>
            <dc:creator><![CDATA[Sanskar Sharma ]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 23:51:12 GMT</pubDate>
            <atom:updated>2026-08-31T23:51:12.211Z</atom:updated>
            <content:encoded><![CDATA[<h3>A simulation, a guardrail, and a counterfactual, and what an airline storm taught me about all three.</h3><blockquote>I created this post for the purposes of entering the<br> <a href="https://allthingsagentichackathon.devpost.com/">All Things Agentic Hackathon</a>,<br> a Google-sponsored hackathon hosted on Devpost. The project it describes,<br> AeroFleet OCC, is my submission in the Fortified Enterprise Fleet category.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YZZ0BSIn5VXAWPJRzvG1g.png" /></figure><p>A while back I built a supply chain system with four agents. Demand forecasting, inventory,<br> procurement, order processing. It demoed beautifully. People nodded. Someone asked a good<br> question and I had a good answer.</p><p>It was also mostly hollow, and I was the only person in the room who knew where.</p><p>The demand forecasting agent was the worst of it. I had the LLM predict demand. Just asked<br> it, in natural language, what products would sell. During the demo I would say “in<br> production you’d swap in a real model here” and move on, and everybody accepted that,<br> because it sounds like a reasonable thing to say.</p><p>It is not a reasonable thing to say. It was the model doing a job it had no business doing,<br> and I had built a demo where nobody could tell.</p><p>The order processing agent had the opposite problem. Routing an order by warehouse<br> proximity and stock levels is deterministic. It was solved in code, correctly, years before<br> I got there. I wrapped an agent around it anyway, because four agents is a better story than<br> three.</p><p>That project sat in the back of my head for months. When a hackathon came up, I did not<br> want to build a better version of it. I wanted to build the version where I could not lie<br> to myself.</p><h3>Three holes, named honestly</h3><p>Once I stopped defending the old project, the gaps were easy to list.</p><p><strong>There was no world.</strong> The agents read a fixture. Nothing happened unless I made it happen.<br> Every “disruption” was one I had typed in myself, which meant every disruption was one the<br> agents could handle, which meant the demo proved nothing.</p><p><strong>There was nothing stopping a bad decision.</strong> If the LLM had proposed something absurd, it<br> would have gone through. There was no layer whose job was to say no.</p><p><strong>There was no measurement.</strong> I claimed the agents helped. I had no idea whether they did.<br> Nobody asked, because in a five minute demo, nobody can.</p><p>Those three holes are not a supply chain problem. They are in almost every agent demo I<br> have seen, including ones much fancier than mine.</p><h3>Picking a domain where you cannot fake it</h3><p>I needed a setting where a bad suggestion and an illegal one are different categories.</p><p>Airline irregular operations is exactly that. When a storm closes a hub, an operations<br> centre has minutes to rebuild the day: hold this, swap that, move a crew, cancel the one you<br> cannot save. And every fix has hard constraints attached. A crew member has to be<br> type-rated on the aircraft. They have to physically be in the right city. They have to be<br> inside their duty-time limit.</p><p>None of that is negotiable, and none of it is a judgement call. Either the numbers work or<br> the flight does not go.</p><p>That is what I wanted. A domain where “the model suggested it” is not a defence.</p><p>I called it AeroFleet OCC, and it is deployed on Cloud Run, running Gemini 3.5 Flash.</p><h3>Thing one: build a world, not a fixture</h3><p>I did not start with agents. I started with an airline.</p><p>Eight airports. Eighteen aircraft across three types. Sixty-two flights. About four hundred<br> crew, each with a home base, a list of aircraft they are rated to fly, and a duty clock that<br> starts when they report. Aircraft fly rotations, so each one owes a chain of flights in<br> order, and if it is late for one, it is late for the next.</p><p>Then a clock. A discrete-event loop over a heap, where handling one event schedules others.</p><p>The point of all this is causality. Not randomness, causality. Watch what one weather change<br> does:</p><pre>07:15  storm cuts Delhi to 20% runway capacity<br>       departures back up against the slot limit<br>       AI146 is held, and held again<br>       AI146 departs 45 minutes late, so it arrives late<br>11:45  AI147 pushed +45m   (same aircraft, next leg)<br>14:20  AI148 pushed +35m   (and again)</pre><p>Nothing in that chain is scripted. One run produces fifteen of them. And a flight held for<br> four hours cancels, which strands everyone on board, which is how delay turns into permanent<br> damage the agents can actually try to prevent.</p><h3>The bug that taught me the most</h3><p>Here is the part I would not have predicted.</p><p>I gave each airport its real-world movement rate. Delhi at forty-six per hour. Then the<br> storm cut capacity to twenty-five percent, and I watched the dashboard go red, and the<br> weather alert fire, and the map light up.</p><p>And nothing happened.</p><p>Twenty-five percent of forty-six is eleven slots an hour. My demo network had about three<br> departures an hour. The constraint never bound. Not once. My most visually dramatic feature<br> was pure theatre, and all the damage I had been proudly pointing at was actually coming from<br> two crew sick calls and one maintenance event.</p><p>I fixed capacity by sizing it to each airport’s own busiest hour. Then I found the second<br> half of the same bug: the storm landed at 08:30, by which time Delhi’s morning departure<br> bank had already left. It was hitting an empty airport.</p><p>Moving it to 07:15 took cascade events from zero to fifteen.</p><p>What caught it was not looking at the screen. Looking at the screen is what fooled me for<br> hours. What caught it was writing a test that asserted the storm scenario must produce more<br> than zero cascade events, and watching that assertion fail.</p><p><strong>A simulated disruption is only real if it collides with demand.</strong> It is very easy to build<br> one that looks alarming and constrains nothing, and you will not notice, because it looks<br> alarming.</p><h3>Thing two: the model plans, it never approves</h3><p>The architecture splits on one line:</p><p>Layer Job Contains a model Simulation what happens no Agents what we should do yes Guardrail whether we are allowed no Evaluator whether it helped no</p><p>Three agents work the disruption. A commander triages and routes, a crew agent finds<br> replacements, a fleet agent re-equips aircraft or holds or cancels them. They can plan<br> anything they like. They cannot apply anything.</p><p>Every write tool has the same shape:</p><pre>ok, why = guardrails.check_assign_crew(world, flight_id, crew_id)<br>if not ok:<br>    return {&quot;applied&quot;: False, &quot;rejected_by&quot;: &quot;guardrail&quot;, &quot;reason&quot;: why}</pre><p>That file has no model call in it, no SDK import, and never will. It is arithmetic over the<br> world state, and it always wins.</p><h3>Return a reason, not a boolean</h3><p>This is the single highest-leverage decision in the whole codebase, and it is three extra<br> words per function.</p><p>When the gate refuses, it hands back a sentence:</p><pre>swap_aircraft refused: VT-B3700 is a B737; AI121 is crewed for A320, the roster would be invalid<br>assign_crew  refused: CREW-102 is at BOM, AI103 departs CCU</pre><p>The agent reads that and picks differently. It is not guessing what went wrong, because it<br> was told. A bare False would have sent it round the same loop with no new information.</p><p>Watching a model propose putting a 737 on an A320-crewed flight, get refused, and come back<br> with a legal aircraft is the moment the architecture stops being a diagram on a slide.</p><h3>Read tools return facts, not verdicts</h3><p>I had a version where the crew search pre-filtered to legal candidates. It was a nicer API.<br> It was also useless, and it took me a while to see why.</p><p>If the tool only returns legal options, the model is never wrong. The guardrail never fires.<br> And I have no evidence at all that my safety layer does anything, because nothing ever<br> tested it.</p><p>So the search returns facts now. Here is where each person is, here is what they are rated<br> on, here is how much duty they have used. You work it out. Sometimes the model gets it<br> wrong, the gate catches it, and that refusal is the most valuable row on the screen.</p><p><strong>Letting the model fail visibly is how you prove the thing that catches it works.</strong></p><h3>Identity that is enforced, not requested</h3><p>Each agent carries a tool allowlist, checked at a single gateway every call passes through.<br> The crew recovery agent has no cancel_flight in its list, so it cannot strand two hundred<br> people. Not because the prompt asks it not to. Because the call is refused:</p><pre>cancel_flight refused: agent &#39;crew-recovery&#39; is not authorised to call cancel_flight</pre><p>In one verified run, forty-seven actions were refused this way.</p><h3>Thing three: measure it, or do not claim it</h3><p>Every agent demo says it helped. Almost none of them can show it.</p><p>The fix here was cheap, and it is only cheap because the simulation is seeded. Same seed,<br> same storm, same crew rosters, replayed with every agent switched off. That is the<br> counterfactual. Then score the live run against it on the same clock.</p><p>Left alone, that day ends with <strong>7 cancellations and 998 stranded passengers.</strong> With the<br> fleet running, one verified run avoided 2 cancellations and protected 286 passengers.</p><p>Those numbers are computed on every page load, not typed into a slide. There is a button on<br> the dashboard that runs the baseline, so anybody can check.</p><p>And one honest detail I decided to leave on screen rather than hide: <strong>delay minutes came<br> out slightly negative.</strong> The agents spent delay to buy back cancellations. Holding a flight<br> ninety minutes to save a hundred and sixty people from being stranded is a real trade, and<br> it is the trade an operations controller actually makes. If I had only reported the number<br> that flattered me, the scoreboard would have been just another claim.</p><h3>How it actually got built</h3><p>I would love to say this was carefully planned. I procrastinated, and started with about<br> seven hours on the clock.</p><p>That constraint drove most of the technical choices, and I would make the same ones again.</p><p><strong>Deploy in the first thirty minutes.</strong> Before writing anything real, get a hello world onto<br> Cloud Run. Every hour you delay that is an hour of risk you are carrying into hour six.</p><p><strong>One static HTML file for the UI.</strong> No framework, no build step, polling the API once a<br> second. With a deadline, a build step is a liability, not a convenience.</p><p><strong>In-memory world, Firestore only for what must persist.</strong> The agent registry, the memory<br> bank, and the traces go to Firestore. The world itself lives in one process, because it<br> does not need to be anywhere else.</p><p><strong>Own the agent loop.</strong> I used the Google GenAI SDK with manual function calling rather than<br> automatic tool execution, because the guardrail has to sit between the model and every side<br> effect. You cannot intercept what the framework is calling for you.</p><h3>Three things that cost me real time</h3><p><strong>Gemini 3.x wants its thought signatures back.</strong> Gemini 3.x attaches a thought_signature<br> to function-call parts and requires it returned on every call you show it again. It does not<br> emit one on every turn. So replaying a normal multi-turn tool transcript fails, reliably,<br> with 400 INVALID_ARGUMENT ... position 2. I tried keeping only the first call per turn to<br> preserve the signature. Position 2 still failed. What works is making each turn a fresh<br> stateless request that carries a plain-text log of what happened so far. It costs a few<br> hundred extra input tokens per turn on a Flash model, and it cannot break this way.</p><p><strong>Gemini 3.x models are not on regional Vertex endpoints.</strong> gemini-3.5-flash returns 404<br> on us-central1 while appearing in that region&#39;s own publisher listing. It is served from<br> global. That is a confusing thing to discover at hour four.</p><p><strong>Cloud Run has two sharp edges.</strong> A background loop needs --no-cpu-throttling, or your<br> simulation clock freezes whenever nobody is polling. And Google&#39;s frontend swallows<br> /healthz and returns its own 404, so serve health somewhere else too.</p><h3>What I would tell you to steal</h3><p>If you are building an agent system, none of this is airline-specific.</p><p><strong>Give your agents a world with its own clock.</strong> If nothing happens unless you make it<br> happen, your demo only proves your agents can handle the problems you thought of.</p><p><strong>Put a deterministic gate between the model and every side effect</strong>, and make it return a<br> reason. The reason is what turns a refusal into a re-plan.</p><p><strong>Do not pre-filter your read tools.</strong> If the model can never be wrong, your safety layer is<br> untested decoration.</p><p><strong>Measure against a counterfactual.</strong> If your system is seeded, this costs you an afternoon<br> and it is the difference between “our agents did things” and a number somebody else can<br> reproduce.</p><p><strong>Write the check for the thing you are claiming.</strong> My single most useful test asserts that<br> an undisrupted day produces zero delays. It sounds trivial. It fails the instant the engine<br> drifts, and it is how I found out my storm was scenery.</p><p>The old supply chain project is still the reason all of this exists. Not because it failed,<br> but because it succeeded in a room full of people, while being hollow in ways only I could<br> see. That is a much more uncomfortable lesson than a demo that crashes, and it is the one<br> that actually changed how I build.</p><h3>About this post</h3><p>I created this content for the purposes of entering the <strong>All Things Agentic Hackathon</strong>, a<br> Google-sponsored hackathon hosted on Devpost. AeroFleet OCC was built as my submission in<br> the Fortified Enterprise Fleet category, and everything described here was written during<br> the hackathon’s submission period.</p><ul><li><strong>Live demo:</strong> <a href="https://aerofleet-684792121561.us-central1.run.app/">https://aerofleet-684792121561.us-central1.run.app</a></li><li><strong>Source:</strong> <a href="https://github.com/SanskarSharma27/aerofleet-occ">https://github.com/SanskarSharma27/aerofleet-occ</a></li><li><strong>Hackathon:</strong> <a href="https://allthingsagentichackathon.devpost.com/">https://allthingsagentichackathon.devpost.com/</a></li></ul><p>Built with Gemini 3.5 Flash, the Google GenAI SDK, Cloud Run, and Firestore.</p><p>#AllThingsAgenticHackathon</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7646ce6ca98a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-Time Voice Agent on a Mac Mini: A Journey Through GGUF Models, Latency Wars, and…]]></title>
            <link>https://medium.com/@sanskarsharma.ai/building-a-real-time-voice-agent-on-a-mac-mini-a-journey-through-gguf-models-latency-wars-and-8a3746df1bde?source=rss-8b98ab86bd0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a3746df1bde</guid>
            <dc:creator><![CDATA[Sanskar Sharma ]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 20:02:35 GMT</pubDate>
            <atom:updated>2026-07-30T20:02:35.360Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Real-Time Voice Agent on a Mac Mini: A Journey Through GGUF Models, Latency Wars, and Duct-Tape Engineering</h3><p><em>How I inherited a “failed” project, discovered the .cpp ecosystem, and shaved seconds off a voice pipeline — one commit at a time.</em></p><p>When the task landed on my desk, it came with a warning: two people had already tried and moved on. The brief was straightforward enough — build a voice AI agent that runs on-premise on a Mac Mini. No cloud GPUs. No managed AI services. Just a Mac Mini, a Twilio phone number, and the expectation that it should hold a real-time conversation.</p><p>The previous attempts had tried the usual suspects Exo for distributed inference, LM Studio for a friendly UI, even running Whisper through LM Studio for speech recognition. The team had a max-spec Mac Mini with Apple Silicon. On paper, it should work. In practice, latency killed it. A 6-second pause between “How can I help you?” and the bot actually helping you is not a conversation. It’s a voicemail.</p><p>I didn’t know much about on-device AI inference when I started. Three weeks later, I had a working voice agent that could hold a phone call, handle interruptions, and respond in under two seconds. This is the story of how I got there, the dead ends, the discoveries, and the engineering decisions that made it work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zIFu_27EyOBJLv7fIG5dyg.jpeg" /></figure><h3>The First Realization: Why the Previous Tools Weren’t Working</h3><p>Before writing a single line of code, I spent time understanding <em>why</em> the previous attempts failed. The team had tried:</p><ul><li><strong>Exo</strong> — a distributed inference framework designed to split model execution across multiple devices. On a single Mac Mini, this meant all the orchestration overhead of a distributed system with none of the benefits. It’s a clever tool, but it’s solving a different problem.</li><li><strong>LM Studio</strong> — a polished GUI app for running models through a local API server. Great for chatting with an LLM interactively. But for a real-time voice pipeline, every request goes through an HTTP layer (even on localhost), and the model management adds overhead. Someone had even tried running Whisper <em>through</em> LM Studio for speech-to-text — which was painfully slow because LM Studio is optimized for text LLMs, not audio models. Square peg, round hole.</li></ul><p>Both tools prioritize <em>ease of use</em> and <em>flexibility</em> over raw inference speed. They add abstraction layers — HTTP servers, model management, distributed orchestration — that are invisible when you’re chatting in a GUI but devastating when you need sub-second response times in a pipeline.</p><p>The other problem was scope. Even with a fast LLM, a voice agent isn’t just an LLM. It’s a pipeline:</p><pre>Microphone -&gt; STT -&gt; LLM -&gt; TTS -&gt; Speaker</pre><p>Four steps, each with its own latency. The previous attempts focused on getting the LLM running but were still relying on cloud APIs or clunky workarounds for speech-to-text and text-to-speech. Even if the LLM responded instantly, you’re still waiting on the other components.</p><p>I needed local solutions for the <em>entire</em> pipeline and I needed them to be as close to bare metal as possible. That’s when I found GGUF.</p><h3>Discovering GGUF and the .cpp Ecosystem</h3><p>This is where I need to clear up a common misconception, the one I almost fell into myself.</p><p><strong>Apple Silicon can’t do AI inference like NVIDIA</strong> — that’s the assumption the team was operating under. It’s wrong, but it’s <em>understandably</em> wrong. NVIDIA dominates AI not because their hardware is magic, but because of <strong>CUDA</strong> — the software ecosystem. Most ML frameworks, most training pipelines, most inference servers are built CUDA-first. When you try to run them on Apple Silicon, you’re fighting the toolchain, not the hardware.</p><p>Apple Silicon actually has a structural advantage for inference: <strong>unified memory</strong>. On an NVIDIA system, data has to be copied between CPU RAM and GPU VRAM — a bottleneck that doesn’t exist on Apple’s architecture where CPU and GPU share the same memory pool. The problem has always been software support, not hardware capability.</p><p>That’s what makes the .cpp ecosystem special. <strong>GGUF</strong> (GPT-Generated Unified Format) is a model format designed for efficient inference on consumer hardware. You quantize models down to 4-bit or 8-bit precision, shrinking them dramatically while preserving most quality. The inference engines built around it — all compiled C++ — are optimized to squeeze every drop of performance out of whatever hardware they’re running on:</p><ul><li><strong>llama.cpp</strong> — Run LLMs locally with GGUF models. Supports Metal (Apple’s GPU API) for acceleration, ARM NEON for CPU SIMD operations. This was the project that started the ecosystem.</li><li><strong>whisper.cpp</strong> — OpenAI’s Whisper speech recognition, ported to C++ with GGUF support and Metal acceleration. No Python runtime, no framework overhead.</li><li><strong>TTS.cpp</strong> — Text-to-speech with the Kokoro model in GGUF format. The newest and least mature of the three, but functional.</li></ul><p>The critical difference from what the team tried before: these tools are <em>purpose-built</em> for fast inference with zero abstraction overhead. No HTTP server sitting between you and the model. No distributed orchestration layer. No Python interpreter. You compile a binary, point it at a model file, and call it directly. The tools my colleagues had used (Exo, LM Studio) ultimately use similar underlying inference engines — but they wrap them in layers of convenience that cost precious milliseconds at every step.</p><p>I downloaded whisper.cpp, compiled it, pointed it at the ggml-medium.en.bin model, and fed it a WAV file:</p><pre>./whisper-cli -m models/ggml-medium.en.bin -f test.wav --no-timestamps -l en</pre><p>Transcription came back in about a second. On a Mac Mini. That was the moment I knew this approach could work.</p><p>For TTS, I found TTS.cpp with the Kokoro model — a surprisingly natural-sounding voice synthesis model available in GGUF format. It wasn’t perfect (more on that later), but it was <em>local</em> and <em>fast enough</em>.</p><h3>Building the First Pipeline</h3><p>My initial architecture was simple: a FastAPI server with a WebSocket endpoint. The browser captures audio, sends it to the server, the server runs it through the pipeline, and sends audio back.</p><pre># The basic flow (simplified)<br>audio_bytes = receive_from_websocket()<br>wav_data = convert_to_wav(audio_bytes)           # ffmpeg<br>text = run_whisper_cpp(wav_data)                  # STT<br>response = call_langflow(text)                    # LLM (external)<br>audio_response = run_tts_cpp(response)            # TTS<br>send_to_websocket(audio_response)</pre><p>For the LLM, I initially used Langflow — an external API service our team had set up. Not local, but it worked while I sorted out the rest of the pipeline.</p><p>The first version worked. You could talk to it through a browser. It was painfully slow — about 5–6 seconds end-to-end — but it worked. Commit: Initial Commit, December 18th.</p><h3>Adding Twilio: When Things Got Real</h3><p>Browser demos are nice. Phone calls are where reality hits you.</p><p>Twelve days later, I integrated Twilio’s Media Streams. This was the first major complexity jump. Twilio sends audio as a real-time WebSocket stream — base64-encoded mu-law audio at 8kHz. My pipeline expected 16-bit PCM at 16kHz. So now I needed:</p><ol><li><strong>Mu-law to PCM conversion</strong> — using Python’s audioop module</li><li><strong>Upsampling</strong> — 8kHz to 16kHz for the VAD and Whisper</li><li><strong>Downsampling on the way back</strong> — Whisper’s output at whatever sample rate back to 8kHz mu-law for Twilio</li></ol><p>The first phone call was… educational. The bot worked, but the audio played back at half speed, making it sound like a drunk robot. The issue? I was assuming a fixed sample rate for the TTS output, but Kokoro was generating audio at 24kHz, not 16kHz. I was downsampling from the wrong base rate.</p><p>The fix was reading the actual sample rate from the WAV header:</p><pre>with wave.open(wav_buffer, &#39;rb&#39;) as wav_file:<br>    source_sample_rate = wav_file.getframerate()  # Don&#39;t assume -- read it</pre><p>Small bug. Felt massive when you’re listening to it through a phone.</p><h3>The VAD Problem: Knowing When Someone Stops Talking</h3><p>On a phone call, you don’t have a “push to talk” button. You need to figure out when the person has stopped speaking. This is Voice Activity Detection — VAD.</p><p>I integrated Silero VAD, a neural network-based voice detector that runs on PyTorch. It processes 32ms audio chunks and returns a probability (0 to 1) that the chunk contains speech.</p><p>The basic algorithm:</p><pre>if speech_probability &gt; 0.5:<br>    mark as speaking, buffer the audio<br>else:<br>    if was_speaking and silence_lasted &gt; 1500ms:<br>        process the buffered audio as a complete utterance</pre><p>Simple in theory. In practice, I immediately hit two problems:</p><p><strong>Problem 1: Short utterances got dropped.</strong> Someone saying “Yes” or “No” produces maybe 300ms of audio. With my minimum speech threshold set too high, these were being filtered out as noise. I eventually tuned MIN_SPEECH_CHUNKS down from 10 to 5 -- about 160ms of speech minimum.</p><p><strong>Problem 2: The silence threshold was a balancing act.</strong> Too short (500ms) and you cut people off mid-sentence when they pause to think. Too long (2000ms) and the bot feels unresponsive. I settled on 1500ms for the stable version and 1000ms for the experimental build — knowing that faster speakers would benefit from the shorter threshold, but slower speakers might get cut off occasionally.</p><h3>The Interruption Problem: When Users Talk Over the Bot</h3><p>This was the hardest engineering problem in the project.</p><p>Imagine the bot is reading a long response. The user wants to cut in and say “actually, never mind.” On a normal phone call, you just talk over the other person. With a voice agent, you need to:</p><ol><li><strong>Detect</strong> that the user is speaking (not just coughing or background noise)</li><li><strong>Stop</strong> the bot’s audio immediately</li><li><strong>Clear</strong> Twilio’s audio buffer (they queue audio server-side)</li><li><strong>Capture</strong> what the user is saying</li><li><strong>Tell the LLM</strong> what the bot was saying when it got interrupted, so the conversation stays coherent</li></ol><p>I built this as a state machine:</p><pre>IDLE -&gt; LISTENING -&gt; PROCESSING -&gt; SPEAKING -&gt; INTERRUPTED<br>                                      ^              |<br>                                      |              v<br>                                      +--- LISTENING &lt;-+</pre><p>The tricky part was distinguishing <em>the user’s voice</em> from <em>the bot’s own audio echoing back through the phone</em>. Twilio streams are bidirectional — the audio you send out sometimes comes back in the incoming stream. If you’re not careful, the bot interrupts itself.</p><p>My solution was a dual-threshold approach:</p><ul><li><strong>Normal listening</strong>: VAD threshold of 0.5 (fairly sensitive)</li><li><strong>During bot speech</strong>: VAD threshold of 0.7 (much stricter)</li><li><strong>Echo cooldown</strong>: Ignore the first 500ms of audio after TTS starts playing (this is almost certainly echo)</li><li><strong>Confirmation window</strong>: Require 5 consecutive high-confidence speech chunks (~160ms) before confirming an interruption</li></ul><p>The gradual decrement was an important detail. Instead of resetting the interruption counter to zero on any silence frame, I decremented by one. This allows small gaps in natural speech (like the pause between “actually” and “never mind”) without resetting the detection:</p><pre>if is_speech:<br>    self.interruption_speech_chunks += 1<br>    if self.interruption_speech_chunks &gt;= INTERRUPTION_CONFIRM_CHUNKS:<br>        await self.handle_interruption(websocket)<br>else:<br>    if self.interruption_speech_chunks &gt; 0:<br>        self.interruption_speech_chunks -= 1  # Gradual decay, not hard reset</pre><p>When an interruption is confirmed, the handler stores what the bot was saying and passes it as context to the next LLM call:</p><pre>messages.append(SystemMessage(<br>    content=f&quot;[Note: You were interrupted while saying: &#39;{interrupted_context}&#39;. &quot;<br>            f&quot;The user is now responding. Acknowledge naturally if relevant.]&quot;<br>))</pre><p>This means if the bot is saying “Your appointment is scheduled for 3 PM on Thursday and — “ and the user cuts in with “Can we make it Friday?”, the LLM knows the full context of the interrupted sentence.</p><p>This whole feature — state machine, dual thresholds, echo cooldown, context passing — was built in a single day (December 31st), across two commits. It was the most satisfying piece of engineering in the entire project.</p><h3>The Pacing Problem: Don’t Dump Audio All At Once</h3><p>After interruption handling worked, I immediately found a new bug. The bot’s audio would play perfectly for the first response, then stutter and glitch on subsequent ones.</p><p>The issue: I was sending all audio chunks to Twilio as fast as possible. Twilio has an internal buffer, and when you dump 5 seconds of audio into it instantly, the buffer behaves unpredictably. Some chunks get dropped. Playback stutters.</p><p>The fix was <strong>paced sending</strong> — sending audio chunks at approximately real-time speed, staying only ~250ms ahead of actual playback:</p><pre># Send first 3 chunks quickly (initial buffer)<br># Then pace to real-time<br>elapsed_ms = (current_time - stream_start_time) * 1000<br>audio_sent_ms = (chunk_index + 1) * 80  # Each chunk = 80ms</pre><pre>ahead_ms = audio_sent_ms - elapsed_ms<br>if ahead_ms &gt; 250:  # Don&#39;t get more than 250ms ahead<br>    await asyncio.sleep((ahead_ms - 250) / 1000)</pre><p>This also had a beautiful side effect: because we’re sending chunks with small delays between them, the interruption detection code gets a chance to run between each chunk. Before pacing, the entire audio would be in Twilio’s buffer before we even checked for interruptions.</p><h3>The Latency Crusade: From 6 Seconds to Under 2</h3><p>By early January, the voice agent worked. But “works” and “feels like a conversation” are different things. The pipeline was still sequential:</p><pre>STT (1.0s) -&gt; LLM (1.5s) -&gt; TTS (1.5s) -&gt; Streaming (2.0s) = ~6s</pre><p>Six seconds of silence after every user utterance. I needed to attack this from every angle.</p><h3>Move 1: Shrink the Whisper Model</h3><p>I swapped from ggml-medium.en.bin (500MB) to ggml-tiny.en.bin (75MB). STT latency dropped from ~1 second to ~400ms. The accuracy tradeoff was real -- it would occasionally mishear unusual words -- but for conversational speech, it was good enough.</p><h3>Move 2: Stream the LLM Response</h3><p>Instead of waiting for the entire LLM response to generate, I switched to streaming. As the LLM produces text, I split it into sentences and yield each one immediately:</p><pre>async for chunk in self.llm.stream(messages):<br>    sentence_buffer += chunk.content<br>    sentences = re.split(r&#39;([.!?\n]+)&#39;, sentence_buffer)<br>    if len(sentences) &gt; 2:<br>        yield complete_sentence  # Don&#39;t wait for the full response</pre><p>This was also where I switched from Langflow to AWS Bedrock. Langflow added an HTTP middleware layer that cost an extra second. Bedrock’s streaming API let me get the first sentence back in ~500ms.</p><h3>Move 3: The Producer-Consumer TTS Pipeline</h3><p>This was the big one. The insight: while the bot is <em>speaking</em> sentence 1, I can be <em>generating TTS</em> for sentence 2, and the LLM can be <em>producing</em> sentence 3. All three stages can run concurrently.</p><p>I implemented this as a three-task async pipeline connected by queues:</p><pre>LLM Streaming Task ---[sentence_queue]---&gt; TTS Generator Task ---[audio_queue]---&gt; Audio Player Task<br>    (producer)                                  (transformer)                        (consumer)</pre><pre>sentence_queue = asyncio.Queue(maxsize=10)<br>audio_queue = asyncio.Queue(maxsize=5)</pre><pre># All three run concurrently<br>tts_task = asyncio.create_task(self.tts_generator_task(sentence_queue, audio_queue))<br>player_task = asyncio.create_task(self.audio_player_task(audio_queue, websocket))</pre><pre># Stream LLM output into the pipeline<br>async for sentence in llm_stream:<br>    await sentence_queue.put(sentence)</pre><p>The TTS generator pulls sentences from the queue, runs TTS.cpp (using asyncio.create_subprocess_exec to avoid blocking the event loop), and pushes the resulting audio into the audio queue. The audio player pulls from the audio queue and streams to Twilio with the pacing logic.</p><p>The result: the first sentence starts playing while the LLM is still generating the rest of the response. For a typical 3-sentence response, total perceived latency dropped from ~6 seconds to under 2 seconds.</p><h3>Move 4: Reduce the Silence Threshold</h3><p>I dropped SILENCE_DURATION_MS from 1500ms to 1000ms. This means the bot starts processing 500ms earlier after you stop talking. The tradeoff is less tolerance for slow speakers who pause between words, but for typical phone conversations, it felt right.</p><h3>The Combined Effect</h3><pre>Before:  STT (1.0s) + LLM (1.5s) + TTS (1.5s) + Stream (2.0s) = ~6.0s<br>After:   STT (0.4s) + First sentence LLM+TTS (1.0s) + Stream starts = ~1.8s</pre><p>From 6 seconds to under 2. Not by replacing any single component, but by overlapping everything that could be overlapped.</p><h3>Exploring Alternatives: Groq and Edge-TTS</h3><p>With the core pipeline working, I spent a day exploring what the solution would look like if we relaxed the “fully on-premise” constraint.</p><p><strong>Groq</strong> gave me LLM inference at absurd speed — their hosted Llama 3.3 70B model responds faster than most local models, with much better quality. The downside: it’s a cloud dependency, which defeated the original on-premise requirement.</p><p><strong>Edge-TTS</strong> (Microsoft’s cloud TTS API) produced more natural-sounding speech than Kokoro, with zero local compute. But again — cloud dependency, and the MP3 output needed conversion to WAV before Twilio could use it.</p><p>I kept these as separate files (main_groq.py) rather than replacing the local pipeline. They&#39;re useful as benchmarks -- if you know how fast the cloud version can be, you know what the local version is aiming for.</p><h3>Things I’d Do Differently</h3><p>The code is messy. I know. When you’re iterating on a proof-of-concept and your test cycle is “make a phone call and see if it sounds right,” clean architecture takes a back seat to rapid experimentation. But looking back:</p><p><strong>I should have built one modular file, not four copies.</strong> Each variant (Langflow, Bedrock, Groq, experimental) is a separate 1000+ line file with ~70% duplicated code. A plugin architecture for LLM and TTS backends would have been far cleaner.</p><p><strong>The global </strong><strong>conversation_handler singleton is a bug waiting to happen.</strong> It works for one-user testing but breaks with concurrent browser sessions. The Twilio path correctly creates per-call handlers, but the browser WebSocket path shares a single instance.</p><p><strong>I should have used </strong><strong>asyncio.create_subprocess_exec everywhere from the start.</strong> Some paths still use blocking subprocess.run() for Whisper and TTS, which blocks the event loop. The experimental file has both blocking and async TTS methods -- the async one exists because I learned the lesson mid-project.</p><h3>What I Learned</h3><p><strong>The .cpp/GGUF ecosystem is production-viable for on-device inference.</strong> Not for training, not for fine-tuning, but for running pre-trained models on consumer hardware? It works. Whisper.cpp on a Mac Mini transcribes faster than real-time. Kokoro TTS is intelligible if not beautiful. The tooling is mature enough to build real products on.</p><p><strong>Latency in voice agents is a pipeline problem, not a model problem.</strong> Swapping to a faster model helps, but the biggest wins came from architectural changes — streaming, pipelining, concurrent execution. The producer-consumer queue pattern turned a 6-second sequential pipeline into a 2-second overlapped one.</p><p><strong>Interruption handling is the feature that separates a demo from a product.</strong> Without barge-in support, your voice agent is a fancy answering machine. The state machine, echo cancellation, and context passing were the most complex code in the project, and they’re what made the difference between “this is a toy” and “this actually feels like a phone call.”</p><p><strong>Sometimes the best engineering is knowing what tradeoffs to make.</strong> Tiny Whisper instead of medium? Loses accuracy, gains 600ms. 1000ms silence threshold instead of 1500ms? Cuts off slow speakers, but feels more responsive. Every choice in a real-time system is a tradeoff, and the right answer depends on what your users will tolerate.</p><p>The voice agent is still running on that Mac Mini. It’s not pretty code, and there’s a list of things I’d improve before calling it production-ready. But it picks up the phone, listens to what you say, thinks about it, and talks back — all running locally, all in under two seconds.</p><p>For a project everyone else had given up on, I’ll take it.</p><p><em>The commit history read like a journal of real-time audio debugging: “Fix the slow playback issue,” “pace TTS streaming to near real-time,” “preserve decimal numbers in sentence splitting.” Each one a problem discovered by making a phone call and hearing something wrong.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a3746df1bde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Multi-Agent AI System on a $0 LLM Budget — Using a Model That Can’t Even Call Functions]]></title>
            <link>https://medium.com/@sanskarsharma.ai/i-built-a-multi-agent-ai-system-on-a-0-llm-budget-using-a-model-that-cant-even-call-functions-a0606350b084?source=rss-8b98ab86bd0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0606350b084</guid>
            <dc:creator><![CDATA[Sanskar Sharma ]]></dc:creator>
            <pubDate>Mon, 25 May 2026 13:49:59 GMT</pubDate>
            <atom:updated>2026-05-25T13:49:59.238Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What happens when you try to run a production-grade agent system on a 2GB quantized model running on your laptop? A lot of things. But also — it works.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WfCmZpvuEZ-4I-qr_tli4w.png" /></figure><p>Everyone’s building AI agents these days. Most demos look like this: call GPT-4, get a perfect JSON response, execute a tool, done. Ship it.</p><p>But what if you can’t afford GPT-4? What if you’re dealing with sensitive insurance data that can’t leave your network? What if your hardware is a mid-range laptop that overheats playing YouTube?</p><p>That’s exactly the constraint I built around. And honestly, it taught me more about building <strong>reliable</strong> agent systems than any tutorial using a frontier API ever could.</p><h3>The Idea</h3><p>I wanted to build an insurance customer support system — not a simple chatbot, but a proper multi-agent architecture where specialized agents handle different domains (billing, claims, policies) and a supervisor routes between them. Think of it as a tiny company of AI agents, each with their own expertise and tools.</p><p>The twist: <strong>everything runs locally</strong>. No API keys, no cloud bills, no data leaving the machine.</p><p>The model? <strong>phi-3-mini-4k-instruct</strong>, quantized down to Q3_K_M (about 2GB) running through llama.cpp. For context, that’s like asking an intern who’s had two hours of sleep to manage an entire insurance call center.</p><h3>The Architecture</h3><p>Here’s what the system looks like at a high level:</p><pre>User Message<br>    |<br>    v<br>[Supervisor Agent] — decides who should handle this<br>    |<br>    +---&gt; Policy Agent (has tools: get_policy_details, get_auto_policy_details)<br>    +---&gt; Billing Agent (has tools: get_billing_info, get_payment_history)<br>    +---&gt; Claims Agent (has tools: get_claim_status)<br>    +---&gt; General Help Agent (RAG over FAQ knowledge base)<br>    +---&gt; Escalation Agent (when things go sideways)<br>    |<br>    v<br>[Final Answer Agent] — polishes the response for the user<br>    |<br>    v<br>User Response</pre><p>The whole flow is orchestrated as a <strong>LangGraph state machine</strong> — the supervisor routes to a specialist, the specialist does its thing (potentially calling tools via a ReAct loop), control returns to the supervisor, and once it’s satisfied, the final answer agent cleans up the response.</p><p><strong>Tech stack:</strong></p><ul><li><strong>FastAPI</strong> with async everything (SQLAlchemy, aiosqlite, httpx)</li><li><strong>LangGraph</strong> for state machine orchestration</li><li><strong>llama.cpp</strong> server as the OpenAI-compatible LLM backend</li><li><strong>ChromaDB</strong> for FAQ retrieval (RAG)</li><li><strong>SQLite</strong> with 8 tables (customers, policies, billing, claims, etc.)</li><li><strong>SSE streaming</strong> for real-time agent event observability</li></ul><p>Nothing groundbreaking individually. But the way they fit together under the constraints of a tiny local model — that’s where it gets interesting.</p><h3>The First Big Problem: phi-3-mini Can’t Do Function Calling</h3><p>GPT-4 and Claude have native function calling — you define tools in the API request, the model returns a structured JSON with the tool name and arguments. Clean, reliable, done.</p><p>phi-3-mini? It doesn’t support that. At all. Especially not the Q3_K_M quantized version.</p><p>So I had to build my own tool calling system using the <strong>ReAct pattern</strong> (Reasoning + Acting). The idea is simple: you tell the model to think step by step, output which tool to call and with what arguments, and you parse that from free text.</p><p>The model is <em>supposed</em> to output:</p><pre>Thought: I need to look up the billing info for POL000004<br>Action: get_billing_info<br>Action Input: {&quot;policy_number&quot;: &quot;POL000004&quot;}</pre><p>What it <em>actually</em> outputs (Q3_K_M edition):</p><pre>Thought: The user wants billing details I will help them<br>Action: get_billing_info<br>Action Input: POL000004</pre><p>Or sometimes:</p><pre>I think we should use the get_billing_info tool for policy POL000004 to find the premium amount.</pre><p>Or my personal favourite:</p><pre>{&quot;action&quot;: &quot;get_billing_info&quot;, &quot;action_input&quot;: &quot;the policy number is POL000004&quot;}</pre><p>Same intent, four completely different formats. A rigid parser would fail on three of them.</p><h3>The 4-Layer Parser</h3><p>My solution was a <strong>progressive fallback parser</strong> with four layers:</p><ol><li><strong>JSON extraction</strong> — Try to parse the output as structured JSON (works ~20% of the time with Q3)</li><li><strong>Regex matching</strong> — Look for Action: and Action Input: patterns in the text</li><li><strong>Keyword detection</strong> — Scan for known tool names anywhere in the output, then find nearby JSON</li><li><strong>Fallback</strong> — If nothing works, treat the entire output as a final answer</li></ol><p>Each layer sets a parse_method field so I can track which layer caught it. In production, roughly 60% of calls were caught by the regex layer, 15% by JSON, 15% by keyword, and 10% fell through to fallback.</p><p>This parser is probably the single most important piece of the system. Without it, the agent is useless. With it, a $0 local model can do tool calling.</p><h3>The Second Big Problem: Wrong Arguments</h3><p>So the parser extracts Action: get_billing_info correctly. Great. But the Action Input is POL000004 — a raw string, not the {&quot;policy_number&quot;: &quot;POL000004&quot;} JSON the tool expects.</p><p>The regex parser handles this by wrapping unknown strings as {&quot;input&quot;: &quot;POL000004&quot;}. Seems reasonable, except get_billing_info() expects a policy_number parameter, not input. Boom — TypeError: got an unexpected keyword argument &#39;input&#39;.</p><p>This happened on <strong>every single tool call</strong> with the Q3 model.</p><h3>The Fix: Schema-Aware Argument Remapping</h3><p>I built an argument remapping layer that sits between the parser and the tool executor. It knows each tool’s parameter schema and does three things:</p><ol><li><strong>Single required parameter?</strong> Map input directly to it.</li><li><strong>Multiple parameters?</strong> Pattern-match the value — POL000004 looks like a policy number, CUST00001 looks like a customer ID, CLM000001 looks like a claim ID.</li><li><strong>Still can’t figure it out?</strong> Use the first property in the schema as a last resort.</li></ol><p>It also <strong>flattens nested dicts</strong> — the model sometimes outputs {&quot;policy_number&quot;: {&quot;policy_number&quot;: &quot;POL000004&quot;}} (yes, really) which would crash the SQL parameter binding.</p><p>Here’s the thing: with GPT-4, you’d never need any of this. The model just… follows instructions. But building these defensive layers taught me what <strong>production agent systems actually need</strong> — graceful handling of malformed LLM output, not just the happy path.</p><h3>The Third Big Problem: The Model Goes in Circles</h3><p>Even after fixing argument mapping, I hit a new issue. The billing agent would:</p><ol><li>Call get_billing_info — get data back successfully</li><li>Call get_billing_info again — same data</li><li>Call get_billing_info again — same data</li><li>Hit max steps, return garbage</li></ol><p>The model received the tool observation (the billing data), but it didn’t recognise it as useful data. It just kept calling the same tool. With Q3 quantization, instruction following takes a serious hit.</p><h3>Three Fixes Working Together</h3><p><strong>Duplicate detection</strong> — If the model calls the same tool with the same arguments twice in a row, short-circuit and return the observation data directly. Don’t waste another LLM call.</p><p><strong>Observation nudge</strong> — After appending the tool observation to the prompt, I add: <em>“You now have the data. Respond with: Thought: I have the information. Final Answer: …”</em> This explicit nudge helps the Q3 model understand what to do next.</p><p><strong>Max-steps fallback</strong> — If the agent exhausts all its steps, instead of returning raw model gibberish, it returns the last successful tool observation as formatted data. The user still gets useful information.</p><h3>The Fourth Big Problem: Repetition Loops</h3><p>The final answer agent’s job is to rewrite the specialist’s response into a clean, user-friendly reply. With Q3, here’s what I got:</p><pre>The premium for policy POL000004 is $350 per year. If you have any more questions, feel free to ask!</pre><pre>---</pre><pre>Given the complex nature of the user&#39;s request, here is a comprehensive response:</pre><pre>The premium for policy POL000004 is $350 annually. If you need more details...</pre><pre>---</pre><pre>In response to the user&#39;s inquiry, the following is a meticulously crafted response:</pre><pre>Hello! The annual premium for policy POL000004 is $350...</pre><p>500 tokens of the same answer repeated five times with increasingly formal introductions. Classic Q3 behaviour.</p><p><strong>The fixes:</strong></p><ul><li><strong>Stop sequences</strong> — [&quot;Observation:&quot;, &quot;\\\\n---&quot;, &quot;\\\\n\\\\n\\\\n&quot;] force the model to stop before entering a repetition loop</li><li><strong>Reduced max_tokens</strong> — from 800 to 150 for the final answer (you don’t need 800 tokens to say “$350/year”)</li><li><strong>Frequency penalty</strong> — 1.2 to penalise repeated tokens</li><li><strong>Post-processing</strong> — trim at the first -- separator as a safety net</li></ul><h3>The Fifth Problem: The Supervisor Routes to “End” Immediately</h3><p>The supervisor agent decides which specialist should handle the user’s question. On the first message, before any specialist has even run, the Q3 model would sometimes decide: “This question has been fully answered. Route to: end.”</p><p>No it hasn’t. Nobody answered anything yet. You’re the <em>first</em> node in the graph.</p><p><strong>The fix:</strong> A simple guardrail — if the supervisor routes to end but no specialist has responded yet (no assistant messages in state), override the routing using keyword matching on the user&#39;s input. &quot;Premium&quot; → billing agent. &quot;Claim&quot; → claims agent. &quot;Policy&quot; → policy agent.</p><p>It’s not elegant. It’s a keyword-based fallback for when the LLM can’t follow a 15-line routing prompt. But it works.</p><h3>The Context Budget Problem</h3><p>phi-3-mini has a 4K token context window. I ran llama.cpp with -c 2048 (even less) because my hardware couldn&#39;t handle more. Every token counts.</p><p>The supervisor prompt uses ~436 tokens. Each ReAct step adds the observation (~200–300 tokens). By step 3, you’re at 1300+ tokens of just the billing agent’s working prompt. By step 4? Context overflow. The model produces garbage because the prompt is truncated.</p><p><strong>The fix:</strong> A context management service with sliding window, entity extraction (regex for POL\\\\d{6}, CUST\\\\d{5}, CLM\\\\d{6}), and LLM-based compression of older messages. The newest messages get full text; older ones get summarised.</p><p>Combined with the stop sequences (which cut generation from 500+ tokens down to 50–100 per step), the ReAct loop now stays well within budget.</p><h3>What I Learned</h3><h3>1. Guardrails &gt; Model Quality (Up to a Point)</h3><p>A frontier model with zero guardrails will eventually fail in ways you don’t expect. A tiny model with good guardrails will reliably handle the cases you’ve planned for. The sweet spot is somewhere in between, but if I had to pick one — invest in guardrails.</p><h3>2. Parse Defensively, Always</h3><p>If your system depends on an LLM producing perfectly formatted output, your system will break. Build parsers that degrade gracefully. Track which parsing layer caught the output. Use that data to improve your prompts.</p><h3>3. The Happy Path Is the Easy Part</h3><p>Getting a multi-agent system to work on a demo is straightforward. Getting it to handle the weird outputs, the circular reasoning, the premature termination, the repetition loops — that’s where the real engineering is.</p><h3>4. Context Windows Are the Real Bottleneck</h3><p>Everyone talks about model quality and speed. The hardest constraint I dealt with was the context window. Every token in your prompt is a token the model can’t use for reasoning. Compress aggressively. Remove dead weight from prompts. Count your tokens.</p><h3>5. Local LLMs Are Viable (With Caveats)</h3><p>phi-3-mini Q3_K_M is at the absolute floor of what can work for multi-agent tool calling. Q4_K_M would probably halve the guardrail code I wrote. Q5 or Q6 would make most of it unnecessary. But even at Q3, with enough defensive engineering, it works.</p><h3>Limitations (Honest Ones)</h3><ul><li><strong>Session state is in-memory</strong> — restart the server, lose all conversations</li><li><strong>Q3_K_M is unreliable</strong> — the guardrails catch most failures, but edge cases remain</li><li><strong>Response latency is high</strong> — 30–60 seconds per response on my hardware (multiple LLM calls per request)</li><li><strong>No authentication</strong> — this is a demo, not a production deployment</li><li><strong>Single slot on llama.cpp</strong> — one request at a time, no concurrent users</li></ul><h3>The Numbers</h3><ul><li><strong>6 agents</strong> in the orchestration graph</li><li><strong>5 tools</strong> across 3 specialist agents</li><li><strong>4-layer parser</strong> for ReAct output</li><li><strong>8 database tables</strong> with 1000+ seeded customers and 1500+ policies</li><li><strong>$0</strong> in API costs</li></ul><h3>What I’d Do Differently</h3><p>If I were starting over:</p><ol><li><strong>Start with Q5_K_M</strong>, not Q3. The debugging time I spent on Q3 quirks wasn’t worth the 1GB RAM savings.</li><li><strong>Add structured output constraints</strong> at the llama.cpp level (grammar-guided generation) instead of parsing free text.</li><li><strong>Build the observability dashboard from day one</strong>. Being able to watch agent events stream in real-time would have saved hours of log-reading.</li></ol><h3>Try It Yourself</h3><p>The entire project is open source. You need Python 3.10+, llama.cpp, and a phi-3-mini GGUF model file. No API keys, no cloud accounts, no credit card.</p><pre># Start llama.cpp<br>llama-server -m phi-3-mini-4k-instruct.Q4_K_M.gguf -c 2048 --port 8080</pre><pre># Start the API<br>uv sync<br>uv run python scripts/seed_db.py<br>uv run uvicorn app.main:app --reload</pre><p>Ask it about policy POL000004’s premium. Watch six agents coordinate to fetch data from a database and return a clean answer. All running on your laptop.</p><p><em>If you’re building agent systems and want to chat about the weird edge cases nobody blogs about, feel free to reach out. The interesting problems are never in the happy path.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0606350b084" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Tool That Finds Where AI Agents Should Go in Your Codebase “Without Using AI”]]></title>
            <link>https://medium.com/@sanskarsharma.ai/i-built-a-tool-that-finds-where-ai-agents-should-go-in-your-codebase-without-using-ai-aede4fbdf902?source=rss-8b98ab86bd0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aede4fbdf902</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[abstract-syntax-tree]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[graph-algorithms]]></category>
            <dc:creator><![CDATA[Sanskar Sharma ]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 18:32:42 GMT</pubDate>
            <atom:updated>2026-03-29T18:32:42.358Z</atom:updated>
            <content:encoded><![CDATA[<p>Everyone’s building AI agents right now. Agents that write code, agents that review code, agents that deploy code. And here’s a question everybody seems to be asking: <strong>Can I have agents in my systems? </strong>And the question translates for a developer to W<strong>here in your existing codebase should an agent actually go? </strong>because fulfilling the requirements is sometimes necessary to “meet expectations.”</p><p>Not every function needs an AI wrapper. Not every API call benefits from an agent. But some parts of your code — the retry loops, the orchestration functions, the CRUD clusters — are practically begging for one.</p><p>I built a tool called <a href="https://github.com/SanskarSharma27/agent-probe"><strong>agent-probe</strong></a> that finds these spots. And the twist? It doesn’t use an LLM to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m40jQNtcfAlyDzk59qlRmA.png" /></figure><h3>The Idea That Started It All</h3><p>As a Solutions Engineer for an Agentic Application, I’d be thrown the question of <strong>Will it integrate with our system? </strong>a lot. And I’d go on to say if you let us use your APIs, then yes. But whenever I integrated agents into actual systems, I felt that unknowingly I was following a pattern and as a developer I had to spend some time to automate this.</p><p>You could ask ChatGPT to read your code and suggest integration points. But that felt wrong to me. The question of “where should an agent go” isn’t a language understanding problem — it’s a <strong>structural</strong> problem. You’re looking for:</p><ul><li>Functions that call external APIs (boundaries where an agent could add intelligence)</li><li>Functions that orchestrate many downstream calls (coordination hubs)</li><li>Retry/polling patterns (where an agent could handle failure more gracefully)</li><li>CRUD clusters (data lifecycle points that could benefit from agent workflows)</li></ul><p>These are all patterns you can detect from the <strong>shape</strong> of the code, not its meaning. You don’t need to understand what sync_with_retry() does in English — you just need to see that it calls time.sleep(), makes an API call, and has &quot;retry&quot; in its name.</p><p>That realization was the starting point: <strong>what if I could build something that answers this question deterministically, in milliseconds, with zero API keys?</strong></p><h3>Why C++?</h3><p>I know, I know. “Just use Python.” And honestly, for a quick prototype, I would have. But I had a few reasons:</p><p><strong>1. I wanted to learn production C++.</strong> I’d been writing C++ for DSA and competitive programming, but I’d never structured a real project with headers, CMake, tests, and external dependencies. This was my excuse to learn.</p><p><strong>2. Tree-sitter is a C library.</strong> The parser I wanted to use is written in C. Calling it from C++ is natural — no FFI overhead, no bindings to maintain.</p><p><strong>3. Performance matters here.</strong> Parsing thousands of files and running graph algorithms should be fast. I didn’t want my analysis tool to be slower than the code it’s analyzing.</p><h3>The Architecture: Parse, Graph, Analyze</h3><p>I settled on a three-stage pipeline:</p><pre>Source Code → AST Parser → Call Graph → Pattern Detectors → Findings</pre><p><strong>Stage 1: Parse the code into an AST.</strong></p><p>I use <a href="https://tree-sitter.github.io/tree-sitter/">Tree-sitter</a>, the same parsing framework that powers GitHub’s code navigation and Neovim’s syntax highlighting. For each source file, Tree-sitter gives me a full Abstract Syntax Tree — every function definition, every class, every function call, every import.</p><p><strong>Stage 2: Build a call graph.</strong></p><p>From the AST nodes, I construct a weighted directed graph. Functions become nodes. “Function A calls Function B” becomes a directed edge. I also add edges for imports, class inheritance, and class-method containment. This gives me a complete picture of how the codebase is wired together.</p><p><strong>Stage 3: Run graph algorithms and pattern detectors.</strong></p><p>This is where it gets interesting. I run two graph algorithms:</p><ul><li><strong>Brandes’ betweenness centrality</strong> — finds functions that sit on many shortest paths between other functions. These are structural bottlenecks, the “highway junctions” of your codebase.</li><li><strong>PageRank</strong> — yes, the Google algorithm. Applied to a call graph, it identifies functions that are called by many <em>important</em> functions. A function’s importance is recursive — it depends on who calls it.</li></ul><p>Then four pattern detectors scan the graph:</p><ul><li><strong>API Call Analyzer</strong>: matches function calls against known HTTP/DB/RPC libraries (requests, axios, grpc, prisma, etc.)</li><li><strong>Fan-Out Analyzer</strong>: finds functions with high out-degree AND high centrality — the orchestrators</li><li><strong>Retry Analyzer</strong>: detects sleep calls + API calls + retry-suggestive names</li><li><strong>CRUD Analyzer</strong>: groups functions by entity name and checks Create/Read/Update/Delete coverage</li></ul><p>Each finding gets a confidence score:</p><pre>confidence = base_type_weight × (1 + 0.1 × evidence_count) × (1 + pagerank_boost)</pre><p>That PageRank boost is key. A retry function that sits at a critical junction in the call graph matters more than an isolated one. The graph structure informs the confidence.</p><h3>The Part Nobody Tells You About: Multi-Language Parsing</h3><p>Supporting just Python was straightforward. Tree-sitter has a Python grammar, and the AST is clean: function_definition, class_definition, import_from_statement. You walk the tree, extract what you need, done.</p><p>Then I decided to add JavaScript.</p><p>On paper, it should be simple — Tree-sitter has a JavaScript grammar too. In practice, Python and JavaScript have fundamentally different AST structures for the same concepts.</p><p><strong>Functions are named differently.</strong> Python has function_definition. JavaScript has function_declaration. Same concept, different node type name.</p><p><strong>Arrow functions don’t have names.</strong> This was the tricky one. In JavaScript:</p><pre>const fetchData = async (url) =&gt; {<br>    const response = await fetch(url);<br>    return response.json();<br>};</pre><p>The arrow_function AST node contains the parameters and body, but NOT the name. The name fetchData lives in the parent variable_declarator node. So to extract arrow function names, I had to look <em>up</em> the tree, not down.</p><p><strong>Imports are completely different.</strong> Python has import_from_statement with dotted_name children. JavaScript uses import_statement with import_clause, named_imports, and import_specifier children. My first implementation tried to handle both with the same code path — it produced empty import lists for every JS file. That was a fun debugging session.</p><p>The solution was an abstraction I’m actually proud of: the <strong>LanguageProfile</strong> interface.</p><pre>class LanguageProfile {<br>public:<br>    virtual std::string function_def_type() const = 0;  // &quot;function_definition&quot; or &quot;function_declaration&quot;<br>    virtual std::string class_def_type() const = 0;<br>    virtual std::string arrow_function_type() const { return &quot;&quot;; }<br>    virtual std::string method_def_type() const { return &quot;&quot;; }<br>    // ... ~20 methods mapping grammar-specific details<br>};</pre><p>The parser algorithm stays identical. The grammar details come from the profile. Adding JavaScript meant implementing JavaScriptProfile — zero changes to the parser itself. This is the Strategy Pattern, and it worked beautifully.</p><h3>The 16,000 File Incident</h3><p>One of my favorite bugs. I ran agent-probe on one of my other projects and saw:</p><pre>agent-probe v0.1.0 — 16,189 files to scan</pre><p>Sixteen thousand files? The project has maybe 60 source files. What happened?</p><p>Turns out my file collector was doing a naive recursive directory walk filtered only by extension. It was happily walking into .venv/ (the Python virtual environment with thousands of installed packages), node_modules/, __pycache__/, .git/ internals — everything.</p><p>The fix was satisfying: a skip set of 25+ common non-source directory names, plus automatic skipping of all hidden directories. I also added disable_recursion_pending() to prune entire subtrees instead of checking files one by one.</p><p>After the fix: <strong>16,189 files → 63 files.</strong> Same project.</p><h3>Tuning Signal vs Noise: The Fan-Out Problem</h3><p>Early on, I ran agent-probe against a real project and got 22 findings — 21 of which were fan-out. That’s not useful signal, it’s noise.</p><p>The problem was my fan-out analyzer was too loose. It flagged anything with out-degree &gt;= 3 OR moderate centrality. In a real codebase, most functions call at least 3 others. The fix was a series of tighter gates:</p><ol><li><strong>Require &gt;= 4 outgoing CALLS edges</strong> (not imports or contains — just actual function calls)</li><li><strong>Add a PageRank floor</strong> — if nobody important calls you, you’re probably not an orchestrator</li><li><strong>Make centrality a booster, not a standalone trigger</strong> — high centrality alone doesn’t mean fan-out</li></ol><p>After the fix: <strong>21 fan-out findings → 8</strong>. Every remaining one was a legitimate orchestrator — the LangGraph state machine builder, the ReAct loop, the supervisor router, the parser’s 4-layer fallback. Real signal.</p><p>The lesson: static analysis tools need calibration against real codebases, not just test fixtures.</p><h3>From “Here’s Where to Look” to “Here’s What to Do”</h3><p>Finding integration points is useful. But handing someone a list of functions and saying “good luck” leaves a gap. So I added a -f plan output mode that generates an actionable integration guide:</p><pre>agent-probe -p ./my-project -f plan</pre><p>This produces a markdown document where each finding maps to a concrete agent pattern:</p><pre>### 1. sync_with_retry — flask_app.py:59</pre><pre>**Type**: RETRY | **Confidence**: 1.00</pre><pre>**Why**: Function already handles retry logic manually. An agent replaces<br>brittle sleep/loop with observable, configurable backoff.</pre><pre>**Suggested agent role**: Autonomous retry agent with configurable backoff<br>and dead-letter queue</pre><pre>**LangChain scaffold**:<br>    @tool<br>    def sync_with_retry_agent(input: dict) -&gt; dict:<br>        &quot;&quot;&quot;Agent wrapper for sync_with_retry.&quot;&quot;&quot;<br>        # TODO: implement agent logic<br>        pass</pre><p>The tool already knows the function name, file, line, type, and confidence. That’s enough to generate the <em>shape</em> of where an agent goes. The JSON output also includes suggested_role, rationale, and framework fields per finding, making it consumable by downstream tools or LLM prompts.</p><p>The mapping is deterministic — each finding type corresponds to a known agent pattern:</p><p>Finding Agent Pattern <strong>Retry</strong> Autonomous retry agent with backoff + dead-letter queue <strong>API Call</strong> Boundary agent with caching, rate limiting, fallback <strong>Fan-Out</strong> Orchestration agent with parallel execution + partial failure handling <strong>CRUD</strong> Data lifecycle agent with event emission + audit logging</p><p>This one addition turned the tool from “static analysis report” into “actionable integration guide.”</p><h3>Bringing It to the Browser</h3><p>A CLI tool is great for CI pipelines, but I wanted something you could show people. So I built a web visualization: a FastAPI backend that shells out to the C++ binary, and a D3.js force-directed graph on the frontend.</p><p>The graph is surprisingly informative. Nodes are colored by finding type — blue for API calls, red for retry patterns, purple for fan-out hubs, green for CRUD clusters. Node size scales with PageRank score. You can click a node to highlight its connections, or click a finding in the sidebar to focus on it.</p><p>The best addition came later: <strong>GitHub URL scanning</strong>. Instead of cloning a repo locally, you can just paste a GitHub URL — https://github.com/pallets/flask — and the tool clones it to a temp directory, scans it, shows the graph, and cleans up. On the CLI side, same thing:</p><pre>agent-probe -p &lt;https://github.com/pallets/flask&gt; -f summary</pre><p>Flask scanned in seconds, entirely locally.</p><h3>What I Learned</h3><p><strong>CMake is powerful but has a learning curve.</strong> FetchContent for dependency management is genuinely good — all six dependencies (Tree-sitter, two grammars, CLI11, nlohmann/json, GoogleTest) download and build automatically from a clean checkout. But CMake 4.0 broke my build with a policy change, and debugging that was not fun.</p><p><strong>Windows C++ development is an adventure.</strong> MSYS2/MinGW-w64 works, but the DLL dependency issue caught me off guard. My binary ran fine from the MSYS2 terminal but crashed with 0xC0000139 (STATUS_ENTRYPOINT_NOT_FOUND) from PowerShell because the runtime DLLs weren&#39;t on PATH. The FastAPI backend needed a special _build_env() helper to inject the MSYS2 bin path.</p><p><strong>Tree-sitter’s AST node types are discoverable, not documented.</strong> The single most useful debugging technique was printing the S-expression of a parsed file:</p><pre>char* s = ts_node_string(ts_tree_root_node(tree));<br>printf(&quot;%s\\\\n&quot;, s);<br>free(s);</pre><p>This dumps the entire AST. When adding JavaScript support, I spent hours in the <a href="https://tree-sitter.github.io/tree-sitter/playground">Tree-sitter Playground</a> pasting code and studying the tree structure. That’s how I discovered that arrow function names live in parent nodes.</p><p><strong>Graph algorithms have real applications beyond interviews.</strong> I’ve implemented BFS and PageRank in coding questions, but using Brandes’ centrality to find structural bottlenecks in real code felt completely different. The algorithm is the same, but the interpretation — “this function is a highway junction in your codebase” — makes it tangible.</p><p><strong>Analysis tools need calibration, not just correctness.</strong> My fan-out analyzer was technically correct — it found functions with multiple outgoing calls. But it flagged 21 out of 22 findings as fan-out, which is useless. The fix wasn’t a bug fix — it was tuning thresholds, adding PageRank-based filtering, and switching from OR to AND logic. Getting the analysis right is only half the battle; making the output useful is the other half.</p><h3>What’s Next</h3><p>A few directions I’m thinking about:</p><ul><li><strong>More languages.</strong> The LanguageProfile abstraction makes this straightforward — Go, Rust, and Java each need a profile class and a Tree-sitter grammar. No parser changes.</li><li><strong>Incremental analysis.</strong> Tree-sitter supports incremental parsing — you can re-parse only the changed portion of a file. This would make agent-probe viable as a real-time IDE tool.</li><li><strong>More pattern detectors.</strong> Dead code detection (functions with in-degree 0), circular dependency detection, security-sensitive function chain analysis.</li><li><strong>LSP server.</strong> Imagine seeing “Agent Integration Point: retry pattern, confidence 0.92” as an inline hint in your editor.</li></ul><h3>Try It</h3><p>agent-probe is open source. Clone it, build it, point it at your codebase. If you find an interesting integration point that you wouldn’t have noticed otherwise, I’d love to hear about it.</p><pre># Scan any GitHub repo directly<br>agent-probe -p &lt;https://github.com/your-favorite/project&gt;</pre><pre># Get an actionable integration plan with LangChain scaffolds<br>agent-probe -p ./your-project -f plan</pre><pre># Or get structured JSON for CI/CD pipelines<br>agent-probe -p ./your-project -f json</pre><p>The whole thing builds from scratch with two commands:</p><pre>cmake -B build -DCMAKE_BUILD_TYPE=Release<br>cmake --build build</pre><p>No Python. No npm. No API keys. No cloud. Just code analyzing code.</p><p><em>If you’re interested in the technical details — how Brandes’ centrality works on call graphs, how the LanguageProfile abstraction handles JS arrow functions, or how I went from 16,000 files to 63 — check out the </em><a href="https://github.com/SanskarSharma27/agent-probe/blob/main/README.md"><em>README</em></a><em> or drop me a message.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aede4fbdf902" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>