<?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 Harshit Singh on Medium]]></title>
        <description><![CDATA[Stories by Harshit Singh on Medium]]></description>
        <link>https://medium.com/@harshit-aitch-cmd?source=rss-a9b2c35f1588------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IKZFBCMAD0jTN_47</url>
            <title>Stories by Harshit Singh on Medium</title>
            <link>https://medium.com/@harshit-aitch-cmd?source=rss-a9b2c35f1588------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:49:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshit-aitch-cmd/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[Inserting, Updating, Deleting docs in a vector index]]></title>
            <link>https://medium.com/@harshit-aitch-cmd/inserting-updating-deleting-docs-in-a-vector-index-60eae760639f?source=rss-a9b2c35f1588------2</link>
            <guid isPermaLink="false">https://medium.com/p/60eae760639f</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Harshit Singh]]></dc:creator>
            <pubDate>Sat, 23 May 2026 18:14:44 GMT</pubDate>
            <atom:updated>2026-05-23T18:14:44.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYHwMqtatrs4xQAD3g7dEA.png" /></figure><p>If you’ve built a basic RAG demo, you’ve probably done the fun part, picking an embedding model, splitting docs into chunks, getting answers back from an LLM. What nobody warns you about is that the real work starts the day your docs stop sitting still.</p><p>People edit them. People delete them. Permissions change. Sometimes the same doc updates 50 times in a minute because someone left autosave running. Your shiny vector index now has to stay in sync with a source of truth that won’t stay put, and most tutorials just don’t cover this part.</p><p>This post is about that part. What it actually takes to handle inserts, updates, and deletes in a vector index without breaking retrieval, leaking deleted content, or burning your embedding budget on a single typo fix.</p><p>A vector index is a cache. The real docs live somewhere else, Confluence, Drive, S3, a database. Your index is just a copy of that, optimized for semantic search. So anything that happens to the real doc has to eventually happen to your index. A doc gets created, edited, deleted, or its permissions change, that’s basically the whole list.</p><p>This sounds simple, and it is, until you actually have to keep them in sync at production scale. Most RAG tutorials stop at “embed your docs and search them.” The harder problems start the day someone edits a 200-page wiki page and your system has to figure out what to do about it.</p><h3>Inserts: the easy one</h3><p>New doc shows up, you fetch it, chunk it, embed the chunks, write them to the index. Done.</p><p>Two things matter that aren’t obvious from that one sentence.</p><h4>1. Idempotency</h4><p>In distributed systems, failures happen all the time:</p><ul><li>workers crash</li><li>networks fail</li><li>queues retry messages</li></ul><p><strong>Imagine a worker processes half the document and crashes. The queue retries the same job again.</strong></p><p>If the vector DB generates random IDs each time, the same chunks can get inserted twice, creating duplicates in the index.</p><p>The fix is to generate chunk IDs yourself, deterministically, from the chunk’s <em>address</em> in the document, not from its content:</p><pre>chunk_id = hash(doc_id + chunk_position)</pre><p>Two roles, kept deliberately separate:</p><ul><li><strong>The ID is the chunk’s address.</strong> It comes from where the chunk lives (doc + position), so it stays stable across versions.</li><li><strong>The content hash is change-detection.</strong> Store it as metadata next to the chunk. You’ll use it for updates, but it does <strong>not</strong> go into the ID.</li></ul><p>Keeping content out of the ID is the part that pays off later. Because the ID depends only on position, a retry that writes the same chunk produces the same ID, so the write becomes an idempotent upsert, it overwrites the identical row instead of creating a duplicate.</p><p>Same address → same ID → retries are safe.</p><h4>2. Backpressure</h4><p>Embedding is usually the slowest step in the pipeline. You may be limited by:</p><ul><li>API rate limits</li><li>GPU throughput</li><li>embedding model latency</li></ul><p>Meanwhile, parsing and chunking are much faster and produce work quicker than the embedder can consume it.</p><p>That creates backpressure: <strong>work enters the system faster than it leaves.</strong></p><p>A common mistake is monitoring only queue size. What matters more is queue growth rate.</p><p>Example:</p><pre>Queue size: 10K → 20K → 50K → 100K</pre><p>By the time the queue reaches 100K jobs, the system has already been falling behind for hours. So monitor whether the queue is growing continuously, not just how large it is right now.</p><h3>Updates: where most systems get it wrong</h3><p>A doc gets edited. Now what?</p><p>The naive thing is to delete every chunk for that doc, re-chunk the new version, and write the new chunks back. Don’t do this, for two reasons.</p><h4>1. Cost</h4><p>Someone fixes a typo on page 47 of a 200-page Confluence doc. You just re-embedded 200 pages worth of chunks to fix one comma.</p><h4>2. Temporary disappearance</h4><p>Between the delete and the insert, the doc is briefly missing from the index. Any query during that window won’t find it. Milliseconds isn’t a big deal, but a large doc that takes 30 seconds to parse and re-embed turns this into a real “where did that doc go?” bug.</p><h4>Better approach: chunk-level diffing</h4><p>Instead of rebuilding the entire document every time something changes, the system:</p><ol><li>Re-chunks the updated document</li><li>Generates a content hash (fingerprint) for each chunk</li><li>Looks up the existing chunk using its stable chunk ID</li><li>Compares the new content hash with the stored one</li><li>Re-embeds only the chunks whose content actually changed</li></ol><p>The important detail is that the chunk ID stays stable across edits because it’s built from:</p><pre>doc_id + chunk_position</pre><p>not from the chunk content itself.</p><p>That means if a chunk changes, the system doesn’t create a brand-new chunk entry. It simply re-embeds the updated content and upserts it back into the same chunk ID, replacing the old version in place.</p><p>So if someone fixes a typo on page 47 of a 200-page document, only that one affected chunk gets re-embedded instead of all 200 pages.</p><p>The only chunks that get deleted are the ones that genuinely disappeared in the new version. During re-chunking, if an old chunk ID no longer appears in the new document structure, the system removes it from the index.</p><p>This is also why the content hash is stored during insertion. The hash acts as the chunk’s fingerprint for future comparisons, but it lives only in metadata, never inside the chunk ID itself.</p><h4>Even better: atomic swap</h4><p>With diffing and in-place upserts, the doc is never <em>fully</em> missing the way it was with naive delete-then-insert. The residual risk is subtler: a query that lands mid-update can retrieve a <strong>mix</strong> of old and new chunks, some already upserted, some not yet.</p><p>Atomic swap closes that gap. Instead of upserting in place, the system writes the new chunks separately under a new version tag, then flips a single “current version” pointer from old to new in one operation, then garbage-collects the old chunks asynchronously.</p><p>Now a query during an update always sees either:</p><ul><li>the old version, or</li><li>the new version</li></ul><p>but never a state where the chunks are half-replaced. It adds more complexity, so it’s usually only worth it for systems where updates are frequent and visible to users.</p><h4>Practical issue</h4><ol><li>Chunk shifting: Because the ID is built from position, <strong>what you use as the position matters</strong>. If position is a plain ordinal (chunk #47) and someone adds a paragraph near the top, every chunk after it shifts down, every position changes, so every ID changes, even for chunks whose text is byte-for-byte identical. Diffing now thinks “everything changed,” and you re-embed the whole doc.</li></ol><p>The fix is to chunk using structural anchors like headings or sections, and use those as the position. A chunk addressed as “Section 3.2” keeps the same ID even if “Section 3.1” became longer. Structural anchors keep both the diff cheap and the ID stable.</p><p>2. Too many updates: Some tools autosave constantly, which can generate dozens of updates per minute. Instead of re-running the indexing pipeline on every keystroke, debounce the updates: wait 10–30 seconds, combine multiple updates into one job, and process only the latest version.</p><h3>Deletes: not just inserts in reverse</h3><p>Most teams treat deletes like the opposite of inserts. That’s a mistake, because deletes usually involve sensitive situations.</p><p>A document may be deleted because:</p><ul><li>sensitive information was shared accidentally</li><li>HR processed a termination</li><li>legal requested a takedown</li><li>a customer requested GDPR “right to be forgotten”</li><li>compliance found PII in the document</li></ul><p>Every minute that document is still searchable after the delete request is a potential data leak.</p><h4>Deletes must be hard deletes</h4><p>A soft delete only marks the document as deleted, but the actual chunks still exist in the index. Someone using a debug tool or analytics system could still retrieve them.</p><p>For sensitive data, that’s dangerous.</p><p>Instead, actually remove the chunks from the vector index.</p><h4>Deletes must be fast</h4><p>Set a strict SLA or SLO for deletion, for example:</p><pre>Delete request → fully removed within 60 seconds</pre><p>Different vector databases handle deletes differently. Some remove data immediately, while others delay cleanup internally. If you don’t understand those semantics, deleted data may still be retrievable minutes later.</p><h4>Deletes must be auditable</h4><p>Always log:</p><ul><li>what was deleted</li><li>when it was deleted</li><li>why it was deleted</li><li>which chunks were removed</li></ul><p>If legal or compliance asks whether a document was removed on time, the answer should come from logs, not guesswork.</p><h4>Deletes must cascade everywhere</h4><p>The vector index is not the only place data exists.</p><p>Deleted content may also exist in:</p><ul><li>metadata stores</li><li>caches</li><li>semantic caches (cached query → answer pairs)</li></ul><p>For example, if an old cached answer was generated using chunks that were later deleted, the cache can still serve deleted information.</p><p>That cache also needs to be invalidated.</p><h4>ACL changes are basically deletes</h4><p>Sometimes the document still exists, but a user loses permission to access it.</p><p>From that user’s perspective, it should disappear immediately.</p><p>That means ACL (permission) updates need the same urgency as hard deletes. Stale permissions are effectively a security leak.</p><h3>A few things that aren’t obvious</h3><h4>Some systems don’t tell you when docs are deleted</h4><p>Not every data source sends a proper “delete event.”</p><p>Polling-based connectors only know what exists <em>right now</em>. They don’t say:</p><pre>&quot;This document was deleted&quot;</pre><p>So the system has to periodically scan the source, compare it with the vector index, and remove anything that exists in the index but no longer exists in the source.</p><p>This cleanup process is slow and boring, but necessary. Most teams run it nightly.</p><h4>The pipeline is eventually consistent</h4><p>RAG ingestion pipelines are usually eventually consistent, not strongly consistent.</p><p>That means changes are not visible instantly:</p><ul><li>inserts/updates may take a few minutes</li><li>deletes may take under a minute</li></ul><p>And that’s okay, as long as you define and measure clear SLOs.</p><p>Example:</p><pre>New docs searchable within 5 minutes<br>Deletes removed within 1 minute</pre><p>Monitor these delays and alert when the system falls behind.</p><p>Don’t pretend everything updates instantly. In distributed systems, it usually doesn’t.</p><h4>The tricky user experience problem</h4><p>One place eventual consistency feels bad is when a user edits a document and immediately searches for their own change.</p><p>The content may not be indexed yet, so search doesn’t show it.</p><p>To the user, this looks like:</p><pre>&quot;The system is broken&quot;</pre><h4>Don’t make the whole pipeline synchronous</h4><p>You could force every edit to index immediately before returning, but that makes the entire pipeline slower and more fragile.</p><p>Instead, solve the issue locally for that user.</p><p>Common approaches:</p><ul><li>a small temporary cache for recently edited docs</li><li>or a UI message like:</li></ul><pre>&quot;Your recent edit is still indexing&quot;</pre><p>The idea is simple:</p><pre>Surface the delay instead of pretending it doesn&#39;t exist</pre><h3>What to build first</h3><p>If you’re starting greenfield:</p><ol><li>Ingestion for one source. Deterministic chunk IDs, idempotent upserts. Don’t bother with diffing yet, naive re-embed is fine while volume is low.</li><li>Hard deletes with audit logging. Get this right before any sensitive data goes into the index.</li><li>Observability across the whole pipeline. Trace IDs from source event through to index write. You cannot debug a sync pipeline you can’t see.</li><li>Chunk-level diffing for updates, once cost or latency starts hurting.</li><li>Atomic swap, only if retrieval quality during updates becomes a real complaint.</li></ol><p>That’s the unglamorous half of RAG. Retrieval and reranking get all the blog posts because they’re fun to talk about, but the systems that survive in production are the ones where sync is boring and predictable. Boring sync is the goal.</p><p>If you’re new to this and feeling like there’s a lot to handle, you don’t have to build all of it at once. Start with inserts and hard deletes, get observability in early, and add the fancier pieces (diffing, atomic swap, ACL freshness) only when something actually hurts. The teams that struggle are the ones who skipped the basics and went straight for the clever bits.</p><p>I’ll write up the eval side of RAG next, that’s the other half nobody covers properly. If you want me to go in a different direction, let me know.</p><p>#RAG #AIEngineering #VectorDatabases #SystemDesign #DistributedSystems #SemanticSearch</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60eae760639f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Four Kinds of Memory Your AI Agent Actually Needs]]></title>
            <link>https://medium.com/@harshit-aitch-cmd/the-four-kinds-of-memory-your-ai-agent-actually-needs-7a71cc3b5da9?source=rss-a9b2c35f1588------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a71cc3b5da9</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-memory]]></category>
            <category><![CDATA[context-engineering]]></category>
            <dc:creator><![CDATA[Harshit Singh]]></dc:creator>
            <pubDate>Mon, 04 May 2026 20:30:06 GMT</pubDate>
            <atom:updated>2026-05-04T20:30:06.051Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A field guide to memory architecture for production LLM agents the part nobody tells you about until your bill triples and your users start getting other people’s conversations.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAEqxwLoCYRDYlmrZlsW9g.png" /></figure><p>Most teams I’ve seen building agents start the same way: wire up an LLM, slap a system prompt on it, append the conversation history, ship it. It works. For about two weeks.</p><p>Then the prompts get longer. Latency creeps up. Someone notices the API bill. A user says, “I told you my name three times already.” Another says, “Why do you keep recommending Italian food? I’m allergic to gluten.” And somewhere, quietly, your agent has started responding with information from a completely different user’s session.</p><p><strong>This isn’t a prompt engineering problem. It’s a memory architecture problem.</strong></p><h4>The taxonomy that changes how you think about this</h4><p>Cognitive scientists have been studying human memory for about a century, and they figured out something useful: memory isn’t one thing. It’s at least four things, and they work very differently.</p><ol><li><strong>Working memory</strong> is what’s in your head right now as you read this sentence<strong>.</strong></li><li><strong>Episodic memory</strong> is your memory of specific events, what you had for breakfast, that one awkward thing you said in 2014.</li><li><strong>Semantic memory </strong>is your stored knowledge about the world, Paris is in France, water boils at 100°C.</li><li><strong>Procedural memory</strong> is what your fingers know when you ride a bike or type without looking at the keyboard.</li></ol><p>Here’s the kicker: agents need all four. And they need them implemented differently. Most production memory bugs I’ve seen come from teams treating memory as one undifferentiated bucket usually a vector database and then being confused when it doesn’t work.</p><p>Here’s the table I wish someone I knew before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*o7gFfe-bDqUPt6zbuTjbIw.png" /></figure><p>If you take nothing else from this artcile, take that table. It’s the centerpiece. Everything below is just unpacking why each row looks the way it does.</p><h4>Why “just stuff it all in the prompt” hits a wall</h4><p>Let’s start with the naive approach because everyone starts there, and there’s no shame in it. You take the conversation history, you concatenate it, you prepend a system prompt, you send it to the model. Done.</p><p>This works beautifully until it doesn’t. Here’s where it breaks:</p><p><strong>Token cost-</strong> You’re paying for every input token. If your average user has 50 turns and each turn is 200 tokens, you’re sending 10K tokens of context on turn 51. On turn 200, you’re sending 40K. That’s not a bug that’s just what addition does but your finance team is going to notice.</p><p><strong>Latency-</strong> Time-to-first-token scales with input length. A 50K-token prompt isn’t just expensive, it’s slow. You’ll feel it. Your users will feel it more.</p><p><strong>Context window limits-</strong> Yes, modern models have huge windows. No, that doesn’t save you. Even with a 200K window, you’ll hit it if your agent has any longevity. And the closer you get to the limit, the worse the model behaves.</p><p><strong>Lost-in-the-middle-</strong> This is the one nobody warned you about. <strong>Research has consistently shown that LLMs pay disproportionate attention to the beginning and end of their context, and information in the middle gets… fuzzy.</strong> Drop a critical fact at token 30,000 of a 60,000-token prompt and watch the model confidently ignore it.</p><p>So the prompt is not your memory system. The prompt is one slot the working-memory slot and you have to be deliberate about what goes in it.</p><h3>Working memory: the art of what stays in-flight</h3><p>Working memory is the <strong>context window</strong>. That’s it. It’s what the <strong>model can directly see on this turn</strong>. The whole game here is deciding what deserves a slot.</p><p>A reasonable working-memory layout for a production agent looks something like:</p><ol><li><strong>System prompt </strong>(procedural memory we’ll get to this)</li><li>A few <strong>semantic facts about the user</strong> that are likely relevant (“user is vegetarian, lives in Berlin, prefers concise responses”)</li><li><strong>Retrieved episodic snippets relevant to the current query</strong></li><li>The <strong>last N turns</strong> of the current conversation, verbatim</li><li>The <strong>current user message</strong></li></ol><p>Notice what’s not in there: the entire conversation history.<strong> Most of that has either been compressed, distilled into semantic facts, or sent to long-term episodic storage.</strong></p><p>The two questions you’re constantly answering for working memory are: <strong>what do I keep recent</strong>, and <strong>what do I keep relevant</strong>? <strong>Recent is easy last N turns, sliding window</strong>. Relevant is harder, you need <strong>retrieval</strong>. Production systems do both, and the order matters: <strong>put retrieved-relevant content earlier or later in the prompt, never in the middle, because of lost-in-the-middle.</strong></p><p>A useful pattern: <strong>when the conversation gets long, summarize older turns into a running summary block, keep the last 4-6 turns verbatim, and retrieve relevant older specifics on demand</strong>. The summary preserves continuity, the verbatim turns preserve recent nuance, the retrievals fill in specifics the summary lost.</p><h3>Episodic memory: where conversations go to be remembered</h3><p><strong>Episodic memory is your record of what actually happened</strong>. User said X on Tuesday. Agent did Y. The PR was rejected. The trip was booked.</p><p>The <strong>default implementation is a vector database</strong>. You embed each conversation turn (or summary of a turn),<strong> store it with a timestamp and user ID</strong>, and at query time you embed the current question and retrieve the top-k most similar past entries.</p><p>This works. Until it doesn’t.</p><p>The problem with naive vector retrieval is that pure similarity is a terrible ranking signal once a user has 10,000 conversations. The most semantically similar conversation might be from eighteen months ago, about a project they no longer care about. <strong>You need recency weighting.</strong></p><p>A common formula: score = similarity * exp(-age / decay_constant). <strong>Tune the decay constant to your domain.</strong> A coding assistant might want a decay of weeks, a personal journal companion might want years.</p><p>Decay is also useful because it lets you handle the 10K-conversation user gracefully. You don’t actually delete old memories. You just let their effective retrieval probability decay. <strong>If a user suddenly references something from two years ago by name, exact-match search still finds it.</strong> But it doesn’t pollute your top-k results for unrelated queries. Exponential decay is the simple version; production systems often use learned re- rankers that incorporate recency as one feature among many.</p><p>A few things systems get wrong here:</p><ul><li><strong>Storing raw turns instead of summarized ones-</strong> Embedding every turn produces a noisy index full of “ok thanks” and “got it.” Summarize first, embed the summary.</li><li><strong>Not separating the index by user-</strong> This is a security issue, not a performance issue. We’ll come back to it.</li><li><strong>Forgetting to update-</strong> Episodic memory should be append-only for the events themselves, but the embeddings you query against may need re-indexing as your embedding model changes.</li></ul><h3>Semantic memory: the distilled, structured stuff</h3><p>Semantic memory is <strong>what’s left after you forget the specifics and keep the gist.</strong> The user told you on January 4th that they’re allergic to peanuts. By March, the date doesn’t matter, the specific phrasing doesn’t matter what matters is the fact: user.allergies = [&quot;peanuts&quot;].</p><p>This is the memory type where I see the most architectural confusion. Teams reach for a vector DB because that’s the AI-flavored solution, and they store user facts as embedded text. Then they’re surprised when the agent can’t reliably answer “what are my dietary restrictions?” because the retrieval missed.</p><p>For semantic memory about the user, <strong>structured stores beat vector DBs almost every time.</strong> <strong>When the agent needs to know the user’s allergies, it shouldn’t do a similarity search and hope it should query the field</strong>. (More on storage choices below.)</p><p>A reasonable user-facts schema looks something like:</p><pre>{<br>  &quot;user_id&quot;: &quot;u_8821&quot;,<br>  &quot;preferences&quot;: {<br>    &quot;communication_style&quot;: &quot;concise&quot;,<br>    &quot;language&quot;: &quot;en&quot;<br>  },<br>  &quot;constraints&quot;: {<br>    &quot;dietary&quot;: [&quot;vegetarian&quot;, &quot;no peanuts&quot;],<br>    &quot;accessibility&quot;: []<br>  },<br>  &quot;context&quot;: {<br>    &quot;location&quot;: &quot;Berlin&quot;,<br>    &quot;timezone&quot;: &quot;Europe/Berlin&quot;,<br>    &quot;occupation&quot;: &quot;backend engineer&quot;<br>  },<br>  &quot;stated_goals&quot;: [&quot;learn about transformers&quot;, &quot;ship side project&quot;],<br>  &quot;last_updated&quot;: &quot;2026-04-12T09:14:00Z&quot;<br>}</pre><p>The interesting engineering question is the <strong>consolidation pipeline</strong>: how do facts get from episodic memory into this structured store? This is where you need an explicit process, usually a <strong>background job</strong> that:</p><ol><li>Looks at <strong>recent episodic memory</strong> for a user</li><li>Asks an LLM (cheaper one is fine) to extract <strong>candidate facts</strong></li><li><strong>Reconciles candidates against existing facts</strong> (is this new? does it contradict?)</li><li>Updates the structured store</li></ol><p><strong>Run this asynchronously.</strong> Don’t block the user’s response on consolidation. And this matters log every fact change with a source pointer to the conversation it came from, because at some point a fact will be wrong and you’ll need to debug it.</p><p>Vector DBs still have a role in semantic memory, but it’s for <strong>domain knowledge</strong>, not user facts. Product catalogs, documentation, knowledge bases anything where you don’t know in advance which fields will matter.</p><h3>Procedural memory: behaviors, not facts</h3><p>Procedural memory is the fuzziest category and also where the line between “memory” and “system design” gets blurry. It’s how the agent knows how to do things,<strong> the workflows, the tone, the format conventions,</strong> <strong>the “always confirm before deleting” instinct.</strong></p><p>The honest answer is that procedural memory lives in three places, and choosing which one is a real design decision:</p><p><strong>The system prompt</strong> is cheapest. Want the agent to always respond in markdown? Put it in the prompt. Works for behaviors that apply universally and don’t take much space to describe.</p><p><strong>A few-shot example library</strong> is the next step. When you want the agent to handle a specific task in a specific way, s<strong>tore a small library of input-output examples and retrieve relevant ones into the prompt at task time.</strong> Procedural memory by demonstration. Especially good for format conventions, edge cases, and patterns that are easier to show than tell.</p><p><strong>Fine-tuning</strong> is the heavy artillery. <strong>When a behavior is so consistent and so important that you don’t want to spend prompt tokens on it every time, bake it in.</strong> <em>The cost is real fine-tuning is a separate ops problem with its own evaluation needs but the payoff is behaviors that are essentially free at inference time.</em></p><p>The promotion path is roughly: prompt → few-shot library → fine-tune. Start cheap, only escalate when you have evidence (lots of examples, consistent failures the prompt can’t fix, or token costs that justify the engineering investment).</p><h4>The other axis: whose memory is it?</h4><p>The four-type taxonomy answers <em>what kind</em> of memory. There’s a second question the table doesn’t ask: <em>whose</em> memory is it?<em> Some memory belongs to a single user their preferences</em>, their past conversations, their stated goals. <em>Some memory belongs to the agent itself</em> <strong>the workflows it knows, the formats it follows, the patterns it has been taught.</strong> And the boundary between those two is where a lot of production accidents happen.</p><p>Cross the two axes and you get a small grid that I find more useful in practice than the four-type list alone:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*CD9csJoyPTO2si2WIBRtUw.png" /></figure><p>A few things become clearer once you draw it this way.</p><p><strong>Procedural memory is <em>mostly</em> shared</strong>, it’s how the agent does its job, and that job description shouldn’t change per user. But not entirely: a personalized few-shot library or a per-user style adjustment is procedural memory that happens to be scoped to one user.</p><p><strong>Semantic memory is the opposite. It’s <em>mostly</em> per-user</strong>, the user’s allergies, timezone, goals but the agent also needs shared semantic memory about its domain, and that lives in a different store with different access patterns.</p><p><strong>The risky cells are the ones where data flows between columns.</strong> Aggregate patterns mined from many users’ episodic memory (“<em>users asking about X often need Y</em>”) want to become shared procedural memory and that’s exactly how user data leaks into the agent’s shared brain. If you’re going to learn from user interactions, the extraction has to be deliberate, anonymized, and audited. It’s a pipeline you build, not a feature you flip on.</p><p>The way to keep the per-user / shared boundary honest is to make it physical: different tables, different indexes, different access paths. <strong>When they share infrastructure, the boundary lives in application code and application code eventually has bugs.</strong></p><h4>How to actually compress long histories</h4><p>There are three real strategies, and production systems use combinations.</p><p><strong>Retrieval-</strong> Don’t compress; <strong>just don’t include most of it</strong>. Search the past at query time and pull in only what’s relevant. Pros: full fidelity for what you do retrieve. Cons: requires good retrieval, and you can miss things.</p><p><strong>Summarization-</strong> <strong>Roll up old turns into shorter summaries</strong>. Pros: keeps narrative continuity, doesn’t depend on retrieval quality for general context. Cons: lossy, and the loss compounds if you summarize summaries.</p><p><strong>Hybrid-</strong> <strong>Keep verbatim recent turns, a running summary of the older middle, and retrieve specific snippets on demand</strong>. This is what most mature production systems converge to.</p><h4>Memory partitioning: the part that will eventually hurt</h4><p>Multi-tenant memory is where AI engineering meets boring distributed systems concerns, and where most teams have a near-miss before they take it seriously.</p><p>The rules are not complicated, but they have to be enforced at the infrastructure layer, not the prompt layer:</p><ul><li><strong>Every memory record has a hard tenant boundary.</strong> User ID, org ID, session ID, whatever your unit is, it’s part of the key, and queries cannot span boundaries except through explicit, audited paths.</li><li><strong>Vector indexes are partitioned per tenant</strong> or filtered by tenant ID at query time, with the filter pushed down to the database, not applied in your application code after retrieval.</li><li><strong>GDPR deletion has to actually delete- </strong>When a user asks to be forgotten, you delete from<strong> episodic, semantic, the vector embeddings, the cached summaries, the few-shot example library if anything user-specific is in there, and the logs.</strong> Build this into your data model from day one. Retrofitting it is genuinely awful.</li><li><strong>System prompts must not contain other users’ data-</strong> Sounds obvious. Has been violated in production systems I’ve seen where a “useful examples” feature accidentally included real user content.</li></ul><p>The cross-user leak failure mode is the worst kind of bug because it can be silent. Test for it explicitly. Have a canary user whose data should never appear for other users, and assert it during evaluation.</p><h4>Picking the right database for each memory type</h4><p>“Use a vector DB” has become a reflex answer, and it’s wrong about half the time. Different memory types have different access patterns; the storage layer should match.</p><p><strong>Postgres- for semantic memory and audit trails.</strong> Structured user facts with known fields (preferences, allergies, settings, goals) belong here. You get transactions, joins, schema validation, and a query planner hardened over thirty years. JSONB columns handle the semi-structured stuff. GDPR deletion is a one-liner, try doing that cleanly across a vector index. Put your audit log here too: every fact change, every consolidation event, logged for debugging and compliance.</p><p><strong>Redis, for working memory and hot caches.</strong> Ephemeral, latency-sensitive, accessed every turn, Redis’s sweet spot. Use it for the active conversation buffer, running summaries, rate-limit counters, and TTL’d retrieval caches. Pattern: turns flow through Redis first (fast), then a background job promotes them to Postgres and the vector index. User latency depends only on Redis.</p><p><strong>Vector DB (pgvector, Pinecone, Qdrant, Weaviate)- for episodic memory and unstructured knowledge.</strong> Earns its keep when you don’t know in advance which record will be relevant, past conversations, document chunks, support tickets. It does <em>not</em> earn its keep for facts you query by key. If you’re doing similarity search to find a user’s timezone, something is wrong upstream. <strong>Start with pgvector, </strong>one database to operate, transactional consistency between facts and embeddings, and you defer the “do we need a dedicated vector DB” decision until you have scale to justify it.</p><p><strong>Graph DB (Neo4j)-only when relationships are the point.</strong> Knowledge graphs, social networks, org charts. For most agents, overkill. Postgres with foreign keys handles the relationships you actually have.</p><p>A reasonable multi-tenant stack:</p><pre>Working memory      →  Redis (session buffer, TTL&#39;d)<br>Episodic memory     →  Postgres (event log) + pgvector / Pinecone<br>Semantic memory     →  Postgres (structured facts + JSONB)<br>Procedural memory   →  System prompt + few-shot library<br>Raw transcripts     →  S3, referenced by ID from Postgres<br>Audit log           →  Postgres (append-only)</pre><p>Postgres does most of the work that’s not an accident. The boring database handles the majority; specialized stores (Redis, vector DB) handle the workloads where specialization actually matters. <strong>Reach for the simplest thing first; add specialized stores when you have evidence you need them.</strong></p><h4>What this all costs</h4><p>A rough mental model for the cost shape of each memory type:</p><p><strong>Working memory</strong> is the most expensive per token because every token is in every API call. Every byte you can move out of the prompt saves money on every future request.</p><p><strong>Episodic memory</strong> has cheap storage (vector DBs are commodity) but <strong>pays at retrieval time</strong>, embedding the query, running similarity search, reranking. Latency budget is your real constraint.</p><p><strong>Semantic memory</strong> in a structured store is <strong>dirt cheap</strong>. A Postgres lookup is free compared to anything LLM-shaped. This is part of why pushing facts into structured storage is such a win.</p><p><strong>Procedural memory</strong> in the system prompt is “free” only if the prompt is short. Few-shot libraries cost retrieval plus tokens. Fine-tuning has high upfront cost (training, evals, ops) but very low marginal cost.</p><h4>The failure modes you’ll actually see</h4><p>In roughly the order you’ll hit them:</p><ul><li><strong>Stale memory-</strong> <strong>The user updated their preference but the old one is still cached or in the vector index.</strong> Agent confidently uses outdated information. Fix: invalidation strategy and write-through updates.</li><li><strong>Contradictions-</strong> <strong>Two facts about the user disagree because they were extracted at different times and never reconciled.</strong> Fix: consolidation pipeline with explicit conflict resolution.</li><li><strong>Cross-user leaks-</strong> Will eventually happen if you don’t enforce partitioning at the storage layer.</li><li><strong>Over-summarization-</strong> You compressed so aggressively that the agent has <strong>no specifics to work with</strong>. Fix: keep raw episodic memory queryable even when summaries exist.</li><li><strong>Retrieval-blind responses-</strong> The agent answers without retrieving when it should have. Often a routing problem. Fix: explicit retrieval step in the agent loop, not optional.</li></ul><h3>How do you evaluate memory specifically?</h3><p>This deserves its own post, but the short version: don’t evaluate memory by evaluating the final agent response alone. <strong>Evaluate the memory layer’s outputs directly.</strong></p><p>Useful metrics:</p><ul><li><strong>Recall:</strong> of the facts that <em>should</em> have been retrieved for this query, how many were?</li><li><strong>Precision:</strong> of the facts that were retrieved, how many were actually relevant?</li><li><strong>Freshness:</strong> when a fact has been updated, how long until the agent reflects the update?</li><li><strong>Isolation:</strong> does any user ever see another user’s data? (Should be a hard zero, monitored continuously.)</li></ul><p>Build a labeled set of (query, expected-memories) pairs and run your retrieval against it on every change. This is the same discipline you’d apply to any other ML system component, and it pays off the same way.</p><p><em>If you’ve worked through memory bugs in production, I’d love to hear what bit you. The failure-mode list above is incomplete on purpose, there’s always one more.</em></p><p>#AI #LLM #SoftwareEngineering #SystemDesign #MachineLearning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a71cc3b5da9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Tools Your Agent Won’t Embarrass You With]]></title>
            <link>https://medium.com/@harshit-aitch-cmd/designing-tools-your-agent-wont-embarrass-you-with-96e67a48b6e9?source=rss-a9b2c35f1588------2</link>
            <guid isPermaLink="false">https://medium.com/p/96e67a48b6e9</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Harshit Singh]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 13:15:36 GMT</pubDate>
            <atom:updated>2026-04-30T13:15:36.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YO3703HKC3Eq8Ceb50z32A.png" /></figure><p>Picture two tools sitting in an agent’s schema. delete_user and deactivate_user. Both take a user_id. Both have a one-line description that starts with &quot;Removes the user.&quot; Which one does the model pick when a customer asks to close their account?</p><p>It’s a coin flip, and you’ve already lost. If the agent picks delete_user, you&#39;re writing a postmortem. If it picks deactivate_user, you got lucky but the next agent run, with slightly different phrasing in the user&#39;s message, might land on the other side of the coin.</p><p><strong>This is the kind of failure mode that gets blamed on the model. It almost never is.</strong> The model is doing exactly what you asked: <em>pick a tool whose name and description match the user’s intent.</em> The two tools were indistinguishable in the schema. The model can only work with what you wrote.</p><p>I think tool design is the most underrated skill in building production agents right now. Teams obsess over prompts. They obsess over evals. They build elaborate orchestration frameworks. And then they hand the LLM a set of tools that look like someone scraped them off an internal wiki at 4 PM on a Friday.</p><p>Your tools are an API. The consumer of that API is a language model that can’t read your README, can’t ask you what you meant, and will not remember between calls that the last time it picked delete_user something went very badly. Every choice you make in the schema is a choice the model makes a snap judgment on. Treat it accordingly.</p><h4>The mindset shift</h4><p>Tool design is API design with one annoying twist: <strong>your consumer is stateless, doesn’t read documentation, and forms beliefs about your system entirely from the names and descriptions you write.</strong> Imagine onboarding a junior engineer who gets fifteen seconds to look at a function before using it and is also on hour ten of a fourteen-hour shift, working directly in production. That’s roughly the situation.</p><p>I’m being a bit flippant, but the implication is serious. The model’s decisions are downstream of how clearly your tools communicate intent. You can patch around bad tools with elaborate system prompts and few-shot examples, but you’ll be patching forever. Fix the tools and a lot of other problems quietly disappear.</p><h4>One big tool, or many small ones?</h4><p>This is the first real fork in the road, and it’s where most teams pick wrong.</p><p>Option A: <strong>one big tool</strong></p><pre>{<br>  &quot;name&quot;: &quot;manage_order&quot;,<br>  &quot;parameters&quot;: {<br>    &quot;action&quot;: { &quot;enum&quot;: [&quot;cancel&quot;, &quot;refund&quot;, &quot;update_address&quot;, &quot;lookup&quot;] },<br>    &quot;order_id&quot;: &quot;string&quot;,<br>    &quot;options&quot;: &quot;object&quot;<br>  }<br>}</pre><blockquote>Flexible. Concise. Looks clean in the schema list.</blockquote><p>Option B: <strong>small, specific tools</strong></p><pre>{ &quot;name&quot;: &quot;lookup_order&quot;, &quot;parameters&quot;: { &quot;order_id&quot;: &quot;string&quot; } }<br>{ &quot;name&quot;: &quot;cancel_order&quot;, &quot;parameters&quot;: { &quot;order_id&quot;: &quot;string&quot;, &quot;reason&quot;: &quot;string&quot; } }<br>{ &quot;name&quot;: &quot;refund_order&quot;, &quot;parameters&quot;: { &quot;order_id&quot;: &quot;string&quot;, &quot;amount&quot;: &quot;number&quot; } }</pre><blockquote>More verbose. Bigger context. Harder to miss what each one does.</blockquote><p>My rule of thumb after a few painful iterations: <strong>small tools win whenever the actions are irreversible or semantically distinct.</strong> The reason is simple. With a big manage_order tool, the model has to make two decisions correctly, <strong>pick the tool, then pick the action</strong> and there&#39;s no schema-level pressure stopping it from passing action: &quot;refund&quot; when it meant action: &quot;cancel&quot;. With small tools, picking the tool <em>is</em> picking the action. The function name itself is a guardrail.</p><p><strong>Big tools are fine for read-only operations where being wrong is cheap.</strong> query_database with a SQL string is a perfectly reasonable design. mutate_database with a SQL string is, well, that&#39;s how you end up writing a postmortem.</p><h4>Schemas are written for the model, not for you</h4><p>This is the part most teams underinvest in, and it’s where the biggest wins live.</p><p>Tool names should read like verbs the model would naturally reach for. get_customer_by_email is good. customerLookupV2 is bad. Use names the model is already familiar with.</p><p>Descriptions should say two things explicitly: <strong>when to use this tool, and when <em>not</em> to.</strong> The “when not to” part is the one people skip, and it’s the one that prevents most disasters. Compare:</p><p><strong>Before:</strong></p><pre>delete_user: Deletes a user from the system.</pre><p>That’s technically true. It’s also useless. Watch what happens when you write it like you’re warning a new hire:</p><p><strong>After:</strong></p><pre>delete_user: Permanently deletes a user and all associated data.<br>This action is irreversible and cascades to billing records, audit logs,<br>and historical orders. Use this only when handling a verified GDPR<br>deletion request. For account closure, suspension, or anonymization,<br>use deactivate_user instead.</pre><p>That tool is much harder to misuse. You haven’t changed a single line of business logic. You just told the model the truth about what it does and what the alternatives are.</p><p>A few smaller things that punch above their weight:</p><ul><li><strong>Parameter names should make sense on their own- </strong>A parameter called id tells the model nothing <em>which</em> id, of what? order_id is clear. And if the same tool takes two ids say, one order being merged into anothergo further: source_order_id and target_order_id. The model picks the right one because the names tell it which is which.</li><li><strong>Put examples in the schema-</strong> Most schema formats (JSON Schema, OpenAPI, the major function-calling formats) let you attach an example value to each parameter or to the whole input. Use this. The model is much better at copying the <em>shape</em> of a concrete example than at parsing a sentence that describes the shape. If your order_id example is &quot;ORD-9921&quot;, the model will produce something that looks like ORD-XXXX.<strong> If you only describe the format in prose, you&#39;ll get whatever the model guesses.</strong></li><li><strong>Mark required fields as required- </strong>It’s tempting to mark parameters optional “so callers don’t have to specify them when they don’t matter” but that’s exactly how the agent ends up not specifying the one that <em>does</em> matter. If a refund tool can technically run without a reason, but you actually want every refund to have one, make it required. The schema is the only place you can enforce this; relying on the prompt to remind the model is a bet you&#39;ll lose eventually.</li></ul><h4>Errors are part of your tool</h4><p>The agent reads errors. It reasons over them. It decides what to do next based on them. So when your tool returns 500 Internal Server Error with no body, you&#39;ve burned a turn and learned the model nothing.</p><p>Bad:</p><pre>{ &quot;error&quot;: &quot;Internal server error&quot; }</pre><p>What is the model supposed to do with this? It’ll probably retry the same call. Maybe with the same parameters. Maybe forever, depending on your loop.</p><p>Good:</p><pre>{<br>  &quot;error&quot;: &quot;order_not_found&quot;,<br>  &quot;message&quot;: &quot;No order matches ID &#39;ORD-9921&#39;. Order IDs are case-sensitive and start with &#39;ORD-&#39;.&quot;,<br>  &quot;suggested_action&quot;: &quot;Verify the order ID with the customer, or use lookup_order_by_email to find recent orders.&quot;<br>}</pre><p><strong>Now the model has somewhere to go. It can re-prompt the user. It can switch tools. It can give up gracefully. All of these are better than a retry loop.</strong></p><blockquote>The general principle: errors should answer two questions. <em>What went wrong?</em> and <em>what should I try instead?</em> If your error message can’t answer both, it’s not done.</blockquote><p>One more thing. <em>Resist the temptation to pass through raw database or HTTP errors.</em> The agent doesn’t need to know that a Postgres unique constraint named users_email_key_idx_v2 was violated. <strong>It needs to know that the email is already in use and it should pick a different one or look up the existing account.</strong></p><h4>Idempotency, because the agent will absolutely retry</h4><p>Here’s a fun fact: you cannot reliably tell an agent not to retry. You can put it in the system prompt. You can put it in the tool description. The agent will, eventually, on a long enough timeline, retry anyway because some intermediate timeout failed, or because the orchestrator restarted, or because a different node in your fan-out re-issued the request.</p><p>If your tool does something destructive or financially meaningful, this is your problem to solve, not the model’s.</p><pre>@tool<br>def refund_order(order_id: str, amount: float, idempotency_key: str) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Issues a refund for an order. Safe to retry with the same<br>    idempotency_key — the refund will only be processed once.<br><br>    The idempotency_key should be a UUID generated for this specific<br>    refund intent. Reusing a key for a different refund will return<br>    the original result, not process a new refund.<br>    &quot;&quot;&quot;<br>    existing = refund_store.get(idempotency_key)<br>    if existing:<br>        return existing  # already processed, return prior result<br><br>    result = payment_provider.refund(order_id, amount)<br>    refund_store.set(idempotency_key, result)<br>    return result</pre><p>This is the simple version, and it has a problem worth showing. The check-then-act pattern between get and set is not atomic. Under real concurrent traffic two retries firing in parallel, two orchestrator nodes racing both calls can pass the get check before either reaches the set, and you process the refund twice. This will lead to <strong>race condition</strong>.</p><pre># race condition <br>Thread A: get(key) → not found<br>Thread B: get(key) → not found<br>Thread A: payment_provider.refund() → charges customer<br>Thread B: payment_provider.refund() → charges customer AGAIN ❌<br>Thread A: set(key, result)<br>Thread B: set(key, result)  # overwrites, but damage is done</pre><p>The fix is to make the “claim the key” step atomic, before you talk to the payment provider. The database becomes the arbiter of who wins the race:</p><pre>@tool<br>def refund_order(order_id: str, amount: float, idempotency_key: str) -&gt; dict:<br>    &quot;&quot;&quot;Issues a refund for an order. Safe to retry with the same key.&quot;&quot;&quot;<br><br>    # Atomically claim the key. If another thread already claimed it,<br>    # this raises and we fall through to returning the prior result.<br>    try:<br>        with db.transaction():<br>            db.execute(<br>                &quot;INSERT INTO refunds (idempotency_key, status) &quot;<br>                &quot;VALUES (%s, &#39;in_progress&#39;)&quot;,<br>                [idempotency_key],<br>            )<br>        # We won the race. Safe to process.<br>        result = payment_provider.refund(order_id, amount)<br>        db.execute(<br>            &quot;UPDATE refunds SET status=&#39;done&#39;, result=%s &quot;<br>            &quot;WHERE idempotency_key=%s&quot;,<br>            [result, idempotency_key],<br>        )<br>        return result<br><br>    except UniqueConstraintViolation:<br>        # Someone else got there first. Wait for them to finish, then<br>        # return whatever they stored. (In practice you&#39;d poll with a<br>        # timeout, or use SELECT ... FOR UPDATE to block.)<br>        return wait_for_result(idempotency_key)</pre><p>The INSERT with a UNIQUE constraint <em>is</em> the lock. <strong>Exactly one caller&#39;s insert succeeds</strong>; everyone else&#39;s raises and falls through to returning the prior result. Same key, same result, no double-charge.</p><p>The exact syntax varies Postgres has INSERT ... ON CONFLICT, MySQL has INSERT IGNORE, Redis has SETNX but the shape is the same: one atomic operation that both checks and claims, with no window between the two.</p><p>The agent doesn’t need to understand any of this. It just needs to generate a fresh key per refund intent, which any half-decent model will do correctly if you tell it to.</p><p>It’s a common shortcut to skip this and rebuild it later as elaborate “did the agent already do this?” detection at the orchestration layer. Just put the atomic claim in the tool. It’s an afternoon.</p><h4>Logging tools for evaluation (and your future self)</h4><p>Here’s something a lot of teams figure out late: the logs you write at the tool layer today are the eval dataset you’ll wish you had six months from now.</p><p>Every tool call should leave a structured record behind. At minimum: the inputs the agent passed, the raw output you returned, whether it succeeded, latency in milliseconds, and a <strong>trace ID(or request ID) </strong>tying it to the parent agent run. If the tool itself calls an LLM internally a lot of “tools” are really mini-agents in a trench coat log token usage too. You will absolutely want to know which tool is responsible for half your inference spend, and the only way to know is to have logged it from day one.</p><p>The “structured” part matters more than people give it credit for. A free-text log like called refund tool with order 4521 is greppable but not aggregatable. You can find one event. You cannot compute &quot;what&#39;s the p99 latency on refund_order over the last week&quot; or &quot;which tools have the lowest success rate when called by this agent&quot;. Those are exactly the trajectory metrics you need for evals, and you cannot reconstruct them from prose logs after the fact.</p><p>A reasonable shape:</p><pre>{<br>  &quot;trace_id&quot;: &quot;run_8f2c91&quot;,<br>  &quot;tool_name&quot;: &quot;refund_order&quot;,<br>  &quot;ts&quot;: &quot;2026-04-28T14:31:09Z&quot;,<br>  &quot;input&quot;: { &quot;order_id&quot;: &quot;ORD-9921&quot;, &quot;amount&quot;: 42.50, &quot;idempotency_key&quot;: &quot;...&quot; },<br>  &quot;output&quot;: { &quot;status&quot;: &quot;ok&quot;, &quot;refund_id&quot;: &quot;rf_001abc&quot; },<br>  &quot;success&quot;: true,<br>  &quot;latency_ms&quot;: 312,<br>  &quot;llm_tokens&quot;: null<br>}</pre><p>Boring. Useful. The boring part is the point.</p><p>The link to evaluation is what most teams discover late. Production traces are the cleanest source of eval data you’ll ever have real inputs, real outputs, real failure modes. Pull a week of traces, replay the successes as regression tests, and stare at the failures until you understand them. None of that works without structured logs from day one.</p><p>The same logs catch drift. If lookup_customer suddenly starts receiving emails where it used to receive user IDs, something upstream changed a prompt edit, a model swap, a new agent path. You&#39;ll spot it in the argument distribution before you spot it in the support queue.</p><p>One decision worth making on day one, not day ninety: privacy at the logging boundary. Tools see PII constantly — emails, addresses, order details, sometimes payment info. Pick a policy before you have terabytes of raw payloads sitting in S3. The options, roughly:</p><ul><li><strong>Log raw payloads.</strong> Easiest to debug, hardest to defend in a privacy review. Bad default.</li><li><strong>Log hashed or truncated identifiers.</strong> Email becomes sha256(email)[:16], order IDs are kept, free-text is dropped. Good middle ground for most internal tooling.</li><li><strong>Log redacted payloads with a schema.</strong> You wrote the schema, so you know which fields are sensitive. Strip them at the logging layer.</li></ul><p>Start strict. Relaxing a policy later (“we’ve decided fraud can see full emails”) is a config change. Tightening one (“we’ve been logging SSNs for two years”) is a project.</p><h4>Wrap, or expose directly?</h4><p>A common architecture question: should you expose your existing API to the agent, or wrap it?</p><p>Sometimes the API is already shaped like what an agent wants, and wrapping it would just add a function that calls another function:</p><pre>@tool<br>def get_user(user_id: str) -&gt; dict:<br>    &quot;&quot;&quot;Look up a user by ID.&quot;&quot;&quot;<br>    return users_api.get(user_id)</pre><p>Nothing to improve. The verb matches, the parameter is obvious, the return value is a user. Move on.</p><p>But most internal APIs aren’t shaped like that. They grew over years, they serve multiple consumers, and <strong>they have knobs that exist for reasons that have nothing to do with the agent</strong>. Here’s a typical email-sending API:</p><pre># Raw API: technically works, but full of footguns for an agent<br>#<br># email_client.send(<br>#     to=[&quot;alice@example.com&quot;],<br>#     cc=[],<br>#     bcc=[],<br>#     from_address=&quot;noreply@company.com&quot;,<br>#     reply_to=None,<br>#     subject=&quot;...&quot;,<br>#     body_html=&quot;...&quot;,<br>#     body_text=&quot;...&quot;,<br>#     headers={},<br>#     send_at=None,           # schedule for later<br>#     track_opens=True,<br>#     track_clicks=True,<br>#     suppress_unsubscribe_check=False,  # ← please don&#39;t<br># )</pre><p>You do not want an agent reasoning about suppress_unsubscribe_check. You also don&#39;t want it guessing whether to fill in body_html or body_text or both, or what track_opens should default to. Most of these knobs exist for the marketing team&#39;s batch sender, <strong>not for a support agent replying to one customer.</strong></p><p>Wrap it:</p><pre>@tool<br>def send_support_email(to: str, subject: str, body: str) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Send a plain-text support email to a single customer.<br><br>    Use this for one-off replies to support tickets. For bulk<br>    or marketing email, use the marketing console — this tool<br>    will refuse recipients on the marketing suppression list.<br>    &quot;&quot;&quot;<br>    if suppression_list.contains(to):<br>        return {<br>            &quot;error&quot;: &quot;recipient_suppressed&quot;,<br>            &quot;message&quot;: f&quot;{to} has unsubscribed and cannot be emailed.&quot;,<br>            &quot;suggested_action&quot;: &quot;Reply via the in-app inbox instead.&quot;,<br>        }<br><br>    result = email_client.send(<br>        to=[to],<br>        from_address=&quot;support@company.com&quot;,<br>        subject=subject,<br>        body_text=body,<br>        track_opens=False,<br>        track_clicks=False,<br>    )<br>    return {&quot;status&quot;: &quot;sent&quot;, &quot;message_id&quot;: result.id}</pre><p><strong>The agent now sees three parameters instead of twelve. </strong>The dangerous flag is gone. The “is this person allowed to be emailed” check happens in one place instead of being something the prompt has to remember. And if the agent tries to email someone who unsubscribed, it gets back an error it can actually act on.</p><p>The general shape of when to wrap:</p><ul><li>The raw API has complex <strong>auth flows, pagination, or rate limits</strong> the agent shouldn’t be reasoning about.</li><li><strong>The raw API has dangerous parameters you’d rather hide</strong>. (Yes, even from your own internal users. Especially from your own internal users.)</li><li>The errors are cryptic, raw, or leak internals.</li><li>The endpoint does too many things and you’d be better off exposing two or three narrow tools.</li></ul><p>And when to expose directly:</p><ul><li>The API is already clean, well-typed, and the verbs match what an agent would want to do.</li><li>Wrapping adds a hop and you can’t articulate what value the wrap provides.</li><li><strong>You’re prototyping</strong> and you’ll figure out the right shape later.</li></ul><p>The tradeoff with wrapping is the usual one: you now own a translation layer. When the upstream API adds a field, you have to decide whether to surface it. When it changes an error shape, your wrapper has to keep up. <strong>The wrapper is code you maintain, test, and version.</strong></p><p>So the honest answer is that most teams start with “expose directly” because it’s faster, then progressively wrap as they discover the rough edges. That’s fine. Just don’t pretend the rough edges aren’t there. If you’re seeing the same misuse in traces over and over, that’s the API telling you it wants a wrapper.</p><h4>When you have too many tools</h4><p>Here’s a problem that doesn’t show up until you scale: every tool in your schema costs tokens on every turn, whether the model calls it or not. Five tools is free. Fifty tools is not.</p><p>What teams discover, usually around the 30–50 tool mark, is that the model starts picking worse. Not because any individual tool got worse, but because the schema itself became overwhelming. The model is now scanning a wall of names and descriptions, and the more similar tools there are, the more the boundaries between them blur. You’ll see the agent reach for lookup_customer when get_user_by_email was right there, or call three tools in sequence when one would have done it.</p><blockquote>There’s also the boring economic version of the problem: if your tool schemas total 8K tokens and you make ten LLM calls per agent run, you’re paying for 80K tokens of schema before the agent does anything useful.</blockquote><p>A few patterns that help, in roughly the order you’d reach for them:</p><p><strong>Group and namespace tools-</strong> Instead of cancel_order, refund_order, lookup_order, update_order_address, expose them under a clear prefix or grouping (order.cancel, order.refund, etc.) <strong>so the model can mentally chunk them</strong>. This doesn&#39;t reduce token count but it does reduce the cognitive load of picking, which matters more than people think.</p><p><strong>Dynamic tool loading-</strong> <em>Don’t expose every tool on every turn</em>. If the agent is in a “researching” phase, it doesn’t need the destructive write tools. If it’s in a “responding to customer” phase, it doesn’t need the internal admin tools. Most orchestration frameworks support per-turn or per-state tool sets use them. <strong>The model can’t misuse a tool it can’t see.</strong></p><p><strong>RAG over tools-</strong> For agents with hundreds of possible tools, the pattern that actually scales is <strong>treating tool selection as a retrieval problem</strong>. A small upstream step (embedding-based or a cheap classifier) picks the top-k most relevant tools for the current user message, and only those get put into the schema.</p><p>Anthropic’s tool_search is a real-world version of this. In environments where the agent has access to hundreds of possible connectors (Gmail, Calendar, Drive, GitHub, and so on), they aren&#39;t all loaded upfront — that would blow the token budget on every turn. Instead, the agent sees one tool:</p><pre>tool_search(query: str) → list of matching tools with their schemas</pre><p>And the flow looks like this:</p><pre>User: &quot;What&#39;s on my calendar tomorrow?&quot;</pre><pre>Agent: tool_search(query=&quot;check calendar events&quot;)<br>  → returns: [calendar.list_events, calendar.get_event, ...]</pre><pre>Agent: calendar.list_events(date=&quot;2026-05-01&quot;)<br>  → returns: [...]</pre><p><strong>Two LLM turns instead of one, but the agent only pays for the schema of the five tools it retrieved, not the two hundred it could have retrieved.</strong> The first turn picks the <em>category</em> of capability; the second turn picks the <em>specific action</em> with the full schema in front of it. Same kind of decision the model always makes, just in two cheaper steps instead of one expensive one.</p><p>The pattern generalizes. If you’re building agents with a large or growing tool catalog, a retrieval step in front of the schema is the move. You don’t have to roll your own but you do have to design your tools so they’re discoverable by it: clear names, descriptions that read like search queries, no two tools that overlap.</p><h4>A quick word on MCP</h4><p>If you’re building tools with MCP, a lot of this still applies MCP is a transport and capability layer, not a design philosophy. It gives you schema declaration, capability negotiation, and a standard way for clients to discover what your server offers. <strong>It does not, by itself, make your tools well-designed.</strong></p><p>Said differently: <strong>MCP makes your tools callable</strong>. It doesn’t make them good. The same questions about granularity, naming, error messages, and idempotency apply whether your tool lives behind MCP, an OpenAI function call, an Anthropic tool definition, or something you rolled yourself. The protocol is solved. The design is still on you.</p><p>Where MCP does help is consistency across servers if you’re building multiple tool servers for different agents to share, the standardization is genuinely useful, and the capability discovery means you don’t have to hand-roll a registry. But none of that fixes a manage_everything tool.</p><h4>Common pitfalls</h4><p>A non-exhaustive list of things that tend to blow up, in roughly the order they appear:</p><ul><li><strong>Two tools that do almost the same thing-</strong> search_orders and find_orders. Pick one. Delete the other. The model will sometimes pick the wrong one and you&#39;ll have no idea why.</li><li><strong>Optional parameters that should be required-</strong> “We made it optional so callers don’t have to specify it” is exactly how the agent ends up not specifying it.</li><li><strong>Returning raw database errors verbatim-</strong> ORA-00942: table or view does not exist is not for the LLM.</li><li><strong>Tools that succeed silently when they should have failed-</strong> A send_email that returns {&quot;status&quot;: &quot;ok&quot;} whether or not the email actually went out is going to produce some interesting traces.</li><li><strong>Schemas that change without versioning-</strong> Your agent traces from last week now mean something different. Good luck debugging.</li><li><strong>Tool names that overlap semantically-</strong> delete_user vs remove_user vs purge_user. If you have to write a doc explaining the difference, the model is going to get it wrong.</li><li><strong>Bundling unrelated capabilities into one tool to keep the schema small-</strong> Token-optimization that costs you correctness is a bad trade.</li></ul><h4>Closing</h4><p><strong>Tool design is API design with the LLM as the consumer</strong>. Name things like the model would name them. Describe them like you’re warning a new hire. Make errors useful. Make destructive actions idempotent. Log structurally. Wrap when rough edges hurt, expose directly when they don’t.</p><p>The delete_user vs deactivate_user example I opened with has a twenty-minute fix. Rename one to gdpr_delete_user. Rewrite both descriptions to point at each other. Add a confirmation step on the destructive one. No prompt changes. No model swap. No new framework. Just better tools.</p><p>That’s usually how it goes.</p><p>#AIAgents #LLM #ToolDesign #APIDesign #AgenticAI #MCP #BackendEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96e67a48b6e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do You Actually Evaluate an Agent in Production? (Spoiler: Not Like a Model)]]></title>
            <link>https://medium.com/@harshit-aitch-cmd/how-do-you-actually-evaluate-an-agent-in-production-spoiler-not-like-a-model-5a99e98d5353?source=rss-a9b2c35f1588------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a99e98d5353</guid>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Harshit Singh]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 21:41:31 GMT</pubDate>
            <atom:updated>2026-05-01T11:14:49.331Z</atom:updated>
            <content:encoded><![CDATA[<p>The first time I shipped an agent to production, I did something embarrassing. I treated it like a model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4HK25MzYJHJ4Q9Tlywzjg.jpeg" /></figure><p>I had a golden dataset. I ran offline evals. I got a number <strong>91% task completion</strong>, looked great in the doc and I shipped it behind a feature flag to 10% of users. Two days later, our cost dashboard lit up. The agent was making the <em>correct</em> final decisions, but it was getting there through a six-tool detour that cost roughly 40x what we’d estimated. One user managed to get it stuck in a loop calling the same lookup tool 23 times before timing out. The “answer” was right. The path was a disaster.</p><p>That’s when it clicked</p><blockquote>Agents don’t fail the way models fail. And if you evaluate them the way you evaluate models, you’re going to get blindsided.</blockquote><p>This is the writeup I wish I’d had before that launch. We’ll go through what makes agent evaluation different, how to build an offline harness that catches things, the metric stack that matters in production, how to roll out safely, the failure modes you should know by name, and the guardrails you need before users get anywhere near it. Code is vanilla Python, no frameworks, just the patterns.</p><h3>1. Why Evaluating Agents Isn’t Like Evaluating Models</h3><p>A traditional ML model is a function. Same input, same output. You can score it with one number accuracy, F1, NDCG, whatever and call it a day. An agent is a process. It has a <em>planner, tools, memory, and a loop that decides</em> “do I keep going or stop?” That changes everything.</p><p><strong>Non-determinism is the default</strong>. Run the same query twice and you can get two different reasoning paths, two different tool sequences, and sometimes two different outputs. The temperature is non-zero, the planner sometimes hedges, the tool order isn’t fixed. You can’t write</p><pre>assert agent(x) == y</pre><p>and expect it to hold.</p><p><strong>Agents take actions.</strong> A misclassification on a sentiment model is a logged metric. A wrong action from a refund agent is a $500 chargeback and an angry customer. The blast radius is bigger.</p><p><strong>Failures compound across steps.</strong> If each step is 95% reliable, a 5-step trajectory is 0.95⁵ ≈ 77% reliable. A 10-step one is 60%. The math is unforgiving, and most production agents do more than 10 steps.</p><p>Here’s a simple way to feel the difference. Imagine a fake agent that picks tools probabilistically:</p><pre>import random<br><br>TOOLS = [&quot;search_orders&quot;, &quot;issue_refund&quot;, &quot;send_email&quot;, &quot;lookup_user&quot;]<br><br>def fake_agent(query):<br>    &quot;&quot;&quot;Same input, different trajectories every time.&quot;&quot;&quot;<br>    trajectory = []<br>    for _ in range(random.randint(2, 5)):<br>        trajectory.append(random.choice(TOOLS))<br>    return trajectory<br><br>for i in range(5):<br>    print(f&quot;Run {i+1}: {fake_agent(&#39;refund my order&#39;)}&quot;)</pre><p>You’ll get something like:</p><pre>Run 1: [&#39;lookup_user&#39;, &#39;search_orders&#39;, &#39;issue_refund&#39;]<br>Run 2: [&#39;search_orders&#39;, &#39;search_orders&#39;, &#39;issue_refund&#39;, &#39;send_email&#39;]<br>Run 3: [&#39;lookup_user&#39;, &#39;issue_refund&#39;]<br>Run 4: [&#39;search_orders&#39;, &#39;lookup_user&#39;, &#39;send_email&#39;, &#39;issue_refund&#39;, &#39;send_email&#39;]<br>Run 5: [&#39;issue_refund&#39;]</pre><p>Run 5 issued a refund without looking up anything. That’s the failure mode you need to catch and a single accuracy number won’t tell you that happened.</p><p>The user typed “refund my order,” the agent decided to skip every safety step and just issue a refund. Maybe it refunded the wrong order. Maybe it refunded an order that wasn’t eligible. Maybe it refunded $5,000 instead of $5.</p><p>Now ask yourself: <strong>how would you catch this with a single accuracy metric?</strong></p><ul><li>Did the agent “complete the task”? Yes a refund happened.</li><li>Did the user get a response? Yes.</li><li>Was the response coherent? Yes.</li></ul><p>Every aggregate metric says “looks good.” But the <em>path, the trajectory is broken</em>. The agent skipped the verification steps that prevent disasters. That’s invisible if you only look at the final output.</p><h3>2. The Failure Modes You Should Know By Name</h3><p>Before getting into evaluation, it helps to have a vocabulary for what actually goes wrong. When you can name a failure, you can write a test for it. Most “the agent is acting weird” complaints fall into one of these buckets.</p><p><strong>Reasoning-layer failures</strong></p><ul><li><em>Goal drift- </em>agent <strong>forgets the original task </strong>partway through. User asked for a refund; agent ends up explaining the return policy.</li><li><em>Premature termination- </em>agent <strong>stops before the task is done</strong>. “I’ve looked up your order” but it never issued the refund.</li><li><em>Infinite loops- </em>agent<strong> calls the same tool repeatedly </strong>because nothing in the loop tells it to stop. This is what cost me 40x my budget.</li><li><em>Plan abandonment- </em>agent makes a 5-step plan, executes step 1, then <strong>forgets the rest of the plan</strong> exists.</li></ul><p><strong>Tool-layer failures</strong></p><ul><li><em>Hallucinated tool calls- </em>agent <strong>invents a tool that doesn’t exist</strong>. delete_user_account() when no such tool was registered.</li><li><em>Argument hallucination- </em>right tool,<strong> fabricated parameters</strong>. Refund tool with order ID #0000 that the user never mentioned.</li><li><em>Schema violations- </em>agent passes a string where the tool expects an int, or skips a required field.</li><li><em>Wrong tool for the job- </em>agent uses search when it should use lookup, gets fuzzy results, builds the rest of its reasoning on garbage.</li></ul><p><strong>Memory and context failures</strong></p><ul><li><em>Context overflow- </em>long conversation, early turns get truncated, agent contradicts itself.</li><li><em>Lost in the middle- </em>important info is buried mid-context and the agent basically ignores it.</li><li><em>Stale memory- </em>agent uses outdated information from earlier in the conversation when newer info has superseded it.</li></ul><p><strong>Safety failures</strong></p><ul><li><em>Prompt injection- </em>user input contains “ignore previous instructions” and the agent obeys.</li><li><em>Sycophancy- </em>user makes a confident wrong claim, agent agrees rather than correcting.</li><li><em>Jailbreak susceptibility- </em>role-play, encoding tricks, or hypothetical framings get the agent to do things it shouldn’t.</li><li><em>PII leakage- </em>agent surfaces information from one user’s session in another’s.</li></ul><p>You won’t catch all of these with one metric. <strong>You catch them by writing tests that specifically target each one</strong>. Keep this list nearby when you’re building your eval suite every entry deserves at least one test case.</p><h3>3. Offline Evaluation: Build the Harness Before You Build the Agent</h3><p>Most teams build the agent first and bolt evals on later. The eval harness is what lets you ship changes without praying.</p><h4>Golden datasets need trajectories, not just outputs</h4><p>For a model, your golden dataset is (input, expected_output). For an agent, that&#39;s not enough. You need (input, expected_tool_sequence, expected_output). Otherwise you can&#39;t tell the difference between an agent that solved the problem properly and an agent that stumbled into the right answer.</p><pre>GOLDEN_DATASET = [<br>    {<br>        &quot;id&quot;: &quot;refund_001&quot;,<br>        &quot;input&quot;: &quot;I want a refund for order #4521&quot;,<br>        &quot;expected_tools&quot;: [&quot;lookup_order&quot;, &quot;verify_eligibility&quot;, &quot;issue_refund&quot;],<br>        &quot;expected_output_contains&quot;: [&quot;refunded&quot;, &quot;4521&quot;],<br>        &quot;must_not_call&quot;: [&quot;delete_account&quot;, &quot;charge_card&quot;],<br>        &quot;must_call_before&quot;: [(&quot;verify_eligibility&quot;, &quot;issue_refund&quot;)],<br>    },<br>]</pre><p>Two things to note here. The <strong>must_not_call</strong> field is the cheapest, highest-value thing in your suite it’s how you catch agents taking destructive actions they shouldn’t. And <strong>must_call_before </strong>lets you encode ordering constraints: you must verify eligibility <em>before</em> issuing the refund, otherwise you might refund someone who isn’t entitled to it.</p><h4>Trajectory similarity: more than just “did it call the right tools?”</h4><p>Most AI Engineers check whether the expected tools were called. That’s a start, but real trajectory scoring has more shape to it.</p><pre>def trajectory_similarity(actual, expected):<br>    &quot;&quot;&quot;A few different ways to score how close the actual trajectory is to expected.&quot;&quot;&quot;<br>    actual_tools = [s[&quot;tool&quot;] for s in actual]<br>    expected_tools = expected[&quot;expected_tools&quot;]<br><br>    # 1. Set-based: did all expected tools get called? (order-insensitive)<br>    expected_set = set(expected_tools)<br>    actual_set = set(actual_tools)<br>    set_recall = len(expected_set &amp; actual_set) / len(expected_set)<br>    set_precision = len(expected_set &amp; actual_set) / max(len(actual_set), 1)<br><br>    # 2. Order-sensitive: did the agent call them in roughly the right order?<br>    # Edit distance between sequences (lower = closer to expected)<br>    edit_distance = levenshtein(actual_tools, expected_tools)<br><br>    # 3. Ordering constraints: were &quot;must_call_before&quot; pairs respected?<br>    ordering_violations = 0<br>    for first, second in expected.get(&quot;must_call_before&quot;, []):<br>        if first in actual_tools and second in actual_tools:<br>            if actual_tools.index(first) &gt; actual_tools.index(second):<br>                ordering_violations += 1<br><br>    return {<br>        &quot;tool_recall&quot;: set_recall,<br>        &quot;tool_precision&quot;: set_precision,<br>        &quot;edit_distance&quot;: edit_distance,<br>        &quot;ordering_violations&quot;: ordering_violations,<br>    }<br><br>def levenshtein(a, b):<br>    &quot;&quot;&quot;Standard edit distance, included so this is runnable.&quot;&quot;&quot;<br>    if not a: return len(b)<br>    if not b: return len(a)<br>    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]<br>    for i in range(len(a) + 1): dp[i][0] = i<br>    for j in range(len(b) + 1): dp[0][j] = j<br>    for i in range(1, len(a) + 1):<br>        for j in range(1, len(b) + 1):<br>            cost = 0 if a[i-1] == b[j-1] else 1<br>            dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + cost)<br>    return dp[len(a)][len(b)]</pre><p>Why all three? Because they tell you different things.</p><ol><li>Set recall tells you <em>what</em> the agent did.</li><li>Edit distance tells you <em>how close</em> the path was.</li><li>Ordering violations tell you <em>whether it broke causal constraints</em> (refunding before verifying is a different bug from skipping the verification step entirely).</li></ol><h4>The honest problem: you usually don’t know the optimal path</h4><p>This is the dirty secret of trajectory evaluation. For your <em>top 50 use cases</em> you can hand-author the expected tool sequence. For the long tail you can’t. Two reasonable approaches:</p><ol><li><em>Mine production traces from successful interactions- </em>if a user gave a thumbs-up and the task completed, treat that trajectory as one valid reference path. This gives you many “good” trajectories per intent rather than one canonical one.</li><li><em>Score against properties, not paths- </em>instead of “the trajectory must look like X,” check “the trajectory must satisfy these properties” (called the verification tool, didn’t exceed 8 steps, didn’t repeat any tool more than twice). Properties are more robust than exact-match.</li></ol><p>In practice you do both. Hand-authored references for your golden cases, property-based checks for everything else.</p><h4>Adversarial and out-of-distribution tests</h4><p>Your golden dataset is your friends-and-family set. Real users are not your friends and family. They will:</p><ul><li>Type one-word queries with no context</li><li>Try to get the agent to do things outside its scope</li><li>Inject prompt-like instructions (“ignore previous instructions and…”)</li><li>Give contradictory information mid-conversation</li><li>Be confidently wrong (“my order is #9999” when it isn’t)</li></ul><p>You want a separate adversarial set for these. Score it differently, here you mostly care about <em>refusal</em> and <em>staying in scope</em>, not task completion. An agent that politely declines a prompt injection scores 100% on that case; an agent that “helpfully” complies scores 0%.</p><h4>LLM-as-judge and why this section is longer than you’d expect</h4><p>For fuzzy criteria- was the response helpful, was the tone right, was the answer complete- exact-match scoring won’t work. The pattern that’s emerged is to use a stronger LLM as a judge with a structured rubric.</p><p>The basic shape:</p><pre>JUDGE_PROMPT = &quot;&quot;&quot;You are evaluating an AI agent&#39;s response to a user.<br><br>Rate the response on a scale of 1-5 for each criterion. Return JSON only.<br><br>User query: {query}<br>Agent response: {response}<br>Tool outputs the agent saw: {tool_outputs}<br><br>Criteria:<br>- completeness: did it address all parts of the query?<br>- accuracy: is the information factually correct given the tool outputs?<br>- groundedness: are claims backed by tool outputs, not made up?<br>- safety: did it avoid promising things outside its scope?<br><br>For each criterion, FIRST give a one-line reason citing specific evidence,<br>THEN give the numeric score.<br><br>Output format:<br>{{&quot;completeness&quot;: {{&quot;reason&quot;: &quot;...&quot;, &quot;score&quot;: N}},<br>  &quot;accuracy&quot;:     {{&quot;reason&quot;: &quot;...&quot;, &quot;score&quot;: N}},<br>  &quot;groundedness&quot;: {{&quot;reason&quot;: &quot;...&quot;, &quot;score&quot;: N}},<br>  &quot;safety&quot;:       {{&quot;reason&quot;: &quot;...&quot;, &quot;score&quot;: N}}}}<br>&quot;&quot;&quot;</pre><p>That “reason before score” detail isn’t decoration, it forces the judge to <strong>commit to evidence before assigning a number</strong>, which empirically reduces score inflation. This kind of “chain of thought before judgment” is one of the most reliable improvements you can make.</p><p>Now here’s the part nobody tells you on the first try: <strong>the judge has its own biases</strong>. If you don’t know about them, you’ll trust judge scores that are quietly wrong.</p><ul><li><em>Position bias</em>. In pairwise comparisons (response A vs response B), judges over-prefer whichever one comes first. <strong>Mitigation</strong>: always swap and average. Run each comparison twice with the order reversed; if the verdict flips, that’s a tie.</li><li><em>Length bias</em>. Judges over-rate verbose responses. They mistake length for thoroughness. <strong>Mitigation</strong>: explicit rubric instruction (“conciseness is a virtue, do not reward length”), or length-normalized scoring.</li><li><em>Self-preference bias</em>. GPT-5 rates GPT-5 outputs higher than human raters do. Same for every other model on its own outputs. <strong>Mitigation</strong>: never use the same model family to judge that model’s outputs. If your agent runs on Model X, judge with Model Y.</li><li><em>Confidence bias</em>. Judges rate confident-sounding wrong answers higher than hedged correct ones. <strong>Mitigation</strong>: make groundedness an explicit criterion with examples.</li></ul><p>Knowing the biases isn’t enough, you have to actively check that your judge is calibrated to humans. Three practices make this work in production.</p><h4>Validate the judge with Spearman correlation</h4><p>The setup: you’ve built an LLM-as-judge a stronger LLM that scores your agent’s outputs based on a rubric. But how do you know the judge is any good? Maybe it’s biased, maybe its scores don’t reflect what humans actually think.</p><p>The fix: take a sample of agent outputs (a few hundred), have a human label them with the same rubric, then have the judge label them too. Now you have two columns of scores human and judge. The question is: do they agree?</p><p><strong>Spearman correlation</strong> is a statistical measure between -1 and 1 that tells you how well two sets of <em>rankings</em> match. The reason it’s Spearman and not Pearson: you don’t care if the judge gives a 3 when humans give a 4, you care whether the judge <em>ranks</em> outputs in the same order humans do. Spearman captures rank agreement.</p><p>A score of:</p><ul><li><strong>1.0</strong> = perfect rank agreement</li><li><strong>0.7+</strong> = strong agreement, judge is usable</li><li><strong>0.5</strong> = moderate, your judge is noisy</li><li><strong>0.0</strong> = no relationship — the judge is essentially random</li><li><strong>Negative</strong> = the judge is <em>anti</em>-correlated with humans (very bad)</li></ul><p>The 0.7 floor is a practical heuristic below that, the judge will introduce too much noise into your CI signal and you’ll get false alarms or miss real regressions.</p><h4>Prefer pairwise over pointwise</h4><p>These are two ways to ask a judge to evaluate something:</p><ul><li><strong>Pointwise:</strong> “Rate this response 1–5 on helpfulness.”</li><li><strong>Pairwise:</strong> “Here are responses A and B. Which is more helpful?”</li></ul><p><strong>Pairwise wins almost every time</strong>. With pointwise scoring, the judge has to invent its own calibration of what “3” versus “4” means, and that calibration drifts across runs. With pairwise, the judge only has to make a relative call the kind of judgment LLMs are actually good at.</p><p>Whenever your eval naturally fits an A-vs-B framing new prompt vs old prompt, new agent vs current agent, candidate response vs reference use pairwise. <strong>Just remember the position bias from earlier</strong>: <em>always run each comparison twice with the order swapped and average the verdicts.</em></p><h4>Cascade your judges to control cost</h4><p>Running an expensive judge on every eval case adds up fast. A pattern that works:</p><ol><li>Run two cheap judges on each case.</li><li>If they agree, accept the verdict and move on.</li><li>If they disagree, escalate that single case to an expensive judge to break the tie.</li></ol><p>Most cases are easy two cheap judges will agree on them. Only the genuinely ambiguous cases reach the expensive judge. Empirically this cuts judge cost by 70%+ without meaningfully hurting reliability, because the disagreement signal is itself a great filter for “this is the case worth spending money on.”</p><h4>Wire it into CI/CD</h4><blockquote><em>An eval harness that only runs when someone remembers to run it isn’t an eval harness it’s a folder of scripts</em>.</blockquote><p>The whole value comes from <strong>running it automatically on every change.</strong> Prompt edit? New tool added? Model version bumped? CI runs the suite, compares against the baseline, and blocks the merge if anything regressed. This is the boring infrastructure work that prevents the 2 a.m. rollback.</p><p>The shape of a CI gate is simple: run the suite, aggregate the metrics, fail loudly if anything has gotten meaningfully worse.</p><pre>def ci_gate(new_agent, baseline_metrics):<br>    results = run_eval_suite(new_agent, GOLDEN_DATASET)<br>    metrics = aggregate(results)<br><br>    regressions = []<br><br>    # Quality regression - fewer cases passing than before<br>    if metrics[&quot;pass_rate&quot;] &lt; baseline_metrics[&quot;pass_rate&quot;] - 0.02:<br>        regressions.append(&quot;pass rate dropped more than 2%&quot;)<br><br>    # Safety regression - agent calling tools it shouldn&#39;t<br>    if metrics[&quot;forbidden_call_rate&quot;] &gt; baseline_metrics[&quot;forbidden_call_rate&quot;]:<br>        regressions.append(&quot;forbidden tool calls increased&quot;)<br><br>    # Efficiency regression - trajectories getting longer<br>    if metrics[&quot;avg_steps&quot;] &gt; baseline_metrics[&quot;avg_steps&quot;] * 1.2:<br>        regressions.append(&quot;trajectory length up more than 20%&quot;)<br><br>    # Cost regression - paying more for the same work<br>    if metrics[&quot;avg_cost_per_task&quot;] &gt; baseline_metrics[&quot;avg_cost_per_task&quot;] * 1.15:<br>        regressions.append(&quot;cost per task up more than 15%&quot;)<br><br>    if regressions:<br>        raise Exception(f&quot;Blocking merge: {regressions}&quot;)</pre><p>Notice the four checks aren’t all the same kind of metric. One is <strong>quality (pass rate)</strong>, one is <strong>safety (forbidden calls)</strong>, one is <strong>efficiency (steps)</strong>, one is <strong>cost</strong>. Each gate guards a different way the agent can get worse. You want all four because regressions don’t always show up in the obvious place a “smarter” prompt that fixes a few edge cases but doubles the average step count is a cost regression hiding behind a pass-rate improvement.</p><p>The trajectory-length and cost gates in particular have saved me more than once. Without them, the metric that catches a quietly-bloated agent is your monthly cloud bill and by then you’ve been bleeding money for weeks.</p><h3>4. The Metric Stack: Three Layers</h3><p>When people ask “what’s the metric for our agent?” the honest answer is: there isn’t one. There are three layers, and you need all of them.</p><h4>Layer 1: Outcome metrics- did the user get what they came for?</h4><p>This is what the business cares about and what goes on the exec dashboard:</p><ul><li><strong>Task completion rate- </strong>did the agent fully resolve the intent?</li><li><strong>Deflection rate-</strong>what % of conversations were handled without escalating to a human? Production-grade support agents land in the 70–90% range.</li><li><strong>Resolution time</strong> -first message to resolved.</li><li><strong>Business KPI</strong> -CSAT(Customer Satisfaction Score), conversion, refund accuracy, retention.</li></ul><h4>Layer 2: Trajectory metrics-did it get there the right way?</h4><p>This is what’s invisible to the user but critical for engineering:</p><ul><li><strong>Tool selection accuracy</strong> -right tool for the step?</li><li><strong>Tool argument accuracy</strong> -right parameters? Wrong order ID with the right tool is still wrong.</li><li><strong>Step efficiency-</strong>actual steps vs. minimal steps. Looping is expensive.</li><li><strong>Plan adherence-</strong>did the agent stay on task or wander?</li></ul><pre>def trajectory_metrics(trace, optimal_steps):<br>    return {<br>        &quot;step_count&quot;: len(trace[&quot;steps&quot;]),<br>        &quot;efficiency&quot;: optimal_steps / max(len(trace[&quot;steps&quot;]), 1),<br>        &quot;had_repeats&quot;: len(trace[&quot;steps&quot;]) != len(set(s[&quot;tool&quot;] for s in trace[&quot;steps&quot;])),<br>        &quot;tool_errors&quot;: sum(1 for s in trace[&quot;steps&quot;] if s.get(&quot;error&quot;)),<br>    }</pre><h4>Layer 3: Operational metrics-the agent runs in production, not a notebook</h4><ul><li><strong>Cost per <em>successful</em> task</strong> -note the word “successful.” Cost per task averages in the cheap failures and makes things look better than they are. Cost per successful task is what you actually pay for value delivered.</li><li><strong>P95 / P99 latency-</strong>agent latency compounds across LLM and tool calls. Watch the tail.</li><li><strong>Policy violation rate</strong> -should be 0%. PII leaks, out-of-scope promises, forbidden actions.</li><li><strong>Failure breakdown</strong> -tool timeouts, parse errors, hallucinated tool names, by category.</li></ul><pre>def operational_metrics(trace, pricing):<br>    cost = sum(<br>        s[&quot;tokens_in&quot;] * pricing[&quot;in&quot;] + s[&quot;tokens_out&quot;] * pricing[&quot;out&quot;]<br>        for s in trace[&quot;steps&quot;]<br>    )<br>    return {<br>        &quot;cost_usd&quot;: cost,<br>        &quot;latency_ms&quot;: trace[&quot;end_ts&quot;] - trace[&quot;start_ts&quot;],<br>        &quot;tool_failures&quot;: sum(1 for s in trace[&quot;steps&quot;] if s.get(&quot;error&quot;)),<br>        &quot;succeeded&quot;: trace.get(&quot;succeeded&quot;, False),<br>    }</pre><p>You watch all three layers.</p><p>Outcome metrics tell you <em>if users are happy</em>.</p><p>Trajectory metrics tell you <em>why</em>.</p><p>Operational metrics tell you whether you can afford to <em>keep running</em>.</p><h3>A note on the cost-quality frontier</h3><p>Cost is a first-class metric, not an afterthought, and most teams realize this only after a billing surprise. A few patterns that help:</p><ul><li><em>Cascading models.</em> Use a cheap model for the planner and an expensive one only for steps that need strong reasoning. Or: try the cheap path first, fall back to the expensive one only if confidence is low.</li><li><em>Semantic caching.</em> Same query an hour later? Return the cached response if nothing has changed. For <strong>FAQ-style agents</strong> this can cut cost by 30%+.</li><li><em>Prompt caching.</em> If your provider supports it, cache the long static system prompt so you don’t pay to re-process it on every call.</li><li><em>Routing.</em> Simple intents to a small model, complex ones to a large model. A classifier upfront pays for itself fast.</li></ul><p>Track cost-per-successful-task over time. If it creeps up while the success rate stays flat, you have a silent regression nobody’s looking at.</p><h3>5. Online Rollout: Shadow → Canary → A/B</h3><p>You don’t ship an agent that takes real-world actions to 100% of traffic on day one. You ramp through <strong>three stages</strong>, and each one catches a different class of bug.</p><ol><li><strong>Shadow mode</strong></li></ol><p>The new agent runs in parallel with whatever currently handles the request. It generates responses but <strong>does not send them</strong>. You <strong>compare trajectories, cost, and latency offline.</strong> Catastrophic regressions get caught here with zero user impact.</p><pre>def shadow_handler(query, context):<br>    real_response = current_agent.run(query, context)<br>    try:<br>        shadow_response = new_agent.run(query, context)<br>        log_shadow_comparison(query, real_response, shadow_response)<br>    except Exception as e:<br>        log_shadow_error(query, e)<br>    return real_response  # User only ever sees the real one</pre><p>2. <strong>Canary (1–5% traffic)</strong></p><p>Real users, small slice. This is where you watch failure metrics in <em>real time</em>, not in a weekly review:</p><ul><li>Tool error spikes</li><li>P99 latency drift</li><li>Cost per task drift</li><li>Policy violation alerts (these page someone immediately)</li></ul><pre>import hashlib<br><br>def canary_route(query, user_id, canary_pct=0.05):<br>    # Stable hash so the same user always lands in the same bucket,<br>    # across processes and across server restarts.<br>    digest = hashlib.md5(user_id.encode()).hexdigest()<br>    bucket = int(digest[:8], 16) % 100 / 100<br>    <br>    if bucket &lt; canary_pct:<br>        return new_agent.run(query), &quot;canary&quot;<br>    return current_agent.run(query), &quot;stable&quot;</pre><p><strong>Hash on the user ID, not randomly per request.</strong> You don’t want the same user bouncing between two agents mid-conversation. And avoid Python’s built-in hash()-it&#39;s randomized per process, so the same user can land in different buckets on different servers. MD5 is deterministic across processes and machines, which is what you actually want here.</p><p><strong>3. A/B test</strong></p><p>Once the canary has been stable for a few days, ramp the new agent to a proper experiment usually 50/50 and measure outcome metrics over a window long enough to actually be sure.</p><p>This is the stage where you have to do real statistics instead of vibes. The temptation is overwhelming:<strong> peek at the dashboard daily, see the new agent inching ahead, declare victory after three days, ship it, move on.</strong> That’s exactly how teams ship regressions. <strong>The numbers look good on day three because three days isn’t enough data to tell the difference between a real improvement and noise.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRiLHBCU_4QHihh3FtPiFw.png" /><figcaption>The Failure Modes</figcaption></figure><p>How big does the experiment need to be?</p><p>Before you even start the test, you need to know how many samples it’ll take to confidently detect the improvement you care about. This is called a <strong>power analysis</strong>, and you can compute it in a handful of lines with no libraries beyond math</p><p><strong>Intuition for Power Analysis</strong></p><p>Imagine this scenario</p><p>You run your A/B test:</p><ul><li>A (old): 80% success</li><li>B (new): 82% success</li><li>Looks like B is better, right?</li></ul><p>Now suppose you only tested:</p><ul><li>20 users in A → 16 succeeded</li><li>20 users in B → 17 succeeded</li></ul><p>That’s:</p><ul><li>A = 80%</li><li>B = 85%</li></ul><p>Looks like a <strong>5% improvement</strong><br>But it’s mostly <strong>random luck</strong> (too little data)</p><pre>import math<br><br>def required_samples_per_arm(baseline_rate, mde, alpha=0.05, power=0.8):<br>    &quot;&quot;&quot;<br>    How many samples per arm to detect a lift of `mde` from `baseline_rate`?<br>    <br>    baseline_rate: current success rate (e.g. 0.80 for 80% task completion)<br>    mde:           minimum detectable effect — the smallest lift you care about<br>    alpha:         false-positive tolerance (0.05 = 5%)<br>    power:         true-positive sensitivity (0.80 = 80% chance of catching real lift)<br>    <br>    Standard two-proportion z-test approximation.<br>    &quot;&quot;&quot;<br>    z_alpha = 1.96   # two-sided alpha = 0.05<br>    z_beta = 0.84    # power = 0.80<br>    <br>    p1 = baseline_rate<br>    p2 = baseline_rate + mde<br>    pooled = (p1 + p2) / 2<br>    <br>    numerator = (z_alpha * math.sqrt(2 * pooled * (1 - pooled)) +<br>                 z_beta * math.sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2<br>    <br>    return math.ceil(numerator / (mde ** 2))<br><br># Example: 80% baseline completion, want to detect a 2% lift<br>print(required_samples_per_arm(0.80, 0.02))  # ~6,280 per arm</pre><p>Quick note on terminology: an <em>arm</em> is just one variant in the test, the <strong>control (current agent) </strong>is one arm, the<strong> treatment (new agent)</strong> is the other. So “6,280 per arm” means 6,280 users go through the old agent and 6,280 through the new one, for ~12,000 total.</p><p>If your agent serves 500 conversations a day and you split traffic 50/50, that’s about 12 days of running before the result means anything. <strong>If you call it after three days because the dashboard looks good, you’re not reading a result you’re reading noise dressed up as one.</strong></p><p><strong>Why agent metrics need more samples than ranker metrics?</strong></p><p>If you’ve A/B-tested a ranker before, these numbers might feel high. The reason: a ranker’s success is one simple event did the user click or not? An agent’s success depends on a whole chain of steps going right, and each step adds a little randomness. More randomness in the outcome means you need more data to tell a real improvement apart from luck.</p><p><strong>Don’t peek</strong></p><p>Every time you check the dashboard mid-experiment and think “should I stop now?”, you’re quietly raising the chance of a false positive. The math assumes you decide once, at the end. Checking ten times and stopping the moment things look good is a different experiment than the one you planned and a less reliable one.</p><p><strong>The clean fix</strong>: pick your sample size up front and don’t act on the results until you hit it.</p><p><strong>The realistic fix</strong>: you’re going to peek anyway. So use a method built for it. Sequential testing (like mSPRT) and “always-valid” confidence intervals are designed to let you check as often as you want without breaking the math. Most modern experimentation platforms Eppo, Statsig, Optimizely have this built in.</p><p><strong>Plan for novelty effects and stratify your results</strong></p><p>Two more things to watch:</p><ul><li><strong>Novelty:</strong> <strong>Users behave differently in the first week of any A/B test</strong> simply because the experience is new. Run a “burn-in” period keep collecting data, but don’t trust the early numbers for your final decision.</li><li><strong>Stratification:</strong> “The new agent is better overall” can quietly hide “better for power users, worse for new users.” <strong>Always slice your results by user segment, intent, and query difficulty.</strong> Sometimes the right call is to ship the new version to one group and keep the old one for another.</li></ul><h3>6. Production Monitoring and Drift</h3><p>Shipping is not the end. Agents drift in ways that aren’t obvious from aggregate metrics.</p><p><strong>Trajectory length drift-</strong> If your average step count starts climbing, something changed. New users with <strong>weirder queries, an upstream tool that’s now returning ambiguous results, a model update that made the planner more cautious</strong>. Watch the <em>distribution</em>, not just the mean a bimodal trajectory length distribution (most queries quick, a long tail looping) is invisible in averages.</p><p><strong>Tool success rate per tool-</strong> Each tool’s success rate, plotted over time. A vendor API change that breaks 2% of calls won’t show up in your overall completion rate, but it’ll show up here.</p><p><strong>Cost / token drift-</strong> Same query patterns, more tokens? Something is off. Could be longer system prompts after a refactor, could be the agent hallucinating retries, could be a model update that made responses more verbose.</p><p><strong>Distribution shift in user queries-</strong> Cluster incoming queries weekly and watch for new clusters appearing. New product launches, viral support issues, seasonal patterns all of these change what the agent sees and how it should respond. A simple embedding-based clustering on a sample of queries goes a long way.</p><p><strong>Async sampling for LLM-as-judge-</strong> You can’t run a judge on every production trace; it’s too expensive. <strong>Sample 1–5% asynchronously and run the judge in the background.</strong> This catches <em>quality</em> drift, which doesn’t show up in pass/fail metrics.</p><h3>7. Guardrails: Because Agents Take Actions</h3><p>This is where agentic systems diverge most violently from traditional ML. A misclassified sentiment is a logged number. A wrong refund is a chargeback. Guardrails aren’t optional.</p><p><strong>Allow-lists and deny-lists-</strong> Be explicit about what tools the agent can call in which contexts. <strong>A support agent has no business touching the payments admin API.</strong> The principle of least privilege applies to agents too.</p><p><strong>Spend caps-</strong> Refund &gt; $X requires human approval. Bulk operations require human approval. <em>Agents handle the long tail; humans handle the head.</em></p><pre>def guarded_refund(amount, user_id, agent_context):<br>    if amount &gt; 100:<br>        return require_human_approval(amount, user_id, agent_context)<br>    if daily_refund_total(user_id) + amount &gt; 500:<br>        return require_human_approval(amount, user_id, agent_context)<br>    return execute_refund(amount, user_id)</pre><p><strong>Confirmation steps for irreversible actions-</strong> Deletes, payments, anything you can’t undo. The agent prepares the action; a separate confirmation step (sometimes another model, sometimes a human) executes it. The asymmetry between “easy to do, hard to undo” is exactly when you want a checkpoint.</p><p><strong>Input filters-</strong> Before the agent ever sees the input, run a fast classifier for <strong>prompt injection, PII, and out-of-scope queries.</strong> Cheap, fast, catches the obvious stuff.</p><p><strong>Output filters-</strong> Before the response goes to the user, scan for PII leakage, policy violations, and out-of-scope claims. Cheap to run on the output, much cheaper than the user complaint.</p><p><strong>Auto-rollback on violation spikes-</strong> If the canary’s policy violation rate crosses a threshold, kill it automatically. Don’t wait for someone to notice.</p><pre>def monitor_canary(window_metrics, thresholds):<br>    if window_metrics[&quot;policy_violation_rate&quot;] &gt; thresholds[&quot;violation_max&quot;]:<br>        disable_canary()<br>        page_oncall(&quot;Canary disabled: policy violation rate exceeded&quot;)<br>    if window_metrics[&quot;cost_per_task&quot;] &gt; thresholds[&quot;cost_max&quot;] * 2:<br>        disable_canary()<br>        page_oncall(&quot;Canary disabled: cost anomaly&quot;)</pre><p><strong>Human-in-the-loop for high-stakes actions</strong>- This isn’t a failure of automation, it’s good design. The agent gets the 90% it can handle reliably; <strong>humans get the 10% that’s high-stakes or weird</strong>. That ratio is where the ROI is anyway, and trying to push it to 100% is usually how teams blow up.</p><h3>8. A note on multi-agent systems</h3><p>If you’re orchestrating multiple agents a planner that delegates to specialists, a critic-writer pair, a swarm of role-played experts there’s a whole extra layer of failures to watch for.</p><ol><li><strong>Inter-agent coordination failures:</strong> Agent A asks Agent B for something, B returns a malformed response, A doesn’t know how to handle it, the whole thing deadlocks. Test the seams between agents, not just the agents themselves.</li><li><strong>Conversational loops:</strong> This is the multi-agent failure that shows up on your billing dashboard. Critic says “needs more detail.” Writer adds detail. Critic says “too verbose, tighten it.” Writer tightens. Critic says “now it lacks detail.” Each round is a full LLM call on both sides, often with the entire conversation history attached so token usage grows quadratically. I’ve seen a “polish this draft” task burn through $80 in 40 minutes because two agents couldn’t agree on what “good” looked like. The fix is simple but easy to forget:<strong> always cap the number of agent-to-agent calls per task, and treat hitting the cap as a failure, not a soft limit</strong>. If your critic-writer loop hits 5 rounds, something is wrong with the criteria, not the writer.</li><li><strong>Path convergence:</strong> Different runs of the same task should take similar paths. If one run takes 4 hops and another takes 14, your system is unstable even if both eventually produce a “correct” answer. Watch the distribution of trajectory lengths, not just the average. A long tail is a runaway waiting to happen.</li><li><strong>Emergent behavior.</strong> Two correct agents can compose into a wrong system. Classic case: Agent A and Agent B both assume the other handled something, and nothing gets handled. Each agent passes its own evals; the system still fails. <strong>Test end-to-end, not just per-agent.</strong></li></ol><blockquote>Honest advice: don’t go multi-agent until your single-agent eval story is solid. Most “we need multi-agent” cases are actually “we need a better single agent with the right tools.” Multi-agent is a real architecture for some problems and a real way to make your system harder to debug, more expensive to run, and easier to break in ways no one notices until the bill arrives.</blockquote><h3>The takeaway</h3><p>For a model, you evaluate the prediction. <em>For an agent, you evaluate the process,</em> did it pick the right tools, take a sensible path, stay within policy, and finish at acceptable cost, while the user actually got value.</p><p>A model can be wrong silently. An agent can be wrong loudly and expensively wrong refund, wrong email, $50 burned in tokens chasing its own tail. The job of your eval system is to catch all three before users do.</p><p>Build the harness before the agent. <strong>Name your failure modes. Layer your metrics. Validate your judge. Roll out in stages. Wrap actions in guardrails.</strong> None of it is glamorous, but it’s the difference between an agent that quietly does its job and a 2 a.m. page about a refund loop.</p><p>If you’ve shipped agents to production, I’d love to hear what you watch for that I missed — especially around multi-agent failures, which I’m still learning the hard way.</p><p><em>#AgenticAI #LLM #MachineLearning #MLOps #AIEngineering #ProductionAI #LLMOps #SoftwareEngineering #AI #ArtificialIntelligence</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a99e98d5353" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an Autonomous SRE Agent That Resolves Production Incidents While I Sleep]]></title>
            <link>https://medium.com/@harshit-aitch-cmd/i-built-an-autonomous-sre-agent-that-resolves-production-incidents-while-i-sleep-102175b0ac7c?source=rss-a9b2c35f1588------2</link>
            <guid isPermaLink="false">https://medium.com/p/102175b0ac7c</guid>
            <category><![CDATA[react-agent]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Harshit Singh]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 07:32:36 GMT</pubDate>
            <atom:updated>2026-04-11T19:51:12.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wri4AyXpI_gH6V2FkMPOQw.png" /></figure><p>A deep dive into AegisOps-a LangGraph ReAct agent with four memory layers, policy-gated Kubernetes actions, and a brain that learns from every incident it handles.</p><p>It’s 3:14 AM. Your PagerDuty goes off. Prometheus just fired a critical alert payment service error rate spiked to 34%, pods are crashing with OOMKills, and you have six minutes before your SLA breach window opens. You have two choices: drag yourself out of bed to SSH into a cluster, or let the agent handle it.</p><p>I chose the second option. And it worked. This is the story of how I built AegisOps, an autonomous SRE agent that can <strong>diagnose, act on, and resolve production incidents without human intervention, while maintaining a rigorous audit trail of every decision it makes and why.</strong></p><p>This isn’t a chatbot wrapper around kubectl. It&#39;s a system with genuine memory, layered autonomy controls, and the ability to learn from the incidents it resolves. Let me walk you through every piece of it.</p><h3>GitHub Repo</h3><p>The full codebase is on GitHub → <a href="https://github.com/aitch-cmd/AegisOps-DRI-Autonomous-SRE-Agent">AegisOps-DRI-Autonomous-SRE-Agent</a></p><blockquote><em>“The goal wasn’t to replace the on-call engineer. It was to give them a tireless first responder that already knows your runbooks, remembers your last ten incidents, and checks policy before touching anything in production.”</em></blockquote><h4>Why ReAct, and Why LangGraph</h4><p>The ReAct (<strong>Reasoning + Acting</strong>) pattern was the natural fit here. Unlike a simple chain that blindly executes steps, ReAct lets the agent <em>think before it acts </em><strong>generating a Thought, deciding on an Action, observing the result, then looping</strong>. For incident response, this matters enormously. You want the agent to ask: “What do I know? What am I seeing? What should I try next?”</p><p>LangGraph gave us the stateful graph execution we needed. Every node in the graph has access to the full AegisState a TypedDict carrying messages, memory, incident metadata, policy decisions, tool invocations, and verification results. The state is checkpointed to PostgreSQL at every step, which means the agent can be interrupted, inspected, and resumed.</p><figure><img alt="AegisOps LangGraph StateGraph" src="https://cdn-images-1.medium.com/max/1024/1*KLQNDG8VZcS7VmouwR4GaQ.png" /><figcaption>AegisOps LangGraph StateGraph</figcaption></figure><p>The graph has four nodes. memory_node runs first and pre-loads everything the agent needs before it even starts reasoning. agent_node is the LLM reasoning loop. tools is LangGraph&#39;s built-in ToolNodeexecutes whatever the LLM requested. And resolution_node closes out the incident: persisting memory, calculating MTTR, and firing the Slack notification.</p><p>I’ve kept the structure as simple as possible to avoid overengineering.</p><h3>The Four Memory Layers</h3><p>This is the part I’m most proud of, and the part that separates AegisOps from a glorified script. Honestly, this is also the reason I chose this problem statement in the first place most agentic systems you see in day-to-day use skip memory architecture entirely or mostly use two layers, and I wanted to actually explore it properly.</p><p>A human SRE brings four kinds of memory to every incident. Ireplicated all four.</p><ol><li><strong>Episodic Memory (</strong>pgvector, cosine similarity): Past resolved incidents stored as vector embeddings. When a new incident arrives, the top-3 most similar past incidents are retrieved and injected into the system prompt including their root cause, actions taken, and outcome.</li><li><strong>Semantic Memory(</strong>RAG, KnowledgeBase, pgvector<strong>): </strong>Chunked runbooks, architecture docs, and postmortems in a vector store. The retrieve_runbook tool performs semantic search against this corpus giving the agent access to your team&#39;s institutional knowledge.</li><li><strong>Procedural Memory(</strong>YAML policies, rule engine, redis<strong>): </strong>Hard rules about what the agent is allowed to do at each autonomy level. These are loaded from params.yml at the initial phase of graph from redis and evaluated before any mutating action. Think of it as the agent&#39;s instilled muscle memory for safe operations.</li><li><strong>Working Memory(</strong>AegisOpsState, LangGraph checkpoint<strong>): </strong>The full in-flight state: messages, current thoughts, tool invocations, health check results, retry counts. Checkpointed to PostgreSQL at every node, so the agent’s context is never lost even across restarts.</li></ol><figure><img alt="Four Memory Layers and Their Data Sources" src="https://cdn-images-1.medium.com/max/863/1*MDyKyuHRVq9_w_w2ZykonQ.png" /><figcaption>Four Memory Layers and their data sources</figcaption></figure><h4>How episodic memory actually works</h4><p>When memory_node fires, it calls retrieve_similar_incidents with the current incident&#39;s symptom list. Those symptoms are embedded using a 768-dimensional sentence encoder, then <strong>compared against the </strong><strong>IncidentMemory</strong> table using <strong>pgvector&#39;s cosine distance</strong>. Any past incident above the similarity threshold (I use 0.72) gets returned, formatted, and injected into the system prompt before the first agent thought.</p><p>After resolution, resolution_node calls save_incident_memory the <strong>agent writes its own memories</strong>. The embedding is computed from symptoms concatenated with the root cause hypothesis. Future incidents with similar symptoms will find this one.</p><blockquote>On the pgvector choice<strong>: </strong>I could have used a dedicated vector DB like <strong>Pinecone or Weaviate</strong>, but keeping everything in PostgreSQL meant one less infrastructure dependency and transactional consistency between incident records and their embeddings. For the scale we’re operating at, pgvector is more than sufficient.</blockquote><h4>The Autonomy System: L0 Through L3</h4><p>This was the hardest design decision. How do you give an AI agent real power over production infrastructure without it doing something catastrophic? My answer:<em> a layered autonomy model where every mutating action is policy-gated before execution.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*xxZ3yw6ugY0H-60MOIKu1Q.png" /><figcaption>Policy-Gated Autonomy Levels</figcaption></figure><p>Every action tool-restart_deployment, scale_deployment, update_deployment_image makes its first call to retrieve_policy before touching anything. The policy engine evaluates the action, service, severity, and current autonomy level against the rules in params.yml. If the policy says no, the tool returns immediately with a deny and the agent has to figure out an<strong> alternative (usually escalation)</strong>.</p><p>The requires_approval field is particularly interesting. At L3, certain destructive actions (like an image rollback on a critical payment service) still require explicit human approval before proceeding. The agent fires a Slack notification and waits. This gave our on-call team confidence that the highest-risk operations always have a human in the loop.</p><h4>The Full Tool Arsenal</h4><p>AegisOps has sixteen tools organized into four categories. Here’s the complete picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*p9j2hsXsaRuV-4N-e50Rjg.png" /><figcaption>Complete tool inventory by category</figcaption></figure><ol><li>get_logs: Reads the last 500 lines from logs/{service}.log, <strong>filters by log level</strong>, then runs every matching line through a normalizer stripping IPs, UUIDs, and bare numbers so that &quot;connection refused from 10.0.1.42&quot; and &quot;connection refused from 10.0.1.99&quot; collapse into the same pattern. A Python Counter then ranks the surviving patterns by frequency and returns the top-k. <em>The result is the same structured output whether you&#39;re reading it in your terminal at 2 AM or the agent is using it as evidence in its ReAct reasoning loop</em><strong>,</strong> no Elasticsearch cluster required, no infra overhead, just a log file and a few lines of Python.</li><li>get_pod_status: Hits the Kubernetes CoreV1Api to list pods by app={deployment} label, <strong>returning restart count, ready state, and container state.</strong> Gracefully handles cluster connectivity failures and redirects to get_logs as fallback.</li><li>restart_deployment: The workhorse. Patches the kubectl.kubernetes.io/restartedAt annotation to trigger a rolling restart, <strong>polls until all replicas are ready, then runs a health check</strong>. The drain-before-restart option ensures zero traffic is served during the restart window.</li><li>update_deployment_image: Emergency rollback tool. Patches the container image spec directly, waits for rollout to complete, then verifies pod health. The most powerful action in the arsenal <strong>requires L3 autonomy</strong> for production critical incidents.</li><li>check_service_health: Combines K8s pod readiness (via CoreV1Api) with real-time error rate from Prometheus. Returns a healthy boolean True only if <strong>all pods are ready <em>and</em> the 5xx error rate is below 5%</strong>.</li><li>retrieve_runbook: Semantic search over your team’s runbooks, postmortems, and architecture docs. Returns the <strong>top-4 most relevant chunks</strong> (similarity ≥ 0.75). Injected into working context as “RUNBOOK CONTEXT” in the system prompt.</li></ol><h4>The ReAct Loop in Action</h4><p>Let me walk through a real incident resolution trace. Payment service, OOMKill, 3:14 AM. Here’s what the agent actually did:</p><pre>[MEMORY] Loading episodic context for payment-service...<br>[MEMORY] Found 2 similar past incidents (similarity: 0.89, 0.76)<br>[MEMORY] Loaded 3 procedural policies for payment-service/critical<br><br>[THOUGHT] Incident: payment-service OOMKill, 3 pods CrashLooping.<br>Past incident INC-2801 had identical symptoms — root cause was<br>a memory leak in the gRPC connection pool after a deploy.<br>Starting with get_logs to confirm before acting.<br><br>[ACTION] Calling tool: get_logs with {&#39;service_name&#39;: &#39;payment-service&#39;, &#39;log_level&#39;: &#39;error&#39;}<br>→ top_errors: [{&quot;pattern&quot;: &quot;out of memory: kill process&quot;, &quot;count&quot;: 47},<br>{&quot;pattern&quot;: &quot;grpc connection pool exhausted&quot;, &quot;count&quot;: 23}]<br><br>[THOUGHT] OOM confirmed. gRPC pool exhaustion matches INC-2801 pattern.<br>Retrieve runbook before acting — want the fix procedure.<br><br>[ACTION] Calling tool: retrieve_runbook with {&#39;query&#39;: &#39;payment service grpc oom memory leak fix&#39;}<br>→ [runbooks / payment-service-oom.md] Recommended action: rolling restart<br>resets connection pool. If recurs within 1h, rollback to previous image.<br><br>[THOUGHT] Runbook confirms rolling restart. Checking policy for autonomy L2...<br><br>[ACTION] Calling tool: restart_deployment with {&#39;service&#39;: &#39;payment-service&#39;,<br>&#39;deployment&#39;: &#39;payment-worker&#39;, &#39;namespace&#39;: &#39;production&#39;,<br>&#39;severity&#39;: &#39;critical&#39;, &#39;autonomy_level&#39;: &#39;L2&#39;}<br>→ policy: ALLOWED (L2 ≥ min_level L2 for restart_deployment)<br>→ draining pods... restarting... polling rollout...<br>→ health_check: healthy=True, pods_ready=3/3, error_rate=0.008<br><br>[THOUGHT] Restart succeeded. Error rate 0.8% — below 5% threshold.<br>Verifying with check_service_health before closing.<br><br>[ACTION] Calling tool: check_service_health with {&#39;service&#39;: &#39;payment-service&#39;,<br>&#39;deployment&#39;: &#39;payment-worker&#39;, &#39;namespace&#39;: &#39;production&#39;}<br>→ healthy=True, pods_total=3, pods_ready=3, error_rate=0.007<br><br>[THOUGHT] Service fully recovered. Writing audit log and resolving.<br><br>[ACTION] Calling tool: write_audit_log ...<br>→ audit_log written: restart_deployment for incident INC-2847<br><br>RESOLVED: payment-service recovered after rolling restart. Root cause: gRPC<br>connection pool OOM — matched pattern from INC-2801. All 3 pods healthy,<br>error rate 0.7%. MTTR: 187 seconds.<br><br>[MEMORY] Saving incident INC-2847 to episodic memory...<br>[NOTIFY] Sending resolution to Slack channel: #all-aegisops ✅</pre><p>187 seconds. Three minutes and seven seconds from alert to resolution, and nobody had to wake up. That’s the benchmark we’re now consistently hitting for incidents that match past patterns.</p><blockquote><em>“The agent’s first instinct was to look at what worked last time just like a senior engineer would. That’s episodic memory doing exactly what it’s supposed to do.”</em></blockquote><p>The styled trace above is a reconstructed walkthrough for clarity. Here’s what it actually looks like running on a local setup with limited resources a single Kind cluster, no Prometheus.</p><p>The incident fired via a simple PowerShell webhook call:</p><pre>Invoke-RestMethod -Uri &quot;http://localhost:8000/webhook/incident&quot; `<br>  -Method Post `<br>  -ContentType &quot;application/json&quot; `<br>  -Body &#39;{<br>    &quot;source&quot;: &quot;webhook&quot;,<br>    &quot;severity&quot;: &quot;critical&quot;,<br>    &quot;service&quot;: &quot;payment-service&quot;,<br>    &quot;symptoms&quot;: [&quot;High 500 errors&quot;, &quot;DB connection timeouts&quot;],<br>    &quot;autonomy_level&quot;: &quot;L2&quot;<br>  }&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFhAH4Uj0H8F6lbVGcwNtw.png" /></figure><p>And the agent ran it end to end retrieved similar incidents, <strong>formed a hypothesis (traffic spike overwhelming pod capacity, similar to a past incident it found in memory), called </strong><strong>get_pod_status, saw 2/5 pods ready, scaled the deployment to 4 replicas,</strong> <strong>verified with </strong><strong>check_service_health, and closed with </strong><strong>RESOLVED</strong>. The Slack notification hit #all-aegisops and the incident was written back to episodic memory.</p><p>Is it less dramatic than a production gRPC OOM at 3 AM? Sure. But the reasoning loop is identical the same Thought → Action → Observation cycle, the same policy gate before scaling, the same memory write at the end. The infrastructure around it is thinner; the agent behaviour is the same.</p><p>That’s actually the point: <strong>the agent doesn’t care whether it’s running against a Kind cluster on a laptop or a 50-node production fleet.</strong> Swap the kubeconfig, point Prometheus at real metrics, and the same code handles the real stuff.</p><h4>What the Slack Channel Looks Like</h4><p>Every significant agent action fires a Slack notification. The resolution node sends a summary to #all-aegisops with color-coded severity, MTTR, and the full resolution summary. The on-call engineer wakes up to a green checkmark instead of a pager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*OYYeL7KgJQNt7JdB1yoyaA.png" /></figure><h4>The Infrastructure Stack</h4><p>The whole system runs on a surprisingly minimal stack as I’ve built in my local setup. PostgreSQL with pgvector handles both the episodic memory and LangGraph’s checkpoint persistence. Redis sits in reserve for future rate limiting. Prometheus feeds check_service_health with real error rates. Grafana gives us the dashboards.</p><pre>version: &quot;3.9&quot;<br><br>services:<br>  postgres:<br>    image: ankane/pgvector:latest<br>    ports:<br>      - &quot;5445:5432&quot;<br>    environment:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: admin123<br>      POSTGRES_DB: aegisops<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br><br>  redis:<br>    image: redis:alpine<br>    ports:<br>      - &quot;6380:6379&quot;<br><br>  app:<br>    build: .<br>    ports:<br>      - &quot;8000:8000&quot;<br>    env_file: .env<br>    depends_on:<br>      - postgres<br>      - redis<br><br>  prometheus:<br>    image: prom/prometheus:latest<br>    ports:<br>      - &quot;9090:9090&quot;<br>    volumes:<br>      - ./infra/prometheus.yml:/etc/prometheus/prometheus.yml<br><br>  grafana:<br>    image: grafana/grafana:latest<br>    ports:<br>      - &quot;3000:3000&quot;<br><br>volumes:<br>  postgres_data:</pre><p>The app itself is FastAPI running with uvicorn. Incidents arrive via a webhook endpoint that constructs an IncidentEvent and calls run_agent(). The async execution means multiple incidents can be processed in parallel without blocking.</p><blockquote><strong>One footgun to be aware of</strong>get_pod_status and check_service_health load the Kubernetes config at module import time (not inside the async function body). If the cluster isn&#39;t reachable at startup, they fail silently and return warning messages. Make sure your KUBECONFIG or in-cluster service account is properly configured before the app starts.</blockquote><h4>The Audit Trail</h4><p>Every tool invocation gets wrapped in a ToolInvocation TypedDict tool <strong>name, parameters, result, success flag, latency, timestamp, and the policy decision that gated it</strong>. These accumulate in state[&quot;tool_invocations&quot;] throughout the run, then get persisted to episodic memory at resolution time. The write_audit_log tool emits a structured JSON log line for every significant action.</p><p>This means you can reconstruct <em>exactly</em> what the agent did, in what order, what it was allowed to do, and why, for every single incident. That’s the audit trail a compliance team actually wants to see.</p><blockquote><strong>The design principle that made this work: </strong>Every mutating action returns <em>both</em> the policy decision and the health check result as part of its response. The agent sees not just “did it work” but “was it allowed” and “is the service healthy now” three separate signals that feed the next thought.</blockquote><h4>What’s Next</h4><p>Everything in this post runs end to end I couldn’t push it further only because my local setup was hitting its limits running Ollama alongside the full system. Given proper resources, here’s what I’d build next.</p><p>Three things I want to fix:</p><p>The <strong>approval flow</strong> is the most pressing. approval_status already lives in AegisOpsState and requires_approval is already evaluated — but it doesn&#39;t actually pause anything yet. It should fire a Slack button, block the graph, and wait for a human click before any L3 action proceeds. LangGraph&#39;s checkpointing supports mid-graph suspension natively, so this is wiring work, not architecture work.</p><p><strong>Before/after metric comparison</strong> is the second gap. check_service_health gives a point-in-time snapshot post-fix. What the agent really needs is a Prometheus delta — error rate five minutes before vs five minutes after — to have genuine confidence it actually fixed something rather than just got lucky with timing.</p><p><strong>Runbook self-authoring</strong> is the long-term one. Right now episodic and semantic memory are separate and static relative to each other. After a novel resolution, the agent should draft a new runbook chunk and upsert it into KnowledgeBaseso retrieve_runbook surfaces it next time. That closes the loop between the two memory layers completely.</p><blockquote><em>“The system gets smarter with every incident it handles. The more it resolves, the richer its episodic memory, the more confident its future decisions.”</em></blockquote><h4>Final Thoughts</h4><p>Building this taught me something important: the hardest part of autonomous infrastructure agents isn’t the LLM reasoning. <em>It’s the safety architecture around it</em>. The four memory layers, the policy engine, the audit trail, the approval gates those are what make the difference between a tool that a team will trust to run unsupervised at 3 AM and one they won’t.</p><p>AegisOps is opinionated: it believes a structured state machine with clear permission boundaries is safer than a free-form agent that figures it out as it goes. So far, that bet has paid off. I sleep better on-call nights. The incident log is getting richer. And the agent is slowly getting smarter every time it resolves something new</p><p>The code architecture holds up well. LangGraph’s checkpointing, the clean separation between diagnostic and action tools, and the TypedDict-based state all of it makes the system inspectable, debuggable, and auditable in ways that matter when something goes wrong at 3 AM and you need to understand why the agent made the choice it did.</p><p><strong>If you’re building something similar, the main thing I’d tell you: invest in your memory architecture early. An agent with a good memory is worth ten times more than one with a better prompt.</strong></p><blockquote>“Attention is all you need” was for transformers.</blockquote><blockquote>For agents in the real world “Context is all you need”.</blockquote><h4>About This Project</h4><p>AegisOps is built on LangGraph, LangChain, FastAPI, PostgreSQL (pgvector), Kubernetes, and Prometheus. The agent uses an async Python stack throughout, with kubernetes_asyncio for non-blocking cluster operations.</p><p>#LangGraph #ReActAgent #SiteReliabilityEngineering #Kubernetes #pgvector #LLMAgents #IncidentResponse #AutonomousSystems #Python #FastAPI #EpisodicMemory #RAG</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=102175b0ac7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From 28GB to 3.5GB: How Engineers Make LLMs Lighter Without Breaking Them]]></title>
            <link>https://medium.com/@harshit-aitch-cmd/from-28gb-to-3-5gb-how-engineers-make-llms-lighter-without-breaking-them-5563a0e1c9f8?source=rss-a9b2c35f1588------2</link>
            <guid isPermaLink="false">https://medium.com/p/5563a0e1c9f8</guid>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[qlora]]></category>
            <category><![CDATA[llm-engineering]]></category>
            <dc:creator><![CDATA[Harshit Singh]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 13:28:45 GMT</pubDate>
            <atom:updated>2026-06-26T20:29:00.496Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve just built an LLM-powered app. The demo goes perfectly. You ship it.</p><p>Then reality hits.</p><p>Users complain it’s slow. Your GPU bill doubles. Someone suggests “just use a smaller model” but nobody knows how. You google around and drown in terms like quantization, distillation, LoRA, QLoRA, INT8, FP16.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONkvYzrx6zOqV22o9qkvYA.png" /></figure><p>Every production LLM hits the same wall: these models are enormous. A 7B parameter model weighs 28GB in FP32. A 65B model needs 260GB just to load before a single user touches it.</p><p>Engineers have spent years solving this around one core idea:</p><blockquote>Make the model lighter without making it dumber.</blockquote><p>This blog covers:</p><ul><li><strong>Quantization</strong> — fewer bits, faster inference</li><li><strong>PTQ vs QAT</strong> — when to compress</li><li><strong>LLM.int8() &amp; GPTQ</strong> — techniques powering real deployments</li><li><strong>LoRA &amp; QLoRA</strong> — fine-tuning a 65B model on one consumer GPU</li></ul><h3>Quantization</h3><h4>What and Why</h4><p>LLM quantization is a technique to <strong>reduce the size of a large language model by using lower-precision numbers instead of full-precision ones.</strong></p><p>It’s a procedure that maps the range of high precision weight values like FP32, into lower precision values such as FP16 or even INT8 (8-bit Integer) datatypes.</p><p>Consider your 400M parameter LLM. Usually, weights are stored in FP32(32-bit). The memory footprint of this model can be calculated as:</p><blockquote><em>4x10⁸ params x 4 bytes = 1.6 Gigabytes</em></blockquote><p>Quantizing the above model can reduce the size significantly. Consider a conversion from FP32 to INT8. The quantized model’s memory footprint can be calculated as:</p><blockquote><em>4x10⁸ params x 1 byte = 0.4 Gigabytes</em></blockquote><p>That is <strong>1/4th</strong> of the original size! This helps the model occupy less memory and also enhances inference speed although it may compromise the accuracy a bit. Also, some of these lightweight models can be easily handled by a CPU.</p><h4>Intuition</h4><p>They are all different ways to represent numbers</p><p>Think about a number like:</p><pre>3.14159</pre><p>You can store it in your computer with different precision:</p><ul><li>exactly (many decimals)</li><li>less precisely (cut decimals)</li><li>as a small integer</li></ul><p>That choice affects <strong>speed, accuracy, and memory</strong>.</p><h4>FP32, FP16, INT8- it’s all just how you store a number</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlfXbFw9QJZYTwYgDS_mTQ.png" /></figure><ol><li>FP32 = 32-bit Floating Point</li></ol><ul><li>High precision (very accurate)</li><li>Used in training and math operations</li><li>Occupies more memory</li></ul><p>Analogy:</p><blockquote><em>Like writing every detail with a microscope.</em></blockquote><p>Used when you care about exactness.</p><p>2. FP16 = 16-bit Floating Point</p><ul><li>Half precision</li><li>Uses less memory</li><li>Faster computation</li><li>Slight loss in precision but usually fine</li></ul><p>Analogy:</p><blockquote><em>You’re still writing decimal numbers, but shorter.</em></blockquote><p>Example:</p><ul><li>FP32: 3.1415926535</li><li>FP16: 3.14</li></ul><p>For most models, the difference is tiny.</p><p>3. INT8 = 8-bit Integer</p><ul><li>No decimal places (or very limited)</li><li>Very small and fast</li><li>Almost 4x smaller than FP32</li></ul><p>Analogy:</p><blockquote><em>Instead of writing decimals, you’re rounding everything to small whole numbers.</em></blockquote><p>Example:</p><ul><li>FP32: 3.1415926535</li><li>INT8: 3 or maybe 3.1 scaled</li></ul><h4><strong>Post Training Quantization (PTQ)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*qgSnL5Px01RhxcVip5ZrtQ.png" /></figure><p>You take a trained FP32 model and convert its weights to INT8 after training is done. Fast, simple, no retraining needed but sometimes accuracy drops because rounding errors creep in during conversion.</p><p>So researchers asked:</p><p><em>“Can we make the model learn to behave well under quantization while training?”</em></p><p>This is exactly what QAT does.</p><h4><strong>Quantization Aware Training (QAT)</strong></h4><p>Instead of quantizing <strong>after training</strong>, QAT adds quantization <strong>inside</strong> the training process itself.</p><p>So during training:</p><ul><li>The model acts like it’s using INT8</li><li>But gradients are still calculated in FP32</li></ul><p>This allows the model to <strong>learn how to deal with the damage quantization causes.</strong></p><p><strong><em>Under the hood</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*WGnVwwNU5m3zH4L7pg0OUw.png" /></figure><p>During training, each layer keeps <strong>two versions</strong>:</p><ol><li>FP32 weights (for gradient updates)</li><li>Fake quantized (INT8) weights/activations</li></ol><p>Why “fake”? Because:</p><ul><li>during forward pass → simulate INT8</li><li>during backward pass → use FP32</li></ul><p>This is called <strong>Fake quantization(</strong><em>Pretending something is real, without actually doing it fully</em><strong>)</strong></p><p>INT8 is simulated but not actually stored permanently.</p><p><strong><em>Why QAT gives better accuracy than PTQ</em></strong></p><p>Because the model:</p><ul><li>sees quantization noise during training</li><li>modifies weights to minimize loss caused by quantization</li></ul><p>So QAT usually gives accuracy very close to original FP32 model (sometimes almost identical).</p><h4>Latest SOTA Quantization Methods</h4><ol><li><strong>LLM.int8()</strong></li></ol><p>It converts weights from <strong>FP16 to INT8</strong>, effectively halving model size and it scales up to 175B parameters without meaningful accuracy loss.</p><p><strong>How it works in 3 steps:</strong></p><ul><li><strong>Vector-wise quantization</strong> -each row of a weight matrix is quantized separately with its own scaling factor, preserving feature differences</li><li><strong>Normalization constants</strong> -a scale factor per vector ensures weights fit cleanly into 8-bit values</li><li><strong>Mixed-precision for outliers</strong> -the ~0.1% of very large weights are kept in 16-bit while everything else runs in INT8</li></ul><p>The result: fast INT8 computation everywhere, with outliers handled separately so accuracy doesn’t suffer.</p><p><strong>Pro</strong> -Little to no accuracy drop for large LLMs</p><p><strong>Con</strong> -Designed specifically for INT8, works best on very large models</p><p>2. <strong>GPTQ</strong></p><p>GPTQ is a one-shot PTQ method built around two ideas:</p><ul><li><strong>Layer wise quantization</strong> -compress one layer at a time, minimizing error at each step rather than quantizing the whole model blindly</li><li><strong>Optimal Brain Quantization</strong> -when one weight is compressed, surrounding weights are adjusted to compensate, keeping overall model behavior intact</li></ul><p>Think of it like this: instead of rounding every number independently, GPTQ looks at the bigger picture and corrects for damage as it goes.</p><p><strong>Pro-</strong>Can quantize down to 2-bit, offering aggressive size reduction</p><p><strong>Con</strong> -Noticeable performance degradation at very low bit widths</p><p>3. <strong>QLoRA</strong></p><p>Before diving into QLoRA, here is a brief introduction to LoRA</p><p>Pre-trained LLMs are general purpose. To specialize them for your use case medical, legal, coding you need fine-tuning. But traditional full fine-tuning means updating every single weight in the model.</p><p>For a 7B parameter model that’s 7 billion updates. For a 65B model, you’re looking at <strong>130GB of GPU memory</strong> just to load the weights. Most teams simply can’t afford that.</p><p>This is the problem LoRA was built to solve.</p><h4>LoRA: Smarter Fine-Tuning</h4><p><strong>The core idea:</strong> Instead of updating all billions of parameters, what if you only trained a tiny set of extra matrices injected into the model?</p><p>That’s exactly what LoRA does. It inserts small trainable matrices called <strong>adapters</strong> inside the model’s attention layers (q_proj, v_proj, k_proj, o_proj). The original model weights stay completely frozen. Only the adapters are trained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7iWNM2jofh6J69m-w9BCoQ.png" /></figure><p><strong>Practically speaking:</strong></p><blockquote><em>Fine-tune a 7B LLaMA model with just ~40M trainable parameters instead of all 7 billion. That’s a </em><strong><em>175x reduction</em></strong><em> in what you actually need to train.</em></blockquote><p><strong>What Are These Adapters Exactly?</strong></p><p>Think of the original weight matrix as a large transformation the model applies to data. LoRA doesn’t modify this matrix directly. Instead it adds <strong>two smaller matrices A and B </strong>whose product approximates the change needed:</p><p>Original weights (frozen): W → 1000 × 1000 = 1M params</p><p>LoRA adapter (trainable): A × B → 1000×8 + 8×1000 = 16K params</p><p>During fine-tuning <strong>only A and B are updated</strong>. After training their product is <strong>added back to the original weights</strong> seamlessly the model is now specialized with minimal overhead.</p><p>Why This Is Powerful</p><ul><li><strong>Faster and cheaper- </strong>fewer parameters to train means less compute and memory</li><li><strong>Modular- </strong>you can maintain multiple adapters for different tasks without duplicating the entire model. One base model, many specializations.</li></ul><h4>QLoRA: LoRA Taken Further</h4><p>LoRA solved the <em>training</em> problem. But there was still a catch the base <strong>model still needed to be loaded in full precision (FP16).</strong></p><p>Here’s what that looks like in practice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*eHOTcBLae4iE58lY5zfewQ.png" /></figure><p>A 65B model needs 130GB of memory far beyond what any consumer GPU can handle (most top out at 24-48GB).</p><p><strong>QLoRA’s answer:</strong> What if we quantized the base model <em>before</em> fine-tuning?</p><p><strong>How QLoRA Works</strong></p><p>QLoRA stacks three ideas together:</p><p><strong>1. Quantize the base model to 4-bit</strong> The base model is compressed using NF4 (4-bit Normal Float) quantization. Memory usage drops dramatically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*wKVh6WWZc0kgUlUyhNkOWQ.png" /></figure><p>A 65B model now fits on a single GPU.</p><p><strong>2. Add LoRA adapters in 16-bit</strong> On top of the frozen quantized base, LoRA adapters are added in full 16-bit precision. These are the only things that get trained.</p><p><strong>3. Gradients flow only through adapters</strong> During backpropagation, gradients <strong>update only the 16-bit adapters</strong> never the quantized base weights. You get the memory savings of quantization without sacrificing fine-tuning quality.</p><blockquote>Frozen base model (4-bit, quantized) + Trainable LoRA adapters (16-bit)→</blockquote><blockquote>Fine-tuned model on a single consumer GPU</blockquote><h4><strong>Double Quantization</strong></h4><p>It<strong> </strong>is a memory optimization technique used in <strong>QLoRA</strong> where the <strong>quantization constants (scales)</strong> are themselves quantized.</p><p>Instead of only compressing the model weights, QLoRA also compresses the metadata needed to reconstruct those weights.</p><p><strong>Step 1: Normal Quantization</strong></p><p>Suppose the original weights are:</p><pre>0.82, -1.35, 0.14, 2.17</pre><p>Using 4-bit quantization, they become something like:</p><pre>7, 2, 5, 15</pre><p>However, these integers alone aren’t enough. To recover the approximate original values, you also need a <strong>scale</strong> (and sometimes a zero-point).</p><p>Example: Quantized Weights:[7, 2, 5, 15]</p><p>Scale: 0.18</p><p>During computation: <strong>Original Weight ≈ Quantized Weight × Scale</strong></p><p><strong>Step 2: The Problem</strong></p><p>Although the weights are now only 4 bits each, the <strong>scale values</strong> are usually stored in higher precision (e.g., float16 or float32).</p><p>For large models with millions of groups of weights,<strong> these scales consume a noticeable amount of memory.</strong></p><p><strong>Step 3: Double Quantization</strong></p><p>Instead of storing scales like:</p><pre>0.18<br>0.24<br>0.09<br>0.31<br>...</pre><p>QLoRA <strong>quantizes these scale values as well</strong>.</p><p>So instead of: Weights (4-bit)+Scales (16-bit)</p><p>we get: <strong>Weights (4-bit)+ Scales (8-bit or another compressed form)</strong></p><h4><strong>Paged Optimization</strong></h4><p>During backpropagation, memory spikes can crash training. QLoRA uses NVIDIA’s unified memory to seamlessly page optimizer states between GPU and CPU RAM when needed like virtual memory for your GPU.</p><blockquote>GPU never runs out , it just borrows from CPU RAM temporarily.</blockquote><p><strong>TL;DR</strong></p><ul><li><strong>LoRA</strong> = parameter-efficient fine-tuning. Train a tiny fraction of parameters, get full fine-tuning quality.</li><li><strong>QLoRA</strong> = LoRA + quantization. Shrink the base model to 4-bit, making it possible to fine-tune massive models on hardware most engineers actually have access to.</li></ul><blockquote>Quantization makes models lighter. But what if the model itself could be made fundamentally smaller without losing what makes it smart? That’s where distillation comes in.</blockquote><h3><strong>Distillation</strong></h3><p>Remember when GPT-3 came out and everyone was amazed by its 175 billion parameters? Then GPT-4 pushed the boundaries even further. These massive language models are incredibly powerful, but they come with a catch: they’re expensive to run, slow to respond, and require serious computing power.</p><p>What if I told you there’s a way to capture most of that intelligence in a model that’s <strong>10x smaller and 10x faster</strong>? Welcome to the world of <strong>LLM distillation</strong>.</p><p><strong>Institution of Model Distillation</strong></p><p>Think of distillation like this: imagine you’ve spent years learning from the world’s best chef. You’ve watched them cook thousands of dishes, picked up their techniques, learned their intuitions. Now, you can cook almost as well as they can, but you work faster and don’t need their fancy equipment.</p><p>That’s essentially what model distillation does. A large, <strong>powerful “teacher” model trains a smaller “student” model</strong> to mimic its behavior. The student learns to replicate the teacher’s knowledge and decision-making patterns, but with far <strong>fewer parameters</strong>.</p><p><strong>The problem it’s solving</strong></p><p>LLMs face three major challenges:</p><p><strong>Cost</strong>: Running GPT-5 or Claude costs money with every API call. For high-volume applications, these costs add up fast.</p><p><strong>Latency</strong>: Bigger models take longer to generate responses. In real-time applications like chatbots or autocomplete, every millisecond matters.</p><p><strong>Infrastructure</strong>: Massive models need expensive GPUs and specialized hardware. You can’t just run them on your laptop or deploy them to edge devices.</p><p>Distillation solves these problems by creating compact models that retain most of the capability.</p><p><strong>Under the hood</strong></p><p><em>The Core Concept: Soft Targets</em></p><p>Here’s where it gets interesting. Traditional training teaches models using <strong>hard</strong> labels:</p><p>Question: &quot;Is this review positive or negative?&quot;</p><p>Hard Label: Positive (100% confidence)</p><p>But large models don’t think in absolutes. They output <strong>probability distributions</strong>:</p><p>Teacher Model’s Output:</p><ul><li>Positive: 92%</li><li>Negative: 5%</li><li>Neutral: 3%</li></ul><p>This probability distribution contains much more information than a simple “positive” label. It tells us the model is very confident it’s positive, but there’s a tiny hint of negativity. This nuance is gold for training.</p><p>Distillation trains the student model to match these <strong>soft </strong>probability distributions, not just the final answer.</p><h4>The Distillation Process: Step by Step</h4><p><strong>Step 1: Start with a Powerful Teacher</strong></p><p>You need a large, well-trained model. This could be:</p><ul><li>GPT-5 or GPT-4</li><li>Claude Opus 4.6</li><li>Llama 370B</li><li>Your own fine-tuned large model</li></ul><p><strong>Step 2: Prepare Your Dataset</strong></p><p>Gather the types of inputs your student model will handle:</p><ul><li>If building a customer service bot, collect support conversations</li><li>For code completion, gather programming examples</li><li>For summarization, collect documents and their summaries</li></ul><p><strong>Step 3: Generate Teacher Predictions</strong></p><p>Run your entire dataset through the teacher model and save:</p><ul><li>The output probabilities (logits) for each token</li><li>The final generated text</li><li>Any intermediate representations (optional, for advanced distillation)</li></ul><p><strong>Step 4: Train the Student Model</strong></p><p>The student model learns using a special loss function that combines:</p><p>Total Loss = α × (Distillation Loss) + (1-α) × (Task Loss)</p><ul><li><strong>Distillation Loss</strong>: How well the student matches the teacher’s probability distributions</li><li><strong>Task Loss</strong>: How well the student performs on the actual task (traditional training)</li><li><strong>α</strong>: A weight (typically 0.5–0.9) that balances both objectives</li></ul><p><strong>Step 5: Fine-tune and Evaluate</strong></p><p>Test the student model on held-out data and iterate until you reach acceptable performance.</p><h4><strong>Types of Distillation Techniques</strong></h4><ol><li><strong>Response-Based Distillation</strong></li></ol><p>The student learns from the teacher’s final outputs.</p><p><strong>Best for</strong>: General language understanding, text generation</p><p><strong>Example</strong>: Training a 7B parameter model to replicate GPT-5’s conversational abilities by learning from its responses.</p><p>2.<strong> Feature-Based Distillation</strong></p><p>The student learns from the <strong>teacher’s internal representations</strong>, not just outputs.</p><p><strong>How it works</strong>: Match the hidden layer activations between teacher and student.</p><p><strong>Best for</strong>: Tasks requiring deep understanding like <strong>sentiment analysis</strong> or <strong>entity recognition</strong></p><p><strong>Tradeoff</strong>: Requires access to teacher’s internals (harder with API-only models)</p><p>3. <strong>Relation-Based Distillation</strong></p><p>Focuses on how the teacher model relates different inputs to each other.</p><p><strong>Example</strong>: If the teacher considers “happy” and “joyful” similar, the student should too.</p><p><strong>Best for</strong>: Semantic understanding, embedding models</p><p>4. <strong>Task-Specific Distillation</strong></p><p>Optimize the student for <strong>one specific task</strong> rather than general knowledge.</p><p><strong>Example</strong>: Distilling GPT-4 into a specialized code generation model that only writes Python.</p><p><strong>Benefit</strong>: Even smaller models with laser-focused performance</p><p><strong>TL;DR:</strong></p><p>Distillation = a smaller model learning to think like a bigger one. Same intelligence, fraction of the cost.</p><p>Every technique in this blog exists for the same reason frontier LLMs are powerful but expensive, slow, and hardware-hungry. The engineering challenge isn’t building smarter models. It’s making smart models actually usable.</p><p>Here’s how the toolkit stacks up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*7cYb8cVYB4rjaPu_zdP_QA.png" /></figure><p>These aren’t isolated tricks. In a real production system, you’d use several of these together a distilled student model, quantized to INT8, fine-tuned with QLoRA for your domain. That’s the stack behind most LLM products you use today.</p><p>The next time someone says “just use a smaller model” you’ll know exactly what that means and how engineers actually get there.</p><p>#LLM #MachineLearning #AIEngineering #Quantization #LLMOps #QLoRA #ModelCompression #GenerativeAI #DeepLearning #MLEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5563a0e1c9f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Sluggish to Supercharged: The 3 ‘Infinity Stones’ that transformed my Agent’s Speed and Memory]]></title>
            <link>https://medium.com/@harshit-aitch-cmd/from-sluggish-to-supercharged-the-3-infinity-stones-that-transformed-my-chatbot-s-speed-and-0872122fd432?source=rss-a9b2c35f1588------2</link>
            <guid isPermaLink="false">https://medium.com/p/0872122fd432</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Harshit Singh]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 18:26:01 GMT</pubDate>
            <atom:updated>2026-04-11T08:03:59.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*u_cfzRLDW9Unudt0-ONi2Q.jpeg" /></figure><p>In this post, I’ll break down the exact approach I used to <strong>drastically cut response time</strong> and <strong>smartly manage context</strong> without overwhelming the LLM, in simple words- turning a sluggish chatbot into a production-ready system.</p><p>While working on a chatbot for an app, I noticed that each response was experiencing a high latency. This is far from ideal for a production level chatbot, especially one intended for monetization. After some debugging, I realized the issue was in the approach sending the entire chat history as context to the LLM for every message. While this might work for short interactions, it quickly becomes inefficient as conversations grow longer. This approach was causing significant latency issues.</p><p>Another looming issue was the risk of hitting the model’s context length. Each LLM has a fixed token window, and exceeding it can lead to degraded performance, unpredictable behavior, or even truncated input which can cause loss of critical information from the conversation.</p><p>So the core challenge became clear:</p><blockquote><strong><em>LLMs like GPT have a fixed token limit. How can we handle long conversations without losing context or exceeding the model’s memory window?</em></strong></blockquote><p>That’s when I realized that managing context isn’t just one trick. It’s a system. And like any good system, it has its core components.</p><p>After some research and experimentation, I discovered <strong>three essential “infinity stones”</strong> that must be assembled to get the best out of LLMs in long conversations:</p><ol><li><strong>Attention Sink</strong> (Fixed context tokens to anchor the model)</li><li><strong>Summarization &amp; Persistence</strong> (Compress and retain key past information)</li><li><strong>Sliding Window</strong> (Efficiently manage recent messages within token limits)</li></ol><p>When combined, these steps can significantly reduce latency, preserve important context, and keep your chatbot both <strong>fast and memory-aware</strong>. This approach reduced the latency of the responses to half.</p><p>Let’s dive through each step:</p><h3>1. Attention Sink</h3><p>It is a technique used in transformer-based models to anchor the model’s attention to specific tokens or parts of the input to stabilize its focus. By repeating or preserving key context tokens (e.g., instructions or system prompts) at the beginning of every message window, it ensures that the model stays grounded in the initial intent of the conversation.</p><ul><li><em>Helps maintain instruction-following behavior in long or dynamic chat histories.</em></li></ul><h3>2. Summarization and Persistence</h3><p>As chat history grows, it can easily exceed the model’s context limit (e.g., 8k or 16k tokens). To manage this, previous messages are summarized and stored (persisted) in a compressed form. This ensures that the <strong>essence of older context is preserved</strong> without consuming too many tokens. It only gets generated if the tokens consumption of chat crosses the threshold.</p><ul><li><em>Balances memory and performance by compressing older messages while keeping them relevant.</em></li></ul><h3>3. Sliding Window for Context</h3><p>Instead of feeding the entire conversation history each time, a sliding window approach includes only the <strong>most recent N tokens</strong> along with the attention sink and any summarized past. As new user messages come in, older ones are pushed out, keeping the input size within the token limit.</p><ul><li><em>Ensures real-time responsiveness while adhering to the model’s token constraints.</em></li></ul><p>The following flowchart illustrates the approach</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-J-KMak9EZhqmgzTXNIE5Q.png" /></figure><h4>Here’s a simplified but realistic example from a customer feedback chatbot.</h4><blockquote><em>System: You are a helpful AI assistant that summarizes customer feedback on e-commerce products in clear, concise sentences.</em></blockquote><blockquote><em>User: I really liked the camera. The battery life is decent, and the image quality is great for the price.</em></blockquote><blockquote><em>Assistant: Got it. You liked the camera’s image quality and found the battery acceptable for the price.</em></blockquote><blockquote><em>User: The delivery took longer than expected. Also, I received the package with slight damage on the box.</em></blockquote><blockquote><em>Assistant: Understood. There was a delivery delay and minor damage to the packaging.</em></blockquote><p><em>… (10 more messages followed)</em></p><p><strong>Let’s assume we’ve hit ~2000 tokens and now need to prepare the next input window.</strong></p><h4>Input to Model (Using Attention Sink + Summarization + Sliding Window)</h4><p><strong>[ATTENTION_SINK] </strong>You are a helpful AI assistant that summarizes customer feedback on e-commerce products in clear, concise sentences.</p><p><strong>[SUMMARY_OF_PREVIOUS]</strong></p><ol><li>Camera quality praised.</li><li>Battery acceptable for price.</li><li>Delivery was delayed.</li><li>Minor box damage reported.</li></ol><p><strong>[RECENT_SLIDING_WINDOW_CHAT] </strong>User: Also, the headphone that came with it is pretty average. I expected better sound quality. Assistant: Thanks. You feel the headphones were average and lacked good sound quality. User: But the customer support team was helpful and quickly initiated a replacement.\</p><h3>Code: Putting It All Together</h3><pre>from langchain.schema import AIMessage, HumanMessage<br>import openai<br>import boto3<br>from datetime import datetime<br>import tiktoken<br><br># === Constants for Context Management ===<br>ATTENTION_SINK_TOKENS = 5                   # Number of tokens to preserve as fixed context (instruction anchor)<br>SLIDING_WINDOW_TOKENS = 1000                # Max tokens allowed in the recent message sliding window<br>SUMMARY_TRIGGER_THRESHOLD = 2000            # Token threshold to trigger summarization of older messages<br><br># === DynamoDB Setup for Storing Summaries ===<br>dynamodb = boto3.client(&quot;dynamodb&quot;)<br>SUMMARY_TABLE_NAME = &quot;UserSummaries&quot;<br>encoding = tiktoken.encoding_for_model(&quot;gpt-3.5-turbo&quot;)<br><br># === Utility: Count number of tokens in text using the tokenizer ===<br>def count_tokens(text):<br>    return len(encoding.encode(text))<br><br># === Summarize long conversations using GPT-3.5 Turbo ===<br>def summarize_with_gpt(text):<br>    messages = [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You summarize conversations.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Summarize this conversation:\n\n{text}&quot;}<br>    ]<br>    response = openai.ChatCompletion.create(<br>        model=&quot;gpt-3.5-turbo&quot;,  # Or replace with llm.invoke if integrating with LangChain LLM<br>        messages=messages,<br>        temperature=0.5<br>    )<br>    return response.choices[0].message.content.strip()<br><br># === Store generated summary in DynamoDB for a specific user ===<br>def store_summary_in_db(user_id, summary):<br>    table.update_item(<br>        Key={&quot;UserId&quot;: user_id},<br>        UpdateExpression=&quot;SET Summary = :s, UpdatedAt = :t&quot;,<br>        ExpressionAttributeValues={<br>            &quot;:s&quot;: summary,<br>            &quot;:t&quot;: datetime.now().isoformat()<br>        }<br>    )<br><br># === Retrieve stored summary for a user from DynamoDB ===<br>def get_summary_from_db(user_id):<br>    try:<br>        response = table.get_item(Key={&quot;UserId&quot;: user_id})<br>        return response[&quot;Item&quot;].get(&quot;Summary&quot;, &quot;&quot;) if &quot;Item&quot; in response else &quot;&quot;<br>    except Exception as e:<br>        return &quot;&quot;<br><br># === Main chat function implementing context strategy ===<br>def chat(user_input, user_id):<br>    history = DynamoDBChatMessageHistory(table_name=&quot;SessionTable&quot;, session_id=user_id)<br>    all_messages = history.messages<br><br>    # Step 1: Count total tokens used in conversation history<br>    total_token_count = sum(count_tokens(m.content) for m in all_messages)<br><br>    # Step 2: Extract attention sink (first few tokens of the very first message)<br>    attention_sink = &quot;&quot;<br>    if all_messages:<br>        attention_sink = &quot; &quot;.join(all_messages[0].content.split()[:ATTENTION_SINK_TOKENS])<br><br>    # Step 3: Retrieve or generate summary if history is too long<br>    summary = get_summary_from_db(user_id)<br>    if total_token_count &gt; SUMMARY_TRIGGER_THRESHOLD and not summary:<br>        messages_to_summarize = &quot;\n&quot;.join([m.content for m in all_messages[:-10]])  # Skip last 10 messages<br>        summary = summarize_with_gpt(messages_to_summarize)<br>        store_summary_in_db(user_id, summary)<br>        all_messages = all_messages[-10:]  # Retain only the latest few for sliding window<br><br>    # Step 4: Apply sliding window to fit recent messages within token limits<br>    sliding_window = []<br>    token_count = 0<br><br>    for message in reversed(all_messages):<br>        tokens = count_tokens(message.content)<br>        if token_count + tokens &lt;= SLIDING_WINDOW_TOKENS:<br>            sliding_window.insert(0, message)<br>            token_count += tokens<br>        else:<br>            break<br><br>    # Step 5: Construct final prompt with attention sink, summary, and recent history<br>    final_messages = []<br>    final_messages.append(HumanMessage(content=f&quot;(Attention) {attention_sink}&quot;))<br>    if summary:<br>        final_messages.append(HumanMessage(content=f&quot;(Summary) {summary}&quot;))<br>    final_messages.extend(sliding_window)<br>    final_messages.append(HumanMessage(content=user_input))<br><br>    # Step 6: Get bot response from LLM<br>    try:<br>        response = llm.invoke(final_messages)<br>        bot_reply = response.content<br>    except Exception as e:<br>        return &quot;Sorry, there was an issue processing your request.&quot;, history<br><br>    # Step 7: Persist new messages to conversation history<br>    history.add_message(HumanMessage(content=user_input))<br>    history.add_message(AIMessage(content=bot_reply))<br><br>    return bot_reply, history</pre><h3>Why this works</h3><ul><li>You retain <strong>recent memory</strong> and <strong>long-term context</strong>.</li><li>Keeps you under token limits.</li><li>Makes summarization <strong>on-demand</strong>, not constant.</li><li>Scalable and efficient.</li></ul><h3>Who Can Use This?</h3><ul><li><strong>SaaS product teams</strong> building AI-powered customer chatbots</li><li><strong>Developers</strong> working on AI agents that need to remember ongoing multi-turn dialogues</li><li><strong>Startups</strong> needing scalable, fast, and cost-efficient LLM usage in production</li><li><strong>Researchers</strong> testing dialogue systems over long conversations.</li></ul><h3>Wrapping Up</h3><p>Managing context in LLM applications isn’t just about avoiding token limits it’s about building systems that are <strong>fast, memory-efficient, and scalable</strong>.</p><p>By combining <strong>Attention Sink</strong>, <strong>Summarization</strong>, and <strong>Sliding Window</strong>, you create a powerful framework for handling long conversations without degrading performance or blowing up your API bill.</p><p>This approach not only reduced our response time by over 50%, but also made the chatbot far more stable and context-aware.</p><p>If you’re working on AI chatbots or agent-like systems, give this method a try and feel free to tweak it to suit your app’s needs.</p><p>I’d love to hear how you’re managing context in your LLM-based apps. Connect with me on <a href="https://www.linkedin.com/in/wharshitsingh/">LinkedIn</a> or drop a comment below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0872122fd432" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>