<?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 Hitesh Nankani on Medium]]></title>
        <description><![CDATA[Stories by Hitesh Nankani on Medium]]></description>
        <link>https://medium.com/@hiteshnankani97?source=rss-52593e532004------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AlfjYiLROrTImf30q4EsQQ.jpeg</url>
            <title>Stories by Hitesh Nankani on Medium</title>
            <link>https://medium.com/@hiteshnankani97?source=rss-52593e532004------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:40:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hiteshnankani97/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[AI Context Isn’t Free]]></title>
            <link>https://medium.com/@hiteshnankani97/ai-context-isnt-free-037ffe30966b?source=rss-52593e532004------2</link>
            <guid isPermaLink="false">https://medium.com/p/037ffe30966b</guid>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-context-handling]]></category>
            <dc:creator><![CDATA[Hitesh Nankani]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 02:23:27 GMT</pubDate>
            <atom:updated>2026-08-11T04:26:45.822Z</atom:updated>
            <content:encoded><![CDATA[<h3>Everything you paste into a prompt, the model has to read. A practical guide to prompt engineering, and to the five ways it quietly falls apart.</h3><p>There is a version of prompt engineering that gets taught everywhere: add “you are an expert,” say “think step by step,” paste in more context, ship it.</p><p>It works. Right up until it doesn’t. And when it stops working, most people reach for the exact lever that broke it. They add <em>more</em>.</p><p>This is a guide to both halves of the job. The first half is how to write a prompt that earns a good answer. The second half, the part nobody puts in the tutorial, is how to stop strangling your own prompt with context. If you only read one section, read the second one.</p><p>You don’t need a CS degree for any of it. Prompt engineering is the craft of getting a brilliant, unfocused, all-of-the-web-in-its-head model to do the specific thing you actually wanted.</p><h3>The whole discipline in four letters: CMRE</h3><p>Every prompt worth shipping answers four questions.</p><p><strong>C: Content.</strong> Set the background. What do you tell it? The background, the document, the transcript, the constraints it can’t guess.</p><p><strong>M: Method.</strong> Choose the method. How do you tell it? Zero-shot, few-shot, chain-of-thought, role assignment, delimiters.</p><p><strong>R: Requirement.</strong> Define the requirement. What do you actually ask for? The task, stated so precisely that a stranger could grade the output.</p><p><strong>E: Evaluation.</strong> Build the eva. How do you know it worked? Because “looks good to me” is not a test, and you will change this prompt eleven more times.</p><p>Most bad prompts fail on <strong>R</strong>. Most bad <em>systems</em> fail on <strong>E</strong>.</p><h3>Before and after</h3><p>Nothing teaches this faster than watching a vague prompt get specific. Read the left, then read the right, and notice what got added.</p><p><strong>❌ “Write a summary.”</strong></p><p><strong>✅</strong> “Summarize the following customer support chat in three bullet points, focusing on the issue, the customer’s sentiment, and the resolution. Use clear, concise language.”</p><p><em>What changed:</em> a length, a structure, three named dimensions, a tone.</p><p><strong>❌ “Write a blog post about microservices.”</strong></p><p><strong>✅</strong> “As a senior software architect with 15 years of experience building distributed systems, write a technical blog post about microservices architecture patterns.”</p><p><em>What changed:</em> a persona, an experience level, and a narrowed subject. “Microservices” is a library; “architecture patterns” is a shelf.</p><p><strong>❌ “Help me with my Python code.”</strong></p><p><strong>✅</strong> “Review this Python function for performance optimization. Focus on reducing memory usage and improving time complexity. The code must maintain backward compatibility.”</p><p><em>What changed:</em> a goal, two priorities, and, critically, a constraint. Constraints are where models most often surprise you badly, because you never mentioned the thing you’d never accept.</p><p><strong>❌ “I want your help to see if I made any error in the above code and let me know if you find any”</strong></p><p><strong>✅</strong> “Find and list every error in the code above.”</p><p><em>What changed:</em> You are not verbose, you are not requesting. When writing code, be direct, be meaningful. Each word has its weight in gold.</p><p><strong>❌ “Tell me about different database types.”</strong></p><p><strong>✅</strong> “Compare NoSQL and SQL databases using this format:</p><pre>- Use cases:<br>- Performance characteristics:<br>- Scalability considerations:<br>- Cost implications:</pre><p>“</p><p><em>What changed:</em> you stopped hoping for structure and specified it.</p><p>The pattern across all four: <strong>vague prompts outsource your thinking to the model, and the model will make choices you didn’t want and can’t see.</strong></p><h3>First, what prompt engineering is not</h3><p>The term gets used for four very different things. Knowing which one you need saves weeks.</p><p><strong>Prompt engineering.</strong> Tailoring behavior via input phrasing. You change what’s in the context; the weights never move. Also called <em>in-context prompting</em>.</p><p><strong>Fine-tuning.</strong> Retraining the model on domain-specific data. Slow, expensive, and the correct answer far less often than people assume.</p><p><strong>Retrieval-augmented generation (RAG).</strong> Supplying relevant context from external sources at query time. The fix when the model needs facts it was never trained on.</p><p><strong>Memory and persistence.</strong> Carrying state across turns, sessions, or between agents.</p><p>A quick definition while we’re here: <strong>your “context” is everything the model can see</strong>: the system prompt, the user prompt, the retrieved documents, the tool definitions, the conversation so far. All of it. That definition matters a lot in the second half of this post.</p><p>Prompt engineering is the cheapest of the four by an order of magnitude. Exhaust it first.</p><h3>Four methods that cover most of the ground</h3><p><strong>Zero-shot.</strong> Feed the task, ask for the result. No examples. Start here: modern models are shockingly good at zero-shot, and every example you add costs tokens and narrows the model’s range.</p><p><strong>One-shot.</strong> One high-quality demonstration: an input <em>and</em> the output you wanted for it.</p><p><strong>Few-shot.</strong> A handful of demonstrations. The model reads your examples and infers your intent, your format, and your standard of quality, including the parts you couldn’t articulate. This is the highest-leverage technique in the list. It is also the easiest to do badly: three sloppy examples will teach the model to be sloppy with total fidelity.</p><p><strong>Chain-of-thought (CoT).</strong> Ask for the reasoning before the answer. The canonical trigger is Let&#39;s think step by step, from <a href="https://arxiv.org/abs/2201.11903">Wei et al., 2022</a>. It buys real accuracy on multi-step arithmetic, logic, and analysis.</p><p>One caveat worth stating plainly: on newer reasoning models, an explicit CoT instruction can be redundant or actively harmful. They already reason internally, and telling them to narrate can crowd it out. Which brings us to a theme: <strong>check the guide for the model you’re actually using.</strong></p><h3>The anatomy of a production prompt</h3><p>Open any serious system prompt and you’ll find the same components. Names and order vary. Presence doesn’t.</p><p><strong>System message (role, tone, persona).</strong> Sets behavior. <em>“You are a senior web developer at a Fortune 500 company.”</em></p><p><strong>Instruction.</strong> The task, stated directly and goal-first. <em>“Summarize the text below in two bullet points.”</em></p><p><strong>Context.</strong> Background the model needs: a document, history, structured input. Fence it:</p><pre>Here is the transcript from the last support call:<br>&lt;transcript&gt;<br>{ADD_TRANSCRIPT_HERE}<br>&lt;/transcript&gt;</pre><p><strong>Examples.</strong> One-shot or few-shot demonstrations that carry tone and format. <em>“Input: ‘Hi, I lost my order.’ → Output: ‘We’re sorry to hear that…’”</em></p><p><strong>Output constraints.</strong> Length, structure, type. <em>“Respond only in JSON.”</em></p><p><strong>Delimiters.</strong> Visual or structural separators: ### Instruction, --- Context Below ---, XML-ish tags, triple quotes. In a long prompt these do more work than any clever phrasing. The model has to know where your instructions end and your data begins, the distinction gives clarity. We want clarity.</p><p>And know your three output modes:</p><ul><li><strong>Text.</strong> Freeform.</li><li><strong>JSON.</strong> You ask for JSON and usually get JSON.</li><li><strong>Structured output.</strong> The schema is enforced at the decoding layer, so the response <em>cannot</em> violate it. If you’re parsing the output in code, use this. (<a href="https://platform.openai.com/docs/guides/structured-outputs#supported-schemas">OpenAI’s schema docs</a> are the clearest reference.)</li></ul><p>The difference between mode two and mode three is the difference between hoping and knowing.</p><h3>Five lines worth stealing</h3><p>Individually small. Together they change the character of what comes back.</p><h3>1. Assign a role</h3><pre>You are a senior web-developer at a Fortune 500 company.</pre><p>Three signals in one line: expertise level, domain, and organizational scale. That last one is sneakily effective: “Fortune 500” pulls answers toward scalability, security, and maintainability without you listing them.</p><h3>2. Specify the deliverable</h3><pre>Always provide full, documented code as artefacts.</pre><p>Kills the fragment problem. No more # ... rest of implementation here.</p><h3>3. Demand non-obvious information</h3><pre>Give me as much insightful, unusual, and important information as<br>possible wherever it may improve efficiency or profitability.</pre><p>Explicitly asks past the consensus answer, and ties “insightful” to an outcome so it isn’t just decorative novelty.</p><h3>4. Grant permission to disagree</h3><pre>Disagree with me if you believe a particular solution is not viable<br>enough. Ask me to change direction if required.</pre><p>The single highest-value line in this list. Default model behavior is agreeable, and an agreeable collaborator will help you build the wrong thing beautifully. This makes disagreement allowed, and models take that permission seriously.</p><h3>5. Open a dialogue</h3><pre>Ask me any questions so you can give me the best possible response.</pre><p>Converts one bad guess into two good turns. Especially strong when you know the task is underspecified but don’t yet know <em>which</em> part.</p><h3>Now the important half: how NOT to prompt</h3><p>Everything above is additive. Here’s the subtractive half, and it’s where most real systems fail.</p><blockquote><em>When you put something in the context, the model will pay attention to it.</em></blockquote><p>Context windows went from tens of thousands of tokens to millions. The natural conclusion is that the best result comes from giving the model everything: every document, every tool, every instruction, all the reference material you have.</p><p>That’s true. Up to a point. Past that point, every one of those tokens is competing for the model’s attention with the tokens that actually mattered.</p><p>Here are the five ways it goes wrong. If you wanted to sabotage someone’s agent, these are the levers. (Four of these are <a href="https://www.dbreunig.com/2025/06/22/how-contexts-fail-and-how-to-fix-them.html">Drew Breunig’s taxonomy</a>; “context rot” comes out of <a href="https://research.trychroma.com/context-rot">Chroma’s research</a>.)</p><p><strong>Context poisoning.</strong> A hallucination or error gets written into the context, and then gets referenced again, and again, and again. In a multi-turn agent, one bad fact early becomes the foundation for everything after. The output looks confident and internally consistent, and it is built on sand.</p><p><strong>Context distraction.</strong> The context grows so long that the model overfocuses on it and discounts its own training. It stops reasoning and starts pattern-matching against your blob. Symptom: the model parrots your input back at you, reworded, and adds nothing.</p><p><strong>Context confusion.</strong> Irrelevant context is still context, and the model will <em>use</em> it. Fifty tools loaded when the task needs two. A retrieved document that matched on keywords and nothing else. Superfluous information gets incorporated into the answer because it was there.</p><p><strong>Context clash.</strong> New information contradicts something earlier in the prompt. Two versions of the spec. An instruction the system prompt forbids. Models are bad at flagging the conflict and good at silently picking one, often the wrong one.</p><p><strong>Context rot.</strong> Around the 100k-token mark, even models advertising much larger windows start losing the ability to separate signal from noise. Retrieval accuracy degrades in the middle. The window says one million; the useful window is smaller, and it is <em>not</em> a cliff you’ll be warned about.</p><p>Notice that none of these throw an error. Every one of them produces a plausible, fluent, wrong answer. That’s what makes them expensive.</p><h3>What to do instead</h3><p><strong>Compress context.</strong> Summarize before you carry forward. In a long agent loop, roll history into a running digest instead of appending forever. The goal is not “fit in the window.” It’s “keep the signal-to-noise ratio high.”</p><p><strong>Feed errors into context, deliberately.</strong> A failed attempt plus its error message is high-value context; the model won’t repeat that mistake. A failed attempt with no diagnosis is just noise. Curate.</p><p><strong>Use RAG properly.</strong> Retrieval is context <em>selection</em>, not context <em>maximization</em>. If your retriever returns twenty chunks and three are relevant, you have shipped seventeen distractions. Tune for precision, not recall. Rerank, where necessary.</p><p><strong>Persist memory outside the window.</strong> Long-lived state belongs in storage you query, not in a transcript you replay.</p><p>The mental model that fixes all five: <strong>treat context as a scarce, curated budget, not a bucket.</strong> Ask of every line whether it is earning its place, and cut what isn’t.</p><h3>Read the manual for the model you’re using</h3><p>There is no one method that works everywhere. Different architectures, different training data, different post-training. A technique that lifts one model’s performance can flatten another’s, and the labs publish exactly which is which:</p><ul><li><a href="https://developers.openai.com/cookbook/examples/gpt4-1_prompting_guide/">OpenAI: GPT-4.1 prompting guide</a></li><li><a href="https://developers.openai.com/cookbook/examples/gpt-5/gpt-5-2_prompting_guide/">OpenAI: GPT-5 prompting guide</a></li><li><a href="https://docs.cloud.google.com/vertex-ai/generative-ai/docs/start/gemini-3-prompting-guide">Google: Gemini 3 prompting guide</a></li><li><a href="https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-4-best-practices">Anthropic: Claude 4 best practices</a></li></ul><p>Twenty minutes in the guide for your model beats twenty prompt iterations of guessing.</p><h3>One more resource, and it’s a good one</h3><p>If you want to see what production-grade prompts actually look like, not tutorial examples but real ones, this repo collects the system prompts behind a long list of shipped AI tools:</p><p>🏁 <a href="https://github.com/x1xhlol/system-prompts-and-models-of-ai-tools">github.com/x1xhlol/system-prompts-and-models-of-ai-tools</a></p><p>Read three or four of them end to end. You’ll notice how long they are, how much of them is constraints and edge cases rather than clever phrasing, and how every component from the anatomy section shows up. It’s the fastest way to recalibrate what “a real prompt” means.</p><h3>The short version</h3><p>Prompting is experimental and iterative. Nobody gets it in one shot, and anyone who tells you they did wasn’t measuring.</p><ul><li>Be direct, specific, and clear. Vagueness is a decision you’re delegating.</li><li>Specify the output format instead of hoping for it.</li><li>Include examples when you can, and make them good, because the model copies everything.</li><li>State your constraints, especially the obvious ones.</li><li>Give the model permission to push back.</li><li>Iterate on results, not vibes. Build the eval.</li><li>Read the prompting guide for your specific model.</li><li>And above all: <strong>cut context before you add it.</strong> Every token you include is a token the model has to weigh.</li></ul><p>The best prompt isn’t the one with the most in it. It’s the one with nothing in it that doesn’t need to be there.</p><p><em>If you build with this stuff daily, I’d genuinely like to know which of the five context failures has bitten you hardest. My money’s on confusion: too many tools, loaded too eagerly. Tell me I’m wrong in the responses.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=037ffe30966b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Loop, Three Patterns: A Practical Guide to Multi-Agent Orchestration]]></title>
            <link>https://pub.towardsai.net/one-loop-three-patterns-a-practical-guide-to-multi-agent-orchestration-8557c60ca23e?source=rss-52593e532004------2</link>
            <guid isPermaLink="false">https://medium.com/p/8557c60ca23e</guid>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[agentic-design]]></category>
            <category><![CDATA[delegation]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Hitesh Nankani]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 20:01:01 GMT</pubDate>
            <atom:updated>2026-04-23T20:01:01.466Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve spent any time with AI coding tools or chat-based assistants, you’ve probably noticed a pattern. The conversation starts sharp. The AI understands the task, makes good suggestions, executes cleanly. But somewhere around the ten back-n-forth mark — after a dozen tool calls, a few dead ends, and a growing pile of intermediate results — things get muddy. The AI starts repeating itself. It forgets a decision you made ten minutes ago. It re-reads a file it already summarized. The context window, that finite scratchpad the model uses to track everything, is full of noise from work that no longer matters.</p><p>The instinct is to blame the model. But the problem isn’t intelligence — it’s architecture. You’re asking one agent to hold an entire project in its head while simultaneously doing the work. That’s like asking a project manager to write every line of code, run every test, and keep the project plan updated, all in a single unbroken train of thought.</p><p>The alternative is to stop treating the AI as one agent and start treating it as several. A parent agent that plans and delegates. Child agents that receive clean, focused prompts, do one job, and return concise results. The parent never sees the mess — it sees summaries.</p><p>This is multi-agent orchestration. And while the idea sounds complex, the underlying mechanics are surprisingly simple. Every agent — whether it’s the planner, the worker, or the reviewer — runs the same loop.</p><h3>The loop that runs everything</h3><p>Here’s the part that reframes the whole design space: there is no special “coordinator runtime” or “worker runtime.” Every agent, regardless of its role, executes the same cycle.</p><p>It receives a prompt. It sends that prompt (along with its available tools) to a language model. The model responds — sometimes with text, sometimes with a request to use a tool. If it asked for a tool, the agent executes that tool and feeds the result back. Then the model responds again. This continues until the agent decides it’s done, or it hits a turn limit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riLMDO7QihW0GKJJ-jSccA.png" /><figcaption>Image 1: The Universal Agent Loop</figcaption></figure><p>That’s it. A coordinator agent runs this loop. A worker agent runs this loop. A reviewer agent runs this loop. What makes them different isn’t the loop — it’s the <em>configuration</em>. Which model powers it. Which tools it can access. What its system prompt says. How many turns it gets before it’s cut off.</p><p>This is worth sitting with for a moment, because it changes how you think about building these systems. You <strong>don’t </strong>need a “coordinator framework” and a “worker framework.” You don’t need different execution engines for different agent roles. <strong>You</strong> <strong>need one loop and a configuration surface wide enough to express the differences between roles</strong>. The orchestration patterns — and there are really only three you need — emerge from how you configure that single primitive.</p><p>It also means that adding a new type of agent is not an infrastructure problem anymore. You aren’t writing new execution logic. You’re writing a new system prompt, choosing a different tool set, and perhaps adjusting the turn limit. The inherent loop stays the same. The orchestration patterns emerge from configuration — not from fundamentally different execution models. The way you think about creating and maintaining agent, changes.</p><h3>Pattern one: Delegation</h3><p>The simplest pattern. A parent agent hits a sub-task it shouldn’t handle itself — maybe it needs to search a codebase for all API endpoints, or read through a set of test files and summarize coverage. Instead of doing it inline (and polluting its own context with all that raw output), it writes a <em>self-contained prompt</em> describing the task and hands it to a fresh agent.</p><p>The child agent starts clean. No history, no accumulated context, no awareness of what the parent has been doing. It gets a prompt, access to required tools, it does the work and returns a result. That result lands back in the parent’s context as a concise summary, not as fifty lines of grep output.</p><p>The key property here is <em>prompt self-containment</em>. The child can’t see anything the parent sees. Everything it needs must be in the prompt. This feels like a limitation, but it’s actually a forcing function for clarity — if the parent can’t articulate the task well enough for it to stand on its own, the decomposition isn’t clean yet. Vague delegation produces vague results, and the self-containment requirement makes vague delegation obvious immediately rather than subtly.</p><p>Delegation comes in two flavors.</p><ul><li><strong>Synchronous</strong>: the parent blocks and waits for the result before continuing.</li><li><strong>Asynchronous</strong>: the parent gets back an ID immediately and checks in later.</li></ul><p>The synchronous flavor is simpler — the sub-agent’s output arrives as a tool result, and the parent picks up where it left off. The async flavor matters when you want to fire off several delegations without waiting for each one sequentially, which leads directly to the second pattern.</p><p>Here comes a Crucial Question: When do we know a task can be delegated? <strong>Answer:</strong> When a focused, well-scoped sub-task can be created, where one agent has one objective, and is self-sufficient. “Read all the test files and summarize coverage.” “Search the codebase for all API endpoints.” Tasks where the answer is “go do this one thing and report back.” The delegated Agent does all work, and comes back with just the response. Your main agent’s context is not polluted unnecessarily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNanFNauB9__Wya--Wiq9w.png" /></figure><h3>Pattern two: The swarm</h3><p>Delegation handles one sub-task at a time. But some problems decompose into several independent pieces that could all run simultaneously. You need three modules reviewed. You need competitive analysis from four different angles. You need a security audit, a performance check, and a documentation review — and none of them depend on each other.</p><p>A swarm is a single operation that fans out to multiple agents and fans back in to a combined result. You define a team: a shared task description, plus a list of agents, each with a name, a role, and optionally a customized prompt, with a set of required tools. All agents launch at once. They run in parallel. When they’re all done, their outputs are collected and returned as one structured result — each agent’s name paired with its findings.</p><p>The distinction between a swarm and several async delegations might seem subtle, but it matters in practice. With individual async delegations, the parent manages each agent separately — launching them, tracking their IDs, polling for completion, aggregating results manually. A swarm handles the fan-out and fan-in as a single atomic operation. You define the team, the system executes all of them, and you get back one unified result. The bookkeeping is handled for you.</p><p>The important nuance is that not every agent in the swarm should be identical. One might have a security-focused system prompt and restricted tools. Another might be tuned for performance analysis. A third checks documentation completeness. Same shared task, different lenses. The configuration-driven nature of the universal loop makes this natural — you’re not building three different agent types, you’re writing three different system prompts and tool configurations over the same loop.</p><p>This is where the “O<strong>ne Loop- Different Config</strong>” insight pays its first real dividend. If agents were fundamentally different things, building a swarm with mixed capabilities would mean wiring together different systems. But because they’re all the same loop with different configs, a swarm is just a list of configurations launched in parallel.</p><p>Swarms shine when the work is <strong>genuinely parallel and independent</strong>. They don’t help when tasks have sequential dependencies — when agent B needs agent A’s output before it can start. For that, you need the third pattern.</p><h3>Pattern three: The coordinator</h3><p>This is the pattern for complex, multi-phase work. Think “refactor the authentication system” — a task that requires understanding the current state, planning the changes, implementing across multiple files, and then verifying nothing broke. No single delegation covers it. A swarm can’t handle it because the phases are sequential and each one depends on what the previous phase found.</p><p>A coordinator is an agent whose entire job is to plan, delegate, collect, synthesize, and iterate. It never does the implementation work itself. It spawns worker agents to gather information, reads their findings, identifies gaps, spawns more workers to fill those gaps, delegates implementation tasks, and then spawns verification workers to check the results.</p><p>The coordinator follows a natural four-phase rhythm: <strong>research</strong>, <strong>synthesis</strong>, <strong>implementation</strong>, <strong>verification</strong>. In the research phase, it spawns workers in parallel to gather information — reading files, searching code, collecting data. In synthesis, it collects those results, identifies what’s missing, and merges findings into a coherent picture. In implementation, it delegates the actual changes to specialized workers. And in verification, it spawns a final round of workers to check that the changes are correct — running tests, reviewing diffs, validating behavior.</p><p>This rhythm isn’t enforced by a rigid state machine. It’s a prompt-level pattern — the coordinator’s system prompt tells it to work in these phases, and because language models follow instructions well, it does. The coordinator can adapt: if the research phase reveals the problem is smaller than expected, it might skip straight to implementation. If verification fails, it loops back to synthesis.</p><p>But there’s one thing about the coordinator that <em>is</em> enforced structurally, not by prompt. And it’s the part of this architecture that matters most.</p><h3>The real enforcement: Tool partitioning</h3><p>Here’s the problem that breaks most naive multi-agent systems. If every agent has access to every tool, there’s no structural reason for a coordinator to delegate instead of just reading files and running commands itself. And there’s nothing stopping a worker from spawning its own sub-agents, which spawn their own sub-agents, in an uncontrolled cascade that burns through your API budget exponentially.</p><p>The fix isn’t telling agents what they shouldn’t do. It’s removing the capability entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nrF7ztXY5dpoZZMUI_AyJg.png" /></figure><p>In a well-designed system, tools are split into three categories. Orchestration tools — spawning agents, sending messages between them, cancelling running agents — are available <em>only</em> to the coordinator. Execution tools — shell commands, file operations, search — are available <em>only</em> to workers. A small set of shared tools, like task tracking, are available to both.</p><p>This creates two hard guarantees. The coordinator <em>cannot</em> read a file or run a command, because those tools don’t exist in its world. If it needs information, it must delegate — which forces it to articulate what it needs in natural language. And workers <em>cannot</em> spawn sub-agents, because the spawn tool isn’t in their toolset. No amount of creative prompting bypasses this, because you can’t call a tool that isn’t there.</p><p>Without these boundaries, you get two predictable failure modes.</p><p>The first is the busy-manager problem. The coordinator starts doing the work itself — reading files, running grep, scrolling through test output. It gets buried in implementation details, burns through its context window with raw data, and produces worse results than a simple single agent would have. The irony is that a coordinator that “helps” by doing work directly is less effective than one that’s forced to delegate, because the act of delegating forces clear task articulation, and clear task articulation produces better results.</p><p>The second is infinite delegation. A worker spawns a sub-worker, which spawns a sub-sub-worker. Each level incurs API costs and context window usage. Without limits, this compounds exponentially. The original task never completes because every agent keeps delegating downward instead of actually doing work. It’s recursion without a base case.</p><p><strong>Tool partitioning makes both structurally impossible</strong>. And that word — <em>structurally</em> — is the point. When you rely on prompts to constrain behavior, you’re relying on model judgment under pressure. Long context, ambiguous tasks, accumulated noise — these are exactly the conditions where model judgment degrades. The agents that misbehave most are the ones that have been running longest and have the most cluttered context. A prompt that says “don’t read files directly” works fine at turn three. By turn forty, the model has forgotten or rationalized past it.</p><p>Removing the tool is a guarantee that holds regardless of how confused, tired, or creative the model gets. It’s the difference between a safety guideline and a guardrail.</p><h3>Choosing the right pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNanFNauB9__Wya--Wiq9w.png" /></figure><p>The three patterns form a complexity gradient, and the meta-principle is to use the simplest one that works.</p><p>If the task is focused and well-scoped — “search the codebase for all uses of this deprecated function” — delegation is enough. One agent, one job, clean result.</p><p>If the task decomposes into independent parallel work — “review these three modules for security issues” — a swarm handles the fan-out and fan-in in a single operation.</p><p>If the task requires planning, iteration, and multi-phase execution — “refactor this subsystem and verify the tests still pass” — the coordinator pattern earns its overhead.</p><p>And if the task can be answered directly by a single agent in a few turns, don’t orchestrate at all. Every pattern adds API cost, latency, and complexity. Orchestration pays for itself when the task genuinely benefits from parallelism, context isolation, or hierarchical planning. It doesn’t pay for tasks one focused agent could handle in five turns. The most common mistake in multi-agent systems isn’t using the wrong pattern — it’s orchestrating when you didn’t need to.</p><p>The underlying insight is that the power of multi-agent systems doesn’t come from any individual agent being smarter. It comes from composition. The same model, running the same loop, configured differently and coordinated through clear boundaries, can tackle problems that no single invocation could handle. The engineering challenge isn’t in the agents — it’s in the orchestration. The boundaries, the tool partitioning, the configuration. Get those right and the agents almost take care of themselves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8557c60ca23e" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/one-loop-three-patterns-a-practical-guide-to-multi-agent-orchestration-8557c60ca23e">One Loop, Three Patterns: A Practical Guide to Multi-Agent Orchestration</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your AI Pair Programmer Forgets Everything — Here’s How to Fix That]]></title>
            <link>https://medium.com/@hiteshnankani97/your-ai-pair-programmer-forgets-everything-heres-how-to-fix-that-b1deddb41dec?source=rss-52593e532004------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1deddb41dec</guid>
            <category><![CDATA[ai-memory]]></category>
            <category><![CDATA[deep-ai]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[ideais]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Hitesh Nankani]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 14:08:34 GMT</pubDate>
            <atom:updated>2026-04-10T14:08:34.387Z</atom:updated>
            <content:encoded><![CDATA[<p>You know the ritual. New session, same preamble. “The project uses Rust 2021 edition.” “We prefer explicit error handling.” “The team picked tokio last week.” Your AI pair programmer nods along like it’s hearing this for the first time — because it is. The conversation history died when the last session ended, and everything you’d established evaporated with it.</p><p>This is the context amnesia problem, and if you’ve spent any time with LLM-based coding tools, you’ve felt it. The model is stateless across sessions. Every useful thing you taught it yesterday — your preferences, your project’s constraints, the architectural decisions you hammered out together — is gone.</p><p>So how do you give it a memory?</p><h3>Two Obvious Ideas That Don’t Survive Contact</h3><p><strong>Save the whole transcript.</strong> Keep everything, lose nothing. Except conversations are full of noise — debugging tangents, reverted ideas, questions asked twice. Load 50,000 tokens of raw history into the next session and you’ve burned your context window budget on low-signal content. The facts that matter are buried somewhere in page twelve of a rambling debug session.</p><p><strong>Let the developer maintain a notes file.</strong> Humans know what’s important, right? They do — but the facts most worth saving are discovered at exactly the moment you’re least inclined to write them down. Nobody stops mid-refactor to jot “we decided against that caching layer.” Manual curation requires discipline during flow state, and flow state is allergic to discipline.</p><p>What you actually want is something that watches the session, waits for it to settle, extracts the signal, and writes it down for you.</p><h3>The Shape of the Solution</h3><p>The approach is a gated pipeline. A gate decides whether extraction should happen at all. If the gate opens, a short pipeline fires once: build a transcript, ask the model to identify the important facts, parse its answer, and write the results to a project-level memory file that the next session can load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nrVOBRtE39ZAmA0LZVXIkw.png" /></figure><p>The interesting design lives in the gate and the parser. The pipeline stages between them — transcript assembly, the API call, file persistence — are mechanical. They work, but they aren’t where the hard thinking happened.</p><h3>When Not to Extract</h3><p>The gate has to answer a deceptively tricky question: <em>when is it safe and worthwhile to extract memories?</em></p><p>“<strong>Are there enough messages?</strong>” is the easy check. Twenty or more model-visible messages is a reasonable floor — anything shorter probably isn’t a meaningful session. But message count alone isn’t enough. You also need to know the session is in a <strong><em>settled</em> state</strong>. If the model just issued a tool call and hasn’t seen the result yet, you’d be extracting a half-formed thought. The gate defers until the last assistant turn has no pending actions.</p><p>And even once the session is long enough and settled, the gate asks one more question: <strong>has enough <em>new work</em> happened</strong> since the last extraction? One metric to measure this can be tool invocations count. Say— at least three tools have been invoked since the last run. This prevents the extractor from firing repeatedly on a session where the developer is just chatting without doing anything materially new.</p><p>Three checks, layered: enough history, a clean conversational state, and evidence of meaningful activity. Only when all three pass does extraction fire. NOTE: This is configured for IDE’s usecase, where tool call is Frequent. Configure these values as per your usecase.</p><h3>Memory Extraction— Be A Diplomat, Not a Bouncer</h3><p>Here’s the core design tension. You’re asking an LLM to produce structured output — category, confidence score, fact — and then parsing it programmatically. As a programmer, your first instinct? to reach for JSON. It’s standard, there are parsers everywhere, and the model mostly knows how to produce it. But “<em>mostly</em>” is the problem. An LLM might wrap JSON in a markdown code fence, or add a chatty preamble before the first brace, or hallucinate a trailing comma. Now your JSON parser throws error, and you’ve lost the whole extraction.</p><p>So, what approach to take here? Lower the tech. <br>Let’s say: The prompt asks in output for one fact per line in a <strong>pipe-delimited format</strong>: <strong><em>category</em></strong>, <strong><em>confidence</em></strong> on a 0–10 integer scale, and the <strong><em>fact</em></strong> itself. That’s it. No nesting, no braces, no schema.</p><p>The parser then treats this format with a philosophy you could call <em>diplomatic</em>: strict enough to read structure from well-formed lines, lenient enough to silently discard everything else. If the model adds a preamble — “Here are the extracted memories:” — the parser doesn’t break. That line simply doesn’t start with the expected prefix, so it’s skipped. If the confidence field is unparseable, it defaults to a neutral value instead of failing. If the category string doesn’t match any known type, it falls back to a sensible default rather than rejecting the entry.</p><p>It’s a diplomat, not a bouncer. A bouncer rejects anything that doesn’t match the dress code. A diplomat assumes good intent, extracts what’s useful, and politely ignores the rest. When your data source is a language model — something that follows instructions <em>almost</em> perfectly, <em>most</em> of the time — the diplomat wins.</p><p>Here is the transferable insight- The confidence score should use <strong>integers</strong> <strong>rather than floats</strong> because LLMs produce integers more reliably. The format uses pipes rather than JSON because a line-oriented parser can recover from any single malformed line without losing the rest. Every choice pushes toward the same principle: <strong>make the happy path structured</strong>, and make <strong>every failure mode a graceful degradation rather than a crash</strong>.</p><h3>The Sharp Edge</h3><p>For the keen observers — there’s an important edge case we’ve missed above. What if the gate is closed but the session has now ended? You’d lose the crucial information from the tail of the conversation.</p><p><strong>The fix:</strong> during session teardown, bypass the activity threshold. If there will be no new messages to count, the threshold doesn’t apply. Without this, a session that ends shortly after its last extraction silently drops whatever happened in that final stretch.</p><h3>The Takeaway</h3><p>When you need structured data from an LLM, don’t optimise for the happy path — optimise for the failure modes. Pick the simplest format that’s still parseable. Build the parser as a diplomat: strict enough to find structure, lenient enough to survive the model’s inevitable deviations. The model will improvise. Your parser’s job is to not care.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1deddb41dec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Modern AI-IDE’s Survives Long Conversations: The Auto-Compaction Engine]]></title>
            <link>https://medium.com/@hiteshnankani97/how-modern-ai-ides-survives-long-conversations-the-auto-compaction-engine-6ddd9daa1e46?source=rss-52593e532004------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ddd9daa1e46</guid>
            <category><![CDATA[ai-memory]]></category>
            <category><![CDATA[ai-contex]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Hitesh Nankani]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 11:03:17 GMT</pubDate>
            <atom:updated>2026-04-06T11:03:17.661Z</atom:updated>
            <content:encoded><![CDATA[<p>A 200,000-token context window sounds enormous — until a single agentic coding session burns through it in fifteen minutes. Every file read, every bash invocation, every tool result accumulates. The model doesn’t just see your latest message; it sees the entire conversation: every grep output, every failed lint run, every 500-line file it read three turns ago and hasn&#39;t needed since. At some point the window fills, and your next request simply won&#39;t fit.</p><p>The obvious solutions don’t work. Truncating the oldest messages throws away decisions the model made — it’ll re-read files it already analysed, reverse choices it already committed to, or lose track of which approach failed and why. Summarising everything into a few sentences is too lossy; agentic coding sessions carry dense technical state (file paths, function signatures, error messages, in-progress edits) that a generic summary would flatten into uselessness.</p><p>An IDE I was Reviewing, its compaction engine takes a different approach: a <strong>graduated pressure-response system</strong> that applies increasingly aggressive compression as the context fills up, always preserving the most recent work verbatim while compressing older history into structured summaries that retain enough detail to continue without interruption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iz8Wlz20I0mF6JxiF1LFCA.png" /><figcaption>DIAGRAM 1: Before &amp; After Compaction</figcaption></figure><h3>The escalation ladder</h3><p>The system doesn’t have a single compaction strategy. It has four, arranged by the severity of context pressure, each trading of fidelity for space as the situation demands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KDF60MF1k_hNZkUOk4wOg.png" /><figcaption>DIAGRAM 2:The escalation ladder — four strategies with their thresholds</figcaption></figure><p>At 75% capacity, <strong>MicroCompact</strong> fires first. It’s a light pass: summarise the oldest messages with a tight 2,048-token budget and keep the last 10 messages intact. It buys breathing room without much cost.</p><p>At 90%, the system escalates to <strong>Auto-Compact</strong> — the primary strategy. It splits the conversation into a head (everything old) and a tail (the 10 most recent messages), sends the head to the LLM for a detailed structured summary with a generous 20,000-token budget, and replaces the entire head with that summary. This is the workhorse; most sessions never need anything more aggressive.</p><p>Also at 90%, there’s an alternative path: <strong>Reactive Compact</strong>. While Auto-Compact fires <em>after</em> a completed assistant turn, Reactive Compact fires <em>during</em> streaming, immediately when the API reports token usage crossing the threshold. It runs the same summarisation but adds two extra phases: stripping image blocks before summarising (images are token-expensive and carry no information a text summary needs), and re-injecting up to 5 recently-modified files afterward so the model retains the file context it’s actively working with.</p><p>At 97%, it’s an emergency. <strong>Context Collapse</strong> fires as a last resort — an ultra-short summary (max 500 words, 1,000-token budget) that captures only the most recent request, the single most important decision, essential file names, and what was being worked on immediately before the collapse. The entire conversation is reduced to two messages: the collapse summary and the user’s last message.</p><h3>How the core summarisation works</h3><p>All four strategies (except Context Collapse, which is its own special case) converge on the same core function: summarise_head. This is the heart of the compaction engine.</p><p>The function takes the oldest portion of the conversation — everything before the 10 most recent messages — and builds a plain-text transcript from it. User messages become Human: ..., assistant messages become Assistant: ..., tool calls become [Tool Call: name (id=...)] blocks with their inputs, and tool results include their content (with errors flagged). This transcript is the raw material the summariser works with.</p><p>That transcript gets wrapped in XML and sent to the LLM as a single, non-streaming API call. The response is then cleaned up — the model’s internal analysis scratchpad is stripped out, the summary XML tags are reformatted into plain text, and redundant blank lines are collapsed. The result is injected as a synthetic user message at the head of a new, shorter conversation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AIuuDmOiiyElMyw9TfiMrA.png" /></figure><p>After compaction, the model sees a conversation that starts with a detailed summary of everything that happened before, followed by the last 10 messages exactly as they were. From the model’s perspective, it’s as if a knowledgeable colleague handed it a briefing document and said “here’s where we are — pick up from here.”</p><p>NOTE: One subtlety- In Compaction call when the LLM goes over older conversations, there is a requirement of Explicit Do not Make any Tool Calls, Read Files and the likes of it, to ensure No New Context is added to the the LLM’s Context (leading to wasted context/ Recursive Compaction)</p><h3>The structured summary format</h3><p>The compaction prompt doesn’t ask for a generic summary. It asks for a 9-section structured document designed to make the session fully resumable:</p><ol><li><strong>Primary request and intent</strong> — what the user actually asked for</li><li><strong>Key technical concepts</strong> — frameworks, patterns, technologies in play</li><li><strong>Files and code sections</strong> — specific files touched, with code snippets and why they matter</li><li><strong>Errors and fixes</strong> — every error encountered and how it was resolved</li><li><strong>Problem solving</strong> — what was figured out and what’s still being debugged</li><li><strong>All user messages</strong> — verbatim listing of every non-tool-result user message (to preserve the user’s feedback and changing intent)</li><li><strong>Pending tasks</strong> — things explicitly requested but not yet done</li><li><strong>Current work</strong> — precisely what was happening when compaction fired</li><li><strong>Optional next step</strong> — the immediate next action, but <em>only</em> if it directly follows from the user’s last request</li></ol><p>This is not a generic summary prompt. It’s engineered for the specific failure modes of agentic coding sessions. Section 4 (errors and fixes) exists because without it, the model will retry approaches that already failed. Section 6 (all user messages) exists because user feedback often subtly redirects the model, and a summary that captures only the model’s actions but not the user’s corrections will drift from the user’s intent. Section 9 is deliberately cautious — the “optional” qualifier and the instruction to only include next steps that directly follow from the most recent request prevent the model from resuming work on stale or completed tasks after compaction.</p><p>The model is also asked to produce an &lt;analysis&gt; scratchpad before the summary — a chain-of-thought pass over the conversation chronologically. This analysis is then <em>stripped out</em> before the summary is stored, so it doesn&#39;t consume context window space. It exists purely to improve the quality of the summary by forcing the model to think through the conversation carefully before committing to what to include.</p><h3>The circuit breaker</h3><p>Compaction makes an API call. API calls can fail. If compaction fails repeatedly — because the model produces empty responses, the request is malformed, or the API is temporarily down — you don’t want the system to keep hammering the endpoint every turn, burning tokens and adding latency for nothing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ont-CtKOBh0oDahto95Cww.png" /><figcaption>DIAGRAM 4: Circuit Breaker will make 3 attempts.</figcaption></figure><p>Three consecutive failures trips the circuit breaker and disables auto-compact for the rest of the session. Any single success resets the counter. Once disabled, it stays disabled — there’s no automatic retry. This is a pragmatic choice: if compaction is failing, something is systematically wrong, and continuing to attempt it would only waste resources. Better to let the session run until it hits the context limit naturally.</p><h3>Context Collapse: the emergency exit</h3><p>When the context reaches 97% — so full that a normal 20,000-token summary might not even fit — Context Collapse abandons the structured approach entirely.</p><p>No structured sections. No analysis scratchpad. No 20,000-token budget. Just four bullet points, 1,000 output tokens, and the instruction to keep it under 500 words. The resulting conversation has exactly two messages: the collapse notice and the user’s last message. Everything else is gone.</p><p>It’s lossy by design. The system accepts significant information loss to keep the session alive rather than failing entirely. A degraded session that can continue is better than one that can’t.</p><h3>The takeaway</h3><p>The compaction engine illustrates a general pattern in building systems around large language models: <strong>the model is both the runtime and the maintenance infrastructure</strong>. The LLM is doing the coding work, and LLM is also doing the compression of its own conversation history. The prompt engineering for the compressor matters as much as the code that calls it — the nine structured summary sections, the anti-tool-call sandwich, the analysis scratchpad that’s generated and then discarded — all of these are engineering decisions that directly affect whether the model can pick up where it left off after compaction.</p><p>The graduated pressure response is the design insight worth generalising. Rather than a single strategy that tries to handle all cases, the system has four strategies calibrated to different levels of urgency, with clean handoffs between them. Each strategy makes different tradeoffs between information preservation and space savings, and the thresholds are set so the gentler strategies fire first and the aggressive ones only activate when they have to. It’s the same pattern as memory hierarchies in hardware — L1 cache is fast but small, main memory is slow but capacious, and the system moves data between them based on access patterns and pressure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ddd9daa1e46" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>