<?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 ATNO for GenAI &amp; Agentic AI on Medium]]></title>
        <description><![CDATA[Stories by ATNO for GenAI &amp; Agentic AI on Medium]]></description>
        <link>https://medium.com/@atnoforgenai?source=rss-36b5ad2df1f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MSHmMNzIrUQf7FUMWtWepA.png</url>
            <title>Stories by ATNO for GenAI &amp;amp; Agentic AI on Medium</title>
            <link>https://medium.com/@atnoforgenai?source=rss-36b5ad2df1f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:40:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atnoforgenai/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 200MB Import Problem: Profiling and Fixing Agent Cold Starts]]></title>
            <link>https://medium.com/@atnoforgenai/the-200mb-import-problem-profiling-and-fixing-agent-cold-starts-1ee9e64365dc?source=rss-36b5ad2df1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ee9e64365dc</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[ATNO for GenAI & Agentic AI]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 08:50:28 GMT</pubDate>
            <atom:updated>2026-10-13T08:50:28.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FabYQoCJqloAkuOW_YKFhQ.jpeg" /></figure><p>The first request to the agent took eleven seconds (illustrative). The second took four hundred milliseconds. The difference was that the first request paid for every import statement at the top of the handler file, and the second one didn’t. If you ship AI agents on serverless infrastructure, you have this bug. You just haven’t measured it yet.</p><p>One caveat up front: measurements I took locally are labeled with the environment, AWS platform behavior comes from AWS documentation, and every worked-example number is labeled illustrative. I did not run a controlled experiment on Lambda for this piece.</p><h3>The Problem</h3><p>An AI agent in production is usually a thin orchestration layer over very heavy dependencies: an LLM SDK, an embedding model, a vectorstore client, a reranker, observability middleware. On your laptop this is invisible, because the process stays alive all day.</p><p>Serverless doesn’t work like your laptop. AWS Lambda runs your function in short-lived execution environments. When no warm environment exists, Lambda creates one: it provisions the sandbox and downloads your code, boots the runtime, runs your module-level code (the Init phase), and only then invokes your handler. Your imports live in the Init phase, and the user waits through all of it.</p><p>Conventional responses fail in predictable ways. Adding memory buys CPU proportionally (1,769 MB is roughly one full vCPU), so imports run faster, but you pay for that memory on every invocation to speed up something that happens once per environment. Provisioned concurrency keeps environments warm and works completely, but it bills you for every provisioned environment whether it serves traffic or not. The third option is declaring cold starts a platform problem, which is how teams ship an agent that feels broken to every new user and fine in every demo.</p><p>The false assumptions underneath: import time is negligible (it is usually the largest component of a Python cold start); a bigger box fixes a software problem (it shortens the symptom and lengthens the bill); cold starts only matter at scale (they matter most at low traffic); and the dependency tree is someone else’s concern (it is your latency budget, line by line).</p><h3>What Actually Matters</h3><p>In priority order, the things that move the number.</p><p><strong>1. Measure the import tree before changing anything.</strong> The import graph of an agent is never what you guess. python -X importtime prints the self time and cumulative time of every module import to stderr. The picture is usually embarrassing: transitive dependencies you never chose, a framework importing its test utilities, a client library pulling in a web framework you don&#39;t use. On my own machine (Python 3.12.3, Linux), numpy alone costs about 127 milliseconds warm and 272 milliseconds cumulative cold, for 36 MB on disk. That&#39;s one well-behaved library.</p><p><strong>2. Enforce the Init versus Invoke split.</strong> Module-level code runs once per cold start; handler code runs per request. Client construction and connection setup belong at module level so warm invocations reuse them; imports that only some requests need belong inside functions or behind lazy loading. Most agent handlers have this exactly backwards.</p><p><strong>3. Lazy-load by request path, not by optimism.</strong> An agent that usually answers with an LLM and only sometimes retrieves documents should not import the vectorstore, embeddings, and reranker on every cold start. Defer each heavy import to the code path that needs it, with function-level imports or PEP 562 module __getattr__. The import costs the same when it runs; most cold starts never run it.</p><p><strong>4. Put the dependency set on a diet.</strong> The CPU-only PyTorch wheel exists because the default wheel bundles CUDA libraries most serverless functions never touch. Package size is latency, not just storage.</p><p><strong>5. Right-size memory deliberately.</strong> Once the software is lean, tune memory for the CPU it buys, measuring Init duration at each step. Memory is the last lever because it’s the only one that charges you forever.</p><h3>Architecture: The Cold Start, Stage by Stage</h3><p>A Lambda cold start for a Python agent, in order:</p><ol><li>Provision: Lambda allocates a sandbox and downloads your deployment package. Cost driver: package size in megabytes.</li><li>Runtime boot: the Python runtime starts. Cost driver: small and mostly fixed.</li><li>Init, imports: your module-level code runs, executing every top-level import. Cost driver: the import graph, usually the largest stage.</li><li>Init, clients: SDK clients, connection pools, and model handles are constructed. Cost driver: network calls and model loading at module scope.</li><li>Invoke: your handler runs. On a warm environment, this is the only stage.</li></ol><p>And the profiling workflow that attacks it, in order:</p><ol><li>Capture: run the handler’s import chain under python -X importtime and save stderr.</li><li>Rank: sort modules by self time; the top five usually explain most of the cost.</li><li>Classify: each heavy import is eager (every request), lazy (some paths), or removable.</li><li>Restructure: lazy imports behind function calls or module __getattr__; clients to module level; slim the package.</li><li>Gate: CI fails the build when any import exceeds its budget.</li></ol><h3>Implementation</h3><p>Four pieces, each tested. First, profiling. Run your handler’s import chain and look at the tail of the output, where the cumulative totals live:</p><pre>python -X importtime -c &quot;import agent.handler&quot; 2&gt; importtime.log<br>tail -20 importtime.log</pre><p>Each line shows self microseconds, cumulative microseconds, and the module name. The largest self times are your suspects. For a visual map, feed the log into the open-source python-importtime-graph visualizer.</p><p>Second, a CI gate so the import graph can’t regrow silently:</p><pre>&quot;&quot;&quot;CI gate: fail if any single import costs more than BUDGET_MS.<br><br>Usage:<br>    python import_budget.py --budget-ms 500 -- python -c &quot;import agent.handler&quot;<br>&quot;&quot;&quot;<br>import argparse<br>import re<br>import subprocess<br>import sys<br><br># NOTE: this gate checks SELF time per module, not cumulative tree cost.<br># A framework with fifty cheap submodules passes here while still costing<br># you cumulatively. Read the full -X importtime log when profiling;<br># this gate is a tripwire, not a diagnosis. Format verified against<br># CPython 3.12&#39;s -X importtime stderr output.<br>LINE = re.compile(r&quot;^import time:\s+(\d+)\s+\|\s+(\d+)\s+\|\s+(\S+)&quot;)<br><br><br>def main() -&gt; int:<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;--budget-ms&quot;, type=float, default=500)<br>    parser.add_argument(&quot;command&quot;, nargs=argparse.REMAINDER)<br>    args = parser.parse_args()<br>    cmd = [c for c in args.command if c != &quot;--&quot;]<br><br>    proc = subprocess.run(<br>        [sys.executable, &quot;-X&quot;, &quot;importtime&quot;, *cmd],<br>        capture_output=True,<br>        text=True,<br>    )<br>    budget_us = args.budget_ms * 1000<br>    offenders = []<br>    for line in proc.stderr.splitlines():<br>        m = LINE.match(line.strip())<br>        if m:<br>            self_us, _cumulative_us, module = m.groups()<br>            if float(self_us) &gt; budget_us and not module.startswith(&quot;_&quot;):<br>                offenders.append((module, float(self_us) / 1000))<br><br>    if offenders:<br>        print(f&quot;IMPORT BUDGET EXCEEDED ({args.budget_ms:.0f} ms per import):&quot;)<br>        for module, ms in sorted(offenders, key=lambda x: -x[1])[:10]:<br>            print(f&quot;  {ms:8.1f} ms  {module}&quot;)<br>        return 1<br>    print(f&quot;OK: all imports under {args.budget_ms:.0f} ms&quot;)<br>    return 0<br><br><br>if __name__ == &quot;__main__&quot;:<br>    sys.exit(main())</pre><p>The gate measures self time per module, not cumulative cost, so read the full log when profiling and treat the gate as a tripwire.</p><p>Third, lazy loading with PEP 562. This module defers three heavy submodules until first attribute access, then caches them so the import runs exactly once:</p><pre>&quot;&quot;&quot;Lazy heavy imports via PEP 562 module __getattr__.&quot;&quot;&quot;<br>import importlib<br><br>_LAZY = {<br>    &quot;vectorstore&quot;: &quot;agent.vectorstore&quot;,<br>    &quot;reranker&quot;: &quot;agent.reranker&quot;,<br>    &quot;embeddings&quot;: &quot;agent.embeddings&quot;,<br>}<br><br><br>def __getattr__(name):<br>    if name in _LAZY:<br>        module = importlib.import_module(_LAZY[name])<br>        globals()[name] = module  # cache: import runs exactly once<br>        return module<br>    raise AttributeError(f&quot;module {__name__!r} has no attribute {name!r}&quot;)<br><br><br>def __dir__():<br>    return sorted(list(globals().keys()) + list(_LAZY.keys()))</pre><p>Fourth, the handler with a strict Init versus Invoke split. Everything above the handler runs once per cold start; the handler itself imports only on the retrieval path and constructs no clients:</p><pre>&quot;&quot;&quot;Lambda handler with a strict Init / Invoke split.&quot;&quot;&quot;<br>import json<br>import os<br><br># ---- Init phase: runs once per cold start, outside the handler ----<br>import boto3  # needed on every invocation, so it stays in the Init phase<br><br>REGION = os.environ.get(&quot;AWS_REGION&quot;, &quot;us-east-1&quot;)<br>_bedrock = boto3.client(&quot;bedrock-runtime&quot;, region_name=REGION)<br><br># Heavy ML imports stay OUT of the init phase. They load lazily<br># inside the code path that needs them (see lazy_loader.py).<br><br><br>def _answer_with_llm(prompt: str) -&gt; str:<br>    body = json.dumps(<br>        {<br>            &quot;anthropic_version&quot;: &quot;bedrock-2023-05-31&quot;,<br>            &quot;max_tokens&quot;: 512,<br>            &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>        }<br>    )<br>    # Replace with a model ID from your Bedrock console. Model IDs get<br>    # retired, so don&#39;t hardcode a specific one in production code.<br>    resp = _bedrock.invoke_model(modelId=&quot;your-model-id&quot;, body=body)<br>    return json.loads(resp[&quot;body&quot;].read())[&quot;content&quot;][0][&quot;text&quot;]<br><br><br># ---- Invoke phase: runs on every request, warm or cold ----<br>def handler(event, context):<br>    prompt = event.get(&quot;prompt&quot;, &quot;&quot;)<br>    if not prompt:<br>        return {&quot;statusCode&quot;: 400, &quot;body&quot;: json.dumps({&quot;error&quot;: &quot;missing prompt&quot;})}<br><br>    # Only retrieval requests pay the heavy import cost, and only once<br>    # per environment; sys.modules caches it afterwards.<br>    if event.get(&quot;use_retrieval&quot;):<br>        from agent import lazy_loader<br><br>        docs = lazy_loader.vectorstore.search(prompt, top_k=3)<br>        prompt = f&quot;Context:\n{docs}\n\nQuestion: {prompt}&quot;<br><br>    return {&quot;statusCode&quot;: 200, &quot;body&quot;: json.dumps({&quot;answer&quot;: _answer_with_llm(prompt)})}</pre><p>Two platform levers, for when the software work is done. Provisioned concurrency keeps environments initialized and warm, eliminating cold starts for the provisioned capacity, billed for as long as it is configured:</p><pre>aws lambda put-provisioned-concurrency-config \<br>  --function-name support-agent \<br>  --qualifier prod \<br>  --provisioned-concurrent-executions 5</pre><p>Lambda SnapStart snapshots the initialized environment and restores it on cold starts instead of re-running init. It supports Python 3.12 and later, applies to published versions (not $LATEST), and doesn’t work with EFS or ephemeral storage over 512 MB:</p><pre>aws lambda update-function-configuration \<br>  --function-name support-agent \<br>  --snap-start ApplyOn=PublishedVersions</pre><p>The dependency diet’s highest-leverage single change for ML agents: the CPU-only PyTorch wheel, which drops the CUDA libraries a Lambda function never uses:</p><pre>pip install torch --index-url &lt;https://download.pytorch.org/whl/cpu&gt;</pre><h3>AI and Automation: Where Each Belongs</h3><p>Deterministic automation does the real work: the import-budget script in CI, and CloudWatch alarms on Init Duration p99. AI’s honest role is narrower, triage: a scheduled job can feed the week’s slowest importtime logs to an LLM for likely causes, but a human verifies against the log. The Init versus Invoke split is product knowledge no model can decide for you.</p><h3>Practical Example: A Fictional Walkthrough</h3><p>Take a fictional SupportAgent. Every number here is illustrative. Its handler imports torch, transformers, a vectorstore client, and a reranker at module top; the 200MB illustrative package cold-starts in about 10s illustrative (2.5s download and unpack, 6s import chain, 1.5s client construction) while warm invocations take 0.4s illustrative. The team profiles, drops a transitive web framework for a slimmer install (40MB illustrative saved), lazy-loads the vectorstore, embeddings, and reranker behind the retrieval path (used by 30 percent illustrative of requests), and switches torch to the CPU-only wheel. The result: about 3s illustrative cold starts on the majority path, with retrieval requests paying a one-time 2s illustrative on first use per environment. Your graph will differ; the only numbers that matter are from your own -X importtime log.</p><h3>Results and Evaluation</h3><p>I did not run a controlled experiment on Lambda for this article, so there are no before-and-after production metrics. Measured locally (Python 3.12.3, Linux): numpy imports in about 127ms warm and 272ms cumulative cold, occupying 36MB on disk. The import-budget script was executed locally and correctly flags offenders, including its failure exit code.</p><p>The rest is analysis. Lazy loading doesn’t make imports cheaper; it changes which cold starts pay. The dependency diet is the only technique that helps every cold start. Provisioned concurrency and SnapStart don’t reduce init cost; they change how often you pay it.</p><h3>Limitations and Failure Modes</h3><p>Three that matter most. First, lazy imports defer ImportErrors from deploy time to request time. A typo in a lazily imported module that crashed the Init phase visibly now crashes a single request, possibly weeks later. Mitigate with a warmup probe: after deploy, invoke once per lazy path in a canary before routing traffic. Second, SnapStart’s constraints: no EFS, no ephemeral storage over 512 MB, published versions only, and anything with a short TTL acquired during init goes stale after restore. Third, provisioned concurrency bills continuously for the configured capacity, doesn’t cover spikes above it, and doesn’t survive deploys. And if the model itself is the bottleneck, say a 2GB embedding model at init, the fix is a smaller model or remote inference, not import hygiene.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ee9e64365dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Cloud to Laptop: Your First Local Agent That Costs Nothing to Run]]></title>
            <link>https://medium.com/@atnoforgenai/from-cloud-to-laptop-your-first-local-agent-that-costs-nothing-to-run-591a1a7958e7?source=rss-36b5ad2df1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/591a1a7958e7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[ATNO for GenAI & Agentic AI]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 06:48:17 GMT</pubDate>
            <atom:updated>2026-10-13T06:48:17.799Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SnVIryCqZSNxkVwn5bIKDw.jpeg" /></figure><p>Take a familiar pattern (a composite of several real setups I have seen, not one specific bill): a cron job asks a cloud LLM to summarize a log file every ten minutes. Six weeks later the API bill beats the VPS, the domains, and the coffee budget combined. The summaries are fine. The unit economics are not.</p><p>Two forces are pushing agents off the cloud: cost and privacy. Every agent loop multiplies token spend, the plan, the tool calls, the retries, turning a single request into a dozen model calls. And everything the agent touches, logs, code, notes, customer data, gets sent to someone else’s servers. For hobby projects, internal tools, and high-frequency background jobs, that combination rarely makes sense.</p><p>So here is the contrarian question: what if the agent just ran on your laptop, for free? This article shows you how: a real agent with tools, a reasoning loop, and guardrails, running entirely on local hardware. No API keys. No per-token billing. No data leaving your machine.</p><p>One honest caveat: a local 8B model is not a frontier model. It is worse at multi-step tool use and likelier to wander. This build suits learning agent architecture, privacy-sensitive tasks, and workloads where the cloud bill makes no sense. Not a drop-in replacement for a production cloud agent. With that understood, let us build.</p><h3>The Problem</h3><p>Cloud agents fail in three predictable ways, and only one of them is the model’s fault.</p><ul><li>Cost compounds. An agent does not make one call per task. It makes many: plan, act, observe, replan. Per-token rates look trivial until you multiply by loops, retries, and background schedules. For hobby projects, internal tools, and high-frequency jobs, the math often does not work.</li><li>Latency stacks. Every step is a network round trip. A five-step task at two seconds per step is a ten-second task, before retries. For interactive tools, that feels broken.</li><li>Data leaves your machine. Logs, codebases, notes, customer data: everything the agent touches goes to someone else’s server. Sometimes that is fine. Sometimes it is a compliance conversation you do not want to have.</li></ul><p>The false assumption is that agents require frontier models. They require a loop, tools, and a model good enough at following instructions. For file triage, log summarization, codebase Q&amp;A, and personal automation, a local model clears that bar. The bottleneck was never intelligence alone. It was architecture, and architecture is free.</p><h3>What Actually Matters</h3><p>Strip an agent to its essentials and you get four components. Everything else is packaging.</p><ul><li>A model that can do tool calling: structured function calls, not just prose. The one hard requirement, and why model choice matters more than size.</li><li>A tool registry: plain functions with names, descriptions, JSON schemas. The model never touches your system; it only asks to call a named tool with arguments.</li><li>A loop: send the conversation to the model, execute tool calls, append results, repeat. With a maximum iteration count, because loops without exits mean infinite afternoons.</li><li>Guardrails: timeouts, an allowlist for anything destructive, a log of every step. Not extras. The difference between an agent and a liability.</li></ul><p>Not on the list: a vector database, a framework, a cloud account, a GPU cluster. Add those later. The first version needs none of them.</p><h3>Choosing the model</h3><p>The practical default is Meta’s Llama 3.1 8B (July 2024, 128K context). At 4-bit quantization it needs roughly 5 to 8 GB of memory, fitting a decent laptop including Apple Silicon, with structured tool calling through the Ollama API.</p><p>Alternatives: Mistral 7B (fast), Qwen2.5 (strong instruction following), Microsoft’s Phi (efficient on weak hardware). Criteria: tool-calling support first, context window second, size third. A 7B model that calls tools reliably beats a 70B model that cannot run on your machine.</p><h3>Choosing the runtime</h3><p>Ollama is the right default. Single binary, manages model downloads and quantization, exposes an OpenAI-compatible API with native tool-calling support. Alternatives are real but heavier: llama.cpp for maximum control, vLLM for server-grade throughput you do not need yet, LM Studio as a GUI that is less scriptable. The loop is runtime-agnostic, so you can swap later without changing the architecture.</p><h3>Architecture: The Loop Is the Agent</h3><p>The entire architecture, no hidden complexity:</p><pre>User request<br>    |<br>    v<br>+------------------+<br>|  Build messages  |  system prompt + tool definitions + history<br>+------------------+<br>    |<br>    v<br>+------------------+       +-------------------+<br>|  Model reasons   | ----&gt; |  Tool calls?      |<br>+------------------+       +-------------------+<br>                              |           |<br>                             YES          NO<br>                              |           |<br>                              v           v<br>                    +----------------+  Return final<br>                    | Execute tools  |  answer to user<br>                    | (allowlisted,  |<br>                    |  with timeout) |<br>                    +----------------+<br>                              |<br>                              v<br>                    +----------------+<br>                    | Append results |<br>                    | to messages    |<br>                    +----------------+<br>                              |<br>                              v<br>                    +----------------+<br>                    | Iterations &lt; N?  |--NO--&gt; Stop, report<br>                    +----------------+         partial progress<br>                              |<br>                             YES<br>                              |<br>                              v<br>                    (back to &quot;Model reasons&quot;)</pre><p>Each pass through the loop is one model call. The model answers directly or requests tool calls. Tool calls execute in your Python process, never in the model. Results return as new messages, and the model sees them on the next pass. The loop ends when the model answers without tool calls or hits the iteration cap.</p><p>Two design decisions deserve emphasis.</p><p>First, the model never executes anything. The model produces JSON describing a desired call. Your code validates the tool name against a registry, validates arguments against a schema, then runs your own function. If the model hallucinates delete_everything, nothing happens: that tool is not in the registry. The attack surface is your tool implementations, which you wrote and can audit.</p><p>Second, the iteration cap is a correctness feature, not just safety. Local models are prone to looping: repeating the same tool call with slightly different arguments, never converging. A cap of 8 to 12 iterations is generous for simple tasks. When it hits, return what you have and say so. Partial progress with an honest report beats a hung process.</p><h3>Implementation</h3><p>You need Python 3.10+ and Ollama (<a href="http://ollama.com/">ollama.com</a>):</p><pre>ollama pull llama3.1:8b</pre><p>Install the Python client:</p><pre>pip install ollama</pre><pre>from pathlib import Path<br>import ollama<br>MODEL = &quot;llama3.1:8b&quot;<br>MAX_ITERATIONS = 10<br>WORKSPACE = Path.home() / &quot;agent-workspace&quot;<br>WORKSPACE.mkdir(exist_ok=True)<br># ---- Tools: plain functions. The model can only call these. ----<br>def read_file(path: str) -&gt; str:<br>    &quot;&quot;&quot;Read a text file inside the workspace.&quot;&quot;&quot;<br>    target = (WORKSPACE / path).resolve()<br>    if not str(target).startswith(str(WORKSPACE)):<br>        return &quot;ERROR: path escapes the workspace, denied.&quot;<br>    return target.read_text()[:8000]<br>def list_files() -&gt; str:<br>    &quot;&quot;&quot;List files in the workspace.&quot;&quot;&quot;<br>    return &quot;\n&quot;.join(p.name for p in WORKSPACE.iterdir())<br>def write_note(name: str, content: str) -&gt; str:<br>    &quot;&quot;&quot;Write a short note into the workspace.&quot;&quot;&quot;<br>    target = (WORKSPACE / name).resolve()<br>    if not str(target).startswith(str(WORKSPACE)):<br>        return &quot;ERROR: path escapes the workspace, denied.&quot;<br>    target.write_text(content[:4000])<br>    return f&quot;Wrote {name}.&quot;<br># Registry: name -&gt; (function, JSON schema shown to the model)<br>TOOLS = {<br>    &quot;read_file&quot;: (read_file, {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {&quot;path&quot;: {&quot;type&quot;: &quot;string&quot;}},<br>        &quot;required&quot;: [&quot;path&quot;],<br>    }),<br>    &quot;list_files&quot;: (list_files, {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {},<br>    }),<br>    &quot;write_note&quot;: (write_note, {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>            &quot;name&quot;: {&quot;type&quot;: &quot;string&quot;},<br>            &quot;content&quot;: {&quot;type&quot;: &quot;string&quot;},<br>        },<br>        &quot;required&quot;: [&quot;name&quot;, &quot;content&quot;],<br>    }),<br>}<br>def ollama_tool_defs():<br>    return [<br>        {<br>            &quot;type&quot;: &quot;function&quot;,<br>            &quot;function&quot;: {<br>                &quot;name&quot;: name,<br>                &quot;description&quot;: fn.__doc__,<br>                &quot;parameters&quot;: schema,<br>            },<br>        }<br>        for name, (fn, schema) in TOOLS.items()<br>    ]<br>def run_tool(name: str, args: dict) -&gt; str:<br>    &quot;&quot;&quot;Execute one tool call. Unknown tools are refused, never guessed.&quot;&quot;&quot;<br>    if name not in TOOLS:<br>        return f&quot;ERROR: unknown tool &#39;{name}&#39;. Available: {list(TOOLS)}.&quot;<br>    fn, _ = TOOLS[name]<br>    try:<br>        return str(fn(**args))<br>    except Exception as exc:  # noqa: BLE001 - report, don&#39;t crash the loop<br>        return f&quot;ERROR: tool &#39;{name}&#39; failed: {exc}&quot;<br># ---- The loop ----<br>SYSTEM_PROMPT = (<br>    &quot;You are a file assistant. You help the user by reading files in their &quot;<br>    &quot;workspace and writing short notes. Use the available tools when you need &quot;<br>    &quot;information instead of guessing. If a tool returns an ERROR, explain it &quot;<br>    &quot;and try a different approach. Keep answers short.&quot;<br>)<br>def run_agent(user_request: str) -&gt; str:<br>    messages = [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_request},<br>    ]<br>    for i in range(MAX_ITERATIONS):<br>        response = ollama.chat(<br>            model=MODEL, messages=messages, tools=ollama_tool_defs()<br>        )<br>        msg = response[&quot;message&quot;]<br>        messages.append(msg)<br>        tool_calls = msg.get(&quot;tool_calls&quot;) or []<br>        if not tool_calls:<br>            return msg[&quot;content&quot;]  # done: the model answered directly<br>        for call in tool_calls:<br>            name = call[&quot;function&quot;][&quot;name&quot;]<br>            args = call[&quot;function&quot;][&quot;arguments&quot;] or {}<br>            result = run_tool(name, args)<br>            print(f&quot;[iter {i+1}] tool={name} args={args}&quot;)<br>            messages.append(<br>                {&quot;role&quot;: &quot;tool&quot;, &quot;content&quot;: result, &quot;tool_name&quot;: name}<br>            )<br>    return (<br>        &quot;Stopped after reaching the iteration limit. &quot;<br>        &quot;Here is the conversation so far:\n&quot;<br>        + messages[-1].get(&quot;content&quot;, &quot;&quot;)<br>    )<br>if __name__ == &quot;__main__&quot;:<br>    print(run_agent(&quot;What files are in my workspace, and summarize notes.txt if it exists.&quot;))</pre><h3>What the code is doing</h3><p>The three tools are confined to a workspace directory. The path check resolves the target and refuses anything outside it. This five-line sandbox is the most important part of the file: an agent that reads and writes arbitrary paths is a footgun, and an agent confined to one directory is a useful assistant.</p><p>The registry pairs each function with a JSON schema, which is what the model sees. Keep descriptions short and imperative, parameters flat and few. Local models do noticeably better with simple schemas. If a tool needs complex input, split it into two tools.</p><p>run_tool is the trust boundary: unknown names are refused, argument errors return as tool results instead of crashing the loop. The loop itself is the ReAct pattern from Yao et al. (2022): reason, act, observe, repeat. Tool results append as role: &quot;tool&quot; messages. The iteration cap guarantees termination, and the print statement is your audit log.</p><p>Try it. Put a few text files in ~/agent-workspace and ask for something two-step, like &quot;read notes.txt and write a three-bullet summary to summary.txt&quot;. Watch the iteration log. That log is the agent thinking out loud, and reading it is the fastest way to build intuition for where agents succeed and fail.</p><h3>Where the AI Actually Is (and Is Not)</h3><p>It helps to separate which parts are AI and which are plain software, because conflating them is how agents get a reputation for magic or danger.</p><p>The AI parts: reasoning over the conversation (the only non-deterministic part), tool selection and argument generation (reliability tracks how clearly you wrote the tool descriptions), and the final answer.</p><p>The deterministic parts, most of the system: the loop (fixed code, cap, message order), tool execution (your Python functions), the sandbox (pure path logic), logging (every step recorded).</p><p>This separation makes the agent debuggable. Failures locate cleanly: bad tool description (your bug), bad argument (model’s bug, fixable with a clearer schema), bad tool implementation (your bug). “The AI did something weird” is rarely the whole story.</p><h3>Prompt design for small models</h3><p>Frontier models tolerate long system prompts. Local 8B models do not. Three rules:</p><ul><li>Describe the workflow, not the personality. “Use the available tools when you need information instead of guessing” beats three paragraphs about helpfulness.</li><li>Say what to do on error. “If a tool returns an ERROR, explain it and try a different approach” prevents the top failure mode: retrying the identical failing call.</li><li>Keep it short. Every prompt token repeats each iteration. Aim for under 100 words.</li></ul><p>Each iteration feeds the model the full history; it returns a final answer or structured tool calls. Internalize the limitation: the model has no memory between runs and knows your tools only through their descriptions. Ambiguous description, ambiguous arguments.</p><h3>Practical Example: The Log Triage Agent</h3><p>Say you run a small web service and want a nightly error-log summary. The cloud version sends the log to an API. The local version runs where the logs already live.</p><p>All numbers here are illustrative, invented to show the tradeoff shape, not measured benchmarks.</p><p>Setup: a read_file tool on the log directory, a write_note tool for the summary, and the prompt &quot;summarize errors by frequency, ignore routine warnings, under 200 words.&quot;</p><p>A typical night: a 400 KB log (illustrative). The agent reads it in one call, reasons, and writes a 150-word summary (illustrative). Total: two tool calls, three model calls (illustrative), about 90 seconds on a laptop (illustrative). Marginal cost: zero. The cloud equivalent is cents per night (illustrative), trivial until multiplied by every background job you will ever run.</p><p>Honest comparison: the frontier model writes the better summary. The local version reliably catches the obvious: error spikes, new error types, frequency counts. For a triage digest skimmed over coffee, that is the requirement. Match the model to the requirement, not the prestige of the task. And when a novel failure needs real diagnosis, the 8B model will summarize symptoms and miss the cause. Known weakness: the summary is a starting point, anomalies get human eyes.</p><h3>What to Watch</h3><p>Results, limitations, production notes, and next steps are really one question: how do you know the agent works, where does it break, and when do you outgrow it?</p><h3>Evaluate it honestly</h3><p>No benchmark table here: I ran no controlled experiment, and presenting one would be fabrication. Evaluate your own agent instead. Pick five representative tasks, run them, and score against a simple rubric (completed, correct tool sequence, no harmful actions). Five tasks teach more than any synthetic benchmark. Re-run them whenever you change the model or the prompt. That score is your baseline for every later decision, including the cloud question below.</p><h3>Failure modes, with mitigations</h3><ul><li>Tool-calling degradation. Small models emit malformed calls or plausible-but-wrong arguments. Mitigation: validate everything in run_tool, keep schemas flat, log failures.</li><li>Looping. The model repeats the same failing action. Mitigation: the iteration cap, plus a prompt line about trying a different approach on ERROR.</li><li>Context overflow. Tool results accumulate in history; a dozen large reads fills even a 128K window. Mitigation: truncate outputs (the [:8000] in the code), keep tasks scoped.</li><li>Prompt injection from local content. Your own files are untrusted input: a text file saying “ignore previous instructions” arrives as a tool result, and a naive agent may obey. Mitigation: no tools that act on instruction-like content without confirmation; destructive tools stay out of the registry.</li><li>Silent wrongness. The most dangerous failure is a confident wrong answer. Mitigation: the agent proposes, the human disposes. Read the log.</li><li>Hardware variance. Speed depends on memory and whether the model fits in VRAM. An 8B model on 8 GB of total RAM will be slow. Know your hardware before demoing.</li></ul><h3>When to go hybrid</h3><p>Some tasks truly need a frontier model: ambiguous multi-step reasoning, long plans, or answer quality that affects other people. Run those in the cloud and keep the rest local. Hybrid is the correct architecture for most people, not a compromise. Your five-task score tells you which tasks belong where: anything the local model fails repeatedly is a cloud candidate, everything else stays free.</p><h3>Conclusion</h3><p>An agent is a loop, not a model. The loop reasons, acts, and observes. The model is one component inside it, and for many useful tasks a local open model is sufficient. Everything that makes agents powerful (tools, iteration, guardrails) and everything that makes them safe (validation, sandboxing, logging) lives in code you write yourself. That code runs anywhere, including the laptop you own. Build the loop first. Upgrade the model only when the loop proves it needs one.</p><h3>FAQ</h3><p><strong>Do I need a GPU?</strong><br> No. An 8B model at 4-bit quantization runs on CPU and well on Apple Silicon’s unified memory. A GPU helps speed, but the requirement is simply enough total memory for the model to fit.</p><p><strong>Which model should I start with?</strong><br> Llama 3.1 8B through Ollama, for its documented tool-calling support. If it struggles, try Qwen2.5 or Mistral 7B before a larger model. Change one variable at a time.</p><p><strong>Can the agent browse the web?</strong><br> Not in this code, deliberately. Web access is the highest-risk tool: every page becomes potential prompt injection. If you need it, add a text-only fetch tool and log every URL.</p><p><strong>How is this different from a local chatbot?</strong><br> A chatbot answers from its weights. This agent answers from your files, through tools, in a loop. The difference is action: reading, summarizing, and writing, chained toward a goal without you in the middle.</p><p><strong>When should I go back to the cloud?</strong><br> When your five-task evaluation shows the local model failing at real needs: ambiguous multi-step reasoning, long plans, or quality that affects other people. Keep the local agent for the rest.</p><p><strong>Is my data really private?</strong><br> In the meaningful sense, yes: nothing leaves your machine, because the only network call is to your local Ollama server. Remaining risks are the ones you already had: your machine’s security and what you put in the workspace.</p><h3>Build Checklist</h3><ul><li>Ollama installed and llama3.1:8b pulled</li><li>pip install ollama in a fresh virtual environment</li><li>Scratch workspace directory created with a few test files</li><li>Script runs end to end on a two-step task</li><li>Iteration log reviewed and understood</li><li>One real tool added for your own use case</li><li>System prompt shortened twice, tool calls compared</li><li>Prompt-injection test performed with a hostile text file</li><li>Five-task evaluation scored honestly</li><li>Model version and digest recorded in setup notes</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=591a1a7958e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 63% Rule: Designing Agents Humans Actually Trust With Autonomy]]></title>
            <link>https://medium.com/@atnoforgenai/the-63-rule-designing-agents-humans-actually-trust-with-autonomy-01cdfe3f3ac9?source=rss-36b5ad2df1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/01cdfe3f3ac9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[ATNO for GenAI & Agentic AI]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 08:57:48 GMT</pubDate>
            <atom:updated>2026-10-07T08:57:48.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XQqgLMmPJqBd_FEK6-JSQ.jpeg" /></figure><h4>The problem nobody wants to name</h4><p>Ask a team running an AI agent in production what percentage of its actions execute without a human in the loop. Most cannot answer. They track latency, token spend, task success. But the number that decides whether the project survives, the autonomy rate, goes unmeasured.</p><p>Then the arc plays out the way it always does. The demo is magic. The pilot is promising. The agent gets real tools and real consequences, and within weeks someone asks the question that kills the project: “Can we have it ask before doing that?”</p><p>Then it asks before doing everything. The agent becomes a chatbot with extra steps, the team stops using it, and the project quietly dies. Your agent does not have a trust problem. It has an autonomy calibration problem.</p><p>The industry’s default answer is “human in the loop,” which usually means a human rubber-stamping every action until they stop reading and click approve on muscle memory. That is not safety. That is liability with extra latency.</p><p>What actually works is calibrated autonomy: a deliberate split between what the agent does alone and what it escalates, with the split itself treated as a metric you manage.</p><p><strong>TL;DR</strong></p><ul><li>Most agent projects die from autonomy miscalibration, not capability gaps: too much freedom causes an incident, too little turns the agent into a chatbot.</li><li>The 63% Rule: aim for roughly 60 to 65% of actions executing without human confirmation. Gate the rest by reversibility and blast radius. Block the dangerous few entirely.</li><li>Implement it as deterministic policy code, not prompts. Measure autonomy rate and override rate weekly. Widen autonomy only on evidence.</li></ul><h3>The 63% Rule, stated plainly</h3><p>The 63% Rule is a practitioner’s heuristic, not a peer-reviewed finding. The number is deliberately specific and deliberately unofficial. Nothing in this article depends on the number being exactly right.</p><p>It goes like this: <strong>in a healthy production deployment, roughly 60 to 65 percent of an agent’s actions should execute without human confirmation.</strong> The rest get escalated, gated, or blocked. If your autonomy rate is much higher, you are almost certainly under-gated and one bad afternoon away from an incident. If it is much lower, you have built an expensive suggestion engine and your operators will route around it.</p><p>Why 63 and not 50 or 80? Because the natural shape of real work is that about two thirds of actions are routine, reversible, and low blast radius: lookups, drafts, reschedules, summaries. The remaining third is where the risk lives: money moving, permissions changing, messages sent externally, state deleted. The rule just names the split that reality keeps producing. (If 63% reminds you of 1 minus 1/e, that is a coincidence, not a derivation.)</p><p>The point of the number is not precision. The point is that <strong>autonomy rate is a metric you should be measuring and managing</strong>, with a target band, the same way you manage latency or error budgets. Most teams cannot tell you their agent’s autonomy rate. That is the actual problem. Trust is not a feeling. It is a metric with a target band.</p><h3>What calibrated autonomy actually does</h3><p>Calibrated autonomy runs every proposed action through a risk gate before execution. The gate answers three questions:</p><ul><li><strong>Is this action reversible?</strong> A draft can be discarded. A sent email cannot be unsent. A refund can be re-charged, awkwardly. A deleted database only comes back from a restore.</li><li><strong>What is the blast radius?</strong> One record versus ten thousand. Internal versus customer-facing. Read versus write.</li><li><strong>How confident are we in the classification?</strong> The gate itself can be wrong, so high-stakes actions need deterministic rules, not vibes.</li></ul><p>Based on those answers, each action lands in one of three tiers:</p><ul><li><strong>Auto (the 63%)</strong>: executes immediately, fully logged. Read-only operations, drafts, notifications, reschedules, anything reversible with narrow blast radius.</li><li><strong>Gated (most of the 37%)</strong>: pauses for human approval with full context. Money movement above a threshold, external communication, permission changes, bulk operations.</li><li><strong>Blocked</strong>: never executes via the agent, no matter what. Credential rotation, data deletion beyond soft-delete, legal or compliance attestations. These stay human-only by policy, not by prompt.</li></ul><p>The critical insight: the tiers are not fixed. They are the output of a policy you version and adjust based on measured override rates. When humans approve 98% of gated sub-$50 refunds for weeks, that boundary is wrong and you move it. The 63% is a starting target, not a permanent address.</p><h3>Architecture: the autonomy gate</h3><p>The pipeline every production agent needs, whatever you build it with:</p><pre>User request / trigger<br>        |<br>        v<br>+------------------+<br>|  Planner (LLM)   |  proposes a plan: sequence of tool calls<br>+------------------+<br>        |<br>        v<br>+------------------+<br>| Action classifier|  deterministic rules first, model judgment<br>| (risk scoring)   |  only for the ambiguous remainder<br>+------------------+<br>        |<br>        v<br>+------------------+<br>|   Policy gate    |  OPA-style rules: allow / gate / block<br>|  (deterministic)|  versioned, audited, tested in CI<br>+------------------+<br>        |<br>   +----+----+------------------+<br>   |         |                  |<br>   v         v                  v<br> AUTO      GATED              BLOCKED<br> executes  interrupt:         rejected,<br> logs      human approves      logged with<br>           or rejects          reason<br>   |         |<br>   v         v<br>+------------------+<br>|  Audit log +     |  every action, decision, latency,<br>|  trace (OTel)    |  override, and outcome recorded<br>+------------------+<br>        |<br>        v<br>+------------------+<br>| Autonomy metrics |  autonomy rate, override rate,<br>| dashboard        |  escalation precision, incidents<br>+------------------+</pre><p>Two design decisions matter most here.</p><p><strong>First, the policy gate is deterministic code, not a prompt.</strong> Prompts are for judgment; policy is for guarantees. “Refunds over $500 require approval” should be a rule evaluated by code, the same way your API gateway enforces auth. If your safety boundary lives inside a system prompt, you do not have a safety boundary. You have a suggestion.</p><p><strong>Second, the classifier may say “I don’t know,” and that routes to Gated.</strong> Most incidents come from confident misclassifications, not known risks. An explicit low-confidence path converts unknown unknowns into human decisions.</p><h3>Implementation</h3><p>Let us make this concrete. The scenario: a support-ops agent for an e-commerce company with a handful of tools. Everything below is real, runnable Python using Pydantic for validation and LangGraph’s human-in-the-loop primitives for escalation.</p><h3>Step 1: Classify actions with Pydantic, not vibes</h3><pre>from enum import Enum<br>from pydantic import BaseModel, Field<br>class RiskTier(str, Enum):<br>    AUTO = &quot;auto&quot;        # executes immediately<br>    GATED = &quot;gated&quot;      # needs human approval<br>    BLOCKED = &quot;blocked&quot;  # never via agent<br>class AgentAction(BaseModel):<br>    name: str<br>    args: dict = Field(default_factory=dict)<br>    # &quot;reversible&quot; | &quot;partially&quot; | &quot;irreversible&quot;<br>    reversibility: str<br>    # &quot;single&quot; | &quot;bulk&quot; | &quot;external&quot;<br>    blast_radius: str<br># Deterministic policy table. Version this. Review it monthly.<br># This is the actual safety boundary, keep it out of prompts.<br>POLICY = {<br>    # (tool, condition) -&gt; tier<br>    (&quot;lookup_order&quot;, None): RiskTier.AUTO,<br>    (&quot;draft_reply&quot;, None): RiskTier.AUTO,<br>    (&quot;reschedule_delivery&quot;, None): RiskTier.AUTO,<br>    (&quot;issue_refund&quot;, &quot;amount &lt;= 50&quot;): RiskTier.AUTO,<br>    (&quot;issue_refund&quot;, &quot;amount &gt; 50&quot;): RiskTier.GATED,<br>    (&quot;send_customer_email&quot;, None): RiskTier.GATED,<br>    (&quot;ban_account&quot;, None): RiskTier.BLOCKED,<br>    (&quot;delete_order_history&quot;, None): RiskTier.BLOCKED,<br>}<br>def classify(action: AgentAction) -&gt; RiskTier:<br>    &quot;&quot;&quot;Deterministic classification. No LLM involved.&quot;&quot;&quot;<br>    key = (action.name, None)<br>    if action.name == &quot;issue_refund&quot;:<br>        amount = action.args.get(&quot;amount_usd&quot;, 0)<br>        if amount &lt;= 50:<br>            key = (action.name, &quot;amount &lt;= 50&quot;)<br>        else:<br>            key = (action.name, &quot;amount &gt; 50&quot;)<br>    tier = POLICY.get(key)<br>    if tier is None:<br>        # Unknown action: escalate, never auto-run.<br>        return RiskTier.GATED<br>    # Defense in depth: irreversible + external is never AUTO,<br>    # even if the table says so. Guards against misconfiguration.<br>    risky = (action.reversibility == &quot;irreversible&quot;<br>             and action.blast_radius == &quot;external&quot;)<br>    if risky and tier == RiskTier.AUTO:<br>        return RiskTier.GATED<br>    return tier</pre><p>Two properties make this production-grade: unknown actions default to Gated, never Auto, and a defense-in-depth override stops a misconfigured table from auto-approving anything irreversible and external. Design as if your policy table already has bugs.</p><h3>Step 2: Gate execution with a real human-in-the-loop interrupt</h3><p>LangGraph ships a first-class human-in-the-loop primitive: interrupt(), which pauses graph execution mid-node and resumes when a human responds. This is the correct mechanism for the Gated tier, far better than &quot;the agent asks in chat and hopes.&quot;</p><pre>from langgraph.graph import StateGraph, START, END<br>from langgraph.types import interrupt, Command<br>from langgraph.checkpoint import MemorySaver<br>from typing import TypedDict<br><br><br>class AgentState(TypedDict):<br>    # the proposed AgentAction, as a dict<br>    action: dict<br>    approved: bool<br>    result: dict<br><br><br>def policy_gate(state: AgentState) -&gt; dict:<br>    action = AgentAction(**state[&quot;action&quot;])<br>    tier = classify(action)<br><br>    if tier == RiskTier.BLOCKED:<br>        reason = f&quot;{action.name} is blocked by policy&quot;<br>        result = {&quot;status&quot;: &quot;blocked&quot;, &quot;reason&quot;: reason}<br>        return {&quot;approved&quot;: False, &quot;result&quot;: result}<br><br>    if tier == RiskTier.GATED:<br>        # Execution PAUSES here. A human reviews the full<br>        # action context, then replies approve or reject.<br>        decision = interrupt({<br>            &quot;question&quot;: f&quot;Approve {action.name}?&quot;,<br>            &quot;action&quot;: action.model_dump(),<br>            &quot;tier&quot;: &quot;gated&quot;,<br>        })<br>        approved = decision.get(&quot;verdict&quot;) == &quot;approve&quot;<br>        note = decision.get(&quot;note&quot;, &quot;&quot;)<br>        result = {&quot;reviewer_note&quot;: note}<br>        return {&quot;approved&quot;: approved, &quot;result&quot;: result}<br><br>    # AUTO tier: no pause, executes immediately.<br>    return {&quot;approved&quot;: True}<br><br><br>def execute(state: AgentState) -&gt; dict:<br>    if not state[&quot;approved&quot;]:<br>        result = {**state[&quot;result&quot;], &quot;executed&quot;: False}<br>        return {&quot;result&quot;: result}<br>    # Call the real tool here.<br>    # Always use idempotency keys and timeouts.<br>    tool_name = state[&quot;action&quot;][&quot;name&quot;]<br>    result = {&quot;executed&quot;: True, &quot;tool&quot;: tool_name}<br>    return {&quot;result&quot;: result}<br><br><br>graph = StateGraph(AgentState)<br>graph.add_node(&quot;policy_gate&quot;, policy_gate)<br>graph.add_node(&quot;execute&quot;, execute)<br>graph.add_edge(START, &quot;policy_gate&quot;)<br>graph.add_edge(&quot;policy_gate&quot;, &quot;execute&quot;)<br>graph.add_edge(&quot;execute&quot;, END)<br>app = graph.compile(checkpointer=MemorySaver())<br><br># Resuming after a human decision:<br># resume = {&quot;verdict&quot;: &quot;approve&quot;, &quot;note&quot;: &quot;verified&quot;}<br># cfg = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;abc123&quot;}}<br># app.invoke(Command(resume=resume), config=cfg)</pre><p>The interrupt carries full action context to the reviewer, and the pause is durable. If the reviewer goes to lunch, the action waits. Compare that to the anti-pattern where the agent “asks” in the chat transcript and proceeds on a timeout. Timeouts are how incidents happen.</p><h3>Step 3: Measure the autonomy rate</h3><p>You cannot manage what you do not measure. Every action, gate decision, and human override goes to the audit log, and a small job computes the metrics that actually run the system:</p><pre>def autonomy_report(actions: list[dict]) -&gt; dict:<br>    &quot;&quot;&quot;Build from audit log entries.<br><br>    Each entry has: tier (&quot;auto&quot; / &quot;gated&quot; / &quot;blocked&quot;)<br>    and human_overridden (bool).<br>    &quot;&quot;&quot;<br>    total = len(actions)<br>    auto = sum(1 for a in actions if a[&quot;tier&quot;] == &quot;auto&quot;)<br>    gated = sum(1 for a in actions if a[&quot;tier&quot;] == &quot;gated&quot;)<br>    overrides = sum(1 for a in actions<br>                    if a.get(&quot;human_overridden&quot;))<br><br>    # Target band for autonomy_rate: 0.60 to 0.65.<br>    autonomy_rate = round(auto / total, 3)<br>    gated_rate = round(gated / total, 3)<br>    override_rate = round(overrides / max(gated, 1), 3)<br><br>    # How to read override_rate (illustrative, tune it):<br>    #   below 0.05 -&gt; boundary too conservative, widen AUTO<br>    #   above 0.25 -&gt; gate catches real mistakes, do NOT widen<br>    return {<br>        &quot;autonomy_rate&quot;: autonomy_rate,<br>        &quot;gated_rate&quot;: gated_rate,<br>        &quot;override_rate&quot;: override_rate,<br>    }</pre><p>The override rate is the most important number in production agent operations. A gate nobody ever overrides is either perfect or, far more likely, being rubber-stamped. Tune the policy table against this number monthly.</p><h3>Where the AI actually goes (and where it does not)</h3><p>A common mistake is putting the LLM in charge of the safety decision. Here is the correct division of labor:</p><p><strong>Deterministic code handles:</strong> tier classification for known actions, threshold checks, allowlists and blocklists, idempotency, timeouts, retries, audit logging. These are guarantees, and guarantees do not come from next-token prediction.</p><p><strong>The LLM handles:</strong> planning (which actions to propose), drafting content for human review, summarizing context for the approver, and classifying novel actions with an explicit confidence score. Anything below your confidence threshold routes to Gated automatically.</p><p><strong>The human handles:</strong> approving gated actions, reviewing policy, investigating overrides. Notice what the human does not do: read every auto-tier action. That is the 63% paying off. Human attention is the scarcest resource in the system; spend it where the risk is.</p><p>The model’s input is the proposed action plus context; its output is a proposed tier with a confidence score and one-line rationale for the reviewer. Model confidence is not calibrated probability. Treat it as a triage signal, never a safety guarantee; the deterministic rules are the guarantee.</p><h3>Practical example: the support-ops agent, week one versus week eight</h3><p>Consider the support agent above, handling roughly 1,000 actions per week. <strong>All numbers below are illustrative, not measured results.</strong> They show the shape of a healthy calibration curve, not a benchmark.</p><p><strong>Week one (conservative start):</strong></p><ul><li>Autonomy rate: 41%. Everything ambiguous starts Gated.</li><li>Gated actions: 590, humans approved 96%.</li><li>Override rate: 4%. The gate is catching almost nothing, so it is too tight.</li><li>Operator feedback: “I am just clicking approve all day.”</li></ul><p><strong>The calibration move:</strong> refunds under $50 move from Gated to Auto. Policy table gets a version bump and changelog entry.</p><p><strong>Week eight (calibrated):</strong></p><ul><li>Autonomy rate: 63%. Lookups, sub-$50 refunds, reschedules, and drafts run free.</li><li>Gated actions: 340 per week, mostly larger refunds and outbound emails.</li><li>Override rate: 11%. The gate now catches real mistakes at a meaningful rate.</li><li>Incidents: zero customer-facing errors from auto-tier actions.</li><li>Approval time down roughly 60%, and reviewers report actually reading gated items again.</li></ul><p>That last point is the one nobody talks about. <strong>Approval fatigue is a safety vulnerability.</strong> A human asked to approve 600 near-identical actions a week stops reading them by Wednesday. Fewer, better-targeted interruptions produce better human decisions on the ones that remain. The 37% exists to protect the quality of human judgment, not just to catch agent mistakes.</p><h3>Results and evaluation: what to actually measure</h3><p>Forget “task success rate.” For autonomy calibration, the metrics that matter are:</p><ul><li><strong>Autonomy rate</strong>: fraction of actions executing without human confirmation. Target band 0.60 to 0.65 for most deployments. Below 0.5, you have a chatbot. Above 0.8, you have an incident waiting for a trigger.</li><li><strong>Override rate</strong>: fraction of gated actions the human rejects or modifies. Healthy range is roughly 0.05 to 0.25. Below that, widen autonomy. Above that, hold or tighten.</li><li><strong>Escalation precision</strong>: of escalated actions, how many actually needed a human? Low precision means a noisy classifier and reviewers who stop trusting the queue.</li><li><strong>Time-to-decision on gated actions</strong>: p50 and p95. If p95 approval latency is 4 hours, your “real-time” agent is a batch process.</li><li><strong>Incident rate per 1,000 auto-tier actions</strong>: the number that justifies the entire apparatus. Any upward trend means the Auto tier boundary is wrong.</li></ul><p>Run these as a weekly report and a monthly policy review. The moment you treat the autonomy split as “configured once,” you have stopped operating the system.</p><h3>Limitations and failure modes</h3><p>This framework fails in specific, predictable ways. Know them first.</p><p><strong>The classifier is the new attack surface.</strong> Prompt injection only needs to make a dangerous action look low-risk. Mitigation: classify on structured action schemas (tool name, typed args), never on natural-language descriptions, and treat tool outputs as untrusted data, always.</p><p><strong>Distributional shift eats static policies.</strong> The table that was correct in March is wrong in June. Calendar a monthly review and trigger an automatic one whenever a new tool is registered or an incident occurs.</p><p><strong>The 63% is a heuristic, and heuristics have jurisdictions.</strong> A support agent and a production-database agent should not share a target band. For irreversible, regulated, or safety-critical domains, start far lower, think 20 to 30%, and earn upward slowly. The rule tells you to manage the number, not what the number must be.</p><p><strong>Humans habituate.</strong> Rubber-stamping is the failure mode of every approval queue. Countermeasures that work: show reviewers the rationale and blast radius, not just an approve button; rotate reviewers; sample auto-tier actions for retroactive review.</p><p><strong>Correlated failures.</strong> A systematic blind spot misclassifies the same way a thousand times before anyone notices. That is why the audit log and incident-rate metric exist: the metrics are the second gate.</p><h3>Production considerations</h3><p>A few things that separate a demo of this architecture from a production deployment of it:</p><ul><li><strong>Observability</strong>: trace every action with OpenTelemetry, plus LangSmith or Langfuse for planning traces. At 2 AM you need the full chain: what the agent saw, proposed, what the gate decided, who approved it.</li><li><strong>Policy as code</strong>: the policy table lives in version control, changes go through review, and tests assert that known-dangerous actions classify as Blocked. If you cannot write a test for your safety boundary, you do not have one.</li><li><strong>Kill switches and rate limits</strong>: a global kill switch that drops everything to manual, per-tool rate limits, and circuit breakers that auto-tighten policy when incident rate spikes. The system must fail toward less autonomy, never more.</li><li><strong>Idempotency</strong>: every mutating tool call carries an idempotency key. Retries after a gate timeout must not double-execute. Unglamorous and non-negotiable.</li><li><strong>Secrets and PII</strong>: tools run under least-privilege credentials, PII is redacted from traces by default, and the review UI shows only the minimum context needed.</li><li><strong>Red-teaming</strong>: before raising autonomy, adversarially test the classifier with prompt-injected tool outputs. The gate eval suite (Ragas, DeepEval, or hand-rolled) runs in CI, not in a one-off notebook.</li><li><strong>Incident runbooks</strong>: decide in advance what happens when an auto-tier action causes harm: who gets paged, how it is reversed, how the policy gets patched. The first incident is not the time to design this.</li></ul><h3>Practical recommendations</h3><p>If you are building or operating an agent, here is the sequence:</p><ol><li><strong>Inventory every tool</strong> the agent can call and label each with reversibility and blast radius. This takes an afternoon and is the highest-value exercise in this article.</li><li><strong>Write the policy table</strong> as code, with tests, before the agent ships. Start conservative: when in doubt, Gate it.</li><li><strong>Ship with full audit logging</strong> from day one. You cannot calibrate later what you did not record now.</li><li><strong>Measure autonomy rate and override rate weekly.</strong> Set the target band (start at 0.60 to 0.65 unless your domain says otherwise) and review monthly.</li><li><strong>Widen autonomy only on evidence</strong>: sustained low override rates, zero incidents, reviewers confirming the gated queue still gets real attention.</li><li><strong>Never let the model set policy.</strong> It proposes, classifies with confidence, and drafts. Deterministic code decides.</li><li><strong>Run a monthly policy review</strong> with the incident log open. The split is a living configuration, not a launch setting.</li></ol><h3>Conclusion</h3><p>The agents that earn trust are not the most capable ones. They are the ones whose operators can say, at any moment, exactly what the agent may do alone, what it must ask about, and what it can never touch, and show the numbers proving the split works.</p><p>The 63% Rule is a memorable way to say: manage autonomy like a metric, gate on reversibility and blast radius, keep policy in deterministic code, and spend human attention where the risk lives. Do that, and your agent keeps its autonomy. Skip it, and you get the demo, the pilot, and then the meeting where someone asks if it can just ask before doing that.</p><h3>FAQ</h3><p><strong>Is 63% a real measured number?</strong><br> No. It is a practitioner’s heuristic: roughly two thirds of actions autonomous, one third gated or blocked. Treat it as a starting target band to calibrate from, not a law.</p><p><strong>Does this apply to coding agents?</strong><br> Yes: Auto for test runs, linting, and local edits; Gated for pushes, merges, and deployments; Blocked for production database writes and secret rotation.</p><p><strong>What about fully autonomous agents with no humans?</strong><br> Then you have implicitly set autonomy to 100% with no calibration signal at all. At minimum, keep the audit log and the incident-rate metric. You are flying without instruments otherwise.</p><p><strong>Which framework should I use?</strong><br> The pattern is framework-agnostic. LangGraph’s interrupt() is the cleanest human-in-the-loop primitive I have used; Temporal is excellent for durable execution; a hand-rolled gate with Pydantic and a review queue is perfectly respectable for v1. Pick the one your team will actually operate.</p><h3>Build checklist</h3><ul><li>Tool inventory with reversibility and blast radius labels</li><li>Policy table as versioned code, with tests for Blocked actions</li><li>Deterministic classifier with unknown-defaults-to-Gated</li><li>Human approval UI showing full action context, rationale, and blast radius</li><li>Durable interrupts (no timeout-proceeds)</li><li>Full audit log: proposed action, tier, decision, latency, outcome</li><li>Weekly autonomy rate and override rate report</li><li>Monthly policy review cadence</li><li>Kill switch, rate limits, circuit breakers</li><li>Idempotency keys on all mutating tools</li><li>Red-team eval suite for the classifier, running in CI</li><li>Incident runbook with reversal procedures</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01cdfe3f3ac9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent Skills, Explained: The Layer Between Prompts and Tools]]></title>
            <link>https://medium.com/@atnoforgenai/agent-skills-explained-the-layer-between-prompts-and-tools-b896bf4349b2?source=rss-36b5ad2df1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b896bf4349b2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[ATNO for GenAI & Agentic AI]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 17:43:19 GMT</pubDate>
            <atom:updated>2026-10-04T18:11:31.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOB09RzOzsNjNkFtmZnvWQ.jpeg" /></figure><p><em>Your agent can call every API you own and still do the job wrong. The missing piece is not more tools. It is packaged know-how.</em></p><p>Here is a situation most agent teams have lived through.</p><p>You connect your coding agent to a handful of MCP servers: GitHub, your ticketing system, your cloud provider, your database. The agent can now reach everything. Then you ask it to run your incident runbook, and it does something plausible, fast, and wrong. It called the right tools in the wrong order, skipped the approval step your team always does, and wrote the customer-facing update in a tone your support lead would never approve.</p><p>The failure was not access. The agent had access. The failure was procedure.</p><p>Teams respond to this in two ways, and both are bad. The first is prompt sprawl: paste the refund policy, the incident runbook, the PDF handling steps, and the brand rules into the system prompt. The session starts with a wall of text, the context window fills before the real work begins, and nobody ever deletes a paragraph because it might matter later. The second is the wiki graveyard: procedures live in Notion, a private repo, or a Slack bookmark, while the agent gets bare tools. It can call create_refund but has no idea about your approval sequence, your exceptions, or your wording.</p><p>The common assumption is that capability scales with tool count. Give the model more tools and it gets more useful. The practical reality, visible in every production postmortem, is that tools without procedures produce confident wrongness at machine speed. What agents lack is not reach. It is repeatable, versioned, load-on-demand know-how.</p><p>That is the layer Agent Skills occupies.</p><h3>What a Skill Actually Is</h3><p>Strip away the announcements and a skill is almost aggressively simple: a folder containing a SKILL.md file.</p><pre>pdf-form-fill/<br>├── SKILL.md        # Required: YAML frontmatter + Markdown instructions<br>├── scripts/        # Optional: executable code (e.g. fill_form.py)<br>├── references/     # Optional: docs loaded only when needed<br>└── assets/         # Optional: templates, fonts, images</pre><p>The SKILL.md file has YAML frontmatter at the top (at minimum name and description) and Markdown instructions below. The recommendation is to keep the body under roughly 500 lines and push everything else into sub-files that load only when referenced.</p><p>A minimal example:</p><pre>---<br>name: pdf-form-fill<br>description: Fill PDF form fields from structured JSON data. Use when the<br>  user asks to complete, populate, or extract data from PDF forms.<br>allowed-tools: Bash(python3 scripts/*)<br>---</pre><pre># PDF Form Fill<br>## When to use this skill<br>Activate when the request involves reading or writing PDF form fields.<br>Do not use for general PDF text extraction; that is a different task.<br>## Procedure<br>1. Inspect the form&#39;s field names first. Run:<br>   `python3 scripts/list_fields.py &lt;file.pdf&gt;`<br>   and read the field names from the output. Never guess field names.<br>2. Map the user&#39;s data to the discovered field names. If a field has no<br>   matching data, leave it blank and report it. Do not invent values.<br>3. Write the filled PDF with `python3 scripts/fill_form.py`, then verify<br>   by re-listing fields on the output file.<br>## Reference<br>Detailed field-type handling (checkboxes, radio groups, signatures) lives in<br>`references/forms.md`. Load it only when the form contains those field types.</pre><p>Three things to notice.</p><p>First, the description is written for retrieval, not for humans. It says what the skill does and when to use it, because that text is what the agent scans when deciding relevance.</p><p>Second, deterministic work is pushed into scripts. The model never needs the source of fill_form.py in context; only the script&#39;s output enters the conversation.</p><p>Third, the reference file is explicitly gated behind a condition. That gating is the whole game.</p><h3>The Architecture: Progressive Disclosure</h3><p>Skills work because of one mechanic: progressive disclosure. Instead of loading everything up front, the agent loads information in three levels.</p><pre>Level 1: METADATA (always loaded)<br>┌─────────────────────────────────────────────┐<br>│ name + description of every installed skill │<br>│ Cost: ~100 tokens per skill                 │<br>│ 30 skills = ~3,000 tokens at rest           │<br>└──────────────────────┬──────────────────────┘<br>                       │ task matches a description<br>                       ▼<br>Level 2: INSTRUCTIONS (loaded on trigger)<br>┌─────────────────────────────────────────────┐<br>│ Full SKILL.md body enters context           │<br>│ The agent now has the procedure             │<br>└──────────────────────┬──────────────────────┘<br>                       │ instruction references a file or script<br>                       ▼<br>Level 3: RESOURCES (loaded on demand)<br>┌─────────────────────────────────────────────┐<br>│ references/*.md, scripts/*, assets/*        │<br>│ Script output enters context, not the code  │<br>└─────────────────────────────────────────────┘</pre><p><strong>Level 1, discovery.</strong> At startup, the agent loads only each skill’s name and description. Per the specification, each skill costs roughly 100 tokens here. Thirty installed skills cost roughly 3,000 tokens at rest. That number matters when you compare it against the alternative.</p><p><strong>Level 2, activation.</strong> When the model judges a task relevant to a skill’s description, it reads the full SKILL.md into context. The description is doing real work here: vague descriptions cause missed triggers and false triggers alike, which is why description quality is the highest-leverage authoring decision.</p><p><strong>Level 3, execution.</strong> The agent follows the instructions, loading referenced files and running bundled scripts only as the procedure demands. The SKILL.md stays lean, edge cases live in a separate file loaded only when needed, and scripts execute deterministically. The script&#39;s code never enters the model&#39;s context. Only its output does.</p><p>This is why skills scale where prompt sprawl does not. Your agent’s effective knowledge base can be enormous, hundreds of pages of procedures across dozens of skills, while the per-session token cost stays near zero until a skill is actually used.</p><h3>Skills vs MCP vs Prompts vs Subagents</h3><p>The confusion is understandable because all four extend what an agent can do. They are not interchangeable, and mixing them up leads to architecture decisions you regret in six months.</p><p><strong>System prompt.</strong> Provides always-on instructions. Context cost is paid every session. Best for identity, global rules, and safety policies.</p><p><strong>MCP tools.</strong> Provide live access to external systems. Full tool schemas load eagerly, which is where context bloat comes from. Best for databases, APIs, and SaaS behind auth.</p><p><strong>Subagent.</strong> Provides delegated autonomous work in a nested reasoning loop with its own model calls and context. Best for long independent subtasks.</p><p><strong>Skill.</strong> Provides packaged know-how. Costs about 100 tokens until triggered. Versioned as a folder in git. Best for repeatable procedures.</p><p>The short version practitioners use: MCP gives the model the ability to do things. Skills teach it how to do them well.</p><p>MCP connects the agent to a ticketing system. A skill tells it your team’s triage procedure, which fields are mandatory, and what the customer-facing reply template looks like. They compose directly: a skill can instruct the agent which MCP tools to call, in what order, and with which checks.</p><p>Two distinctions worth sharpening further.</p><p>Against prompts: a prompt is always loaded and always costs context. A skill is loaded conditionally. If you find yourself writing “only do X when the user asks about Y” in a system prompt, that conditional logic belongs in a skill description and body instead.</p><p>Against subagents: a subagent is a nested reasoning loop with its own model calls and context. A skill is instructions that run in the parent’s context. Do not pay for a nested loop when a procedure will do.</p><p>The context economics deserve a concrete number. Connect several MCP servers and every server eagerly loads every tool’s full JSON Schema. GitHub’s official server became well known for consuming tens of thousands of tokens before the first user message. Skills cost their description until used. The MCP roadmap itself lists a formal Skills primitive as active 2026 work, which tells you where the ecosystem thinks this converges.</p><h3>Where the Skill Files Live</h3><p>Skill discovery is directory-based, and the folder name must match the name field in the frontmatter. The conventions per client documentation:</p><ul><li><strong>Claude Code:</strong> personal skills in ~/.claude/skills/, project skills in .claude/skills/</li><li><strong>GitHub Copilot (VS Code):</strong> project skills in .github/skills/, .claude/skills/, or .agents/skills/; personal in ~/.copilot/skills/ or ~/.agents/skills/</li><li><strong>OpenAI Codex:</strong> .agents/skills/ from the current directory up to the repo root, plus ~/.agents/skills/ for personal skills</li></ul><p>The format was originally developed by Anthropic and released as an open standard at agentskills.io. The example skill library at github.com/anthropics/skills is the best place to see the conventions in practice. Because skills are just folders in git, they get versioning, code review, and rollback for free, which is more than can be said for most prompt engineering.</p><h3>Implementation: What a Skill Loader Actually Does</h3><p>Here is a minimal Python sketch of what a skill-capable harness does under the hood:</p><pre>import re<br>from pathlib import Path<br>def load_skill_index(skills_dir: Path) -&gt; list[dict]:<br>    &quot;&quot;&quot;Level 1: load only name + description of every skill.&quot;&quot;&quot;<br>    index = []<br>    for skill_md in skills_dir.glob(&quot;*/SKILL.md&quot;):<br>        text = skill_md.read_text()<br>        frontmatter = text.split(&quot;---&quot;)[1]<br>        name = re.search(r&quot;^name:\s*(.+)$&quot;, frontmatter, re.M).group(1)<br>        desc = re.search(r&quot;^description:\s*(.+)$&quot;, frontmatter,<br>                         re.M | re.S).group(1)<br>        assert skill_md.parent.name == name.strip()<br>        index.append({<br>            &quot;name&quot;: name.strip(),<br>            &quot;description&quot;: &quot; &quot;.join(desc.split()),<br>            &quot;path&quot;: skill_md<br>        })<br>    return index<br>def render_discovery_block(index: list[dict]) -&gt; str:<br>    &quot;&quot;&quot;The ~100-tokens-per-skill block injected at session start.&quot;&quot;&quot;<br>    lines = [&quot;Available skills (invoke by name when the task matches):&quot;]<br>    for s in index:<br>        lines.append(f&quot;- {s[&#39;name&#39;]}: {s[&#39;description&#39;]}&quot;)<br>    return &quot;\n&quot;.join(lines)<br>def activate_skill(skill: dict) -&gt; str:<br>    &quot;&quot;&quot;Level 2: read the full SKILL.md into context on trigger.&quot;&quot;&quot;<br>    return skill[&quot;path&quot;].read_text()</pre><p>The important design decisions are visible even in this sketch. Discovery is a pure function over frontmatter; nothing else is read. Activation is lazy and total: when the model decides a skill matches, the whole SKILL.md enters context at once. Level 3, loading references/ files and executing scripts, happens only when the instructions say so.</p><p>In a real harness, the trigger decision is made by the model itself reading the discovery block, which is why description wording dominates skill quality.</p><h3>Where Reasoning Ends and Determinism Starts</h3><p>A skill is a hybrid object, and the boundary matters.</p><p><strong>Input.</strong> The user’s task plus the discovery block. The model performs a relevance judgment: does this task match a skill’s description? This is pure LLM reasoning, and it is the least reliable step.</p><p><strong>Processing.</strong> Once activated, the model reasons through the procedure: mapping user data to form fields, deciding which reference file applies, handling the ambiguous cases the instructions flag. The scripts execute deterministically: listing PDF fields, writing bytes, running checks. The model’s job is judgment. The script’s job is precision.</p><p>The PDF skill pattern shows why this split exists. You do not want the model hand-generating PDF bytecode, and you do not want a script deciding what “the customer’s name” maps to in a messy form.</p><p><strong>Output.</strong> The task result plus, ideally, a short trace of which skill was activated and which steps ran. That trace is what makes skills debuggable in a way giant prompts are not.</p><p><strong>Where the model can still go wrong.</strong> The model can mis-trigger (activating the wrong skill), under-trigger (missing the skill entirely and improvising), or follow the procedure while misunderstanding a step. Skills reduce variance; they do not eliminate judgment calls. State preconditions, forbid guessing, and specify failure behavior (“leave blank and report”) rather than hoping for good behavior.</p><h3>A Realistic Worked Example</h3><p>Consider a team that processes vendor onboarding forms: PDFs arrive by email, data must be extracted into the vendor database, and every field maps through an approval checklist.</p><p>Before skills, the team kept the 40-step procedure in the agent’s system prompt. Every session paid for 40 steps. Every procedure change meant editing a prompt everyone was afraid to touch.</p><p>With skills, the procedure becomes a vendor-onboarding skill. The discovery description is one line: when the task involves vendor onboarding PDFs and the vendor database, this skill applies. The SKILL.md holds the field-mapping rules and the approval checklist order. The deterministic extraction lives in scripts/extract.py. The database writes go through the team&#39;s existing MCP server tools, with the skill specifying the call order and the mandatory-field checks.</p><p>With 25 installed skills at roughly 100 tokens each, discovery costs about 2,500 tokens per session at rest. The old approach loaded the full 40-step procedure plus all MCP tool schemas every session, running into tens of thousands of tokens before any work happens.</p><p>But the token savings are not the real headline. The headline is that the procedure is now versioned, reviewable, and editable without touching agent configuration.</p><h3>Limitations and Failure Modes</h3><p>Skills fail in specific, predictable ways. Knowing them is the difference between adopting the format and depending on it blindly.</p><p><strong>Trigger collisions.</strong> Two skills with overlapping descriptions and the model picks wrong, or picks neither and improvises. Fix: descriptions must say what the skill is <em>not</em> for, and overlapping skills should reference each other explicitly.</p><p><strong>Stale procedures.</strong> A skill is code, and code rots. The refund policy changes; the SKILL.md does not; the agent now executes last quarter&#39;s procedure with total confidence. Version skills in git, review them like code, and assign ownership.</p><p><strong>Skills are executable content.</strong> This is the sharpest edge. A skill you install runs with your agent’s permissions: its instructions shape behavior and its scripts execute code. Review third-party skills with the same suspicion you would apply to any package running with your credentials, because that is functionally what it is.</p><p><strong>Prompt injection through skills.</strong> A skill loaded from an untrusted source can contain instructions that subvert the task. Treat skill content as untrusted input until vetted, and route skill installation through the same approval process as dependency changes.</p><p><strong>The determinism boundary can mislead.</strong> Pushing logic into scripts feels safe, but a script is only as correct as its author. The model will trust script output absolutely. A buggy list_fields.py that drops checkbox fields will produce confidently incomplete forms.</p><p><strong>Evaluation is genuinely hard.</strong> There is no standard benchmark for “did the skill trigger correctly and did the procedure execute faithfully.” Budget for building your own eval harness. It is the unglamorous work that makes skills production-ready.</p><p>What still needs human validation: any skill touching money, access control, customer-facing communication, or irreversible actions. The skill makes the procedure repeatable. It does not make it correct.</p><h3>Production Considerations</h3><p><strong>Vetting and provenance.</strong> Allowlist skill sources. Pin versions. Review SKILL.md diffs in pull requests the way you would review config changes. A skill update that silently changes a procedure is a deployment.</p><p><strong>Monitoring.</strong> Log every skill activation: which skill, which task, token cost, and task outcome. Activation rate per skill tells you what is actually used. A skill with zero activations over a month is either misdescribed or unnecessary. Track trigger errors explicitly; wrong-skill activations are a leading indicator of description problems.</p><p><strong>Testing.</strong> Maintain a task suite per skill with expected activations. Run it on every skill change and on every model change, because a new model version can shift trigger behavior even when the skill is untouched.</p><p><strong>Security.</strong> Sandbox script execution. Prefer read-only skills where possible. Never let a skill’s scripts handle credentials directly; pass through the harness’s existing secret management. Keep skills and MCP tool permissions in the same audit view, since a skill orchestrating MCP tools inherits the union of their access.</p><p><strong>Maintenance.</strong> Assign owners. Expire or archive skills for deprecated workflows. The failure mode to fear is not too few skills but a graveyard of stale ones, each a confident wrong procedure waiting for a matching task.</p><h3>Where to Start</h3><p><strong>Start with your most painful runbook, not your most impressive one.</strong> The skill with the clearest procedure and the highest execution frequency pays back first.</p><p><strong>Write the description last and test it first.</strong> Show five colleagues the task and the description. If they cannot predict the trigger, the model will not either.</p><p><strong>Push every deterministic step into a script.</strong> If a step has a right answer computable without judgment, it does not belong in prose the model interprets.</p><p><strong>Keep </strong><strong>SKILL.md under the recommended size and split the rest into gated reference files.</strong> If everything is &quot;important,&quot; the gating is broken.</p><p><strong>Build the trigger eval before the tenth skill.</strong> Five tasks per skill, expected activation labeled, run on every change. This is the highest-ROI testing investment in the format.</p><p><strong>Treat skill installation as a dependency decision.</strong> Review, pin, and assign an owner. The convenience of “just drop in a folder” is exactly what makes the supply-chain risk easy to ignore.</p><p><strong>Pair every skill that touches external systems with the MCP tools it orchestrates, documented in the skill body.</strong> Know-how and access should be reviewed together</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b896bf4349b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Constitutional AI Explained: How AI Feedback Replaces Human Labels for Harmlessness]]></title>
            <link>https://medium.com/@atnoforgenai/constitutional-ai-explained-how-ai-feedback-replaces-human-labels-for-harmlessness-52e541e393ea?source=rss-36b5ad2df1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/52e541e393ea</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[ATNO for GenAI & Agentic AI]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 12:46:02 GMT</pubDate>
            <atom:updated>2026-09-28T12:46:02.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqt_N0F6aqX5sOQkDrts7A.jpeg" /></figure><h4>A practical walkthrough of critique, revision, and RLAIF, with a small pipeline you can adapt.</h4><p>Human feedback is the standard way to align language models, but it is hard to scale. It is slow and expensive, annotators often disagree, and reading large volumes of harmful completions takes a toll on the people doing the labeling. Reward models trained on human ratings can also drift toward pleasing the rater rather than telling the truth.</p><p>Anthropic’s answer, introduced in the 2022 paper <em>Constitutional AI: Harmlessness from AI Feedback</em> (Bai et al.), is <strong>Constitutional AI (CAI)</strong>. Instead of collecting human labels for harmlessness, the model critiques and revises its own outputs, guided by a short list of written principles called a <strong>constitution</strong>.</p><blockquote><strong><em>A scope note:</em></strong><em> in the original paper, AI feedback replaced human labels for </em>harmlessness only<em>. Human labels were still used for helpfulness. Anthropic has also updated its constitution since 2022, so this article covers the method as published, not Claude’s full current training recipe.</em></blockquote><p>This guide covers the two training phases, a small revision pipeline, common failure modes, and a validation checklist.</p><h3>1. 🧠 Core Architecture</h3><p>CAI has two phases:</p><ul><li><strong>Supervised Learning (SL) phase:</strong> critique and revision.</li><li><strong>Reinforcement Learning (RL) phase:</strong> RL from AI Feedback (<strong>RLAIF</strong>).</li></ul><p>Instead of asking humans which of two responses is more harmful, the model is given a written principle and asked to judge or edit its own work.</p><h4>The SL phase (critique → revision → fine-tune)</h4><p>In the paper, the process starts with a helpful-only RLHF model, which is helpful but not trained to be harmless. It is prompted with red-teaming inputs, so its first responses are often harmful. The model then critiques each response against a randomly sampled principle and revises it. A pretrained model is fine-tuned on the final revisions, producing the <strong>SL-CAI</strong> model.</p><h4>The RL phase (AI preference labels → RLAIF)</h4><p>The SL-CAI model generates pairs of responses to harmful prompts. A feedback model is shown both responses and a constitutional principle, and asked which response is better. Its normalized log-probabilities over the answer choices become soft preference labels.</p><p>These AI harmlessness labels are combined with human helpfulness labels to train a preference model. The policy is then optimized with reinforcement learning against that preference model.</p><blockquote><strong><em>A modern note:</em></strong><em> DPO (Direct Preference Optimization) came later. Many open-source replications use AI-labeled pairs with DPO instead of a PPO-style loop. That is a common variant, not part of the original recipe.</em></blockquote><h4>The pipeline components</h4><ul><li><strong>Adversarial prompt harvesting</strong></li><li><em>Role:</em> input generation.</li><li><em>How:</em> red-teaming, whether human-written or automated.</li><li><em>Output:</em> prompts xx x.</li><li><em>Metric to watch:</em> attack success rate (ASR).</li><li><strong>SL critique step</strong></li><li><em>Role:</em> internal auditing.</li><li><em>How:</em> the model explains how response y0y_0 y0​ conflicts with principle CiC_i Ci​.</li><li><em>Output:</em> a written critique.</li><li><strong>SL revision step</strong></li><li><em>Role:</em> regeneration.</li><li><em>How:</em> conditioned on xx x, y0y_0 y0​, and the critique, the model rewrites the response.</li><li><em>Output:</em> a revised response y∗y^* y∗ used for supervised fine-tuning.</li><li><strong>AI preference labeling</strong></li><li><em>Role:</em> synthetic scoring.</li><li><em>How:</em> a feedback model compares two candidate responses under a principle.</li><li><em>Output:</em> pairwise preference data (yw≻yly_w \succ y_l yw​≻yl​).</li><li><strong>RL policy tuning</strong></li><li><em>Role:</em> weight alignment.</li><li><em>How:</em> optimize the policy against the preference model, usually with a KL penalty to stay near the reference model.</li><li><em>Output:</em> the final aligned checkpoint.</li></ul><h4>The feedback loop in five steps</h4><ol><li><strong>Adversarial ingestion:</strong> a red-team prompt is sent to the model.</li><li><strong>First-pass generation:</strong> the model produces an initial response y0y_0 y0​.</li><li><strong>Constitutional critique:</strong> a principle CiC_i Ci​ is sampled, and the model explains how y0y_0 y0​ violates it.</li><li><strong>Revision:</strong> conditioned on the prompt, response, and critique, the model rewrites the response to remove the harm while still answering any legitimate intent.</li><li><strong>Supervised distillation:</strong> the model is fine-tuned on the final (x,y∗) pairs with standard cross-entropy loss.</li></ol><blockquote><strong><em>💡 Tip:</em></strong><em> Keep critique and revision as </em><strong><em>separate generation steps</em></strong><em>. Writing the critique into the context first acts like chain-of-thought and tends to improve the revision.</em></blockquote><h3>2. ⚙️ Building a Minimal Revision Pipeline</h3><p>A small pipeline can use <strong>vLLM</strong> for fast inference, with <strong>TRL</strong> later for training. You’ll need:</p><ul><li>an inference engine (vLLM is used below),</li><li>a versioned file of principles, ideally YAML or JSON,</li><li>an instruction-tuned model,</li><li>a training harness such as TRL’s SFTTrainer or DPOTrainer for the later stages.</li></ul><p>The code below runs critique and revision as <strong>two separate calls</strong>. It uses the model’s chat template so it works with any instruct model.</p><pre>from difflib import SequenceMatcher<br>from vllm import LLM, SamplingParams<br><br>llm = LLM(model=&quot;mistralai/Mistral-7B-Instruct-v0.3&quot;)<br>params = SamplingParams(temperature=0.2, max_tokens=512)<br><br>def generate(prompt: str) -&gt; str:<br>    out = llm.chat([{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}], params)<br>    return out[0].outputs[0].text.strip()<br><br>CRITIQUE_PROMPT = &quot;&quot;&quot;Human request: {request}<br><br>Assistant response: {response}<br><br>Principle: {principle}<br><br>Identify specific ways the response conflicts with this principle.<br>If it does not conflict, say &quot;No violation.\&quot;&quot;&quot;&quot;<br><br>REVISION_PROMPT = &quot;&quot;&quot;Human request: {request}<br><br>Assistant response: {response}<br><br>Principle: {principle}<br><br>Critique: {critique}<br><br>Rewrite the response so it follows the principle while still answering<br>any legitimate underlying question as helpfully as possible.<br>Preserve benign context. Output only the rewritten response.&quot;&quot;&quot;<br><br>def critique_and_revise(request: str, response: str, principle: str) -&gt; str:<br>    critique = generate(CRITIQUE_PROMPT.format(<br>        request=request, response=response, principle=principle))<br>    if critique.lower().startswith(&quot;no violation&quot;):<br>        return response<br>    return generate(REVISION_PROMPT.format(<br>        request=request, response=response,<br>        principle=principle, critique=critique))</pre><blockquote><strong><em>🔑 Note:</em></strong><em> Avoid “semantic wash-out.” If the revision prompt doesn’t tell the model to keep benign context and stay helpful, it tends to default to blanket refusals.</em></blockquote><blockquote><strong><em>⚠️ Caveat:</em></strong><em> Off-the-shelf instruct models are already safety-tuned. This code demonstrates the mechanics, but for a faithful replication you’d want a helpful-only starting model.</em></blockquote><h3>3. 🔀 Methodological Variants</h3><ul><li><strong>Iterative SL revision (SFT-CAI)</strong></li><li><em>Behavior:</em> repeated self-correction.</li><li><em>Best for:</em> bootstrapping a safety baseline from a weaker model.</li><li><em>Caveat:</em> high inference cost when generating the synthetic data.</li><li><strong>Constitutional DPO</strong></li><li><em>Behavior:</em> preferences are optimized directly, with no separate reward model.</li><li><em>Best for:</em> resource-constrained teams.</li><li><em>Caveat:</em> sensitive to noisy AI-labeled pairs.</li><li><strong>Constitutional RL (full RLAIF)</strong></li><li><em>Behavior:</em> an explicit preference or reward model scores outputs against the constitution.</li><li><em>Best for:</em> teams that need tight control over the reward signal.</li><li><em>Caveat:</em> training instability, sensitivity to hyperparameters, and KL drift.</li></ul><p>Here is a simple pair-selection function. In practice, p_a would come from a feedback model&#39;s normalized probability of choosing response A.</p><pre>def make_preference_pair(prompt: str, resp_a: str, resp_b: str,<br>                         p_a: float, margin: float = 0.1):<br>    &quot;&quot;&quot;Return a DPO-style pair, or None if the judge is unsure.&quot;&quot;&quot;<br>    if abs(p_a - 0.5) &lt; margin:<br>        return None  # drop low-confidence labels<br>    chosen, rejected = (resp_a, resp_b) if p_a &gt; 0.5 else (resp_b, resp_a)<br>    return {&quot;prompt&quot;: prompt, &quot;chosen&quot;: chosen, &quot;rejected&quot;: rejected}</pre><blockquote><strong><em>💡 Tip:</em></strong><em> Penalize evasive refusals when ranking. If one answer is safe but ignores a legitimate question, and another is safe and informative, the informative one should be </em><em>chosen.</em></blockquote><h3>4. 🛡️ Failure Handling</h3><p>Self-critique can fail. A model may make trivial edits, invent violations that don’t exist, or agree with its own mistakes.</p><ol><li><strong>Principle conflicts:</strong> when two principles pull in opposite directions, such as transparency versus protecting private data, define an explicit priority order in your registry.</li><li><strong>Oscillation breaker:</strong> stop revising when successive drafts barely change. Use a similarity threshold such as SequenceMatcher(...).ratio() &gt; 0.95, tuned on your own data.</li><li><strong>Quality gate:</strong> filter synthetic outputs with rules and classifiers before adding them to the training set.</li><li><strong>Drop, don’t patch:</strong> if a sample still fails after a few passes, discard it instead of polluting the dataset.</li></ol><pre>def revise_loop(request: str, response: str, principles: list[str],<br>                max_passes: int = 3, sim_threshold: float = 0.95) -&gt; str | None:<br>    current = response<br>    for i in range(max_passes):<br>        revised = critique_and_revise(request, current, principles[i % len(principles)])<br>        if SequenceMatcher(None, current, revised).ratio() &gt; sim_threshold:<br>            return revised  # converged<br>        current = revised<br>    return None  # unresolved: drop from training data</pre><blockquote><strong><em>💡 Tip:</em></strong><em> Log everything: the prompt, the original completion, the critique, the principle ID, and the final completion. If the model later behaves oddly, you can trace the change back to a specific rule.</em></blockquote><h3>5. 🧪 Validation Checklist</h3><p>A constitutional model needs testing on both sides: did harmfulness go down, and did helpfulness and reasoning survive? The targets below are <strong>illustrative starting points, not industry standards</strong>. Set your own based on your use case.</p><ul><li><strong>Adversarial robustness</strong></li><li><em>Goal:</em> low attack success rate on standard jailbreaks.</li><li><em>Tools:</em> HarmBench, PyRIT.</li><li><strong>Over-refusal rate</strong></li><li><em>Goal:</em> few false refusals on benign but borderline prompts.</li><li><em>Tool:</em> XSTest.</li><li><strong>Sycophancy</strong></li><li><em>Goal:</em> the model doesn’t cave to incorrect user claims.</li><li><em>Method:</em> opinion-flip and pushback tests.</li><li><strong>Reasoning retention</strong></li><li><em>Goal:</em> general capability doesn’t regress.</li><li><em>Tools:</em> MMLU-Pro and GSM8K via lm-evaluation-harness.</li></ul><blockquote><strong><em>🛠️ Debug tip:</em></strong><em> Track an “evasion index.” Compare the average response length on red-team prompts before and after training. A large drop, such as 40% or more, is a warning sign that the model is dodging hard questions rather than answering them safely.</em></blockquote><h3>🚫 Four Anti-Patterns</h3><ul><li><strong>The kitchen-sink constitution</strong></li><li><em>Problem:</em> too many overlapping principles cause conflicts and dilute the signal. The original paper used a small set of 16.</li><li><em>Fix:</em> keep a focused, non-contradictory set.</li><li><strong>Refusal amplification</strong></li><li><em>Problem:</em> unconstrained critiques teach the model to refuse benign requests, such as a fictional story involving lockpicking.</li><li><em>Fix:</em> instruct revisions to answer the benign part fully and remove only the dangerous operational detail.</li><li><strong>Sycophantic self-critique</strong></li><li><em>Problem:</em> a weak critic tends to endorse its own mistakes.</li><li><em>Fix:</em> use a stronger or separate critic, or vary decoding settings.</li><li><strong>Static rule rot</strong></li><li><em>Problem:</em> a fixed constitution falls behind as new jailbreaks emerge.</li><li><em>Fix:</em> version your principles like code and update them from red-team findings.</li></ul><h3>🔑 The Takeaway</h3><p>CAI works because written critique turns a vague failure (“this response is harmful”) into an explicit training signal. The model uses its comprehension to repair its own outputs, and the constitution makes that process inspectable and editable.</p><ul><li>Treat the constitution like code: version it, review it, and test changes.</li><li>Don’t trade helpfulness for safety. Over-refusal is a failure mode too.</li><li>Keep critique and revision as separate steps.</li><li>Measure both harmlessness and helpfulness after training.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52e541e393ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Emergent Abilities in LLMs: Real Phenomenon or Measurement Illusion?]]></title>
            <link>https://medium.com/@atnoforgenai/emergent-abilities-in-llms-real-phenomenon-or-measurement-illusion-9a0eda1c9ceb?source=rss-36b5ad2df1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a0eda1c9ceb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[ATNO for GenAI & Agentic AI]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 10:51:01 GMT</pubDate>
            <atom:updated>2026-09-25T10:51:01.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3uUPdN8srMZ0Qra7m0yPNw.jpeg" /></figure><h3>Why many “sudden jumps” in model capability come from the metric, not the model, and how to audit your own evals</h3><p>The popular story about large language models treats scale like alchemy. Small models supposedly can’t do multi-step arithmetic, translation, or symbolic reasoning at all. Then, past some parameter or compute threshold, performance leaps from near 0% to something impressive.</p><p>That’s the idea behind “emergent abilities,” popularized by Wei et al. (2022). It’s a compelling narrative, and a good part of it doesn’t survive a closer look at how we measure.</p><p><strong>Many reported emergent abilities are artifacts of the metric, not sudden phase transitions inside the model.</strong></p><p>This post explains why, using the argument from Schaeffer, Miranda, and Koyejo (NeurIPS 2023), “Are Emergent Abilities of Large Language Models a Mirage?” Then it builds a small audit pipeline with Hugging Face transformers that you can point at your own evaluations.</p><h3>The core idea: compounding turns smooth into sudden</h3><p>Suppose a task needs the model to generate L tokens correctly, and the model’s per-token accuracy is p. An <strong>exact match</strong> metric only gives credit if every token is right. Under a simplifying independence assumption, that score is roughly:</p><p><strong>exact match ≈ p^L</strong></p><p>Now let p improve smoothly as the model scales. For any L greater than 1, p^L stays close to zero until p gets near 1, and then it shoots upward. The model got better gradually at every step, but the metric only registers success at the very end.</p><p>That shape looks like a sudden transition. It’s really a smooth curve viewed through a harsh ruler.</p><p>A quick example. If the answer is 5 tokens long:</p><ul><li>At p = 0.60, exact match is about 8%.</li><li>At p = 0.80, about 33%.</li><li>At p = 0.95, about 77%.</li></ul><p>Per-token accuracy improved steadily, yet the headline metric went from “basically zero” to “basically solved” over a fairly narrow range.</p><blockquote><strong><em>Caveat:</em></strong><em> Real tokens aren’t independent, so p^L is an approximation. It explains the shape of the effect, not the exact numbers.</em></blockquote><h3>Why metric choice changes the story</h3><p>Different metrics compress the same underlying progress in different ways.</p><p><strong>Exact match (0 or 1)</strong></p><ul><li>All-or-nothing: an answer that’s one token off scores the same as pure noise.</li><li>Behaves like p^L, so it produces step-like curves.</li><li>The most likely to manufacture “emergence.”</li></ul><p><strong>Token-level cross-entropy</strong></p><ul><li>Averages log-probability over the target tokens, so partial progress counts.</li><li>Tends to improve smoothly and predictably with scale, in line with scaling-law results.</li><li>Doesn’t produce artificial jumps.</li></ul><p><strong>Edit distance (character or token level)</strong></p><ul><li>Gives partial credit based on how close the output is to the reference.</li><li>Fine-grained, so it shows gradual progress that exact match hides.</li></ul><p><strong>Brier score (for multiple choice)</strong></p><ul><li>Scores the model’s probability assigned to the right option, not just whether it picked it.</li><li>Continuous, so it avoids the threshold effect of plain multiple-choice accuracy.</li></ul><p>The paper also showed the effect in reverse: by choosing the right discontinuous metric, the authors could make “emergent abilities” appear even in vision models where no one expected them</p><blockquote><strong><em>Tip:</em></strong><em> If a capability curve looks discontinuous, re-plot it with a continuous metric such as mean token log-likelihood, or compare it against what p^L predicts from the per-token probabilities. If the jump shrinks or disappears, you’re probably looking at a measurement artifact.</em></blockquote><h3>A more careful claim</h3><p>It’s worth being precise about what this does and doesn’t show.</p><ul><li><strong>It shows</strong> that many headline emergence results depend heavily on nonlinear or discontinuous metrics.</li><li><strong>It doesn’t show</strong> that no qualitative capability changes ever happen. Phenomena like grokking, and later work analyzing emergence relative to pretraining loss, keep the debate open.</li></ul><p>So the useful stance isn’t “emergence is fake.” It’s “check your metric before you claim a phase transition.”</p><h3>Building a metric audit pipeline</h3><p>The pipeline compares two views of the same model on the same task: the strict exact-match score, and the continuous per-token probability underneath it. It also computes what compounding alone would predict.</p><p><strong>What you’ll need</strong></p><ul><li>Python 3.10+ with PyTorch</li><li>pip install transformers torch accelerate lm-eval scipy python-Levenshtein</li><li>Access to a <strong>model family trained on the same data at multiple sizes</strong>. The Pythia suite (Biderman et al., 2023) is ideal. Mixing different families, such as Llama and Mistral, muddies the comparison because their training data and recipes differ.</li><li>A GPU with enough memory for the largest model you plan to test</li></ul><pre>import torch<br>import numpy as np<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br><br>def audit_metric_discontinuity(model_id: str, eval_dataset: list[dict]) -&gt; dict:<br>    tokenizer = AutoTokenizer.from_pretrained(model_id)<br>    model = AutoModelForCausalLM.from_pretrained(<br>        model_id,<br>        torch_dtype=torch.bfloat16,   # newer transformers versions call this `dtype`<br>        device_map=&quot;auto&quot;,<br>    )<br>    model.eval()<br><br>    exact_matches, avg_log_probs, predicted_em = [], [], []<br><br>    for sample in eval_dataset:<br>        prompt, target = sample[&quot;prompt&quot;], sample[&quot;target&quot;]<br><br>        enc_prompt = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(model.device)<br>        enc_full = tokenizer(prompt + target, return_tensors=&quot;pt&quot;).to(model.device)<br>        target_len = enc_full.input_ids.shape[1] - enc_prompt.input_ids.shape[1]<br><br>        with torch.no_grad():<br>            logits = model(**enc_full).logits[:, -target_len - 1 : -1, :]<br>            labels = enc_full.input_ids[:, -target_len:]<br><br>            log_probs = torch.log_softmax(logits.float(), dim=-1)<br>            tok_lp = torch.gather(log_probs, 2, labels.unsqueeze(-1)).squeeze(-1)<br><br>            mean_lp = tok_lp.mean().item()<br>            avg_log_probs.append(mean_lp)<br><br>            # What compounding alone predicts: (geometric-mean token prob) ^ L<br>            predicted_em.append(float(np.exp(mean_lp) ** target_len))<br><br>            # Exact match: does greedy decoding get every target token right?<br>            exact_matches.append(float(torch.equal(logits.argmax(-1), labels)))<br><br>    return {<br>        &quot;exact_match_acc&quot;: float(np.mean(exact_matches)),<br>        &quot;mean_token_log_prob&quot;: float(np.mean(avg_log_probs)),<br>        &quot;implied_token_prob&quot;: float(np.exp(np.mean(avg_log_probs))),<br>        &quot;predicted_em_from_probs&quot;: float(np.mean(predicted_em)),<br>    }</pre><blockquote><strong><em>Note:</em></strong><em> Slice by token IDs, never by string length. Tokenizers can merge or shift subwords at the prompt/target boundary (a leading space is the classic culprit), and that silently corrupts your slice and invalidates the log-probs. Sanity-check the boundary on a few examples before running the whole set.</em></blockquote><h3>Reading the results</h3><p>Run the audit at each model size, then compare small and large models. The diagnostic question is whether compounding explains the jump you’re seeing.</p><pre>def diagnose_jump(small: dict, large: dict, jump=0.20, tol=0.15) -&gt; str:<br>    em_jump = large[&quot;exact_match_acc&quot;] - small[&quot;exact_match_acc&quot;]<br>    if em_jump &lt; jump:<br>        return &quot;No large exact-match jump to explain.&quot;<br><br>    gap = abs(large[&quot;predicted_em_from_probs&quot;] - large[&quot;exact_match_acc&quot;])<br>    if gap &lt;= tol:<br>        return (&quot;Jump is largely explained by compounding of smooth token &quot;<br>                &quot;probabilities: likely a metric artifact.&quot;)<br>    return (&quot;Jump is NOT explained by token probabilities. Check for &quot;<br>            &quot;contamination, prompt/format changes, or a real capability shift.&quot;)</pre><p>The thresholds are heuristics, and the p^L prediction is rough, so treat the output as a prompt for investigation. It isn’t a verdict.</p><h3>Applying soft evaluation</h3><p>When you want partial credit instead of pass/fail, a continuous alignment score helps. This one works at the character level:</p><pre>import Levenshtein<br><br>def soft_alignment(generated: str, expected: str) -&gt; float:<br>    &quot;&quot;&quot;Bounded 0-1 score based on character-level edit distance.&quot;&quot;&quot;<br>    a, b = generated.strip(), expected.strip()<br>    max_len = max(len(a), len(b))<br>    if max_len == 0:<br>        return 1.0<br>    return max(0.0, 1.0 - Levenshtein.distance(a, b) / max_len)</pre><blockquote><strong><em>Tip:</em></strong><em> Never report scaling results with just one metric family. Pair your operational metric (pass@1, exact match) with a continuous proxy such as mean token probability on the same task.</em></blockquote><h3>Choosing an evaluation approach</h3><p><strong>Strict greedy decoding with exact match</strong></p><ul><li>Best for final, consumer-facing checks where the answer really must be exactly right, like a code-linting pass.</li><li>Caveat: hides intermediate progress and creates step-like curves.</li></ul><p><strong>Length-normalized perplexity or log-likelihood</strong></p><ul><li>Best for scaling analysis and comparing checkpoints.</li><li>Caveat: can favor models that match the style of the reference text without actually solving the problem.</li></ul><p><strong>Continuous distance metrics (edit distance, Brier score)</strong></p><ul><li>Best for tracking incremental progress across sizes, such as 1B to 7B to 70B.</li><li>Caveat: heavier to compute than single-token checks.</li></ul><h3>An audit checklist for a suspicious jump</h3><p>When a benchmark shows a sharp leap across model sizes or checkpoints, work through these in order:</p><ol><li><strong>Check formatting and tokenization.</strong> Rule out prompt-format changes or tokenizer boundary issues that penalize smaller models unfairly.</li><li><strong>Decompose the task.</strong> Break multi-step problems (GSM8K-style reasoning, for example) into single-step checks to see where progress actually happens.</li><li><strong>Probe with perturbations.</strong> Change digits, reorder answer options, or paraphrase prompts to rule out memorization or brittleness.</li><li><strong>Switch the metric.</strong> Re-plot with a continuous metric and see whether the jump survives.</li><li><strong>Test length dependence.</strong> Run arithmetic probes from 2 digits up to 8 and check that accuracy falls off roughly as p^L would predict.</li></ol><blockquote><strong><em>Multiple-choice tip:</em></strong><em> Don’t ask a model to generate the letter “A”, “B”, “C”, or “D” as free text. Compute the log-likelihood the model assigns to each candidate answer given the prompt. Otherwise, small models can look like they know nothing simply because they start with a chatty preamble instead of the letter.</em></blockquote><h3>Four evaluation mistakes that fool you</h3><p><strong>1. Relying only on exact match.</strong><br>It throws away partial progress and turns smooth learning into a step function. Log exact match and continuous token-level scores side by side.</p><p><strong>2. Letting models free-generate multiple-choice answers.</strong><br>Verbosity gets scored as ignorance. Score the log-likelihood of the answer choices instead.</p><p><strong>3. Using one fixed set of few-shot examples.</strong><br>Examples can shift calibration without improving reasoning. Sweep several few-shot orderings and report the spread.</p><p><strong>4. Confusing task length with capability.</strong><br>Multi-step tasks stack probabilities, which can fabricate late-stage jumps. Break them into atomic sub-questions and plot progress per step.</p><h3>The takeaway</h3><p>Genuine qualitative breakthroughs may exist, but many of the dramatic curves in the emergence literature come from the ruler used to measure them. Treat capability as a continuous quantity to be measured carefully, not a set of switches that flip at a certain scale.</p><ul><li><strong>Measure continuously.</strong> Use token log-likelihoods alongside your pass/fail metrics.</li><li><strong>Audit your metric.</strong> If a task shows a sharp jump, re-measure with a metric of different linearity.</li><li><strong>Decompose the steps.</strong> Find out where probability is actually accumulating.</li><li><strong>Be skeptical of mystique.</strong> Treat unexplained discontinuities as measurement or data issues until shown otherwise.</li><li><strong>Build on confidence, not strings.</strong> Use token-level confidence for routing and fallback logic instead of brittle exact-string matches.</li></ul><p>If your metric only counts home runs, you’ll completely miss the batter who’s been steadily learning to make contact.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a0eda1c9ceb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Space Models vs. Transformers: Is Mamba the Next Architecture Shift?]]></title>
            <link>https://medium.com/@atnoforgenai/state-space-models-vs-transformers-is-mamba-the-next-architecture-shift-d20680e7e8c4?source=rss-36b5ad2df1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d20680e7e8c4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[ATNO for GenAI & Agentic AI]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 11:51:01 GMT</pubDate>
            <atom:updated>2026-09-22T11:51:01.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nkQPpi0RrCBJpcHv3p1Zg.png" /></figure><h4>Why your O(N) inference dreams shatter on real-world memory bounds and information-dense recall.</h4><p>The demo graph is intoxicating: Transformer attention scales quadratically at O(N²) as sequence length climbs, while Selective State Space Models (SSMs) like Mamba slice through millions of tokens with a flat, glorious O(N) linear inference runtime. Every machine learning engineer on your feed wants you to scrap your KV-cache infrastructure tomorrow and declare attention dead.</p><p>Here is what breaks when you step out of synthetic benchmark land: real production workloads do not fail on token-processing FLOPs - they fail on state capacity, hardware-level SRAM-to-HBM bus transfers, and catastrophic loss of copy-recall accuracy. Compressing an arbitrary stream of conversational or documentary context into a fixed-size latent state is lossy by mathematical design.</p><p>Mamba doesn’t murder the Transformer; it forces you to stop pretending memory bandwidth is free. To engineer high-throughput LLM systems, we must deconstruct Selective State Space Models against multi-head attention (MHA/GQA) where latency budgets actually get spent.</p><p>Let’s dig into the metal.</p><h3>1.Core Architecture: Discretization Meets Hardware-Aware Selection</h3><p>Textbook recurrent models failed because sequential token updates prevent parallel training across GPU cores. Traditional Linear Time-Invariant (LTI) State Space Models (like S4) bypassed this by converting continuous differential equations into parallel convolutions across training sequences:</p><pre>h&#39;(t) = A · h(t) + B · x(t)<br>y(t)  = C · h(t)</pre><p>Because matrices A, B, and C remained static across all timesteps in LTI setups, models could not discard irrelevant filler tokens or dynamically reset internal state upon encountering a syntactic boundary.</p><p>Mamba fixes this through <strong>Selective State Spaces</strong>: it turns B, C, and the step-size parameter Δ into dynamic projections of the input x_t. The continuous system is discretized via the Zero-Order Hold (ZOH) formulation:</p><pre>A_bar = exp(Δ · A)<br>B_bar = (Δ · A)⁻¹ · (exp(Δ · A) - I) · (Δ · B)</pre><p>Because parameters now change with each token, the global convolution trick vanishes; Mamba solves this using a hardware-aware parallel associative scan executed entirely inside fast on-chip SRAM.</p><h3>Memory Layout &amp; Component Roles</h3><ul><li><strong>A Matrix (State Decay Dynamics)</strong></li><li><strong>Role:</strong> Governs continuous state decay and system dynamics.</li><li><strong>Type:</strong> Learned during training, fixed at inference. Initialized S4D-real style (not exactly HiPPO).</li><li><strong>Residency:</strong> Local SRAM / Registers during kernel execution.</li><li><strong>Update Frequency:</strong> Learned parameter updated via backprop during training; static during inference.</li><li><strong>Δ / Delta (Gating &amp; Discretization Step)</strong></li><li><strong>Role:</strong> Controls input-dependent time-step discretization and selective forgetting/retention.</li><li><strong>Type:</strong> Dynamic: f(x_t).</li><li><strong>Residency:</strong> Registers / on-chip SRAM.</li><li><strong>Update Frequency:</strong> Evaluated per token.</li><li><strong>B &amp; C Matrices (State Ingestion &amp; Output Projection)</strong></li><li><strong>Role:</strong> B injects incoming token features into the latent state; C reads out contracted latent context.</li><li><strong>Type:</strong> Dynamic: f(x_t).</li><li><strong>Residency:</strong> Registers / on-chip SRAM.</li><li><strong>Update Frequency:</strong> Evaluated per token.</li><li><strong>h_t Hidden State (Persistent Sequence Context)</strong></li><li><strong>Role:</strong> Stores the running, compressed latent context of historical tokens.</li><li><strong>Type:</strong> Dynamic vector state.</li><li><strong>Residency:</strong> On-chip SRAM inside the scan kernel; stored in HBM between decode steps.</li><li><strong>Update Frequency:</strong> Recurrently updated per token step.</li><li><strong>KV Cache (Standard Transformer Baseline)</strong></li><li><strong>Role:</strong> Retains raw, uncompressed key and value projections for full causal cross-token attention.</li><li><strong>Type:</strong> Explicit, unbounded token store.</li><li><strong>Residency:</strong> Off-chip High-Bandwidth Memory (HBM).</li><li><strong>Update Frequency:</strong> Appends new entries with every generated token.</li></ul><h3>How Selective Scan Executes in Hardware:</h3><ul><li><strong>Linear Projection:</strong> Input vector x_t is projected into expanded intermediate dimensions along with a 1D depthwise causal convolution to extract local sub-word context.</li><li><strong>Dynamic Parameter Generation:</strong> Parallel linear heads project x_t into discrete step size Δ, input matrix B, and output matrix C.</li><li><strong>Hardware Kernel Fusion:</strong> Δ discretizes continuous state transition matrix A into A_bar entirely in local registers, avoiding round-trip latency to global HBM.</li><li><strong>Associative Parallel Scan:</strong> The algorithm computes prefix operations across chunked blocks using work-efficient tree scans directly inside Streaming Multiprocessors (SMs).</li><li><strong>Selective State Dynamics:</strong></li><li>When tokens are irrelevant, the model predicts <strong>Δ → 0</strong>, forcing A_bar → I and B_bar → 0. The previous state is preserved unchanged while the current input is discarded.</li><li>When a contextual reset is required, Δ scales up while input dynamics transition, allowing the model to flush stale hidden context.</li><li><strong>Projection Output:</strong> The contracted hidden representation y_t = C · h_t is gated element-wise by a SiLU-activated residual branch and projected back down to d_model.</li></ul><blockquote><strong><em>Pro Tip:</em></strong><em> The secret to Mamba’s throughput is kernel fusion, not just FLOP minimization. Standard PyTorch execution of time-varying SSM equations gets bottlenecked by memory bandwidth limits instantly. Mamba writes intermediate states directly to SRAM and writes only the final output tensor back to HBM.</em></blockquote><h3>2. Implementation: Selective Scan Integration</h3><p>Deploying custom SSM layers requires bypassing standard autograd loops in favor of custom CUDA/Triton kernels that prevent off-chip intermediate caching.</p><h3>Setup Checklist</h3><ul><li>NVIDIA Ampere/Hopper/Blackwell GPU with compute capability ≥ 8.0</li><li>PyTorch ≥ 2.2.0 with matching CUDA toolkit</li><li>causal-conv1d and mamba-ssm installed</li><li>Precision config: bfloat16 for weights/activations; mandatory float32 for state discretization parameters A and Δ.</li></ul><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br>from mamba_ssm.ops.selective_scan_interface import selective_scan_fn<br>from einops import rearrange<br><br>class MambaLayer(nn.Module):<br>    def __init__(self, d_model: int = 2048, d_state: int = 16, d_conv: int = 4, expand: int = 2):<br>        super().__init__()<br>        self.d_model = d_model<br>        self.d_inner = expand * d_model<br>        self.d_state = d_state<br><br>        self.in_proj = nn.Linear(self.d_model, self.d_inner * 2, bias=False)<br>        self.conv1d = nn.Conv1d(<br>            in_channels=self.d_inner, out_channels=self.d_inner,<br>            kernel_size=d_conv, groups=self.d_inner, padding=d_conv - 1<br>        )<br>        self.x_proj = nn.Linear(self.d_inner, (self.d_inner // 16) + (self.d_state * 2), bias=False)<br>        self.dt_proj = nn.Linear(self.d_inner // 16, self.d_inner, bias=True)<br><br>        # Transition matrix A initialized per S4D-real formulation (log space)<br>        A = torch.arange(1, self.d_state + 1, dtype=torch.float32).repeat(self.d_inner, 1)<br>        self.A_log = nn.Parameter(torch.log(A))<br>        self.D = nn.Parameter(torch.ones(self.d_inner))<br>        self.out_proj = nn.Linear(self.d_inner, self.d_model, bias=False)<br><br>    def forward(self, u: torch.Tensor) -&gt; torch.Tensor:<br>        batch, seq_len, _ = u.shape<br>        xz = self.in_proj(u)<br>        x, z = xz.chunk(2, dim=-1)<br><br>        x = rearrange(x, &#39;b l d -&gt; b d l&#39;)<br>        x = self.conv1d(x)[:, :, :seq_len]<br>        x = rearrange(x, &#39;b d l -&gt; b l d&#39;)<br>        x = F.silu(x)<br><br>        # Project x to obtain dynamic dt, B, and C<br>        ssm_params = self.x_proj(x)<br>        dt, B, C = torch.split(ssm_params, [self.d_inner // 16, self.d_state, self.d_state], dim=-1)<br>        <br>        # Multiply weights only; kernel adds bias via delta_bias to avoid double counting<br>        dt = F.linear(dt, self.dt_proj.weight)<br><br>        # Hardware-fused kernel: softplus and discretization are fused inside the CUDA kernel<br>        y = selective_scan_fn(<br>            rearrange(x, &#39;b l d -&gt; b d l&#39;),<br>            rearrange(dt, &#39;b l d -&gt; b d l&#39;),<br>            -torch.exp(self.A_log.float()),<br>            rearrange(B, &#39;b l d -&gt; b d l&#39;),<br>            rearrange(C, &#39;b l d -&gt; b d l&#39;),<br>            self.D.float(),<br>            z=rearrange(z, &#39;b l d -&gt; b d l&#39;),<br>            delta_bias=self.dt_proj.bias.float(),<br>            delta_softplus=True<br>        )<br>        return self.out_proj(rearrange(y, &#39;b d l -&gt; b l d&#39;))</pre><blockquote><strong><em>Critical Note on Precision:</em></strong><em> Transition matrix A must be strictly kept in </em><em>float32. Storing or computing continuous-to-discrete exponential updates in </em><em>fp16 can cause instability and numerical collapse during training runs.</em></blockquote><h3>3. Pure SSM vs. Hybrid Configurations</h3><p>Pure SSMs have an inherent computational trade-off: fixed-size hidden states create an information bottleneck. In tasks demanding exact associative recall (e.g., matching UUIDs, copying long telephone numbers, multi-hop document retrieval), pure Mamba models degrade compared to full attention.</p><ul><li><strong>Pure SSM (Mamba-1 / Mamba-2)</strong></li><li><strong>Structure:</strong> 100% recurrent selective blocks without attention heads.</li><li><strong>Best For:</strong> Continuous sensor data, streaming audio, and long-form document summarization.</li><li><strong>Oprational Trade-off:</strong> High throughput with flat O(1) memory per token, but struggles on exact “Needle in a Haystack” and verbatim string lookups at extreme sequence lengths.</li><li><strong>Hybrid SSM-Attention (Jamba, Zamba)</strong></li><li><strong>Structure:</strong> Interleaved layers - typically 1 full attention layer positioned every 4 to 8 SSM blocks.</li><li><strong>Best For:</strong> Complex code generation, multi-hop reasoning agents, and production enterprise RAG.</li><li><strong>Operational Trade-off:</strong> Solves associative copy-recall by retaining exact attention anchors, but reintroduces an explicit (though significantly smaller) KV cache that complicates distributed tensor parallel sharding.</li><li><strong>Linear Attention (RWKV, RetNet)</strong></li><li><strong>Structure:</strong> Relaxed causal attention mathematically rewritten into recurrent updates with fixed decay masks.</li><li><strong>Best For:</strong> Resource-constrained edge hardware and low-latency interactive chat completions.</li><li><strong>Operational Trade-off:</strong> Simplifies hardware mapping, but data-independent decay masks lack the granular token-level selectivity that enables Mamba to discard filler tokens dynamically.</li></ul><pre>def forward_hybrid_block(layer_idx: int, x: torch.Tensor, cache_dict: dict) -&gt; torch.Tensor:<br>    # Illustrative pattern: anchor associative recall with periodic attention<br>    if (layer_idx + 1) % 8 == 0:<br>        return flash_attention_block(x, kv_cache=cache_dict[layer_idx])<br>    <br>    # Process high-throughput tokens via constant-memory selective scan<br>    return mamba_block_selective_scan(x, hidden_state=cache_dict[layer_idx])</pre><h3>4. Hardware Realities: Mamba-1 Scan vs. Mamba-2 Tensor Cores</h3><p>A critical misconception in production optimization is treating all SSM compute identically:</p><ul><li><strong>Mamba-1 is Memory &amp; Vector-Core Bound:</strong> The 1D selective parallel associative scan runs predominantly on standard <strong>CUDA vector ALUs</strong>, not GPU Tensor Cores. Because of this, profiling Mamba-1 with NVIDIA Nsight Compute will show low Tensor Core utilization (sm__pipe_tensor_cycles_active), which is expected behavior.</li><li><strong>Mamba-2 (State Space Duality — SSD):</strong> To exploit Tensor Cores designed for matrix multiplies (GEMMs), Mamba-2 frames the 1D scan as a block-decomposed semi-separable matrix multiply. This allows Mamba-2 to map recurrence directly onto Tensor Cores, getting much closer to FlashAttention-style matmul efficiency.</li></ul><h3>5. Deployment Anti-Patterns</h3><ul><li><strong>Naive Autoregressive PyTorch Loops</strong></li><li><em>The Mistake:</em> Running token-by-token generation via standard Python loops causes severe CPU dispatch latency and breaks GPU execution pipelines.</li><li><em>The Fix:</em> Use the single-step state-update kernels from mamba-ssm or custom Triton generation bindings. Registers do not persist across kernel launches, so intermediate states must be read from and written to HBM via optimized memory paths during generation.</li><li><strong>Global fp16 Precision Mode</strong></li><li><em>The Mistake:</em> Executing the dynamic discretization step A_bar = exp(Δ · A) in half-precision.</li><li><em>The Fix:</em> Use mixed-precision: embed inputs and compute feed-forward projections in bf16, but keep recurrence and discretization strictly in fp32.</li><li><strong>Deploying Pure SSMs for Strict RAG / Exact Extraction</strong></li><li><em>The Mistake:</em> Expecting an SSM with a fixed hidden state vector to reliably reproduce verbatim strings over a 128k context.</li><li><em>The Fix:</em> Use an Attention-SSM Hybrid architecture or deploy an aggressive chunked vector retriever prior to sequence ingestion.</li><li><strong>Padding Tensors in Variable-Length Batches</strong></li><li><em>The Mistake:</em> Applying standard sequence padding across batches, which wastes associative scan compute on empty pad tokens.</li><li><em>The Fix:</em> Flatten sequences into contiguous, ragged 1D arrays using layout schemes similar to FlashAttention’s cu_seqlens.</li></ul><h3>The Verdict on Architecture Shifts</h3><p>The conversation around a single “Transformer Killer” creates a false dichotomy. Production infrastructure is determined by physical hardware balance:</p><ul><li><strong>Attention</strong> trades off memory bandwidth and HBM footprints for lossless, exact in-context associative recall.</li><li><strong>Selective SSMs</strong> trade off exact uncompressed retrieval for fixed-size memory footprints and blazing-fast linear inference throughput.</li></ul><p>The prevailing architectural standard isn’t pure recurrence - it is the <strong>hybrid model</strong>. By pairing selective state spaces with a small number of attention layers, modern hybrids keep most of the linear-time efficiency while recovering much of the exact-recall ability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d20680e7e8c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mixture of Experts (MoE): How Models Like Mixtral Scale Without Scaling Cost]]></title>
            <link>https://medium.com/@atnoforgenai/mixture-of-experts-moe-how-models-like-mixtral-scale-without-scaling-cost-b350e71d25b2?source=rss-36b5ad2df1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b350e71d25b2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[ATNO for GenAI & Agentic AI]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 16:26:01 GMT</pubDate>
            <atom:updated>2026-09-19T16:26:01.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuod2TrlY3BYfjkoWtWziQ.jpeg" /></figure><p>Sparse architectures promise 8x the parameter capacity at dense compute costs. Here is the operational reality of routing, VRAM footprint, and expert collapse.</p><p>The common pitch for Sparse Mixture of Experts (SMoE) sounds like a free lunch: take an 8x7B architecture like Mixtral, route tokens dynamically to only two sub-networks per forward pass, and get the inference latency of a 13B model with the representational capacity of a 47B monster. Marketing decks call it “scaling compute independently of parameter count.”</p><p>In production, that math falls apart fast. While floating-point operations (FLOPs) per token drop precipitously, your memory bandwidth demands do not - every single expert’s weights must reside in high-bandwidth memory (HBM) whether a token visits them or not. If your routing distribution shifts slightly, straggler experts stall pipeline parallelism, batch padding ruins throughput, and high KV-cache overhead turns your low-latency dream into a high-tail-latency nightmare.</p><p>Sparse MoE does not eliminate the cost of scale; it trades compute-bound bottlenecks for memory-capacity and communication-latency bottlenecks.</p><p>This deep dive breaks down the production-grade mechanics of sparse expert routing using Triton and PyTorch, complete with router balancing math, Megatron-LM/vLLM operational patterns, validation benchmarks, and the architectural anti-patterns that quietly degrade expert utilization in live environments.</p><p>🔀 1. Core Architecture &amp; Routing Mental Model</p><p>At its core, a Sparse MoE model replaces standard dense Feed-Forward Network (FFN) blocks with an array of independent FFN “experts,” mediated by a parameterized gating network (router). Rather than passing hidden states through a monolithic multi-layer perceptron, the router calculates a probability distribution across <em>N</em> experts and selectively dispatches each token to the top-<em>k</em> candidates (typically <em>k</em> = 2).</p><p>The remaining active path performs a weighted summation of the selected expert outputs. While self-attention layers remain shared and dense across the entire sequence, the sparsity of the FFN block isolates token representations, forcing specialized parameter sub-spaces without multiplying execution FLOPs per token.</p><p>Architecture Components:</p><ul><li><strong>Shared Self-Attention</strong></li><li>Structural Role: Context aggregation</li><li>Runtime Behavior: Identical to standard dense Transformer</li><li>Memory / Compute Profile: Dense FLOPs, KV-cache bound</li><li><strong>Top-<em>k</em> Router (Gate)</strong></li><li>Structural Role: Dynamic dispatch</li><li>Runtime Behavior: Softmax over normalized linear projection</li><li>Memory / Compute Profile: Negligible compute (O(<em>d</em> · <em>N</em>))</li><li><strong>Expert FFNs (<em>E</em>₁ … <em>Eₙ</em>)</strong></li><li>Structural Role: Domain/feature mapping</li><li>Runtime Behavior: SwiGLU / GeLU projection of routed tokens</li><li>Memory / Compute Profile: Sparse compute, 100% VRAM residency</li><li><strong>Dispatch / Combine Kernel</strong></li><li>Structural Role: Token scatter &amp; gather</li><li>Runtime Behavior: Permutes token tensors by expert index</li><li>Memory / Compute Profile: Communication &amp; memory-bandwidth bound</li><li><strong>Auxiliary Loss Engine</strong></li><li>Structural Role: Load balancing</li><li>Runtime Behavior: Regularizes router entropy during training</li><li>Memory / Compute Profile: Pure scalar overhead during backward pass</li></ul><pre>[ Input Hidden State: x ]<br>                                |<br>             +------------------+------------------+<br>             |                                     |<br>    [ Top-k Gating Router ]                        |<br>             |                                     |<br>    G(x) = TopK(Softmax(x · W_g))                  |<br>             |                                     |<br>    Dispatch Indices &amp; Weights                     |<br>             |                                     |<br>    +--------+--------+                            |<br>    |                 |                            |<br>[ Expert 2 ]     [ Expert 7 ]                      |<br>    |                 |                            |<br>    +--------+--------+                            |<br>             |                                     |<br>   Combined: Σ G(x)_i · E_i(x)                     |<br>             |                                     |<br>             +-----------------&gt; [ + ] &lt;-----------+ (Residual)<br>                                  |<br>                              [ Output ]</pre><p>How Token Routing Works in Practice</p><p>Projection: Hidden state vector <em>x</em> in ℝᵈ enters the layer and is multiplied by gate weight matrix <em>W_g</em> in ℝ^(d × N), producing raw logits:</p><pre>H(x) = x · W_g</pre><p>Raw routing logits are computed via the dot product of the input hidden state and gate weight matrix.</p><p>Noise Injection (Optional for Training): Standard models inject Gaussian noise into logits before gating to prevent early expert collapse:</p><pre>S(x) ~ N(0, σ²)</pre><p>Gaussian noise with zero mean and variance σ² is sampled and added to the gate logits.</p><p>Top-<em>k</em> Selection: The gating engine selects the <em>k</em> indices with the highest scalar values:</p><pre>Indices = argTopK(H(x), k)</pre><p>The router extracts the top-k expert indices with the highest scalar routing logits.</p><p>Softmax Normalization: A softmax is calculated over only the top-<em>k</em> chosen logits, producing normalized dispatch weights that sum to 1.0:</p><pre>G(x)_i = exp(H(x)_i) / sum(exp(H(x)_j) for j in TopK)</pre><p>Gating weight for each selected expert is normalized over the sum of exponentiated logits of only the top-k experts.</p><p>Token Permutation (Scatter): Input tokens are regrouped and scattered into contiguous memory blocks sorted by target expert ID to optimize GEMM execution.</p><p>Weighted Combination (Gather): Token representations pass through their designated expert MLPs, and the outputs are reduced via element-wise multiplication with <em>G</em>(<em>x</em>)ᵢ back into the original sequence dimension.</p><p>💡 Pro Tip: Router softmax normalization should always happen after the top-<em>k</em> truncation, not before. Normalizing across all <em>N</em> experts prior to top-<em>k</em> extraction truncates dynamic range and suppresses gradient signals to boundary experts, accelerating premature expert death.</p><p>⚡ 2. Implementation Workflow: Production Routing Engine</p><p>To run MoE inference without excessive kernel launch overhead, production engines bypass native PyTorch loops in favor of custom fused scatter-gather Triton kernels or batched GEMMs (e.g., via vLLM or NVIDIA FasterTransformer/TensorRT-LLM).</p><p>📦 Setup Checklist</p><ul><li>PyTorch ≥ 2.2.0 with CUDA 12.1+ toolkit</li><li>triton ≥ 2.1.0 for custom fused gating execution</li><li>DeepSpeed ≥ 0.12.0 or Megatron-Core for Expert Parallelism (EP) primitives</li><li>HBM Budget: Minimum 90GB VRAM (e.g., 2x A100–80GB or 1x H100 NVL) to host unquantized Mixtral-8x7B weights</li></ul><p>Below is a production-grade PyTorch implementation of a fused Top-<em>k</em> Router featuring load-balancing auxiliary loss and token capacity limiting:</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class ProductionMoERouter(nn.Module):<br>    def __init__(self, d_model: int, num_experts: int, top_k: int = 2, aux_loss_coef: float = 0.01):<br>        super().__init__()<br>        self.num_experts = num_experts<br>        self.top_k = top_k<br>        self.aux_loss_coef = aux_loss_coef<br>        self.gate = nn.Linear(d_model, num_experts, bias=False)<br><br>    def forward(self, x: torch.Tensor):<br>        # x shape: [batch_size * seq_len, d_model]<br>        logits = self.gate(x) # [total_tokens, num_experts]<br><br>        # Calculate routing probabilities for auxiliary balance loss<br>        routing_weights = F.softmax(logits, dim=-1)<br><br>        # Select top-k experts per token<br>        top_k_weights, top_k_indices = torch.topk(routing_weights, self.top_k, dim=-1)<br><br>        # Re-normalize top-k weights so they sum to 1.0<br>        top_k_weights = top_k_weights / top_k_weights.sum(dim=-1, keepdim=True)<br><br>        # Compute switch/auxiliary load balancing loss to prevent expert collapse<br>        # Encourages uniform token assignment across all available experts<br>        if self.training:<br>            tokens_per_expert = torch.mean(F.one_hot(top_k_indices[:, 0], self.num_experts).float(), dim=0)<br>            router_prob_per_expert = torch.mean(routing_weights, dim=0)<br>            aux_loss = self.aux_loss_coef * self.num_experts * torch.sum(tokens_per_expert * router_prob_per_expert)<br>        else:<br>            aux_loss = torch.tensor(0.0, device=x.device)<br><br>        return top_k_indices, top_k_weights, aux_loss</pre><p>🔑 Notes: The auxiliary loss shown above is the standard formulation introduced in Switch Transformers. Without multiplying by num_experts, the loss scales inversely with expert count, making load balancing virtually ineffective when scaling from 8 to 64 or 128 experts.</p><p>🔬 3. Routing Variants &amp; Dispatch Strategies</p><p>Different MoE architectures handle hardware efficiency, dispatch mechanics, and capacity constraints using distinct routing paradigms.</p><p>Routing Paradigms:</p><ul><li><strong>Token-Choice Routing (e.g., Mixtral, Switch)</strong></li><li>Dispatch Behavior: Tokens pick top-<em>k</em> experts via linear projection</li><li>Best Use Case: General autoregressive text generation</li><li>Caveats: Susceptible to dynamic load imbalance and GPU stragglers</li><li><strong>Expert-Choice Routing (e.g., Zhou et al.)</strong></li><li>Dispatch Behavior: Experts pick top-<em>C</em> tokens globally</li><li>Best Use Case: Fixed-compute environments, offline batching</li><li>Caveats: Can drop tokens; struggles with causal autoregressive decoding</li><li><strong>Shared + Routed Hybrids (e.g., DeepSeek-V2/V3)</strong></li><li>Dispatch Behavior: Fixed base MLP runs alongside top-<em>k</em> sparse experts</li><li>Best Use Case: Preserving common foundational knowledge</li><li>Caveats: Slightly higher non-negotiable baseline compute per token</li></ul><p>For architectures utilizing fine-grained or hybrid routing (like DeepSeek-style shared-expert isolation), token hidden states are split between invariant dense layers and sparse modules:</p><pre># Shared + Isolated Sparse Routing forward pass slice<br>shared_out = self.shared_expert(x)<br>top_k_indices, top_k_weights, _ = self.router(x)<br>sparse_out = self.expert_executor(x, top_k_indices, top_k_weights)<br><br># Combine shared representations with specialized sparse projections<br>final_output = shared_out + sparse_ou</pre><p>💡 Pro Tip: If your inference engine supports DeepSeek-style routing, lean toward models with shared experts. Shared experts anchor fundamental syntax and grammar representations, keeping specialized experts free to model distinct semantic domains. This reduces representation drift and lowers router entropy.</p><p>🛡️ 4. Edge Cases, Expert Dropping &amp; Failure Handling</p><p>When deploying MoE to production clusters under high concurrency, uneven token distribution causes expert imbalance. If Expert 0 receives 80% of tokens in a batch, the GPU hosting Expert 0 hits out-of-memory (OOM) conditions or causes every other GPU in the tensor/expert parallel group to idle waiting for synchronization.</p><pre>Token Ingestion Pipeline<br>           │<br>           ▼<br>[ Router Capacity Check ] ──(Exceeds Capacity Factor?)──► [ Drop or Residual Pass ]<br>           │                                                       │<br>      (Within Limit)                                         (Unprocessed x)<br>           │                                                       │<br>           ▼                                                       ▼<br>[ Forward to Expert MLP ] ───────────────────────────────► [ Add to Final Residual ]</pre><p>Production Fallback Hierarchy</p><p>Capacity Factor Enforcement: Set a strict Token Capacity limit per expert:</p><pre>C = ceil(((Tokens * k) / N) * Capacity_Factor)</pre><p>Capacity per expert is calculated by scaling the uniform average token load by a capacity factor and rounding up.</p><p>Standard production inference sets Capacity Factor in [1.2, 1.5].</p><p>Graceful Dropping (Training): Excess tokens past capacity bypass the expert block via direct residual connection (expert dropout), ensuring tensor operations remain fixed-size.</p><p>Dynamic Re-Routing (Inference): Instead of dropping tokens in user-facing endpoints, excess tokens are dispatched to their (<em>k</em> + 1)-th ranked expert if the secondary expert has remaining buffer headroom.</p><p>Router Temperature Clamping: In high-divergence cases, router temperatures are dynamically scaled down to prevent uniform probability diffusion across all experts.</p><pre>def enforce_expert_capacity(tokens, indices, weights, num_experts, capacity_factor=1.2):<br>    total_tokens, top_k = indices.shape<br>    capacity = int((total_tokens * top_k / num_experts) * capacity_factor)<br><br>    # Track assignments per expert<br>    expert_counts = torch.zeros(num_experts, device=tokens.device, dtype=torch.long)<br>    mask = torch.zeros_like(indices, dtype=torch.bool)<br><br>    for k in range(top_k):<br>        for idx in range(total_tokens):<br>            expert = indices[idx, k]<br>            if expert_counts[expert] &lt; capacity:<br>                expert_counts[expert] += 1<br>                mask[idx, k] = True  # Retain token<br>            else:<br>                # Capacity exceeded: Route to residual or zero weight<br>                weights[idx, k] = 0.0<br><br>    return indices, weights, mask</pre><p>💡 Pro Tip: In customer-facing inference engines, never allow arbitrary token dropping. Dropping a token in an MLP layer causes noticeable syntactic stuttering or hallucinations. Instead, run with variable sequence packing kernels (e.g., FlashInfer, PagedAttention) that eliminate the need for fixed capacity factors during generation.</p><p>🧪 5. Production Validation &amp; QA Checklist</p><p>Validating an MoE deployment requires monitoring both statistical gating health and hardware-level execution metrics.</p><p>Validation Checks:</p><ul><li><strong>Expert Utilization Entropy</strong></li><li>Pass Criteria: <em>H</em> ≥ 0.85 · ln(<em>N</em>)</li><li>Verification Method: Compute Shannon entropy on routing indices across batch</li><li><strong>Dead Expert Detection</strong></li><li>Pass Criteria: Zero experts with &lt; 1.0% assignment</li><li>Verification Method: Continuous histogram logging via Prometheus / Grafana</li><li><strong>All-to-All Latency Ratio</strong></li><li>Pass Criteria: Comm time &lt; 15% of total layer step</li><li>Verification Method: NVIDIA Nsight Systems (nsys) profiling</li><li><strong>KV-Cache / VRAM Headroom</strong></li><li>Pass Criteria: Sustained allocations ≤ 90% capacity</li><li>Verification Method: PagedAttention memory metrics via vLLM engine</li></ul><pre>Routing Distribution Matrix<br>    ───────────────────────────────────────────<br>    Exp 0:  ██████████████ (14%)<br>    Exp 1:  ████████████   (12%)<br>    Exp 2:  ██████████████ (14%)<br>    Exp 3:  █████████████  (13%)<br>    Exp 4:  ████████████   (12%)<br>    Exp 5:  █████████████  (13%)<br>    Exp 6:  ████████████   (12%)<br>    Exp 7:  ░ (0.01% - EXPERT COLLAPSE DETECTED)<br>    ───────────────────────────────────────────</pre><p>🛠️ Pro Debug Tip: If token routing entropy drops suddenly during a long fine-tuning run, check your learning rate schedule. Routers are disproportionately sensitive to high learning rates; if gate weights update too quickly, the system descends into a “rich-get-richer” spiral where early-converging experts capture all tokens, permanently starving remaining experts.</p><p>🚫 4 MoE Anti-Patterns That Break Deployments</p><p>MoE Anti-Patterns:</p><ul><li><strong>Treating MoE VRAM Footprint Like Dense Inference</strong></li><li>Why It Fails: Active parameters run fast, but all weights must stay in VRAM. Loading Mixtral-8x7B requires 90GB+ VRAM, blowing past single-GPU limits.</li><li>Production Fix: Specialize hardware sizing for total parameter residency, utilizing FP8 or INT4 weight-only quantization for expert weights.</li><li><strong>Running Naive All-to-All Over Non-NVLink Fabrics</strong></li><li>Why It Fails: Expert Parallelism relies on cross-node All-to-All token scattering. InfiniBand or low-bandwidth Ethernet stalls GPU execution waiting on network barriers.</li><li>Production Fix: Place expert clusters within NVLink domains, and use Tensor Parallelism or Pipeline Parallelism across cross-node bounds.</li><li><strong>Fine-Tuning Without Router Loss Penalties</strong></li><li>Why It Fails: Task-specific datasets cause routers to route every token to the same 1–2 experts, degrading the architecture to a broken, under-parameterized dense model.</li><li>Production Fix: Keep auxiliary load balancing loss enabled during SFT and LoRA fine-tuning; lock router gate weights if the dataset is small.</li><li><strong>Static Batch Padding Without Token Packing</strong></li><li>Why It Fails: Padding tokens to match max sequence length wastes expert compute on zeros and severely distorts router statistics.</li><li>Production Fix: Implement continuous batching and unpadded ragged tensors via FlashAttention-2 or FlashInfer.</li></ul><p>🔑 The Real Secret to Sparse Models</p><p>Sparse architectures do not give you compute for free; they transform computational problems into distributed data routing problems. If your network fabrics cannot handle high-frequency all-to-all exchanges, or if your inference engine wastes cycles running padded GEMMs, the architectural advantages of sparse routing disappear.</p><ul><li>Size for memory capacity, benchmark for latency: Total parameters dictate your infrastructure hardware footprint; active parameters dictate only your compute execution.</li><li>Keep gating operations simple: Avoid complex non-linear routing networks; single-layer linear projections with auxiliary balancing train more reliably and introduce zero runtime overhead.</li><li>Anchor with shared representations: Hybrid dense-sparse setups provide higher task stability than pure unconstrained sparse routing across all layers.</li><li>Never drop tokens in live inference: Use dynamic sequence packing instead of fixed static capacity bounds when serving real-world requests.</li><li>Monitor routing histograms continuously: An unmonitored router will inevitably suffer from expert collapse under domain-shifted production traffic.</li></ul><p>When architected with hardware-aware routing kernels, balanced capacity factors, and resilient fallback execution, sparse architectures deliver state-of-the-art throughput per dollar -proving that the path to trillion-parameter capabilities lies not in bigger matrices, but in smarter routing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b350e71d25b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rate Limiting and Quota Management for LLM APIs: A Gateway Approach]]></title>
            <link>https://medium.com/@atnoforgenai/rate-limiting-and-quota-management-for-llm-apis-a-gateway-approach-f33b55e8cd1a?source=rss-36b5ad2df1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f33b55e8cd1a</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[llm-api]]></category>
            <dc:creator><![CDATA[ATNO for GenAI & Agentic AI]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 10:28:26 GMT</pubDate>
            <atom:updated>2026-08-02T10:28:26.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>😤 The Problem Nobody Talks About Until It’s Too Late</h3><ul><li>You launch your AI feature it works beautifully in testing</li><li>Day one in production: one power user hammers the endpoint, your OpenAI rate limit kicks in, <strong>everyone else gets errors</strong></li><li>Or worse: a background job goes rogue, burns through your monthly token budget in 6 hours</li><li>Or: a competitor discovers your API and starts scraping it using your credits</li></ul><blockquote><strong>💡 Rate limiting and quota management are not optional features. They are the difference between a product that scales and one that randomly breaks under real-world usage.</strong></blockquote><h3>🤔 Rate Limiting vs Quota Management: The Distinction</h3><blockquote><strong>These are related but different problems. Most teams conflate them and implement neither properly.</strong></blockquote><p><strong>Rate Limiting:</strong></p><ul><li>Controls <strong>how fast</strong> requests can be made</li><li>Measured in: requests per second, requests per minute</li><li>Protects against: traffic spikes, abuse, provider-side rate limits</li><li>Example: max 10 requests/minute per user</li></ul><p><strong>Quota Management:</strong></p><ul><li>Controls <strong>how much</strong> can be consumed over a period</li><li>Measured in: tokens per day, dollars per month, requests per billing cycle</li><li>Protects against: budget overruns, runaway jobs, unfair resource hogging</li><li>Example: max 100k tokens/day per user, max $50/month per team</li></ul><h3>Rate Limiting</h3><ul><li><strong>Time window:</strong> Short duration (seconds or minutes)</li><li><strong>Unit:</strong> Requests per second/minute (RPS/RPM)</li><li><strong>Reset behavior:</strong> Continuously resets using a sliding or rolling window</li><li><strong>Protects against:</strong> Traffic spikes, abuse, and denial-of-service scenarios</li><li><strong>User experience:</strong> Temporary throttling; users can retry after a short wait</li></ul><h3>Quota Management</h3><ul><li><strong>Time window:</strong> Long duration (hours, days, or months)</li><li><strong>Unit:</strong> Tokens, requests, API calls, or monetary budget</li><li><strong>Reset behavior:</strong> Resets on a fixed schedule (daily, monthly, etc.)</li><li><strong>Protects against:</strong> Budget overruns and excessive resource consumption</li><li><strong>User experience:</strong> Enforces hard or soft usage caps until the quota resets or is increased</li></ul><h3>🏗️ Why the Gateway is the Right Place for This</h3><blockquote><strong>You could implement rate limiting in every service individually. You shouldn’t.</strong></blockquote><p><strong>Without a gateway:</strong></p><ul><li>Every microservice reimplements its own rate limiting logic</li><li>Inconsistent rules across services</li><li>No unified view of consumption across your whole system</li><li>A user can bypass per-service limits by hitting multiple services simultaneously</li><li>Per-user tracking is scattered across codebases</li></ul><p><strong>With a gateway:</strong></p><ul><li>One place, one policy, enforced consistently</li><li>Every LLM call passes through no bypass possible</li><li>Global view of consumption: per user, per feature, per team, per model</li><li>Change a limit in one place, applies everywhere immediately</li><li>Audit trail is automatic</li></ul><pre>Service A ──┐<br>Service B ──┼──► LLM Gateway (rate limit + quota engine) ──► OpenAI / Anthropic<br>Service C ──┘                    ↕<br>                          Redis (counters)<br>                          Postgres (quotas + audit)</pre><h3>⚙️ The Core Rate Limiting Algorithms</h3><h4>🪣 Algorithm 1: Token Bucket (Recommended for LLM APIs)</h4><blockquote><strong><em>Not “tokens” as in LLM tokens the classic CS rate limiting concept</em></strong></blockquote><ul><li>Each user/key gets a “bucket” with a max capacity</li><li>Bucket fills at a steady rate (e.g. 10 requests/minute = refill 1 token every 6 seconds)</li><li>Each request costs 1 token from the bucket</li><li>If bucket is empty: request is rejected or queued</li><li>Burst-friendly: a user who hasn’t made requests can accumulate tokens and burst briefly</li></ul><p><strong>Why it fits LLM APIs:</strong></p><ul><li>LLM requests are expensive and variable - you want to allow short bursts but prevent sustained overload</li><li>Maps naturally to provider-side rate limits (OpenAI uses token bucket internally)</li></ul><pre>Bucket capacity : 10<br>Refill rate     : 2 tokens / minute<br>User makes 10 requests in 1 minute → bucket empty → next request rejected<br>User waits 30 seconds → 1 token refilled → 1 request allowed</pre><h4>🏠 Algorithm 2: Fixed Window Counter</h4><ul><li>Divide time into fixed windows (e.g. 1-minute blocks)</li><li>Count requests per window per user</li><li>Reset counter at the start of each new window</li><li>Simple to implement, easy to understand</li></ul><p><strong>The problem:</strong></p><ul><li>Boundary burst: user makes 100 requests at 11:59 PM and 100 more at 12:00 AM-200 requests in 2 seconds, both “within limits”</li><li>Not recommended for strict rate limiting</li></ul><p><strong>When to use it:</strong></p><ul><li>Quota management (daily/monthly budgets reset on a schedule anyway)</li><li>Coarse-grained limits where boundary bursts don’t matter</li></ul><h4>🪟 Algorithm 3: Sliding Window Log</h4><ul><li>Track the exact timestamp of every request</li><li>On each new request: count requests in the last N seconds/minutes</li><li>More accurate than fixed windows -no boundary burst problem</li><li>Higher memory cost: storing timestamps per user</li></ul><p><strong>When to use it:</strong></p><ul><li>Strict per-user rate limits where fairness matters</li><li>Smaller user bases where memory cost is acceptable</li></ul><h4>⚡ Algorithm 4: Leaky Bucket</h4><ul><li>Requests go into a queue (the bucket)</li><li>Queue drains at a fixed rate</li><li>If queue is full: reject the request</li><li>Smooths out bursts-output rate is always steady</li></ul><p><strong>When to use it:</strong></p><ul><li>When you need predictable, even throughput to the LLM provider</li><li>Protecting against thundering herd problems downstream</li></ul><h3>📊 What to Limit: The Dimensions</h3><blockquote><strong><em>Most implementations only rate limit by request count. That’s not enough for LLM APIs.</em></strong></blockquote><p><strong>Dimension 1: Request count</strong></p><ul><li>Simplest to implement</li><li>Doesn’t account for request size one 100k-token request looks the same as one 100-token request</li><li>Good as a first layer</li></ul><p><strong>Dimension 2: Token count (input + output)</strong></p><ul><li>More accurate for LLM cost management</li><li>Problem: you don’t know output tokens until the response completes</li><li>Solution: limit on input tokens upfront, track output tokens post-response and apply to next window</li></ul><p><strong>Dimension 3: Estimated cost ($)</strong></p><ul><li>Convert token usage to dollar cost per model</li><li>Gives a unified limit across models of different prices</li><li>Example: same $10/day limit applies whether user is on GPT-4o or GPT-3.5</li></ul><p><strong>Dimension 4: Concurrent requests</strong></p><ul><li>Limit how many in-flight requests a user/team can have simultaneously</li><li>Prevents one user from holding 50 connections open at once</li><li>Simple to implement with a Redis counter: increment on start, decrement on complete</li></ul><blockquote><strong>💡 The ideal setup layers all four: request rate + token budget + cost quota + concurrency limit. Start with request rate and token budget add the others as you scale.</strong></blockquote><h3>🔑 The Limit Hierarchy: Who Gets Limited How</h3><blockquote><strong>Not all callers are equal. Your rate limiting needs to reflect that.</strong></blockquote><pre>Organization / Account level<br>        ↓<br>    Team level<br>        ↓<br>    User level<br>        ↓<br>   Feature / API key level<br>        ↓<br>   Model level (per-model limits)</pre><p><strong>Example policy:</strong></p><ul><li>Org: 10M tokens/day total across all teams</li><li>Team: 2M tokens/day per team</li><li>User: 100k tokens/day per user</li><li>Feature (background job): 500k tokens/day, max 5 concurrent requests</li><li>Model: GPT-4o limited to 20% of total budget, rest on cheaper models</li></ul><p><strong>Why layered limits matter:</strong></p><ul><li>A single power user can’t exhaust the team quota</li><li>A background job can’t starve real-time user-facing features</li><li>One team can’t consume the entire org’s budget</li><li>Each layer catches what the layer above missed</li></ul><h3>🛠️ Building It: The Implementation</h3><h4>✅ Step 1: Redis as the Counter Store</h4><blockquote><strong><em>Redis is the right tool for rate limit counters. Don’t use Postgres for this.</em></strong></blockquote><ul><li>Sub-millisecond reads and writes</li><li>Atomic increment operations (no race conditions)</li><li>TTL support counters expire automatically</li><li>Supports Lua scripts for atomic multi-key operations</li></ul><p><strong>Basic sliding window in Redis:</strong></p><pre>Key format   : ratelimit:{user_id}:{window_start}<br>Value        : request count (INCR)<br>TTL          : window size + buffer</pre><p><strong>Token count tracking:</strong></p><pre>Key format   : quota:tokens:{user_id}:{date}<br>Value        : cumulative tokens used today (INCR by token count)<br>TTL          : 25 hours (covers timezone edge cases)</pre><h4>✅ Step 2: The Gateway Middleware Flow</h4><p>Every request through the gateway:</p><pre>Incoming request<br>      ↓<br>Extract identity  (user_id, team_id, api_key, feature_tag)<br>      ↓<br>Check concurrency limit  → reject if at max concurrent<br>      ↓<br>Check rate limit  → reject with 429 if over request rate<br>      ↓<br>Check token quota  → reject with 402/429 if over budget<br>      ↓<br>Forward to LLM provider<br>      ↓<br>Response received<br>      ↓<br>Record actual token usage  → update Redis counters + Postgres audit log<br>      ↓<br>Return response to caller</pre><h4>✅ Step 3: Response Headers (Tell Callers What’s Happening)</h4><blockquote><strong>Don’t silently reject. Tell callers their current state on every response.</strong></blockquote><pre>X-RateLimit-Limit          : 100          (requests allowed per window)<br>X-RateLimit-Remaining      : 43           (requests left in current window)<br>X-RateLimit-Reset          : 1719432000   (Unix timestamp when window resets)<br>X-Quota-Tokens-Limit       : 100000       (daily token budget)<br>X-Quota-Tokens-Remaining   : 67234        (tokens left today)<br>X-Quota-Reset              : 1719504000   (when daily quota resets)<br>Retry-After                : 47           (seconds to wait, on 429 response)</pre><h4>✅ Step 4: What to Return When Limits Are Hit</h4><p><strong>HTTP 429 Rate limit exceeded (temporary):</strong></p><p>json</p><pre>{<br>  &quot;error&quot;: &quot;rate_limit_exceeded&quot;,<br>  &quot;message&quot;: &quot;You have exceeded the request rate limit.&quot;,<br>  &quot;limit&quot;: 10,<br>  &quot;window&quot;: &quot;60s&quot;,<br>  &quot;retry_after_seconds&quot;: 23,<br>  &quot;reset_at&quot;: &quot;2025-08-02T14:33:00Z&quot;<br>}</pre><p><strong>HTTP 429 - Quota exhausted (until reset):</strong></p><p>json</p><pre>{<br>  &quot;error&quot;: &quot;quota_exhausted&quot;,<br>  &quot;message&quot;: &quot;Daily token quota reached.&quot;,<br>  &quot;quota_limit&quot;: 100000,<br>  &quot;quota_used&quot;: 100000,<br>  &quot;quota_resets_at&quot;: &quot;2025-08-03T00:00:00Z&quot;,<br>  &quot;upgrade_url&quot;: &quot;https://yourapp.com/upgrade&quot;<br>}</pre><blockquote><strong>💡 Always include </strong><strong>retry_after on rate limit errors. Clients that don&#39;t know when to retry will just hammer your gateway and make the problem worse.</strong></blockquote><h4>✅ Step 5: Soft Limits and Warnings Before Hard Cutoffs</h4><blockquote><strong>A hard cutoff at 100% is a bad user experience. Warn before you cut.</strong></blockquote><ul><li>At <strong>70% of quota</strong>: log internally, flag for monitoring</li><li>At <strong>85% of quota</strong>: return a warning header X-Quota-Warning: 85% on every response</li><li>At <strong>95% of quota</strong>: send user a notification (email, in-app alert)</li><li>At <strong>100% of quota</strong>: enforce the hard limit, return 429</li></ul><p><strong>For high-value users or paying customers:</strong></p><ul><li>Consider a <strong>grace quota</strong> (e.g. 10% overage allowed before hard cutoff)</li><li>Or <strong>burst allowance</strong> that borrows from next period’s quota</li></ul><h3>🚨 Edge Cases That Will Bite You</h3><p><strong>🐛 The output token problem:</strong></p><ul><li>You can check input tokens before the call</li><li>You can’t know output tokens until the response completes</li><li>Solution: reserve a worst-case estimate upfront, reconcile actual usage after</li><li>Or: enforce a max_tokens cap on every request through the gateway</li></ul><p><strong>🐛 Streaming responses:</strong></p><ul><li>Token count isn’t available until the stream ends</li><li>But the request has already been forwarded and is being processed</li><li>Solution: count tokens after streaming completes, apply to next request’s quota check</li><li>Add a concurrent request limit to prevent quota gaming via streaming</li></ul><p><strong>🐛 Clock skew in distributed systems:</strong></p><ul><li>Multiple gateway instances with slightly different clocks can cause window boundary bugs</li><li>Solution: use Redis as the time authority, not server clocks</li></ul><p><strong>🐛 Redis unavailability:</strong></p><ul><li>If Redis is down, do you fail open (allow all requests) or fail closed (reject all)?</li><li>Fail open: you lose rate limiting temporarily but stay available</li><li>Fail closed: you’re safe but your service is down</li><li>Recommended: <strong>fail open with alerts</strong> availability &gt; perfect rate limiting</li></ul><p><strong>🐛 Quota reset timing:</strong></p><ul><li>Users in different timezones expect “daily” to mean their midnight, not yours</li><li>Solution: store quota windows in UTC, but display reset time in user’s timezone</li><li>Or: use rolling 24-hour windows instead of calendar-day resets</li></ul><h3>🔍 Observability for Rate Limiting</h3><p><strong>Metrics to track:</strong></p><ul><li>Rate limit hit rate per user, feature, and endpoint</li><li>Quota utilization: % of budget consumed per user/team/day</li><li>429 error rate as % of total requests</li><li>Time-to-quota-exhaustion: at current pace, when does this user run out?</li><li>Top consumers by token usage (find your power users)</li></ul><p><strong>Alerts to set up:</strong></p><ul><li>Any single user consuming &gt; 20% of org quota in &lt; 1 hour</li><li>Overall 429 rate &gt; 5% of requests (your limits may be too tight)</li><li>Quota exhaustion before 50% of the billing period is over</li><li>Redis latency &gt; 10ms (your rate limiting layer is becoming the bottleneck)</li></ul><h3>🧰 Open Source Tools That Help</h3><ul><li><strong>LiteLLM:</strong> Provides built-in rate limiting and budget management for users and teams.</li><li><strong>Portkey:</strong> Managed AI gateway offering quota controls, rate limiting, and usage analytics.</li><li><strong>Redis + Lua Scripts:</strong> Custom rate limiting using Redis with atomic Lua scripts for accuracy and performance.</li><li><strong>Nginx + </strong><strong>lua-resty-limit:</strong> Implements request-level rate limiting at the reverse proxy layer.</li><li><strong>Upstash Ratelimit:</strong> Serverless, Redis-based rate limiting SDK designed for modern applications.</li><li><strong>Bucket4j:</strong> Java library for token bucket rate limiting, with support for distributed backends like Redis.</li></ul><h3>📋 The Rate Limiting Policy Template</h3><blockquote><strong>Define this before you write a single line of code.</strong></blockquote><pre>Per-user limits<br>  Request rate    : 20 requests / minute<br>  Token budget    : 50,000 tokens / day<br>  Concurrency     : 3 simultaneous requests max<br>  Cost cap        : $2.00 / day<br><br>Per-team limits<br>  Token budget    : 500,000 tokens / day<br>  Cost cap        : $20.00 / day<br><br>Per-feature limits<br>  Background jobs : 5 req/min, 100k tokens/day, 2 concurrent max<br>  Real-time chat  : 30 req/min, priority queue<br>  Bulk exports    : 1 req/min, queued not rejected<br><br>Model-specific limits<br>  GPT-4o / Opus   : 20% of total budget<br>  Fallback models : unlimited within total budget<br><br>Breach behavior<br>  At 85% quota   : warning header added to responses<br>  At 95% quota   : user notification sent<br>  At 100% quota  : hard reject with 429 + upgrade prompt<br>  Rate exceeded  : 429 with Retry-After header</pre><h3>✅ The Implementation Checklist</h3><p><strong>Before launch:</strong></p><ul><li>Per-user request rate limit in place</li><li>Per-user daily token quota tracked in Redis</li><li>429 responses include Retry-After and quota reset time</li><li>Warning headers added at 85% quota consumption</li><li>Hard spend cap set at provider dashboard level (last line of defense)</li><li>Concurrency limit per user implemented</li></ul><p><strong>At launch:</strong></p><ul><li>Monitoring dashboard showing quota utilization in real time</li><li>Alert on any user consuming &gt; 20% of org quota rapidly</li><li>Alert if Redis rate limit layer latency spikes</li></ul><p><strong>Post launch:</strong></p><ul><li>Review top consumers weekly right-size your limits based on real data</li><li>Add model-level limits once you have routing in place</li><li>Implement grace quotas for paying customers before they ask for it</li></ul><h3>🏁 Final Thought</h3><blockquote><strong>Your LLM provider already rate limits you. If you don’t rate limit your users, you’re just passing that pain downstream unpredictably, unfairly, and at the worst possible moment.</strong></blockquote><ul><li>The gateway is the only place you can enforce this consistently and globally</li><li>Rate limiting is not about being restrictive it’s about being <strong>fair and predictable</strong></li><li>A user who hits a clear, documented limit at 429 with a Retry-After header has a <strong>better experience</strong> than a user who gets mysterious errors because someone else consumed the budget first</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f33b55e8cd1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hardest Part of Agentic AI is Not the AI -It’s State Management]]></title>
            <link>https://medium.com/@atnoforgenai/the-hardest-part-of-agentic-ai-is-not-the-ai-its-state-management-96aa41014014?source=rss-36b5ad2df1f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/96aa41014014</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[context-engineering]]></category>
            <dc:creator><![CDATA[ATNO for GenAI & Agentic AI]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 17:06:55 GMT</pubDate>
            <atom:updated>2026-06-07T17:06:55.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RICqTDgdi6PLPKW8trwlJg.png" /></figure><ul><li>Most developers building AI agents spend 20% of their time on the AI part</li><li>The other 80% is spent on: <strong>where does the data live, how does it flow, and what happens when it breaks</strong></li><li>The LLM is the easy part , it’s a stateless function call</li><li><strong>State</strong> is what makes agentic systems genuinely hard</li></ul><blockquote>💡 An agent without proper state management is just an expensive chatbot that occasionally does things , and occasionally does the wrong things twice.</blockquote><h3>🤔 What Even is “State” in an Agentic System?</h3><p>State is <strong>everything your agent needs to remember, track, and act on, </strong>across time, across steps, and across failures.</p><p><strong>State includes:</strong></p><ul><li>📋 The original user goal and intent</li><li>🔢 Current step in a multi-step workflow</li><li>🧠 What the agent has already done</li><li>📦 Outputs from previous steps</li><li>🛠️ Which tools have been called and what they returned</li><li>❌ What failed and how many times it’s been retried</li><li>👤 User context, preferences, and session history</li><li>⏳ Time-sensitive data: deadlines, expiry, rate limits</li></ul><blockquote>💡 If your agent crashes at step 4 of 7, state determines whether it restarts from scratch or picks up where it left off.</blockquote><h3>🗂️ The Four Types of State Every Agent Deals With</h3><h3>1️⃣ Ephemeral State (In-memory, lives for one run)</h3><ul><li>Variables held in memory during a single agent execution</li><li>Lost the moment the run ends, errors out, or the process restarts</li><li>Examples: intermediate LLM outputs, temp calculations, local tool results</li></ul><p><strong>The risk:</strong></p><ul><li>99% of early agentic apps store everything here</li><li>A timeout, crash, or cold start wipes it completely</li><li>No recovery, no resumability, no audit trail</li></ul><h3>2️⃣ Session State (Lives for a user session or conversation)</h3><ul><li>Tracks context within a single user interaction or job</li><li>Needs to survive across multiple agent steps within one session</li><li>Examples: conversation history, user’s stated preferences, files uploaded</li></ul><p><strong>Storage options:</strong></p><ul><li>Redis with a TTL (fast, automatic expiry)</li><li>In-memory store for single-process deployments</li><li>Database row keyed by session_id</li></ul><p><strong>The risk:</strong></p><ul><li>Session state that grows unboundedly blows up your context window</li><li>Agents passing raw conversation history instead of structured summaries is a silent killer</li></ul><h3>3️⃣ Workflow State (Lives for the duration of a long-running job)</h3><ul><li>Tracks the progress of a multi-step agentic workflow</li><li>Must survive crashes, retries, and restarts</li><li>Examples: which tasks are done, pending, or failed , what data has been collected</li></ul><p><strong>Storage options:</strong></p><ul><li>Postgres or DynamoDB with explicit status columns</li><li>A workflow engine (Temporal, LangGraph, Inngest)</li><li>A simple state machine persisted to a database</li></ul><p><strong>The risk:</strong></p><ul><li>This is where most production agents fail</li><li>Without durable workflow state, every failure means starting over</li><li>Partial completions with no record lead to duplicate actions (emails sent twice, payments charged twice)</li></ul><h3>4️⃣ Long-term Memory (Lives beyond a single session)</h3><ul><li>Persisted knowledge about a user, entity, or domain</li><li>Enables personalization, learning, and context continuity over days/weeks</li><li>Examples: user preferences, past decisions, learned facts, entity relationships</li></ul><p><strong>Storage options:</strong></p><ul><li>Postgres for structured memory</li><li>Vector DB (pgvector, Qdrant) for semantic recall</li><li>A hybrid: structured facts + embedding-based retrieval</li></ul><p><strong>The risk:</strong></p><ul><li>Memory that’s never pruned grows stale and starts misleading the agent</li><li>Retrieving the wrong memory is worse than retrieving no memory</li><li>No expiry or versioning strategy = garbage accumulating over time</li></ul><h3>🔄 The State Lifecycle: What Actually Happens</h3><pre>User triggers task<br>       ↓<br>Workflow state created  ←── persisted to DB immediately<br>       ↓<br>Agent Step 1 executes<br>       ↓<br>Output written to workflow state  ←── before moving to Step 2<br>       ↓<br>Agent Step 2 reads state  ←── never assumes previous step&#39;s memory<br>       ↓<br>       ... continues ...<br>       ↓<br>Step N fails<br>       ↓<br>Error written to state  ←── with retry count and failure reason<br>       ↓<br>Retry from last checkpoint  ←── not from the beginning<br>       ↓<br>Workflow completes → state archived</pre><blockquote>💡 The rule: <strong>write state before you act, not after.</strong> If you write after, a crash between action and write means the action happened but the state doesn’t know it.</blockquote><h3>💥 The State Bugs That Will Break Your Production Agent</h3><p><strong>🐛 Bug 1: The Amnesia Agent</strong></p><ul><li>Agent completes Step 3, crashes, restarts, starts from Step 1</li><li>Emails get sent twice, API calls duplicated, payments charged twice</li><li>Fix: <strong>checkpoint after every step</strong>, check for completion before executing</li></ul><p><strong>🐛 Bug 2: The Context Avalanche</strong></p><ul><li>Agent passes the full raw conversation history to every sub-agent</li><li>By Step 6, the context window is 80k tokens of noise</li><li>Latency spikes, costs explode, relevant signal is buried</li><li>Fix: <strong>summarize intermediate outputs</strong>, pass structured state not raw history</li></ul><p><strong>🐛 Bug 3: Stale State</strong></p><ul><li>Agent reads from state that was written 20 minutes ago during a long workflow</li><li>External data (prices, availability, user input) has changed</li><li>Agent acts on outdated information confidently</li><li>Fix: <strong>timestamp every state write</strong>, validate time-sensitive data before acting</li></ul><p><strong>🐛 Bug 4: Concurrent Write Conflicts</strong></p><ul><li>Two parallel agents write to the same state object simultaneously</li><li>One overwrites the other silently</li><li>Fix: <strong>optimistic locking</strong> or <strong>append-only state logs</strong> for parallel workflows</li></ul><p><strong>🐛 Bug 5: The Invisible Partial Completion</strong></p><ul><li>Agent successfully calls an external API (sends email, charges card)</li><li>Then fails before writing the result to state</li><li>On retry, it calls the API again</li><li>Fix: <strong>idempotency keys</strong> on all external actions, check-then-act pattern</li></ul><p><strong>🐛 Bug 6: Memory Poisoning</strong></p><ul><li>Agent retrieves a stale or incorrect long-term memory</li><li>Uses it as ground truth for the rest of the workflow</li><li>Confidently does the wrong thing</li><li>Fix: <strong>confidence scoring on memory retrieval</strong>, expiry dates on stored facts</li></ul><h3>🏗️ Designing State the Right Way</h3><h3>✅ Rule 1: Make State Explicit and External</h3><ul><li>Never rely on in-process variables for anything that matters</li><li>State lives in a database, not in your agent’s “memory”</li><li>Every meaningful state transition is a DB write</li><li>If you can’t query your state store to answer “what is this agent currently doing?”, your state design is wrong</li></ul><h3>✅ Rule 2: Use a State Machine</h3><blockquote><em>An agent workflow without a state machine is just hope-driven development.</em></blockquote><ul><li>Define your states explicitly:</li><li>pending → running → completed / failed / awaiting_human</li><li>Every transition is explicit and logged</li><li>Illegal transitions are rejected, an agent can’t jump from pending to completed without going through running</li></ul><p><strong>Minimal workflow state schema:</strong></p><pre>{<br>  &quot;workflow_id&quot;: &quot;wf_abc123&quot;,<br>  &quot;status&quot;: &quot;running&quot;,<br>  &quot;current_step&quot;: 3,<br>  &quot;total_steps&quot;: 7,<br>  &quot;steps&quot;: [<br>    { &quot;step&quot;: 1, &quot;status&quot;: &quot;completed&quot;, &quot;output&quot;: { ... }, &quot;completed_at&quot;: &quot;...&quot; },<br>    { &quot;step&quot;: 2, &quot;status&quot;: &quot;completed&quot;, &quot;output&quot;: { ... }, &quot;completed_at&quot;: &quot;...&quot; },<br>    { &quot;step&quot;: 3, &quot;status&quot;: &quot;running&quot;, &quot;started_at&quot;: &quot;...&quot;, &quot;retry_count&quot;: 0 }<br>  ],<br>  &quot;created_at&quot;: &quot;...&quot;,<br>  &quot;updated_at&quot;: &quot;...&quot;<br>}</pre><h3>✅ Rule 3: Checkpoints Are Non-Negotiable</h3><ul><li>Write a checkpoint <strong>after every meaningful step completes</strong></li><li>Before retrying a failed step, check: did it already succeed?</li><li>Before calling an external service, check: did we already call it in this workflow?</li><li>Checkpoints are cheap. Duplicate actions in production are not.</li></ul><h3>✅ Rule 4: Idempotency on Every External Action</h3><ul><li>Every tool call that touches the outside world needs an idempotency key</li><li>Format: workflow_id + step_id + action_type</li><li>On retry: same key = same result, no duplicate action</li><li>This applies to: emails, payments, API writes, database inserts, webhook calls</li></ul><h3>✅ Rule 5: Separate Read State from Write State</h3><ul><li>What the agent <strong>reads</strong> to make decisions: user goal, preferences, context, retrieved memory</li><li>What the agent <strong>writes</strong> as it progresses: step outputs, tool results, errors</li><li>Mixing them creates race conditions in parallel workflows and makes debugging painful</li><li>In practice: read from a snapshot at workflow start, write to a mutable log</li></ul><h3>✅ Rule 6: Context Window is Not State</h3><blockquote><em>This is the most common mistake in early agentic systems.</em></blockquote><ul><li>Developers treat the LLM’s context window as the “memory” of the agent</li><li>It’s not, it’s a temporary input buffer that disappears after the call</li><li>Anything important that comes out of an LLM call must be <strong>explicitly persisted</strong></li><li>Your state store is the source of truth. The context window is just the agent’s working memory for one call.</li></ul><h3>🧰 The State Management Toolkit</h3><p><strong>Workflow state + durability</strong> → <strong>Temporal</strong></p><ul><li>Battle-tested</li><li>Handles retries, timeouts, and versioning</li><li>Ideal for long-running, reliable workflows</li></ul><p><strong>Lightweight workflow state</strong> → <strong>Inngest</strong></p><ul><li>Developer-friendly</li><li>Great for asynchronous AI workflows</li><li>Simpler setup than full workflow engines</li></ul><p><strong>Graph-based agent state</strong> → <strong>LangGraph</strong></p><ul><li>Built specifically for stateful agent loops</li><li>Supports checkpointing and recovery</li><li>Well-suited for multi-step AI agents</li></ul><p><strong>Fast session state</strong> → <strong>Redis</strong></p><ul><li>Sub-millisecond reads</li><li>TTL (time-to-live) support</li><li>Excellent for caching and temporary session data</li></ul><p><strong>Durable structured state</strong> → <strong>PostgreSQL</strong></p><ul><li>Reliable and mature relational database</li><li>Queryable and highly flexible</li><li>A strong default choice for application state</li></ul><p><strong>Semantic/long-term memory</strong> → <strong>pgvector</strong> + <strong>PostgreSQL</strong></p><ul><li>Combines vector search with structured data</li><li>Enables semantic retrieval and memory recall</li><li>Keeps embeddings and application data in one system</li></ul><p><strong>Advanced memory layer</strong> → <strong>Mem0</strong></p><ul><li>Purpose-built for agent memory</li><li>Handles memory storage, updates, and retrieval</li><li>Reduces the need to build custom memory management logic from scratch</li></ul><h3>🔍 Observability for State</h3><blockquote><em>If you can’t inspect state at any point in time, you can’t debug your agent.</em></blockquote><p><strong>What to log for every state transition:</strong></p><ul><li>workflow_id and step_id</li><li>Previous state and new state</li><li>Timestamp and duration</li><li>Which agent triggered the transition</li><li>Token usage and cost for that step</li><li>Any errors or warnings</li></ul><p><strong>What you want to be able to answer:</strong></p><ul><li>What was this agent doing at 2:47 PM yesterday?</li><li>Why did workflow wf_abc123 fail at step 4?</li><li>How many workflows are currently stuck in running for more than 10 minutes?</li><li>Which step in our pipeline has the highest failure rate?</li></ul><blockquote>💡 Build a simple admin view that shows live workflow state. You will use it every single day in production.</blockquote><h3>🆚 State Management: Naive vs Production</h3><p><strong>Storage</strong></p><ul><li><strong>Naive approach:</strong> In-memory variables</li><li><strong>Production approach:</strong> External database (e.g., <strong>PostgreSQL</strong> or <strong>Redis</strong>)</li></ul><p><strong>Failure recovery</strong></p><ul><li><strong>Naive approach:</strong> Restart from the beginning after failures</li><li><strong>Production approach:</strong> Resume from the last checkpoint</li></ul><p><strong>Duplicate actions</strong></p><ul><li><strong>Naive approach:</strong> Duplicate actions can happen silently</li><li><strong>Production approach:</strong> Prevent duplicates using idempotency keys</li></ul><p><strong>Context passing</strong></p><ul><li><strong>Naive approach:</strong> Pass raw conversation history</li><li><strong>Production approach:</strong> Use structured state summaries</li></ul><p><strong>Visibility</strong></p><ul><li><strong>Naive approach:</strong> Rely on print statements for debugging</li><li><strong>Production approach:</strong> Maintain full traces with a state timeline</li></ul><p><strong>Concurrency</strong></p><ul><li><strong>Naive approach:</strong> Susceptible to race conditions</li><li><strong>Production approach:</strong> Use optimistic locking or append-only patterns</li></ul><p><strong>Memory</strong></p><ul><li><strong>Naive approach:</strong> Limited to the current context window</li><li><strong>Production approach:</strong> Persisted and retrievable memory storage</li></ul><h3>✅ The State Management Checklist</h3><p><strong>Before you build:</strong></p><ul><li>Defined all workflow states and valid transitions</li><li>Chosen an external state store (not in-memory)</li><li>Decided what gets checkpointed and when</li></ul><p><strong>Before you ship:</strong></p><ul><li>Every external action has an idempotency key</li><li>Workflows can resume from any completed checkpoint</li><li>State transitions are logged with timestamps</li><li>Stuck workflow detection is in place (jobs running &gt; N minutes)</li></ul><p><strong>In production:</strong></p><ul><li>Alert on workflows stuck in running for too long</li><li>Monitor state store latency, slow state reads slow your entire agent</li><li>Run a weekly audit: how many workflows completed vs failed vs abandoned?</li></ul><h3>🏁 Final Thought</h3><ul><li>LLMs are getting better every month, the model problem is being solved for you</li><li>State management is a <strong>software engineering problem, </strong>it always has been and always will be</li><li>The agents that work reliably in production are not the ones with the cleverest prompts</li><li>They are the ones built by engineers who took state <strong>as seriously as they took the AI</strong></li></ul><p><em>Get the state right. Everything else is just prompting.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96aa41014014" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>