<?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 Simran Kaur Kahlon on Medium]]></title>
        <description><![CDATA[Stories by Simran Kaur Kahlon on Medium]]></description>
        <link>https://medium.com/@simran-kahlon?source=rss-83917a9b1446------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*rGYDTpMFyg1VAbn9aXTkdQ.jpeg</url>
            <title>Stories by Simran Kaur Kahlon on Medium</title>
            <link>https://medium.com/@simran-kahlon?source=rss-83917a9b1446------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:25:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simran-kahlon/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[The Agent That Ships Code — Part 1: Getting It Right From Line Zero]]></title>
            <link>https://simran-kahlon.medium.com/the-agent-that-ships-code-part-1-getting-it-right-from-line-zero-d060b4ef78bf?source=rss-83917a9b1446------2</link>
            <guid isPermaLink="false">https://medium.com/p/d060b4ef78bf</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-coding-agent]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Simran Kaur Kahlon]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 11:54:01 GMT</pubDate>
            <atom:updated>2026-10-10T11:54:33.040Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 1 of the series </em><strong><em>“The Agent That Ships Code.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/the-agent-that-ships-code-part-1-getting-it-right-from-line-zero-d060b4ef78bf?sharedUserId=simran-kahlon"><em>Introduction</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCdI6nTBgl3fQ5pwlUkbVw.png" /></figure><p>In the intro, I laid out what we’re building — a pipeline that reads error logs, groups them into bugs, and lets an agent investigate, fix, and open a draft PR. If you haven’t read it, start there.</p><p>Before any of that, the project has to actually exist. Just an empty command-line tool that does nothing yet. This article is about what I put into it before writing a single feature.</p><p>It’s the boring part. Nobody writes about it. But every decision here saved me later, so let’s do it properly.</p><h3>Why bother before there’s anything to build?</h3><p>This pipeline would eventually hold AWS credentials, a Jira token, and write access to a repo. The moment something holds secrets and can write to real systems, a sloppy setup turns into a leaked key or a weird bug three phases deep that takes you an hour to track down.</p><p>The setup is cheapest to get right when there’s nothing there yet. So three things went in first.</p><h3>Config that checks itself</h3><p>The usual way people read config in Python is os.getenv() sprinkled wherever they need a value. It works — until someone typos a variable name. Then the program runs anyway with a missing value and blows up somewhere confusing later.</p><p>So instead, all config goes through one schema. Every setting lives in one place, with a type. If something required is missing, the program stops right at startup and tells you exactly which field is wrong.</p><p>That’s the whole point. Instead of debugging a weird failure three steps in, you get a clear error in about 200ms with the field name. Your secrets are protected by the schema refusing to start — not by a note in the README reminding you to set them.</p><h3>Logging from the very first line</h3><p>Next thing in was logging. Not print statements — proper structured logging, where every line is a JSON object with a run ID attached.</p><p>Why set this up when there’s nothing to log yet? Because once this thing is spawning agents, writing files, and opening PRs, you’ll want to see exactly what happened in one run. With a run ID on every line, you can pull a whole run’s story out of the logs with a single grep.</p><p>And there’s a bigger payoff later. Further into the series we build a way to actually evaluate what the pipeline did — and that only works because the logs were structured from day one. You can’t bolt observability onto a system that wasn’t built for it.</p><h3>Secrets that never touch the repo</h3><p>No committed config file. None. In a project sitting on AWS keys and tokens, a committed config file is a leak waiting to happen — one careless commit and your secrets are in git history forever.</p><p>So config comes from the environment. A .env file holds the real values and is git-ignored. A .env.example with just the key names (no values) gets committed, so anyone cloning the repo knows what to set without ever seeing a real secret.</p><h3>One thing people get backwards</h3><p>The order these load in matters:</p><ol><li>Config first — so bad env vars fail before anything else even runs.</li><li>Logging second — so every line after that carries the run ID.</li></ol><p>Flip it and your earliest, most important failures are the ones you can’t see cleanly.</p><p>And that’s the scaffold. No agent, nothing to show off. But the config schema, the structured logs, and the secrets setup are the foundation everything else stands on.</p><p>Next up we write the first real feature — fetching the error logs. And the first lesson is resisting the most tempting beginner move: reaching for the AI to do a job that should never be the AI’s.</p><p><em>This is Part 1 of </em><strong><em>“The Agent That Ships Code.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/the-agent-that-ships-code-part-1-getting-it-right-from-line-zero-d060b4ef78bf?sharedUserId=simran-kahlon"><em>Introduction</em></a> <em>▶ Part 2: Why Reading Your Logs Is Not an AI Problem — coming next</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d060b4ef78bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Agents, The Way Nobody Told You — Part 13: The Lessons]]></title>
            <link>https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-13-the-lessons-d24e83a9bacb?source=rss-83917a9b1446------2</link>
            <guid isPermaLink="false">https://medium.com/p/d24e83a9bacb</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agent-orchestration]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Simran Kaur Kahlon]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 10:30:09 GMT</pubDate>
            <atom:updated>2026-10-02T10:30:09.189Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the final part of the series </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-12-how-do-you-test-an-agent-88161d3bf209?sharedUserId=simran-kahlon"><em>◀ Part 12: How Do You Test an Agent?</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3PidcEjJ_7XdAD5dU7k3g.png" /></figure><p>This is the last article. I want to use it differently from the rest.</p><p>Everything so far was technical — the loop, tools, memory, sub-agents, hooks, caching, testing. The what and the how. This one is the what-now. The principles that survived the project, the decisions I would reverse with hindsight, and a few opinions I kept off the page until now.</p><p>If you have stuck with me through twelve articles, this is where I tell you what the whole thing actually taught me.</p><h3>The principles worth keeping</h3><p>These are the ideas that earned their place. I use them at work now, not just in agent code. They generalise.</p><p><strong>Design observability when you build, not after.</strong></p><p>The single most important principle from the series. The audit log in Part 7 did not exist because I needed testing — it existed because hooks needed to record every gated decision. Then in Part 12, the entire testing harness fell out of it almost for free.</p><p>You cannot bolt observability onto a system that was not built for it. What you can observe later is fixed by the architecture you choose now. Build every system to emit structured events from day one, even when you do not yet know what they are for. Future you will thank present you.</p><p><strong>Stable contracts, evolving implementations.</strong></p><p>The core data types in the project did not change once across all the phases. The implementations behind them changed constantly — single-shot to tools, in-process to MCP, prose to structured results. The interface stayed. The engine swapped underneath.</p><p>This is the highest-leverage habit in modern engineering. Every interface you write is either a stable contract — small, deliberate, change-resistant — or a leaky implementation detail that sprawls and couples everything together. The first kind compounds. The second kind rots.</p><p><strong>Trade latency for grounding.</strong></p><p>Every tool call replaces a chance to hallucinate with a verified fact. The single-shot version was fast and lying. The tool version was a little slower and correct. Correct and slightly slower beats fast and wrong for any customer-facing system, every time.</p><p>I have watched people optimise agents the wrong way — cutting tool calls to make it feel snappier — and ship agents that lie to users faster. The extra time is the agent checking its facts instead of guessing. That is time well spent.</p><p><strong>Agents are tools.</strong></p><p>Wrap everything — sub-agents, external APIs, side effects, database queries — as tool calls. Same mechanism, same hook layer, same audit log, same test surface.</p><p>The question in agentic systems is never “should this be a tool?” It is “is there a reason this is not a tool?” Direct Python calls give you none of the observability, gating, or composability the tool surface gives you for free.</p><p><strong>The output is not proof. The trajectory is proof.</strong></p><p>The agent that fluently describes work it never did. The reply that sounds right while nothing actually happened underneath. This is the production bug that defines agent engineering. If you remember nothing else from this series, remember this one.</p><p><strong>Capability, authorisation, policy — different layers.</strong></p><p>This took me longest to internalise. Tools check shape — are these inputs valid. Hooks check permission and policy — are you allowed to do this right now. They are different layers because they need different inputs. Tools only see what the model generated. Hooks also see the trusted server-side truth. Put the right check in the right layer and the whole codebase gets cleaner in a way that is hard to describe until you feel it.</p><h3>Decisions I would reverse</h3><p>Being honest about what I would change.</p><p><strong>I should have built the audit log in Part 4, not Part 7.</strong></p><p>Until Part 7, my logging was print statements. When I finally built the audit hook, I was retrofitting observability into an agent that had none. It worked, but I had spent several phases debugging blind.</p><p>The audit log is so cheap to add and so valuable to have that it should have been one of the first things I built. If you are starting your own agent: add structured logging in week one. Not later.</p><p><strong>I underestimated how much of this is API contract management.</strong></p><p>I thought agents would be about prompts and reasoning. Most of the actual difficulty turned out to be protocol mechanics — the tool_use and tool_result binding, the alternating-roles rule, the BLOCKED prefix convention, the byte-exact cache rule, the streaming timing rules.</p><p>None of that is prompting. It is the boring engineering layer underneath the magic, and it is almost the entire job. If I started over, I would read the tool-use, streaming, and prompt-caching sections of the API reference closely before writing any code — that is where the contracts that actually bite you live.</p><p><strong>I should have built a tiny testing harness early.</strong></p><p>The harness in Part 12 caught real bugs. But a three-case version right after the agent loop existed would have caught earlier bugs earlier. Trajectory testing does not need MCP, hooks, or sub-agents to be useful. It needs an audit log, a few expected behaviours, and a small scorer. Ship it early even if it is tiny.</p><p><strong>I should have used streaming from the start.</strong></p><p>I added streaming as an optimisation near the end. It turned out to be more than that — the agent felt alive, the experience improved, and debugging got easier because I could watch output as it streamed. It is not an optimisation. It is a default.</p><p><strong>I would be more aggressive about deleting flexibility.</strong></p><p>Early on I wrote a lot of code that was flexible in case future needs changed. Most of that flexibility was never used and some of it made the code harder to follow. The phases where I wrote the most opinionated, least-flexible code aged the best. You are not gonna need it applies harder to agent code than most, because the problem space moves so fast that future-proofing guesses are usually wrong.</p><h3>Opinions you might not have heard</h3><p>These are takes I have not seen written elsewhere. I could be wrong about any of them. This is just how I think after building the thing.</p><p><strong>Frameworks are mostly a distraction when you are learning.</strong></p><p>I built the whole agent without any framework — raw SDK, my own Python, MCP. The result was easier to understand, debug, evolve, and teach. If you are learning, build from the SDK first. You will understand what frameworks abstract over, which means you can actually judge whether you need one. Most people would be served by a few hundred lines of well-organised Python and an MCP server.</p><p><strong>The loop is the thing. Everything else is plumbing.</strong></p><p>Once you understand the four-step loop, you understand the heart of every agent. Frameworks, orchestration, multi-agent systems — all variations on the same loop with different things wrapped around it. If you can write the loop on a whiteboard, you can read any framework’s source and understand it in five minutes. If you cannot, every framework feels like magic. Get the loop into your bones.</p><p><strong>Sub-agents are the right idea. Most “multi-agent systems” are not.</strong></p><p>The orchestrator and specialist pattern is genuinely useful — focused prompts, scoped tools, cost-aware routing. What people often call multi-agent systems — agents arguing over a shared scratchpad, electing leaders, voting on decisions — looks impressive in demos and rarely ships. The real constraint is almost always “this agent needs to do specific work reliably,” and the answer is almost always one orchestrator, a few specialists, structured handoffs. Build boring. Boring ships.</p><p><strong>Most agents have more tools than they need.</strong></p><p>I started with twelve tools and ended with eleven, three of which I would happily delete. The model makes better decisions with a short, unambiguous tool list than with fifteen overlapping options. More tools means more decision burden means more confused routing. If you cannot articulate why a tool exists, delete it.</p><p><strong>The verdict field is one of the most useful patterns in agent engineering and almost nobody talks about it.</strong></p><p>Structured returns with a categorical verdict field that your code branches on, separate from the natural-language explanation. This one pattern eliminates endless “LLM parses LLM output” round-trips. It cuts API calls, cuts latency, makes the system deterministic where it should be, and makes real testing possible because you can assert on a verdict instead of parsing English. I think a lot of the next few years of agent improvements will look like replacing English with structured discriminators in more and more places.</p><h3>If you are just starting</h3><p>If you are about to build your first agent, here is the order I would recommend:</p><ol><li>Start with one API call and a structured schema. Reasoning before answer.</li><li>Build the four-step loop by hand. No frameworks. Print the messages list. Understand every block.</li><li>Add memory by moving the messages list onto an object. It is that simple.</li><li>Add an audit log. Now. Every tool call appends a record.</li><li>Add three test cases that read the audit log and check the right tools fired.</li><li>Build sub-agents. Wrap them as tools. Use the verdict pattern.</li><li>Add write tools with the case-file pattern — store-assigned IDs, append-only.</li><li>Move tools to an MCP server, while they are still small.</li><li>Add hooks for authorisation.</li><li>Add caching and streaming. Not later.</li><li>Grow your test suite as you go. Do not backfill it at the end.</li></ol><p>Each step adds one capability and answers one question. By the end you have a real agent and, more importantly, a real understanding of every layer in it.</p><h3>A note on learning</h3><p>I will close with something less technical.</p><p>I built this project because I learn by building. I wrote this series because I learn by explaining. Writing the articles taught me as much as building the agent did, maybe more. Putting concepts into words is a different operation than running them through code. Both are necessary.</p><p>If you have been reading this passively, I want to push back. You will not understand agents from reading about them — even from reading me. You will understand them from writing a tool definition, watching the model call it wrong, debugging why, and fixing it. Then doing that fifty more times.</p><p>The articles are a map. The territory is your terminal.</p><p>Pick a domain — support, scheduling, research, anything with multiple intents. Mock the backend. Write the loop yourself. Make every mistake I made plus the ones I missed. Then come back and re-read whichever article covers the thing you got stuck on. The second read will land in a way the first one could not.</p><p>Thank you for reading the whole series. Long-form technical writing only matters when someone reads it. Knowing this helped even one engineer trying to make sense of agents is why I will keep writing.</p><p>Now go build something.</p><p><em>This is the final part of </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-12-how-do-you-test-an-agent-88161d3bf209?sharedUserId=simran-kahlon"><em>Part 12: How Do You Test an Agent?</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d24e83a9bacb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Agents, The Way Nobody Told You — Part 12: How Do You Test an Agent?]]></title>
            <link>https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-12-how-do-you-test-an-agent-88161d3bf209?source=rss-83917a9b1446------2</link>
            <guid isPermaLink="false">https://medium.com/p/88161d3bf209</guid>
            <category><![CDATA[agent-orchestration]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agent-observability]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Simran Kaur Kahlon]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 08:39:05 GMT</pubDate>
            <atom:updated>2026-10-02T10:30:37.983Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 12 of the series </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-11-making-it-fast-and-cheap-056ad358a5cd?sharedUserId=simran-kahlon"><em>Part 11: Making It Fast and Cheap</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3PidcEjJ_7XdAD5dU7k3g.png" /></figure><p>Let me tell you about the bug that made me build a testing harness.</p><p>I was demoing the agent. The user said: “my practice test crashes every time I tap Submit on Android.” The agent replied: “I’m sorry about that. I’ve filed a ticket with engineering — they will look into it shortly.”</p><p>Sounded right. Looked right. Then I checked where tickets get stored.</p><p>No ticket.</p><p>The agent said it filed a ticket. It had not. The tool that files tickets was never called. The model made up the entire claim. And the user — me, in this case — was sitting there reassured, while engineering had no idea anything was broken.</p><p>This is the failure that breaks agents in production. The model is fluent enough to describe work it never did. The reply looks perfect. A human reading it has no way to tell the work did not happen. The user trusts the reply. The trust is misplaced.</p><p>If you only test the reply, you will never catch this. The reply looks correct. The test passes. Production is broken.</p><p>You have to test what the agent actually did. Which specialist ran. Which tools fired. Which hooks blocked things. Which files got written. That path — the sequence of what actually happened — is called the trajectory. Testing the trajectory, not just the final reply, is how you find out whether the agent did the work or only claimed to.</p><h3>Output testing vs trajectory testing</h3><p>There are two ways to test, and they catch different things.</p><p><strong>Output testing</strong> compares the final reply to an expected reply. This works fine for normal code — a function that sorts a list either returns the sorted list or it does not. The output tells you everything.</p><p><strong>Trajectory testing</strong> inspects the path — which specialist, which tools, which hooks, which files. This is what agents need.</p><p>Why the difference? Because for an agent, the reply is a symptom of the work, not the work itself. The exact same fluent reply could come from:</p><ul><li>Correct routing, correct tool calls, correct files written. Good.</li><li>No tool calls at all — the model just made the whole thing up. Broken.</li></ul><p>Output testing cannot tell these two apart. Trajectory testing can.</p><p>The shift in thinking: “did the right work actually happen?” matters as much as “did the reply look right.” Sometimes more. The reply is what the customer sees. The trajectory is the truth.</p><h3>What this failure looks like</h3><p>Just so the pattern is unmistakable, here are five real examples from my agent. Every one of them produces a fluent, helpful-sounding reply. Every one would pass output testing. Every one is broken.</p><ol><li>“I’ve filed ticket #47.” The ticket tool was never called. The model invented the ticket number.</li><li>“I see you’ve missed 3 sessions.” The call-logs tool was never called. The number was guessed from how the user phrased their message.</li><li>“You’re within the 14-day refund window.” Neither the purchase-history tool nor the date tool was called. Both dates were guessed.</li><li>“I’ve prepared a case file for our team.” No case file exists on disk. The tool was never called.</li><li>“I’ll loop in your counsellor.” That is actually a different specialist’s job. The wrong specialist was routed to.</li></ol><p>Fluent, plausible, wrong. Output testing says PASS on all five. Trajectory testing catches all five.</p><h3>The four things to score</h3><p>There are four independent questions you can ask about any agent run. Each one is scored separately, so when something fails you know exactly which part broke.</p><p><strong>Routing.</strong> Did the orchestrator delegate to the right specialist? You read this from the audit log — every delegate_to_specialist call records which specialist was chosen.</p><p><strong>Tools.</strong> Did the right tools fire, and did the forbidden ones stay silent? You read this from the audit log — every tool call is there.</p><p><strong>Hooks.</strong> Did the hooks block the calls they were supposed to block? You read this from the audit log — denied calls are recorded as errors with a BLOCKED marker.</p><p><strong>Artifacts.</strong> Did the right files get written, and did the forbidden ones stay unwritten? You check the actual files on disk before and after.</p><p>Each of these is a small function that takes what you expected and what actually happened, and returns pass or fail with a reason. Because they are separate, a run can pass three and fail one — and you know precisely which one, so you can debug straight to the problem.</p><p>The nice part is how naturally this handles complex cases. “This query should route to both counselling and refund” is just a set — did both appear in the actual routing? No special logic needed.</p><h3>Why the audit log is the source of truth</h3><p>Everything above reads from the audit log — the one we built back in Part 7. Not from special test-only instrumentation added to the agent. This matters, and here is why.</p><p><strong>It matches production exactly.</strong> The audit log is the same log production writes. If you added test-only tracking instead, you would have two code paths — one for production, one for tests — and they would drift. Your test would pass on a path real users never hit. Reading the production audit log removes that risk entirely. The test reads what production writes.</p><p><strong>It is free and fast.</strong> Reading a log file costs nothing. Re-running the agent with test-only tracking would burn API money on every test run.</p><p><strong>It decouples everything.</strong> The agent writes events to the log. Anyone — compliance, tests, dashboards, debugging — reads independently. Want a new metric? Write a new reader. You never touch the agent.</p><p><strong>It is replayable.</strong> You can run today’s test logic against last week’s log. Improve your scoring and re-check historical runs to see if old behaviour would now be flagged. You cannot do that with test-only tracking — you would have to re-run the whole agent.</p><p>The shape to remember: the audit log is a structured event stream with many readers. Build the log once, let each reader take what it needs. Same idea as event sourcing, or audit trails in banking. It generalises far beyond this project.</p><h3>This is where the architecture pays off</h3><p>Here is the part I want you to really see.</p><p>Trajectory testing was easy to build — around 150 lines — and it was easy only because of decisions we made much earlier in the series. Each one looked locally motivated at the time. Together they made testing almost free.</p><p><strong>Part 6 — sub-agents wrapped as tools.</strong> Because delegation goes through a tool call, routing appears in the audit log automatically. Had we made delegation a direct Python call, routing would be invisible to the log, and the routing scorer would be impossible.</p><p><strong>Part 5 — specialists return structured results with a verdict.</strong> Because the output is structured, scoring is unambiguous. Had specialists returned plain text, we would be parsing English to guess what happened.</p><p><strong>Part 6 — one uniform tool surface.</strong> Because every action flows through the same mechanism, one audit log captures everything. Had reads, writes, and delegation gone through different code paths, the log would only see some of them.</p><p><strong>Part 7 — the audit log and structured files.</strong> Because we log every tool call and write structured artifacts, there is a data source to test against at all. No audit log means no list of what fired. No structured files means no way to check what got written.</p><p>If any one of these had gone the other way — delegation as a direct call, specialists returning text, mixed tool surfaces, no audit log — trajectory testing would be impossible, or would need invasive instrumentation nobody wants to maintain.</p><p>The principle for the whole series: <strong>design observability when you build, not after.</strong> You cannot bolt it onto a system that was not built for it. What you can observe is fixed by architectural choices you make early. None of those four decisions were made for testing. But each one compounded into a system where the question “did the agent do the real work?” has a clear, readable answer in a log file.</p><h3>What a test case looks like</h3><p>Here is one real case:</p><pre>{<br>  &quot;case_id&quot;: &quot;EV-02&quot;,<br>  &quot;description&quot;: &quot;free user attempts a formal escalation — hook should DENY&quot;,<br>  &quot;user_id&quot;: &quot;u_001&quot;,<br>  &quot;user_message&quot;: &quot;my counsellor never showed up, I want a formal complaint filed&quot;,<br>  &quot;expected&quot;: {<br>    &quot;must_route_to&quot;: [&quot;counselling&quot;],<br>    &quot;must_be_denied_by_hook&quot;: [&quot;prepare_case_file&quot;],<br>    &quot;must_not_create_artifact&quot;: &quot;case_file&quot;<br>  }<br>}</pre><p>Three expectations, three scorers:</p><ul><li>Routing — was counselling delegated to?</li><li>Hooks — was the case-file tool denied by a hook?</li><li>Artifacts — did no case file end up on disk?</li></ul><p>All three pass, the case passes. Any one fails, the case fails — and the failure points at the exact layer that broke.</p><p>I keep about 15 cases like this — multi-concern queries, edge cases, attempted-abuse cases, simple happy paths. The full suite runs in about a minute. I run it periodically, not on every commit, because each run makes real API calls and real disk writes, and the cost adds up if you run it constantly.</p><h3>Two assertions that look redundant but are not</h3><p>Look at that test case again:</p><ul><li>The hook should deny the case-file tool.</li><li>No case file should be written.</li></ul><p>Are those not the same thing? If the hook denied it, no file gets written, right?</p><p>In a healthy system, yes. In a broken system, they come apart — and that is exactly what tells you where the bug is.</p><p><strong>If the hook fires but a file gets written anyway</strong> — the hook is fine, the file store has a bug. You know instantly it is a storage problem, not a hook problem.</p><p><strong>If the hook silently failed but no file got written</strong> — the hook is broken, and you only avoided a bad write by luck. The second assertion catches the hook bug the first one missed.</p><p>Two assertions for one guarantee. When they agree, the system is healthy. When they disagree, you know exactly which layer broke. Any time you can cheaply check the same thing at two layers, do it.</p><h3>Adding a new specialist costs almost nothing</h3><p>Say I add a sixth specialist tomorrow. What changes in the testing harness?</p><p>The scoring code — nothing. It reads a list of specialists that were routed to. No hard-coded list.</p><p>The trajectory builder — nothing. It extracts whatever specialist value the model produced.</p><p>The test cases — yes, add some for the new specialist.</p><p>That is it. The harness was built generically enough that a new specialist just slots in. This is the stable-contract-evolving-implementation idea from the start of the series paying off again. The scoring contract — “what does correct routing mean?” — stays stable. The set of specialists changes. The scorer does not.</p><p>When you build with the right contracts, adding new functionality is a config change, not a rewrite.</p><p>In Part 13 — the final article — I look back at the whole project and tell you what I would do differently, what I would keep, and what I think most people get wrong about building agents.</p><p><em>This is Part 12 of </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-11-making-it-fast-and-cheap-056ad358a5cd?sharedUserId=simran-kahlon"><em>Part 11: Making It Fast and Cheap</em></a> <em>▶ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-13-the-lessons-d24e83a9bacb"><em>Part 13: The Lessons</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88161d3bf209" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Agents, The Way Nobody Told You — Part 11: Making It Fast and Cheap]]></title>
            <link>https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-11-making-it-fast-and-cheap-056ad358a5cd?source=rss-83917a9b1446------2</link>
            <guid isPermaLink="false">https://medium.com/p/056ad358a5cd</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[prompt-caching]]></category>
            <dc:creator><![CDATA[Simran Kaur Kahlon]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 13:23:56 GMT</pubDate>
            <atom:updated>2026-10-02T08:46:03.126Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 11 of the series </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-10-langchain-and-the-sdk-landscape-e70e6426caff?sharedUserId=simran-kahlon"><em>Part 10: LangChain and the SDK Landscape</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3PidcEjJ_7XdAD5dU7k3g.png" /></figure><p>By now the agent works. It routes, looks things up, remembers, gates writes, audits everything. I was happy with it.</p><p>Then I looked at the bill.</p><p>Every turn was re-sending the entire system prompt — around 4,000 tokens of orchestrator and specialist instructions, tool definitions, persona setup. After ten turns, that same 4,000-token prefix had been billed ten times. Same bytes, same cost, ten times over.</p><p>And the experience was slow. The user types, the agent thinks for a few seconds, then the whole reply appears at once. Even when the agent was doing useful work, it felt like staring at a loading spinner followed by a wall of text.</p><p>This article fixes both. Caching fixes the cost. Streaming fixes the feel. They are independent — you can use one without the other — but in production you almost always want both.</p><p>One thing worth clearing up early, since it is a common misconception: caching is not only about money. When the API reuses a cached prefix, it skips reprocessing those tokens, so the response also starts coming back a little sooner. The cost saving is the main win. The speed-up is a smaller bonus on top. Streaming is still the real latency tool — we get to that in Part B.</p><h3>Part A — Prompt caching</h3><h3>The idea</h3><p>Every turn, you send the same system prompt and tool definitions. They do not change. So why pay to process them every single time?</p><p>Prompt caching lets you tell the API: “this part of the request is stable, remember it.” On the next call, if that stable part is byte-for-byte identical, the API charges you a fraction of the normal cost for it.</p><p>You mark the boundary with something called a cache_control breakpoint:</p><pre>system = [<br>    {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;text&quot;: &quot;You are a customer support agent. ... (all your instructions) ...&quot;,<br>        &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}   # everything up to here is cached<br>    }<br>]</pre><p>Everything before the breakpoint gets cached. Everything after it — user messages, tool results — stays dynamic. The breakpoint marks where the stable part ends.</p><h3>The savings are large</h3><p>Here is the pricing, simplified:</p><ul><li>The first call costs a little extra — about 25% more — to write the cache.</li><li>Every call after that, within the cache window, costs about 10% of normal for the cached part. A 90% discount.</li></ul><p>Let us put real numbers on it. Your system prompt and tools are 4,000 tokens, and you do 10 turns in a few minutes:</p><p><strong>Without caching:</strong> 10 × 4,000 = 40,000 tokens at full price.</p><p><strong>With caching:</strong> the first write (4,000 × 1.25) plus nine cheap reads (9 × 4,000 × 0.1) = 5,000 + 3,600 = 8,600 tokens billed.</p><p>That is roughly an 80% reduction. For most agents, the system prompt and tool definitions are the bulk of the per-turn cost. Caching takes the agent from expensive to nearly free.</p><p>There is a second benefit people forget. When the API reads a cached prefix, it skips reprocessing those tokens — so it also responds faster. The cached part does not have to be computed from scratch each time. So caching is not purely a cost win. It trims latency too. The bigger latency win still comes from streaming, which we get to next, but caching helps on both fronts.</p><h3>Caching also makes it faster</h3><p>Cost is the headline benefit, but there is a second one worth knowing. A cache hit is also faster.</p><p>When the API reads a cached prefix, it skips the work of processing those tokens again. Those thousands of tokens do not have to be re-computed from scratch on every turn. That reduces the time before the model starts producing its reply — the time-to-first-token drops.</p><p>So caching is not purely a cost feature. It saves money as its main effect, and it shaves latency as a bonus. Streaming is still the bigger lever for how fast the agent feels, but caching contributes on both fronts.</p><h3>The cache is byte-exact — this is the whole catch</h3><p>Here is the thing that trips everyone up. The cache does not understand meaning. It matches bytes.</p><p>If the stable part is byte-for-byte identical to the previous call, you get a cache hit. If a single character is different — a space, a comma, a reordered word — it is a different set of bytes, and you get a cache miss. The cache has no idea the two versions mean the same thing. It only sees bytes.</p><p>This is why what you put in the cached part matters so much. Anything that changes between calls will break the cache.</p><p>Keep these OUT of the cached prefix:</p><ul><li><strong>Dates and timestamps</strong> — they change, so the cache breaks every time they do.</li><li><strong>User IDs</strong> — bake a user ID into the system prompt and every user gets their own cache with a terrible hit rate.</li><li><strong>Anything random</strong> — request IDs, session IDs, anything that varies per call.</li></ul><p>Remember Part 4b, where we said dynamic data belongs in tools, not the system prompt? This is one of the reasons why. Dynamic data in the system prompt does not just go stale — it destroys your cache. Today’s date comes through a get_today_date() tool, which lands after the breakpoint. The cached prefix stays stable.</p><h3>The four cache-miss bugs I actually shipped</h3><p><strong>1. A date in the system prompt.</strong></p><pre>SYSTEM_PROMPT = f&quot;Today is {datetime.now().date()}. You are a support agent...&quot;</pre><p>The bytes change every day at midnight. The cache silently breaks once a day. Subtle, slow, and it quietly costs you money. Fetch the date with a tool instead.</p><p><strong>2. Tools in a non-deterministic order.</strong></p><p>If your tools live in a Python set, their order can change between process restarts. Different order means different bytes means cache miss. Sort them:</p><pre>tools_list = sorted(tools, key=lambda t: t[&quot;name&quot;])</pre><p><strong>3. Stray whitespace.</strong></p><p>If your prompt has a trailing space in some calls and not others — maybe your editor added one — those are different bytes. The cache does not know you did not mean it. Normalise how you build your prompts.</p><p><strong>4. A model version bump.</strong></p><p>The cache is tied to the exact model. Bumping from one version to the next invalidates the whole cache. This is correct behaviour, but if you do not expect it, your spend spikes on deploy day.</p><p>The lesson under all four: the cache cares about bytes, not intent. Sort your keys, sort your lists, strip your whitespace. Boring work that pays for itself in the first week.</p><h3>The cache lives on the server</h3><p>One more useful detail. The cache is stored on the API’s side, not yours. Which means:</p><ul><li>It is shared across all your processes. One worker warms it, every worker benefits.</li><li>It is shared across users, if your system prompt is the same for everyone.</li><li>The first call after a deploy is always a miss — new bytes, no cache entry yet. Plan for a small spend bump right after deploying.</li></ul><p>Design your stable prefix once, deploy it, and let it warm up. After the first few minutes, you are paying the cheap rate.</p><h3>Part B — Streaming</h3><p>Streaming is a separate thing from caching. Caching lowers your bill (and trims some latency). Streaming makes the agent feel fast, and does not change your bill at all.</p><h3>What streaming actually is</h3><p>Without streaming, you wait for the entire reply, then show it. With streaming, the reply arrives in pieces, and you show each piece the moment it lands — the way you see ChatGPT or Claude type out an answer word by word.</p><p>Here is what is actually happening underneath. Normally, when you call the API, it generates the whole response and then sends it back to you in one piece. You wait for all of it. With streaming, you open a connection and the API pushes the response to you in small chunks as it generates them, over that one open connection. The model generates text one token at a time anyway — streaming just means each token is sent to you as it is produced instead of being held back until the end.</p><p>Nothing about the model changes. The same reply gets generated either way. The only difference is when you receive it — all at once at the end, or piece by piece as it is made.</p><p>The API sends you a sequence of small events as the reply is generated. The two that matter most:</p><ul><li><strong>A text fragment arrives</strong> — display it immediately. This is what makes the reply appear to type itself out.</li><li><strong>A tool request finishes arriving</strong> — now you can run that tool.</li></ul><h3>The one rule people get wrong</h3><p>Text and tool calls are handled differently, and mixing them up is the classic bug.</p><p><strong>Text</strong> you display the instant each fragment arrives. Character by character. That is the whole point of streaming.</p><p><strong>Tool calls</strong> you cannot act on until they finish arriving. Here is why: a tool call’s arguments arrive as fragments of JSON. Mid-stream you might have {&quot;user_id&quot;: &quot;u_0 — that is not valid JSON yet. You cannot run the tool with half its arguments. You wait until that tool&#39;s block is complete, then you run it.</p><p>So the rule is: <strong>display text as it streams, but only run a tool once its request has fully arrived.</strong></p><p>If you ignore this and wait for the entire message to finish before doing anything, you lose both benefits. The text does not stream — the user stares at nothing until the end. And if there were two tool calls, they run one after another instead of starting as soon as each one is ready.</p><h3>Why running tools early matters</h3><p>Say the model wants to call two tools — lookup_user and get_call_logs. With streaming done right, the moment lookup_user&#39;s request finishes arriving, you fire it — even while get_call_logs is still streaming in. By the time the second tool&#39;s request is complete, the first tool might already have its answer back.</p><p>Run them as they complete and they overlap. Wait for the whole message and they run one at a time. For multi-tool turns, doing it right can nearly halve the wait.</p><h3>Streaming and caching do not interact</h3><p>Just to be clear, because people conflate them:</p><ul><li><strong>Caching</strong> lowers your bill, and trims some latency too. Works with or without streaming.</li><li><strong>Streaming</strong> improves how fast it feels. Works with or without caching.</li></ul><p>They optimise overlapping things — caching helps cost the most and latency a little, streaming helps perceived latency the most and cost not at all. But mechanically they are independent. You can use either alone.</p><p>In development, use neither — it is easier to debug. In production, use both. They do not affect each other. They are just both worth doing.</p><p>One practical note on what to stream: stream the surfaces a human is actually watching — the final reply to the user. Do not bother streaming the internal specialist calls. Those return short JSON objects that no human ever sees. Stream the parts someone is reading. Leave the internal plumbing alone.</p><h3>Fast and cheap are earned, not bolted on</h3><p>I want to make one point about how this connects to everything before it.</p><p>The reason caching worked cleanly here is a decision we made back in Part 5 — we stored the user ID once in the first message instead of re-injecting it every turn. That kept the cached prefix stable. Had we re-injected the user ID every turn, the prefix would have changed every turn, and caching would have bought us nothing.</p><p>The reason streaming worked cleanly is that the agent loop was built around discrete blocks — text and tool_use — from the start. That is the API’s actual data model. Had we flattened everything into raw text, streaming would have been a rewrite.</p><p>This is the pattern. The optimisations in Part 11 were made possible by architectural decisions in Part 5 and Part 4. Fast and cheap are not features you bolt on at the end. They are earned by choices you made early, often without knowing you were making them.</p><p>In Part 12 we answer the question I have been avoiding for the whole series — how do you actually test an agent, when the model gives slightly different output every time?</p><p><em>This is Part 11 of </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-10-langchain-and-the-sdk-landscape-e70e6426caff?sharedUserId=simran-kahlon"><em>Part 10: LangChain and the SDK Landscape</em></a> <em>▶ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-12-how-do-you-test-an-agent-88161d3bf209"><em>Part 12: How Do You Test an Agent?</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=056ad358a5cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Agents, The Way Nobody Told You — Part 10: LangChain and the SDK Landscape]]></title>
            <link>https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-10-langchain-and-the-sdk-landscape-e70e6426caff?source=rss-83917a9b1446------2</link>
            <guid isPermaLink="false">https://medium.com/p/e70e6426caff</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Simran Kaur Kahlon]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 03:48:19 GMT</pubDate>
            <atom:updated>2026-10-02T08:46:27.189Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 10 of the series </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-9-mcp-44610046caca?sharedUserId=simran-kahlon"><em>Part 9: MCP</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3PidcEjJ_7XdAD5dU7k3g.png" /></figure><p>We have built an entire agent from scratch — the loop, memory, tools, sub-agents, hooks. All with the raw Anthropic SDK. No framework.</p><p>Now is the right time to talk about frameworks. And here is the good news: because you built everything by hand, frameworks will never confuse you again.</p><h3>The names you keep hearing</h3><p>LangChain. LangGraph. LlamaIndex. CrewAI. AutoGen. The OpenAI Agents SDK.</p><p>Each has its own vocabulary and its own way of doing what looks like the same thing. For a beginner this is overwhelming.</p><p>Here is the one idea that cuts through all of it:</p><p><strong>Every one of these frameworks is wrapping the same loop you built in Part 4.</strong></p><p>That is it. That is the whole secret. None of them are magic. They are all running send-messages, check-stop-reason, run-tools, send-results-back — the exact loop you already understand.</p><p>Think of it like cooking. You have learned to cook a dish from raw ingredients — you know every step, you can taste as you go, and if something is off you know exactly what to fix. A framework is like a meal kit. The chopping is done, the sauce is pre-made, and you assemble it in five minutes. Faster, yes. But if the sauce tastes wrong, you cannot fix it — you did not make it and you do not know what is in it.</p><p>That is the trade every framework makes. Speed in exchange for control.</p><h3>Seeing it with your own eyes</h3><p>Let me show you the same thing built both ways.</p><p>Here is roughly what our agent looks like in the raw SDK — the version you now understand completely:</p><pre>messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_message}]</pre><pre>while True:<br>    # call the API — this runs again every time the model asks for a tool<br>    response = client.messages.create(<br>        model=&quot;claude-sonnet-4-6&quot;,<br>        tools=tools,<br>        messages=messages,<br>    )</pre><pre>    # if the model is done, stop<br>    if response.stop_reason == &quot;end_turn&quot;:<br>        break</pre><pre>    # otherwise it asked for a tool: run it, append the result, loop again<br>    messages.append(response_as_message)<br>    messages.append(tool_result_message)</pre><p>This is the exact loop from Part 4. The API call sits inside the while because it runs over and over — once for the first response, again after each tool result — until the model finally says it is done.</p><p>And here is roughly the same agent in LangChain:</p><pre>from langchain.agents import create_agent</pre><pre>agent = create_agent(model=&quot;claude-sonnet-4-6&quot;, tools=tools)<br>result = agent.invoke({&quot;messages&quot;: [user_message]})</pre><p>Five lines instead of thirty. That looks like a clear win.</p><p>But look at what happened. The loop disappeared. The stop_reason check disappeared. The message handling disappeared. It all still happens — it is just hidden inside create_agent now.</p><p>When it works, you saved time. When it breaks, you are debugging code you cannot see.</p><p>That trade-off is the entire story of frameworks. Everything else is detail.</p><h3>What you actually do vs what the framework does</h3><p>Here is the part that surprises people. With a framework, you never touch stop_reason. You never check for tool_use. You never append a tool_result. You never write the loop.</p><p>All you do is three things:</p><ol><li>Write your tool functions — same as the raw SDK.</li><li>Register them with the agent — create_agent(tools=[...]).</li><li>Call agent.invoke(...) once.</li></ol><p>That is it. You register the tools and call invoke a single time.</p><p>Underneath, the framework runs the entire loop you built in Part 4 — it sends the messages, checks the stop reason, sees the model wants a tool, calls your function, appends the result, loops again, and keeps going until the model returns end_turn. Then it hands you the final answer.</p><p>So the framework does not just hide the loop. It hides the whole mechanism of how tool calling works. A beginner who starts here would not even know that end_turn exists, or that tool calls happen in a loop. They would just think &quot;I registered a tool and it magically got used.&quot;</p><p>That is fine — until a tool call misbehaves. Then you are staring at a magic box, because you never learned the mechanism underneath. You, on the other hand, built that mechanism by hand. You know exactly what is happening in there.</p><h3>LangChain, LangGraph — what is the difference?</h3><p>You will hear both names constantly, so here is the plain version.</p><p><strong>LangChain</strong> is the framework. It gives you the tool definitions, the model connections, and the create_agent call — the loop-hiding convenience we just talked about.</p><p><strong>LangGraph</strong> is a more advanced runtime that sits underneath. You reach for it when you need serious control — pausing the agent to wait for a human to approve something, complex branching between multiple agents, or state that survives a server crash and resumes where it left off.</p><p>The simple way to hold it in your head: LangChain is the quick, high-level way in. LangGraph is what you drop down to when the quick way is not enough. In late 2025 LangChain was rebuilt to run on top of LangGraph, so they are now two layers of the same system — a simple layer and a powerful layer — not two competing tools.</p><p>For most people starting out, you do not need either. The raw SDK you already understand will take you a long way.</p><h3>When a framework helps</h3><p>Frameworks are not a trap. There are real situations where they are the right call.</p><p><strong>You need prebuilt integrations.</strong> Say you want your agent to pull data from a Pinecone vector database and load PDFs from Google Drive. In the raw SDK you would write both connectors yourself. LangChain already has them — you import and use them. That is genuinely hours saved.</p><p><strong>You are prototyping fast.</strong> Your manager asks for a demo by tomorrow. You do not care about the internals yet — you just need something that works. The five-line version gets you there tonight.</p><p><strong>You need complex orchestration you do not want to build.</strong> Imagine an agent that pauses, waits for a human to click “approve” before it sends money, then resumes exactly where it left off — even if the server crashed in between. Some frameworks give you this out of the box. Building it yourself is a serious project.</p><h3>When a framework hurts</h3><p><strong>Debugging gets harder.</strong> Say your agent occasionally returns an empty reply and you do not know why. In your own code, you add a print statement, watch the loop, and find the bug in minutes. In a framework, the bug is somewhere inside create_agent — code you did not write. You end up reading the framework&#39;s source on GitHub to figure out what your own agent is doing.</p><p><strong>The abstraction leaks.</strong> Frameworks are built for the common case. Say you want tool results returned in a slightly custom format, or a retry rule specific to your setup. The framework did not plan for it. Now you are writing awkward workarounds to force the framework to do something your own thirty lines would have done directly.</p><p><strong>You learn the framework, not the concept.</strong> If you start with a framework, you learn “how to use LangChain” — not how agents work. Then LangChain changes its API (it has, many times) and your knowledge is suddenly outdated. The loop from Part 4 has not changed since agents existed and will not change.</p><h3>The rule I actually use</h3><p><strong>Start with the raw SDK.</strong> Build the loop yourself. You will understand exactly what your agent does and you can debug every line. For most agents this is all you need.</p><p><strong>Reach for a framework when you hit a specific thing it does better than you can</strong> — a prebuilt integration, durable state across crashes, human-in-the-loop approval. Then use it deliberately, for that reason.</p><p><strong>Do not start with a framework to skip understanding the loop.</strong> That is the trap. It becomes a black box you cannot debug, built on concepts you never learned.</p><p>Understand the loop first. Then a framework is a tool you choose, not a crutch you lean on.</p><h3>Why this series built everything from scratch</h3><p>This is exactly why we did not touch a framework until now.</p><p>If I had opened with “install LangChain, call create_agent,” you would have a working agent and no understanding. You would not know what a tool_use block is, why parallel tool results go in one message, or why authorisation belongs in a hook.</p><p>Now you know all of it. So you can pick up any framework, read its docs, and instantly map its ideas onto what you already understand. Its agent is the loop. Its memory is the messages list. Its tools are tool_use blocks. Its middleware is hooks.</p><p>That is the position you want to be in. Not “I know LangChain.” But “I understand agents — and LangChain is just one way to express that.”</p><p>Frameworks keep changing. New ones launch every quarter. The loop stays the same. Build on the thing that does not change.</p><p>In Part 11 we make the agent fast and cheap — prompt caching and streaming.</p><p><em>This is Part 10 of </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-9-mcp-44610046caca?sharedUserId=simran-kahlon"><em>Part 9: MCP</em></a> <em>▶ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-11-making-it-fast-and-cheap-056ad358a5cd?sharedUserId=simran-kahlon"><em>Part 11: Making It Fast and Cheap</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e70e6426caff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Agents, The Way Nobody Told You — Part 9: MCP]]></title>
            <link>https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-9-mcp-44610046caca?source=rss-83917a9b1446------2</link>
            <guid isPermaLink="false">https://medium.com/p/44610046caca</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Simran Kaur Kahlon]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 16:46:01 GMT</pubDate>
            <atom:updated>2026-10-26T16:49:59.378Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 9 of the series </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-8-hooks-f18c4204ed69?sharedUserId=simran-kahlon"><em>Part 8: Hooks</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3PidcEjJ_7XdAD5dU7k3g.png" /></figure><p>Here is a question worth sitting with for a moment.</p><p>You have built an agent for customer support. Tomorrow your company wants the same set of tools — lookup_user, search_kb, get_purchases — to power a different agent. A sales bot. An internal data lookup tool for the customer success team.</p><p>Do you copy-paste the tool code into the new project? Build a shared Python package and import it? Set up a microservice that exposes them as a REST API?</p><p>All of those work. None of them are standard. Every team invents their own answer. Every time the model provider changes — Claude to GPT to Gemini — the tool-calling format changes, so every wrapper has to change too. There is no protocol.</p><p>That is the gap MCP fills.</p><h3>What MCP actually is</h3><p>MCP — Model Context Protocol — is an open standard for exposing tools, resources, and prompts to LLM clients. It was created by Anthropic in 2024 and has since been open-sourced and donated to the Linux Foundation, making it an industry-wide standard. Claude clients, OpenAI clients, custom clients — they all speak the same protocol to the same servers.</p><p>Three pieces:</p><ul><li>The <strong>client</strong> is the agent. It needs to find available tools and call them.</li><li>The <strong>server</strong> is the tool process. It exposes tools, accepts calls, returns results.</li><li>The <strong>protocol</strong> is JSON-RPC. The client and server send each other structured JSON messages.</li></ul><p>The server runs as a separate process. It could be a subprocess of the agent communicating over stdio. It could be a remote HTTP service. The client does not care which. It just sends JSON-RPC frames.</p><p>That subtle abstraction — the agent does not care where the tools live — is the whole point.</p><h3>What changed structurally</h3><p>Before MCP, all tools lived inside the agent process — regular Python functions called directly. With MCP, tools move to a separate server process. The agent talks to them over JSON-RPC.</p><p>Before MCP After MCP Where tools live In-process Python Separate process How agent calls them Direct Python function call JSON-RPC over stdio Release cadence Same as agent Independent Crash blast radius Tool crash can kill agent Tool process crashes independently Same LLM provider required? Yes — tools are provider-specific No — MCP is provider-agnostic Agent behaviour identical identical</p><p>The last row is the most important. From the user’s perspective, nothing changed. The agent says the same things, calls the same tools, produces the same outputs. The wiring underneath changed. The behaviour did not.</p><h3>The wire protocol — what is actually on the wire</h3><p>Once you see what is actually happening, the abstraction stops being mysterious.</p><p><strong>Handshake at startup:</strong></p><pre>client → initialize  {protocolVersion, capabilities, clientInfo}<br>server → result      {protocolVersion, capabilities, serverInfo}<br>client → notifications/initialized<br>client → tools/list<br>server → result      {tools: [...all tool definitions...]}</pre><p>The client asks what tools exist. The server tells it. That is dynamic discovery — the client does not need a hard-coded list of tools. Add a new tool to the server, restart the client, it picks it up automatically.</p><p><strong>Per tool call:</strong></p><pre>client → tools/call  {name: &quot;lookup_user&quot;, arguments: {user_id: &quot;u_004&quot;}}<br>server → result      {content: [{type: &quot;text&quot;, text: &quot;{...}&quot;}]}</pre><p>The agent emits a tool_use block. The MCP client wraps it into a tools/call JSON-RPC frame. The server receives the frame, runs the tool, returns the result. The MCP client unwraps the result into a tool_result block. The agent loop continues.</p><p><strong>Shutdown:</strong></p><pre>client closes stdin → server&#39;s read loop gets EOF → process exits</pre><h3>stdout is the protocol, stderr is for logs</h3><p>This is the rule that will burn you if you do not know it.</p><p>When your MCP server runs as a subprocess and communicates over stdio, stdout is reserved for JSON-RPC frames. Nothing else. No log messages, no debug prints, no informational output. Stdout is the protocol channel.</p><p>Anything you want to log goes to stderr.</p><pre># WRONG — corrupts the protocol stream<br>def my_tool(...):<br>    print(&quot;debug: looking up user&quot;)   # goes to stdout → breaks JSON-RPC</pre><pre># RIGHT<br>import logging<br>logging.basicConfig(stream=sys.stderr)<br>def my_tool(...):<br>    logging.debug(&quot;looking up user&quot;)  # goes to stderr → safe</pre><p>A single stray print() to stdout from a tool handler corrupts the entire protocol stream. The client&#39;s parser breaks. The whole connection collapses. Then you spend hours wondering why the agent stopped working after you added &quot;harmless logging.&quot;</p><p>Never print to stdout from MCP tool handlers. Use logging.basicConfig(stream=sys.stderr) at the top of the server file. This is the same convention LSP and gRPC-over-stdio use. It is not an MCP quirk — it is a stdio-protocol convention. Internalise it once and apply it everywhere.</p><h3>Three primitives MCP exposes</h3><p>MCP servers can expose three different kinds of things:</p><p>Primitive What it is Example <strong>Tools</strong> Actions the agent invokes with parameters lookup_user(u_004) <strong>Resources</strong> Fetchable documents at stable URIs kb://refund_policy.md <strong>Prompts</strong> Reusable prompt templates the server offers &quot;Summarise this ticket&quot; template</p><p>In this project I only use tools. But the distinction is worth knowing.</p><p>The rule of thumb: if the agent has to think about what to type as the argument, it is a tool. If it just says which thing by name, it could be a resource.</p><p>lookup_user(u_004) — the agent constructed the argument. That is a tool.</p><p>A hypothetical kb://refund_policy.md — the agent just says &quot;give me this document.&quot; That is a resource. Named, not constructed.</p><p>In practice you can model almost everything as a tool. Resources are for cases where you want clients to fetch documents by name without reasoning about parameters — like a static doc tree.</p><h3>What MCP actually buys you</h3><p>Moving tools out of the agent process might seem like unnecessary complexity. The agent worked fine with in-process tools. So what is the upside?</p><p>Six things.</p><p><strong>LLM-agnostic.</strong> Today the agent uses Claude. Tomorrow someone wants to evaluate GPT or Gemini. With in-process tools, swapping the LLM means rewriting every tool wrapper for the new provider’s format. With MCP, the server does not change at all. Only the client wrapper changes. This is a large reduction in the cost of changing models.</p><p><strong>Project-agnostic.</strong> The same MCP server can power five different agents. Customer support agent, sales bot, internal data lookup, premium pitch tool. Each agent connects to the same server and gets the same tools with the same definitions. You write the server once.</p><p><strong>Dynamic discovery.</strong> Clients call tools/list at startup. Add a new tool to the server? Restart any client and it picks it up automatically. No client-side update needed. No hard-coded tool lists drifting out of sync.</p><p><strong>Universal tooling.</strong> The MCP Inspector debugs any MCP server. The MCP SDKs in Python and TypeScript handle retries, timeouts, and edge cases. The ecosystem grows and everyone benefits.</p><p><strong>Distributable.</strong> Ship your MCP server as a package. Anyone can plug it into their agent in minutes. There are already prebuilt MCP servers for Postgres, Slack, GitHub, Stripe, Linear — meaning when you want your agent to interact with one of those services, you install the server rather than building the integration.</p><p><strong>Composable.</strong> An agent can talk to multiple MCP servers at once. Your support agent could connect to your custom server with lookup_user and search_kb, plus the Postgres MCP server for ad-hoc queries, plus the GitHub MCP server for issue creation — all at the same time. The agent does not care that tools come from different servers. They are all just tool_use blocks.</p><h3>Protocols outlive frameworks</h3><p>There is a deeper point here that is worth making directly.</p><p>Frameworks come and go. A few years ago LangChain was the answer. Then CrewAI. Then AutoGen. New agent frameworks launch every quarter. Each one has its own tool definition format. Each one has its own abstraction over the LLM provider. Each one is a potential lock-in.</p><p>Protocols outlive frameworks. MCP is a protocol — not a framework. It is a wire format. Anything implementing the wire format works with everything else implementing the wire format. The way HTTP outlived every HTTP framework. The way SQL outlived every ORM.</p><p>When you build on MCP, you are betting on a wire format that any framework, any provider, any IDE will end up speaking. You are not betting on any specific company’s success or market share. You are betting on a contract.</p><p>That is a much safer bet.</p><h3>Stable contracts, evolving implementations</h3><p>This principle has come up throughout the series. MCP is the clearest example of it.</p><p>What stays stable when you migrate tools to an MCP server:</p><ul><li>The tool <strong>names</strong> — lookup_user, get_purchases, search_kb</li><li>The tool <strong>schemas</strong> — input parameters, return types</li><li>The tool <strong>descriptions</strong> — when to call, what to expect</li></ul><p>What becomes swappable:</p><ul><li>The tool <strong>implementations</strong></li><li>The tool <strong>transport</strong> — in-process function vs JSON-RPC over stdio</li><li>The tool <strong>language</strong> — the server could be Python, Go, Rust. The agent does not care</li><li>The tool <strong>owner</strong> — your team owns the agent, a different team owns the server, they ship independently</li></ul><p>The model only knows the tool’s name and schema. The implementation, transport, and ownership can all change underneath and the model never notices. Stable contract, swappable backend.</p><h3>Subprocess lifecycle — a few production notes</h3><p>When your MCP server runs as a subprocess, manage its lifecycle carefully. Three things to know:</p><p>The subprocess only sees the parent die when its stdin gets EOF. If you kill the agent process hard, the MCP server might keep running orphaned.</p><p>Parent crashes do not kill the subprocess automatically. You need explicit cleanup.</p><p>In production, wrap the agent in a process supervisor — systemd, supervisord. They handle orphans.</p><p>My defence in depth: try/finally around the orchestrator loop so .close() always fires, atexit.register(client.stop) for uncaught exceptions, and the server&#39;s own FastMCP.run() exits cleanly on stdin-EOF. Subprocess lifecycle bugs are silent and expensive.</p><p>In Part 10 we look at LangChain and the SDK landscape — what these frameworks are actually doing, when they help, and when they get in the way.</p><p><em>This is Part 9 of </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-8-hooks-f18c4204ed69?sharedUserId=simran-kahlon"><em>Part 8: Hooks</em></a> <em>▶ </em><a href="https://medium.com/@simran-kahlon/llm-agents-the-way-nobody-told-you-part-10-langchain-and-the-sdk-landscape-e70e6426caff?sharedUserId=simran-kahlon"><em>Part 10: LangChain and the SDK Landscape</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44610046caca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Agents, The Way Nobody Told You — Part 8: Hooks]]></title>
            <link>https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-8-hooks-f18c4204ed69?source=rss-83917a9b1446------2</link>
            <guid isPermaLink="false">https://medium.com/p/f18c4204ed69</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Simran Kaur Kahlon]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 07:57:05 GMT</pubDate>
            <atom:updated>2026-10-02T08:47:17.095Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 8 of the series </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-7-letting-the-agent-act-c769b6f20425?sharedUserId=simran-kahlon"><em>Part 7: Letting the Agent Act</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3PidcEjJ_7XdAD5dU7k3g.png" /></figure><p>Let me describe a bug I shipped in an early version of this project.</p><p>The refund specialist’s system prompt said: <em>“only premium users can request refunds. Free users should be politely informed that refunds are not part of their plan.”</em> I tested it. It worked. Free users got told no, premium users got the case file treatment.</p><p>Then I introduced a slightly unusual test case. A free-tier user with a creatively worded complaint that sounded like a refund request but was actually about a different kind of credit. The model — confused by the framing, helpful by nature — decided to file a case file anyway. The system prompt said “only premium users.” The model thought this was close enough, let me help.</p><p>The case file got created. A free user who should not have been allowed to create case files just did.</p><p>This is the bug class that defines Part 8. You cannot trust the LLM to follow rules. Not because the LLM is bad — it is actually quite good — but because LLMs are probabilistic. A prompt rule that holds for 99% of inputs will fail for the 1% of inputs that look just unusual enough.</p><p>If the rule matters — if breaking it has real cost — the rule cannot live in the prompt. It has to live in code. Deterministic, runs-every-time code that the LLM has no say in.</p><p>That is what hooks are.</p><h3>The three hook types</h3><p>There are three kinds of hooks. Each fires at a different point in the tool-call lifecycle:</p><ul><li><strong>PreToolUse</strong> — fires before the tool runs. Can deny, modify the input, or observe.</li><li><strong>PostToolUse</strong> — fires after the tool runs. Can observe only — log, audit, notify. Cannot undo.</li><li><strong>Stop</strong> — fires when the session ends. Cleanup, summary, persistence.</li></ul><p>The short version:</p><ul><li>Pre = <em>“should this happen?”</em></li><li>Post = <em>“this happened.”</em></li><li>Stop = <em>“we are done.”</em></li></ul><p>PreToolUse is where authorisation decisions live. PostToolUse is where audit logging lives. Stop is where session cleanup lives. These are not interchangeable.</p><p>Putting authorisation in PostToolUse is wrong — the action already happened, it is too late. Putting audit logs in PreToolUse is wrong — the action might not happen, you would be logging intent rather than facts.</p><p>Each hook type has a purpose. Match the purpose to the hook.</p><h3>Capability vs authorisation vs policy</h3><p>This is the distinction that took me the longest to internalise. Once you see it you will spot it in every system you build.</p><p>Imagine you are adding a new check to the case file system. Where does it go?</p><ul><li><strong>Check A:</strong> “the evidence list must contain at least one item.”</li><li><strong>Check B:</strong> “free-tier users cannot create case files.”</li><li><strong>Check C:</strong> “no case files can be created between 2am and 4am during the weekly deploy window.”</li></ul><p>All three are checks. All three reject some tool calls. But they belong in three completely different places:</p><p>Check type Where it lives Example Capability — are the inputs internally consistent? Tool implementation “evidence list must be non-empty” Authorisation — are you allowed to do this right now? PreToolUse hook “free users cannot create case files” Policy — org-level rules PreToolUse hook “no writes during deploy window” Observation — record what happened PostToolUse hook “log every write to audit log”</p><p>The shortcut I use constantly:</p><ul><li>The <strong>tool</strong> asks: <em>“can I do this with these inputs?”</em> — input shape check.</li><li>The <strong>hook</strong> asks: <em>“are you allowed to do this right now?”</em> — runtime authorisation.</li></ul><p>Why does this split matter? Because they need different inputs.</p><p>The tool only sees the LLM-generated arguments. It can validate those arguments against each other — is the evidence list non-empty, is the amount positive — but it cannot validate against anything outside its arguments.</p><p>The hook sees the trusted server-side context in addition to the arguments. The session’s real user ID, the user’s actual tier, the current time, the session ID. These come from a HookContext object that was built when the session started, frozen, and is implicitly trusted.</p><p>So the hook can ask: <em>“the LLM is trying to call lookup_user with user_id=’u_999&#39;. The session’s real user ID is ‘u_004’. Mismatch. Deny.”</em> The tool cannot do this — it never saw the session’s real user ID.</p><p>Authorisation decisions compare untrusted LLM input against trusted server context. Tools only have the untrusted input. Hooks have both. That is why authorisation lives in hooks.</p><h3>Trusted context vs untrusted input</h3><p>Lock this distinction in. It matters for the rest of the series.</p><p>HookContext is server-side state. It was built when the session started, by your code, from sources you trust — your auth system, your session manager, your database. It is frozen for the duration of the session. The user cannot influence it. The LLM cannot influence it. It is the truth.</p><pre>@dataclass(frozen=True)<br>class HookContext:<br>    user_id: str         # set from your auth layer<br>    tier: Literal[&quot;free&quot;, &quot;premium&quot;]<br>    session_id: str</pre><p>tool_input is the dictionary the LLM generated. It is whatever the model decided to put in the tool_use block. It is untrusted. Treat it like an HTTP request body. The user could have nudged the model to produce anything in there.</p><p>When you write an authorisation check, you compare these two. Does the LLM-provided user_id match the trusted HookContext.user_id? Does the trusted HookContext.tier == &quot;free&quot; block this write tool?</p><p>The rule that keeps you safe: <strong>never let LLM-provided input make the security decision.</strong> The decision must rest on HookContext.</p><h3>What a denial actually looks like</h3><p>When PreToolUse denies a tool call, the instinct is to just skip the tool call and move on. You cannot do that.</p><p>We covered this in Part 4 — every tool_use block the assistant emitted must be answered by a tool_result block with the matching tool_use_id in the very next user message. If you skip the tool result, the next API call fails with a 400 error.</p><p>So the hook cannot block silently. It has to return a synthetic tool result:</p><pre>{<br>  &quot;type&quot;: &quot;tool_result&quot;,<br>  &quot;tool_use_id&quot;: &quot;toolu_01ABC&quot;,<br>  &quot;is_error&quot;: True,<br>  &quot;content&quot;: &quot;BLOCKED: free-tier users cannot call prepare_case_file. Suggest upgrade or route to general FAQ.&quot;<br>}</pre><p>The synthetic result satisfies the API contract. The model reads it as an observation — “that was denied for tier reasons, let me apologise and offer a different path.” The conversation continues gracefully.</p><p>Two things worth locking in here.</p><p><strong>The “BLOCKED:” prefix matters.</strong> It is not required by the API. It is a convention — the model recognises this prefix as a deliberate denial rather than a tool error, and recovers correctly instead of retrying. The same prefix gets read later by the eval harness to distinguish denials from genuine errors. Convention as machine-readable signal.</p><p><strong>The content is itself a prompt.</strong> Write it like one. “Denied” is a bad denial message. “BLOCKED: free-tier users cannot call X. Suggest upgrade or route to Y.” is a good one. The model reads this and uses it to compose the next reply. Give it material to work with.</p><h3>The wrapping trick — how hooks actually attach</h3><p>The cleanest way to attach hooks is to wrap the function that dispatches tool calls. You have an existing call_tool function in your dispatcher — the one that reads a tool_use block and calls the right Python function. You want hooks to fire before and after every call, without rewriting the dispatcher.</p><pre>original_call_tool = dispatcher.call_tool   # save the reference FIRST</pre><pre>def hooked_call_tool(name, args):<br>    event = build_event(name, args)<br>    if denial := registry.run_pre(event):<br>        return synthetic_error_result(denial)   # PreToolUse denied<br>    result = original_call_tool(name, args)     # call the saved original<br>    registry.run_post(event, result)<br>    return result</pre><pre>dispatcher.call_tool = hooked_call_tool   # NOW replace it</pre><p>Five steps:</p><ol><li>Build the tool_use into a hook event.</li><li>Run all PreToolUse hooks.</li><li>If any hook denied, return a synthetic error result. The actual tool never runs.</li><li>Otherwise, call the original tool and capture the result.</li><li>Run all PostToolUse hooks — audit, notify, log.</li></ol><p>The important pattern here is <strong>save before replace</strong>. You see this in decorators, middleware, interceptors — any “wrap a function” pattern.</p><p>If you did not save the original first — if you just wrote dispatcher.call_tool = lambda *a, **kw: dispatcher.call_tool(*a, **kw) — here is what happens. When the wrapper runs and tries to call dispatcher.call_tool, it looks up dispatcher.call_tool at that moment. But dispatcher.call_tool is now pointing to the wrapper itself. So the wrapper calls itself, which calls itself, which calls itself. Infinite recursion. Stack overflow on the first tool call.</p><p>Saving the original to a local variable before replacing it means the closure captures the old reference — the actual original function — not the name. The wrapper always calls the real original, not itself.</p><h3>Why hooks beat “just put it in the prompt”</h3><p>Approach Failure mode Prompt advisory — “do not do X” Model may ignore on a bad day Tool filtering — do not include the tool in the list at all Static — cannot depend on runtime state Hooks Deterministic and runtime-aware</p><p>Tool filtering is actually good for some cases. If the free-tier specialist never needs create_jira_ticket, just do not include that tool in its tool list. The model literally cannot emit a tool_use for a tool it does not know exists. Capability the model does not have is stronger than an instruction it might ignore.</p><p>Where tool filtering breaks down is rules that depend on runtime state. “User is free-tier” depends on which user is in the session — same agent code, different sessions, different allowed tools. Tool filtering is static. Hooks are runtime-aware.</p><p>The layered defence is:</p><ol><li><strong>Tool filtering</strong> at the specialist level — for “this specialist never needs this tool.”</li><li><strong>Prompt advisory</strong> for general nudges and soft guidance.</li><li><strong>Hooks</strong> for runtime rules that must hold.</li></ol><p>All three together. Agents need all of it.</p><h3>The uniform tool surface payoff</h3><p>In Part 6 I said wrap everything — sub-agent calls, external API calls, database queries — as tool_use blocks so they all flow through the same mechanism. This is where that pays off.</p><p>One hook layer covers everything. The same hooked_call_tool wrapper sees reads, writes, sub-agent delegation, knowledge base searches, and any tool we add in the future.</p><p>Authorisation, policy, audit — all enforced uniformly across the agent’s entire action surface. Because everything is a tool_use, hooks see everything.</p><p>If we had implemented sub-agent delegation as a direct Python call — the option we rejected in Part 6 — the hook layer would be blind to it. We would need a parallel authorisation layer just for routing. Two systems, two sets of bugs. Instead: one tool surface, one hook layer, one set of rules.</p><p>Plan for uniform tool surface from the start and hooks is a small addition. Do not plan for it and hooks becomes a large refactor.</p><h3>PreToolUse chain semantics</h3><p>When you have multiple PreToolUse hooks — a tier check, a deploy window check, a user ID match check, an amount limit check — they run in order. The semantics:</p><ul><li><strong>First deny wins.</strong> Short-circuits. Remaining hooks do not run. The tool does not run.</li><li><strong>Allow does not short-circuit.</strong> All hooks must pass for the call to go through.</li><li><strong>Modify composes.</strong> Hook B sees hook A’s modified input.</li></ul><p>Order hooks by criticality. Cheap, fast denials first. “Is the user free-tier?” is a one-field lookup — run it before “is this amount under the weekly org limit?” which might require a database query. Same idea as ordering WHERE clauses by selectivity in SQL.</p><h3>Failure modes by hook type</h3><p>Hook type If the hook crashes Why PreToolUse Should propagate A crashed policy hook is a bug. You do not want to silently pretend a gate fired. Halt the agent until the policy is fixed. PostToolUse Must be swallowed Audit logging failure should not break the agent. The user’s request matters more than your logs in the moment. Log the failure to a separate stream and move on. Stop Must be swallowed The session is already ending. Best you can do is log the cleanup failure and exit.</p><p>These are not preferences. They are correctness requirements. A PreToolUse hook that silently swallows its own errors is a security hole — the gate did not fire, the call went through, the audit log does not show why. A PostToolUse hook that propagates is a denial-of-service waiting to happen.</p><h3>Where audit logs live</h3><p>Hooks write two files in my project.</p><p>data/audit_log.jsonl — every tool call via PostToolUse. Every entry has the tool name, the input, the result, whether it errored, and a timestamp. This is the file the eval harness in Part 12 reads.</p><p>data/session_summaries.jsonl — once per session via the Stop hook. One row per conversation with high-level stats.</p><p>The audit log is the most important file in the project. When you build observability in from the start, this file becomes useful for compliance, evals, cost analytics, debugging, and dashboards — all from one source of truth.</p><p>In Part 9 we cover MCP — how to pull your tools out of the agent process and into a separate server so they become portable across models, teams, and projects.</p><p><em>This is Part 8 of </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-7-letting-the-agent-act-c769b6f20425?sharedUserId=simran-kahlon"><em>Part 7: Letting the Agent Act</em></a> <em>▶ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-9-mcp-44610046caca"><em>Part 9: MCP</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f18c4204ed69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Agents, The Way Nobody Told You — Part 7: Letting the Agent Act]]></title>
            <link>https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-7-letting-the-agent-act-c769b6f20425?source=rss-83917a9b1446------2</link>
            <guid isPermaLink="false">https://medium.com/p/c769b6f20425</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Simran Kaur Kahlon]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 09:18:21 GMT</pubDate>
            <atom:updated>2026-10-02T08:47:47.031Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 7 of the series </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://medium.com/@simran-kahlon/llm-agents-the-way-nobody-told-you-part-6-when-one-agent-is-not-enough-952c415bc88f?sharedUserId=simran-kahlon"><em>Part 6: When One Agent is Not Enough</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3PidcEjJ_7XdAD5dU7k3g.png" /></figure><p>By the end of Part 6, the bot was doing a lot. It routed between specialists. It looked up real data. It remembered previous turns. It generated grounded, correct replies.</p><p>But it could not actually do anything.</p><p>A user reports a real Android crash, the technical specialist confirms the bug — and then the conversation ends with “I’ll flag this with engineering.” No Jira ticket gets created. Nothing makes it into anyone’s backlog.</p><p>A premium user asks for a refund, the refund specialist confirms eligibility — and we say a human will follow up. No record, no queue. The moment the agent’s reply scrolls off the screen, the request might as well never have existed.</p><p>This is the third leg of the agent. Memory, reads, writes. Part 3 added reads. Part 5 added memory. This article adds writes. That is the full agent.</p><p>And the moment you let an agent write, an entire new class of problems shows up.</p><h3>Reads are reversible. Writes are not.</h3><p>This is the asymmetry that makes write tools harder than read tools.</p><p>A wrong lookup_user call returns &quot;not found&quot; and the model recovers on the next turn. Wrong reads are cheap. The blast radius is one turn.</p><p>A wrong Jira ticket pollutes the engineering backlog. A wrong case file creates a phantom refund queue entry. A wrong cancellation actually cancels something. Writes have persistence and side effects. The agent might be wrong, but the world has already moved.</p><p>So when you design a write tool, the bar goes up. You need four things:</p><p><strong>Stricter tool descriptions.</strong> The model should be slightly afraid to call a write tool. The description should specify exactly when it is appropriate, what counts as sufficient evidence, and what the consequences are. A vague description gets you speculative write attempts — the agent not knowing what to do, filing a ticket just in case. Make the model think twice before writing anything.</p><p><strong>Authorisation in front of the call.</strong> Not every user is allowed to write. Free-tier users can file support tickets but not case files. Premium users have different rules. This is not the tool’s job to enforce — that is the hook layer’s job. We cover this in Part 8.</p><p><strong>Audit logging behind the call.</strong> Every write must leave a record. Not just “we wrote something” — who wrote it, why, with what evidence, what arguments the model produced.</p><p><strong>A structured artifact format.</strong> Which brings us to the case file pattern.</p><h3>The case file pattern</h3><p>For most write operations in a customer support agent, the agent is not doing the thing. It is preparing the thing for a human to do.</p><p>The agent does not refund the money. It writes a case file describing the user’s situation, the evidence gathered, and a suggested action. A human reads the case file, checks the work, and clicks approve.</p><p>This is the right shape for almost every write that touches money, accounts, or compliance. The agent is the investigator. The human is the decider.</p><p>Here is what a case file looks like:</p><pre>@dataclass(frozen=True)<br>class CaseFile:<br>    case_id: str                # server-assigned (CF-1, CF-2, ...)<br>    case_type: Literal[&quot;refund&quot;, &quot;counsellor&quot;, &quot;cancellation&quot;]<br>    created_at: datetime        # immutable timestamp<br>    user_id: str                # immutable<br>    summary: str                # one paragraph<br>    evidence: list[str]         # concrete facts found via tools<br>    recommendation: str         # machine suggestion — NOT a decision</pre><p>Three things make this format work.</p><p><strong>It is structured.</strong> A human reviewing 30 cases a day does not read 30 paragraphs of prose. They scan the evidence list, look at the recommendation, and decide. The structure is a UX choice for the human.</p><p><strong>It forces evidence.</strong> The evidence field is a list of concrete facts — &quot;Purchase date: 2026-04-12&quot;, &quot;Counselling sessions completed: 2 of 8&quot;, &quot;Refund window: 14 days.&quot; Not impressions. Specific facts the agent extracted from tool calls. If the model tries to submit an empty evidence list, the tool rejects the call.</p><p><strong>It separates recommendation from decision.</strong> The agent recommends. The human decides. This matters because it keeps the human in the loop for irreversible actions while still letting the agent do 80% of the work. The agent is not replacing the human — it is preparing the homework so the human’s job is faster.</p><h3>ID generation belongs in the store, not the caller</h3><p>This is a bug that will catch you if you are not thinking about concurrency.</p><p>A naive implementation lets the specialist pick the next case ID:</p><pre># DO NOT DO THIS<br>def prepare_case_file(case_type, summary, evidence, recommendation):<br>    existing = list_case_files()<br>    next_id = f&quot;CF-{len(existing) + 1}&quot;   # caller picks the ID<br>    write_to_disk(next_id, ...)</pre><p>This looks fine in single-threaded code. Now remember from Part 6 — the orchestrator can fan out to multiple specialists in one turn. Both run in parallel:</p><pre>T=0  Specialist A: reads case_files.jsonl, sees max ID = CF-7<br>T=0  Specialist B: reads case_files.jsonl, sees max ID = CF-7<br>T=1  Specialist A: picks CF-8, writes file with id=CF-8<br>T=1  Specialist B: picks CF-8, writes file with id=CF-8  ← collision</pre><p>Two case files claiming to be CF-8. The audit log cannot disambiguate them. The append-only history you thought you had is silently corrupted.</p><p>The fix is to centralise ID assignment in the store:</p><pre>class CaseFileStore:<br>    def create(self, case_type, summary, evidence, recommendation) -&gt; str:<br>        next_id = self._compute_next_id()  # atomic<br>        self._write(next_id, ...)<br>        return next_id</pre><p>Same principle as AUTOINCREMENT in a database. The store assigns the ID. The caller gets it back. The race goes away.</p><p>The rule: <strong>ID generation belongs in the store, not the caller.</strong> Caller-picked IDs race under concurrency. Always.</p><h3>Three layers of audit-grade records</h3><p>Once you start writing things that humans will rely on, the records have to be trustable. There are three layers to that.</p><p><strong>Layer 1 — in-memory immutability.</strong> Use @dataclass(frozen=True) for case files and tickets. Once the object is constructed, no one can do ticket.severity = &quot;low&quot; to fudge the data after the fact. Python enforces this at runtime — you get a FrozenInstanceError. Facts do not change. The dataclass tells the language that.</p><p><strong>Layer 2 — explicit timestamps.</strong> Every record has a created_at field. Not modified_at. created_at. The record captures when the fact was recorded. If a bug later creates a duplicate, the timestamps let you reconstruct what happened in what order.</p><p><strong>Layer 3 — append-only storage.</strong> All write artifacts go to .jsonl files — JSON Lines, one record per line. The store only appends. It never rewrites. It never deletes. Once bytes are at file position N, they stay there.</p><p>All three layers together give you tamper-evident history. Mutable records are not auditable.</p><h3>Validation in code, not just in prompts</h3><p>The prepare_case_file tool description says:</p><p><em>“The evidence array MUST contain at least one concrete fact extracted from a tool call.”</em></p><p>The specialist’s system prompt also says:</p><p><em>“Always include evidence in your case files. If you do not have evidence, do more investigation first.”</em></p><p>Both of these are advisory. The model usually follows them. Under unusual conditions — a confusing user message, an edge case — it tries to call prepare_case_file with evidence=[].</p><p>If you trust the prompt to enforce this, you will ship case files with no evidence. So you also validate in the tool implementation:</p><pre>def prepare_case_file(case_type, summary, evidence, recommendation):<br>    if not evidence:<br>        return {<br>            &quot;error&quot;: &quot;evidence_required&quot;,<br>            &quot;message&quot;: &quot;evidence must contain at least one concrete fact from a tool call. Do more investigation before calling this tool.&quot;<br>        }<br>    # write the file</pre><p>The tool returns the error as is_error=True. The model reads it as an observation — &quot;I did not include evidence, let me go investigate first.&quot; It self-corrects on the next turn. The case file never gets written without evidence.</p><p>Three layers of defence, in increasing strength:</p><ul><li>Tool description — advisory. The model may ignore it.</li><li>System prompt — advisory. The model may ignore it.</li><li>Code validation — mandatory. The model literally cannot proceed.</li></ul><p>Use all three. The prompt is a nudge. The description is a nudge. The code is load-bearing.</p><h3>Bad records stay forever</h3><p>Suppose the agent files a Jira ticket in error. Engineering looks at it and says this is not a real bug.</p><p>The instinct is to delete it.</p><p>Do not.</p><p>Bad records stay. Five reasons:</p><p><strong>Evals need them.</strong> In Part 11 we build an eval suite that scores the agent’s behaviour. If you silently delete bad outputs, the metrics lie. The agent looks better than it is.</p><p><strong>Audit integrity.</strong> A sanitised history is worse than an honest history. The moment you can selectively delete records, you have lost the append-only tamper-evident property.</p><p><strong>Debugging.</strong> Future similar bugs need historical examples. If you delete the bad ticket, you cannot study what the agent was thinking when it produced it.</p><p><strong>The model’s behaviour changes.</strong> If the agent learns that bad writes disappear, it gets less careful about writes. This is subtle but real.</p><p><strong>It is a category violation.</strong> Writes are append-only by design. Deletion is a separate operation with separate authorisation. Mixing them invites worse misuse later.</p><p>How do you fix a bad record? You write a corrective record that references the old one:</p><pre>{&quot;ticket_id&quot;: &quot;YOC-15&quot;, &quot;status&quot;: &quot;superseded&quot;, &quot;superseded_by&quot;: &quot;YOC-16&quot;, &quot;reason&quot;: &quot;duplicate&quot;}</pre><p>The bad record stays. The corrective record explains it. Anyone reading the log can reconstruct the truth. The history is honest.</p><h3>Capability vs authorisation — where the user tier check lives</h3><p>You might think the case file tool should check if the user is free-tier and refuse if so.</p><p>It should not. That is putting authorisation inside the capability layer.</p><p>The tool’s job is capability — can I do this thing given these inputs? Is the evidence non-empty, is the case type valid, is the user ID present?</p><p>The tool’s job is not authorisation — is this user allowed to do this thing right now? That is the hook layer’s job.</p><p>Why does this distinction matter?</p><p>The “free user” check applies to multiple write tools. If you put it inside each tool, you have duplicated the rule multiple times. Put it in a hook and one rule covers all tools.</p><p>Also — the tool only sees the LLM-generated arguments. The hook sees the trusted server-side context. Authorisation decisions need server-side context. The tool cannot make them safely.</p><p>We go deep on this in Part 8. For now: writes go through a layered defence. Tool checks shape. Hook checks permission. Both happen on every call.</p><p>In Part 8 we add the hook layer — the code that enforces rules the LLM cannot be trusted to follow on its own.</p><p><em>This is Part 7 of </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://medium.com/@simran-kahlon/llm-agents-the-way-nobody-told-you-part-6-when-one-agent-is-not-enough-952c415bc88f?sharedUserId=simran-kahlon"><em>Part 6: When One Agent is Not Enough</em></a> <em>▶ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-8-hooks-f18c4204ed69"><em>Part 8: Hooks</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c769b6f20425" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Agents, The Way Nobody Told You — Part 6: When One Agent is Not Enough]]></title>
            <link>https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-6-when-one-agent-is-not-enough-952c415bc88f?source=rss-83917a9b1446------2</link>
            <guid isPermaLink="false">https://medium.com/p/952c415bc88f</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agent-orchestration]]></category>
            <dc:creator><![CDATA[Simran Kaur Kahlon]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 06:26:41 GMT</pubDate>
            <atom:updated>2026-10-02T08:48:26.388Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 6 of the series </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://medium.com/@simran-kahlon/llm-agents-the-way-nobody-told-you-part-5-teaching-an-agent-to-remember-7e30f317f003"><em>Part 5: Teaching an Agent to Remember</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3PidcEjJ_7XdAD5dU7k3g.png" /></figure><p>By Part 5, the bot was working well. It had memory. It could look up real data. It handled refund questions and technical issues and counsellor complaints — as long as I gave it one thing at a time and kept the system prompt short enough to reason over.</p><p>Then I tried to make it real.</p><p>I added the technical specialist’s rules: <em>“if the user reports a crash, check their device. Free users can file a support ticket but not a case file. If it is a web bug, attach browser info. If it is mobile, attach OS version…”</em></p><p>Then the refund rules: <em>“check the purchase date. Check the refund window. Premium plans get 14 days unless they bought during a promo, in which case it is 30. Eligibility does not mean approval — a human still needs to sign off…”</em></p><p>Then the counsellor rules. The billing rules. The lifecycle rules.</p><p>The system prompt was 800 lines. The model started making strange mistakes — calling the wrong tool, applying refund rules to billing questions, filing tickets when a knowledge base answer would have done. Every new rule I added seemed to nudge two old rules out of alignment.</p><p>That is the signal. When a single prompt fills up with “only call X when Y” gating instructions, you have outgrown single-agent.</p><h3>The orchestrator and specialist pattern</h3><p>You have probably heard the words “orchestrator” and “agentic workflow” everywhere. They sound complicated. They are not.</p><p>An orchestrator is just an agent whose only job is to decide what other agents should do. That is it. It does not do the actual work — it coordinates who does.</p><p>Think of it like a manager and a team. The manager does not write the code, handle the refund, or file the ticket. The manager reads the request, decides who is best placed to handle it, hands it off, and presents the result. The specialists are the ones who do the actual work.</p><p>In our case the fix is to split the agent into two layers:</p><ol><li>One <strong>orchestrator</strong> at the top. Its only job is routing — it reads the user’s message and decides which specialist should handle it.</li><li>Several <strong>specialists</strong> underneath. Each specialist owns one domain — refunds, technical, counselling, billing. Each has its own system prompt, its own tool list, and its own focus.</li><li>The orchestrator never calls data tools directly. Specialists do all the work.</li><li>The orchestrator synthesises a final reply based on what the specialists return.</li></ol><p>So the “agent” is now six agents — one orchestrator and five specialists. To the user it still feels like one. The orchestrator hides the seams.</p><p>This solves the prompt problem immediately. The refund specialist’s prompt only talks about refunds. The technical specialist’s prompt only talks about bugs. Each prompt is short, focused, and easy to change. When you want to update the refund window from 14 to 30 days, you touch one file. The other four specialists do not know that rule exists.</p><h3>Specialists are tools — this is the important part</h3><p>When the orchestrator decides which specialist to call, it needs to actually trigger that specialist somehow. There are two ways to do this and the choice matters more than it seems.</p><p><strong>Option A</strong> is the obvious one — a direct Python call. After the model picks a route, you just call refund_specialist.run(query) as a regular function in your code. Simple, direct, works fine.</p><p><strong>Option B</strong> is to wrap the specialist as a tool. You define a tool called delegate_to_specialist(specialist: str, query: str). When the orchestrator&#39;s model decides to route, it emits a tool_use block for this tool — the same mechanism it uses for every other tool call. Your dispatcher reads the block and calls the right specialist&#39;s run() method.</p><p>Both options produce roughly the same result. The user gets a correct reply either way.</p><p>So why does it matter which one you pick?</p><p>Because everything that comes later — hooks, audit logs, evals, caching — is built on top of the tool_use mechanism. If delegation goes through tool_use, all of that comes for free. If it goes through a direct Python call, none of it does.</p><p>Let me be specific.</p><p><strong>Hooks.</strong> In the hooks article we add a layer that intercepts every tool_use call to enforce rules — &quot;free users cannot file a case file.&quot; Because delegation goes through tool_use, the hook layer covers specialist calls automatically. With a direct Python call, the hook layer would be blind to it. You would need a separate gating system just for routing. Two parallel systems, twice the bugs.</p><p><strong>Audit logs.</strong> When we build the eval harness, it reads the audit log to score agent behaviour. Routing decisions appear in the log as delegate_to_specialist tool calls. No separate routing log needed.</p><p><strong>Single turn decision.</strong> The orchestrator’s model decides where to route in one tool-calling turn. With direct Python calls you would need one LLM pass to decide the route and a second to invoke the work.</p><p><strong>Extensibility.</strong> Adding a sixth specialist is one line of registration code. The orchestrator’s tool surface does not grow — there is still exactly one tool, delegate_to_specialist. Its argument values just include one more option.</p><p>The principle worth locking in: <strong>in agentic systems, the question is never “should this be a tool?” The question is “is there a reason this is not a tool?”</strong></p><p>Every action — reads, writes, sub-agent calls, external API calls, database queries — should go through tool_use. Because every tool gets hooks, audit logs, message history, caching, and eval coverage for free. Direct Python calls give you none of that. This is the uniform tool surface principle. It is load-bearing for everything that comes after.</p><h3>Why the orchestrator only has one tool</h3><p>The question always comes up: why not give the orchestrator lookup_user too? It could handle simple lookups without spinning up a specialist.</p><p>Tempting. Wrong. Four reasons — Role, Context, Cost, Authz:</p><p><strong>Role.</strong> The orchestrator’s job is routing. The moment it can also do data lookups, its prompt has to teach it both “which specialist?” and “when to fetch data myself?” The conditional logic grows back. You are back to the 800-line prompt problem you just escaped.</p><p><strong>Context.</strong> A lookup_user result is a JSON blob. If the orchestrator calls it, that blob lives in the orchestrator&#39;s message history forever — costing tokens on every future turn. Specialists are compression boundaries: a specialist can call ten tools internally, accumulate kilobytes of evidence, and return a small structured summary to the orchestrator. The orchestrator never sees the raw data. Pulling tool calls up into the orchestrator destroys that boundary.</p><p><strong>Cost.</strong> The orchestrator runs on a capable, expensive model. Specialists can run on a cheaper, faster model. If you give the orchestrator data tools, you are paying expensive-model rates for work a cheaper model could do.</p><p><strong>Authz.</strong> Each specialist has its own restricted tool list. The technical specialist cannot see purchase history. The refund specialist cannot create support tickets. This per-specialist scoping is a security feature. If the orchestrator can do anything any specialist can do, the scoping is meaningless.</p><p>Orchestrator has exactly one tool: delegate_to_specialist. Specialists have several. The orchestrator routes. The specialists work.</p><h3>SpecialistResult — the structured handoff</h3><p>Specialists do not return strings. They return a structured object:</p><pre>class SpecialistResult(BaseModel):<br>    reasoning: str<br>    evidence: list[str]<br>    verdict: Literal[<br>        &quot;resolved&quot;,<br>        &quot;needs_human_review&quot;,<br>        &quot;delegate_to_other&quot;,<br>        &quot;out_of_scope&quot;,<br>        &quot;ineligible&quot;<br>    ]<br>    suggested_action: str<br>    user_reply: str</pre><p>Notice reasoning comes first — same chain-of-thought trick from Part 2. The model writes its reasoning before committing to a verdict.</p><p>The most important field is verdict. Here is why.</p><p>When the specialist returns, the orchestrator needs to decide what to do next. Send the reply to the user? Escalate to a human? Try a different specialist? That decision is a branch in Python control flow.</p><p>If verdict did not exist — if the specialist only returned user_reply as plain text — the orchestrator would have to pass that text into another LLM call to figure out the right next step. Another round-trip. More latency. Non-deterministic results.</p><p>With verdict, the orchestrator does this:</p><pre>if result.verdict == &quot;needs_human_review&quot;:<br>    enqueue_for_human(result)<br>elif result.verdict == &quot;resolved&quot;:<br>    return result.user_reply<br>elif result.verdict == &quot;delegate_to_other&quot;:<br>    return delegate(...)</pre><p>Pure Python. No extra LLM call. Deterministic.</p><p>verdict is the join column between LLM judgment and Python control flow. The LLM is good at producing reasoning, but you do not want reasoning making your control flow decisions. You want the LLM to produce a categorical signal you can branch on. The natural language explanation comes along as a separate field.</p><p>Any time you find yourself sending LLM output into another LLM call “to figure out what to do with it” — stop. Restructure the first output to include a categorical field. Branch on the field. Save the round-trip.</p><h3>Multi-concern queries — how fan-out works</h3><p>A user types: “my counsellor never showed up and I want a refund.”</p><p>Two concerns. Counselling and refund. Here is what actually happens:</p><ol><li>The orchestrator’s model sees the message. It generates one assistant response with two tool_use blocks — one for delegate_to_specialist(specialist=&quot;counselling&quot;, ...) and one for delegate_to_specialist(specialist=&quot;refund&quot;, ...).</li><li>The dispatcher loops through both blocks. Each specialist runs its own complete agent loop internally — calls its own tools, builds its own evidence, returns its own SpecialistResult.</li><li>Both results come back as tool_result blocks in a single user message — same rule from Part 4, parallel tool calls always return in one message.</li><li>The orchestrator’s next turn sees both results and composes a single reply.</li></ol><p>The fan-out happens inside one assistant turn. The model decides to delegate to two specialists at once. The dispatcher just iterates through whatever the model emitted.</p><p>One rule worth noting: specialists never call each other. Only the orchestrator can spawn specialists. If the refund specialist thinks the issue is really a counselling problem, it returns verdict=&quot;delegate_to_other&quot; with a hint, and lets the orchestrator decide. Routing stays centralised.</p><h3>The file structure</h3><pre>src/<br>  base_specialist.py     ← Specialist dataclass, run() returns SpecialistResult<br>  delegate_tool.py       ← the delegate_to_specialist tool<br>  orchestrator.py        ← Conversation from Part 5, but tools = [delegate]<br>  specialists/<br>    technical.py<br>    billing.py<br>    refund.py<br>    counselling.py<br>    lifecycle.py</pre><p>Each specialist file is short. A system prompt focused on one domain, a tool subset filtered to what that specialist is allowed to call, and a run() method that is essentially the Part 4 agent loop wrapped to return a SpecialistResult.</p><p>The whole sub-agent system adds roughly 400 lines on top of Part 5. It feels bigger than that conceptually — but the code is small. That is a sign the architecture is right. Good architectural choices do not bloat a codebase. They make small code do more.</p><p>The bot can now read data, remember conversations, and route complex queries to the right specialist. But it still cannot write anything. It cannot actually file a ticket or initiate a refund. Everything it produces is text.</p><p>In Part 7 we give the agent the ability to act — tools that write, not just read.</p><p><em>This is Part 6 of </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://medium.com/@simran-kahlon/llm-agents-the-way-nobody-told-you-part-5-teaching-an-agent-to-remember-7e30f317f003"><em>Part 5: Teaching an Agent to Remember</em></a> <em>▶ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-7-letting-the-agent-act-c769b6f20425"><em>Part 7: Letting the Agent Act</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=952c415bc88f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Agents, The Way Nobody Told You — Part 5: Teaching an Agent to Remember]]></title>
            <link>https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-5-teaching-an-agent-to-remember-7e30f317f003?source=rss-83917a9b1446------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e30f317f003</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Simran Kaur Kahlon]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 09:42:09 GMT</pubDate>
            <atom:updated>2026-10-02T08:49:13.827Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 5 of the series </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-4b-system-prompt-vs-tools-fd59a0535c82?sharedUserId=simran-kahlon"><em>Part 4b: System Prompt vs Tools</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3PidcEjJ_7XdAD5dU7k3g.png" /></figure><p>By the end of Part 4, the bot could look things up. Real user data, real purchase history, real dates. The hallucinations were gone.</p><p>But it had goldfish brain.</p><p>Every time the user typed something, it started from zero. “I want a refund.” It looks up the user, finds the purchase, explains the refund window. “Actually, can you cancel that instead?” It looks up the user again, finds the purchase again, and has no idea what “that” refers to.</p><p>You cannot have a real conversation with something that forgets everything the moment you finish a sentence. Part 5 is about fixing that.</p><h3>Memory is not what you think it is</h3><p>When most developers hear “agent memory,” they think Redis. Vector databases. A memory module. Some separate system that stores and retrieves information.</p><p>None of that.</p><p>Memory in an LLM agent is much simpler and weirder than that.</p><p><strong>Memory is the messages list. You just do not throw it away.</strong></p><p>That is the entire insight. The model has no internal memory between API calls — we established that in Part 1. But the messages list you pass to the API is the model’s memory. Every turn you append to it, every tool call gets recorded in it, every result stays in it. By the time turn 3 arrives, the model sees the full history of turns 1 and 2. That is memory.</p><h3>The code change is tiny</h3><p>In Part 4, every call to the agent looked like this:</p><pre>def run(user_message: str) -&gt; str:<br>    messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_message}]<br>    # ... agent loop ...<br>    return final_text</pre><p>The messages list was a local variable. It got created at the top, used during the loop, and dropped at the end. The next call started fresh. That is why the bot forgot.</p><p>The fix is to move messages onto a class that survives between turns:</p><pre>from dataclasses import dataclass, field</pre><pre>@dataclass<br>class Conversation:<br>    messages: list = field(default_factory=list)<br>    user_id: str | None = None<br>    turn_count: int = 0</pre><pre>    def send(self, user_message: str) -&gt; str:<br>        self.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_message})<br>        # ... same agent loop, but uses self.messages ...<br>        self.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: final_text})<br>        self.turn_count += 1<br>        return final_text</pre><p>That is it. The agent loop did not change. The four steps from Part 4 are identical. The only change is that messages now lives on an object that persists between turns instead of a local variable that gets thrown away.</p><p>Now when the user sends turn 2, the model sees all of turn 1 — the question, the tool calls, the results, the reply. The whole history. That is the memory.</p><h3>The Python gotcha that will leak data across users</h3><p>There is a bug version of the above that looks almost identical, passes code review, and will cause a serious production incident.</p><pre>class Conversation:<br>    messages = []   # ← do not do this</pre><p>This looks fine. It runs fine in development. It will betray you in production.</p><p>Here is what is happening. messages = [] at the class level creates one empty list, shared by every instance of the class. When Alice&#39;s session does self.messages.append(...), Python looks for messages on self — does not find it — falls back to the class — finds the shared list — and appends to it. When Bob&#39;s session does the same thing, it appends to the same list.</p><p>Alice and Bob now share one conversation. Their messages interleave. Their data mixes. The agent looks up Bob’s purchases when Alice asks a question. You will not notice until the first production incident.</p><p>The fix is field(default_factory=list) in a dataclass, or putting messages inside __init__:</p><pre># Option A — dataclass<br>@dataclass<br>class Conversation:<br>    messages: list = field(default_factory=list)</pre><pre># Option B — regular class<br>class Conversation:<br>    def __init__(self):<br>        self.messages = []</pre><p>Both create a new list per instance. The bug version creates one list for the class.</p><p>In normal Python this is just a bug. In agent code, where each Conversation is a user&#39;s session, it is a cross-user data leak. Each session must own its own messages list. The class structure is not a style choice — it is an isolation boundary.</p><h3>Inject the user ID once, not every turn</h3><p>When the conversation starts, your application knows who the user is. You inject the user ID into the first message so the model has it:</p><pre>def send(self, user_message: str) -&gt; str:<br>    if self.turn_count == 0:<br>        user_message = f&quot;[user_id: {self.user_id}]\n{user_message}&quot;<br>    self.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_message})<br>    # ...</pre><p>Notice the if self.turn_count == 0. The user ID only gets injected on the very first turn. Never again.</p><p>Why? Because once it is in the history, the model has it forever. The messages list is permanent. Re-injecting it on every turn wastes tokens, and later when you add prompt caching — we cover this in Part 9 — repeating the user ID breaks the cached prefix. The model already knows who the user is. Telling it again every turn is noise.</p><p>Once-grounded, persistently-known. Stable session context goes into the history once. The model carries it from that point on.</p><h3>Do not prune tool_use and tool_result blocks</h3><p>As conversations get longer, the messages list grows. After a few turns it has user messages, assistant tool_use blocks, tool_result blocks with big JSON payloads, more assistant text. It looks bloated.</p><p>The temptation is to trim the older tool results. They are large. The model does not need them anymore, right?</p><p>It does. Do not prune them.</p><p>Here is the concrete failure. A user says on turn 1: “my counsellor keeps missing our sessions.” The agent calls get_call_logs, sees three no-shows, and writes a sympathetic reply. On turn 2, the user says: &quot;should I switch counsellors?&quot;</p><p>If you pruned the tool_result from turn 1, the agent now has three bad options:</p><ol><li><strong>Re-fetch the call logs.</strong> Defeats the entire point of memory. Wastes tokens and time.</li><li><strong>Hallucinate.</strong> Says something like “yes, given those 3 missed sessions…” — without any proof, because the proof was deleted.</li><li><strong>Lose continuity.</strong> Does not reference the no-shows at all. The user feels like the agent forgot.</li></ol><p>Tool_use and tool_result blocks are not transient. They are reasoning history. The model reasons over its prior tool calls to decide what to do next. When you prune them, you break reasoning continuity.</p><p>The right answer to a long history is prompt caching, not pruning. We cover that in Part 9 — it makes long histories almost free. Until then, keep everything.</p><h3>What the messages list actually looks like</h3><p>Let me show you what is in the messages list after two turns.</p><p><strong>Before turn 1:</strong> messages = []</p><p><strong>User sends turn 1:</strong> “my counsellor missed our last 3 sessions.”</p><p>After turn 1 completes, messages contains:</p><pre>1. user:      &quot;[user_id: u_004]\nmy counsellor missed our last 3 sessions.&quot;<br>2. assistant: [tool_use: lookup_user(u_004)]<br>3. user:      [tool_result: {tier: &quot;premium&quot;, ...}]<br>4. assistant: [tool_use: get_call_logs(u_004)]<br>5. user:      [tool_result: {sessions: [..., no_show, no_show, no_show]}]<br>6. assistant: &quot;I am sorry to hear that. I can see your counsellor missed 3 sessions...&quot;</pre><p>Six entries. The model saw everything it did.</p><p><strong>User sends turn 2:</strong> “should I switch counsellors?”</p><p>The orchestrator appends:</p><pre>7. user: &quot;should I switch counsellors?&quot;</pre><p>And sends all seven entries to the API. No user ID prefix this time — it is already in entry 1. No re-running of lookup_user or get_call_logs — the model can see the results in entries 3 and 5.</p><p>The reply on turn 2 references the no-shows from turn 1. The conversation feels continuous because it is continuous. There is no magic. There is just a messages list that did not get thrown away.</p><h3>What actually changed</h3><p>I want to be clear about this because it is easy to miss.</p><p>The agent loop from Part 4 did not change at all. Same four steps. What changed is where the messages list lives — from a local variable that gets dropped after each call, to an attribute on a long-lived object that persists between turns.</p><p>This is a pattern that will show up again. The agent loop is small and stable. Most of the architectural work in agents is about what surrounds the loop — what feeds messages in, what state outlives the loop, what observes it. The loop is the core. Everything else is plumbing.</p><p>In Part 6 we hit the next ceiling. Right now the entire bot is one model, one system prompt, one tool list. That works for simple cases. But when you need to handle five different types of problems — each with their own policies, tone, and tools — cramming everything into one system prompt makes the model confused and unreliable.</p><p>The fix is sub-agents. And the way to wire them up is cleaner than you would expect.</p><p><em>This is Part 5 of </em><strong><em>“LLM Agents, The Way Nobody Told You.”</em></strong> <em>◀ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-4b-system-prompt-vs-tools-fd59a0535c82?sharedUserId=simran-kahlon"><em>Part 4b: System Prompt vs Tools</em></a> <em>▶ </em><a href="https://simran-kahlon.medium.com/llm-agents-the-way-nobody-told-you-part-6-when-one-agent-is-not-enough-952c415bc88f"><em>Part 6: When One Agent is Not Enough</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e30f317f003" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>