<?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 Ajay raj S on Medium]]></title>
        <description><![CDATA[Stories by Ajay raj S on Medium]]></description>
        <link>https://medium.com/@ajayraj296?source=rss-4f64fc69a652------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Bj26KOcDEoCkUmRIIlqVaw.jpeg</url>
            <title>Stories by Ajay raj S on Medium</title>
            <link>https://medium.com/@ajayraj296?source=rss-4f64fc69a652------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:59:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajayraj296/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[Models Are Eating Harnesses]]></title>
            <link>https://medium.com/deployedai/models-are-eating-harnesses-fffb7e1442c8?source=rss-4f64fc69a652------2</link>
            <guid isPermaLink="false">https://medium.com/p/fffb7e1442c8</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ajay raj S]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 15:23:22 GMT</pubDate>
            <atom:updated>2026-09-18T15:23:22.511Z</atom:updated>
            <content:encoded><![CDATA[<p>The consensus eighteen months ago was clear: frontier models couldn’t be trusted. They hallucinated. They failed silently. They needed guardrails, lots of them.</p><p>So everyone building agents layered on complexity. Planner agents coordinating researchers. Verifier agents checking the work. Context routers deciding which information goes where. System prompts, skill libraries, MCP servers, retry loops, multi-turn validation. The harness was the actual product. The model was a component inside it.</p><p>That assumption is no longer true, and the builders who haven’t noticed are now maintaining overhead that’s destroying their margin.</p><h3>What we’re actually building</h3><p>Let me define the term precisely, because it gets thrown around.</p><p>A harness is the complete scaffolding around a model that makes it capable of real work. This includes:</p><ul><li>Prompt engineering and context engineering — the instructions, skill libraries, example traces that guide behavior</li><li>Tool definition and orchestration — which APIs the model can call, constraints on their use, orchestration between them</li><li>Process architecture — planners, routers, review workflows, multi-stage verification</li><li>Guardrails and execution constraints — rate limiting, output validation, safety checks, environment sandboxes</li></ul><p>Through 2024 and into 2025, the working theory was correct: this layer was the differentiator. You could point any model at a problem. The harness was what made it work.</p><p>That’s changing faster than most people’s architecture is tracking.</p><h3>The shift happened quietly</h3><p>Frontier models got substantially more reliable, and the shift was dramatic enough that it rewired task difficulty in most domains.</p><p>Take security research. Two years ago, a model flagging a vulnerability was low-confidence — lots of false positives, lots of hallucinations misidentifying safe code as unsafe. The harness had to carry that work: threat modeling agents, specialized verification passes, secondary checkers, thresholds before escalation. The model was noisy. The harness was the filter.</p><p>Run the same task now. The false positive rate dropped. Hallucinations are rarer. When a current frontier model flags a vulnerability, the finding is likely real — maybe not exploitable, but real. The model’s reasoning about code, about threat models, about system behavior is simply different.</p><p>This rippled across domains. Agents got better at understanding what they didn’t know. They recovered faster when a tool call failed. They reasoned through multi-step problems without needing an external planner to supervise them. The model started doing the work the harness was built to enforce.</p><h3>Minimalism is outperforming elaborate scaffolding</h3><p>Look at the actual evidence.</p><p>Pi Agent ships with four tools: read, write, edit, execute. No specialized orchestration. No reviewer layer. No verification gate. It performs at parity with Claude Code and other substantially more elaborate systems on most tasks.</p><p>Why? Because the frontier model is already executing the logic that you’d normally build custom architecture to enforce. It knows when to read before writing. It understands when to verify its work. It can reason about whether it even needs to call a tool.</p><p>This is even sharper in vulnerability research. That domain is a search problem fundamentally. You have a massive space of code paths, object lifetimes, weird inputs, parser edge cases, component interactions. Somewhere in that space is a behavior worth understanding. Your job is to explore that space intelligently until you find something interesting.</p><p>An overly prescriptive harness actually gets in the way. If your system says “first threat model, then enumerate endpoints, then run these checks, then escalate to secondary verification,” you’ve already decided what good research looks like. You’ve constrained the search path.</p><p>But the model might notice something that doesn’t fit your threat model. It might spot an invariant that feels wrong. It might want to follow that thread instead of adhering to your predetermined workflow. In the current generation of models, that instinct is often worth preserving.</p><p>The rigid harness blocks that. Minimalism leaves room for it.</p><h3>The cost of carrying complexity</h3><p>Every layer of scaffolding has a direct economic cost.</p><p>Your system prompt costs tokens. Your skill library costs tokens. Your context of enterprise failure modes costs tokens. An elaborate workflow means more turns, more state carried forward, more opportunity for information to degrade between steps. Multi-stage verification means the model reads a much larger instruction manual before it ever gets to the actual work.</p><p>You’re spending frontier model inference on executing architecture that the model could internalize on its own.</p><p>The token math gets brutal fast. If your harness adds 8,000 tokens of context per request, and you’re running hundreds of tasks, you’re paying for that context every single time. If a newer model can generate that reasoning internally — in fewer tokens, without external orchestration — suddenly the harness is overhead.</p><p>The economics flip sharply when a new model generation arrives that can handle what used to require multi-agent orchestration in pure inference. The beautiful planning-research-verification workflow you spent months building isn’t an advantage anymore. It’s technical debt that makes you slower than someone who just pointed the new model at the problem.</p><h3>Why the moat collapses</h3><p>This is why the “elaborate harness as moat” story doesn’t survive the next model generation.</p><p>You can spend six months building a beautiful workflow. Planning agents. Research agents. Coding agents. Reviewers. Verifiers. It works. You have an operational advantage.</p><p>Then a new frontier model ships. It internalizes half of that workflow internally. Suddenly your architecture is overhead. Every model generation pulls another piece of agent engineering back into the model itself.</p><p>The companies that raised hundreds of millions to build “AI infrastructure” made this bet: the harness is the asset. They structured entire platforms around elaborate orchestration and verification. They built go-to-market around deployment complexity.</p><p>But the actual asset was always the model. And they don’t control that.</p><h3>The shape of minimal harnesses</h3><p>This doesn’t mean no scaffolding. It means rebuilding what belongs in the harness versus what belongs in the model’s native capability.</p><p><strong>Keep in the harness:</strong></p><ul><li>Context that the model cannot discover itself — the structure of a codebase you want it to analyze, the hard rules of a system it’s operating inside, the constraints on what it isn’t allowed to do</li><li>Tools and their accurate definitions — the model needs to know which APIs exist and what they actually do</li><li>Verification that must be deterministic — output validation, safety checks, anything where non-determinism is a bug</li></ul><p><strong>Drop from the harness:</strong></p><ul><li>Orchestration the model can handle internally — planners, multi-stage workflows, explicit reasoning gates</li><li>Redundant verification — if the frontier model is already producing reliable outputs, additional review loops just add latency and cost</li><li>Overly prescribed reasoning paths — let the model explore</li></ul><p>The best harnesses are increasingly boring. They hand the model a problem, a set of tools, the context it can’t discover on its own, and then they get out of the way.</p><h3>Close the gap with knowledge, not architecture</h3><p>Here’s what actually separates a bare model from a capable agent system: operational knowledge about how systems fail.</p><p>The difference between a 58% success rate and a 92% success rate on enterprise tasks isn’t elegant orchestration. It’s knowing that status=resolved also matches tickets that were resolved and then reopened. It&#39;s knowing that a pagination endpoint returns 200 but only 50 records. It&#39;s knowing that a name filter matches one of three org records from an acquisition, not all of them.</p><p>None of that knowledge lives in the model’s weights. It lives in the head of someone who already got burned by it in production.</p><p>That’s the asset. And it’s method, not IP. Method can be written down.</p><p>The vendors who understood this built private failure catalogues — exhaustive lists of ways systems fail silently in production. Their engineers accumulated that knowledge across client engagements. They kept it private.</p><p>But the structure of that knowledge doesn’t require orchestration. It requires retrieval. A well-organized failure catalogue that the model consults at the right moments can close most of the gap a frontier model leaves open.</p><p>The moat isn’t the harness architecture. It’s the knowledge.</p><h3>The closing thought</h3><p>If you’re building an agent system right now, stop asking “what clever harness should I build?” Ask instead: “what can only I provide that this model cannot?”</p><p>For most tasks, the answer is three things:</p><ol><li>Context specific to your domain that the model cannot discover on its own</li><li>The actual tools that do your work</li><li>Knowledge about how those tools fail silently</li></ol><p>Everything else is overhead.</p><p>The signal that you’ve got the harness right is that it’s almost boring. No multi-agent choreography. No elaborate skill files. No clever routers. Just a model pointed at a problem, with the specific context it actually needs and room to work.</p><p>That boring harness is probably the right one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fffb7e1442c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deployedai/models-are-eating-harnesses-fffb7e1442c8">Models Are Eating Harnesses</a> was originally published in <a href="https://medium.com/deployedai">DeployedAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enterprise AI: The Adoption Path Forward]]></title>
            <link>https://medium.com/deployedai/enterprise-ai-the-adoption-path-forward-c91e6e33541c?source=rss-4f64fc69a652------2</link>
            <guid isPermaLink="false">https://medium.com/p/c91e6e33541c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Ajay raj S]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 07:40:04 GMT</pubDate>
            <atom:updated>2026-09-08T07:40:04.272Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A funded vendor’s agent scores 92.9%. A bare harness on the same weights scores 58.6%. I closed that gap for $300 and MIT licensed it. What that means for build vs buy.</em></p><p>Over the past few months I got the same call from Google, Pfizer, GE Healthcare, and a handful of smaller companies including DevRev, Avataar and Questt. Different products, different industries, same role: sit at the customer site, advocate, prototype, deploy. Forward deployed engineer.</p><p>Around the same time, <a href="https://medium.com/u/be36e94a7e47">Google</a> raised money by issuing 100 year bonds. A company that prints cash was borrowing on a century-long horizon to fund AI infrastructure. I spent three years as a quant before this and that combination stuck with me: enormous capital going into the stack, and simultaneously a hiring scramble for people to sit in a room with the customer and make it actually work.</p><p>Those two facts are the same fact. The second one is what this post is about.</p><h3>Six years of the same job title</h3><p>I have been a forward deployed engineer for six years, and the job has been three completely different jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5alKGEWp_rZCmTec5i6BgQ.png" /></figure><p>At <a href="https://medium.com/u/6d7067f5e211">Qure AI</a> I spent three years taking ML models that find pathologies in X-rays, CT and MRI scans and deploying them into hospitals and OEM devices. The model was the product. It was validated, regulated, and essentially fixed. My job was the integration layer: PACS, DICOM, worklists, the specific way one hospital’s radiology workflow differed from the next. Real work, but thin relative to the platform. The company shipped one thing many times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46xjyRg3ey3GgIRWUDohvQ.png" /></figure><p>Nine deployments, one set of weights. Everything that varied was plumbing.</p><p>Then three years self employed, working with small hedge funds in the US on their research process. Here there was no platform at all. Every engagement was a harness written around a model for a particular research job. I did develop patterns, and I templatised what I could, exploration and exploitation strategies for hypothesis generation being the obvious ones. But the customisation was much heavier than anything at Qure.ai, and I worked with one client at a time, fully committed.</p><p>Now look at the third column. Enterprise agent vendors in 2026 are shaped like the second case while being sold like the first.</p><p>Here is the number that made me stop and think. Talking to people at these companies and to their customers, the ratio of forward deployed engineers to customers is greater than one almost everywhere. For one platform company it is 2.3. Two point three engineers per customer.</p><p>That is my own field observation from conversations, not a published statistic, so weigh it accordingly. But if the platform were genuinely the product, headcount would not scale with customers. It does.</p><h3>So what is a platform?</h3><p>Nothing about the above is wrong or dishonest. Enterprises are getting real value. When they run build vs buy today, buy usually wins, and it wins on capability, not on marketing. The delta is real.</p><p>The pattern I keep seeing is this. An enterprise tries to build in house. It stalls somewhere around 50 to 60 percent task success. It evaluates vendors in parallel. A vendor demos at 95 percent. That gap is enormous and obvious, and the enterprise reasonably concludes the vendor has something it does not.</p><p>Then you read the vendor descriptions side by side and they use the same handful of phrases. Knowledge graphs. Connecting disconnected systems. Enterprise context.</p><p>So what is actually in that gap?</p><p>My claim is that it is not intellectual property. It is a workflow. It is operational knowledge about how agents fail silently inside real systems, accumulated by forward deployed engineers across engagements, compounding privately inside the vendor, built out of the customer’s own operational reality, and never written down anywhere the customer can reach.</p><p>The customer rents the outcome. The vendor keeps the compounding asset.</p><h3>Why “silent” is the load-bearing word</h3><p>Take a task: close all Acme tickets resolved last week.</p><p>The agent calls the API with a customer filter, a status filter and a date range. Three ways this goes wrong:</p><ul><li>status=resolved also matches tickets that were resolved and then reopened. Six of them are live customer issues. The agent closes them.</li><li>Acme has three org records from an acquisition. The name filter matches one. The agent sees a third of the tickets and believes that is all of them.</li><li>The endpoint paginates at 50. There were 340. The agent processes 50 and reports the job complete.</li></ul><p>Every one of those returns HTTP 200. No exception, no empty result, nothing that looks like failure. The agent is not uncertain and does not hedge. It is confident, wrong, and the environment confirms it.</p><p>Now ask where the agent could have found the information that prevents this. Not the docs, which say status=resolved filters resolved tickets, and that is true. Not the schema, which is well formed. Not the tool response, which succeeded.</p><p>It exists in exactly one place: the head of somebody who already got burned by it.</p><p>That is the asset. And notice its acquisition cost. You cannot build a moat out of listening to customers, because customers talk to everyone. You can absolutely build one out of failure knowledge, because the only way to get it is to break things in production and pay attention, repeatedly, for years.</p><h3>A note on Enterprise-Bench, since it seems to be like LongMemEval</h3><p>DevRev publishes Enterprise-Bench, described on their homepage as the world’s first benchmark for enterprise AI agents. I found it while interviewing with them. It is 14 tasks, 10 trials each, 140 trials per configuration, curated from enterprise data.</p><p>It gets compared to LongMemEval, and the comparison is usually framed as a difference in dataset. I think the difference is deeper than that, and it matters for what follows.</p><p>LongMemEval is built by an authoring pipeline. Someone picks a fact, writes a session containing it, buries it under filler sessions, and writes a question whose answer is that fact. The evidence is labelled, because the author knows where they put it. A correct question-to-evidence mapping is guaranteed to exist. Difficulty is a dial, and the dial is haystack size. It is a clean controlled experiment, and it measures retrieval.</p><p>Enterprise-Bench is not built that way. An agent is placed in a working system with tools and given a goal. The system’s behaviour was not invented for the benchmark. There is no authored question-to-evidence map, because there isn’t one.</p><p>So: LongMemEval tests search over a space someone has already mapped. Enterprise-Bench tests behaviour in a space nobody has mapped. A benchmark that guarantees the answer is in the context cannot measure whether you possess knowledge that is not. That is precisely the knowledge I am arguing about.</p><p>There is a second structural difference. LongMemEval instances are single shot and independent. An Enterprise-Bench trial is a chain of dependent decisions, so an early silent error is executed against perfectly for the next nine steps. Silent failure only exists where there are actions.</p><h3>What I did</h3><p>I was rejected by DevRev, incidentally, and I am fairly sure the moment was when I expanded RAG as retrieval augmented gatherings.<a href="https://claude.ai/epitaxy/local_00b7e4dc-0b01-4a43-b76b-75f7306d840b#user-content-fn-1">1</a></p><p>Afterwards I got curious about something narrow: I have spent six years accumulating exactly the kind of harness knowledge I just described. Could I write it down and close the delta with it, without any model work at all?</p><p>Put less kindly, I wanted to find out whether someone who cannot reliably expand the acronym could close the gap anyway. That is not only a joke at my own expense. It is the claim in miniature. If the delta were deep technical knowledge, a person who fumbles the vocabulary should not be able to touch it.</p><p>Two methods, both on Enterprise-Bench, both on open weight models, on top of both a closed harness (Claude Code) and an open one (OpenCode).</p><p>Empirical Failure Cataloguing (EFC). The failure modes written as plain text skills, loaded statically into the agent’s context. Exhaustive. Everything present at all times. No database but as a meat skills pack.</p><p>Fractional Knowledge Graph (FKG). The same knowledge decomposed into a graph and retrieved selectively per situation, so only the fraction relevant to the current state is pulled. Built on Cognee, backed by Neo4j, with Postgres and pgvector alongside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ic7xKoZm7RZcYoucZNMdXQ.png" /></figure><p>The agent sees one MCP tool. Behind it, Cognee routes the recall: Neo4j holds the graph and does the traversal, pgvector holds embeddings, Postgres holds metadata. The graph is not an offline index build here. It is queried synchronously in the middle of the agent’s task.</p><p>Total spend across all of it, about $300(Opencode API) of my own money. Everything MIT licensed.</p><h3>Result one: the accepted entry</h3><p>Trinity-EFC(Trinity is just a school name that I attended and sounded good to be a name for this) on DeepSeek V4 Pro scores 78.6% over 140 trials. It sits at rank 4 of 14 on the public board, and pass@10 is 1.000, meaning every task in the suite was solved at least once within ten attempts. The baseline for the same model on the same board is 51.4%.</p><p>The three configurations above it are all DevRev Computer, the benchmark author’s own agent. Against every other submission it ranks first.</p><p>That is a real result and it is merged and live. But on its own it is a weak argument, because it compares across different models, and someone can always say the model did it.</p><h3>Result two: hold the model fixed</h3><p>This is the one that matters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qbBZTJ-Qv0FstaVLFI6Uw.png" /></figure><p>Same weights in all three rows. GLM-5.2 throughout. 140 trials each.</p><ul><li>Claude Code, bare harness: 58.6% (rank 9, accepted)</li><li>DevRev Computer: 92.9% (rank 3, accepted)</li><li>Trinity-EFC: 94.3% (submitted as PR <a href="https://github.com/devrev/enterprise-bench/pull/15">#15</a>, pending review)</li></ul><p>34.3 points separate the bare harness from the vendor’s own agent. That gap is what enterprises are buying. A written catalogue of failure modes covers it, and 1.4 points more, on identical weights.</p><p>To be completely explicit: PR <a href="https://github.com/devrev/enterprise-bench/pull/15">#15</a> is open and unreviewed as I write this. It is not on the leaderboard. It is a submission, and it may be rejected. But the run is 140 trials on the public benchmark with a job ID anyone can open, and the number will be whatever it is.</p><p>If that result stands, the delta enterprises are paying for is not technology. It is method, and method can be written down.</p><p>Which also answers the question I set out with. Apparently you can close the gap without knowing what the letters stand for, because the letters were never where the gap was.</p><h3>Does it transfer?</h3><p>A catalogue that only works inside one harness is a configuration trick, not knowledge. So I ported it to a completely different agent system in a completely different representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggo33HUMP5KoZe3_G780Zg.png" /></figure><p>OpenCode with DeepSeek V4 Pro and no knowledge layer scores 40.7%. With the same catalogue restructured as a retrieved graph, 57.1%. Both runs are mine and neither is on the public board.</p><p>+16.4 points. The knowledge is not tuned to one tool.</p><p>And now the part that does not flatter me. pass@10 did not move. It was 0.857 before and 0.857 after, identical to the bare baseline. Read plainly: the graph made the agent substantially more reliable on tasks it could already sometimes solve, but it did not unlock a single task the agent could not previously reach. EFC did unlock them, which is how it got to 1.000.</p><p>The knowledge that solves those tasks is in the graph, because it is the same catalogue. FKG is failing to retrieve it at the moment it is needed. That is a retrieval quality problem in traversal and ranking, and it is unsolved.</p><h3>What I am not claiming</h3><p>Enterprise-Bench is a young and imperfect instrument. 14 tasks and 140 trials is statistically noisy compared to a benchmark with 500 instances. Small-N benchmarks are easier to overfit to, and “the catalogue is overfitted to this benchmark” is a live hypothesis that I cannot rule out from the inside. The transfer result above is evidence against it, but it is one data point.</p><p>There is a structural conflict of interest, in that the benchmark is published by DevRev and DevRev’s own agent holds ranks 1, 2 and 3. I do not think anything improper is happening, and I say more about their conduct below, but a reader should know it.</p><p>I cannot give you a clean token efficiency comparison between the two methods. I tried. The FKG side is solid: 32.38M tokens at baseline, 41.22M with the graph, so +8.84M bought +16.4 points, roughly 0.54M tokens per point at 27 percent over baseline. Both figures come from job records through the same reporting path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vfrp85D7Uw9Dd5f28QBYA.png" /></figure><p><strong>I cannot give you a clean efficiency comparison between the two methods.</strong> I tried. The accounting on these runs is unreliable in both directions, so any ratio I quoted would be invented rather than measured. I had one written up before I checked, and it did not survive checking.</p><p>What I do think, having built both, is that the choice between them is a false one. EFC holds everything at once, which is exhaustive but has a ceiling. FKG fetches only what it judges relevant, which scales but currently misses things at the moment they are needed. The obvious shape is both: a small always-present core of failure modes that apply everywhere, with the long tail retrieved on demand. That is what I am building next, and it will land in the Trinity repo. Bookmark it if you want to follow along.</p><h3>What I actually want</h3><p>I want this layer to be public.</p><p>The default future is that it gets enclosed. Each vendor builds its own private catalogue, and the price of competent AI inside an organisation stays permanently high, because the knowledge is the moat and the moat is the business model. Nothing about that is technically necessary. It is happening because nobody has tried to build the thing in the open.</p><p>So Trinity is MIT licensed and the methodology is published, including the results that do not flatter it. Right now the techniques are implemented in silos. The intent is a solidified, incremental set of approaches across enterprise use cases, that enterprises record into and improve on themselves.</p><p>The point is to change the build vs buy calculation as a long term strategic matter. Not because vendors are bad, but because an enterprise that owns this layer compounds it internally instead of renting it, and the layer is the actual asset.</p><p>If 27 points cost one person $300, the gap was never an IP gap. It was a skill gap, and skill can be written down. Written down in the open, it compounds on your side of the wall.</p><h3>Credit where it is due</h3><p>The Enterprise-Bench team at <a href="https://medium.com/u/4bb6553166a0">DevRev</a> deserve real credit for running this as a transparent effort held separate from their core engineering org, and for putting a public board up that they can lose on. They also invited me to the AgentNexus, where I was able to meet folks from <a href="https://medium.com/u/26bec2028463">Neo4j</a>, Qualcomm, etc., Jeff Smith and Nimit in particular have put visible work into keeping it honest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HDOFAhXQmrdVSa_sYpzTLg.jpeg" /><figcaption>Left(Myself and right to me is Nimit at the AgentNexus)</figcaption></figure><h3>Links</h3><ul><li>Code and full methodology: <a href="https://github.com/ajayr4j/trinity">https://github.com/ajayr4j/trinity</a></li><li>Leaderboard: <a href="https://hub.harborframework.com/datasets/Enterprise-Bench/l1-l2-bench?tab=leaderboard">https://hub.harborframework.com/datasets/Enterprise-Bench/l1-l2-bench?tab=leaderboard</a></li><li>Trinity-EFC on DeepSeek V4 Pro, accepted: <a href="https://hub.harborframework.com/jobs/02b0a6e5-ce65-4a5e-9494-feab0f5f5ed4">https://hub.harborframework.com/jobs/02b0a6e5-ce65-4a5e-9494-feab0f5f5ed4</a></li><li>Trinity-EFC on GLM-5.2, pending review: <a href="https://github.com/devrev/enterprise-bench/pull/15">https://github.com/devrev/enterprise-bench/pull/15</a></li><li>Trinity-FKG on OpenCode: <a href="https://hub.harborframework.com/jobs/bbf1315d-6a87-4c6e-a420-7ef62690a3ea">https://hub.harborframework.com/jobs/bbf1315d-6a87-4c6e-a420-7ef62690a3ea</a></li></ul><p>Ajay Raj S | <a href="/service/mailto:ajayraj296@gmail.com">ajayraj296@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c91e6e33541c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deployedai/enterprise-ai-the-adoption-path-forward-c91e6e33541c">Enterprise AI: The Adoption Path Forward</a> was originally published in <a href="https://medium.com/deployedai">DeployedAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Built an AI Agency on the Belief That AI Fixes Everything. Our First Client Proved Us Wrong.]]></title>
            <link>https://medium.com/deployedai/we-built-an-ai-agency-on-the-belief-that-ai-fixes-everything-our-first-client-proved-us-wrong-afe08d2765b3?source=rss-4f64fc69a652------2</link>
            <guid isPermaLink="false">https://medium.com/p/afe08d2765b3</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[agency]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[small-business]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ajay raj S]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 05:05:03 GMT</pubDate>
            <atom:updated>2026-07-20T05:05:03.048Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What a 2007-founded agri-equipment supplier in Tamil Nadu taught us about the difference between automating a business and actually fixing one.</em></p><p>When myself and <a href="https://medium.com/u/6715d829d291">Yashwanth Sai</a> set out to build DeployedAI, we started with a belief that felt obvious at the time: AI is the ultimate lever for business leverage and profit. Cutting-edge LLMs, agentic systems wrapped around them, the prospect of automating every process that could be automated deploy that across Sales, Marketing, and Operations, and higher net profit follows. That was the thesis. It’s the thesis most AI agencies are selling right now.</p><p><a href="https://www.valarpirai.com/pages/about">Valarpirai Agency</a> became our first real test of that thesis. Founded in 2007, based in Namakkal, Tamil Nadu, they supply farmers with agricultural and dairy equipment — chaff cutters, milking machines, brush cutters, HTP sprayers, cow mats. Real revenue, real customers, real trust built over close to two decades. Not a startup. Not a pilot. An actual business with an owner, Jijendhran, who we know personally and who agreed to be our founding client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD11wOi6WlDAadj_SfGQtg.jpeg" /><figcaption>Jijendhran, owner of Valarpirai Agency (Left) &amp; Ajay (Right)</figcaption></figure><p>We went in with our usual audit process talk to the owner, talk to the staff, talk to a few customers. Understand the business before touching anything. Here’s roughly what we found.</p><h3>What the audit actually surfaced</h3><p>On paper, Valarpirai looks healthy. Revenue in the neighborhood of ₹30-40 lakh a month. Around 17 employees across fabrication, field service, and office staff. A customer base built almost entirely on trust roughly 60% of sales come in organically, word of mouth, a five-thousand-plus contact notebook accumulated over years of relationships.</p><p>Underneath that, three things stood out that no AI tool touches:</p><p><strong>The margin is thin and that’s the nature of this sector.</strong> Net margin sits around 2–4%. Interest payments run close to annual net profit with stock in trade in warehouse. This isn’t a business with slack to spend on speculative software.</p><p><strong>The operations are ad hoc.</strong> Order dispatch across four staff runs on coordination, not a system. Jiju had already paused aggressive sales campaigns before we arrived not because leads were short, but because the business couldn’t absorb more volume without breaking what already works.</p><p><strong>Customers were leaving over something nobody had measured.</strong> Some customers move to competitors because delivery on customized or equivalent products takes too long. Nobody at Valarpirai had a number for how long “too long” actually is. It was a feeling, backed by a few remembered conversations, not data.</p><h3>The temptation, and why we didn’t take it</h3><p>The obvious agency move here is a WhatsApp AI agent qualify inbound leads off a Click-to-WhatsApp ad, handle Instagram comment-to-DM funnels, automate the top of funnel. We actually built prototypes for this. A working WhatsApp intake simulator. A Telegram-based version with a live dashboard. We priced out Zoho’s SalesIQ/Zobot stack, mapped a native-Anthropic integration, understood exactly how we’d ship it.</p><p>And then we stopped, because of one sentence from the audit: customers are already leaving over slow delivery on customized orders.</p><p>Think about what a lead-gen funnel actually does to a business that’s losing customers on the fulfillment side. It brings in more qualified leads, faster, into a pipe that’s already too slow to keep the customers it has. Best case, the funnel works exactly as designed and Valarpirai loses a higher number of new prospects to the same delivery problem, just with better top-of-funnel conversion data to prove it. That’s not a fix. That’s a faster path to the same wall.</p><p>This is the trap. AI increases your capacity to do things. It does not tell you which things are worth doing. If your team’s capacity goes up and you point that capacity at something that was never the constraint, you haven’t gained leverage you’ve just gotten more efficient at doing something irrelevant, faster. A business can AI-max its way through a dozen tools and still not move net profit, because none of those tools touched the actual bottleneck. We were about to do exactly that to our own founding client.</p><h3>What we did instead</h3><p>Before any AI got deployed anywhere, we went back to basics. Not a system, not software a spreadsheet.</p><p>Every customized order now gets logged by hand across five checkpoints: order placed, fabrication started, ready for dispatch, dispatched, delivered. A free-text field captures the delay reason, in the staff’s own words, whenever one comes up. Nothing automated. Nothing AI-driven. Just visibility.</p><p>The logic is simple and it’s the same logic we’d apply to any client from here forward: you cannot fix a constraint you haven’t measured, and you cannot claim credit for improving something you never had a baseline for. A month of this data tells us whether the delay concentrates in fabrication, in dispatch coordination, or somewhere in between and that answer determines whether the fix is a hire, a lightweight tracker, or just setting a realistic delivery-window expectation at the point of sale. Three very different fixes, three very different costs, and no way to know which one is right without the data first.</p><p>Only once that’s measured does it make sense to reopen the marketing conversation, and even then, only in proportion to what the ops side can actually absorb. And, the excel would get converted to a SaaS tooling if that’s more convenient once the value is proven.</p><h3>The three fundamentals, unchanged by AI</h3><p>There’s a version of this argument that’s older than any of us and that a lot of AI-forward founders conveniently skip past: businesses grow on exactly three things generating demand, converting a higher percentage of that demand, and delivering high quality once the sale is made. AI can assist all three. It replaces none of them. Applying AI on top of a business that hasn’t nailed the fundamentals doesn’t accelerate growth it accelerates whatever’s already broken.</p><p>Valarpirai’s actual constraint right now isn’t demand. Word of mouth is already doing 60% of the work. It’s not conversion either. It’s delivery the third fundamental, the one no chatbot fixes. And the highest-leverage thing we could do as an agency wasn’t shipping a clever AI system. It was making the call to not ship one yet, and pointing our first real engagement at a spreadsheet instead.</p><h3>Where this leaves us</h3><p>We’re not walking away from AI. We’re recalibrating what it’s for. The businesses where AI genuinely moves net profit the case studies worth pointing to share a pattern: high-volume, already-digitized, repeatable information work. Tickets, claims, documents, leads processed at a scale where saving seconds compounds into real money. Valarpirai isn’t that business, not yet. It’s a physical-goods operation with a paper notebook and a four-person dispatch team, and its constraint lives in fabrication and delivery, not in text moving between systems.</p><p>So the honest version of our pitch to Jiju changed. Not “let AI 10x your sales.” Instead: measure the business first, fix the actual constraint once we know what it is, and only then decide whether AI belongs in the picture at all as a targeted tool for a diagnosed problem, not a blanket layer applied because the technology exists.</p><p>Net margin at 2–4% has real room to grow. Getting there starts with an Excel sheet, not a chatbot or an AI Agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JM5DJqlJri0WYWdK2Gfb8A.png" /></figure><p><em>We’re documenting this build in public as we work through </em><a href="https://www.valarpirai.com/pages/about"><em>Valarpirai</em></a><em> and the businesses after it. If you’re running a business that feels like it should be growing faster than it is, the first question worth asking isn’t “where can I add AI” it’s “do I actually know what’s slowing me down.” Reach out if you want a second pair of eyes on that question.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afe08d2765b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deployedai/we-built-an-ai-agency-on-the-belief-that-ai-fixes-everything-our-first-client-proved-us-wrong-afe08d2765b3">We Built an AI Agency on the Belief That AI Fixes Everything. Our First Client Proved Us Wrong.</a> was originally published in <a href="https://medium.com/deployedai">DeployedAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncertainty Is the Moat]]></title>
            <link>https://medium.com/deployedai/uncertainty-is-the-moat-166caf29ff4c?source=rss-4f64fc69a652------2</link>
            <guid isPermaLink="false">https://medium.com/p/166caf29ff4c</guid>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Ajay raj S]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 12:27:55 GMT</pubDate>
            <atom:updated>2026-07-06T12:27:55.196Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why the same instinct that makes entrepreneurship terrifying is the reason it pays, and why running an AI agency rewards it even more</em></p><p>Most career advice is secretly advice on how to minimize uncertainty. Get the degree, get the job, get the promotion ladder. Every step is designed to remove ambiguity about what happens next. That’s not a criticism, it’s the whole point of employment: you trade upside for a predictable path.</p><p>Entrepreneurship is the opposite trade. You give up the predictable path and, in exchange, you get access to returns that only exist because most people won’t tolerate the ambiguity required to reach them.</p><p>That’s the part people miss. The uncertainty isn’t a tax you pay for better upside. It’s the actual mechanism generating the upside.</p><h3>Why certainty gets arbitraged away</h3><p>If there were a known, documented, low-variance way to make outsized returns, it would already be crowded and flattened. Competition eats certainty. The reason a systematic trading edge, a niche consulting practice, or an early technical bet pays more than a comparable salaried role is precisely that most people won’t sit with the not-knowing long enough to get there.</p><p>A job gives you a role someone else already defined, a process someone else debugged, and a feedback loop someone else installed. An entrepreneur is the one defining the problem, the metric, and the process, usually with incomplete information and real consequences if they’re wrong.</p><p>That’s structurally uncertain by design. There’s no answer key to check against. And that’s exactly why the payoff exists at all. Remove the uncertainty and you remove the reason the opportunity was scarce in the first place.</p><p>Uncertain environments also produce fat-tailed outcomes. A job has a capped, linear payoff, your salary. An independent bet has a convex one: bounded downside against unbounded upside. You cannot get the tail without the variance that makes people uncomfortable enough to leave the tail unclaimed.</p><h3>Where this shows up daily in AI work</h3><p>Run an AI agency for six months and you’ll notice something that doesn’t show up in the pitch decks: there are a lot of moving parts, constantly, and most of them are outside your control.</p><p>Model providers ship new versions on their own schedule. Tool ecosystems (agentic runtimes, inference stacks, orchestration frameworks) fork and rewrite themselves every few months. Client requirements shift mid-project because the client themselves is still figuring out what “AI” should mean for their business. Pricing benchmarks move because someone underbid last week. None of this settles into a stable process the way, say, a mature web dev stack has.</p><p>The natural response to that much flux is to chase certainty anyway: overcommit to one framework because it feels safe, quote a fixed price against a spec that will obviously change, wait for the “standard approach” to emerge before building anything. All of that is certainty-seeking behaviour wearing a technical costume, and it costs you the same way it costs an aspiring founder who waits for the market to de-risk before starting.</p><p>What actually works is narrower than people expect: pick a focus, keep attending to what’s actually happening in the tools and the client’s problem as it shifts, and don’t require the ground to stop moving before you commit. The moving parts aren’t a sign you’re doing something wrong. They’re the reason there’s still margin in doing this work at all. A fully solved, fully documented AI implementation playbook would already be commoditized, and the rates would already be compressed to match.</p><p>The chaos is filtering out the competition in real time. Most technical people default to wanting a settled best practice before they’ll act. The ones willing to operate without one are the ones still getting paid well for it.</p><h3>The mechanism, stated plainly</h3><p>Uncertainty isn’t the price of the payoff. It’s the source of it.</p><ul><li>It filters out the people unwilling to tolerate it, which keeps the field thin.</li><li>It creates convex, fat-tailed payoff structures instead of linear, capped ones.</li><li>Every ambiguous decision you sit with and get feedback on becomes information nobody else has, and that compounds into judgment, which is the actual moat, not any specific tool or tactic.</li></ul><p>Ask what a fully de-risked version of entrepreneurship, or of running an AI agency, would look like. It would look exactly like a job: a defined role, a documented process, a predictable and capped return. The uncertainty is not what you push through to get to the reward. It is the reward’s entire supply mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUZ6FpB3QT16pdaNWMEb2g.png" /></figure><p><em>I run DeployedAI, building RAG pipelines, agentic systems, and backend infrastructure for teams navigating exactly this kind of moving-parts environment. If you’re trying to figure out where the certainty-seeking instinct is quietly costing you, that’s usually the first thing worth looking at. Book Consultation </em><a href="https://www.upwork.com/services/product/development-it-ajay-2068782203852322190?ref=project_share"><em>here</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=166caf29ff4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deployedai/uncertainty-is-the-moat-166caf29ff4c">Uncertainty Is the Moat</a> was originally published in <a href="https://medium.com/deployedai">DeployedAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VS Code, Pi, ClaudeCode and OpenCode Aren’t the Same Tool Wearing Different Skins]]></title>
            <link>https://medium.com/deployedai/vs-code-pi-and-opencode-arent-the-same-tool-wearing-different-skins-89816926e697?source=rss-4f64fc69a652------2</link>
            <guid isPermaLink="false">https://medium.com/p/89816926e697</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ajay raj S]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 15:11:22 GMT</pubDate>
            <atom:updated>2026-07-02T15:19:11.189Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Four agentic coding runtimes can look like the same product in different UI. Their runtime contracts say otherwise, and that difference is what actually decides which one to use.</em></p><p>VS Code’s Agent Host, Claude Code, Pi, and OpenCode all do the same job on the surface: take a prompt, run tools, write code. Compare them by feature list and they look almost interchangeable. Read the actual source surfaces, and they turn out to be four different architectural bets wearing the same “AI coding agent” label. I traced a single refactor task through all four to find out where the real differences live, then built a selection policy out of it.</p><p>One scope caveat is worth naming up front. VS Code, Pi, and OpenCode expose deeply inspectable runtime internals in-tree (reducers, loop engines, durable execution paths). Claude Code is partially different: you can inspect a lot of policy and behavior surfaces (settings hierarchy, permission and sandbox configs, hooks, plugins, changelog-level runtime behavior), but not an equally open core loop implementation in the same way. So this comparison treats Claude Code as a managed runtime with open policy/plugin surfaces, and compares on the parts you can actually verify in-repo.</p><p>I’ve been evaluating Pi and OpenCode for automation &amp; optimization work, and VS Code’s host architecture plus Claude Code’s terminal runtime kept coming up as two very different governance models worth understanding properly instead of hand-waving. Rather than trust feature tables, I had the code read end-to-end: where state lives, who owns the loop, what happens when a tool call fails mid-run, how plan mode and approval rules are enforced, and what survives interruption.</p><p>What came out was not “which one is best.” It was four fundamentally different answers to the same question: where authority sits in an agent runtime.</p><p>The one-sentence models:</p><ul><li>VS Code: state machine plus side effects plus provider adapters</li><li>Claude Code: managed CLI runtime plus hooks/plugins policy bus</li><li>Pi: single loop first, policy and hooks second</li><li>OpenCode: durable admission plus coordinated execution drains</li></ul><h3>Same problem, four different owners of authority</h3><p>Strip branding and all four solve the same abstract loop: accept intent, build model-visible context, run iterative model/tool turns, apply permission gates, handle queued or steering messages, emit visible progress, persist enough state to resume later.</p><p>Almost every practical difference you feel comes from one decision: where authority for that loop actually lives.</p><p>In VS Code’s Agent Host, authority sits in a protocol orchestrator and reducer pipeline. Copilot, Claude, and Codex are backend adapters into one shared action graph. Every state mutation flows through dispatch and reduction. Providers keep native SDK loops, but the host owns turn lifecycle, pending queues, and approval semantics.</p><p>In Claude Code, authority is split between a managed runtime core and explicit policy surfaces around it: permission settings, sandbox settings, hook lifecycle points (SessionStart, PreToolUse, PostToolUse, Stop), and plugin-defined workflows. The runtime owns turn execution; operators and orgs shape behavior through settings and plugin hooks rather than writing a host orchestrator.</p><p>In Pi, authority sits directly in runLoop. It&#39;s explicit: stream assistant, execute tools, process steering, then only consume follow-up when idle. There is no heavy control plane above it. Policy exists where hooks and extensions define it.</p><p>In OpenCode V2, authority sits in durable admission and execution coordination. A prompt is admitted first, then executed. Admission emits durable events, a coordinator serializes session drains, and a runner executes one provider turn at a time with durable projection and continuation semantics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*HRd9O-01iTlh6qR1atz0Xg.png" /></figure><h3>What that buys you, and what it costs</h3><p>VS Code centralization buys consistency across very different providers. Approval precedence and turn-state semantics are host-owned and deterministic. The cost is debugging complexity across three layers: UI, orchestrator, adapter.</p><p>Claude Code buys terminal-native governance out of the box: plan mode, permission modes, managed settings precedence, and rich hook/plugin control without building a separate platform. The cost is less source-level visibility into the deepest core loop internals than fully open loop engines, so some behavior must be treated as managed-runtime contract rather than directly audited function-by-function.</p><p>Pi buys an extremely clear mental model. One loop, two phases, explicit hook points. The cost is that built-in workflow rigor is intentionally minimal. No mandatory global plan control plane, no mandatory subagent stack. If your extension policy is weak, the platform will not save you.</p><p>OpenCode V2 buys the strongest durability story. Admission is durable, execution is coordinated, interruption is explicit, and continuation is evented. The cost is architectural complexity and transition overhead while legacy loop compatibility still exists.</p><h3>The same refactor, four different traces</h3><p>Take one task: refactor a shared function across a repo, run checks, explain diff.</p><p>In VS Code, the UI dispatches protocol action -&gt; orchestrator opens turn -&gt; provider executes native loop -&gt; tool updates flow back through shared protocol -&gt; central approval manager decides allow/ask/bypass behavior -&gt; turn completes and queued messages are consumed coherently.</p><p>In Claude Code, prompt enters the terminal runtime -&gt; runtime applies mode/permission policy -&gt; tool calls can be intercepted by hook chain -&gt; plugins can enforce stricter workflow gates (for example feature-development flows that require explicit approval before implementation) -&gt; Stop hooks may allow completion or block/rewake continuation -&gt; runtime finalizes state and supports resume/background behavior.</p><p>In Pi, runLoop injects steering messages, streams assistant output, executes tools (parallel by default, forced sequential if any tool requires it), runs before/after tool hooks, repeats until no immediate continuation, then checks follow-up queue before stopping.</p><p>In OpenCode V2, prompt is durably admitted before execution, coordinator wakes runner, runner promotes steer/queue per policy, runs one provider turn at a time, settles tools durably, and continues or pauses based on explicit state transitions. If the process dies, admitted state still exists to recover.</p><h3>Two more axes that matter in production</h3><p>Queue semantics diverge hard under load.</p><ul><li>VS Code: reducer/orchestrator-owned pending state, atomically consumed with server-started turns.</li><li>Claude Code: runtime-managed queue semantics, with hook/plugin continuation controls at lifecycle boundaries.</li><li>Pi: callback-owned (getSteeringMessages, getFollowUpMessages) polled at explicit loop phases.</li><li>OpenCode V2: durable delivery records (steer vs queue) with explicit promotion logic.</li></ul><p>Plan semantics are also fundamentally different.</p><ul><li>VS Code: platform mode axis (interactive/plan/autopilot) mapped into provider-specific behavior.</li><li>Claude Code: first-class runtime plan mode (/plan) with active permission interaction and ongoing hardening in release behavior.</li><li>Pi: plan is extension-defined, not mandatory runtime core behavior.</li><li>OpenCode: plan is agent identity and policy profile (plan vs build), not just a UI bit.</li></ul><p>Subagents are first-class in some systems and optional/non-core in others.</p><ul><li>OpenCode: built-in subagent roles and task-tool invocation model.</li><li>VS Code: multi-chat/subagent patterns through orchestrator and provider/harness mechanisms.</li><li>Claude Code: supports subagent and agent-scoped behaviors through runtime/plugin features.</li><li>Pi: intentionally minimal by default.</li></ul><h3>What surprised me</h3><p>I expected branding differences over similar internals. That was wrong.</p><p>Pi’s “missing” built-in plan mode is a deliberate architecture choice, not an omission. If you want strict plan workflows, you author and own that policy yourself.</p><p>OpenCode is currently two runtime shapes in one product story: legacy compatibility and V2 durability path. That’s pragmatic, but it means “OpenCode behavior” is context-dependent until full parity finishes.</p><p>VS Code’s central orchestration gives coherence and policy control, but there is a real debug tax: bugs can live in reducer logic, side-effects plumbing, or provider mapping.</p><p>Claude Code sits in an interesting middle: stronger built-in terminal governance than a bare loop framework, plus very open hooks/plugins/settings surfaces — but with less inspectable core loop internals than Pi/OpenCode source trees.</p><h3>So which one do you actually pick?</h3><p>Choose VS Code Agent Host when governance must be centralized across multiple providers, and rich IDE-mediated plan/approval UX is non-negotiable.</p><p>Choose Claude Code when you want terminal-first operation with strong native plan/permission controls, managed policy precedence, and plugin/hook extensibility without building your own host control plane.</p><p>Choose Pi when you want the simplest, most transparent loop and maximum extension-level freedom with minimal orchestration overhead.</p><p>Choose OpenCode V2 when long-running autonomy and restart correctness are primary risks, and durable admission/execution separation is worth the added architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*29YHmJFvkHZArcbyuG-W9Q.png" /></figure><p>Fast version:</p><ul><li>safety + IDE governance -&gt; VS Code</li><li>safety + terminal governance -&gt; Claude Code</li><li>speed + minimalism -&gt; Pi</li><li>durability + long autonomous pipelines -&gt; OpenCode V2</li></ul><h3>If you’re already committed to one and considering a switch</h3><p>These are not drop-in replacements. A runtime switch is usually a control-model migration, not a UI migration.</p><ul><li>Pi -&gt; VS Code: move extension policy into centralized host governance surfaces.</li><li>Pi -&gt; OpenCode: shift from “prompt runs now” to “prompt admitted, then executed durably.”</li><li>Claude Code -&gt; Pi: rebuild plan/permission guardrails explicitly as extension logic.</li><li>VS Code -&gt; Claude Code: translate protocol-orchestrator expectations into settings + hooks + plugins.</li><li>VS Code -&gt; Pi: re-implement orchestration-dependent behavior you used to get “for free.”</li><li>OpenCode legacy -&gt; V2: validate admission/projection invariants before declaring parity complete.</li></ul><h3>The actual takeaway</h3><p>None of these is “the best agent runtime” in the abstract. The right question is which failure mode you are least willing to tolerate:</p><ul><li>policy drift or unsafe actions,</li><li>workflow rigidity that slows your team,</li><li>or unrecoverable state loss in long autonomous runs.</li></ul><p>Pick by that failure mode, not by branding, and not by whichever tool you heard about first.</p><p>I’m Ajay, building <a href="http://deployedai.io/">DeployedAI</a>. If you’re choosing between agentic coding runtimes, designing long-running autonomous engineering workflows, or stuck in the exact failure mode your current runtime wasn’t built for, I’ve likely hit that same wall. <a href="https://www.upwork.com/services/product/development-it-ajay-2068782203852322190?ref=project_share">Book an audit</a> and we’ll map it to the right architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwAXSWt9t5m3PHGXeaSLQA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89816926e697" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deployedai/vs-code-pi-and-opencode-arent-the-same-tool-wearing-different-skins-89816926e697">VS Code, Pi, ClaudeCode and OpenCode Aren’t the Same Tool Wearing Different Skins</a> was originally published in <a href="https://medium.com/deployedai">DeployedAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing a Trading Backtest With Agentic AI: A Step-by-Step Breakdown]]></title>
            <link>https://medium.com/deployedai/optimizing-a-trading-backtest-with-agentic-ai-a-step-by-step-breakdown-0b68b3cc814b?source=rss-4f64fc69a652------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b68b3cc814b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ajay raj S]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 08:21:45 GMT</pubDate>
            <atom:updated>2026-07-01T08:25:06.571Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s a moment in every serious research project where the plan meets reality and something has to give.</p><p>For us, that moment came when we sat down to build an autonomous research system one that would generate and evaluate thousands of strategy variants automatically and realized the thing we needed to run thousands of times took <strong>138 minutes per run</strong>.</p><p>That’s the conflict. Here’s how we resolved it.</p><h3>What we were trying to do</h3><p>Think of a trading strategy as a rulebook. It says: under these market conditions, buy this, sell that, adjust when things drift. A backtest is how you test that rulebook you feed it years of historical market data and see how it would have performed.</p><p>We had a backtest for a systematic options strategy. It worked correctly. It had been validated carefully(A live fund of $1.5 million in Nifty derivatives). The problem was we wanted to improve it not manually, but by building an autonomous system where an AI proposes changes, the backtest evaluates them, and the results feed the next round of proposals. Repeat hundreds of times, find what actually works better by genetic mutation approach where it combines various successful ideas onto hypothesizing new novel variants</p><p>The economics broke immediately.</p><p>One full run covered 7 years of minute-by-minute market data, January 2019 to June 2026, 90 months in total. Each run took 138 minutes. With 1,000 variants to evaluate across 25 parallel servers, that’s 92 hours of continuous compute before a single research cycle completes. The research loop we were building would have been slower than just doing it manually.</p><p>Something had to change before we could scale anything.</p><h3>The conflict: everything was happening at every minute, from scratch, every time</h3><p>To understand what was wrong, you need to understand what the backtest was actually doing on each run.</p><p><strong>First, it loaded raw data from scratch.</strong> Every run opened the raw market data files 90 months of options prices, index levels, and volatility readings and rebuilt all the internal structures needed to run the simulation. Lookup tables, time indexes, contract mappings all reconstructed from the ground up, every single run, even though the market data never changed between runs. Two runs evaluating different strategy variants were both spending the first chunk of their runtime rebuilding the exact same data structures from the same files.</p><p><strong>Then, it stepped through every minute of 7 years.</strong> For each of the roughly 330,000 minutes in the dataset, the backtest did two things in the same breath: it made strategy decisions (should we adjust any positions right now?) and it immediately computed the full portfolio valuation (what is everything worth, what are the risk numbers, how much collateral do we need to hold?).</p><p>The valuation step is the expensive one. For a short-options book, computing risk correctly means pricing the entire portfolio under 16 different hypothetical market scenarios at every single minute what if prices drop sharply? What if volatility spikes? What if both happen at once? Real regulatory requirements, not optional. Important to get right. Also expensive to compute.</p><p>Here’s where the conflict compounds: <strong>most of those minutes, the portfolio hadn’t changed at all</strong>. Between a decision at 9:47am and the next one at 10:03am, every position was identical. But the backtest ran all 16 valuation scenarios anyway at 9:48, 9:49, 9:50, every minute between decisions computing the same result on the same unchanged portfolio, throwing it away, then computing it again one minute later.</p><p><strong>Finally, the quote lookups were slow.</strong> Every time the strategy needed to check the current price of a specific option contract, it searched through a dictionary using a multi-part key option type, strike price, expiry date, timestamp constructed fresh on every lookup. For a book holding dozens of contracts, running at minute resolution across 7 years, those lookups added up to millions of redundant key constructions and dictionary searches per run.</p><p>Three separate problems, all pointing at the same root cause: the backtest was designed to be correct, not to be run thousands of times.</p><h3>Why we used an AI agent and why OpenCode specifically</h3><p>This is the kind of problem that sounds straightforward but isn’t. Fixing it requires understanding every dependency across a 1,700-line codebase, refactoring carefully without breaking anything, and verifying at each step that the outputs still match exactly. Get one dependency wrong and your results silently drift you think you’ve sped things up, but you’re now evaluating the wrong thing.</p><p>Having worked across Codex and other coding agents, OpenCode running Codex is simply the strongest combination available for this kind of deep, iterative codebase work. It reasons about structure and execution flow, not just syntax, and it maintains coherence across long multi-step refactors in a way other agents don’t. For a task that required understanding the full dependency graph before touching anything, that mattered.</p><p>We pointed it at the codebase with three skills from <a href="https://github.com/addyosmani/agent-skills">addyosmani’s agent-skills pack</a> active:</p><p><strong>performance-optimization</strong> : measure before you touch anything. The agent profiled the backtest first, confirmed exactly where time was going, and only then proposed changes. This sounds obvious. Most people skip it and optimize the wrong thing.</p><p><strong>incremental-implementation</strong> : one change at a time, verify after each one. Not a risky full rewrite. Four distinct phases, each targeting one specific bottleneck, each benchmarked before moving to the next.</p><p><strong>debugging-and-error-recovery</strong> : after every phase, run the output against the original and confirm they match exactly. Row by row, number by number. Not &quot;seems about right&quot; confirmed. Summary metrics, full timeseries, position-level outputs, all verified before the agent moved forward.</p><p>The discipline these skills encode is what makes agentic optimization trustworthy. The agent couldn’t proceed past a phase until it could prove nothing had broken.</p><h3><strong>Four phases. One principle: stop repeating work.</strong></h3><p>Phase 1 moved data preparation : loading and indexing raw market files from every run to a one-time build step. Phase 2 replaced dictionary-based quote lookups with direct array indexing. Phase 3 merged two separate passes over the portfolio into one. Phase 4 eliminated small but cumulative overhead in the innermost loops key construction, type conversions, membership checks.</p><h3>The result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*bdgwlTERv9WxdMgYYpsriA.png" /></figure><p>The research loop that would have taken four days of continuous compute now runs overnight. The conflict that made autonomous research unworkable was resolved not by adding more servers, but by fixing the thing we were scaling before we scaled it.</p><h3>The honest caveat: this pattern doesn’t work for everyone</h3><p>The build-and-split approach works when your valuation step doesn’t feed back into your decisions. In our case, the decision logic reads from current market prices and portfolio composition not from computed risk numbers. So valuation can happen after decisions. Clean separation.</p><p>It breaks down when decisions depend on live valuation. If your strategy says “cut the position if unrealized loss exceeds X” that decision reads from valuation. Those two steps can’t be cleanly separated because the decision at minute N depends on the valuation at minute N.</p><p><strong>If your strategy is simpler</strong> : fixed rules, infrequent trades, no feedback from valuation into decisions you can often vectorize the entire thing directly. That’s easier and worth trying first.</p><p><strong>If your strategy is complex</strong>, ask: does your decision logic read from valuation outputs, or only from market data and portfolio state? If only market data” clean split, full speedup. If from valuation outputs map that dependency before assuming this pattern applies.</p><h3>The broader principle</h3><p>We added 25 servers to speed up our research. That gave us a linear improvement. Fixing the evaluation function gave us 13x and that multiplier applies to every variant, every research cycle, every future run. Permanently.</p><p>Profile before you scale. The bottleneck is almost never where you expect it.</p><h3>What comes next</h3><p>This was the prerequisite step. Once the backtest ran in 10 minutes instead of 138, we built the autonomous research loop on top of it.</p><p>The next post covers that loop in full how to structure an autonomous research system that actually produces trustworthy results, how we staged and ran 10,000 evaluated variants without the results drifting or the infrastructure silently corrupting outputs, and what the findings actually looked like after the system had run long enough to converge on something meaningful.</p><p>If you’re thinking about building autonomous research for your own strategies or just want to understand what a production-grade agentic research loop looks like that post is the one to read.</p><p>I’m Ajay, building <a href="http://deployedai.io/">DeployedAI</a>. If you’re running backtests at scale, building autonomous research loops, or just hitting a wall with your current AI infrastructure, I’ve been in the trenches with this. <a href="https://www.upwork.com/services/product/development-it-ajay-2068782203852322190?ref=project_share">Book a free audit</a> and we’ll look at it together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ra5QJpe7d1FLsX685u3WVQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b68b3cc814b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deployedai/optimizing-a-trading-backtest-with-agentic-ai-a-step-by-step-breakdown-0b68b3cc814b">Optimizing a Trading Backtest With Agentic AI: A Step-by-Step Breakdown</a> was originally published in <a href="https://medium.com/deployedai">DeployedAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I gave GPT-4.1]]></title>
            <link>https://medium.com/@ajayraj296/i-gave-gpt-4-1-twelve-rules-and-a-nearly-full-context-window-heres-what-actually-broke-8ba7b93a6d45?source=rss-4f64fc69a652------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba7b93a6d45</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Ajay raj S]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 06:47:10 GMT</pubDate>
            <atom:updated>2026-06-25T06:48:54.989Z</atom:updated>
            <content:encoded><![CDATA[<h3>I gave GPT-4.1 six types of behavioral rules and a nearly-full context window. Here’s what actually broke</h3><p><strong>TL;DR:</strong> I ran 5,400 controlled experiments measuring whether LLM behavioral instructions degrade as context fills. Most constraints don’t degrade at all, they either always work or they never work. Only two showed genuine context-pressure effects. The finding that surprised me most had nothing to do with context length.</p><p>There’s a belief that as your context window fills up, the model forgets its instructions. The system prompt gets “diluted.” Your rules stop sticking.</p><p>I believed it too. I’d seen it happen or at least thought I had.</p><p>So I ran the experiment properly.</p><h3>The setup</h3><p>I picked twelve behavioural constraints across six categories, designed to represent the kinds of rules you’d actually put in a production system prompt:</p><ul><li><strong>Format</strong>: “Start every response with a bold one-sentence summary” and “structure your response in exactly three paragraphs”</li><li><strong>Avoidance</strong>: “Never use the word ‘however’” and “never say ‘it is important to note’”</li><li><strong>Reasoning</strong>: “Show step-by-step reasoning before your conclusion” and “attach a confidence percentage after every factual claim”</li><li><strong>Scope</strong>: “Only use information from the provided documents” and “acknowledge when documents don’t contain enough”</li><li><strong>Persona</strong>: “Write as a senior engineer” and “include at least one labelled Limitation or Assumption”</li><li><strong>Meta</strong>: “Tag uncertain claims with [UNCERTAIN]” and “cite every document-based claim as [Doc N, Para N]”</li></ul><p>I then filled the context window to five different levels 10%, 25%, 50%, 75%, 90% using synthetic financial analyst documents. Three instruction positions: rules stated once at the start, rules repeated at the end, and rules distributed throughout the document every 25,000 tokens.</p><p>GPT-4.1 answered 450 analytical tasks. GPT-4.1-mini judged all 5,400 (response × constraint) pairs. Every verdict: satisfied or not.</p><h3>What the data actually shows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*AmPtVioC2_n2TsXyPynS4Q.png" /></figure><p>The first thing that jumps out: avoidance and persona constraints don’t degrade. They’re essentially perfect from 10% fill all the way to 90%. The model never wanted to use “however” in formal analytical writing anyway. These are non-problems in production.</p><p>The second thing: reasoning and meta constraints fail at 10% fill. At 57% and 47% respectively. That’s not context degradation that’s baseline non-compliance. These constraints fail before you add a single extra token of context.</p><p>And this is the finding that changed how I think about this problem.</p><h3>Two failure modes, not one</h3><p>The popular narrative “context pressure destroys instruction following” is wrong as a general claim. What the data reveals is a clean split:</p><p><strong>Failure mode 1: Context-sensitive degradation.</strong> Two constraint categories show genuine fill-level effects. The format category drops from 85% at 10% fill to 65% at 90% driven almost entirely by one constraint: maintaining a strict three-paragraph structure across a long response. Document-only scope degrades meaningfully when the context is 75% full. These are real effects, and they matter if you’re operating RAG pipelines or long-context agents near capacity.</p><p><strong>Failure mode 2: Baseline non-compliance.</strong> Some constraints fail regardless of context length. Attaching a confidence percentage after every factual claim, flagging uncertain statements inline, citing the specific document paragraph behind every claim these sit between 20% and 50% compliance at 10% fill. Adding more context doesn’t change that number meaningfully. The model simply doesn’t perform pervasive sentence-level transformations consistently, no matter how clearly you ask and no matter how empty the context is. The context window is not the problem here.</p><p>These require completely different fixes. Context-sensitive degradation responds to instruction repetition (more on that below). Baseline non-compliance doesn’t you need a post-processing verification layer or a different constraint design entirely.</p><h3>Does repeating instructions help?</h3><p>I tested two repetition strategies: reinforced (repeat instructions at the end of the context) and distributed (insert reminder blocks every 25K tokens throughout the document).</p><p>The result was interesting too: reinforced instructions at 90% fill hurt as often as they helped. Format: -1.7pp. Reasoning: -1.7pp. Meta: -5.0pp.</p><p>The only genuinely positive effect was distributed repetition for meta-instruction constraints at 90% fill: <strong>+16.7 percentage points</strong>. That’s real. Everything else was noise or negative.</p><p>The practical implication: don’t repeat your entire system prompt at the end of a long context. If you have meta-instruction constraints (uncertainty flagging, inline citations) and you’re operating near context capacity, distributed reminders help. For everything else, they don’t.</p><h3>What this means if you’re building production systems</h3><p>Four things I’d take from this:</p><p><strong>1. Test your constraints at low fill, not just high fill.</strong> If something fails at 10% fill, you don’t have a context problem. You have a constraint design problem.</p><p><strong>2. Avoidance and format constraints are robust.</strong> Stop worrying about whether the model will forget to avoid certain phrases. It won’t. Focus your attention on the constraints that actually break.</p><p><strong>3. Inline self-monitoring doesn’t work reliably.</strong> If your system depends on the model flagging its own uncertainty or citing sources on every claim verify that in post-processing. The model passes the constraint ~40–50% of the time at best. Your downstream system should not trust it blindly.</p><p><strong>4. Response length may matter more than context length.</strong> The format degradation pattern suggests the mechanism isn’t attention dilution — it’s that longer documents produce longer responses, and structural constraints are harder to maintain over a longer generation. That’s a different problem with different solutions.</p><p>The code, data, and full analysis tables are at <a href="https://github.com/ajayr4j/constraintfade">github.com/ajayr4j/constraintfade</a>.</p><p>If you’re building agentic systems or RAG pipelines with behavioural constraints, I’d be curious whether these patterns hold in your production data. The experiment was synthetic and real workloads may tell a different story. Let me know what you think about the same.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba7b93a6d45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pgtoken: storing what you already know]]></title>
            <link>https://medium.com/@ajayraj296/pgtoken-storing-what-you-already-know-04154bc5c667?source=rss-4f64fc69a652------2</link>
            <guid isPermaLink="false">https://medium.com/p/04154bc5c667</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Ajay raj S]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 05:28:14 GMT</pubDate>
            <atom:updated>2026-06-06T05:28:14.081Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a function your inference server runs on every request.</p><p>It takes text. It returns a list of integers. It is deterministic — same input, same output, every single time, with no exceptions. It cannot produce a different result for the same input. That is mathematically required for the model to behave consistently.</p><p>For most of your prompt, the input doesn’t change either.</p><p>Your system prompt is the same across all requests. Your tool definitions are the same. Your instructions are the same. And yet the tokenizer runs on all of it, every time, produces the same integers it produced last time, and throws them away.</p><p>pgtoken is a PostgreSQL extension that stores those integers. The tokenizer runs once. Every subsequent request retrieves.</p><p>That is the entire idea.</p><h3>The inspiration</h3><p>Python’s default sort is Timsort. It uses insertion sort for arrays up to 64 elements, then switches to merge sort for larger ones. Insertion sort is not the fastest sorting algorithm that exists. For large inputs, it is clearly not optimal. But for small inputs — the common case in real programs — it is fast, simple, and has good cache behaviour. Merge sort is not actually better than insertion sort below that threshold. The overhead of recursive splitting, the function call cost, and the auxiliary memory allocation make merge sort slower in practice for short arrays even though its asymptotic complexity is superior. The tradeoff point is 64 elements: below it, insertion sort wins on real hardware; above it, merge sort’s O(n log n) advantage takes over. Timsort doesn’t optimise for the theoretical worst case. It optimises for the actual distribution of inputs it will see.</p><p>pgtoken is built on the same principle. The common case in LLM inference is not arbitrary text. It is a stable system prompt followed by a variable user query. The stable part is seen millions of times. The variable part is unique every request. But the static portion is not limited to just the system prompt. In many real deployments, a significant share of the context window is fixed — tool definitions that never change, a reference document that every request in a session shares, retrieved chunks that appeared in the previous request and appear again in this one, the earlier turns of a long conversation that are already settled and will not change. Any text that is present in the context window and is not going to change is a candidate. pgtoken optimises for that distribution not for the theoretical general case of arbitrary token sequences.</p><p>The encoding scheme, the storage format, the codebook design — all of it reflects the real distribution of tokens in conversational text, not a uniform assumption about all possible inputs. More on that below.</p><h3>What the tokenizer actually does</h3><p>To understand what pgtoken stores, it helps to understand what runs before it.</p><p>Modern LLM tokenizers use Byte Pair Encoding (BPE). The process runs in three stages.</p><p>First, a regex splits the raw text into chunks. For GPT-4’s tokenizer, this pattern respects word boundaries, contractions, numbers, and punctuation. &quot;the cat sat&quot; becomes [&quot;the&quot;, &quot; cat&quot;, &quot; sat&quot;]. BPE merges will only happen within each chunk - they never cross chunk boundaries.</p><p>Second, each chunk is converted to its UTF-8 byte sequence. This handles all of Unicode. Every possible character maps to bytes, so the tokenizer can handle any input.</p><p>Third, for each chunk, the BPE merge loop runs. It looks up every adjacent pair of units in a pre-trained merge table, finds the highest-priority pair (lowest rank number in the table), collapses them into a single unit, and repeats until no more merge rules apply. The merge table is a fixed artifact — trained once, never changes at inference time. The resulting units each map to an integer token ID via a vocabulary lookup.</p><p>This loop is O(n log n) in the number of tokens, using a priority queue. In Rust — which tiktoken uses it runs at perhaps 50 microseconds for a 140-token system prompt. That sounds negligible. Under 100 concurrent processes on 16 CPU cores, it becomes 13ms mean latency and 113ms at the P99. The function itself is not slow. The contention is.</p><p>The key property: it is deterministic. The merge table doesn’t change. The vocabulary doesn’t change. Given the same input text, you will always get the same token IDs. Always.</p><h3>The encoding: why not just store the integers</h3><p>The naive approach stores token IDs as integer[] - a Postgres array of 32-bit integers. For a 140-token system prompt, that’s 560 bytes. For a 2,000-token context, it’s 8,000 bytes. Across millions of stored chunks, this adds up.</p><p>pgtoken stores rank-varint encoded bytea instead.</p><p>The idea starts with an observation about token IDs. They are assigned during vocabulary construction and carry no inherent meaning in their numeric values. Token ID 11 being the comma character and token ID 39308 being some rare technical term is an accident of training order, not a reflection of frequency.</p><p>But frequency itself is not random. In any real text corpus, a small number of tokens appear constantly — punctuation, common words, common subwords — and the vast majority appear rarely. The top 128 tokens by frequency account for a disproportionate share of all token occurrences in conversational text.</p><p>Rank-varint exploits this. You build a codebook: a mapping from token ID to frequency rank, where rank 0 is the most frequent token in your corpus. Then you encode not the token ID but the rank, using a variable-length encoding:</p><pre>rank 0–127      →  1 byte<br>rank 128–16511  →  2 bytes<br>rank 16512+     →  3 bytes</pre><p>The top 128 tokens — which cover a large fraction of real text each take one byte instead of four. The result, for a typical conversational corpus, is about 1.7 bytes per token on average, compared to 4 bytes for raw int32. For a 2,000-token context that’s 3,400 bytes instead of 8,000.</p><p>The pre-built cl100k_base codebook was generated from <a href="https://huggingface.co/datasets/allenai/WildChat">WildChat - 529K real</a> GPT-3.5 and GPT-4 conversations across 66 languages. We validated it against <a href="https://huggingface.co/datasets/allenai/WildChat-4.8M">WildChat-4.8M</a>, a 6× larger version of the same corpus. 90.2% of tokens stayed in the same varint byte tier across both versions. The core frequency distribution is stable. The frequency rankings reflect actual usage in conversational text, not a theoretical assumption. This is the Timsort principle again: optimise for the real distribution, not the theoretical worst case.</p><h3>The four-byte header</h3><p>Every encoded bytea starts with a 4-byte little-endian integer: the token count. Just the count. Before any varint payload.</p><p>This makes pgtoken_count() trivial:</p><pre>n = (int32)( (uint32)data[0]<br>           | (uint32)data[1] &lt;&lt; 8<br>           | (uint32)data[2] &lt;&lt; 16<br>           | (uint32)data[3] &lt;&lt; 24 );<br>PG_RETURN_INT32(n);</pre><p>Read 4 bytes. Return. The varint payload is never touched.</p><h3>The codebook in memory</h3><p>The codebook doesn’t reload from CSV on every query. The C extension maintains a static array of up to 8 loaded codebooks in the Postgres backend process. First call loads from disk. Every subsequent call is a direct array lookup.</p><p>The internal structure is two arrays:</p><pre>int32 *token_to_rank;   /* index=token_id  →  rank,     -1 if missing */<br>int32 *rank_to_token;   /* index=rank      →  token_id, -1 if missing */</pre><p>Encode path: for each token ID, look up token_to_rank[tid], get rank, varint-encode rank into the output buffer.</p><p>Decode path: varint-decode rank from buffer, look up rank_to_token[rank], get token ID.</p><p>Both are O(1) direct array index lookups. No hash table, no search, no iteration.</p><p>One detail worth noting: the codebook arrays are allocated in TopMemoryContext rather than per-transaction memory. Per-transaction allocations get freed when the transaction ends. If the codebook lived in per-transaction memory, the static pointer would dangle on the next call. TopMemoryContext allocations survive for the life of the Postgres backend process. This was a bug in an earlier version palloc silently went into per-transaction context, leaving dangling pointers that corrupted the heap on subsequent calls. The fix is one line but the consequence of getting it wrong is subtle and hard to debug.</p><h3>The three functions</h3><pre>pgtoken_encode(token_ids integer[], codebook text)  →  bytea<br>pgtoken_decode(encoded bytea, codebook text)         →  integer[]<br>pgtoken_count(encoded bytea)                         →  integer</pre><p>encode takes token IDs you already have (produced by your tokenizer, once) and compresses them to bytea for storage.</p><p>decode takes stored bytea and returns the original token IDs. You pass these directly to your inference engine. No tokenizer call.</p><p>count reads the 4-byte header and returns. The encoded payload is untouched.</p><p>A fourth function, pgtoken_reload_codebooks(), clears the in-memory cache so updated codebook CSVs take effect without restarting Postgres.</p><h3>Building a codebook</h3><p>The pre-built cl100k_base codebook works for OpenAI models. For other tokenizers - Qwen, Llama, Mistral, any HuggingFace model - you build your own from a corpus.</p><pre># from WildChat dataset<br>python scripts/build_codebook.py \<br>    --source arrow \<br>    --data-dir ./wildchat_data \<br>    --tokenizer-hf Qwen/Qwen2.5-1.5B-Instruct \<br>    --output data/qwen25_codebook.csv</pre><pre># from your own Postgres table<br>python scripts/build_codebook.py \<br>    --source postgres \<br>    --dsn &quot;postgresql://user:pass@localhost/mydb&quot; \<br>    --table messages --column content \<br>    --tokenizer cl100k_base \<br>    --output data/cl100k_base_codebook.csv</pre><p>The builder includes every token in the tokenizer’s vocabulary in the codebook not just tokens seen in the corpus. Unseen tokens are ranked last by token ID. Combined with the tokenizer’s byte-level fallback, this means any input text, regardless of how unusual or out-of-distribution, will always produce token IDs that pgtoken can encode. No production input can cause an encode error.</p><p>The quality of compression depends on how well your corpus matches your actual workload. WildChat covers general conversational text and works well for most applications. For domain-specific deployments — medical, legal, financial — building from your own data typically improves compression.</p><h3>Drawbacks</h3><p>There is one real cost: every time you switch tokenizers, you need to rebuild the codebook and re-encode your stored sequences. Moving from cl100k_base to o200k_base, or from GPT to Qwen, means re-running pgtoken_encode across your stored data.</p><p>This is worth the tradeoff. The alternative — recomputing token IDs from raw text on every request is a repeated non-deterministic-feeling operation on identical input. The codebook rebuild is a one-time migration cost for a one-time compute, after which every lookup is O(1) forever. Tokenizer changes are infrequent. Request volume is constant. The math favours rebuilding once over recomputing endlessly.</p><p>The other minor cost: the codebook CSV must live in $PGDATA/pgtoken_codebooks/. It is external state that the extension depends on. If the CSV is missing or corrupted, encode and decode will error. This is the expected behaviour a missing codebook is a deployment error, not a silent failure - but it means codebook management is part of your deployment process.</p><h3>The schema pattern</h3><pre>CREATE EXTENSION pgtoken;</pre><pre>CREATE TABLE chunks (<br>    id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),<br>    document_id uuid NOT NULL,<br>    content     text NOT NULL,<br>    token_ids   bytea,              -- pgtoken encoded<br>    chunk_order int NOT NULL<br>);</pre><p>Store once at ingest time. Query without tokenization. The token count is always available without decoding. The token IDs are available for retrieval without re-running any tokenizer.</p><h3>Where it helps</h3><p><strong>Explicit and implicit prefix caching.</strong> The most direct use case is a static system prompt — store the token IDs once at application boot, retrieve on every request, tokenize only the user’s unique query. The tokenizer never runs on the static part again. But the same pattern extends further.</p><p>In document-heavy RAG systems, the retrieved context — often 5,000 to 20,000 tokens of document chunks is assembled fresh on every request even when the underlying chunks are identical to what another user requested 10 seconds ago. Those chunk token IDs can be stored in pgtoken at ingest time and retrieved directly, bypassing tokenization entirely at query time. Long conversation histories work the same way: earlier turns in a session are fixed, their token IDs known, and can be stored progressively as the conversation grows rather than re-tokenized from scratch on every new message.</p><p>For implicit prefix detection where no developer explicitly declares a boundary — pgtoken can serve as the storage backend for two discovery mechanisms. A sliding window approach watches recent requests, computes the longest common prefix across them, and promotes any sequence that appears in more than a threshold fraction of the window to stored pgtoken entries automatically. A radix tree approach inserts every incoming token sequence into a prefix tree; any node with a visit count above a threshold is a discovered shared prefix and can be stored. In both cases, pgtoken is where the discovered prefix lives. The detection mechanism finds the boundary. pgtoken stores the result and makes every subsequent retrieval O(1).</p><p>The larger the prefix and the higher the request volume, the larger the saving compounds.</p><p><strong>Context window filtering in RAG.</strong> The 4-byte count header means pgtoken_count() is O(1) on any stored sequence. The most common RAG query - does this chunk fit within my token budget? - becomes a single integer comparison in SQL with no tokenization, no decoding, no round-trip to your application layer.</p><pre>-- pack as many chunks as fit within 8000 tokens<br>SELECT id, content, pgtoken_count(token_ids) AS tokens<br>FROM chunks<br>WHERE document_id = $1<br>ORDER BY chunk_order<br>LIMIT 20;</pre><p>Filter in Postgres, return only what fits. The token count is stored alongside the content. No application-side tokenization loop needed.</p><p><strong>Multi-tokenizer storage.</strong> The same table can hold chunks encoded under different codebooks. pgtoken_encode(ids, &#39;cl100k_base&#39;) for GPT models, pgtoken_encode(ids, &#39;qwen25&#39;) for Qwen, pgtoken_encode(ids, &#39;o200k_base&#39;) for newer OpenAI models. The codebook name is a string parameter. You can maintain parallel encodings for the same content without duplicating the content itself - one content column, multiple encoded bytea columns.</p><pre>CREATE TABLE chunks (<br>    id            uuid PRIMARY KEY,<br>    content       text NOT NULL,<br>    tokens_gpt    bytea,   -- cl100k_base<br>    tokens_qwen   bytea,   -- qwen25<br>);</pre><p><strong>Efficient token archive.</strong> If you store conversation history, fine-tuning datasets, or evaluation logs, pgtoken gives you a compact binary representation that is directly usable at inference time. No re-tokenization on read. The stored bytea decodes directly to the integer array your model needs. At 1.7 bytes per token average versus 4 bytes for raw int32, a 10-million-token archive shrinks from 40MB to 17MB. More importantly, reads from that archive go straight to your inference pipeline without touching a tokenizer.</p><h3>Where to find it</h3><p><a href="http://github.com/ajayr4j/pgtoken">github.com/ajayr4j/pgtoken</a></p><p>The codebook builder supports both tiktoken and any HuggingFace tokenizer. The benchmark harness measures both thread and process concurrency modes and is included in the repo. The README covers installation on Ubuntu 24.04 with PostgreSQL 18.</p><h3>A note on the implementation</h3><p>pgtoken exists as a PostgreSQL extension because our applications are already built on Postgres. That is the only reason it lives here.</p><p>The core idea has no dependency on Postgres. The varint encoding, the frequency-ranked codebook, the O(1) count header — none of this is specific to any database. You can port the same logic to MySQL, SQLite, Redis, a key-value store, or maintain the storage layer yourself entirely outside a database. The encode and decode functions are a few dozen lines of C. The codebook is a CSV and two integer arrays.</p><p>What matters is the pattern: compute the token IDs once, store the result, retrieve on every subsequent request. The storage medium is incidental. If your stack runs on a different database, write the same two lookup arrays there. If you prefer to manage it in application memory, a dict works just as well for small vocabularies.</p><p>pgtoken is one answer to a question worth asking in every stack: why are we computing the same thing twice?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04154bc5c667" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Improved RAG Prompt Cache Hit Rates by 2.6× and Cut Costs by 8.1%]]></title>
            <link>https://medium.com/@ajayraj296/how-we-improved-rag-prompt-cache-hit-rates-by-2-6-and-cut-costs-by-8-1-9bdd168226f0?source=rss-4f64fc69a652------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bdd168226f0</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ajay raj S]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 07:15:05 GMT</pubDate>
            <atom:updated>2026-06-05T07:15:05.382Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time a user asks your RAG chatbot a question, your pipeline does something like this:</p><ol><li>Embed the query</li><li>Retrieve the top-k relevant chunks from your vector store</li><li>Concatenate those chunks into a string</li><li>Send that string to the LLM</li></ol><p>Step 3 is where there is optimisation to be done — especially for event-driven traffic patterns where many users ask similar questions in a short window.</p><h3>The cache you’re not hitting</h3><p>Modern LLM APIs support prompt caching. When the beginning of your prompt matches something the model processed recently, those tokens get served at a discount of 50% on Azure OpenAI, 90% on Anthropic Claude. The mechanic is simple: the API stores intermediate attention states (the KV cache) and reuses them when it sees the same prefix again.</p><p>The economics make sense here. Storing computed KV tensors is marginal compared to running a full forward pass on a GPU. The labs are now passing that efficiency on to users-but only if your prompts are structured to take advantage of it.</p><p>The catch: <strong>prefix caching only works when the prefix is byte-for-byte identical.</strong> One character difference. Cache miss. Zero savings.</p><p><em>(How the labs implement this differs meaningfully - more on that at the end.)</em></p><h3>Why RAG breaks it</h3><p>Your system prompt is static. That part caches fine. But your retrieved chunks — the 10,000–20,000 tokens of context that dominate your prompt get assembled fresh on every request.</p><p>The problem is not the content. It is the <strong>ordering</strong>.</p><p>Vector similarity search ranks chunks by cosine distance. Request 1 asks “What are NVDA risk factors?” and gets chunks ranked [280, 234, 245, 291, 135]. Request 2 asks “What regulatory risks does NVIDIA face?” - same intent, same underlying chunks, but the similarity scores shift slightly. The ranking comes back [245, 280, 234, 135, 291].</p><p>Different order. Different token sequence. Cache miss. The LLM reprocesses content it saw 30 seconds ago, and you pay full price.</p><h3>The fix</h3><p>Sort your retrieved chunks by a stable key before assembling the prompt. A UUID assigned at ingest time works perfectly.</p><pre># Baseline - similarity order, changes every request<br>chunks = vector_search(query, top_k=10)</pre><pre># Deterministic - stable order, same chunks always appear at same positions<br>chunks = vector_search(query, top_k=10)<br>chunks.sort(key=lambda c: c.id)</pre><p>That is the core. Same chunks, same content, consistent positions. When two users ask similar questions and retrieve overlapping chunks, those chunks land at the same positions in the prompt. The prefix matches. The cache hits.</p><h3>One layer further: prioritize previously-seen chunks</h3><p>Sorted order alone is good. But you can push it further.</p><p>Track which chunks appeared in recent requests. When assembling a new prompt, put previously-seen chunks first (in stable order), then append new chunks at the end.</p><pre>Request 1: [chunk_234, chunk_245, chunk_280]<br>Request 2 retrieves: [chunk_245, chunk_280, chunk_135, chunk_310, chunk_234]</pre><pre>  → seen chunks: [chunk_234, chunk_245, chunk_280]  ← prefix match with req 1<br>  → new chunks:  [chunk_135, chunk_310]              ← appended after<br>  → final:       [chunk_234, chunk_245, chunk_280, chunk_135, chunk_310]</pre><p>Azure already cached the first three chunks from request 1. Request 2 gets those for free. Only the two new chunks cost full price. This is cross-session caching — different users, different sessions, sharing a cached prefix because they are querying the same corpus. <em>(Here “users” refers to your application’s end users, not accounts at the model provider.)</em></p><p>The tracking mechanism uses two disk-backed data structures: a seen_cache that maps each request to its ordered chunk list, and an inverted_index that maps each chunk ID to the requests that contained it. When a new request arrives, the inverted index lets you find the best-matching previous request in O(k) time - no scanning the full history.</p><h3>The numbers</h3><p>I ran this on a NASDAQ-100 SEC filings RAG system — 10,000 requests split evenly between baseline and deterministic ordering, all NVIDIA-focused questions across five categories: risk factors, revenue, AI positioning, competition, and supply chain.</p><p>The dataset was chosen deliberately. SEC filings chatbots face exactly this traffic pattern in the real world: earnings announcements, product launches, and regulatory events trigger short bursts of many similar queries from different users. That is the scenario where this optimization pays off most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/0*w2KJmFZEfGLtt9j-.png" /></figure><p><strong>+17.22 percentage points</strong> improvement in cache hit rate. <strong>8.1% cost reduction.</strong> No infrastructure changes. No model changes. Just ordering.</p><p>At 1M requests that is ~$54,000 saved. At 10M requests, over half a million dollars — for reordering an array.</p><p>The improvement is not uniform across query types. Conceptual questions about AI positioning and competition benefit most — they cluster around the same sections of the corpus, so chunk overlap between requests is high. Time-specific financial queries like revenue and earnings benefit less — they pull from specific quarterly filings that vary more across requests.</p><h3>Does it hurt answer quality?</h3><p>The obvious concern: similarity ordering puts the most relevant chunk first. Does sorted ordering degrade answers?</p><p>My intuition before running this was that it should not matter much. There is a well-known phenomenon in long-context LLMs where tokens at the very start and end of the context window receive higher attention than content in the middle — sometimes called the “lost in the middle” effect. Since chunk reordering happens within the middle layer of the prompt (after the system prompt and before the question), the positional effect should be minimal.</p><p>The numbers confirmed it. I ran LLM-as-judge evaluation on 200 paired responses — same question, both approaches, blind scoring on factual accuracy, completeness, and clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*YoshZnbOsxIMXPn3.png" /></figure><p>A difference of <strong>0.04 points</strong> on a 10-point scale. That is noise. The quality is indistinguishable in aggregate — consistent with the lost-in-the-middle intuition.</p><p>Answers generated with high cache hit rates (&gt;50%) scored 8.40 versus 8.34 for low-cache requests. Cache reuse does not introduce degradation. The model reasons correctly regardless of whether context tokens came from cache or were freshly computed.</p><h3>The implementation</h3><p>The full implementation — the assembly logic, seen_cache with inverted index, the A/B experiment infrastructure, and the evaluation scripts — is on GitHub:</p><p><a href="https://github.com/ajayr4j/rag-cache-optimization"><strong>github.com/ajayraj/rag-cache-optimization</strong></a></p><p>The README covers the algorithm in detail: how the inverted index works, why the 24-hour window matters (it matches Azure’s extended cache TTL), and how to adapt it to your own corpus.</p><h3>What this is not</h3><p>This does not solve prompt caching entirely. Your system prompt already caches well if it is static. Conversation history is a different problem.</p><p>This is also not semantic caching — returning cached LLM responses for near-duplicate queries without calling the API at all. That is orthogonal and complementary. Deterministic ordering reduces cost per API call. Semantic caching eliminates API calls entirely. Both together form a complete caching strategy.</p><h3>What’s next: how the labs implement this, and when to use which</h3><p>Prompt caching is not one thing — each provider implements it differently, and those differences matter when you are optimizing for cost.</p><p><strong>Azure OpenAI (gpt-5.4 and newer):</strong> Automatic, no configuration needed. For gpt-5.4, 24-hour extended retention is the default — no prompt_cache_retention parameter required. Cached tokens billed at 50% of standard input pricing. The cache is keyed on a hash of the prompt prefix and is private to your Azure subscription.</p><p><strong>Anthropic Claude:</strong> Requires explicit opt-in via cache_control markers on specific content blocks. Cache writes cost 25% more than standard input tokens, but cache reads cost only 10% - a 90% discount on reads. Break-even is roughly 1.4 cache hits per cached prefix. Up to 4 cache checkpoints per request, with a 5-minute default TTL (extendable to 1 hour with activity).</p><p><strong>OpenAI (direct API):</strong> Automatic like Azure, no opt-in needed. 50% discount on cached tokens. Cache TTL is 5–10 minutes by default, cleared within 1 hour of inactivity.</p><p><strong>vLLM (self-hosted):</strong> Automatic prefix caching (APC) via a hash-table-based KV block store with O(1) lookups. No per-token billing — the benefit shows up as throughput improvement. Production deployments report 14–24x throughput improvement for workloads with heavy prefix sharing.</p><p><strong>When to choose what:</strong></p><p>If you are on Azure and using gpt-5.4 — the 24-hour extended retention window is unusually long. That is the right deployment for this optimization because your seen_cache has the full day to accumulate ordering history before entries expire.</p><p>If you are on Anthropic — the 90% read discount is the highest available, but cache writes cost more upfront. The math favors caching when your cache hit rate is above ~30%. Deterministic ordering gets you there faster.</p><p>If you are self-hosting with vLLM — caching is free and the throughput gains are dramatic. Deterministic ordering matters even more here because the KV block store is content-addressed: same token sequence = instant cache hit, no compute at all.</p><p>The underlying principle is the same across all providers: stable prefixes hit cache, unstable prefixes miss it. Deterministic retrieval ordering makes your prefixes stable. The rest is provider-specific configuration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bdd168226f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>