<?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 Ankit Goel on Medium]]></title>
        <description><![CDATA[Stories by Ankit Goel on Medium]]></description>
        <link>https://medium.com/@ankitgoelcmu?source=rss-de94f8b1bcf4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*AslCDoZENMtNGWJ-</url>
            <title>Stories by Ankit Goel on Medium</title>
            <link>https://medium.com/@ankitgoelcmu?source=rss-de94f8b1bcf4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:47:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankitgoelcmu/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[Speculative Decoding, Disaggregation, and How to Pick the Right LLM Inference Optimizations]]></title>
            <link>https://levelup.gitconnected.com/speculative-decoding-disaggregation-and-how-to-pick-the-right-llm-inference-optimizations-081c110cd3d3?source=rss-de94f8b1bcf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/081c110cd3d3</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ankit Goel]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 21:56:50 GMT</pubDate>
            <atom:updated>2026-11-11T16:09:05.728Z</atom:updated>
            <content:encoded><![CDATA[<h4>LLM Inference Optimization, Part 3 of 3. Generate faster, split the phases, and measure what actually matters.</h4><p><a href="https://medium.com/p/401c9fb743bb"><strong>Part 1</strong></a> covered prefill vs decode, the KV cache, GQA and PagedAttention. <a href="https://medium.com/p/3855fc1784f6"><strong>Part 2</strong></a> covered FlashAttention, prefix caching, continuous batching and chunked prefill.</p><p>This final part covers the last two techniques, then pulls everything together: a cheat sheet, how to choose, what to measure, and a worked example for an AI agent.</p><h3>Key takeaways</h3><ul><li>Speculative decoding lets a small model guess ahead while the big model checks the guesses in one pass. Same output distribution, lower latency.</li><li>Disaggregation runs prefill and decode on separate GPU pools, so long prompts stop stalling token streaming.</li><li>Start from your bottleneck, not from the list of techniques.</li><li>For agents, the metric that matters is cost per successful task, not tokens per second.</li></ul><h3>7. Speculative decoding: guess ahead, verify in one pass</h3><p>Decode is slow because a big model writes one token at a time. Speculative decoding lets a small, fast draft model guess ahead:</p><ol><li>The draft model proposes the next few tokens.</li><li>The large target model scores all of them in one forward pass.</li><li>An acceptance rule keeps a prefix of the draft tokens. Each one is accepted with a probability based on how the draft and target models rate it.</li><li>At the first rejected token, the target model samples a replacement from a correction distribution. Then drafting starts again.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRWVNoyinjniwELHfdpg9w.png" /></figure><p>With this sampling rule, the output follows the same distribution as the large model alone (Leviathan et al., ICML 2023). The small model speeds things up. It doesn’t decide the answer.</p><p><strong>If the big model checks everything, where does the speedup come from?</strong> From the fact that checking 5 tokens costs the big model about the same as generating 1.</p><ul><li><strong>Decode is memory-bound.</strong> Each step, the big model reads all its weights from memory, and that read is the slow part. The math for 1 token or 5 tokens fits in the same pass, because the GPU has spare compute while it waits on memory.</li><li><strong>So verification is nearly free.</strong> Scoring 5 draft tokens works like a tiny prefill: one weight read, five tokens processed in parallel.</li><li><strong>The draft model is cheap.</strong> It’s much smaller, so its 5 sequential steps cost a fraction of one big-model step.</li></ul><p>In the diagram above, one big-model pass produced 4 tokens (3 accepted plus 1 resampled) instead of 1. Even if every draft token is rejected, you still get 1 token from the target model, so the worst case is normal speed plus the draft model’s cost.</p><p>This also explains when it stops helping. At large batch sizes the GPU is already compute-bound, so there’s no spare compute for checking drafts. And if the draft is rejected often, the wasted guesses eat the gain.</p><p><strong>Wait, doesn’t an LLM generate one token at a time?</strong> It does, when it’s writing. It can’t pick token 2 until it has picked token 1. But the big model isn’t writing these 5 tokens. The draft model already wrote them. The big model is reading them, and reading a sequence that already exists can happen all at once. That’s exactly what prefill does with your prompt. It’s like a teacher grading a finished paragraph: the student wrote it word by word, but the teacher can check every word in one read.</p><p><strong>What “a prediction at every position” means.</strong> Say your prompt is 5 tokens: “The alert came from the”. In one prefill pass, the model processes all 5 positions. At each position it predicts the next token, using only the tokens up to that point:</p><ul><li>Position 1 sees “The” → predicts token 2</li><li>Position 2 sees “The alert” → predicts token 3</li><li>Position 3 sees “The alert came” → predicts token 4</li><li>Position 4 sees “The alert came from” → predicts token 5</li><li>Position 5 sees “The alert came from the” → predicts token 6</li></ul><p>So one pass gives 5 predictions. In normal prefill only the last one matters: it starts the answer. The others are thrown away. The model still has to process every position, because each one’s K and V go into the KV cache.</p><p>Speculative decoding simply keeps all of those predictions. The big model reads the prompt plus the 5 draft tokens. The prediction at the last prompt position grades draft token 1. The prediction at draft token 1 grades draft token 2, and so on. The prediction at draft token 5 is the bonus token you get when every draft is accepted.</p><p><strong>The grading rule, step by step:</strong></p><ol><li><strong>Compare at each position, left to right.</strong> For each draft token, look at how likely the draft model thought it was (q), and how likely the big model thinks it is (p).</li><li><strong>Accept or reject.</strong> If the big model likes the token at least as much as the draft did (p ≥ q), keep it. If not, keep it with probability p ÷ q.</li><li><strong>Stop at the first rejection.</strong> Throw away that token and every draft token after it, since they were built on a token we’re not keeping.</li><li><strong>Fill the gap from the big model.</strong> Sample a replacement from the part of the big model’s distribution the draft under-weighted. If every draft token was accepted, take one bonus token from the big model’s prediction at the last position.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTSFwqgrw_goK01RnBAZTQ.png" /></figure><p>The big model then samples “in” for position 4, and the next round of drafting starts from “The alert came in”.</p><p>With greedy decoding (always pick the top token), the rule is simpler: keep a draft token only if it’s exactly the big model’s top choice. Either way, the output comes out as if the big model had generated every token itself.</p><ul><li><strong>Win:</strong> lower latency per request, especially for long outputs.</li><li><strong>When it doesn’t help:</strong> if the draft is often wrong, the checking work is wasted. It also helps less when the GPU is already compute-bound or heavily batched. It works best with a cheap draft model and a high acceptance rate.</li></ul><h3>8. Disaggregated prefill and decode: separate hardware for each phase</h3><p>Why split them? Because the two phases use the GPU in opposite ways.</p><ul><li><strong>Prefill</strong> loads each weight once and uses it for every prompt token. A 10,000-token prompt does 10,000 tokens’ worth of math for each weight it reads. The GPU’s cores stay busy, so prefill is usually limited by compute.</li><li><strong>Decode</strong> loads every weight to produce just one token per request. For a 70B model in FP16, that’s about 140 GB read from memory on every step. The cores finish the math quickly, then sit waiting for the next read, so decode is usually limited by memory bandwidth.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-5rvOSVt0GX2EjXTzQ44w.png" /></figure><p>On shared GPUs, the phases fight. A long prefill takes over the GPU’s compute for a while. Every decode step queued behind it waits, so users in the middle of an answer see their tokens stall. One GPU also can’t be tuned for both: the batch sizes and parallelism that suit prefill don’t suit decode.</p><p>Splitting fixes both. Prefill never interrupts decode, and each pool gets the hardware and settings its phase needs. When prefill is done, it hands the KV cache to the decode pool, which streams the answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-9i5RNehsJXU8TSTdIjrg.png" /></figure><ul><li><strong>Win:</strong> each pool can be tuned to its phase, and long prompts stop slowing down token streaming (DistServe).</li><li><strong>Cost:</strong> the KV cache has to move from the prefill pool to the decode pool over the interconnect or network. More infrastructure, more coordination.</li><li><strong>Not automatic:</strong> separate pools pay off only when the workload mix and GPU split justify that transfer and coordination overhead.</li></ul><p><strong>Your workload shape decides the split.</strong> Most workloads lean one of two ways: long input with short output (LISO), or short input with long output (SILO).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPWeURBBfoC-YOmxZe3dqg.png" /></figure><p>In one line: LISO is about reading fast (prefill); SILO is about writing fast (decode). Put your GPUs, and your optimizations, on the side that does the work.</p><h3>Cheat sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bkkmu3_Sybd7LsdoN17wyw.png" /></figure><h3>How to choose</h3><p>Start from your bottleneck, not from the list of techniques:</p><ul><li><strong>High TTFT on repeated prompts</strong> → prefix caching</li><li><strong>High TTFT on long prompts</strong> → efficient attention kernels, chunked prefill</li><li><strong>KV cache memory pressure</strong> → PagedAttention, a GQA model</li><li><strong>Low throughput under concurrency</strong> → continuous batching</li><li><strong>Slow generation of long outputs</strong> → speculative decoding</li><li><strong>Prefill competing with decode</strong> → chunked prefill, disaggregation</li></ul><h3>What to measure</h3><p>An optimization only counts if it moves a metric your application cares about. I’d track these:</p><ul><li><strong>TTFT:</strong> how fast the response starts. Key for chat.</li><li><strong>TPOT:</strong> how fast tokens stream. Key for long outputs.</li><li><strong>End-to-end latency:</strong> total time per response. Key for agents that chain many calls.</li><li><strong>P95/P99 latency:</strong> the slow tail. Averages hide what users feel when the system is busy.</li><li><strong>Throughput:</strong> output tokens or requests per second. Drives cost per request.</li><li><strong>Goodput:</strong> requests or tokens served within your latency targets. Throughput that misses the target doesn’t count.</li><li><strong>GPU memory use:</strong> weights, KV cache and buffers. Tells you how many users fit.</li><li><strong>Cost per completed task:</strong> for agents, the one that matters most.</li></ul><p>An agent might make ten model calls to finish one investigation. A faster model that needs more retries, or gives worse answers, can raise the cost of each successful task.</p><p><strong>How to compare fairly:</strong> hold the model, hardware, precision, prompt and output lengths, concurrency and quality bar constant. Change one setting at a time. Compare P95 TTFT, P95 TPOT, throughput, goodput and cost per successful task.</p><h3>Example: an incident-investigation agent</h3><p>Take an agent that gets an alert, pulls logs, checks metrics, calls diagnostic tools and writes a root-cause report. One investigation means several LLM calls, some with very large contexts. Here’s how I’d apply the techniques:</p><ul><li><strong>Shared context → prefix caching.</strong> System prompt, tool descriptions and runbooks are the same every time. Put them first and cache them.</li><li><strong>Big log dumps → FlashAttention + chunked prefill.</strong> Long inputs get processed efficiently and don’t stall other investigations.</li><li><strong>Many investigations at once → continuous batching + PagedAttention.</strong> More concurrent runs per GPU.</li><li><strong>Long reports → test speculative decoding.</strong> Turn it on only if your benchmarks show a real gain.</li><li><strong>Measure the outcome.</strong> Track completion time, accuracy, cost and failure rate per investigation.</li></ul><p>The goal isn’t maximum tokens per second. It’s the most successful investigations per dollar, within your latency and quality targets.</p><p>One limit to keep in mind: these optimizations work at the serving layer. They won’t fix slow tool calls, poor retrieval or an agent stuck in a loop. Those need fixing in the agent itself.</p><h3>The catch: faster isn’t always better</h3><p>A common mistake is to turn everything on. These techniques interact:</p><ul><li>Speculative decoding speeds up one request but uses compute that could serve other users.</li><li>Continuous batching raises throughput but can slow down each individual request.</li><li>KV and prefix caching save compute but take memory that could hold more sessions. With a low hit rate, that memory is wasted.</li></ul><p>Memory a cache uses isn’t automatically wasted. If it saves enough compute, it’s a good trade. Judge a cache by its hit rate and what it saves, not by its size.</p><p>The right setup depends on what you’re optimizing for:</p><ul><li>A real-time chat assistant cares about latency.</li><li>A document-processing pipeline cares about throughput.</li><li>A long-running agent cares about cost per successful task.</li></ul><p>There’s no single best configuration. Benchmark against your own workload.</p><h3>Final thoughts</h3><p>Inference optimization doesn’t make a model smarter. It makes it practical to run:</p><ul><li>KV cache skips recomputing past tokens.</li><li>GQA makes that cache smaller inside the model.</li><li>PagedAttention wastes less memory.</li><li>FlashAttention moves less data.</li><li>Prefix caching reuses shared prompts.</li><li>Continuous batching keeps the GPU busy.</li><li>Chunked prefill stops long prompts from blocking others.</li><li>Speculative decoding speeds up generation when the draft is accepted often.</li><li>Disaggregation gives each phase hardware suited to it.</li></ul><p>The fastest single request doesn’t make the fastest, cheapest or most reliable AI application. Optimize the whole workload. For agents, measure what counts: successful tasks within your latency, quality and cost limits.</p><h3>Further reading</h3><ul><li>Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (SOSP 2023)</li><li>Dao et al., FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (NeurIPS 2022)</li><li>Leviathan et al., Fast Inference from Transformers via Speculative Decoding (ICML 2023)</li><li>Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (EMNLP 2023)</li><li>Yu et al., Orca: A Distributed Serving System for Transformer-Based Generative Models (OSDI 2022)</li><li>Agrawal et al., Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve (OSDI 2024)</li><li>Zhong et al., DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving (OSDI 2024)</li><li>Zheng et al., SGLang: Efficient Execution of Structured Language Model Programs (introduces RadixAttention)</li><li>vLLM documentation: scheduling, prefix caching and chunked prefill</li><li>NVIDIA TensorRT-LLM documentation: inference optimization and serving</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=081c110cd3d3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/speculative-decoding-disaggregation-and-how-to-pick-the-right-llm-inference-optimizations-081c110cd3d3">Speculative Decoding, Disaggregation, and How to Pick the Right LLM Inference Optimizations</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FlashAttention, Prefix Caching and Continuous Batching: How LLM Servers Keep the GPU Busy]]></title>
            <link>https://levelup.gitconnected.com/flashattention-prefix-caching-and-continuous-batching-how-llm-servers-keep-the-gpu-busy-3855fc1784f6?source=rss-de94f8b1bcf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3855fc1784f6</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Ankit Goel]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 21:54:58 GMT</pubDate>
            <atom:updated>2026-11-11T16:09:22.812Z</atom:updated>
            <content:encoded><![CDATA[<h4>LLM Inference Optimization, Part 2 of 3. Move less data, reuse shared prompts, and stop one request from blocking everyone else.</h4><p>In <a href="https://medium.com/p/401c9fb743bb"><strong>Part 1</strong></a>, we split inference into two phases. Prefill reads the prompt and is usually compute-bound. Decode writes the answer one token at a time and is usually memory-bound. We then looked at the KV cache, GQA and PagedAttention: how to avoid recomputing the past and how to use cache memory well.</p><p>This part covers four more techniques. Two reduce work (FlashAttention, prefix caching). Two keep the GPU busy under real traffic (continuous batching, chunked prefill).</p><h3>Key takeaways</h3><ul><li>FlashAttention speeds up the attention math by moving less data. PagedAttention organizes the cache. You want both.</li><li>Prefix caching reuses work across requests, but only for exact token matches. Put stable content first.</li><li>Continuous batching fills empty slots on every decode step instead of waiting for the slowest request.</li><li>Chunked prefill stops one huge prompt from stalling everyone else’s tokens.</li></ul><h3>3. FlashAttention: move less data</h3><p>GPUs have large but slower high-bandwidth memory (HBM), and small but very fast on-chip SRAM. A naive attention implementation writes the full attention matrix out to HBM and reads it back. That traffic, not the math, is often the bottleneck.</p><p>FlashAttention (Dao et al., NeurIPS 2022) works in tiles that fit in SRAM and uses an online softmax, so the full matrix is never stored in HBM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PR_flGpj1XNx0NHOtHU6Yw.png" /></figure><ul><li><strong>Win:</strong> faster attention and less memory, with the same result (exact, apart from normal floating-point differences).</li><li><strong>Not the same as PagedAttention:</strong> FlashAttention speeds up the attention math. PagedAttention organizes the KV cache. Production engines use both.</li></ul><h3>4. Prefix caching: reuse work across requests</h3><p>Most enterprise prompts start the same way: system prompt, policies, tool descriptions. Only the last part changes per user.</p><p>Prefix caching keeps the KV cache for a shared prompt prefix and reuses it for any request that starts with the same tokens. If 1,000 requests share a 4,000-token system prompt, in the best case that prefill runs once instead of 1,000 times. In practice, cache capacity, eviction and tenant isolation decide how much actually gets reused. vLLM’s automatic prefix caching and SGLang’s RadixAttention are two common implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OjlwRGLi8toZq81tI9X_g.png" /></figure><ul><li><strong>Win:</strong> less prefill work and a faster time to first token.</li><li><strong>Catch:</strong> the match is exact, token by token. Put stable content first and changing content last: system instructions → shared context → user-specific info → current request.</li><li><strong>Not semantic caching.</strong> Prefix caching reuses computation and the model still writes a fresh answer. Semantic caching reuses a previous answer for a similar question. That carries real correctness risk.</li></ul><p><strong>What about prompt caching?</strong> It’s the same idea, offered as an API feature. Hosted model APIs such as Anthropic, OpenAI and Google Gemini let you reuse a long, stable prompt prefix, which can mean faster responses and cheaper input tokens. Eligibility, pricing, retention and whether you must mark the cached part all vary by provider and change often, so check the current docs. The rule is the same: stable content first, changing content last.</p><h3>5. Continuous batching: don’t wait for the slowest request</h3><p>Picture a restaurant that won’t seat anyone new until every diner at the table has finished. That’s static batching. One request needs 20 output tokens, another needs 2,000. When the short ones finish, their slots sit empty until the long one is done.</p><p>Continuous batching schedules at the level of each decode step, known as iteration-level scheduling, from the Orca paper. When a request finishes, a waiting one takes its slot on the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0M-57cSjuqoTui7tvhoPg.png" /></figure><ul><li><strong>Win:</strong> much higher GPU use and throughput. That matters when a support bot’s short replies share hardware with a coding agent’s long ones.</li><li><strong>Cost:</strong> a more complex scheduler. More concurrent requests also means more competition for compute and KV cache, so each request can get a little slower.</li></ul><h3>6. Chunked prefill: don’t let one big prompt block everyone</h3><p>Hundreds of users send short prompts. Then one user sends a 100,000-token document. If the engine prefills it in one go, everyone else’s decode stalls behind it.</p><p>Chunked prefill splits a large prompt into pieces. The scheduler mixes those pieces in with other users’ decode steps, so long prompt processing stops competing head-to-head with ongoing decode for the same GPU (Sarathi-Serve).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R23-v79_e1W7L_t4Z84eMQ.png" /></figure><ul><li><strong>Win:</strong> smoother latency for everyone under mixed workloads.</li><li><strong>Tuning:</strong> small chunks add scheduling overhead. Large chunks leave less room to interleave. The right size depends on your traffic, hardware and latency targets.</li></ul><h3>Wrapping up Part 2</h3><ul><li>FlashAttention moves less data, so attention runs faster on long prompts.</li><li>Prefix caching reuses shared prompts and cuts time to first token.</li><li>Continuous batching keeps the GPU busy.</li><li>Chunked prefill stops long prompts from blocking others.</li></ul><p>None of these is free. Caches take memory, bigger batches can slow each request, and chunk sizes need tuning. Measure against your own traffic.</p><p><strong>Next in this series:</strong> <a href="https://medium.com/p/081c110cd3d3">Part 3</a> covers speculative decoding, disaggregated prefill and decode, and how to choose and measure the right mix for your workload, including AI agents.</p><p><strong>Further reading:</strong> Dao et al., <em>FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness</em> (NeurIPS 2022). Yu et al., <em>Orca: A Distributed Serving System for Transformer-Based Generative Models</em> (OSDI 2022). Agrawal et al., <em>Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve</em> (OSDI 2024). Zheng et al., <em>SGLang: Efficient Execution of Structured Language Model Programs</em> (RadixAttention). vLLM docs on prefix caching and chunked prefill.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3855fc1784f6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/flashattention-prefix-caching-and-continuous-batching-how-llm-servers-keep-the-gpu-busy-3855fc1784f6">FlashAttention, Prefix Caching and Continuous Batching: How LLM Servers Keep the GPU Busy</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why LLM Inference Is Slow: Prefill, Decode and the KV Cache]]></title>
            <link>https://levelup.gitconnected.com/why-llm-inference-is-slow-prefill-decode-and-the-kv-cache-401c9fb743bb?source=rss-de94f8b1bcf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/401c9fb743bb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ankit Goel]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 21:52:47 GMT</pubDate>
            <atom:updated>2026-11-11T16:09:38.318Z</atom:updated>
            <content:encoded><![CDATA[<h4>LLM Inference Optimization, Part 1 of 3. Training gets the headlines. Serving is where the bill comes due.</h4><p>A model can top every benchmark and still be too slow or too expensive to ship. Every request has to read the prompt, generate tokens, hold state in GPU memory, and share the hardware with everyone else.</p><p>That’s the job of inference optimization. It doesn’t make the model smarter. It makes what the model already knows practical to serve.</p><p>This is a 3-part series on eight techniques that make LLMs cheaper and faster in production:</p><ul><li><strong>Part 1 (this post):</strong> how inference actually works, the KV cache, GQA and PagedAttention.</li><li><a href="https://medium.com/p/3855fc1784f6"><strong>Part 2</strong></a><strong>:</strong> FlashAttention, prefix caching, continuous batching and chunked prefill.</li><li><a href="https://medium.com/p/081c110cd3d3"><strong>Part 3</strong></a><strong>:</strong> speculative decoding, disaggregated prefill/decode, and how to pick what to turn on.</li></ul><h3>Key takeaways</h3><ul><li>Inference has two phases: prefill (read the prompt) and decode (write the answer, one token at a time). They often hit different bottlenecks.</li><li>The KV cache avoids recomputing the past, but it costs memory, and that memory often decides how many users fit on one GPU.</li><li>GQA shrinks the cache inside the model. PagedAttention stops wasting the memory you have.</li><li>Every optimization trades something. Speed for one user can cost throughput for everyone else.</li></ul><h3>First, what actually happens: prefill and decode</h3><p>Every LLM request runs in two phases.</p><p><strong>Prefill reads the prompt.</strong> Send a 10,000-token document and ask for a summary, and the model first processes all 10,000 tokens. It works on all prompt positions in parallel, so prefill is often compute-bound, especially for long prompts.</p><p><strong>Decode writes the answer, one token at a time:</strong> “The”, then “document”, then “describes”. Each token depends on the ones before it, so this part is sequential. At small batch sizes, decode is often memory-bandwidth-bound: the GPU spends more time moving weights and cache than doing math. The real bottleneck depends on the model, hardware, batch size and workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4Iu5uQH0fhEepEGo_DW9Q.png" /></figure><p><strong>Why prefill is compute-heavy and decode is memory-heavy.</strong> It comes down to how much math the GPU does for each byte it loads from memory. This is called arithmetic intensity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AtI6mYagXPrqdXlY1-C81w.png" /></figure><p>To make it concrete: a 70B model in FP16 has about 140 GB of weights. Every decode step reads all of them to produce one token per request.</p><p>That’s also why batching matters so much for decode. One pass over the weights serves every request in the batch, so arithmetic intensity rises with batch size. At large batches, decode can become compute-bound too.</p><p>Three metrics fall out of this:</p><ul><li><strong>Time to first token (TTFT):</strong> how long the user waits before anything appears. Mostly prefill.</li><li><strong>Time per output token (TPOT):</strong> how fast the rest of the answer streams. Mostly decode.</li><li><strong>End-to-end latency:</strong> total time for the full response.</li></ul><p>Keep the split in mind. A fix for prefill may do nothing for decode, and the other way round.</p><h3>1. KV cache: don’t recompute the past</h3><p>To generate token 5,001, the model needs the key and value (K/V) vectors of the 5,000 tokens before it. A naive engine would recompute them on every step. That’s like rereading a whole book before each new sentence.</p><p>The KV cache stores those vectors after prefill and reuses them on every decode step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fyv2Zth1BNtaamgzgSnbjw.png" /></figure><ul><li><strong>Win:</strong> past tokens’ K/V vectors are computed once, not on every step. Attention still reads those cached vectors for each new token, so the work per token shrinks but doesn’t disappear.</li><li><strong>Cost:</strong> memory. The cache grows with context length and with the number of concurrent requests. For long-running agents, it often decides how many users fit on one GPU.</li></ul><p><strong>How fast does it grow?</strong> KV cache size = 2 (K and V) × layers × KV heads × head dim × bytes per value × tokens × concurrent requests. It’s linear in both context length and users:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlcidzMYdzFKQ67nTPbV8A.png" /></figure><p>One long request fits easily. Thirty-two users with 8K context each need more KV cache than a whole 80 GB GPU holds, before counting the model weights.</p><p><strong>Linear vs quadratic: what grows how.</strong> The KV cache grows linearly with context length, O(n): one more token, one more set of K and V vectors. Attention compute grows faster. Every token scores every earlier token, so a prompt of n tokens needs about n × n scores, O(n²).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0L_1q6JtJGRCPEYeT8hrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sb-w-4mX260-9g6aQ3CCfQ.png" /></figure><p>What this means in practice:</p><ul><li><strong>Long prompts hurt TTFT more than linearly.</strong> Double the prompt and prefill attention work roughly quadruples. That’s why FlashAttention and chunked prefill (Part 2) matter most for long contexts.</li><li><strong>Long contexts slow down every decode step too.</strong> Each new token reads a longer cache, so TPOT creeps up as the conversation grows.</li><li><strong>At short contexts, attention isn’t the main cost.</strong> The model’s other layers (projections and MLPs) grow linearly and dominate. The n² term takes over only as contexts get long.</li><li><strong>Without a KV cache it’s worse.</strong> Each step would recompute K and V for the whole prefix, so generation cost grows faster still.</li></ul><h3>Related: grouped-query attention (GQA)</h3><p>GQA attacks the cache-size problem from inside the model. In standard multi-head attention (MHA), every query head has its own key and value head, and each one adds to the KV cache. GQA lets a group of query heads share one K/V head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOTeBa1GCvd4_UuJ-OQIGA.png" /></figure><ul><li><strong>Win:</strong> the KV cache shrinks by the group size. Llama 3 70B has 64 query heads but only 8 KV heads, so it needs about 8× less KV cache memory than an equivalent MHA model (same layers, head size and sequence length). That’s the cache only. The model weights don’t shrink.</li><li><strong>The spectrum:</strong> multi-query attention (MQA) goes all the way and shares one K/V head across every query head. It has the smallest cache and may lose some quality. GQA sits in between and aims to keep quality close to MHA.</li><li><strong>Not a serving switch:</strong> GQA is set when the model is built. You get it by choosing a GQA model (Llama 2 70B, Llama 3, Mistral 7B), not by turning on a flag in your inference engine. The GQA paper (Ainslie et al., EMNLP 2023) also shows how to convert an existing MHA model with a small amount of extra training.</li><li><strong>Stacks with the rest:</strong> GQA makes each token’s cache smaller. PagedAttention and prefix caching then manage and reuse that smaller cache.</li></ul><h3>2. PagedAttention: stop wasting cache memory</h3><p>Some earlier KV cache allocators reserved one contiguous block of GPU memory per request, sized for its maximum possible length. When a request finished early, most of that space sat empty.</p><p>PagedAttention, introduced with vLLM (Kwon et al., SOSP 2023), splits the KV cache into small fixed-size blocks, like pages in an OS. Blocks are handed out as tokens arrive and can live anywhere in memory. A block table maps each request’s logical blocks to physical ones, so they don’t need to sit side by side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r07Jj0ZPVE0CHAjiJrNnWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vASg6j7ukqxnZsNz8mDdw.png" /></figure><ul><li><strong>Win:</strong> far less wasted memory, so more requests fit at once and throughput goes up.</li><li><strong>Best for:</strong> many concurrent users, long contexts, outputs of very different lengths.</li><li>It doesn’t change the model. It only changes how cache memory is managed.</li></ul><h3>Wrapping up Part 1</h3><ul><li>Prefill reads the prompt and is usually compute-bound. Decode writes the answer and is usually memory-bound.</li><li>The KV cache skips recomputing past tokens, but its memory grows with context and users.</li><li>GQA makes that cache smaller inside the model.</li><li>PagedAttention wastes less of the memory you have.</li></ul><p><strong>Next in this series:</strong> <a href="https://medium.com/p/3855fc1784f6">Part 2</a> covers FlashAttention, prefix caching, continuous batching and chunked prefill: moving less data, reusing prompts and keeping the GPU busy. <a href="https://medium.com/p/081c110cd3d3">Part 3</a> covers speculative decoding, disaggregation, and how to choose what to turn on.</p><p><strong>Further reading:</strong> Kwon et al., <em>Efficient Memory Management for Large Language Model Serving with PagedAttention</em> (SOSP 2023). Ainslie et al., <em>GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints</em> (EMNLP 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=401c9fb743bb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/why-llm-inference-is-slow-prefill-decode-and-the-kv-cache-401c9fb743bb">Why LLM Inference Is Slow: Prefill, Decode and the KV Cache</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent Memory: What to Keep, Where to Keep It, and When to Read It]]></title>
            <link>https://levelup.gitconnected.com/agent-memory-what-to-keep-where-to-keep-it-and-when-to-read-it-1cdfecb455be?source=rss-de94f8b1bcf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cdfecb455be</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ankit Goel]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 18:16:21 GMT</pubDate>
            <atom:updated>2026-11-11T16:10:18.422Z</atom:updated>
            <content:encoded><![CDATA[<h4>Most agents start every session from scratch. Here’s how to give yours a memory without stuffing everything into the prompt.</h4><h3>Key takeaways</h3><ul><li>The model has no automatic memory. Your application decides what history and stored knowledge to send it.</li><li>Memory comes in two tiers: <strong>short-term</strong> (this thread or task) and <strong>long-term</strong> (reused across threads and sessions).</li><li>Long-term memory has three kinds: <strong>semantic</strong> (facts), <strong>episodic</strong> (what happened), <strong>procedural</strong> (how to do things).</li><li>The production pattern is simple: <strong>read before reasoning, write after acting.</strong></li><li>Never retrieve everything. Authorize, filter, rank, trim to a token budget.</li><li>Memory needs a lifecycle: offload it, expire it, compact it, promote only what’s earned it.</li></ul><h3>Why agents need memory</h3><p>The model has no automatic memory of previous calls. Your application has to supply the relevant history, or retrieve what it stored, every time.</p><p>That works for a chatbot. It breaks for agents:</p><ul><li><strong>Sessions end.</strong> Close the run and the agent forgets your preferences, the fix that worked, the mistake it made.</li><li><strong>Context windows fill up.</strong> Long runs pile up tool outputs until the model loses track of the goal.</li><li><strong>Bigger isn’t better.</strong> Models pay less attention to what’s buried in the middle of a long prompt. More context can mean worse answers.</li></ul><p>Take <strong>CyberGuard</strong>, my agent that turns threat intel into Sigma detection rules. Without memory, every run starts cold. It doesn’t know I want rules in test status. It doesn&#39;t know a similar attack took two validation attempts last week. It can&#39;t reuse the fix that worked.</p><p>Here’s the pattern, as an illustrative run:</p><ul><li><strong>Monday:</strong> CyberGuard drafts a rule. Validation fails. It takes two attempts to find the fix.</li><li><strong>Wednesday, no memory:</strong> a similar attack comes in. Same mistake, same two attempts, same tokens burned.</li><li><strong>Wednesday, with memory:</strong> it retrieves Monday’s episode, applies the saved fix, and passes on the first try.</li></ul><p>The fix isn’t a bigger context window. It’s deciding <strong>what to keep, where to keep it, and when to read it back.</strong></p><h3>At a glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anbbIeBjm29p7Dh5SXuhGw.png" /></figure><p>Short-term memory is scoped to one thread, even when a checkpointer saves it. Long-term memory splits by what it holds and how you find it. The one arrow that matters: extract what’s worth keeping before the thread’s state goes away.</p><h3>Short-term memory: the current thread</h3><p>Short-term memory belongs to the current thread or task. Also called working memory.</p><ul><li>The message history for this session</li><li>Intermediate tool results</li><li>A draft rule halfway through revision</li><li>The agent’s todo list</li></ul><p>It lives in the context window and the graph’s state. A checkpointer can persist it across invocations, but it’s still scoped to this thread. <strong>The difference is scope, not lifespan:</strong> long-term memory is what you reuse across threads and sessions.</p><p>Two jobs here are easy to mix up:</p><ul><li><strong>Managing it:</strong> keeping it small enough to fit. Summarization middleware (deepagents has one) compresses history when it gets too long.</li><li><strong>Persisting it:</strong> saving it so it survives a crash or restart. In LangGraph, that’s a <strong>checkpointer</strong>. It saves thread state after each step, so a run can resume where it stopped.</li></ul><p>Compressing context doesn’t save it. Saving it doesn’t compress it. You usually need both.</p><h3>Long-term memory: three kinds</h3><p>Long-term memory survives across sessions. It splits into three kinds, borrowed from cognitive science. Each answers a different question and is retrieved a different way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBiWgikjIqDebgcnpJdkKQ.png" /></figure><p><strong>Semantic</strong> memory is facts, cut loose from when you learned them. It’s the same idea as RAG over documents, applied to facts about the user and the domain.</p><p><strong>Episodic</strong> memory is a timeline: conversations, decisions, tool calls, outcomes, errors. It’s how an agent learns from precedent.</p><p><strong>Procedural</strong> memory is skill. It lives in one of two places:</p><ul><li><strong>In the weights.</strong> Fine-tuning bakes the skill in. The model doesn’t look up how to write a Sigma rule. It just knows.</li><li><strong>In a playbook.</strong> Versioned prompts, policies or skill files the agent reads when needed. Easier to edit, review and roll back.</li></ul><p>Over time, some episodes turn into facts. But repeated behavior isn’t always a preference. Changing a rule to test three times might be a preference, or three one-off situations.</p><p>Before promoting an episode to a fact, check:</p><ul><li><strong>Source:</strong> did the user say it, or did the agent infer it? Explicit instructions beat patterns.</li><li><strong>Confidence:</strong> how many episodes support it, and how recent are they?</li><li><strong>Conflicts:</strong> does it contradict an existing fact? Flag it, don’t silently overwrite.</li><li><strong>Provenance:</strong> store where each fact came from, so you can correct or delete it later.</li></ul><h3>The loop: read before reasoning, write after acting</h3><p>Most production agents follow the same rhythm:</p><ol><li><strong>Receive</strong> the input.</li><li><strong>Read memory.</strong> Load working memory, query the long-term store, build the context.</li><li><strong>Reason and plan.</strong></li><li><strong>Act.</strong> Call a tool.</li><li><strong>Observe</strong> the result.</li><li><strong>Write memory.</strong> Update working memory. Append the event to episodic memory.</li><li><strong>Loop or stop.</strong></li></ol><p>In LangGraph, that maps to a few nodes:</p><ul><li><strong>Retrieval node</strong> before the LLM node. Query semantic memory, attach the top K results to graph state.</li><li><strong>Procedure picker.</strong> Classify the intent, then load only the playbook for that task. Not all of them.</li><li><strong>Write node</strong> after each action. Append the event to episodic memory.</li><li><strong>Promotion job,</strong> async. Distill stable facts from episodes into semantic memory. Run it in the background so the user never waits on it.</li></ul><p>One rule to keep in mind: <strong>reads are on the hot path, writes don’t have to be.</strong> Keep retrieval fast. Push slow work like summarizing and fact extraction off to the side.</p><h3>Retrieval: never pull everything</h3><p>The context window has a token budget. Memory retrieval is about picking the few items that earn their place.</p><p>A typical pipeline:</p><ol><li><strong>Filter first.</strong> Narrow by metadata: user, tenant, thread, memory type, time range. Cheap, and it stops one user’s memories leaking into another’s.</li><li><strong>Search.</strong> Rank what’s left by relevance. <strong>Vector search</strong> finds items with similar meaning. <strong>Keyword search</strong> catches exact terms: rule IDs, CVE numbers, hostnames. Embeddings are bad at these. Research cited by Redis found <strong>hybrid</strong> (both together) beats either alone.</li><li><strong>Score.</strong> Boost by <strong>recency</strong> and <strong>importance</strong>, especially for episodes and facts that change over time.</li><li><strong>Trim.</strong> Deduplicate, summarize, and keep only what fits the budget.</li></ol><p><strong>Filtering isn’t authorization.</strong> A metadata filter narrows results. It doesn’t prove this user may see them. Before anything enters the model’s context, check access, including:</p><ul><li><strong>Restored checkpoints and cached summaries.</strong> They were built under yesterday’s permissions.</li><li><strong>Long-term memories.</strong> If someone’s access is revoked, an old memory must not become a back door.</li><li><strong>Tenant isolation.</strong> One tenant’s memories never reach another’s context, even by similarity.</li><li><strong>Deletion and retention.</strong> When a user asks to be forgotten, delete the facts, the episodes <strong>and</strong> the embeddings and summaries built from them. Decide up front how long sensitive data stays.</li></ul><p><strong>Vector search vs cosine similarity.</strong> People use these as if they mean the same thing. They don’t.</p><ul><li><strong>Vector search</strong> is the capability: find the nearest neighbors to a query embedding, usually with an index (like HNSW) and filters.</li><li><strong>Cosine similarity</strong> is one way to measure “near.” Others are L2 (Euclidean) distance and inner product.</li></ul><p>When I built Sigma rule search for CyberGuard, I started with cosine similarity over a NumPy array. It worked. But it vanished when the Python process ended, and it scanned every vector on every query. A vector database fixes both.</p><h3>Keeping memory lean: offload, expire, compact</h3><p>Memory that only grows becomes noise. Three habits keep it useful.</p><p><strong>1. Offload</strong></p><ul><li>Move scratchpads, tool outputs and old chat turns <strong>out</strong> of the prompt and into fast external storage.</li><li>Write after every step, instead of piling raw history into the context.</li><li>Pull back only the slice the current step needs.</li></ul><p><strong>2. Expire (TTL)</strong></p><ul><li>Give short-lived memory a time-to-live. A session’s working state can expire when the session ends, or a few minutes after.</li><li>Cached LLM responses need a TTL too, so stale answers refresh.</li><li>Long-term facts usually don’t expire. They get updated or replaced.</li></ul><p><strong>3. Compact</strong></p><ul><li><strong>Truncate.</strong> Keep a sliding window of recent raw messages.</li><li><strong>Summarize.</strong> Condense older turns into a short summary with a smaller, cheaper model. That summary starts the next prompt.</li><li><strong>Extract before you delete.</strong> Before a TTL or truncation wipes a session, pull out candidate facts. Promote them only if they pass the checks above.</li></ul><p>The last point is the one teams miss. If you expire a session before extracting from it, the agent forgets things it should have learned.</p><p><strong>What to forget</strong> is still an open problem. A simple start: expire raw episodes, keep facts with their provenance, review facts that contradict each other, and retire facts that haven’t been confirmed in a long time.</p><h3>Where Redis fits, and where it doesn’t</h3><p>Redis comes up a lot in agent memory. It does two different jobs, and it’s a poor fit for a third.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcoG9yAHHwOw4fZMtOwI-w.png" /></figure><p>A few details worth knowing:</p><ul><li><strong>There’s an open-source memory layer.</strong> <a href="https://redis.io/blog/long-term-memory-architectures-ai-agents/">Redis Agent Memory Server</a> handles working and long-term memory, fact extraction and MCP access.</li><li><strong>Redis isn’t required.</strong> Postgres with pgvector, or a managed vector database, can do the same jobs. Pick based on what you already run.</li></ul><p>The point isn’t the tool. It’s matching each kind of memory to storage that fits how it’s <strong>written</strong> and how it’s <strong>read</strong>.</p><h3>Start small</h3><p>You don’t need a complex memory system on day one.</p><ul><li><strong>Save working state</strong> so tasks can resume after interruptions.</li><li><strong>Add summarization</strong> when context grows too large.</li><li><strong>Add long-term memory</strong> when the agent needs to reuse facts, past runs or procedures across sessions.</li><li><strong>As memory grows,</strong> add retrieval filters, expiration rules, conflict handling and access controls.</li></ul><p>Not every conversation deserves to become permanent memory.</p><p><strong>Then measure.</strong> Run the same tasks with memory on and off. Track task success, plus:</p><ul><li><strong>Usefulness:</strong> did the retrieved memory help finish the task?</li><li><strong>Retrieval precision:</strong> how much irrelevant memory got into the context?</li><li><strong>Staleness:</strong> did an outdated or contradicting fact change the answer?</li><li><strong>Cost and latency:</strong> what did reading and writing memory add?</li><li><strong>Security:</strong> did any unauthorized or cross-tenant memory show up?</li></ul><p>A useful memory system improves decisions, not just prompt length. For how to set up the evals, see <a href="https://ankitgoelcmu.medium.com/how-to-evaluate-ai-agents-a-practical-guide-8d5d6378d6de">How to Evaluate AI Agents</a>.</p><p><strong>The goal isn’t to make an agent remember everything. It’s to make it remember the right things, at the right time, for the right reason.</strong></p><h3>Further reading</h3><ul><li><a href="https://redis.io/blog/long-term-memory-architectures-ai-agents/">Long-Term Memory Architectures for AI Agents</a>, Redis</li><li><a href="https://ankitgoelcmu.medium.com/how-to-evaluate-ai-agents-a-practical-guide-8d5d6378d6de">How to Evaluate AI Agents: A Practical Guide</a></li><li><a href="https://medium.com/@ankitgoelcmu/your-ai-agent-is-only-as-reliable-as-its-60th-tool-call-e9cc79a73e8a">Your AI Agent Is Only as Reliable as Its 60th Tool Call</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cdfecb455be" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/agent-memory-what-to-keep-where-to-keep-it-and-when-to-read-it-1cdfecb455be">Agent Memory: What to Keep, Where to Keep It, and When to Read It</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Evaluate AI Agents: A Practical Guide]]></title>
            <link>https://levelup.gitconnected.com/how-to-evaluate-ai-agents-a-practical-guide-8d5d6378d6de?source=rss-de94f8b1bcf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d5d6378d6de</guid>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankit Goel]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 05:47:04 GMT</pubDate>
            <atom:updated>2026-11-11T16:12:07.425Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Agents don’t fail like chatbots. They fail in the middle of a run, for the wrong reasons, and only some of the time. Here’s how to catch that before your users do.</em></p><h3>Key takeaways</h3><ul><li>Agents are stochastic. One passing run proves nothing. Run each task several times.</li><li>Grade three layers: the outcome, the path the agent took, and every tool call.</li><li>Use code graders first, LLM judges where code can’t decide, and humans to keep the judges honest.</li><li>Start with 20 to 50 tasks pulled from real failures. Don’t wait for a perfect suite.</li><li>Read the traces. A pass/fail result only judges the final answer. The trace shows how the agent got there. A pass can hide a lucky guess, and a fail can be a bug in your eval.</li></ul><h3>A running example: right verdict, wrong window</h3><p>Here’s an illustrative case from the kind of SOC agent I’ve built.</p><ul><li>An alert fires: suspicious login for a service account, six hours ago.</li><li>The agent investigates and recommends: “Compromised. Disable the account.”</li><li>That’s the right verdict.</li><li>But the trace shows it queried the identity logs for the <strong>last hour</strong>, not the window around the alert. It reached the verdict from one threat-intel match on the source IP.</li><li>Next time the IP won’t be on a list, and the agent will miss it.</li></ul><p>An outcome-only eval scores this run a pass. Here’s how each layer scores it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*VEK62R1IOvh8fDKoyTMxmg.png" /></figure><p>One pass, two fails, one open question. That’s the gap this post is about. The sections below come back to this example.</p><h3>Why agent evals are harder</h3><p>Testing an LLM is simple: one prompt in, one answer out, compare it to the expected answer.</p><p>Agents break that model:</p><ul><li><strong>They’re stochastic.</strong> The same input can take a different path and reach a different result on each run.</li><li><strong>There’s no single right path.</strong> Many tool sequences can solve the same task.</li><li><strong>They act on the world.</strong> A bad step isn’t just a bad sentence. It’s a wrong ticket, a blocked IP, a deleted file.</li><li><strong>Errors compound.</strong> A small mistake at step 5 can derail step 50.</li><li><strong>They can be right for the wrong reasons.</strong> The final answer looks fine, but the agent skipped a step or guessed.</li></ul><p>So the goal changes. You’re not proving the agent is correct. You’re catching <strong>systemic failures and regressions</strong> with several signals that cover each other’s blind spots.</p><p>Anthropic’s engineering team put it well in <a href="https://www.anthropic.com/research/demystifying-evals-for-ai-agents">Demystifying evals for AI agents</a>: the value of evals compounds over an agent’s life, while the cost shows up on day one. That’s why teams skip them, and why they regret it later.</p><h3>The building blocks</h3><p>A few terms first. Anthropic’s vocabulary is clean, so I’ll use it, with one change: Anthropic says “transcript,” but in this post I’ll say “trace,” the term most agent tooling uses.</p><ul><li><strong>Task:</strong> one test case, with an input and a clear definition of success.</li><li><strong>Trial:</strong> one attempt at a task. You run several, because results vary.</li><li><strong>Trace:</strong> the full record of a trial: messages, tool calls with their inputs and outputs, handoffs and the final answer. Also called a transcript (Anthropic’s term) or a trajectory.</li><li><strong>Outcome:</strong> the final state of the world after the trial. Not what the agent <em>said</em> it did. Did the booking actually land in the database?</li><li><strong>Grader:</strong> the logic that scores a trial. One task can have several.</li><li><strong>Eval harness:</strong> the code that runs tasks, records traces, grades them and adds up the results.</li><li><strong>Eval suite:</strong> a set of tasks that measure one capability or behavior.</li></ul><p>One point that’s easy to miss: when you evaluate “an agent,” you’re testing the model <strong>and</strong> its harness together. Change the prompt, a tool description or the retry logic, and you have a different agent.</p><p>The practical rule: <strong>capture the full trace on every run.</strong> Trajectory evals, tool-call checks and LLM judges all depend on it. Without it, you can only grade the final answer.</p><h3>What to grade: three layers</h3><p>I think of agent evals as layers. Each one catches failures the others miss.</p><h4>1. Outcome: did it solve the task?</h4><ul><li>Check the end state against ground truth. Binary pass or fail.</li><li>Build the dataset from the happy path <strong>and</strong> edge cases.</li><li>Cheapest layer. Run it on everything.</li><li>Running example: did it reach the right verdict and recommend the right containment?</li></ul><h4>2. Trajectory: did it get there the right way?</h4><ul><li>Did it break the task into sensible steps?</li><li>Did it route to the right subagent with the right inputs?</li><li>Did it gather enough evidence before acting? Running example: identity activity, network signals and threat intel, checked before recommending containment.</li><li>This catches the agent that gets the right answer for the wrong reasons.</li></ul><p><strong>Rule: grade the required checks, let the path vary.</strong> Require the evidence. Allow different log sources and query orders, as long as they cover it.</p><h4>3. Tool calls: was each step correct?</h4><ul><li>Right tool, right parameters? Running example: did it query the right identity and time window?</li><li>No hallucinated tools (calling tools that don’t exist).</li><li>Does it recover when a tool fails, or loop forever?</li></ul><h4>Cross-cutting: what did it cost?</h4><ul><li><strong>Latency:</strong> wall-clock time per task.</li><li><strong>Cost:</strong> tokens and API calls per run.</li><li><strong>Context use:</strong> is the run getting close to the window limit and cutting itself short?</li></ul><h4>Cross-cutting: does it hold up under stress?</h4><ul><li><strong>Consistency:</strong> same task, K runs. Same outcome? Did every run make the required checks? Stable cost and latency? Don’t require the same tools in the same order.</li><li><strong>Fault injection:</strong> feed it timeouts, HTTP 500s, empty or malformed tool output. Does it retry, report the evidence gap, or make something up? Think chaos engineering for agents.</li><li><strong>Prompt robustness:</strong> same intent, different wording. Formal, casual, typos. Does behavior change?</li></ul><h3>Who does the grading</h3><p>Three kinds of graders. Use all three, in this order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*fczjxnH8hYAK14Zywjrd0A.png" /></figure><p>A few rules that save pain:</p><ul><li><strong>Default to code.</strong> If a check can be written as code, write it as code.</li><li><strong>Grade the outcome, not the exact steps.</strong> Agents find valid paths you didn’t think of. Anthropic describes Opus 4.5 “failing” a flight-booking task by finding a policy loophole that was better for the user.</li><li><strong>Give partial credit</strong> on multi-step tasks.</li><li><strong>Let the judge say “Unknown”</strong> instead of forcing a guess.</li><li><strong>Stratify at scale.</strong> At 100+ incidents a day, run full evals on high-severity cases, sample about 10% of the rest, and batch overnight.</li></ul><h3>Calibrating the LLM judge</h3><p>An uncalibrated judge is just another model guessing. Before you trust its scores, check it against humans.</p><h4>Before you label</h4><ul><li><strong>Measure human-to-human agreement first.</strong> Have 2+ people grade the same items. If they only agree 80% of the time, that’s realistically the ceiling for your judge. It usually means the rubric is too vague, so fix that first.</li><li><strong>Expect the criteria to change.</strong> Reviewers often refine what “good” means once they see real outputs. Lock the rubric only after a first pass through the data.</li><li><strong>Prefer simple yes/no checks.</strong> “Did it cite a source? Yes/No” calibrates far better than “rate quality 1–5.” Use one judge per criterion rather than one judge scoring everything.</li></ul><h4>Step 1: Build a gold dataset</h4><ul><li>Collect 30–200 real input/output pairs from production logs, not synthetic prompts.</li><li>Weight it toward edge cases, ambiguous cases and failures, not just easy passes.</li><li>Have domain experts grade each one independently. These grades are the ground truth.</li><li>Split it in two: a calibration set for tuning the judge, and a held-out test set you only use to measure. Step 6 explains why.</li></ul><h4>Step 2: Run the judge blind</h4><ul><li>The judge gets the input, the output and the rubric.</li><li>It does not get the human grade. If it saw the grade, you’d be testing whether it agrees with you, not whether it can judge.</li><li>It returns its reasoning first, then its score.</li></ul><h4>Step 3: Measure agreement</h4><p>Use code to compare the judge’s grades with the human grades.</p><p><strong>Pass/fail:</strong> Count how often the grades match, but also count two kinds of mistakes:</p><ul><li><strong>Missed failure:</strong> humans said fail, the judge said pass.</li><li><strong>False alarm:</strong> humans said pass, the judge said fail.</li></ul><p><strong>Example:</strong> 100 runs, and humans failed 5 of them.</p><ul><li><strong>Judge A</strong> says “pass” every time. It matches 95 of 100 (95%) but catches 0 of the 5 failures.</li><li><strong>Judge B</strong> catches all 5 failures but flags 6 good runs by mistake. It matches 94 of 100 (94%).</li></ul><p>Judge A has the higher score but is useless. Judge B is the one you want. That’s why you track missed failures and false alarms, not just the match rate.</p><ul><li><strong>1–5 scores:</strong> Count grades within one point as a match.</li><li><strong>Before launch:</strong> Use 85% agreement as a starting target. Be stricter about missed failures when they’re costly.</li></ul><h4>Step 4: Analyze the mismatches</h4><ul><li><strong>Too strict:</strong> the judge scores lower than humans do.</li><li><strong>Too lenient:</strong> the judge passes outputs humans failed.</li><li><strong>Comprehension gap:</strong> the judge misses a subtle issue humans caught.</li><li><strong>Bad label:</strong> sometimes the human is wrong. Check the label too. Fixing bad labels is part of calibration.</li></ul><h4>Step 5: Fix the judge</h4><ul><li>Tighten the rubric. Spell out exactly what counts as a fail.</li><li>Add 2–3 example cases to the prompt, with the correct human grade and reasoning.</li><li>Upgrade the model if a small judge misses complex logic.</li></ul><h4>Step 6: Re-test, then score once on the held-out set</h4><ul><li>Re-run on the calibration set. Confirm the old errors are fixed and no new ones appeared. Repeat until you hit your target.</li><li>Then score the judge once on the held-out set. That’s your real number.</li><li>Why the split matters: if you put the examples the judge got wrong into its prompt and re-test on the same data, the score goes up for the wrong reason. The judge has already seen the answers.</li></ul><h4>Judge design tips</h4><ul><li><strong>Reasoning before score.</strong> It’s more accurate and easier to debug.</li><li><strong>Structured output.</strong> JSON with fields for reasoning, score and failure category.</li><li><strong>Give it a reference answer</strong> when you have one. Grading against a reference beats open-ended judging.</li><li><strong>Watch for known biases.</strong> Position bias: in A-vs-B comparisons, run both orders. Verbosity bias: longer answers tend to score higher. Self-preference: don’t let a model judge its own outputs.</li><li><strong>Test consistency.</strong> Score the same item several times. If the score flips, the judge is unreliable even when its average looks fine.</li><li><strong>Be careful with small samples.</strong> With 30 examples, “85% agreement” could really be anywhere from about 72% to 97%.</li></ul><h4>After deployment</h4><ul><li><strong>Re-calibrate on a schedule.</strong> Sample production items, have humans grade them, and recheck agreement. Production data drifts.</li><li><strong>Version the judge.</strong> Track the prompt, model and rubric version. Re-run calibration when any of them changes, including a provider model update.</li><li><strong>Correct your reported numbers.</strong> If you know how often the judge wrongly passes or fails, adjust the measured pass rate to estimate the true one.</li></ul><p>Even a well-calibrated judge misses some failures. That’s fine. It’s one signal among several, not the final word.</p><h3>Two kinds of suites, two ways to count</h3><h4>Capability vs regression</h4><ul><li><strong>Capability evals</strong> ask: what can the agent do well yet? They should start with a <strong>low</strong> pass rate. That’s your hill to climb.</li><li><strong>Regression evals</strong> ask: does it still do what it used to? They should sit near <strong>100%</strong>. Any drop is a red flag.</li><li>When a capability eval passes consistently, it <strong>graduates</strong> into the regression suite and runs on every change.</li></ul><h4>pass@k vs pass^k</h4><p>Agents are stochastic, so you run each task k times. How you count those runs changes the answer:</p><ul><li><strong>pass@k:</strong> at least one of k runs succeeds. Goes <strong>up</strong> as k grows. Fine when one good answer is enough, like generating candidate fixes.</li><li><strong>pass^k:</strong> <strong>all</strong> k runs succeed. Goes <strong>down</strong> as k grows. This is what users feel. A support agent that works 3 times out of 4 is broken for the 4th customer.</li></ul><p>The math, assuming independent runs on a task that succeeds 75% of the time:</p><ul><li>pass@3 = 1 − (0.25 × 0.25 × 0.25) ≈ 98%</li><li>pass^3 = 0.75 × 0.75 × 0.75 ≈ 42%</li></ul><p>Same agent, very different story. For anything customer-facing, report pass^k.</p><p>Across a suite, compute pass^k <strong>per task</strong>, then average. Tasks succeed at different rates, so averaging the success rate first and then raising it to the power k gives the wrong number.</p><h3>Evals by agent type</h3><p>The layers stay the same. What you check changes with the agent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*i3H_hWA_TNyoaUXwfKugSg.png" /></figure><p>A note on research agents: “good” depends heavily on context, so LLM rubrics drift. Recalibrate them against experts often.</p><h3>How to start: zero to a working suite</h3><p>You don’t need hundreds of tasks. You need a few good ones, today.</p><ol><li><strong>Start with 20–50 tasks.</strong> Pull them from real failures: bug reports, support tickets, things you already check by hand. Early on, changes are big, so a small set is enough to see them.</li><li><strong>Make tasks unambiguous.</strong> Two experts should give the same pass/fail verdict. Write a reference solution for each. If the agent scores 0% across many runs, suspect the task before the agent.</li><li><strong>Test both directions.</strong> Check that the agent does the thing when it should, <strong>and</strong> doesn’t when it shouldn’t. Over-triggering is a failure too.</li><li><strong>Isolate every trial.</strong> Fresh environment each run. Shared state inflates scores. Anthropic caught Claude reading git history left over from earlier trials.</li><li><strong>Capture full traces.</strong> Every tool call with inputs and outputs, every handoff, the final answer. Everything else builds on this.</li><li><strong>Grade with code first,</strong> then LLM judges, then humans to calibrate.</li><li><strong>Debug your evals.</strong> Opus 4.5 first scored 42% on CORE-Bench. After Anthropic fixed rigid grading, ambiguous specs and tasks that couldn’t be reproduced, and moved to a less constrained scaffold, it scored 95%. Many “agent failures” are partly eval bugs.</li><li><strong>Make graders hard to game.</strong> Passing should require actually solving the problem.</li><li><strong>Read the traces.</strong> Every week. Scores hide the details that matter.</li></ol><p><strong>Close the loop.</strong> Each failure points to a fix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*6LCsiXIMMxZI2O9986jUHw.png" /></figure><p><strong>Watch for saturation.</strong> Once the agent passes everything solvable, the suite stops telling you anything new. Add harder tasks, or graduate the suite to regression.</p><h3>The one thing to remember</h3><p>No single eval catches everything. Think of it like Swiss cheese: each layer has holes, but stacked together, few failures get through.</p><ul><li>Code graders catch the obvious breaks.</li><li>LLM judges catch what code can’t express.</li><li>Humans keep the judges honest.</li><li>Production monitoring catches what all of them missed.</li></ul><p>Start small. Pull 20 real failures into tasks this week, run each one five times, and read the traces. You’ll learn more from that than from any benchmark.</p><h4>Further reading</h4><ul><li><a href="https://www.anthropic.com/research/demystifying-evals-for-ai-agents">Demystifying evals for AI agents</a>, Anthropic</li><li><a href="https://ankitgoelcmu.medium.com/how-to-read-an-ai-agent-trace-fab8e8391506">How to Read an AI Agent Trace</a>, on reading traces</li><li><a href="https://medium.com/@ankitgoelcmu/your-ai-agent-is-only-as-reliable-as-its-60th-tool-call-e9cc79a73e8a">Your AI Agent Is Only as Reliable as Its 60th Tool Call</a>, on why small tool errors compound</li><li><a href="https://ankitgoelcmu.medium.com/guardrails-for-ai-agents-what-actually-enforces-them-fbf6c6f5f8cf">Guardrails for AI Agents: What Actually Enforces Them</a>, on rules in code vs prompts</li></ul><p><em>If this was useful, follow me for more on building and testing AI agents in production.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d5d6378d6de" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-evaluate-ai-agents-a-practical-guide-8d5d6378d6de">How to Evaluate AI Agents: A Practical Guide</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Agent Can Talk While It Works: Testing LangChain’s Async Subagents]]></title>
            <link>https://levelup.gitconnected.com/your-agent-can-talk-while-it-works-testing-langchains-async-subagents-474ab1c85882?source=rss-de94f8b1bcf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/474ab1c85882</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Ankit Goel]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 00:43:23 GMT</pubDate>
            <atom:updated>2026-11-09T16:22:02.598Z</atom:updated>
            <content:encoded><![CDATA[<h4>Agents are going async</h4><h3>Key takeaways</h3><ul><li>Agents now take on long tasks. They need to keep talking to you while that work runs.</li><li>Async subagents split the job: a supervisor stays with the user, and subagents run tasks in the background and report back when done.</li><li>You can change a running task mid-flight: interrupt for corrections, enqueue for additions.</li><li>Background work is becoming the default, from coding agents like Claude Code to personal agents like OpenAI’s dots.</li></ul><p>Most agents make you wait. Nothing comes back until the slowest step is done.</p><ul><li>Fine for a two-second answer.</li><li>Not fine when a step is a fare search, a sandbox scan, or a research job that runs for minutes.</li><li>And while it runs, you can’t change your mind.</li></ul><p>LangChain just shipped a fix in Deep Agents: <strong>async subagents</strong> (<a href="https://www.langchain.com/blog/agents-are-going-async">Agents are going async</a>). A main agent hands work to background agents, keeps talking to you, and picks up results when they’re ready.</p><p>Always-on agents already work this way:</p><ul><li><strong>Claude Code</strong> runs subagents in the background by default.</li><li><strong>OpenAI’s dots</strong> hand work to background workers.</li><li><strong>DeepSeek Harness</strong> uses a router that talks to people while workers run tasks in parallel.</li></ul><p>My example: a supervisor and a flight agent.</p><ul><li>Ask for a flight to Portland.</li><li>Switch to Seattle mid-search.</li><li>The result comes back on its own.</li><li>Runs on a local model, zero API cost.</li></ul><h3>Why blocking agents break on long work</h3><p>One agent, one run. Ten seconds into the search, the meeting moves to Seattle:</p><pre>0s   you:    &quot;Find me a flight to Portland&quot;<br>0s   agent:  search_flights(Portland) ........ 30s<br>10s   you:    &quot;Actually, make it Seattle&quot;     &lt;- waits for the run to end<br>30s   agent:  &quot;Cheapest flight to Portland: $244&quot;<br>30s   agent:  reads your message, searches again ... 30s<br>60s   agent:  &quot;Cheapest flight to Seattle: $244&quot;</pre><ul><li><strong>Your change is blocked.</strong> The agent finishes the wrong search, then starts over.</li><li><strong>You wait for the whole run.</strong> Even “how’s it going?” gets no reply.</li><li><strong>You can’t stop it.</strong> The run goes on until it ends.</li></ul><p>The 30 seconds is my mock search. Real flight APIs are often slower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9-K03Q1OGbMLD_kpyvLxw.jpeg" /><figcaption>Sync vs async: the same trip change in both</figcaption></figure><ul><li><strong>Sync:</strong> the supervisor is busy while it waits on agents, so your change waits too.</li><li><strong>Async:</strong> the supervisor starts the agents, replies, and is free. Your change goes straight to the running task, which drops Portland and starts Seattle.</li></ul><h3>How async subagents work</h3><ul><li>An async subagent is a separate agent running in the background on its own thread.</li><li>The <strong>supervisor</strong> starts it, carries on, and hears back when it’s done.</li><li>Subagents run on an Agent Server, the same one that hosts LangGraph deployments. Locally, langgraph dev runs one on your laptop.</li><li>Same deployment = in-process calls. No network hop, no auth (<a href="https://docs.langchain.com/oss/python/deepagents/async-subagents">docs</a>).</li></ul><p>Define a subagent with a name, a description and a graph:</p><pre>from deepagents import AsyncSubAgent, create_deep_agent<br><br>flight = AsyncSubAgent(<br>    name=&quot;flight_agent&quot;,<br>    description=&quot;Finds the cheapest flight to a city.&quot;,<br>    graph_id=&quot;flight_agent&quot;,          # a graph in langgraph.json<br>    update_strategy=&quot;interrupt&quot;,      # what a follow-up does to a running task<br>)<br><br>supervisor = create_deep_agent(model=llm, system_prompt=PROMPT, subagents=[flight])</pre><p>The supervisor gets five tools:</p><ul><li>start_async_task: start a subagent, get a task ID back at once</li><li>check_async_task: status, plus the result when done</li><li>update_async_task: send new instructions; same task ID</li><li>cancel_async_task: stop a running task</li><li>list_async_tasks: every task with live status</li></ul><p>Three more pieces:</p><ul><li><strong>Update strategy.</strong> interrupt (default) restarts the run with new instructions: use for corrections. enqueue runs the follow-up after the current run: use for additions.</li><li><strong>Notifications.</strong> A finished subagent tells the supervisor. Idle supervisor: a new run starts. Busy supervisor: it picks up the result before its next model call. Notifications are tagged, so your app can tell them from user messages.</li><li><strong>Waiting.</strong> A subagent paused for a human (e.g., payment approval) shows waiting. The person answers on that subagent&#39;s thread. The supervisor isn&#39;t blocked.</li></ul><p>Watch out:</p><ul><li>Notifications, waiting and update_strategy are beta and need deepagents 0.7.30+.</li><li>LangChain’s <a href="https://github.com/langchain-ai/async-deep-agents">example repo</a> is older than the docs: it uses async_subagents= and launch_async_subagent. Current versions use subagents= and the tool names above.</li></ul><h3>The full example</h3><p>Three files. The two agents, in agents.py:</p><pre>import asyncio<br><br>from deepagents import AsyncSubAgent, create_deep_agent<br><br>MODEL = &quot;ollama:qwen3-coder-next:latest&quot;<br><br><br>async def search_flights(city: str) -&gt; str:<br>    &quot;&quot;&quot;Find the cheapest flight to a city.&quot;&quot;&quot;<br>    # Fakes a slow real API (30s) so you can change the city mid-search.<br>    # Remove it in real code; the actual API call is the slow part.<br>    await asyncio.sleep(30)<br>    return f&quot;Cheapest flight to {city}: $244, nonstop.&quot;<br><br><br>flight_agent = create_deep_agent(<br>    model=MODEL,<br>    tools=[search_flights],<br>    system_prompt=&quot;Search flights for the requested city and report the cheapest.&quot;,<br>)<br><br>supervisor = create_deep_agent(<br>    model=MODEL,<br>    system_prompt=(<br>        &quot;You are a travel assistant.\n&quot;<br>        &quot;- Flight search: call start_async_task with flight_agent, reply in one sentence, then stop.\n&quot;<br>        &quot;- The user changes the city: call update_async_task on the running task, reply in one sentence, then stop.\n&quot;<br>        &quot;- Never call check_async_task unless the user asks for status. Results come back on their own.&quot;<br>    ),<br>    subagents=[<br>        AsyncSubAgent(<br>            name=&quot;flight_agent&quot;,<br>            description=&quot;Finds the cheapest flight to a city.&quot;,<br>            graph_id=&quot;flight_agent&quot;,<br>        )<br>    ],<br>)</pre><p>langgraph.json registers both on one server:</p><pre>{<br>  &quot;dependencies&quot;: [&quot;.&quot;],<br>  &quot;graphs&quot;: {<br>    &quot;supervisor&quot;: &quot;./agents.py:supervisor&quot;,<br>    &quot;flight_agent&quot;: &quot;./agents.py:flight_agent&quot;<br>  }<br>}</pre><p>run.py plays the user:</p><pre>import asyncio<br><br>from langgraph_sdk import get_client<br><br>client = get_client(url=&quot;http://127.0.0.1:2024&quot;)<br><br><br>async def say(thread, text):<br>    print(&quot;you:&quot;, text)<br>    await client.runs.wait(<br>        thread,<br>        &quot;supervisor&quot;,<br>        multitask_strategy=&quot;enqueue&quot;,<br>        input={&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: text}]},<br>    )<br>    await show(thread)<br><br><br>async def show(thread):<br>    state = await client.threads.get_state(thread)<br>    print(&quot;agent:&quot;, state[&quot;values&quot;][&quot;messages&quot;][-1][&quot;content&quot;], &quot;\n&quot;)<br><br><br>async def main():<br>    thread = (await client.threads.create())[&quot;thread_id&quot;]<br>    await say(thread, &quot;Find me a flight to Portland.&quot;)  # replies in seconds; search keeps running<br>    await say(thread, &quot;Actually, make it Seattle.&quot;)  # changes the running search<br>    await asyncio.sleep(45)  # the result arrives on its own<br>    await show(thread)<br><br><br>asyncio.run(main())</pre><p>Run it in two terminals:</p><pre>uv run langgraph dev --n-jobs-per-worker 10   # terminal 1: the local Agent Server<br>uv run python run.py                          # terminal 2</pre><p>Three details matter:</p><ul><li><strong>Use create_deep_agent, not create_agent, for the subagent.</strong> It adds the middleware that reports back when a run ends. A plain create_agent graph finishes silently; the supervisor only knows if it polls.</li><li><strong>asyncio.sleep(30) fakes a slow API.</strong> Without it, the search ends in a second or two and there’s nothing to interrupt. In real code, the API call is the slow part.</li><li><strong>Give the server enough workers.</strong> The supervisor, the subagent and each notification all take a slot. Too few and tasks queue.</li></ul><h3>A real run, second by second</h3><p>Local model (qwen3-coder-next on Ollama). Timings from the server&#39;s records, not the chat:</p><pre>0s   you:         &quot;Find me a flight to Portland.&quot;<br>      supervisor:  start_async_task(flight_agent)<br> 5s   supervisor:  &quot;I&#39;ve started searching for the cheapest flight to Portland.&quot;<br> 6s   you:         &quot;Actually, make it Seattle.&quot;<br>      supervisor:  update_async_task(...)<br>10s   server:      Portland run interrupted; a Seattle run starts on the same thread<br>11s   supervisor:  &quot;I&#39;ve updated the destination to Seattle and am now searching.&quot;<br>43s   flight agent finishes and wakes the supervisor<br>44s   supervisor:  &quot;The cheapest flight to Seattle is $244, nonstop.&quot;</pre><p>Three things a blocking agent can’t do:</p><ul><li><strong>First reply in 5 seconds</strong>, while the 30-second search kept running.</li><li><strong>The change landed mid-search.</strong> Portland run shows interrupted; Seattle run starts on the same thread, same task ID.</li><li><strong>The result arrived on its own.</strong> At 43s the flight agent woke the supervisor. No polling.</li></ul><h3>When to use async subagents</h3><p>Use them when a person is waiting and the work is slow:</p><ul><li><strong>A step takes more than a few seconds.</strong> Searches, scans, research, long tool chains.</li><li><strong>The user may change their mind.</strong> interrupt for corrections, enqueue for additions.</li><li><strong>A step needs a human.</strong> Approval waits on its own thread, blocks nothing.</li><li><strong>The parts are independent.</strong> No subagent waits on another.</li></ul><p>Skip them when the job takes a couple of seconds. A parallel graph is simpler.</p><p>What I’d tell anyone starting:</p><ul><li><strong>Build subagents with create_deep_agent.</strong> Results come back without polling.</li><li><strong>Add workers.</strong> I ran langgraph dev --n-jobs-per-worker 10.</li><li><strong>Be explicit in the supervisor prompt:</strong> when to start, update and leave a task alone.</li><li><strong>Check the server, not just the chat.</strong> Run statuses show what actually happened.</li><li><strong>Expect beta.</strong> Pin your deepagents version.</li></ul><h3>Try it</h3><ul><li>Code: <a href="https://github.com/ankitgoelcmu/agentic-ai/tree/main/examples/async_agent">async_agent on GitHub</a></li><li>Runs on Ollama, so it’s free.</li><li>Start langgraph dev, then run run.py, or chat with the supervisor graph in LangGraph Studio.</li></ul><p>Async subagents remove the wait. What’s left: tell the supervisor clearly when to start, update or leave a task alone, then check the server to see that it did.</p><p>Further reading:</p><ul><li><a href="https://www.langchain.com/blog/agents-are-going-async">Agents are going async</a>, the LangChain announcement</li><li><a href="https://docs.langchain.com/oss/python/deepagents/async-subagents">Async subagents docs</a></li><li><a href="https://medium.com/@ankitgoelcmu/your-ai-agent-is-only-as-reliable-as-its-60th-tool-call-e9cc79a73e8a">Your AI Agent Is Only as Reliable as Its 60th Tool Call</a>, on why small tool errors compound</li><li><a href="https://ankitgoelcmu.medium.com/guardrails-for-ai-agents-what-actually-enforces-them-fbf6c6f5f8cf">Guardrails for AI Agents: What Actually Enforces Them</a>, on why rules belong in code, not prompts</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=474ab1c85882" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-agent-can-talk-while-it-works-testing-langchains-async-subagents-474ab1c85882">Your Agent Can Talk While It Works: Testing LangChain’s Async Subagents</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your RAG Is Only as Good as Your OCR]]></title>
            <link>https://levelup.gitconnected.com/your-rag-is-only-as-good-as-your-ocr-7b2100bffd9f?source=rss-de94f8b1bcf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b2100bffd9f</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Ankit Goel]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 20:52:46 GMT</pubDate>
            <atom:updated>2026-11-06T15:17:51.713Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1 of 3: OCR and RAG, end to end</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjInKws9CYyFXRoVNxLrcA.png" /></figure><p>Most enterprise AI answers start as a scanned PDF, a phone photo of an invoice, or a messy spreadsheet. If the text pulled from those files is wrong, everything after it is wrong too, no matter how good the LLM is.</p><p>This series walks the full path, from raw documents to a cited answer:</p><ul><li><strong>Part 1 (this post):</strong> the pipeline, and how to measure and fix OCR</li><li><strong>Part 2:</strong> RAG basics, why RAG still hallucinates, and advanced RAG</li><li><strong>Part 3:</strong> measuring retrieval, and debugging RAG in production</li></ul><h3>The pipeline at a glance</h3><p>Six stages, two flows. Ingestion runs offline, once per document. Answering runs online, every time someone asks a question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*WeojDXE8XmgF6Qv1RDB3hg.png" /></figure><p>The online flow is only as good as what the offline flow stored.</p><h3>Ingestion (offline)</h3><h4>Stage 1: Route each page</h4><p>Inputs are mixed: native PDFs, low-res scans, phone photos, spreadsheets. A routing script checks each page:</p><ul><li><strong>Real text layer?</strong> Send it to a fast programmatic parser.</li><li><strong>Scan or mixed media?</strong> Send it to the heavier vision engine.</li></ul><p>You only pay for vision where you need it.</p><h4>Stage 2: Agentic OCR</h4><p>Old OCR dumps a wall of text. Agentic OCR uses a vision-language model and checks its own work:</p><ul><li><strong>Layout analysis.</strong> Split the page into titles, headers, columns, tables and images.</li><li><strong>Multi-pass validation.</strong> If it reads a financial table, it adds up the columns and compares the sum to the listed total. No match? It re-reads that region.</li><li><strong>Structured output.</strong> Write the page as Markdown, with clean tables and LaTeX for formulas.</li><li><strong>Bounding boxes.</strong> Keep the page number and pixel coordinates of every block. This is what makes exact citations possible later.</li></ul><p>Tools like LlamaParse, Reducto and Docling work this way.</p><h4>Stage 3: Chunk and embed</h4><ul><li><strong>Split by structure, not by word count.</strong> Keep each table, list and section whole, so a table row never loses its header.</li><li><strong>Tag every chunk</strong> with file name, page number, bounding box and document type.</li><li><strong>Embed</strong> each chunk with an embedding model (for example OpenAI text-embedding-3 or Cohere).</li></ul><h4>Stage 4: Store in two places</h4><ul><li><strong>Vector database</strong> (Pinecone, Qdrant, Milvus): embeddings plus text and metadata, for semantic search.</li><li><strong>Relational database or lake</strong> (PostgreSQL, Delta Lake): structured rows like invoice totals, for exact math and SQL.</li></ul><p>Vector search is good at “find something like this.” It is bad at “add up these 40 numbers.” SQL is the opposite.</p><h3>Answering (online)</h3><p>Take a real question: <em>“What were our total legal expenses in Q3, according to the vendor invoices?”</em></p><h4>Stage 5: Route the intent</h4><p>An LLM agent reads the question and picks a path:</p><ul><li><strong>Semantic search</strong> for open-ended questions</li><li><strong>Exact lookup (SQL)</strong> for numbers and totals</li><li><strong>Both</strong>, for questions like this one</li></ul><h4>Stage 6: Retrieve, build context, answer</h4><ul><li><strong>Semantic path:</strong> embed the question and pull matching chunks from the vector DB.</li><li><strong>Structured path:</strong> generate a SQL query and get the exact total.</li><li><strong>Build the context:</strong> put the chunks, the SQL result and the page metadata into the prompt.</li><li><strong>Answer with citations:</strong> the LLM writes the answer and points to its sources.</li></ul><blockquote><em>Your total legal expenses for Q3 were $145,200.00 [SQL verified]. This includes an invoice from Smith &amp; Associates for a compliance review [Invoice_Doc.pdf, page 14].</em></blockquote><p>The number comes from SQL, not from the LLM doing math. The citation comes from the bounding boxes saved in Stage 2. Both depend on OCR getting the page right, which is the rest of this post.</p><h3>How to evaluate OCR</h3><p>An engine can get 99% of characters right and still break your agent. If the 1% it misses is a minus sign on a financial row, the answer is wrong.</p><h4>Text metrics (the foundation)</h4><p>Both need a human-checked “ground truth” to compare against.</p><ul><li><strong>Character Error Rate (CER):</strong> the share of characters inserted (I), deleted (D) or substituted (S). Best for plain text.</li><li><strong>Word Error Rate (WER):</strong> the same, counted by word.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtdhVt_nqUJocZvMzK_xOQ.png" /></figure><h4>Structure metrics (what agents actually need)</h4><ul><li><strong>Field-level accuracy:</strong> does Invoice_Total hold the right value, under the right key?</li><li><strong>Table structure (tree edit distance):</strong> compare the table the OCR produced to the real one. Penalize cells that leak into the wrong row or column.</li><li><strong>Reading order:</strong> are multi-column pages read column by column, not straight across?</li></ul><h4>Public benchmarks</h4><ul><li><strong>OCRBench (v1 and v2):</strong> text recognition, layout and math reasoning for vision-language models.</li><li><strong>DocVQA / TextVQA:</strong> can the system read a document well enough to answer questions about it?</li></ul><h4>A 4-step framework for your own data</h4><ol><li><strong>Build a golden dataset.</strong> 100 to 200 real documents, not clean digital PDFs. Include blurry phone photos, skewed scans, multi-column pages and handwriting. Transcribe them by hand into your target format.</li><li><strong>Run the candidates.</strong> For example Docling, LlamaParse, Mistral OCR, Tesseract.</li><li><strong>Score them in code.</strong> Normalize trivial differences (extra spaces, trailing punctuation), then compute CER and WER with JiWER or Hugging Face evaluate. Check key fields for exact match.</li><li><strong>Map scores to business risk.</strong> Green (WER under 5%): process automatically. Yellow (5% to 15%): run an LLM correction pass or a second agent to check totals. Red (over 15%): send to a human.</li></ol><h3>Getting field accuracy from 92% to 99%</h3><p>99% means one wrong field in every 100. You won’t get there with a better OCR engine alone. You get there with a validation layer on top of it.</p><h4>Step 1: Find out where the errors come from</h4><p>Run about 500 pages from your golden set, pull every failure, and group them. A typical breakdown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jb1CN1_RZe4VxolF2CdQjQ.png" /></figure><p>Fix the biggest bucket first.</p><h4>Step 2: Cheap code checks first</h4><ul><li><strong>Checksums.</strong> Does Subtotal + Tax = Total? If not, test common misreads, like a 9 read as a 4.</li><li><strong>Regex.</strong> Dates, tracking numbers and IDs follow fixed patterns. Flag anything that doesn’t match.</li><li><strong>Fuzzy matching against master data.</strong> Compare vendor names to the customer’s CRM. “Smlth &amp; Co.” becomes “Smith &amp; Co.” automatically.</li></ul><h4>Step 3: An LLM reviewer for what code can’t fix</h4><ul><li><strong>Fix from context.</strong> Give a small model the surrounding text: “OCR read the date as 01/3l/2026. Correct it to ISO format.” It sees that the l is a 1.</li><li><strong>Two models must agree.</strong> For critical numbers, extract twice: once with your OCR engine and once with a vision LLM. If they agree, accept. If not, send it to a tie-breaker agent.</li></ul><h4>Step 4: Confidence scores and a human in the loop</h4><p>Fully automatic 100% accuracy on messy scans isn’t realistic. Be upfront with the customer about that.</p><ul><li>Give every field a confidence score from 0.0 to 1.0, based on scan clarity and which checks passed.</li><li><strong>0.95 or higher:</strong> straight into the database.</li><li><strong>Below 0.95:</strong> into a review screen where a person confirms it with one click.</li></ul><p>If humans review the 5 to 10% of fields the system is least sure about, the data that reaches the database can clear 99%.</p><h3>Takeaways</h3><ul><li>Route pages so you only pay for vision OCR where you need it.</li><li>Keep bounding boxes. They are your citations.</li><li>Measure fields and tables, not just characters.</li><li>99% comes from validation and human review, not a better engine.</li></ul><p><strong>Next in this series:</strong> <a href="https://ankitgoelcmu.medium.com/why-rag-still-hallucinates-and-what-advanced-rag-fixes-fd66f40008f5">https://ankitgoelcmu.medium.com/why-rag-still-hallucinates-and-what-advanced-rag-fixes-fd66f40008f5</a></p><p>, why RAG still hallucinates even with clean data, and what advanced RAG does about it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b2100bffd9f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-rag-is-only-as-good-as-your-ocr-7b2100bffd9f">Your RAG Is Only as Good as Your OCR</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why RAG Still Hallucinates, and What Advanced RAG Fixes]]></title>
            <link>https://levelup.gitconnected.com/why-rag-still-hallucinates-and-what-advanced-rag-fixes-fd66f40008f5?source=rss-de94f8b1bcf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd66f40008f5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ankit Goel]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 20:51:01 GMT</pubDate>
            <atom:updated>2026-11-06T15:17:35.092Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of 3: OCR and RAG, end to end</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rvcBFzcum1qgBmhTOCVmAg.png" /></figure><p>In Part 1 we turned messy documents into clean, tagged chunks in a vector database. Clean data is necessary, but it isn’t enough. RAG can still pull the wrong chunk, or pull the right one and ignore it.</p><p>This post covers:</p><ul><li>How retrieval scores a chunk: cosine similarity vs. dot product</li><li>The six most common reasons RAG still hallucinates</li><li>Advanced RAG: what to add before, during and after retrieval</li></ul><h3>How retrieval scores a chunk: cosine vs. dot product</h3><p>Both score how close a query is to a chunk. The difference is one word: <strong>magnitude</strong> (the length of the vector).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EsfVrjTOh-RA8yoT8YckmQ.png" /></figure><h4>The shortcut: normalized vectors</h4><p>If every vector has length 1 (L2-normalized), cosine and dot product give <strong>identical</strong> scores and rankings. Most popular embedding models (OpenAI text-embedding-3, Cohere, BGE, Jina) already normalize, or have an option to.</p><h4>Which one to pick</h4><p>The rule: <strong>use the metric your embedding model was trained with.</strong> Beyond that:</p><ul><li><strong>Pick cosine</strong> when vectors aren’t normalized and chunk lengths vary a lot, or when you want scores in a fixed range for thresholds.</li><li><strong>Pick dot product</strong> when vectors are normalized (same results as cosine, faster), or when length carries meaning. Some recommendation models encode popularity in vector length, so popular items rank higher.</li></ul><h3>Why RAG still hallucinates</h3><p>RAG cuts hallucinations a lot. It doesn’t remove them. In production the cause is usually plumbing, and it fails in one of two places.</p><h4>Retrieval failures (garbage in)</h4><ul><li><strong>Chunk boundaries.</strong> Split every 500 words and a fact can land in chunk A while what it refers to lands in chunk B. Retrieve only A and the LLM guesses.</li><li><strong>Sounds similar, isn’t the same.</strong> Ask “Did we sign the agreement with Company X?” and vector search may return chunks about <em>drafting</em> that agreement. The LLM then says it was signed.</li><li><strong>Conflicting versions.</strong> Proposal_Draft_V2.pdf and Proposal_FINAL.pdf both sit in the index. Old and new facts get mixed.</li></ul><h4>Generation failures (garbage out)</h4><ul><li><strong>Prior knowledge wins.</strong> If your document contradicts something the model learned in training, it may go with its training.</li><li><strong>Lost in the middle.</strong> Pass 20 chunks and the model pays most attention to the first and last. Facts in the middle get missed.</li><li><strong>Going along with a false premise.</strong> Ask “Why did revenue drop 50%?” and the model may invent a reason instead of saying it didn’t drop.</li></ul><h4>Quick fixes</h4><ul><li><strong>Hybrid search plus reranking.</strong> Combine vector search (meaning) with BM25 keyword search (exact SKUs, serial numbers). Then rerank with a model like Cohere Rerank or BGE-Reranker.</li><li><strong>Let the model say “I don’t know.”</strong> For example: <em>“Answer using ONLY the context below. If the answer isn’t there, say ‘I do not have enough verified information to answer.’”</em></li><li><strong>Check the answer before the user sees it.</strong> Tools like DeepEval or Galileo score <strong>faithfulness</strong> (does the answer match the context?) and <strong>answer relevance</strong> (did it answer the question?).</li></ul><p>These help. To go further, you change how retrieval itself works.</p><h3>Advanced RAG</h3><p>Naive RAG takes the top 5 vector matches and hands them to the LLM. Advanced RAG adds work before, during and after retrieval, so the LLM gets the best possible context.</p><h4>Before retrieval: fix the query</h4><ul><li><strong>Query rewriting.</strong> Users write vague questions. An LLM rewrites them 3 or 4 ways, or splits a complex question into sub-questions.</li><li><strong>HyDE (Hypothetical Document Embeddings).</strong> A fast LLM writes a fake ideal answer, and you search with that. An answer looks more like your documents than a question does.</li></ul><h4>During retrieval: fix the data structure</h4><ul><li><strong>Small-to-big (parent-child) chunks.</strong> Search over small, precise sentences. When one matches, return the full paragraph around it. This fixes the chunk-boundary problem.</li><li><strong>Hierarchical retrieval.</strong> Search document summaries first to find the right document, then search only that document’s chunks.</li></ul><h4>After retrieval: fix the context</h4><ul><li><strong>Cross-encoder reranking.</strong> Vector search is fast but shallow. Take the top 20 to 50 results and let a reranker (Cohere Rerank, BGE-Reranker, Jina Rerank) score each one against the query, then reorder.</li><li><strong>Context compression.</strong> Tools like LongLLMLingua drop filler and boilerplate, so the prompt is shorter and less gets lost in the middle.</li><li><strong>Corrective RAG (CRAG).</strong> An agent grades the retrieved chunks before generation. If they’re weak, it tries another source instead of passing on bad context.</li></ul><h3>Which fix for which failure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTviCVIYMqD-PGxM9b9epg.png" /></figure><h3>Takeaways</h3><ul><li>Use the similarity metric your embedding model was trained with. With normalized vectors, cosine and dot product are the same.</li><li>Most hallucinations start in retrieval, not in the model.</li><li>Advanced RAG is a set of small fixes, each aimed at one failure. Add the one that matches your failure.</li></ul><p><strong>Next in this series:</strong> <a href="https://ankitgoelcmu.medium.com/your-rag-works-in-the-demo-heres-why-it-fails-in-production-0721c7e713f3">https://ankitgoelcmu.medium.com/your-rag-works-in-the-demo-heres-why-it-fails-in-production-0721c7e713f3</a></p><p>, how to measure retrieval with Precision@K, Recall@K, MRR and NDCG, and how to debug a RAG system that worked in the demo but fails in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd66f40008f5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/why-rag-still-hallucinates-and-what-advanced-rag-fixes-fd66f40008f5">Why RAG Still Hallucinates, and What Advanced RAG Fixes</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your RAG Works in the Demo. Here’s Why It Fails in Production.]]></title>
            <link>https://levelup.gitconnected.com/your-rag-works-in-the-demo-heres-why-it-fails-in-production-0721c7e713f3?source=rss-de94f8b1bcf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0721c7e713f3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Ankit Goel]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 20:48:57 GMT</pubDate>
            <atom:updated>2026-11-06T15:17:17.790Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3 of 3: OCR and RAG, end to end</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aS11UN1cYa-oZ_5k3JKJTw.png" /></figure><p>Part 1 built clean data. Part 2 covered the retrieval tricks that stop hallucinations. But most RAG systems that fail in production don’t fail for lack of tricks. They fail because nobody measured retrieval, so nobody saw it break.</p><p>This post covers:</p><ul><li>The @K metrics: Precision@K, Recall@K, MRR and NDCG</li><li>Why production pipelines use two Ks, not one</li><li>Why RAG works in the demo but fails in production, and how to debug it</li></ul><h3>Measuring retrieval: the @K metrics</h3><p>K is the number of chunks you retrieve. Measure retrieval on its own, separate from the LLM, against a human-checked test set.</p><h4>Precision@K: how clean is the context?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LvkPU2k7o2QfEotRWznT4A.png" /></figure><p>You retrieve 5 chunks and 3 are useful. Precision@5 = 3/5 = 0.60. High precision means less noise for the LLM to get confused by.</p><h4>Recall@K: did you find everything?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HgG3BS6JyRX2kvSGomjjTg.png" /></figure><p>10 chunks in the database are relevant. Your top 5 has 4 of them. Recall@5 = 4/10 = 0.40. High recall means you didn’t miss a caveat or footnote.</p><p><strong>The trade-off:</strong> raise K from 5 to 50 and recall goes up (wider net), but precision goes down (more junk).</p><h4>Order matters too: MRR and NDCG</h4><p>Precision and recall treat every slot the same. LLMs don’t. They pay most attention to the top.</p><ul><li><strong>MRR (Mean Reciprocal Rank):</strong> 1 / rank of the first relevant chunk, averaged over queries. First chunk relevant: 1.0. First relevant chunk at #3: 0.33. Best for single-fact questions.</li><li><strong>NDCG (Normalized Discounted Cumulative Gain):</strong> grades relevance (0 = no, 1 = somewhat, 2 = very) and discounts lower positions by 1 / log2(position + 1). Best when the strongest chunks must sit in the top two slots.</li></ul><h4>Two Ks, not one</h4><p>Rerankers are slow, so you can’t run them on the whole database. Production pipelines use two stages:</p><ol><li><strong>K₁ (the net):</strong> vector search pulls a wide set, say 25 to 30 chunks.</li><li><strong>K₂ (the plate):</strong> the reranker reorders them and keeps the best 5 for the LLM.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60qfooSq6KpLjvw3PbBDYA.png" /></figure><p>Measure each stage with the metric that fits it:</p><ul><li><strong>Recall@K₁ tests your embeddings and chunking.</strong> If the right chunk isn’t in the top 25, the reranker can’t save it.</li><li><strong>Precision@K₂ and NDCG@K₂ test your reranker.</strong> Recall@25 at 95% but Precision@5 at 10%? The reranker is pushing junk to the top.</li></ul><p>Quick debugging rule:</p><ul><li><strong>Model misses facts or says “I don’t know”</strong> → recall at K₁ is broken. Try a better embedding model, better chunking, or a bigger K₁.</li><li><strong>Model hallucinates or drifts</strong> → precision at K₂ is broken. Upgrade the reranker or tighten K₂.</li></ul><h4>Why adding a reranker can raise Recall@5</h4><p>It sounds odd: a reranker only reorders. Here’s how it works with one golden chunk that vector search ranks at #8.</p><ul><li><strong>Without a reranker:</strong> you take the top 5. The golden chunk at #8 is cut. Recall@5 = 0%.</li><li><strong>With a reranker:</strong> you take the top 25, so #8 is in the pool. The reranker moves it to #1. You keep the top 5. Recall@5 = 100%.</li></ul><p>The reranker didn’t find new data. It let you cast a wider net safely. If you rerank only the same 5 chunks, Recall@5 doesn’t change (only MRR and NDCG do).</p><h4>Tools that wrap all of this</h4><p>Frameworks like Ragas and DeepEval turn these metrics into three LLM-assisted scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEdB-Crk8my4cRJQWCtgig.png" /></figure><h3>Why does RAG work in the demo but fail in production?</h3><p><strong>Short answer:</strong> the demo tested an easy version of the problem. Production changes the data, the questions and the scale all at once, and nothing measured the gap.</p><h4>What changes between demo and production</h4><ul><li><strong>The data gets messy.</strong> The demo used 20 clean PDFs. Production has thousands of scans, phone photos, duplicates and old versions.</li><li><strong>The questions change.</strong> You wrote the demo questions, using the same words as the documents. Real users are vague, use acronyms and typos, and ask two things at once.</li><li><strong>The haystack grows.</strong> Finding the top 5 in 500 chunks is easy. In a million chunks, many near-matches crowd out the right one, and Recall@K drops.</li><li><strong>The index goes stale.</strong> The demo index was built once. Real documents change every week. Without re-indexing, answers come from last quarter.</li><li><strong>Filters and permissions shrink results.</strong> Users can only see some documents. Filtering after retrieval can leave the top 5 with nothing useful in it.</li><li><strong>Latency and cost cut corners.</strong> To hit response-time targets, teams lower K or skip the reranker, which is exactly what made the demo work.</li><li><strong>Nobody is measuring.</strong> The demo was judged on 10 hand-picked questions. Production has no golden set, so failures show up as user complaints, not metrics.</li></ul><h4>How to debug it: trace one failing question</h4><p>Take a question that got a bad answer. Walk it through the pipeline in order and stop at the first “no.” That stage is your bug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CwNaukI-JdHbYxXbHbXY0Q.png" /></figure><p>Most teams jump to step 6 and change the prompt. In practice, most failures start in steps 1 to 4.</p><h4>Make it repeatable</h4><ul><li><strong>Log every request:</strong> the query, the rewritten query, the retrieved chunk IDs with scores, the reranked list and the final prompt. Without this you can’t do the trace above.</li><li><strong>Turn every failure into a test.</strong> Add each bad question, with its correct source chunk, to your golden set.</li><li><strong>Track the metrics on every change:</strong> Recall@K₁, Precision@K₂ and faithfulness. A fix that improves one question but drops recall overall isn’t a fix.</li></ul><h3>Bottom line for the series</h3><p>A good answer depends on every stage before it.</p><ul><li><strong>OCR</strong> decides whether the data is right at all. Measure fields and tables, not just characters.</li><li><strong>Validation and humans in the loop</strong> take you from 92% to 99%. A better engine alone won’t.</li><li><strong>Retrieval</strong> decides whether the LLM sees the right facts. Measure recall wide (K₁), then precision narrow (K₂).</li><li><strong>Generation</strong> needs guardrails: citations, permission to say “I don’t know,” and a faithfulness check.</li></ul><p>Fix problems where they start. A hallucination at the end often begins with a misread digit in Stage 2.</p><p><em>Missed the earlier parts? </em><a href="https://ankitgoelcmu.medium.com/your-rag-is-only-as-good-as-your-ocr-7b2100bffd9f"><em>Part 1</em></a><em> covers the OCR pipeline and accuracy. </em><a href="https://ankitgoelcmu.medium.com/why-rag-still-hallucinates-and-what-advanced-rag-fixes-fd66f40008f5"><em>Part 2</em></a><em> covers why RAG hallucinates and advanced RAG.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0721c7e713f3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-rag-works-in-the-demo-heres-why-it-fails-in-production-0721c7e713f3">Your RAG Works in the Demo. Here’s Why It Fails in Production.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An AI Just Edited Another AI’s Brain. No Training Required.]]></title>
            <link>https://levelup.gitconnected.com/an-ai-just-edited-another-ais-brain-no-training-required-eae29176d031?source=rss-de94f8b1bcf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/eae29176d031</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-research]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Ankit Goel]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 23:52:00 GMT</pubDate>
            <atom:updated>2026-11-06T15:18:28.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMCO8CLdqCEjb5pLveJWmQ.png" /></figure><p>A small AI model kept getting stuck in its own thinking. Another AI opened up its weights, found the problem, and fixed it by hand.</p><p>No training run. No new data. It changed 0.016% of the numbers, and the small model’s math score went from 7.9% to 48.1%.</p><p>This comes from a <a href="https://rikiyat.github.io/blog/weight-space-programming/">November 2, 2026 blog post</a> by four MIT CSAIL researchers: Rikiya Takehi, Jayden Teoh, Alex Zhang, and Omar Khattab (who also created DSPy). They call the idea <strong>weight-space programming</strong>.</p><p>Here’s what it is, what they showed, and where it breaks.</p><h3>How models usually change</h3><p>A neural network is just a big pile of numbers called weights. Today there are a few ways to set them:</p><ul><li><strong>Training with gradient descent.</strong> Show the model examples, measure the error, nudge every weight a little. Repeat millions of times. This is how almost every model is built.</li><li><strong>Fine-tuning.</strong> Same idea, smaller scale, on new data for a new task.</li><li><strong>Generated weights.</strong> One network trained to output another network’s weights.</li></ul><p>In all of these, nobody decides what a single weight should be. An optimizer does it blindly, one tiny step at a time.</p><p>Weight-space programming skips that. An LLM looks at the weights, reasons about what they do, and edits them on purpose, the way an engineer edits code.</p><h3>What weight-space programming is</h3><p>You give a strong LLM (here, GPT-6 Astra) two things:</p><ul><li>the raw weights of another network</li><li>a goal in plain English, like “stop this model from looping” or “write a network that plays Breakout”</li></ul><p>The LLM then reads, fixes, or writes the weights directly. No training loop.</p><p>How it sees the weights depends on size:</p><ul><li><strong>Small networks:</strong> every weight is pasted into the prompt as text.</li><li><strong>Larger networks:</strong> the LLM gets a Python sandbox to inspect them, and sometimes a small budget of test runs (forward passes) to check its work.</li></ul><h3>An analogy: neurosurgery for AI</h3><p>Think of it like neurosurgery. When someone has a tremor, doctors don’t retrain their whole brain. With deep brain stimulation, they find the one circuit that’s misfiring and intervene right there.</p><p>The pieces line up:</p><ul><li><strong>Reading weights = reading a brain scan.</strong> Naming a game from the weights is like looking at a scan and saying “this person plays piano.”</li><li><strong>Fixing Qwen = removing a faulty pathway.</strong> Astra found the circuit causing the loops and switched it off. That’s closer to precise surgery than to retraining.</li><li><strong>The limits match too.</strong> Surgery can quiet a misfiring circuit, but it can’t teach someone French. Editing weights can remove a fault, but it can’t add a skill the model never learned.</li></ul><h3>What they showed</h3><p>The team ran 8 experiments in three groups: reading weights, fixing them, and writing them from scratch.</p><h3>1. Reading: what does this network do?</h3><ul><li>Four game-playing agents, all with the same shape and inputs. Astra wasn’t told which games. Looking only at the weights, it named all four correctly: Breakout, Pong, Pac-Man, Freeway.</li><li>Three small image generators. Without running them, it said which one draws circles, squares, or triangles.</li><li>Tiny language models. From just their middle layers, it named what each was trained on (Python, English, or romaji Japanese) and found the attention heads that copy patterns.</li></ul><h3>2. Fixing: a car that never made it up the ramp</h3><p>A game agent trained for 1 billion steps kept driving into a ramp and stalling. Astra read its weights plus one recorded run, explained the bug, and wrote a fix in one reply.</p><ul><li>Weights changed: 3.5%</li><li>Success rate: 0% → 100% over 1,024 runs</li></ul><h3>3. Writing: networks from zero</h3><p>Astra got game rules and an all-zero network, then wrote every weight as text. No data, no training, no tools. Scores vs. PPO trained for 100M steps:</p><ul><li><strong>Breakout:</strong> PPO 15.8 → Astra 517.4</li><li><strong>Seaquest:</strong> PPO 5.6 → Astra 53.1</li><li><strong>Asterix:</strong> PPO 25.8 → Astra 53.2</li></ul><p>For Breakout it basically wrote a program in weights: layer one works out where the ball will land, layer two moves the paddle there.</p><h3>4. The headline: fixing Qwen’s thinking loops</h3><p>Qwen3.5–0.8B is known to get stuck in loops while reasoning. In the tests, 93% of its math answers ran until they hit the token limit.</p><p>With a Python sandbox and 50 test runs, Astra traced the loops to one direction in two MLP layers (15 and 19) and subtracted it. That touched 131,072 weights out of 0.8 billion.</p><ul><li><strong>MATH-500:</strong> 7.9% → 48.1%</li><li><strong>GSM8K:</strong> 13.8% → 67.1%</li><li><strong>IFEval (instruction following):</strong> 21.0% → 62.3%</li></ul><p>Instruction following improved too, because loops hurt every task, not just math.</p><p>The result has already been checked once. Hugging Face’s Ahsen Khaliq rebuilt the edited model from the logs and got 51.0% on MATH-500. The edited model and a demo are both public on Hugging Face.</p><h3>Where it breaks</h3><p>The authors were upfront about the failures, and they matter as much as the wins.</p><ul><li><strong>It can remove a fault, not add a skill.</strong> Gemma 3 270M is bad at math but doesn’t loop. With no single bug to remove, Astra’s best edit moved its MATH-500 score from 6.8% to 7.7%.</li><li><strong>Some behavior doesn’t show up in weights.</strong> Astra couldn’t tell an honest model from a sycophantic one by weights alone. Once it could see their attention patterns, it caught the sycophant every time.</li><li><strong>More training still wins sometimes.</strong> PPO agents trained for 500M steps beat Astra on Seaquest and Asterix.</li><li><strong>Test budget matters.</strong> With 10 or 25 test runs instead of 50, Qwen’s loops barely went away.</li><li><strong>It’s early.</strong> One LLM, networks up to 0.8B weights, and a blog post, not a peer-reviewed paper. The team is still building a benchmark.</li></ul><h3>Why it matters if you build with AI</h3><p>This isn’t a production tool yet. But three things are worth watching:</p><ul><li><strong>Debugging models like code.</strong> Today, when a small model has one narrow bug, the fix is fine-tuning on new data. A targeted edit to 0.016% of weights leaves the rest of the model alone, so there’s less risk of breaking what already works.</li><li><strong>A first pass at interpretability.</strong> “Ask a frontier model what this layer does” could become the quick check before heavier interpretability tools.</li><li><strong>Auditing without running.</strong> The authors hope this leads to checking models for backdoors or removing capabilities without data. That’s a goal, not a result yet.</li></ul><p>There’s a pattern here too. LLMs already tune prompts, write programs, and write training code. This pushes the same reasoning one level down, into the weights.</p><h3>Bottom line</h3><p>Weight-space programming shows a frontier LLM can read and edit a network’s weights by reasoning, at least for small models with one clear bug.</p><p>It won’t replace training. It might become how we debug models.</p><p>The best part: everything is public. The prompts, outputs, and scores are on GitHub, and you can try the edited Qwen model yourself on Hugging Face.</p><h3>Sources</h3><ul><li><a href="https://rikiyat.github.io/blog/weight-space-programming/">Sparks of Weight-Space Programming (original MIT blog post)</a></li><li><a href="https://github.com/RikiyaT/lm_understand-logs">Experiment logs on GitHub</a></li><li><a href="https://huggingface.co/RikiyaT/Qwen3.5-0.8B-weight-space-programming">Edited Qwen3.5–0.8B on Hugging Face</a></li><li><a href="https://huggingface.co/spaces/akhaliq/weight-space-programming-demo">Hugging Face demo: base vs. edited model</a></li><li><a href="https://www.datacamp.com/blog/weight-space-programming">DataCamp: Weight-Space Programming explained</a></li><li><a href="https://venturebeat.com/technology/like-gene-editing-for-neural-networks-mit-researchers-used-gpt-6-astra-to-edit-qwens-open-weights-directly-boosting-math-performance">VentureBeat coverage</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eae29176d031" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/an-ai-just-edited-another-ais-brain-no-training-required-eae29176d031">An AI Just Edited Another AI’s Brain. No Training Required.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>