<?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 Srivatsa Narasimha on Medium]]></title>
        <description><![CDATA[Stories by Srivatsa Narasimha on Medium]]></description>
        <link>https://medium.com/@srivatsa.n63?source=rss-22246753979c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XDXBc9B5ufJmXl1A</url>
            <title>Stories by Srivatsa Narasimha on Medium</title>
            <link>https://medium.com/@srivatsa.n63?source=rss-22246753979c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:33:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srivatsa.n63/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AI Agents from Scratch, Part 5: Short-Term Memory]]></title>
            <link>https://medium.com/@srivatsa.n63/ai-agents-from-scratch-part-5-short-term-memory-b92a5d69ac99?source=rss-22246753979c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b92a5d69ac99</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Srivatsa Narasimha]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 19:34:36 GMT</pubDate>
            <atom:updated>2026-11-08T19:34:36.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETl9Zj7zrcCCNU5hmFYBAQ.png" /></figure><p>If you have spent a long afternoon with a coding assistant, you have probably met this moment. Early on you told it that it must never touch the payments module. Forty file reads later, it opens the payments module with great enthusiasm. Some tools warn you first: Claude Code shows how much room is left before it compacts the conversation. What happened is mundane: the assistant&#39;s desk filled up, and your note about the payments module fell off the back.</p><p>Researchers are still working out how to forget well. On 6 October 2026, Jan-Peter Franke posted <a href="https://arxiv.org/abs/2610.10590">Agent-Controlled Forgetting for Tool-Using Agents</a> on arXiv: the AI agent itself shrinks old tool outputs into short notes and can restore the originals from an archive. On a debugging task it roughly halved the total input; on an app-building task it saved nothing. So the right amount of forgetting depends on the job.</p><p>A quick recap. In <a href="https://medium.com/p/f7f584a3ba0d">Part 4</a> we taught our agent to plan: write the whole plan first, run the steps without calling the model, and re-plan when a step fails. Every part so far quietly assumed one thing. Whenever we call the model, it gets to see the whole trajectory: every thought, every action and every observation since the start. Today we take that assumption away.</p><p>So this part answers a question that sounds like a fortune cookie: what should an agent forget? Get it wrong in one direction and the agent crashes halfway through a task with a &quot;prompt is too long&quot; error, like a goldfish that files bug reports. Get it wrong in the other direction and it forgets the one fact it needed, like me walking into the kitchen with great purpose and then standing there holding a spoon. By the end, tiny_agent.py will have a memory manager, and three forgetting strategies will race to find a bad deploy in a pile of logs.</p><h4>The desk and the sticky notes</h4><p>A language model (the text predictor behind every chat assistant) remembers nothing between calls. Each time the agent loop asks it for the next action, we hand it a fresh stack of paper: the instructions, the tool descriptions, the question, and the story so far. The model reads the stack, writes one reply, and forgets everything. If the agent seems to remember what it did ten steps ago, that is only because we put those ten steps back on the stack.</p><p>The stack is measured in tokens. A token is a chunk of text, often a short word or a piece of a longer one; in English, one token is roughly four characters. The context window is the largest stack the model accepts in one call, counted in tokens, and the reply has to fit in it too. Everything the agent knows right now has to sit inside that window, which is why people call it the agent&#39;s short-term memory, or working memory. Long-term memory, the filing cabinet the agent can search later, gets its own part in this series.</p><p>Picture the window as a desk. Each step of the loop drops a new pile on it: a thought, an action, and an observation (the tool&#39;s result). Thoughts and actions are small. Observations are the problem, because one log page or one web page can be bigger than everything else combined. When the desk is full, you have three honest options:</p><ul><li><strong>Do nothing.</strong> Send everything until the provider refuses the request, then stop.</li><li><strong>Sliding window.</strong> Push the oldest piles off the desk until the rest fits.</li><li><strong>Observation masking.</strong> Replace each bulky old printout with a sticky note that says what was there and how big it was, keep every thought and action, and only push piles off the desk when even that is not enough.</li></ul><p>The animation below runs all three on the same task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*OG0uenFG9qYV3e2hHkNawg.gif" /><figcaption><em>The same incident hunt under three strategies. Doing nothing overflows on turn 5, the sliding window keeps dropping old steps (and with them the ticket), and masking shrinks old log pages into green sticky notes</em></figcaption></figure><h4>How it works</h4><p>On turn t the loop builds a prompt of size P_t. It holds a fixed preamble of T_pre tokens (instructions, tool descriptions and the question) plus every earlier step, where step i costs τ_i tokens. The request only goes through if the prompt leaves room for the reply: W is the context window and R is the number of tokens we reserve for the model&#39;s answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*kf2XMx63DVYCboDN4xKeGA.png" /></figure><p>The sum only ever grows, so without help every agent eventually breaks this rule. In the demo below, W is 2,000 tokens and R is 300, which leaves a budget of 1,700. The preamble costs 179 tokens, reading the ticket adds 114, and each log page adds roughly 580 to 640, because logs are mostly timestamps and hex ids, which chop into many small tokens. The prompt goes 179, 293, 934, 1,543, and then 2,169 on turn five, which is over the budget.</p><p>There is a second, quieter cost. If each step adds about m tokens, the total number of tokens you pay to send over n turns is roughly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*eAAKDXb5Jfhb6hsqwsuoFA.png" /></figure><p>That second term grows with n squared. You pay for the first log page again on every later turn, so a 30-step agent pays for its first observation 29 times. (Prompt caching softens this, and it gets its own part later.) That is why the code below logs the total tokens sent as well as the largest prompt.</p><p>Each strategy gets the full trajectory and returns a smaller view for this turn only; the full record is never edited. Doing nothing stops with an overflow, as a real provider would. The sliding window deletes whole steps from the front and leaves a one-line note saying how many are gone. Masking swaps the oldest observations for a note like &quot;[observation elided to save context: 587 tokens]&quot;, always keeps the newest two in full, and deletes whole steps only if that is still too big.</p><p>Masking works because of something we built in <a href="https://medium.com/p/7195a44864f5">Part 3</a>. In a ReAct trace the thoughts are the agent&#39;s own notes: &quot;the ticket says errors started at 14:32&quot;, &quot;page 3 shows deploy d-8801 at 11:45&quot;. They are tiny compared to the pages they summarize. Masking throws away the bulky evidence and keeps the conclusions, like copying the one highlighted line before binning the printout.</p><p>The test task is a toy incident. The agent must find the deploy that went out just before checkout started failing. It has two tools: get_ticket reads the ticket and its start time, and read_log returns one hour of checkout log per page. The model is a scripted stand-in that reads only the prompt string, like a real model would, and writes each new fact once, in the thought right after it learns it. Here is the fixed incident with a 2,000-token window:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzBthhcPptyiPebuKyXSHQ.png" /></figure><p>The sliding window got the right answer, but look at how. Every time the ticket step slid off the desk, the agent no longer knew when the errors started, so it read the ticket again. Two rereads, plus one log page that masking never needed, cost three extra tool calls and 45% more tokens. I know the feeling. I reread the same chat thread three times a day.</p><p>One incident proves nothing, so I generated 200 random incidents (6 to 12 log pages, 12 to 24 lines per page, 2 to 5 deploys) and ran each strategy at window sizes from 1,000 to 6,000 tokens:</p><pre>import functools, json, statistics as st<br>import tiny_agent as ta<br>ta.count_tokens = functools.lru_cache(maxsize=None)(ta.count_tokens)   # speed only<br>budgets=list(range(1000,6001,250)); N=200<br>res={}<br>for strat in (&quot;none&quot;,&quot;window&quot;,&quot;mask&quot;):<br>    for B in budgets:<br>        oks=0; toks=[]; steps=[]; alls=[]<br>        for seed in range(N):<br>            t,ok,_=ta.run_incident(strat,B,seed=seed)<br>            oks+=ok; alls.append(len(t.steps))<br>            if ok: toks.append(sum(c[&quot;sent&quot;] for c in t.context_log)); steps.append(len(t.steps))<br>        res[f&quot;{strat}|{B}&quot;]=(oks/N, st.mean(toks) if toks else None, st.mean(steps) if steps else None)<br>        print(strat,B,res[f&quot;{strat}|{B}&quot;], flush=True)<br>json.dump(res,open(&quot;sweep.json&quot;,&quot;w&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*aV8JCl1BcRoEiIiNfxrkjQ.png" /><figcaption><em>Share of 200 random toy incidents solved correctly at each window size, with a scripted stand-in model and the rough token counter</em></figcaption></figure><p>Doing nothing climbs slowly, because it only wins when the entire hunt fits, and the longest incidents do not fit even at 6,000 tokens, where it solves 93.5%. The other two jump between 1,000 and 1,500 tokens. Below about 1,250, the preamble plus even a single log page does not fit, so both are forced to cut down the very page they are reading. Above that, masking is ahead at every size: 96.5% against 88.5% at 1,500 tokens, 99.5% against 95% at 2,000, and 100% from 2,500 onwards. Every sliding-window failure from 2,000 tokens up is the same comedy: it forgets the start time, rereads the ticket, loses its place, and asks for pages past the end of the log until the 30-step limit stops it. Even when both succeed, at 2,000 tokens masking needs 6.3 tool calls and 7,713 tokens on average, against 7.2 calls and 8,773 tokens for the window.</p><p>My stand-in model is a very diligent note-taker, and masking leans on those notes. With real models the answer depends on the setup. <a href="https://arxiv.org/abs/2508.21433">The Complexity Trap</a> (Lindenbauer and colleagues, 2025) found that plain observation masking roughly halved a coding agent&#39;s cost on SWE-bench Verified while matching LLM summarization, and a May 2026 study, <a href="https://arxiv.org/abs/2606.00408">Masking Stale Observations Helps Search Agents, Until It Does Not</a>, maps when it helps and when it removes evidence the model needed.</p><h4>Building it from scratch: tiny_agent.py</h4><p>The file is now about 1,000 lines, so here are only the new and changed parts, still using nothing beyond the Python standard library. As in every part, a scripted stand-in plays the model in the demos shown here. Step gets a masked flag, Trajectory gets a log of prompt sizes, and the Agent gets an optional memory that sits between the full trajectory and the policy:</p><pre>@dataclass<br>class Step:<br>    ...                                 # Parts 1 to 4 fields, unchanged<br>    masked: bool = False                # Part 5: observation hidden to save context<br><br>@dataclass<br>class Trajectory:<br>    ...<br>    context_log: list = field(default_factory=list)   # Part 5: prompt size at every turn<br><br>class Agent:<br>    def __init__(self, policy, env=None, max_steps=20, tools=None, stop_on_tool_error=False,<br>                 memory=None):<br>        ...<br>        self.memory = memory                           # Part 5: None = unlimited memory<br><br>    def run(self, goal):<br>        traj = Trajectory(goal)<br>        for _ in range(self.max_steps):<br>            view = traj.steps                                 # Part 5: what the model sees<br>            if self.memory is not None:<br>                try:<br>                    view = self.memory.fit(goal, traj.steps, traj.context_log)<br>                except ContextOverflow as e:<br>                    traj.stopped_because = f&quot;context overflow ({e})&quot;<br>                    return traj<br>            decision = self.policy(goal, view)                # decide<br>            ...                                               # the rest is unchanged</pre><p>The policy never knows the difference: ReActPolicy builds its scratchpad from whatever steps it is handed, and the full trajectory stays intact as an archive. Here is the new section:</p><pre>def count_tokens(text):<br>    &quot;&quot;&quot;A rough tokenizer: a run of letters costs one token per 6 letters, a run of digits<br>    one per 3 digits, any other visible character one token, spaces nothing. Real<br>    tokenizers (byte-pair encoding) differ in detail; for exact counts, pass a real<br>    counter as ContextWindow(measure=...), as the adapters below can.&quot;&quot;&quot;<br>    total = 0<br>    for piece in re.findall(r&quot;[A-Za-z]+|\d+|\S&quot;, text):<br>        if piece[0].isascii() and piece[0].isalpha():<br>            total += -(-len(piece) // 6)               # ceiling division<br>        elif piece[0].isdigit():<br>            total += -(-len(piece) // 3)<br>        else:<br>            total += 1<br>    return total<br><br>class ContextOverflow(Exception):<br>    pass<br><br>def render_step(step):<br>    &quot;&quot;&quot;How a step reads inside a prompt (the ReAct scratchpad lines from Part 3).&quot;&quot;&quot;<br>    return (f&quot;Thought: {step.thought}\nAction: {format_action(step)}\n&quot;<br>            f&quot;Observation: {step.observation}&quot;)<br><br>class ContextWindow:<br>    &quot;&quot;&quot;Decides what the model sees on each turn. The Trajectory keeps every step (the<br>    full record); the policy gets a view that fits in max_tokens minus reserve.<br>      strategy=&quot;none&quot;    send everything; over budget raises ContextOverflow<br>      strategy=&quot;window&quot;  drop the oldest steps until it fits (a sliding window)<br>      strategy=&quot;mask&quot;    swap the oldest observations for a one-line note, keeping every<br>                         thought and action; drop steps only if that is not enough<br>    keep_last: the newest steps whose observations are never masked.<br>    preamble(goal) -&gt; the text sent before the steps (instructions, tools, question).<br>    measure(goal, view) -&gt; exact prompt tokens, when you have a real counter.&quot;&quot;&quot;<br>    def __init__(self, max_tokens, reserve=256, strategy=&quot;mask&quot;, keep_last=2,<br>                 preamble=lambda goal: goal, measure=None):<br>        assert strategy in (&quot;none&quot;, &quot;window&quot;, &quot;mask&quot;) and keep_last &gt;= 1<br>        self.max_tokens, self.reserve = max_tokens, reserve<br>        self.budget = max_tokens - reserve             # the reply needs room too<br>        self.strategy, self.keep_last = strategy, keep_last<br>        self.preamble, self.measure = preamble, measure<br><br>    def estimate(self, goal, view):<br>        return count_tokens(self.preamble(goal)) + sum(count_tokens(render_step(s)) for s in view)<br><br>    def fit(self, goal, steps, log=None):<br>        kept, dropped = list(steps), 0                 # we edit copies, never the Trajectory<br><br>        def view():<br>            note = Step(&quot;(earlier steps)&quot;, f&quot;[{dropped} earlier step{&#39;s&#39; * (dropped != 1)} dropped &quot;<br>                                           &quot;to fit the context window]&quot;)<br>            return ([note] if dropped else []) + kept<br><br>        full = self.estimate(goal, kept)<br>        sizers = [lambda: self.estimate(goal, view())]  # cheap estimate first ...<br>        if self.measure:                               # ... then the exact count, if any<br>            sizers.append(lambda: self.measure(goal, view()))<br>        for size in sizers:<br>            while (need := size()) &gt; self.budget:<br>                if self.strategy == &quot;none&quot;:<br>                    raise ContextOverflow(f&quot;prompt needs {need} tokens, budget is {self.budget}&quot;)<br>                old = [i for i, s in enumerate(kept[:len(kept) - self.keep_last]) if not s.masked]<br>                if self.strategy == &quot;mask&quot; and old:    # mask the oldest full observation<br>                    s = kept[old[0]]<br>                    note = f&quot;[observation elided to save context: {count_tokens(s.observation)} tokens]&quot;<br>                    kept[old[0]] = replace(s, observation=note, masked=True)<br>                elif len(kept) &gt; 1:                    # drop the oldest step entirely<br>                    kept.pop(0)<br>                    dropped += 1<br>                elif kept and len(kept[0].observation) &gt; 80:   # one huge result: keep its ends<br>                    o, q = kept[0].observation, len(kept[0].observation) // 4<br>                    kept[0] = replace(kept[0], observation=f&quot;{o[:q]} [...trimmed...] {o[-q:]}&quot;)<br>                else:<br>                    raise ContextOverflow(f&quot;even a minimal prompt needs {need} tokens, &quot;<br>                                          f&quot;budget is {self.budget}&quot;)<br>        if log is not None:<br>            log.append({&quot;full&quot;: full, &quot;sent&quot;: sizers[-1](), &quot;dropped&quot;: dropped,<br>                        &quot;masked&quot;: sum(s.masked for s in kept)})<br>        return view()</pre><p>Our count_tokens is a deliberately rough stand-in for a real tokenizer, so ContextWindow also accepts an exact measure function and keeps cutting until that count fits too. Each pass of the loop in fit makes the view a notch smaller: mask the oldest full observation, otherwise drop the oldest step, otherwise trim one giant observation to its ends, and if even that fails, raise ContextOverflow. The dropped-steps note matters: without it, the model would read a trajectory that starts in the middle with no idea anything is missing.</p><p>At the bottom of the file, make_incident builds the toy tools, scripted_incident_llm is the stand-in model, and run_incident wires them up. Its measure applies our counter to the exact ReAct prompt, so the number we check is the number we send:</p><pre>def run_incident(strategy, max_tokens, seed=None, reserve=300, keep_last=2, max_steps=30):<br>    &quot;&quot;&quot;One incident hunt under one memory strategy. Returns (trajectory, correct?, memory).&quot;&quot;&quot;<br>    reg, (deploy, start) = make_incident(seed)<br>    memory = ContextWindow(max_tokens, reserve=reserve, strategy=strategy, keep_last=keep_last,<br>                           preamble=lambda g: build_react_prompt(g, [], reg),<br>                           measure=lambda g, view: count_tokens(build_react_prompt(g, view, reg)))<br>    agent = Agent(ReActPolicy(scripted_incident_llm, reg), tools=reg, max_steps=max_steps,<br>                  memory=memory)<br>    t = agent.run(INCIDENT_GOAL)<br>    ok = t.answer is not None and deploy in t.answer and start in t.answer<br>    return t, ok, memory<br><br># in the __main__ block:<br>    print(&quot;\n--- Part 5: short-term memory (context window of 2,000 tokens) ---&quot;)<br>    for strategy in (&quot;none&quot;, &quot;window&quot;, &quot;mask&quot;):<br>        t, ok, memory = run_incident(strategy, max_tokens=2000)<br>        sent = [c[&quot;sent&quot;] for c in t.context_log]<br>        print(f&quot;{strategy}: {&#39;correct&#39; if ok else &#39;WRONG&#39;}, {t.stopped_because} after &quot;<br>              f&quot;{len(t.steps)} tool calls; largest prompt {max(sent)} tokens, {sum(sent)} sent in total&quot;)<br>        print(f&quot;  answer: {t.answer}&quot;)<br>    print(&quot;What the mask strategy showed the model on its last turn (thought | observation):&quot;)<br>    for s in memory.fit(INCIDENT_GOAL, t.steps):<br>        obs = s.observation if len(s.observation) &lt; 34 else s.observation[:31] + &quot;...&quot;<br>        thought = s.thought if len(s.thought) &lt; 56 else s.thought[:53] + &quot;...&quot;<br>        print(f&quot;  {thought:&lt;56} | {obs}&quot;)</pre><p>Running python tiny_agent.py prints the earlier parts&#39; demos, unchanged, and then this:</p><pre>--- Part 5: short-term memory (context window of 2,000 tokens) ---<br>none: WRONG, context overflow (prompt needs 2169 tokens, budget is 1700) after 4 tool calls; largest prompt 1543 tokens, 2949 sent in total<br>  answer: None<br>window: correct, done after 10 tool calls; largest prompt 1585 tokens, 13617 sent in total<br>  answer: Deploy d-8812 (rolled out at 13:52) is the likely cause of INC-4127: checkout errors started at 14:32, 40 minutes later.<br>mask: correct, done after 7 tool calls; largest prompt 1677 tokens, 9417 sent in total<br>  answer: Deploy d-8812 (rolled out at 13:52) is the likely cause of INC-4127: checkout errors started at 14:32, 40 minutes later.<br>What the mask strategy showed the model on its last turn (thought | observation):<br>                                                           | [1 earlier step dropped to fit ...<br>  The ticket says checkout errors started at 14:32. I w... | [observation elided to save con...<br>  Page 1 shows deploy d-8790 at 09:10. Next, page 2.       | [observation elided to save con...<br>  Page 2 has no deploys. Next, page 3.                     | [observation elided to save con...<br>  Page 3 shows deploy d-8801 at 11:45. Next, page 4.       | [observation elided to save con...<br>  Page 4 has no deploys. Next, page 5.                     | {&quot;service&quot;: &quot;checkout&quot;, &quot;page&quot;:...<br>  Page 5 shows deploy d-8812 at 13:52. Next, page 6.       | {&quot;service&quot;: &quot;checkout&quot;, &quot;page&quot;:...</pre><p>On its final turn the masking agent sees four of its six log pages only as sticky notes, and the ticket step is gone entirely, yet every fact it needs is still there, written in its own handwriting: the start time in one thought and the deploy in another.</p><h4>Putting a chat model in the loop</h4><p>The hunt above uses the Part 3 text format, where the whole history is one long prompt string. Most agents today talk to a chat model through native tool calling instead (the <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> way), and there the history is a list of messages: the model&#39;s text and tool_use blocks, and our tool_result blocks. ContextWindow needs no change for that. It still trims the list of steps, and Part 3&#39;s to_react_messages turns whatever steps it kept into messages. A masked step simply becomes a tool_result whose content is the one-line note, which is what Anthropic&#39;s tool result clearing does on the server (more on that below).</p><p>What changes is the measurement. The budget now has to cover the whole request: the system prompt, the tool specs as JSON schemas, and the text inside every message block. chat_request_tokens adds those up with our rough counter, and run_incident_chat points the chat policy from Part 3 at the same incident. Like ReActChatPolicy, it speaks Anthropic&#39;s message shape, and it slots in right after the Part 5 demo:</p><pre># =====================================================================<br># Part 5 (revisited): the same incident hunt with a chat model and native tool calling<br># =====================================================================<br>def _as_react_text(messages):<br>    &quot;&quot;&quot;Write a chat transcript the way Part 3&#39;s scratchpad reads: the scripted incident model<br>    below reuses scripted_incident_llm, so both versions make exactly the same decisions.&quot;&quot;&quot;<br>    lines = [messages[0][&quot;content&quot;]]<br>    for m in messages[1:]:<br>        if m[&quot;role&quot;] == &quot;assistant&quot; and isinstance(m[&quot;content&quot;], list):<br>            text = &quot;&quot;.join(b[&quot;text&quot;] for b in m[&quot;content&quot;] if b[&quot;type&quot;] == &quot;text&quot;)<br>            for b in m[&quot;content&quot;]:<br>                if b[&quot;type&quot;] == &quot;tool_use&quot;:<br>                    lines += [f&quot;Thought: {text}&quot;, f&quot;Action: {b[&#39;name&#39;]}[{json.dumps(b[&#39;input&#39;])}]&quot;]<br>        elif m[&quot;role&quot;] == &quot;user&quot; and isinstance(m[&quot;content&quot;], list):<br>            lines += [f&quot;Observation: {b[&#39;content&#39;]}&quot; for b in m[&quot;content&quot;] if b[&quot;type&quot;] == &quot;tool_result&quot;]<br>        else:                                          # a plain-text note, e.g. dropped steps<br>            lines.append(f&quot;Observation: {m[&#39;content&#39;]}&quot; if m[&quot;role&quot;] == &quot;user&quot; else f&quot;Thought: {m[&#39;content&#39;]}&quot;)<br>    return &quot;\n&quot;.join(lines)<br><br>def scripted_incident_chat_llm(system, tools, messages):<br>    &quot;&quot;&quot;Scripted stand-in for a tool-calling chat model hunting the bad deploy. Like a real one,<br>    it sees only the system prompt, the tool list and the messages (whatever the context window<br>    kept), and replies with a text block (its thought) and a tool_use block, or text alone.&quot;&quot;&quot;<br>    reply = scripted_incident_llm(_as_react_text(messages))   # same decisions as the text model<br>    thought = re.search(r&quot;Thought: (.*)&quot;, reply).group(1)<br>    action = re.search(r&quot;Action: (\w+)\[(.*)\]\s*$&quot;, reply, re.S)<br>    if action.group(1) == &quot;finish&quot;:<br>        return [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: action.group(2)}]<br>    n = sum(m[&quot;role&quot;] == &quot;assistant&quot; for m in messages)<br>    return [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: thought},<br>            {&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: f&quot;toolu_{n + 1:02d}&quot;, &quot;name&quot;: action.group(1),<br>             &quot;input&quot;: json.loads(action.group(2))}]<br><br>def chat_request_tokens(policy, goal, view):<br>    &quot;&quot;&quot;Rough tokens the model reads in one chat request: the system prompt, the tool specs and<br>    the text inside every message block (the JSON wrapping on the wire is left out).&quot;&quot;&quot;<br>    total = count_tokens(policy.system) + count_tokens(json.dumps(policy.tools))<br>    for m in to_react_messages(goal, view):<br>        blocks = m[&quot;content&quot;] if isinstance(m[&quot;content&quot;], list) else [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: m[&quot;content&quot;]}]<br>        for b in blocks:<br>            total += count_tokens({&quot;text&quot;: lambda: b[&quot;text&quot;],<br>                                   &quot;tool_use&quot;: lambda: b[&quot;name&quot;] + json.dumps(b[&quot;input&quot;]),<br>                                   &quot;tool_result&quot;: lambda: b[&quot;content&quot;]}[b[&quot;type&quot;]]())<br>    return total<br><br>def run_incident_chat(strategy, max_tokens, seed=None, reserve=300, keep_last=2, max_steps=30):<br>    &quot;&quot;&quot;run_incident with ReActChatPolicy (Part 3, revisited) as the policy. The ContextWindow<br>    is unchanged: it trims steps, and to_react_messages turns the kept steps into messages, so<br>    a masked step&#39;s tool_result carries the one-line note instead of the log page.&quot;&quot;&quot;<br>    reg, (deploy, start) = make_incident(seed)<br>    policy = ReActChatPolicy(scripted_incident_chat_llm, reg)<br>    memory = ContextWindow(max_tokens, reserve=reserve, strategy=strategy, keep_last=keep_last,<br>                           preamble=lambda g: &quot;\n&quot;.join([policy.system, json.dumps(policy.tools), g]),<br>                           measure=lambda g, view: chat_request_tokens(policy, g, view))<br>    t = Agent(policy, tools=reg, max_steps=max_steps, memory=memory).run(INCIDENT_GOAL)<br>    ok = t.answer is not None and deploy in t.answer and start in t.answer<br>    return t, ok, policy</pre><p>The stand-in, scripted_incident_chat_llm, sees exactly what a real chat model would see: the system prompt, the tool list and whatever messages the window kept. It answers in content blocks, so swapping in Claude changes nothing else. To keep the comparison fair, it makes the same decisions as the text model: _as_react_text writes the messages out as a scratchpad and hands them to scripted_incident_llm. The bottom of the file runs the same 2,000-token hunt:</p><pre>    print(&quot;\n--- Part 5 (revisited): the same hunt with a chat model (context window of 2,000 tokens) ---&quot;)<br>    for strategy in (&quot;none&quot;, &quot;window&quot;, &quot;mask&quot;):<br>        t, ok, chat = run_incident_chat(strategy, max_tokens=2000)<br>        sent = [c[&quot;sent&quot;] for c in t.context_log]<br>        print(f&quot;{strategy}: {&#39;correct&#39; if ok else &#39;WRONG&#39;}, {t.stopped_because} after &quot;<br>              f&quot;{len(t.steps)} tool calls; largest request {max(sent)} tokens, {sum(sent)} sent in total&quot;)<br>    reg = make_incident()[0]<br>    print(f&quot;First request: {sent[0]} tokens as a chat request, &quot;<br>          f&quot;{count_tokens(build_react_prompt(INCIDENT_GOAL, [], reg))} as the Part 3 text prompt&quot;)<br>    print(&quot;Tool calls of the mask run: &quot; + &quot;, &quot;.join(<br>        f&quot;{s.call.name}({s.call.arguments.get(&#39;page&#39;, &#39;&#39;)})&quot;.replace(&quot;()&quot;, &quot;&quot;) for s in t.steps))<br>    print(&quot;The last request of the mask run, block by block:&quot;)<br>    for m in chat.requests[-1]:<br>        blocks = m[&quot;content&quot;] if isinstance(m[&quot;content&quot;], list) else [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: m[&quot;content&quot;]}]<br>        for b in blocks:<br>            body = {&quot;text&quot;: b.get(&quot;text&quot;), &quot;tool_use&quot;: f&quot;{b.get(&#39;name&#39;)} {json.dumps(b.get(&#39;input&#39;))}&quot;,<br>                    &quot;tool_result&quot;: b.get(&quot;content&quot;)}[b[&quot;type&quot;]]<br>            print(f&quot;  {m[&#39;role&#39;]:&lt;9} {b[&#39;type&#39;]:&lt;11} {body if len(body) &lt; 64 else body[:61] + &#39;...&#39;}&quot;)</pre><p>It prints:</p><pre>--- Part 5 (revisited): the same hunt with a chat model (context window of 2,000 tokens) ---<br>none: WRONG, context overflow (prompt needs 2290 tokens, budget is 1700) after 4 tool calls; largest request 1634 tokens, 3373 sent in total<br>window: correct, done after 10 tool calls; largest request 1651 tokens, 13909 sent in total<br>mask: correct, done after 8 tool calls; largest request 1647 tokens, 10854 sent in total<br>First request: 300 tokens as a chat request, 179 as the Part 3 text prompt<br>Tool calls of the mask run: get_ticket, read_log(1), read_log(2), read_log(3), read_log(4), read_log(5), get_ticket, read_log(6)<br>The last request of the mask run, block by block:<br>  user      text        Incident INC-4127: which deploy most likely caused the checko...<br>  assistant text        I need to know when the errors started. I will read the ticket.<br>  assistant tool_use    get_ticket {&quot;id&quot;: &quot;INC-4127&quot;}<br>  user      tool_result [observation elided to save context: 73 tokens]<br>  assistant text        The ticket says checkout errors started at 14:32. I will scan...<br>  assistant tool_use    read_log {&quot;service&quot;: &quot;checkout&quot;, &quot;page&quot;: 1}<br>  user      tool_result [observation elided to save context: 587 tokens]<br>  assistant text        Page 1 shows deploy d-8790 at 09:10. Next, page 2.<br>  assistant tool_use    read_log {&quot;service&quot;: &quot;checkout&quot;, &quot;page&quot;: 2}<br>  user      tool_result [observation elided to save context: 561 tokens]<br>  assistant text        Page 2 has no deploys. Next, page 3.<br>  assistant tool_use    read_log {&quot;service&quot;: &quot;checkout&quot;, &quot;page&quot;: 3}<br>  user      tool_result [observation elided to save context: 584 tokens]<br>  assistant text        Page 3 shows deploy d-8801 at 11:45. Next, page 4.<br>  assistant tool_use    read_log {&quot;service&quot;: &quot;checkout&quot;, &quot;page&quot;: 4}<br>  user      tool_result [observation elided to save context: 568 tokens]<br>  assistant text        Page 4 has no deploys. Next, page 5.<br>  assistant tool_use    read_log {&quot;service&quot;: &quot;checkout&quot;, &quot;page&quot;: 5}<br>  user      tool_result [observation elided to save context: 588 tokens]<br>  assistant text        Page 5 shows deploy d-8812 at 13:52. I need to know when the ...<br>  assistant tool_use    get_ticket {&quot;id&quot;: &quot;INC-4127&quot;}<br>  user      tool_result {&quot;id&quot;: &quot;INC-4127&quot;, &quot;service&quot;: &quot;checkout&quot;, &quot;started&quot;: &quot;14:32&quot;,...<br>  assistant text        The ticket says checkout errors started at 14:32. I will scan...<br>  assistant tool_use    read_log {&quot;service&quot;: &quot;checkout&quot;, &quot;page&quot;: 6}<br>  user      tool_result {&quot;service&quot;: &quot;checkout&quot;, &quot;page&quot;: 6, &quot;of&quot;: 8, &quot;lines&quot;: [&quot;14:10:...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbNsEj32N433neRQM4PxHA.png" /><figcaption><em>Left: the final request of the masking run, with old tool results reduced to notes. Right: tokens per model call with masking, for the Part 3 text prompt and for the chat version</em></figcaption></figure><p>Same incident, same answer, and the same order of finish: doing nothing overflows on turn 5, the sliding window sends 13,909 tokens over 10 tool calls, and masking sends 10,854 over 8. The chat version costs a little more across the board because its fixed part is bigger. Its first request is 300 tokens against 179 for the text prompt, since the tools now travel as JSON schemas next to a system prompt. Those 121 extra tokens bite on the sixth and seventh calls: even with the old log pages masked, the request was still over the 1,700-token budget, so the window dropped the oldest steps as well. Once the step whose thought held the start time fell off, the agent read the ticket a second time, which is the one extra tool call (8 against 7 in the text version). The left panel shows the end state, with the ticket and five log pages reduced to notes and every thought still in place.</p><p>With Claude, the adapter does both jobs: it is the policy, and its count_tokens asks the provider for the exact size of the request it is about to send. It is an untested placeholder, not run for this post, so plug in your key to try it:</p><pre># Real-model version - UNTESTED, plug in your key; not run for this post. The adapter&#39;s<br># count_tokens asks the provider for the exact size of the request it is about to send:<br>#     reg = make_incident()[0]<br>#     policy = AnthropicPolicy(reg)<br>#     Agent(policy, tools=reg, memory=ContextWindow(200_000, reserve=4_096, strategy=&quot;mask&quot;,<br>#                                                   measure=policy.count_tokens))</pre><h4>Plugging in a real model</h4><p>AnthropicPolicy and OpenAIPolicy mport their SDKs lazily and read the key (ANTHROPIC_API_KEY or OPENAI_API_KEY) and model name (TINY_AGENT_MODEL) from environment variables, so the file still runs with only the standard library. The one change is exact counting: each adapter builds its request in one place, and count_tokens sends that request to the provider&#39;s free, rate-limited counting endpoint, client.messages.count_tokens for Anthropic and client.responses.input_tokens.count for OpenAI. Both return input_tokens.</p><pre>class AnthropicPolicy:<br>    ...<br>    def _request(self, goal, steps):<br>        messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}]<br>        ...                                               # replay loop from Part 3, unchanged<br>        return dict(model=self.model, system=self.system, tools=self.tools, messages=messages)<br><br>    def count_tokens(self, goal, steps):<br>        &quot;&quot;&quot;Part 5: exact input tokens of the request (free, rate-limited endpoint).<br>        Use as ContextWindow(..., measure=policy.count_tokens).&quot;&quot;&quot;<br>        return self.client.messages.count_tokens(**self._request(goal, steps)).input_tokens<br><br>    def __call__(self, goal, steps):<br>        resp = self.client.messages.create(max_tokens=self.max_tokens, **self._request(goal, steps))<br>        ...                                               # unchanged<br><br>class OpenAIPolicy:         # UNTESTED placeholder - plug in your key; not run for this post<br>    ...<br>    def _request(self, goal, steps):<br>        items = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}]<br>        ...                                               # replay loop from Part 3, unchanged<br>        return dict(model=self.model, instructions=self.instructions, tools=self.tools, input=items)<br><br>    def count_tokens(self, goal, steps):<br>        &quot;&quot;&quot;Part 5: exact input tokens of the request. Use as ContextWindow(measure=...).&quot;&quot;&quot;<br>        return self.client.responses.input_tokens.count(**self._request(goal, steps)).input_tokens<br><br>    def __call__(self, goal, steps):<br>        resp = self.client.responses.create(**self._request(goal, steps))<br>        ...                                               # unchanged</pre><p>To use one, pass ContextWindow(..., measure=policy.count_tokens) as the Agent&#39;s memory, with the window size from your model&#39;s documentation.</p><p>Next time, tiny_agent.py gets a compactor that writes summaries instead of sticky notes.</p><h4>Why practitioners should care</h4><p>If you build agents on a real API, you are already running one of these strategies, chosen or not. Anthropic&#39;s beta <a href="https://platform.claude.com/docs/en/build-with-claude/context-editing">context editing</a> feature has a tool result clearing strategy that is observation masking done on the server: past a token threshold it replaces the oldest tool results with a placeholder and keeps the three most recent by default. The same page describes server-side compaction, which summarizes the history instead.</p><p>A bigger window does not make the problem go away. <a href="https://arxiv.org/abs/2307.03172">Lost in the Middle</a> (Liu and colleagues, TACL) showed that models use facts at the start and end of a long input much better than facts buried in the middle, and Chroma&#39;s <a href="https://www.trychroma.com/research/context-rot">Context Rot</a> report (Hong, Troynikov and Huber, July 2025) found reliability dropping as inputs grow across 18 models, even on simple tasks. So a desk covered in stale log pages makes the agent worse at reading the one page that matters, long before the provider rejects anything.</p><p>Franke&#39;s agent also made more requests and ran 17% longer while saving tokens. When you tune this in your own agent, measure the three numbers our demo printed: correct answers, tool calls and tokens sent.</p><h4>Closing thoughts</h4><p>Our agent now has a desk with edges. It knows how big each prompt is, it notices when the next one will not fit, and it can choose between forgetting whole chapters or just the bulky appendices. In my toy incidents the sticky-note approach won comfortably, mostly because my stand-in model writes excellent notes, which is more than I can say for myself in most meetings. In Part 6 we will find out whether a summary is a better memory than a pile of sticky notes or just a more confident way to forget.</p><h4>References</h4><ol><li>Jan-Peter Franke. <a href="https://arxiv.org/abs/2610.10590"><em>Agent-Controlled Forgetting for Tool-Using Agents: Reversible Context Curation in Practice</em></a>. arXiv:2610.10590, 6 October 2026.</li><li>Tobias Lindenbauer, Igor Slinko, Ludwig Felder, Egor Bogomolov, Yaroslav Zharov. <a href="https://arxiv.org/abs/2508.21433"><em>The Complexity Trap: Simple Observation Masking Is as Efficient as LLM Summarization for Agent Context Management</em></a>. arXiv:2508.21433, 2025.</li><li>Haoxiang Zhang, Qixin Xu, Zhuofeng Li, Lei Zhang, Pengcheng Jiang, Yu Zhang, Julian McAuley. <a href="https://arxiv.org/abs/2606.00408"><em>Masking Stale Observations Helps Search Agents, Until It Does Not: A Regime Map and Its Mechanism</em></a>. arXiv:2606.00408, May 2026.</li><li>Nelson F. Liu, Kevin Lin, John Hewitt, Ashwin Paranjape, Michele Bevilacqua, Fabio Petroni, Percy Liang. <a href="https://arxiv.org/abs/2307.03172"><em>Lost in the Middle: How Language Models Use Long Contexts</em></a>. Transactions of the Association for Computational Linguistics, 2024 (arXiv 2023).</li><li>Kelly Hong, Anton Troynikov, Jeff Huber. <a href="https://www.trychroma.com/research/context-rot"><em>Context Rot: How Increasing Input Tokens Impacts LLM Performance</em></a>. Chroma Research, 14 July 2025.</li><li>Anthropic. <a href="https://platform.claude.com/docs/en/build-with-claude/context-editing"><em>Context editing</em></a> and <a href="https://platform.claude.com/docs/en/build-with-claude/token-counting"><em>Token counting</em></a>. Claude API documentation.</li><li>OpenAI. <a href="https://developers.openai.com/api/docs/guides/token-counting"><em>Counting tokens</em></a>. OpenAI API documentation.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b92a5d69ac99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents from Scratch, Part 4: Planning]]></title>
            <link>https://medium.com/@srivatsa.n63/ai-agents-from-scratch-part-4-planning-f7f584a3ba0d?source=rss-22246753979c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7f584a3ba0d</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Srivatsa Narasimha]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 19:17:33 GMT</pubDate>
            <atom:updated>2026-11-04T19:17:33.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rAPicTUUFElIWRrGnIMfQ.png" /></figure><p>If you have used a coding assistant this year, you have probably met plan mode. You ask for a feature and, before a single file changes, the assistant hands you a numbered list: read these files, change that function, add a test, run the suite. Copilot, Cursor and Claude Code all ship a version of it. Everyone seems to agree that AI agents should think before they act.</p><p>Then the plan meets reality. A test you did not know about fails, or a file is not where the plan said it would be, and the agent either adapts or marches on with step 4 as if nothing happened. A paper posted on October 15, 2026 measured exactly this. Oriol Miro-Lopez-Feliu and colleagues hid a formal planning model (written in PDDL, a language that spells out what each action needs and what it changes) behind plain-English tasks, so they could check whether every single action an agent took was legal. Their best setup solved 78% of the solvable tasks when it wrote the whole plan offline, but only 40% when it had to act online, step by step, and the agents mostly acted without looking at the state of the world. They also noticed an impossible task in fewer than 10% of episodes.</p><h4>Where we left off</h4><p>In <a href="https://medium.com/p/7195a44864f5">Part 3</a> we taught tiny_agent.py to think out loud. ReAct interleaves a Thought, an Action and an Observation: the model writes a sentence of reasoning before every tool call and reads the result before it picks the next move. It works well, but look at the rhythm. Every action costs one call to the language model (the text-predicting system behind the assistant), and the model never looks further ahead than the next step.</p><h4>Two kinds of travel buddy</h4><p>ReAct is the friend who plans a road trip one exit at a time. At every junction they pull over, reread the whole group chat from the beginning, open the map and choose the next turn. You do get there, and most of the fuel went into map reading. The other friend prints the full route the night before and follows it even when the bridge is closed, because the printout says bridge.</p><p>This part is about the space between those two friends: when an agent should write its plan up front, and what it should do when the world disagrees with that plan.</p><h4>Plans with blanks in them</h4><p>The trick that makes up-front planning possible is that a plan does not need to know the answers yet. It only needs to know where the answers will come from. A recipe can say &quot;pour the sauce from step 2 over the pasta&quot; long before any sauce exists.</p><p>A planning agent writes its plan the same way. Here is the plan my tiny agent writes for the task &quot;Book the cheapest hotel for the Atlantic AI Summit and tell me the total in USD&quot;:</p><pre>#E1 = event_info[{&quot;name&quot;: &quot;Atlantic AI Summit&quot;}]  # where is it, how many nights<br>#E2 = find_hotels[{&quot;city&quot;: &quot;#E1.city&quot;}]  # hotels there, cheapest first<br>#E3 = book_hotel[{&quot;hotel&quot;: &quot;#E2.hotels.0.name&quot;, &quot;nights&quot;: &quot;#E1.nights&quot;}]  # book the cheapest<br>#E4 = convert_currency[{&quot;amount&quot;: &quot;#E3.total_eur&quot;, &quot;from_currency&quot;: &quot;EUR&quot;, &quot;to_currency&quot;: &quot;USD&quot;}]  # total in USD</pre><p>Each line names a tool and its arguments, and #E1 to #E4 are placeholders for results that do not exist yet. &quot;#E1.city&quot; means &quot;whatever city step 1 returns&quot;. The format comes from ReWOO (Xu et al., 2023), which splits an agent into a Planner that writes this list, Workers that run the tools, and a Solver that reads the results and writes the answer.</p><p>An executor then walks down the list, fills in each placeholder with the real value and calls the tool, and the model is nowhere in sight. The model comes back once at the end to turn the evidence into a sentence.</p><p>In my toy Porto, the cheapest hotel is sold out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*T00xMa62KtD2bhzgZD2gDA.gif" /><figcaption><em>The real trace from tiny_agent.py: step #E3 fails, the planner is called once more and rewrites the remaining steps. Three model calls in total, against six for ReAct on the same task</em></figcaption></figure><h3>How it works</h3><p>Three strategies, one task:</p><ul><li><strong>Step by step (ReAct).</strong> The model picks every action after reading every observation. One model call per tool call, plus one to write the answer.</li><li><strong>Plan, execute.</strong> One call writes the whole plan, the executor runs it, one call writes the answer. If a step fails, the agent gives up.</li><li><strong>Plan, execute, re-plan.</strong> The same, except that a failed step sends the planner back to work. It sees everything that succeeded so far plus the error message, and rewrites only the steps that are left.</li></ul><p>If a task needs T tool calls and R re-plans:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*4nm2wwLWsSSQ-oYXK7oZlQ.png" /></figure><p>That is for a run that finishes; a run that gives up skips the answer call. The difference is T − R − 1. Every step that goes as planned is a step where nobody bothers the model.</p><p>Success is also easy to predict in my toy world. Porto has H = 4 hotels and each one is sold out with probability p, independently of the others. The rigid plan books the cheapest hotel, so it succeeds only when that hotel is free. The other two strategies keep going down the list until something is free:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*IxlNAtT_9IB-af_RZ18q3Q.png" /></figure><p>To check both formulas, I ran all three strategies on the same 10,000 random worlds for every p from 0 to 0.9. The models are scripted stand-ins, so they reason perfectly and the only difference between strategies is when they get to look at the world. For each run I counted correct bookings, model calls, and prompt characters, which is how much text the model has to read and a rough proxy for input tokens (the word pieces that model APIs, the web interfaces programs use to call a model, bill by).</p><pre>def run_one(strategy, sold_out):<br>    world = make_trip_world(sold_out=sold_out)<br>    if strategy == &quot;react&quot;:<br>        pol = ReActPolicy(scripted_react_booker, world)<br>    else:<br>        pol = PlanAndExecutePolicy(scripted_planner_llm, scripted_solver_llm, world,<br>                                   replan=(strategy == &quot;replan&quot;))<br>    t = Agent(pol, tools=world).run(GOAL)<br>    exp = expected(sold_out)<br>    ok = exp is not None and exp[0] in t.answer and exp[1] in t.answer<br>    return ok, len(pol.prompts), sum(len(p) for p in pol.prompts), len(t.steps)<br><br>if __name__ == &quot;__main__&quot;:<br>    N = 10000<br>    ps = [round(0.1 * i, 1) for i in range(10)]<br>    strategies = [&quot;react&quot;, &quot;plan&quot;, &quot;replan&quot;]<br>    res = {s: {&quot;success&quot;: [], &quot;calls&quot;: [], &quot;chars&quot;: [], &quot;tools&quot;: []} for s in strategies}<br>    for p in ps:<br>        rng = random.Random(1000 + int(p * 10))<br>        worlds = [{n for n, _ in PORTO_HOTELS if rng.random() &lt; p} for _ in range(N)]<br>        for s in strategies:<br>            rows = [run_one(s, w) for w in worlds]          # same worlds for every strategy<br>            res[s][&quot;success&quot;].append(sum(r[0] for r in rows) / N)<br>            res[s][&quot;calls&quot;].append(sum(r[1] for r in rows) / N)<br>            res[s][&quot;chars&quot;].append(sum(r[2] for r in rows) / N)<br>            res[s][&quot;tools&quot;].append(sum(r[3] for r in rows) / N)</pre><p>The averages at p = 0.3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*mPVwP4OUr_-svnWiv-U45g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eqj_VTR8f31wATwBNpTqXw.png" /><figcaption><em>Measured success sits on the two theory curves: 1 − p for the rigid plan, 1 − p⁴ for the two strategies that look at the world</em></figcaption></figure><p>The success chart matches the theory. The rigid plan tracks 1 − p (70.4% at p = 0.3, against 70% predicted), and re-planning ties ReAct world for world, because both eventually try every hotel. At p = 0.9 both reach 34.0% against a ceiling of 34.4%; the rest of the worlds have no free hotel at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4NiR4VT0mEqQERhr4O1zg.png" /><figcaption><em>Planning needs fewer model calls at every p, but its prompt advantage shrinks from 3.6 times to 1.5 times as surprises pile up</em></figcaption></figure><p>The cost chart has more going on. With no surprises, ReAct makes 5 model calls and the planner makes 2, exactly T + 1 and R + 2 with T = 4 and R = 0. ReAct also reads 3.6 times as much text (6,280 characters against 1,745), because every one of its calls re-sends the instructions, the tool list and the growing scratchpad.</p><p>Then the surprises arrive and re-planning gets expensive. A re-plan prompt carries the instructions, the tools, every result so far and the error, so it is the heaviest call the planner makes, and every surprise adds a whole new one, while ReAct only adds one step to its scratchpad. At p = 0.9 the planner still makes fewer calls (4.45 against 6.79), yet the text gap has shrunk to 1.5 times. Push this further, to a task where nearly every step surprises you, and R creeps up towards T. At that point plan-and-execute is just ReAct with longer prompts. The rigid plan looks cheapest of all on both panels, in the same way that walking out of a restaurant before ordering is the cheapest dinner.</p><h4>Building it from scratch: tiny_agent.py</h4><p>Time to add planning to our framework: still one file, still standard library only, and the earlier parts keep working. The file is about 750 lines now, so here are only the new parts. They slot in as a &quot;Part 4&quot; section right after the ReAct code, plus a demo at the bottom. As in Parts 1 to 3, a scripted stand-in plays the model in the runs below, so every output is reproducible.</p><p>First, the plan format, a parser for it, and a resolver that swaps the #E placeholders for real values:</p><pre>PLAN_INSTRUCTIONS = &quot;&quot;&quot;Write a plan that answers the question with the tools below.<br>One line per step, in this format:<br>  #E1 = tool_name[{&quot;arg&quot;: value}]   # why this step<br>An argument may refer to the result of an earlier step: &quot;#E1.city&quot; is the field<br>&quot;city&quot; of #E1&#39;s result, and &quot;#E2.hotels.0.name&quot; indexes into a list.<br>Write every step now. You will not see any result until the plan has run.&quot;&quot;&quot;<br><br>REPLAN_INSTRUCTIONS = &quot;&quot;&quot;The plan hit a problem. Results under &quot;Done so far&quot; are kept and<br>can still be referred to. Write only the remaining steps, numbered from #E{next},<br>in the same format. If the goal cannot be reached, write: give_up[reason]&quot;&quot;&quot;<br><br>SOLVE_INSTRUCTIONS = &quot;Answer the question in one sentence, using only the evidence below.&quot;<br><br>@dataclass<br>class PlanStep:<br>    id: str                     # &quot;E1&quot;<br>    tool: str<br>    arguments: dict             # may hold references such as &quot;#E1.city&quot;<br>    why: str = &quot;&quot;<br><br>_PLAN_LINE = re.compile(r&quot;^\s*#(E\d+)\s*=\s*([A-Za-z_]\w*)\s*\[(.*)$&quot;)<br>_GIVE_UP = re.compile(r&quot;^\s*give_up\s*\[(.*)\]\s*$&quot;, re.I)<br>_REF = re.compile(r&quot;#(E\d+)((?:\.\w+)*)&quot;)<br><br>def parse_plan(text):<br>    &quot;&quot;&quot;Read plan text into ([PlanStep, ...], give_up_reason or None).<br>    Lines that are not steps (headings, chatter) are skipped.&quot;&quot;&quot;<br>    steps = []<br>    for line in text.replace(&quot;```&quot;, &quot;&quot;).splitlines():<br>        g = _GIVE_UP.match(line)<br>        if g:<br>            return steps, g.group(1).strip()<br>        m = _PLAN_LINE.match(line)<br>        if m is None:<br>            continue<br>        sid, name, body = m.group(1), m.group(2), m.group(3).lstrip()<br>        try:<br>            args, end = json.JSONDecoder().raw_decode(body)<br>        except json.JSONDecodeError as e:<br>            raise ToolError(f&quot;step #{sid}: arguments are not valid JSON ({e.msg})&quot;)<br>        if not isinstance(args, dict):<br>            raise ToolError(f&quot;step #{sid}: arguments must be a JSON object&quot;)<br>        tail = body[end:]                              # &quot;]   # why this step&quot;<br>        why = tail.split(&quot;#&quot;, 1)[1].strip() if &quot;#&quot; in tail else &quot;&quot;<br>        steps.append(PlanStep(sid, name, args, why))<br>    if not steps:<br>        raise ToolError(&#39;no plan steps found; write lines like #E1 = tool[{&quot;arg&quot;: 1}]&#39;)<br>    return steps, None<br><br>def _follow(match, results):<br>    sid, path = match.group(1), match.group(2)<br>    if sid not in results:<br>        raise ToolError(f&quot;#{sid} has no result&quot;)<br>    value = results[sid]<br>    for key in filter(None, path.split(&quot;.&quot;)):<br>        try:<br>            value = value[int(key)] if isinstance(value, list) else value[key]<br>        except (KeyError, IndexError, ValueError, TypeError):<br>            raise ToolError(f&quot;#{sid}{path}: the result has no {key!r}&quot;)<br>    return value<br><br>def resolve(value, results):<br>    &quot;&quot;&quot;Swap #E references in plan arguments for real values from earlier results.<br>    A string that is only a reference keeps the value&#39;s type (&quot;#E1.nights&quot; -&gt; 3).&quot;&quot;&quot;<br>    if isinstance(value, dict):<br>        return {k: resolve(v, results) for k, v in value.items()}<br>    if isinstance(value, list):<br>        return [resolve(v, results) for v in value]<br>    if not isinstance(value, str):<br>        return value<br>    whole = _REF.fullmatch(value)<br>    if whole:<br>        return _follow(whole, results)<br>    return _REF.sub(lambda m: str(_follow(m, results)), value)</pre><p>Then the prompts and the policy itself. The policy keeps its three kinds of model call (plan, re-plan, answer) in three small methods, which pays off in a minute:</p><pre>def format_plan_step(ps, why=True):<br>    note = f&quot;  # {ps.why}&quot; if why and ps.why else &quot;&quot;<br>    return f&quot;#{ps.id} = {ps.tool}[{json.dumps(ps.arguments)}]{note}&quot;<br><br>def build_plan_prompt(goal, registry):<br>    lines = [PLAN_INSTRUCTIONS, &quot;&quot;, &quot;Tools:&quot;] + [format_tool_line(s) for s in registry.specs()]<br>    return &quot;\n&quot;.join(lines + [&quot;&quot;, f&quot;Question: {goal}&quot;, &quot;Plan:&quot;])<br><br>def build_replan_prompt(goal, registry, done, failed, error, next_n):<br>    lines = [PLAN_INSTRUCTIONS, &quot;&quot;, &quot;Tools:&quot;] + [format_tool_line(s) for s in registry.specs()]<br>    lines += [&quot;&quot;, f&quot;Question: {goal}&quot;, &quot;Done so far:&quot;]<br>    lines += [f&quot;{format_plan_step(ps, why=False)} -&gt; {obs}&quot; for ps, obs in done] or [&quot;(nothing)&quot;]<br>    lines += [f&quot;Failed: {format_plan_step(failed, why=False)} -&gt; {error}&quot;, &quot;&quot;,<br>              REPLAN_INSTRUCTIONS.format(next=next_n), &quot;Remaining plan:&quot;]<br>    return &quot;\n&quot;.join(lines)<br><br>def build_solve_prompt(goal, done):<br>    lines = [SOLVE_INSTRUCTIONS, &quot;&quot;, f&quot;Question: {goal}&quot;, &quot;Evidence:&quot;]<br>    lines += [f&quot;{format_plan_step(ps, why=False)} -&gt; {obs}&quot; for ps, obs in done]<br>    return &quot;\n&quot;.join(lines + [&quot;Answer:&quot;])<br><br>class PlanAndExecutePolicy:<br>    &quot;&quot;&quot;A policy that plans up front. planner_llm(prompt) -&gt; plan text,<br>    solver_llm(prompt) -&gt; answer text. The model is called once to plan, once per<br>    re-plan, and once to answer; the steps in between run without it.&quot;&quot;&quot;<br>    def __init__(self, planner_llm, solver_llm, registry, replan=True, max_replans=5):<br>        self.planner_llm, self.solver_llm, self.registry = planner_llm, solver_llm, registry<br>        self.replan, self.max_replans = replan, max_replans<br>        self.prompts = []                              # every model call, for counting<br><br>    def _ask(self, llm, prompt):<br>        self.prompts.append(prompt)<br>        return llm(prompt)<br><br>    def _new_plan(self, prompt):<br>        &quot;&quot;&quot;Ask for a (re)plan. Returns None, or a (&quot;final&quot;, ...) if there is nothing to run.&quot;&quot;&quot;<br>        try:<br>            steps, give_up = parse_plan(self._ask(self.planner_llm, prompt))<br>        except ToolError as e:<br>            return (&quot;final&quot;, f&quot;gave up: unreadable plan ({e})&quot;)<br>        return self._accept(steps, give_up)<br><br>    def _accept(self, steps, give_up):<br>        if give_up is not None:<br>            return (&quot;final&quot;, f&quot;gave up: {give_up}&quot;)<br>        self.queue = list(steps)                       # replaces whatever was left<br>        self.plans.append(steps)                       # kept whole, for inspection<br>        return None<br><br>    # The three model calls. A chat-model planner (PlanChatPolicy) overrides these.<br>    def _plan(self, goal):<br>        return self._new_plan(build_plan_prompt(goal, self.registry))<br><br>    def _replan(self, goal, failed, error, next_n):<br>        return self._new_plan(build_replan_prompt(goal, self.registry, self.done, failed,<br>                                                  error, next_n))<br><br>    def _solve(self, goal):<br>        return self._ask(self.solver_llm, build_solve_prompt(goal, self.done)).strip()<br><br>    def __call__(self, goal, steps):<br>        if not steps:                                  # new run: plan everything first<br>            self.queue, self.done, self.results, self.plans = [], [], {}, []<br>            self.replans = 0<br>            self.prompts = []<br>            stop = self._plan(goal)<br>            if stop:<br>                return stop<br>        else:<br>            last = steps[-1]                           # what did the current step return?<br>            if not last.is_error:<br>                self.results[self.current.id] = json.loads(last.observation)<br>                self.done.append((self.current, last.observation))<br>            elif not self.replan:<br>                return (&quot;final&quot;, f&quot;gave up: #{self.current.id} failed ({last.observation})&quot;)<br>            elif self.replans &gt;= self.max_replans:<br>                return (&quot;final&quot;, f&quot;gave up: still failing after {self.replans} re-plans&quot;)<br>            else:                                      # surprise: re-plan from here<br>                self.replans += 1<br>                used = max(int(s.id[1:]) for plan in self.plans for s in plan)<br>                stop = self._replan(goal, self.current, last.observation, used + 1)<br>                if stop:<br>                    return stop<br>        if not self.queue:                             # plan finished: one call to answer<br>            return (&quot;final&quot;, self._solve(goal))<br>        self.current = self.queue.pop(0)<br>        thought = f&quot;#{self.current.id}: {self.current.why}&quot;<br>        try:<br>            call = ToolCall(self.current.tool, resolve(self.current.arguments, self.results))<br>        except ToolError as e:                         # a bad reference fails like a tool would<br>            return ReActTurn(thought, e)<br>        return ReActTurn(thought, call)</pre><p>The demo world (make_trip_world) has four tools: event_info, find_hotels, book_hotel and the convert_currency tool from <a href="https://medium.com/p/b08b83a1ad50">Part 2</a>. Its four Porto hotels cost 95, 110, 128 and 160 EUR a night, all toy prices, and the cheapest one, Ribeira Inn, is sold out. The planner and the solver are plain Python functions that read only the prompt string and return text, exactly as a real model would. The demo sits at the end of the main block:</p><pre>    print(&quot;\n--- Part 4: plan, execute, re-plan ---&quot;)<br>    goal = &quot;Book the cheapest hotel for the Atlantic AI Summit and tell me the total in USD.&quot;<br>    world = make_trip_world(sold_out={&quot;Ribeira Inn&quot;})<br>    policy = PlanAndExecutePolicy(scripted_planner_llm, scripted_solver_llm, world)<br>    t = Agent(policy, tools=world).run(goal)<br>    print(&quot;First plan:&quot;)<br>    for ps in policy.plans[0]:<br>        print(&quot;  &quot; + format_plan_step(ps))<br>    print(&quot;Run:&quot;)<br>    for s in t.steps:<br>        obs = s.observation if len(s.observation) &lt; 60 else s.observation[:57] + &quot;...&quot;<br>        print(f&quot;  {s.thought:&lt;34} -&gt; {obs}&quot;)<br>    print(&quot;Re-plan:&quot;)<br>    for ps in policy.plans[1]:<br>        print(&quot;  &quot; + format_plan_step(ps))<br>    print(f&quot;Answer: {t.answer}&quot;)<br>    print(f&quot;Model calls: {len(policy.prompts)} (plan, re-plan, answer); tool calls: {len(t.steps)}&quot;)<br><br>    rigid = PlanAndExecutePolicy(scripted_planner_llm, scripted_solver_llm, world, replan=False)<br>    t = Agent(rigid, tools=world).run(goal)<br>    print(f&quot;Without re-planning: {t.answer}&quot;)</pre><p>Running python tiny_agent.py prints the Part 1 to 3 demos as before, then this:</p><pre>--- Part 4: plan, execute, re-plan ---<br>First plan:<br>  #E1 = event_info[{&quot;name&quot;: &quot;Atlantic AI Summit&quot;}]  # where is it, how many nights<br>  #E2 = find_hotels[{&quot;city&quot;: &quot;#E1.city&quot;}]  # hotels there, cheapest first<br>  #E3 = book_hotel[{&quot;hotel&quot;: &quot;#E2.hotels.0.name&quot;, &quot;nights&quot;: &quot;#E1.nights&quot;}]  # book the cheapest<br>  #E4 = convert_currency[{&quot;amount&quot;: &quot;#E3.total_eur&quot;, &quot;from_currency&quot;: &quot;EUR&quot;, &quot;to_currency&quot;: &quot;USD&quot;}]  # total in USD<br>Run:<br>  #E1: where is it, how many nights  -&gt; {&quot;name&quot;: &quot;Atlantic AI Summit&quot;, &quot;city&quot;: &quot;Porto&quot;, &quot;nights&quot;:...<br>  #E2: hotels there, cheapest first  -&gt; {&quot;city&quot;: &quot;Porto&quot;, &quot;hotels&quot;: [{&quot;name&quot;: &quot;Ribeira Inn&quot;, &quot;eur...<br>  #E3: book the cheapest             -&gt; error: Ribeira Inn is sold out for those dates<br>  #E5: the next cheapest             -&gt; {&quot;hotel&quot;: &quot;Douro Rooms&quot;, &quot;nights&quot;: 3, &quot;total_eur&quot;: 330}<br>  #E6: total in USD                  -&gt; {&quot;amount&quot;: 356.4, &quot;currency&quot;: &quot;USD&quot;}<br>Re-plan:<br>  #E5 = book_hotel[{&quot;hotel&quot;: &quot;#E2.hotels.1.name&quot;, &quot;nights&quot;: &quot;#E1.nights&quot;}]  # the next cheapest<br>  #E6 = convert_currency[{&quot;amount&quot;: &quot;#E5.total_eur&quot;, &quot;from_currency&quot;: &quot;EUR&quot;, &quot;to_currency&quot;: &quot;USD&quot;}]  # total in USD<br>Answer: Booked Douro Rooms for 3 nights: 330 EUR, about 356.40 USD (toy prices).<br>Model calls: 3 (plan, re-plan, answer); tool calls: 5<br>Without re-planning: gave up: #E3 failed (error: Ribeira Inn is sold out for those dates)</pre><p>Notes:</p><ul><li><strong>The policy fits the old loop.</strong> PlanAndExecutePolicy is still a policy(goal, steps), so the Agent class from <a href="https://medium.com/p/3e839ba288b8">Part 1</a> did not change at all. Planning lives in the policy, and the loop keeps doing what it always did: decide, act, observe.</li><li><strong>Placeholders keep their type.</strong> resolve turns &quot;#E1.nights&quot; into the integer 3, so the <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> validator sees the type book_hotel asked for. A reference that points at nothing (say &quot;#E9.city&quot;) raises a ToolError, which reaches the loop as an ordinary error observation and triggers a re-plan, just like a failed tool.</li><li><strong>Re-plans start where the plan broke.</strong> The planner sees what worked under &quot;Done so far&quot; and the failure under &quot;Failed&quot;, and writes only what is left, numbered from #E5 so new results never overwrite old ones. That is why the run jumps from #E3 to #E5: #E4 was thrown away unrun.</li><li><strong>Giving up is a legal move.</strong> If every hotel is full, the planner can answer give_up[reason] instead of inventing a fifth hotel. max_replans caps the loop for planners that never admit defeat.</li></ul><h4>Putting a chat model in the loop</h4><p>The plan format above is plain text, and it works with any model that reads and writes text. Most agents today talk to a chat model through native tool calling instead (the <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> way), and planning moves over neatly. The trick is to give the planner exactly one tool, submit_plan, whose input is the plan itself. The model never calls event_info or book_hotel directly. It lists them as steps, the provider hands the plan back as JSON, and the Part 2 validator checks it against a schema before a single step runs. No regular expression has to read plan text anymore.</p><p>The whole run also becomes one conversation. The plan arrives as a tool_use block, the executor runs the steps without the model, and the results go back as the tool_result of that same call: with the error when a step fails, so the model re-plans, or with the evidence when the plan is done, so the model answers in plain text. PlanChatPolicy gets there by overriding the three small methods from above, _plan, _replan and _solve. Like Part 2&#39;s ToolChatPolicy, it speaks Anthropic&#39;s message shape, and it slots in right after the Part 4 demo:</p><pre># =====================================================================<br># Part 4 (revisited): the same plan-and-execute run with a chat model and native tool calling<br># =====================================================================<br>PLAN_SYSTEM = &quot;&quot;&quot;You plan before you act. Call submit_plan with every step needed to answer<br>the question, using the tools listed below. A step&#39;s arguments may refer to the result of an<br>earlier step: &quot;#E1.city&quot; is the field &quot;city&quot; of the result of step E1, and<br>&quot;#E2.hotels.0.name&quot; indexes into a list. You will not see any result until the plan has run.<br>If a step fails, you get the results so far and the error: call submit_plan again with only<br>the remaining steps, or with give_up set to the reason if the goal cannot be reached.<br>When the plan has run, answer the question in one sentence, using only the evidence.<br>Tools:<br>{tools}&quot;&quot;&quot;<br><br>def plan_tool(registry):<br>    &quot;&quot;&quot;The one tool a chat-model planner gets. Its input IS the plan, so the provider&#39;s tool<br>    calling hands the plan back as JSON: no plan text to parse. The world&#39;s tools are listed<br>    in the system prompt and named in an enum; the planner never calls them itself.&quot;&quot;&quot;<br>    return {&quot;name&quot;: &quot;submit_plan&quot;,<br>            &quot;description&quot;: &quot;Submit the plan, or after a failure the remaining steps.&quot;,<br>            &quot;input_schema&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;steps&quot;: {&quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {<br>                        &quot;type&quot;: &quot;object&quot;,<br>                        &quot;properties&quot;: {<br>                            &quot;id&quot;: {&quot;type&quot;: &quot;string&quot;},          # &quot;E1&quot;, &quot;E2&quot;, ...<br>                            &quot;tool&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [t[&quot;name&quot;] for t in registry.specs()]},<br>                            &quot;arguments&quot;: {&quot;type&quot;: &quot;object&quot;},   # may hold &quot;#E1.city&quot; references<br>                            &quot;why&quot;: {&quot;type&quot;: &quot;string&quot;}},<br>                        &quot;required&quot;: [&quot;id&quot;, &quot;tool&quot;, &quot;arguments&quot;], &quot;additionalProperties&quot;: False}},<br>                    &quot;give_up&quot;: {&quot;type&quot;: &quot;string&quot;}},<br>                &quot;additionalProperties&quot;: False}}<br><br>def plan_from_input(data, schema):<br>    &quot;&quot;&quot;Check a submit_plan input with the Part 2 validator and turn it into PlanSteps.<br>    Returns (steps, give_up reason or None); raises ToolError with what is wrong.&quot;&quot;&quot;<br>    problems = validate(data, schema)<br>    for i, st in enumerate(data.get(&quot;steps&quot;, []) if isinstance(data, dict) else []):<br>        if isinstance(st, dict) and not re.fullmatch(r&quot;E\d+&quot;, str(st.get(&quot;id&quot;, &quot;&quot;))):<br>            problems.append(f&quot;arguments.steps[{i}].id must look like E1, got {st.get(&#39;id&#39;)!r}&quot;)<br>    if problems:<br>        raise ToolError(&quot;invalid plan: &quot; + &quot;; &quot;.join(problems))<br>    if data.get(&quot;give_up&quot;):<br>        return [], data[&quot;give_up&quot;]<br>    if not data.get(&quot;steps&quot;):<br>        raise ToolError(&quot;invalid plan: no steps and no give_up&quot;)<br>    return [PlanStep(st[&quot;id&quot;], st[&quot;tool&quot;], st[&quot;arguments&quot;], st.get(&quot;why&quot;, &quot;&quot;))<br>            for st in data[&quot;steps&quot;]], None<br><br>class PlanChatPolicy(PlanAndExecutePolicy):<br>    &quot;&quot;&quot;Plan-and-execute for a tool-calling chat model. llm(system, tools, messages) -&gt; content<br>    blocks, in Anthropic&#39;s message shape like ToolChatPolicy (Part 2). The whole run is one<br>    conversation: the plan comes back as a submit_plan tool call, the executor runs its<br>    steps without the model, and the results go back as that call&#39;s tool_result, with the<br>    error when a step fails (the model re-plans) or with the evidence when the plan is done<br>    (the model answers in text). An invalid plan is sent back once with what is wrong.&quot;&quot;&quot;<br>    def __init__(self, llm, registry, replan=True, max_replans=5, fixes=1):<br>        super().__init__(None, None, registry, replan, max_replans)<br>        self.llm, self.fixes = llm, fixes<br>        self.tool = plan_tool(registry)<br>        self.system = PLAN_SYSTEM.format(<br>            tools=&quot;\n&quot;.join(format_tool_line(t) for t in registry.specs()))<br>        self.messages, self.requests = [], []<br><br>    def _send(self):<br>        self.requests.append(json.loads(json.dumps(self.messages)))   # a copy, for printing<br>        self.prompts.append(self.requests[-1])                        # counts as a model call<br>        reply = self.llm(self.system, [self.tool], self.messages)<br>        self.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: reply})<br>        return reply<br><br>    def _reply_to_plan(self, text, is_error):<br>        self.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [<br>            {&quot;type&quot;: &quot;tool_result&quot;, &quot;tool_use_id&quot;: self.plan_id, &quot;content&quot;: text,<br>             &quot;is_error&quot;: is_error}]})<br><br>    def _take(self, reply):<br>        for attempt in range(self.fixes + 1):<br>            uses = [b for b in reply if b[&quot;type&quot;] == &quot;tool_use&quot; and b[&quot;name&quot;] == &quot;submit_plan&quot;]<br>            if not uses:<br>                text = &quot;&quot;.join(b.get(&quot;text&quot;, &quot;&quot;) for b in reply).strip()<br>                return (&quot;final&quot;, f&quot;gave up: the model replied without a plan ({text[:60]})&quot;)<br>            self.plan_id = uses[0][&quot;id&quot;]<br>            try:<br>                return self._accept(*plan_from_input(uses[0][&quot;input&quot;], self.tool[&quot;input_schema&quot;]))<br>            except ToolError as e:<br>                if attempt == self.fixes:<br>                    return (&quot;final&quot;, f&quot;gave up: {e}&quot;)<br>                self._reply_to_plan(f&quot;error: {e}. Call submit_plan again with a fixed plan.&quot;, True)<br>                reply = self._send()<br><br>    def _plan(self, goal):<br>        self.messages, self.requests = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}], []<br>        return self._take(self._send())<br><br>    def _replan(self, goal, failed, error, next_n):<br>        lines = [&quot;Done so far:&quot;]<br>        lines += [f&quot;{format_plan_step(ps, why=False)} -&gt; {obs}&quot; for ps, obs in self.done] or [&quot;(nothing)&quot;]<br>        lines += [f&quot;Failed: {format_plan_step(failed, why=False)} -&gt; {error}&quot;,<br>                  f&quot;Call submit_plan with only the remaining steps, numbered from #E{next_n}, &quot;<br>                  &quot;or give up.&quot;]<br>        self._reply_to_plan(&quot;\n&quot;.join(lines), True)<br>        return self._take(self._send())<br><br>    def _solve(self, goal):<br>        lines = [&quot;The plan ran. Evidence:&quot;]<br>        lines += [f&quot;{format_plan_step(ps, why=False)} -&gt; {obs}&quot; for ps, obs in self.done]<br>        self._reply_to_plan(&quot;\n&quot;.join(lines + [&quot;Answer the question in one sentence.&quot;]), False)<br>        reply = self._send()<br>        return &quot;&quot;.join(b[&quot;text&quot;] for b in reply if b[&quot;type&quot;] == &quot;text&quot;).strip()<br><br>def scripted_plan_chat_llm(system, tools, messages):<br>    &quot;&quot;&quot;Scripted stand-in for a tool-calling chat model planning the Part 4 booking. Like a real<br>    one, it sees only the system prompt, the tool list and the messages. It plans with a<br>    submit_plan tool_use block, re-plans from the error in a tool_result, and answers in text.&quot;&quot;&quot;<br>    n = sum(m[&quot;role&quot;] == &quot;assistant&quot; for m in messages)<br>    def submit(note, steps):<br>        return [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: note},<br>                {&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: f&quot;toolu_{n + 1:02d}&quot;, &quot;name&quot;: &quot;submit_plan&quot;,<br>                 &quot;input&quot;: {&quot;steps&quot;: steps}}]<br>    def as_dicts(plan_steps):<br>        return [{&quot;id&quot;: p.id, &quot;tool&quot;: p.tool, &quot;arguments&quot;: p.arguments, &quot;why&quot;: p.why}<br>                for p in plan_steps]<br>    if n == 0:                                            # the first plan, written blind<br>        return submit(&quot;I will find the event, list its hotels, book the cheapest one and convert &quot;<br>                      &quot;the total.&quot;, as_dicts(parse_plan(scripted_planner_llm(&quot;first plan&quot;))[0]))<br>    result = messages[-1][&quot;content&quot;][0][&quot;content&quot;]        # the tool_result for my last plan<br>    if result.startswith(&quot;The plan ran.&quot;):<br>        return [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: scripted_solver_llm(result)}]<br>    steps, give_up = parse_plan(scripted_planner_llm(result))   # same decisions as Part 4<br>    if give_up:<br>        return [{&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: f&quot;toolu_{n + 1:02d}&quot;, &quot;name&quot;: &quot;submit_plan&quot;,<br>                 &quot;input&quot;: {&quot;give_up&quot;: give_up}}]<br>    return submit(&quot;That hotel is full, so I will try the next cheapest.&quot;, as_dicts(steps))</pre><p>The stand-in, scripted_plan_chat_llm, sees exactly what a real chat model would see: the system prompt, the one tool and the messages. It answers in content blocks, so swapping in Claude changes nothing else. To keep the comparison fair, it makes the same decisions as the text planner, which is why it borrows scripted_planner_llm and scripted_solver_llm. The bottom of the file runs the same booking:</p><pre>    print(&quot;\n--- Part 4 (revisited): plan-and-execute with a chat model ---&quot;)<br>    chat = PlanChatPolicy(scripted_plan_chat_llm, world)<br>    t = Agent(chat, tools=world).run(goal)<br>    first = chat.requests[1][1][&quot;content&quot;]                 # the model&#39;s first reply, replayed<br>    print(&quot;The plan, as a submit_plan tool call:&quot;)<br>    print(&quot;  &quot; + json.dumps([b for b in first if b[&quot;type&quot;] == &quot;tool_use&quot;][0][&quot;input&quot;][&quot;steps&quot;][2]))<br>    for s in t.steps:<br>        obs = s.observation if len(s.observation) &lt; 60 else s.observation[:57] + &quot;...&quot;<br>        print(f&quot;  {s.thought:&lt;34} -&gt; {obs}&quot;)<br>    print(&quot;The tool_result that asked for a re-plan:&quot;)<br>    for line in chat.requests[1][-1][&quot;content&quot;][0][&quot;content&quot;].splitlines():<br>        print(&quot;  &quot; + (line if len(line) &lt; 90 else line[:87] + &quot;...&quot;))<br>    print(f&quot;Answer: {t.answer}&quot;)<br>    sizes = [len(json.dumps({&quot;system&quot;: chat.system, &quot;tools&quot;: [chat.tool], &quot;messages&quot;: m}))<br>             for m in chat.requests]<br>    print(f&quot;{len(t.steps)} tool calls, {len(chat.requests)} model calls; request size &quot;<br>          + &quot; -&gt; &quot;.join(f&quot;{x:,}&quot; for x in sizes) + &quot; characters (system prompt + plan tool + messages)&quot;)<br>    try:<br>        plan_from_input({&quot;steps&quot;: [{&quot;id&quot;: &quot;1&quot;, &quot;tool&quot;: &quot;book_hotel&quot;, &quot;arguments&quot;: {}}]},<br>                        chat.tool[&quot;input_schema&quot;])<br>    except ToolError as e:<br>        print(f&quot;A malformed plan is caught before anything runs: {e}&quot;)</pre><p>It prints:</p><pre>--- Part 4 (revisited): plan-and-execute with a chat model ---<br>The plan, as a submit_plan tool call:<br>  {&quot;id&quot;: &quot;E3&quot;, &quot;tool&quot;: &quot;book_hotel&quot;, &quot;arguments&quot;: {&quot;hotel&quot;: &quot;#E2.hotels.0.name&quot;, &quot;nights&quot;: &quot;#E1.nights&quot;}, &quot;why&quot;: &quot;book the cheapest&quot;}<br>  #E1: where is it, how many nights  -&gt; {&quot;name&quot;: &quot;Atlantic AI Summit&quot;, &quot;city&quot;: &quot;Porto&quot;, &quot;nights&quot;:...<br>  #E2: hotels there, cheapest first  -&gt; {&quot;city&quot;: &quot;Porto&quot;, &quot;hotels&quot;: [{&quot;name&quot;: &quot;Ribeira Inn&quot;, &quot;eur...<br>  #E3: book the cheapest             -&gt; error: Ribeira Inn is sold out for those dates<br>  #E5: the next cheapest             -&gt; {&quot;hotel&quot;: &quot;Douro Rooms&quot;, &quot;nights&quot;: 3, &quot;total_eur&quot;: 330}<br>  #E6: total in USD                  -&gt; {&quot;amount&quot;: 356.4, &quot;currency&quot;: &quot;USD&quot;}<br>The tool_result that asked for a re-plan:<br>  Done so far:<br>  #E1 = event_info[{&quot;name&quot;: &quot;Atlantic AI Summit&quot;}] -&gt; {&quot;name&quot;: &quot;Atlantic AI Summit&quot;, &quot;cit...<br>  #E2 = find_hotels[{&quot;city&quot;: &quot;#E1.city&quot;}] -&gt; {&quot;city&quot;: &quot;Porto&quot;, &quot;hotels&quot;: [{&quot;name&quot;: &quot;Ribei...<br>  Failed: #E3 = book_hotel[{&quot;hotel&quot;: &quot;#E2.hotels.0.name&quot;, &quot;nights&quot;: &quot;#E1.nights&quot;}] -&gt; err...<br>  Call submit_plan with only the remaining steps, numbered from #E5, or give up.<br>Answer: Booked Douro Rooms for 3 nights: 330 EUR, about 356.40 USD (toy prices).<br>5 tool calls, 3 model calls; request size 1,769 -&gt; 3,292 -&gt; 4,688 characters (system prompt + plan tool + messages)<br>A malformed plan is caught before anything runs: invalid plan: arguments.steps[0].id must look like E1, got &#39;1&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQSLto9e_CzvEgTfUAXuZw.png" /><figcaption><em>Left: the third request, with the whole run in one conversation. Right: characters sent per model call, for the text planner from earlier and for the chat version</em></figcaption></figure><p>Same plan, same sold-out Ribeira Inn, same jump from #E3 to #E5, same 356.40 USD, and still 3 model calls for 5 tool calls. Because the plan is now a tool call, a malformed one, like a step called &quot;1&quot; instead of &quot;E1&quot;, is rejected with a readable message before anything runs, and PlanChatPolicy sends that message back once so the model can fix it. The price shows up in the right-hand chart. The text planner builds a fresh prompt for every call, and its answer prompt carries only the evidence (820 characters). The chat version resends the whole conversation every time, so its requests grow from 1,769 to 3,292 to 4,688 characters, and 1,658 characters of each one are the system prompt and the plan tool. That growing transcript is the problem Part 5 picks up.</p><p>With Claude it is one line, because Part 2&#39;s anthropic_tool_llm already returns text and tool_use blocks as dicts. It is an untested placeholder, not run for this post, so plug in your key to try it:</p><pre># Real-model version - UNTESTED, plug in your key; not run for this post.<br>PlanChatPolicy(anthropic_tool_llm, make_trip_world(sold_out={&quot;Ribeira Inn&quot;}))</pre><h4>Plugging in a real model</h4><p>Real models plug in through the same adapters as before. Each one gains a complete(prompt) method, a plain text-in, text-out call with no tools, which is all the planner and solver need. These are untested placeholders. Plug in your key; they were not run for this post. To use one, create it with your tool registry and pass its complete method as both the planner and the solver.</p><pre># Placeholders: real models. UNTESTED - plug in your key; not run for this post.<br>...<br>class AnthropicPolicy:<br>    ...<br>    def complete(self, prompt):<br>        &quot;&quot;&quot;Part 4: text in, text out (no tools). Use as planner_llm / solver_llm.&quot;&quot;&quot;<br>        resp = self.client.messages.create(model=self.model, max_tokens=self.max_tokens,<br>                                           messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}])<br>        return &quot;&quot;.join(b.text for b in resp.content if b.type == &quot;text&quot;)<br><br>class OpenAIPolicy:<br>    ...<br>    def complete(self, prompt):<br>        &quot;&quot;&quot;Part 4: text in, text out (no tools). Use as planner_llm / solver_llm.&quot;&quot;&quot;<br>        resp = self.client.responses.create(model=self.model, input=prompt)<br>        return resp.output_text                           # joins all text output items</pre><p>As before, the Anthropic and OpenAI Python libraries (for the Messages and Responses APIs) are imported lazily, and the key and model name come from environment variables (ANTHROPIC_API_KEY or OPENAI_API_KEY, and TINY_AGENT_MODEL), so the file still runs on the standard library alone. Both classes keep their native tool-calling policy method from <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> and <a href="https://medium.com/p/7195a44864f5">Part 3</a>, so the same adapter can run ReAct or plan-and-execute.</p><p>Next time, tiny_agent.py gets a context window: a token counter, a budget, and a way to decide what falls out of the prompt when the scratchpad gets too long.</p><h4>Why this matters if you build agents</h4><p>Plan mode in coding tools is this exact pattern with a human in the middle: <a href="https://devblogs.microsoft.com/visualstudio/plan-before-you-build-introducing-the-plan-agent-in-visual-studio/">Copilot&#39;s Plan agent in Visual Studio</a> (May 21, 2026) explores the code with read-only tools and changes nothing until you approve, and <a href="https://cursor.com/blog/plan-mode">Cursor&#39;s Plan Mode</a> works the same way. Reviewing a plan is much cheaper than reviewing a diff, and it is the moment where a person can catch the agent planning to book the hotel before checking the dates.</p><p>The research this autumn says the hard part is carrying the plan out. Besides the <a href="https://arxiv.org/abs/2610.22469">October 15 PDDL study</a> from the opening, a September 29, 2026 paper on the <a href="https://arxiv.org/abs/2609.38108">plan declaration-execution gap</a> found that a generic Plan+ReAct agent kept the structure of the plan it had declared in only about 22% to 45% of trajectories. Handing the plan to a deterministic executor that matches its shape raised success on ALFWorld, a benchmark (a standard test set) of household tasks, from 0.48 to 0.92. PlanAndExecutePolicy does that job in miniature: once the plan exists, plain code walks it, and the model cannot wander off halfway through.</p><p>Some practical habits:</p><ul><li><strong>Plan when the steps are predictable.</strong> Lookups, data pipelines and multi-step forms are mostly known in advance, so planning saves calls and lets independent steps run in parallel. <a href="https://arxiv.org/abs/2312.04511">LLMCompiler</a> (Kim et al., ICML 2024) does exactly that, turning the plan into a graph of calls that run at the same time.</li><li><strong>Go step by step when every step depends on what you just saw.</strong> Debugging and browsing surprise you constantly, which is exactly where re-planning stops paying for itself.</li><li><strong>Always let the agent re-plan, and cap it.</strong> A plan that cannot change scored 70.4% in our sweep at p = 0.3, against 99.3% for one that can. Setting max_replans keeps a stubborn planner from looping forever.</li><li><strong>Give the planner a way to say no.</strong> The PDDL study saw agents spot impossible tasks in fewer than 10% of episodes. An explicit give_up action is cheap and turns &quot;this cannot be done&quot; into a valid answer.</li></ul><p>Newer work such as <a href="https://arxiv.org/abs/2610.27032">M-Plan</a> (October 19, 2026) goes further and feeds the planner milestones and lessons from earlier tasks. It still sits on the same loop you just built.</p><h4>Closing</h4><p>Our agent now writes a plan, keeps the model out of the boring middle, and only phones the planner when a hotel is full. It is a bit like a manager who writes the to-do list on Monday and then stays out of the way until something catches fire. The catch is that every re-plan prompt carries the whole story so far, and the story only gets longer. In Part 5 we give tiny_agent.py a context window, so it can count its tokens and decide what to forget when the story no longer fits.</p><h4>References</h4><ol><li>Miro-Lopez-Feliu, O., Gimenez-Abalos, V., Vazquez-Salceda, J., et al. (2026). <em>Testing the Planning Claims of LLM-Based Agents against Formal Semantics.</em> arXiv:2610.22469, October 15, 2026. <a href="https://arxiv.org/abs/2610.22469">arxiv.org/abs/2610.22469</a></li><li>Oota, S. R., Herrera, F., Cabot Sagrera, J., López de Prado, M., &amp; Khan, S. (2026). <em>Do LLM Agents Execute the Plans They Declare? From Planning-Mode Declaration to Pattern-Specific Execution.</em> arXiv:2609.38108, September 29, 2026. <a href="https://arxiv.org/abs/2609.38108">arxiv.org/abs/2609.38108</a></li><li>Xu, B., Peng, Z., Lei, B., Mukherjee, S., Liu, Y., &amp; Xu, D. (2023). <em>ReWOO: Decoupling Reasoning from Observations for Efficient Augmented Language Models.</em> arXiv:2305.18323. <a href="https://arxiv.org/abs/2305.18323">arxiv.org/abs/2305.18323</a></li><li>Kim, S., Moon, S., Tabrizi, R., Lee, N., Mahoney, M. W., Keutzer, K., &amp; Gholami, A. (2024). <em>An LLM Compiler for Parallel Function Calling.</em> ICML 2024. arXiv:2312.04511. <a href="https://arxiv.org/abs/2312.04511">arxiv.org/abs/2312.04511</a></li><li>Liu, Z., Yuan, J., Fan, J., &amp; Chen, T. (2026). <em>M-Plan: Comprehensive Planning For LLM Agents with Memory Arrangement.</em> arXiv:2610.27032, October 19, 2026. <a href="https://arxiv.org/abs/2610.27032">arxiv.org/abs/2610.27032</a></li><li>Kang, R. (2026). <em>Plan Before You Build: Introducing the Plan agent in Visual Studio.</em> Visual Studio Blog, May 21, 2026. <a href="https://devblogs.microsoft.com/visualstudio/plan-before-you-build-introducing-the-plan-agent-in-visual-studio/">devblogs.microsoft.com</a></li><li>Smith, J. (2025). <em>Introducing Plan Mode.</em> Cursor blog, October 7, 2025. <a href="https://cursor.com/blog/plan-mode">cursor.com/blog/plan-mode</a></li><li>Anthropic. <em>Messages API reference.</em> <a href="https://platform.claude.com/docs/en/api/messages">platform.claude.com/docs/en/api/messages</a></li><li>OpenAI. <em>Text generation guide (Responses API).</em> <a href="https://developers.openai.com/api/docs/guides/text">developers.openai.com/api/docs/guides/text</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7f584a3ba0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents from Scratch, Part 3: ReAct]]></title>
            <link>https://medium.com/@srivatsa.n63/ai-agents-from-scratch-part-3-react-7195a44864f5?source=rss-22246753979c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7195a44864f5</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Srivatsa Narasimha]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 02:31:00 GMT</pubDate>
            <atom:updated>2026-11-03T02:31:00.550Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGEtYOcScJgSm2fOmccywQ.png" /></figure><p>If you have watched an AI agent write code, you have seen the little lines it prints between tool calls: &quot;The test imports a helper I have not seen yet, so I will open utils.py.&quot; Then it opens utils.py, prints another short line and makes another call. For months I skimmed past those lines the way I skim past cookie banners. They turn out to be the most interesting part of the show.</p><p>When Anthropic launched Sonnet 5.5 on September 28, 2026, its API got a thinking setting called <em>between_tools</em>: the model skips the long think at the start and reasons in short bursts between tool calls instead (<a href="https://platform.claude.com/docs/en/release-notes/overview">Claude Platform release notes</a>). Ten days later, on October 8, Yiruo Cheng and colleagues posted <em>When Should Agents Think?</em> on arXiv, which asks the follow-up question every finance team would ask: if the agent thinks before every single action, which of those thoughts could we have skipped? (<a href="https://arxiv.org/abs/2610.12061">Cheng et al., 2026</a>). Both build on a pattern called ReAct.</p><p>In <a href="https://medium.com/p/3e839ba288b8">Part 1</a> the agent became a loop, and in <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> we gave it hands. A language model (a program that predicts the next piece of text) cannot run code by itself, so we described each tool with a JSON schema, let the model ask for a call as structured data, validated the arguments, and sent every error back as an observation the model could read and fix. The file tiny_agent.py ended <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> with a ToolRegistry, a small schema validator and two untested adapters for real models.</p><p>That agent could act, but it never explained itself. It went straight from one observation to the next call, like a friend who takes your phone, types something and hands it back without a word. That works until the day the friend books a hotel in Portland, Maine, for a conference in Porto, Portugal, and nobody can tell you which step went wrong. This part answers one question: what changes when the agent writes down its reasoning before every action, and how do we build that into our little framework?</p><h4>A detective with a notebook</h4><p>Picture a detective who never writes anything down. If she gets the case wrong, there is no record of what she believed at each point. Now make her scribble one line before every move: &quot;The butler lied about the time, so check the train timetable.&quot; The notebook catches nobody, but every next move is decided with the notes in front of her.</p><p>ReAct, short for Reasoning plus Acting, is that notebook. It comes from Shunyu Yao and colleagues at Princeton and Google (<a href="https://arxiv.org/abs/2210.03629">Yao et al., 2022</a>, published at ICLR 2023). Back then, chain-of-thought prompting made a model reason step by step without looking anything up, so it reasoned neatly about facts it had invented, while act-only agents looked things up without reasoning and wandered from search to search. ReAct interleaves the two: a Thought, then an Action, then the Observation that comes back, and around again.</p><p>Here is that loop running on a question from this part&#39;s demo: what do the hotel nights for the (fictional) Atlantic AI Summit cost in US dollars? The question does not say where the summit is, so the agent has to find out first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*H10OziyVSjo6libmiWS04Q.gif" /><figcaption><em>The real trace from this part’s demo, one line at a time. The loop on the left lights up the phase being written</em></figcaption></figure><p>The thoughts in that trace do three jobs. The first plans (&quot;I need the summit&#39;s city and length before I can price anything&quot;). The second handles an exception: the lookup fails, and the thought spots the suggested title in the error and retries with it. The third carries &quot;Porto, 3 nights&quot; forward so the next action has its arguments ready. The paper says reasoning traces help the model &quot;induce, track, and update action plans as well as handle exceptions&quot;.</p><h4>How it works</h4><p>The paper uses a little notation. At time t the agent has a context c_t: every observation and action so far. A normal agent picks its next action from A, the things it can do in the world (call a tool, click a button). ReAct adds L, the space of language, so writing a thought counts as an action too:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1hjM6uiaWpiM4ISlelhDQ.png" /></figure><p>Here π is the policy, the thing that chooses actions, which for us is the language model. The interesting part is what happens when the chosen action is a thought. Nothing in the world changes and no observation comes back. The thought is simply appended to the context:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*lfAiAUBQQLRRKfWly99SNw.png" /></figure><p>So a thought is an action whose only effect is on the agent&#39;s own context. It sounds useless, but the next action is sampled with that context in view, so the model is writing notes to its future self. A language model produces text one token (a word or piece of a word) at a time, and a thought gives it room to work something out before it has to commit to a tool name and arguments.</p><p>For a model that only reads and writes text, all of this becomes a prompt format: instructions, the tool list, the question, and a scratchpad of earlier Thought, Action and Observation lines, ending with an open &quot;Thought:&quot; so the model starts by thinking. Our code parses the action in the reply, runs the tool, appends the observation and calls the model again.</p><p>Two engineering problems fall out of that. The first is that the prompt grows every turn. The chart shows the prompt the model received on each of its five calls, counted in words plus punctuation marks; a real tokenizer gives different numbers but the same shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mw7-aJRQ6jZOF_ukGedwbg.png" /><figcaption><em>Prompt size on each of the five model calls, split by source. Rough tokens are words plus punctuation marks, not a real tokenizer</em></figcaption></figure><p>The prompt goes from 163 to 428 rough tokens in four turns. Thoughts take 78 of the final 428, about 18 percent. Observations are the biggest slice at 108, and these toy tools return one sentence each; a real search result would dwarf the rest. That bill is what the October paper goes after: its method, RACE, trains the agent to skip reasoning on turns where earlier thoughts already cover the next move, and the authors report a large cut in reasoning cost with the same or better task performance on four agent benchmarks.</p><p>The second problem is parsing, because models are creative about formatting. I wrote ten replies in styles real models tend to produce and ran two parsers over them: a strict regular expression (a pattern-matching rule) that wants exactly &quot;Thought: ...&quot; on one line and &quot;Action: ...&quot; on the next, and the forgiving parse_react we build below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*RIUnuVHlSe24MwXHpyT3CQ.png" /><figcaption><em>Ten hand-written replies run through both parsers. Green means the parser did the right thing, which for the last two rows is a rejection</em></figcaption></figure><p>The strict parser got 5 of the 10 right. It rejected lowercase labels, a two-line thought, a code fence, chatter after the action and, my favorite, an invented Observation. Models that have seen a lot of ReAct-style text like to keep going and write the tool&#39;s answer themselves, which is why classic ReAct prompts set a stop sequence at &quot;Observation:&quot; so the provider halts generation there. Our parser does the same job after the fact. The forgiving parse_react got all 10 right, including rejecting the two replies that really are broken, but I wrote both the cases and the parser, so treat that as a unit test and not a benchmark.</p><h4>Building it from scratch: tiny_agent.py</h4><p>The file is now about 490 lines, so here are the new and changed parts. It is still standard-library Python, and as in <a href="https://medium.com/p/3e839ba288b8">Part 1</a> and <a href="https://medium.com/p/b08b83a1ad50">Part 2</a>, a scripted stand-in plays the model in the runs below, so every output is reproducible.</p><p>First, the loop. A Step gains a thought and a raw field (raw is for the real-model adapters), and a policy can now return a ReActTurn, an action with its thought attached. The Agent unwraps it, stores the thought with the step, and turns an unreadable reply into an error observation, as <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> did for bad tool calls. Old policies that return bare actions still work.</p><pre>@dataclass<br>class Step:<br>    action: str<br>    observation: str<br>    call: &quot;ToolCall | None&quot; = None      # Part 2: the structured call, if any<br>    is_error: bool = False              # Part 2: did the tool call fail?<br>    thought: str = &quot;&quot;                   # Part 3: the reasoning written before the action<br>    raw: list | None = None             # Part 3: provider blocks to replay verbatim (adapters)<br><br>@dataclass<br>class Trajectory:<br>    goal: str<br>    steps: list = field(default_factory=list)<br>    answer: str | None = None<br>    stopped_because: str = &quot;&quot;<br>    final_thought: str = &quot;&quot;             # Part 3: the reasoning behind the answer<br><br>@dataclass<br>class ReActTurn:<br>    &quot;&quot;&quot;Part 3: what a ReAct policy returns - a thought plus the action it led to.<br>    action is a ToolCall, (&quot;final&quot;, answer), or a ToolError if the reply was unreadable.&quot;&quot;&quot;<br>    thought: str<br>    action: object<br>    raw: list | None = None<br><br>class Agent:<br>    &quot;&quot;&quot;policy(goal, steps) -&gt; an action, or (&quot;final&quot;, answer) to stop.<br>    Without tools, env(action) -&gt; observation string (Part 1 style).<br>    With a ToolRegistry, an action is a ToolCall or the JSON text of one (Part 2).<br>    A policy may wrap its action in a ReActTurn to attach its reasoning (Part 3).&quot;&quot;&quot;<br>    def __init__(self, policy, env=None, max_steps=20, tools=None, stop_on_tool_error=False):<br>        self.policy, self.env, self.max_steps = policy, env, max_steps<br>        self.tools = tools<br>        self.stop_on_tool_error = stop_on_tool_error   # &quot;fail fast&quot; harness, for comparison<br><br>    def run(self, goal):<br>        traj = Trajectory(goal)<br>        for _ in range(self.max_steps):<br>            decision = self.policy(goal, traj.steps)          # decide<br>            thought, raw = &quot;&quot;, None<br>            if isinstance(decision, ReActTurn):               # Part 3: unwrap the thought<br>                thought, raw, decision = decision.thought, decision.raw, decision.action<br>            if isinstance(decision, tuple) and decision[0] == &quot;final&quot;:<br>                traj.answer, traj.stopped_because = decision[1], &quot;done&quot;<br>                traj.final_thought = thought<br>                return traj<br>            if isinstance(decision, ToolError):               # Part 3: unreadable reply<br>                step = Step(&quot;&quot;, f&quot;error: {decision}&quot;, is_error=True)<br>            elif self.tools is None:                          # act (Part 1 path)<br>                step = Step(decision, self.env(decision))<br>            else:<br>                step = self.tools.run(decision)               # act (Part 2 path)<br>            step.thought, step.raw = thought, raw<br>            traj.steps.append(step)                           # observe<br>            if step.is_error and self.stop_on_tool_error:<br>                traj.stopped_because = &quot;tool error&quot;<br>                return traj<br>        traj.stopped_because = &quot;out of steps&quot;<br>        return traj</pre><p>Next, the new Part 3 block, which slots in right after the <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> ToolRegistry. build_react_prompt writes the prompt a text-only model sees, parse_react reads the reply back, and ReActPolicy glues them to any function that takes a prompt string and returns text.</p><pre># =====================================================================<br># Part 3: ReAct - Thought / Action / Observation as text<br># =====================================================================<br>REACT_INSTRUCTIONS = &quot;&quot;&quot;Answer the question by alternating Thought, Action and Observation.<br>Thought: reason about what you know so far and what to do next.<br>Action: exactly one of<br>  tool_name[{&quot;arg&quot;: value, ...}]   (JSON arguments)<br>  finish[your final answer]<br>After each Action, stop. The Observation will be written for you.&quot;&quot;&quot;<br><br>def format_tool_line(spec):<br>    params = spec[&quot;parameters&quot;].get(&quot;properties&quot;, {})<br>    args = &quot;, &quot;.join(f&quot;{k}: {v.get(&#39;type&#39;, &#39;any&#39;)}&quot; for k, v in params.items())<br>    return f&quot;- {spec[&#39;name&#39;]}({args}): {spec[&#39;description&#39;]}&quot;<br><br>def format_action(step):<br>    if step.call is None:                              # unreadable reply: show what it said<br>        return step.action or &quot;(no action)&quot;<br>    return f&quot;{step.call.name}[{json.dumps(step.call.arguments)}]&quot;<br><br>def build_react_prompt(goal, steps, registry):<br>    &quot;&quot;&quot;The whole prompt a text-only model sees: instructions, tools, and the scratchpad.&quot;&quot;&quot;<br>    lines = [REACT_INSTRUCTIONS, &quot;&quot;, &quot;Tools:&quot;] + [format_tool_line(s) for s in registry.specs()]<br>    lines += [&quot;&quot;, f&quot;Question: {goal}&quot;]<br>    for s in steps:                                    # the scratchpad grows by 3 lines a step<br>        lines += [f&quot;Thought: {s.thought}&quot;, f&quot;Action: {format_action(s)}&quot;,<br>                  f&quot;Observation: {s.observation}&quot;]<br>    lines.append(&quot;Thought:&quot;)                           # nudge the model to think first<br>    return &quot;\n&quot;.join(lines)<br><br>_LABEL = r&quot;^[ \t]*{}[ \t]*:[ \t]*&quot;                      # &quot;Action:&quot; at a line start, any case<br><br>def parse_react(text):<br>    &quot;&quot;&quot;Split a model reply into (thought, action). action is a ToolCall or (&quot;final&quot;, answer).<br>    Forgiving about case, spacing, code fences and chatter after the action. Raises ToolError<br>    with a message the model can act on when the reply cannot be read.&quot;&quot;&quot;<br>    text = text.replace(&quot;```&quot;, &quot;&quot;)<br>    fake = re.search(_LABEL.format(&quot;observation&quot;), text, re.I | re.M)<br>    if fake:                                           # the model invented an Observation:<br>        text = text[:fake.start()]                     # that is the environment&#39;s job, cut it<br>    act = re.search(_LABEL.format(&quot;action&quot;), text, re.I | re.M)<br>    if act is None:<br>        raise ToolError(&#39;no &quot;Action:&quot; line found. Reply with &quot;Thought: ...&quot; then &#39;<br>                        &#39;&quot;Action: tool_name[{json args}]&quot; or &quot;Action: finish[answer]&quot;&#39;)<br>    thought = re.sub(_LABEL.format(&quot;thought&quot;), &quot;&quot;, text[:act.start()], flags=re.I | re.M).strip()<br>    rest = text[act.end():].strip()<br>    m = re.match(r&quot;([A-Za-z_]\w*)\s*\[&quot;, rest)<br>    if m is None:<br>        raise ToolError(f&#39;could not read the action {rest[:40]!r}; expected name[...]&#39;)<br>    name, body = m.group(1), rest[m.end():]<br>    if name.lower() == &quot;finish&quot;:                       # the answer runs to the last &quot;]&quot;<br>        end = body.rfind(&quot;]&quot;)<br>        if end == -1:<br>            raise ToolError(&#39;finish[...] is missing its closing &quot;]&quot;&#39;)<br>        return thought, (&quot;final&quot;, body[:end].strip())<br>    try:                                               # JSON may itself contain &quot;]&quot;<br>        args, _ = json.JSONDecoder().raw_decode(body.lstrip())<br>    except json.JSONDecodeError as e:<br>        raise ToolError(f&quot;arguments for {name} are not valid JSON ({e.msg} at char {e.pos})&quot;)<br>    if not isinstance(args, dict):<br>        raise ToolError(f&quot;arguments for {name} must be a JSON object&quot;)<br>    return thought, ToolCall(name, args)<br><br>class ReActPolicy:<br>    &quot;&quot;&quot;Turns any text-in, text-out function llm(prompt) -&gt; str into an agent policy.&quot;&quot;&quot;<br>    def __init__(self, llm, registry):<br>        self.llm, self.registry = llm, registry<br>        self.prompts = []                              # kept for inspection and charts<br><br>    def __call__(self, goal, steps):<br>        prompt = build_react_prompt(goal, steps, self.registry)<br>        self.prompts.append(prompt)<br>        reply = self.llm(prompt)<br>        try:<br>            thought, action = parse_react(reply)<br>        except ToolError as e:<br>            return ReActTurn(reply.strip(), e)         # becomes an error observation<br>        return ReActTurn(thought, action)</pre><p>Three choices are worth a sentence. The parser cuts the reply at the first invented Observation before it looks for the action, so a fake tool result never reaches the scratchpad. It reads arguments with json.JSONDecoder().raw_decode, which decodes exactly one JSON value and stops, so a &quot;]&quot; inside a string or chatter after the call does not confuse it. And a parse failure returns a message saying which format to use, since <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> showed that the hint in an error is what lets the model recover.</p><p>Finally, the demo: a lookup tool over a one-entry toy encyclopedia, the two trip tools from <a href="https://medium.com/p/b08b83a1ad50">Part 2</a>, and scripted_react_llm as the model. Like any text model, it sees only the prompt string and reacts to the last Observation in it. I made it sloppy on purpose in its third and fourth replies: a lowercase &quot;action:&quot; with chatter after it, and an invented Observation claiming &quot;about 300 USD&quot;.</p><pre># =====================================================================<br># Part 3 demo: a two-hop question. The answer needs a fact the question does not give.<br># =====================================================================<br>react_tools = ToolRegistry()<br>react_tools.tools.update(trip_tools.tools)               # reuse the Part 2 tools<br>TOY_WIKI = {&quot;Atlantic AI Summit&quot;: &quot;The Atlantic AI Summit is a (fictional) conference held &quot;<br>                                  &quot;in Porto. The 2026 edition runs 3 nights.&quot;}<br><br>@react_tools.tool(&quot;Look up a short encyclopedia entry by its exact title.&quot;,<br>                  {&quot;type&quot;: &quot;object&quot;, &quot;properties&quot;: {&quot;title&quot;: {&quot;type&quot;: &quot;string&quot;}},<br>                   &quot;required&quot;: [&quot;title&quot;], &quot;additionalProperties&quot;: False})<br>def lookup(title):<br>    if title in TOY_WIKI:<br>        return {&quot;title&quot;: title, &quot;text&quot;: TOY_WIKI[title]}<br>    close = [t for t in TOY_WIKI if set(title.lower().split()) &amp; set(t.lower().split())]<br>    raise ToolError(f&quot;no entry titled {title!r}&quot; + (f&quot;; similar: {&#39;, &#39;.join(close)}&quot; if close else &quot;&quot;))<br><br>def scripted_react_llm(prompt):<br>    &quot;&quot;&quot;Scripted stand-in for a language model: text in, text out. It reads only the<br>    prompt string (the last Observation), exactly as a real text model would.&quot;&quot;&quot;<br>    obs = re.findall(r&quot;^Observation: (.*)$&quot;, prompt, re.M)<br>    last = obs[-1] if obs else &quot;&quot;<br>    if not obs:<br>        return (&#39;Thought: I need the summit\&#39;s city and length before I can price anything. &#39;<br>                &#39;I will look it up.\nAction: lookup[{&quot;title&quot;: &quot;Atlantic Summit&quot;}]&#39;)<br>    if &quot;similar:&quot; in last:<br>        title = last.split(&quot;similar: &quot;)[1].split(&quot;, &quot;)[0]<br>        return (f&quot;Thought: Wrong title. The error suggests {title!r}, so I will retry with it.\n&quot;<br>                f&#39;Action: lookup[{{&quot;title&quot;: &quot;{title}&quot;}}]&#39;)<br>    if &#39;&quot;text&quot;&#39; in last:<br>        return (&quot;Thought: The summit is in Porto for 3 nights. Next, the hotel price.\n&quot;<br>                &#39;action: get_hotel_price[{&quot;city&quot;: &quot;Porto&quot;, &quot;nights&quot;: 3}]\n&#39;<br>                &quot;I will wait for the price.&quot;)             # sloppy case + chatter: still parses<br>    if &#39;&quot;EUR&quot;&#39; in last:<br>        eur = json.loads(last)[&quot;total&quot;]<br>        return (f&quot;Thought: The hotel costs {eur} EUR. The question asks for USD, so convert.\n&quot;<br>                f&#39;Action: convert_currency[{{&quot;amount&quot;: {eur}, &quot;from_currency&quot;: &quot;EUR&quot;, &#39;<br>                f&#39;&quot;to_currency&quot;: &quot;USD&quot;}}]\nObservation: about 300 USD&#39;)   # a made-up observation<br>    usd = json.loads(last)[&quot;amount&quot;]<br>    return (f&quot;Thought: {usd} USD is the converted total. I have everything I need.\n&quot;<br>            f&quot;Action: finish[3 hotel nights for the Atlantic AI Summit cost about {usd:.2f} USD &quot;<br>            f&quot;(toy prices)]&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    for name, pol in [(&quot;bisect&quot;, bisect_policy), (&quot;blind&quot;, blind_policy)]:<br>        t = Agent(pol, number_env).run(&quot;Find the hidden number between 1 and 1000&quot;)<br>        calls = len(t.steps)<br>        print(f&quot;Part 1, {name} policy: {t.answer} ({t.stopped_because} after {calls} &quot;<br>              f&quot;tool call{&#39;s&#39; * (calls != 1)})&quot;)<br><br>    t = Agent(clumsy_trip_policy, tools=trip_tools).run(&quot;What do 3 nights in Lisbon cost in USD?&quot;)<br>    print(f&quot;Part 2, clumsy trip policy: {t.answer} ({t.stopped_because} after &quot;<br>          f&quot;{len(t.steps)} tool calls, {sum(s.is_error for s in t.steps)} errors)&quot;)<br><br>    print(&quot;\n--- Part 3: ReAct ---&quot;)<br>    policy = ReActPolicy(scripted_react_llm, react_tools)<br>    t = Agent(policy, tools=react_tools).run(<br>        &quot;What do the hotel nights for the Atlantic AI Summit cost in USD?&quot;)<br>    for i, s in enumerate(t.steps, 1):<br>        print(f&quot;Thought {i}: {s.thought}\nAction {i}: {format_action(s)}\n&quot;<br>              f&quot;Observation {i}: {s.observation}&quot;)<br>    print(f&quot;Final thought: {t.final_thought}\nAnswer: {t.answer} &quot;<br>          f&quot;({t.stopped_because} after {len(t.steps)} tool calls)&quot;)<br>    print(f&quot;prompt size: {len(policy.prompts[0])} characters at step 1, &quot;<br>          f&quot;{len(policy.prompts[-1])} at step {len(policy.prompts)}&quot;)</pre><p>Running python tiny_agent.py prints this. The <a href="https://medium.com/p/3e839ba288b8">Part 1</a> and <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> demos still pass.</p><pre>Part 1, bisect policy: The number is 737 (done after 10 tool calls)<br>Part 1, blind policy: The number is 500 (done after 1 tool call)<br>Part 2, clumsy trip policy: 3 nights in Lisbon cost about 388.80 USD (toy prices) (done after 4 tool calls, 2 errors)<br><br>--- Part 3: ReAct ---<br>Thought 1: I need the summit&#39;s city and length before I can price anything. I will look it up.<br>Action 1: lookup[{&quot;title&quot;: &quot;Atlantic Summit&quot;}]<br>Observation 1: error: no entry titled &#39;Atlantic Summit&#39;; similar: Atlantic AI Summit<br>Thought 2: Wrong title. The error suggests &#39;Atlantic AI Summit&#39;, so I will retry with it.<br>Action 2: lookup[{&quot;title&quot;: &quot;Atlantic AI Summit&quot;}]<br>Observation 2: {&quot;title&quot;: &quot;Atlantic AI Summit&quot;, &quot;text&quot;: &quot;The Atlantic AI Summit is a (fictional) conference held in Porto. The 2026 edition runs 3 nights.&quot;}<br>Thought 3: The summit is in Porto for 3 nights. Next, the hotel price.<br>Action 3: get_hotel_price[{&quot;city&quot;: &quot;Porto&quot;, &quot;nights&quot;: 3}]<br>Observation 3: {&quot;city&quot;: &quot;Porto&quot;, &quot;nights&quot;: 3, &quot;total&quot;: 285, &quot;currency&quot;: &quot;EUR&quot;}<br>Thought 4: The hotel costs 285 EUR. The question asks for USD, so convert.<br>Action 4: convert_currency[{&quot;amount&quot;: 285, &quot;from_currency&quot;: &quot;EUR&quot;, &quot;to_currency&quot;: &quot;USD&quot;}]<br>Observation 4: {&quot;amount&quot;: 307.8, &quot;currency&quot;: &quot;USD&quot;}<br>Final thought: 307.8 USD is the converted total. I have everything I need.<br>Answer: 3 hotel nights for the Atlantic AI Summit cost about 307.80 USD (toy prices) (done after 4 tool calls)<br>prompt size: 727 characters at step 1, 1651 at step 5</pre><p>The first lookup fails on a wrong title, and the second thought repairs it by reading the hint inside the error. Step 4 is the best part: the model claimed &quot;about 300 USD&quot;, the parser threw that line away, the real tool ran, and the answer uses the real 307.8. Meanwhile the prompt grew from 727 to 1,651 characters.</p><h4>Putting a chat model in the loop</h4><p>The text format above is how the original paper worked, and it still works with any model that reads and writes plain text. Most agents today talk to a chat model through native tool calling instead (the <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> way), and ReAct survives the move. The model replies with a text block and then a tool_use block. The text block is the Thought, the tool_use block is the Action, and the tool_result our code sends back is the Observation. Nobody parses an &quot;Action:&quot; line anymore, and the model cannot slip a fake observation into the transcript, because only our code writes tool_result blocks.</p><p>Two small additions to tiny_agent.py handle this, in Anthropic&#39;s message shape like <a href="https://medium.com/p/b08b83a1ad50">Part 2</a>&#39;s ToolChatPolicy. to_react_messages replays each step as an assistant turn with the thought as a text block in front of the tool_use block, so the model rereads its own reasoning next to every call and result. ReActChatPolicy sends the REACT_SYSTEM prompt from the adapters further down, splits each reply into a thought and an action, and treats a reply with only text as the answer. They slot in right after the Part 3 demo:</p><pre># =====================================================================<br># Part 3 (revisited): the same ReAct trip with a chat model and native tool calling<br># =====================================================================<br>def to_react_messages(goal, steps):<br>    &quot;&quot;&quot;Like to_tool_messages (Part 2), but every assistant turn carries the model&#39;s thought as<br>    a text block before its tool_use block, so on the next call the model reads its own<br>    earlier reasoning next to each action and result (Anthropic&#39;s message shape).&quot;&quot;&quot;<br>    messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}]<br>    for s in steps:<br>        if s.call is None:                             # unreadable call: show it as text<br>            messages += [{&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: s.action or &quot;(empty)&quot;},<br>                         {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: s.observation}]<br>            continue<br>        thought = [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: s.thought}] if s.thought else []<br>        messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: thought + [<br>            {&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: s.call.id, &quot;name&quot;: s.call.name, &quot;input&quot;: s.call.arguments}]})<br>        messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [<br>            {&quot;type&quot;: &quot;tool_result&quot;, &quot;tool_use_id&quot;: s.call.id, &quot;content&quot;: s.observation,<br>             &quot;is_error&quot;: s.is_error}]})<br>    return messages<br><br>class ReActChatPolicy:<br>    &quot;&quot;&quot;ReAct for a tool-calling chat model. llm(system, tools, messages) -&gt; content blocks.<br>    The model no longer writes &quot;Action:&quot; lines: the text block it writes before a tool_use<br>    block is the Thought, the tool_use block is the Action, and the tool_result we send back<br>    is the Observation. A reply with only text is the final answer.&quot;&quot;&quot;<br>    def __init__(self, llm, registry, system=REACT_SYSTEM):<br>        self.llm, self.system = llm, system<br>        self.tools = [{&quot;name&quot;: t[&quot;name&quot;], &quot;description&quot;: t[&quot;description&quot;],<br>                       &quot;input_schema&quot;: t[&quot;parameters&quot;]} for t in registry.specs()]<br>        self.requests = []                             # every transcript sent, for printing<br><br>    def __call__(self, goal, steps):<br>        messages = to_react_messages(goal, steps)<br>        self.requests.append(messages)<br>        reply = self.llm(self.system, self.tools, messages)<br>        thought = &quot;&quot;.join(b[&quot;text&quot;] for b in reply if b[&quot;type&quot;] == &quot;text&quot;).strip()<br>        for block in reply:<br>            if block[&quot;type&quot;] == &quot;tool_use&quot;:            # thought + action<br>                return ReActTurn(thought, ToolCall(block[&quot;name&quot;], block[&quot;input&quot;], block[&quot;id&quot;]))<br>        return ReActTurn(&quot;&quot;, (&quot;final&quot;, thought))       # text only: the answer<br><br>def scripted_react_chat_llm(system, tools, messages):<br>    &quot;&quot;&quot;Scripted stand-in for a tool-calling chat model doing the Part 3 trip. Like a real one,<br>    it sees only the system prompt, the tool list and the messages, and it answers with a<br>    text block (its reasoning) followed by a tool_use block, or with text alone at the end.&quot;&quot;&quot;<br>    n = sum(m[&quot;role&quot;] == &quot;assistant&quot; for m in messages)            # tool calls so far<br>    def act(thought, name, args):<br>        return [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: thought},<br>                {&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: f&quot;toolu_{n + 1:02d}&quot;, &quot;name&quot;: name, &quot;input&quot;: args}]<br>    if n == 0:<br>        return act(&quot;I need the summit&#39;s city and length before I can price anything.&quot;,<br>                   &quot;lookup&quot;, {&quot;title&quot;: &quot;Atlantic Summit&quot;})<br>    result = messages[-1][&quot;content&quot;][0]                             # the latest tool_result<br>    if result[&quot;is_error&quot;] and &quot;similar:&quot; in result[&quot;content&quot;]:<br>        title = result[&quot;content&quot;].split(&quot;similar: &quot;)[1].split(&quot;, &quot;)[0]<br>        return act(f&quot;Wrong title. The error suggests {title!r}, so I will retry with it.&quot;,<br>                   &quot;lookup&quot;, {&quot;title&quot;: title})<br>    data = json.loads(result[&quot;content&quot;])<br>    if &quot;text&quot; in data:<br>        return act(&quot;The summit is in Porto for 3 nights. Next, the hotel price.&quot;,<br>                   &quot;get_hotel_price&quot;, {&quot;city&quot;: &quot;Porto&quot;, &quot;nights&quot;: 3})<br>    if data.get(&quot;currency&quot;) == &quot;EUR&quot;:<br>        return act(f&quot;The hotel costs {data[&#39;total&#39;]} EUR. The question asks for USD, so convert.&quot;,<br>                   &quot;convert_currency&quot;, {&quot;amount&quot;: data[&quot;total&quot;], &quot;from_currency&quot;: &quot;EUR&quot;,<br>                                        &quot;to_currency&quot;: &quot;USD&quot;})<br>    return [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: f&quot;3 hotel nights for the Atlantic AI Summit cost about &quot;<br>                                     f&quot;{data[&#39;amount&#39;]:.2f} USD (toy prices).&quot;}]</pre><p>The model in this run, scripted_react_chat_llm, sees exactly what a real chat model would see: the system prompt, the tool specs and the messages. It answers in content blocks, so swapping in Claude changes nothing else. The bottom of the file runs the same summit question:</p><pre>    print(&quot;\n--- Part 3 (revisited): ReAct with a chat model ---&quot;)<br>    chat = ReActChatPolicy(scripted_react_chat_llm, react_tools)<br>    t = Agent(chat, tools=react_tools).run(<br>        &quot;What do the hotel nights for the Atlantic AI Summit cost in USD?&quot;)<br>    for i, s in enumerate(t.steps, 1):<br>        print(f&quot;{i}. text: {s.thought}\n   tool_use: {s.call.name}({json.dumps(s.call.arguments)})&quot;<br>              f&quot;\n   tool_result: {s.observation[:70] + (&#39;...&#39; if len(s.observation) &gt; 70 else &#39;&#39;)}&quot;)<br>    print(f&quot;Answer: {t.answer}&quot;)<br>    sizes = [len(json.dumps({&quot;system&quot;: chat.system, &quot;tools&quot;: chat.tools, &quot;messages&quot;: m}))<br>             for m in chat.requests]<br>    print(f&quot;{len(t.steps)} tool calls, {len(chat.requests)} model calls; request size &quot;<br>          f&quot;{sizes[0]:,} -&gt; {sizes[-1]:,} characters (system prompt + tool specs + messages)&quot;)<br>    last = chat.requests[-1][1][&quot;content&quot;]<br>    print(&quot;The model&#39;s first turn, as replayed in its last request:&quot;)<br>    print(&quot;  &quot; + json.dumps(last))</pre><p>It prints:</p><pre>--- Part 3 (revisited): ReAct with a chat model ---<br>1. text: I need the summit&#39;s city and length before I can price anything.<br>   tool_use: lookup({&quot;title&quot;: &quot;Atlantic Summit&quot;})<br>   tool_result: error: no entry titled &#39;Atlantic Summit&#39;; similar: Atlantic AI Summit<br>2. text: Wrong title. The error suggests &#39;Atlantic AI Summit&#39;, so I will retry with it.<br>   tool_use: lookup({&quot;title&quot;: &quot;Atlantic AI Summit&quot;})<br>   tool_result: {&quot;title&quot;: &quot;Atlantic AI Summit&quot;, &quot;text&quot;: &quot;The Atlantic AI Summit is a (...<br>3. text: The summit is in Porto for 3 nights. Next, the hotel price.<br>   tool_use: get_hotel_price({&quot;city&quot;: &quot;Porto&quot;, &quot;nights&quot;: 3})<br>   tool_result: {&quot;city&quot;: &quot;Porto&quot;, &quot;nights&quot;: 3, &quot;total&quot;: 285, &quot;currency&quot;: &quot;EUR&quot;}<br>4. text: The hotel costs 285 EUR. The question asks for USD, so convert.<br>   tool_use: convert_currency({&quot;amount&quot;: 285, &quot;from_currency&quot;: &quot;EUR&quot;, &quot;to_currency&quot;: &quot;USD&quot;})<br>   tool_result: {&quot;amount&quot;: 307.8, &quot;currency&quot;: &quot;USD&quot;}<br>Answer: 3 hotel nights for the Atlantic AI Summit cost about 307.80 USD (toy prices).<br>4 tool calls, 5 model calls; request size 1,293 -&gt; 3,067 characters (system prompt + tool specs + messages)<br>The model&#39;s first turn, as replayed in its last request:<br>  [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;I need the summit&#39;s city and length before I can price anything.&quot;}, {&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: &quot;toolu_01&quot;, &quot;name&quot;: &quot;lookup&quot;, &quot;input&quot;: {&quot;title&quot;: &quot;Atlantic Summit&quot;}}]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zqJJpjUhFsXe8q81UtUpg.png" /><figcaption><em>Left: the fifth request, where every thought (blue) sits in front of its tool call (orange) and result. Right: request size per model call</em></figcaption></figure><p>Same trip, same recovery from the wrong title, same 307.80 USD, but now each thought travels as a text block. That last printed line is the point: on its fifth call, the model rereads the thought it wrote on its first call, right next to the call it led to. There were 5 model calls for 4 tool calls, because the answer costs a call too. The request grew from 1,293 to 3,067 characters, and 1,182 of those are the system prompt and tool specs, sent again on every call.</p><p>With Claude it is one line, because <a href="https://medium.com/p/b08b83a1ad50">Part 2</a>&#39;s anthropic_tool_llm already returns text and tool_use blocks as dicts. It is an untested placeholder, not run for this post, so plug in your key to try it:</p><pre># Real-model version - UNTESTED, plug in your key; not run for this post. Part 2&#39;s<br># anthropic_tool_llm already returns text and tool_use blocks, so ReAct with Claude is:<br>#     ReActChatPolicy(anthropic_tool_llm, react_tools)</pre><h4>Plugging in a real model</h4><p>The two adapters from <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> get a ReAct upgrade. With native tool calling the model no longer writes &quot;Action:&quot; lines, but the thought survives. Claude can write a text block before its tool_use block, plus thinking blocks when extended thinking is on, and Anthropic&#39;s docs say the assistant message must be echoed back exactly as received, thinking blocks included (<a href="https://platform.claude.com/docs/en/build-with-claude/thinking-tool-workflows">thinking with tools</a>). OpenAI&#39;s reasoning models return reasoning items that the <a href="https://developers.openai.com/cookbook/examples/reasoning_function_calls">OpenAI cookbook</a> likewise says to keep next to their function calls.</p><p>So each adapter now sends a short ReAct-style system prompt, keeps the text written before the call as the step&#39;s thought, and stores the provider&#39;s whole output in Step.raw to replay untouched. Our agent runs one tool call per step, so any extra calls in the same turn get a polite &quot;not run&quot; result instead of vanishing. These are untested placeholders: plug in your key; they were not run for this post. Here are the new constants and the two rewritten __call__ methods (the constructors only gained a system or instructions argument).</p><pre>REACT_SYSTEM = (&quot;Before every tool call, write one or two sentences of reasoning: what you &quot;<br>                &quot;know so far and why this call is the next step. When you have the answer, &quot;<br>                &quot;reply with the answer only.&quot;)<br>SKIPPED = &quot;not run: this agent runs one tool call per step; ask again if you still need it&quot;<br><br>class AnthropicPolicy:<br>    &quot;&quot;&quot;UNTESTED placeholder. Needs `pip install anthropic`, ANTHROPIC_API_KEY and TINY_AGENT_MODEL.&quot;&quot;&quot;<br>    # __init__(self, registry, max_tokens=1024, system=REACT_SYSTEM): lazy import, as in Part 2<br><br>    def __call__(self, goal, steps):<br>        messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}]<br>        for s in steps:                                   # replay the trajectory<br>            if s.call is None:                            # unparseable action: show it as text<br>                messages += [{&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: s.action or &quot;(empty)&quot;},<br>                             {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: s.observation}]<br>                continue<br>            content = s.raw or [{&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: s.call.id, &quot;name&quot;: s.call.name,<br>                                 &quot;input&quot;: s.call.arguments}]<br>            messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: content})   # echoed exactly as received<br>            messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [<br>                {&quot;type&quot;: &quot;tool_result&quot;, &quot;tool_use_id&quot;: b[&quot;id&quot;],<br>                 &quot;content&quot;: s.observation if b[&quot;id&quot;] == s.call.id else SKIPPED,<br>                 &quot;is_error&quot;: s.is_error if b[&quot;id&quot;] == s.call.id else True}<br>                for b in content if b[&quot;type&quot;] == &quot;tool_use&quot;]})          # one result per tool_use<br>        resp = self.client.messages.create(model=self.model, max_tokens=self.max_tokens,<br>                                           system=self.system, tools=self.tools,<br>                                           messages=messages)<br>        thought = &quot;&quot;.join(b.text for b in resp.content if b.type == &quot;text&quot;)<br>        for block in resp.content:                        # stop_reason == &quot;tool_use&quot;<br>            if block.type == &quot;tool_use&quot;:                  # we run the first call only<br>                raw = [b.to_dict() for b in resp.content] # thinking, text, tool_use: all of it<br>                return ReActTurn(thought, ToolCall(block.name, dict(block.input), block.id), raw)<br>        return ReActTurn(&quot;&quot;, (&quot;final&quot;, thought))<br><br>class OpenAIPolicy:<br>    &quot;&quot;&quot;UNTESTED placeholder (Responses API). Needs `pip install openai`, OPENAI_API_KEY<br>    and TINY_AGENT_MODEL. Reasoning items are passed back next to their function calls.&quot;&quot;&quot;<br>    # __init__(self, registry, instructions=REACT_SYSTEM): lazy import, as in Part 2<br><br>    def __call__(self, goal, steps):<br>        items = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}]<br>        for s in steps:<br>            if s.call is None:<br>                items += [{&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: s.action or &quot;(empty)&quot;},<br>                          {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: s.observation}]<br>                continue<br>            items += s.raw or [{&quot;type&quot;: &quot;function_call&quot;, &quot;call_id&quot;: s.call.id,<br>                                &quot;name&quot;: s.call.name, &quot;arguments&quot;: json.dumps(s.call.arguments)}]<br>            items += [{&quot;type&quot;: &quot;function_call_output&quot;, &quot;call_id&quot;: i[&quot;call_id&quot;],<br>                       &quot;output&quot;: s.observation if i[&quot;call_id&quot;] == s.call.id else SKIPPED}<br>                      for i in (s.raw or items[-1:]) if i[&quot;type&quot;] == &quot;function_call&quot;]<br>        resp = self.client.responses.create(model=self.model, instructions=self.instructions,<br>                                            tools=self.tools, input=items)<br>        thought = &quot;&quot;.join(c.text for item in resp.output if item.type == &quot;message&quot;<br>                          for c in item.content if c.type == &quot;output_text&quot;)<br>        for item in resp.output:<br>            if item.type == &quot;function_call&quot;:              # arguments arrive as a JSON string<br>                try:<br>                    args = json.loads(item.arguments)<br>                except json.JSONDecodeError:<br>                    args = {&quot;_unparsed&quot;: item.arguments}  # the registry will reject it<br>                raw = [i.to_dict() for i in resp.output]  # reasoning, message, function calls<br>                return ReActTurn(thought, ToolCall(item.name, args, item.call_id), raw)<br>        return ReActTurn(&quot;&quot;, (&quot;final&quot;, resp.output_text))</pre><p>Both still import their SDK lazily and read the key and the TINY_AGENT_MODEL name from environment variables, so the file runs on the standard library alone. I checked the replay logic against fake response objects, which is not the same as a real API call, so expect to adjust a detail or two.</p><p>In Part 4, tiny_agent.py gets a Planner class and a re-planning hook.</p><h4>Why practitioners should care</h4><p>Almost nobody parses &quot;Action:&quot; lines in production anymore, because native tool calling took over that job, but the pattern underneath stayed. Anthropic has interleaved thinking, OpenAI has reasoning items that travel with function calls, and Sonnet 5.5 has a setting named after the idea; all three are ReAct by another name.</p><ul><li><strong>Debugging.</strong> Thoughts tell you whether the agent misread an observation or read it correctly and then chose badly. Those bugs have different fixes (a better tool description in one case, a better prompt or model in the other).</li><li><strong>Error recovery.</strong> Our trace recovered from a wrong title because a thought read the error. <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> made errors readable; ReAct gives the model a place to read them.</li><li><strong>Cost.</strong> Thoughts cost tokens, which means money and latency. That is why work like RACE (<a href="https://arxiv.org/abs/2610.12061">Cheng et al., 2026</a>) teaches agents which turns can skip the thinking.</li><li><strong>Faithfulness.</strong> A thought is text the model wrote, and it usually lines up with the action, which is what makes it useful. Treat it as evidence about the model&#39;s reasoning, not proof of it.</li></ul><p>The original <a href="https://arxiv.org/abs/2210.03629">paper</a> and <a href="https://github.com/ysymyth/react">code</a> are short and readable. With one or two examples, ReAct beat imitation and reinforcement learning baselines on ALFWorld and WebShop by 34 and 10 points of success rate respectively.</p><h4>Closing thoughts</h4><p>So our agent now has a notebook, a parser that forgives sloppy handwriting, and a firm policy against inventing its own observations, which is more than I can say for some meetings I have attended. It still decides one step at a time, though, squinting at the last observation and asking what to do next. Ask it to organize a three-city trip and it will happily book Lisbon before checking whether the train to Porto even runs that week. In Part 4 we give it a planner that writes the whole route first and re-plans when the world disagrees.</p><h4>References</h4><ol><li>Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, Yuan Cao. <a href="https://arxiv.org/abs/2210.03629"><em>ReAct: Synergizing Reasoning and Acting in Language Models</em></a>. arXiv:2210.03629, October 2022; ICLR 2023. Code: <a href="https://github.com/ysymyth/react">github.com/ysymyth/react</a>.</li><li>Yiruo Cheng, Shen Huang, Xiaoshuai Song, Jiejun Tan, Guanting Dong, Pengjun Xie, Ji-Rong Wen, Zhicheng Dou. <a href="https://arxiv.org/abs/2610.12061"><em>When Should Agents Think? Adaptive Reasoning via Cross-Turn Estimation</em></a>. arXiv:2610.12061, October 8, 2026.</li><li>Anthropic. <a href="https://platform.claude.com/docs/en/release-notes/overview"><em>Claude Platform release notes</em></a> (Sonnet 5.5 and the <em>between_tools</em> thinking setting, September 28, 2026).</li><li>Anthropic. <a href="https://platform.claude.com/docs/en/build-with-claude/thinking-tool-workflows"><em>Thinking in tool and multi-turn workflows</em></a>. Claude Platform docs.</li><li>OpenAI. <a href="https://developers.openai.com/cookbook/examples/reasoning_function_calls"><em>Managing Function Calls With Reasoning Models</em></a>. OpenAI Cookbook.</li><li><a href="https://medium.com/p/b08b83a1ad50"><em>AI Agents from Scratch, Part 2: Tool Calling</em></a>. Medium.</li><li><a href="https://medium.com/p/3e839ba288b8"><em>AI Agents from Scratch, Part 1: An Agent Is a Loop</em></a>. Medium.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7195a44864f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents from Scratch, Part 2: Tool Calling]]></title>
            <link>https://medium.com/@srivatsa.n63/ai-agents-from-scratch-part-2-tool-calling-b08b83a1ad50?source=rss-22246753979c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b08b83a1ad50</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Srivatsa Narasimha]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 03:31:01 GMT</pubDate>
            <atom:updated>2026-11-02T06:39:04.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDZpSCApyaf89YWHAJdm0A.png" /></figure><p>Ask a chat assistant for the weather in Lisbon and it tells you 19 degrees and cloudy. Ask an AI agent to fix a failing test and it opens files, runs the test suite and edits a line. Yet a language model (the neural network behind the assistant, which reads text and predicts more text) cannot touch your files or the network; all it ever produces is text. The small, unglamorous plumbing that turns that text into actions is called tool calling, and it is today&#39;s topic.</p><p>It is also a live topic. On 16 October 2026, Chattopadhyay, Halder and Roy posted <a href="https://arxiv.org/abs/2610.23342">Robust Function Calling for LLM Agents Under Interface Drift</a>, about agents whose tool descriptions change after deployment while the tools keep working. Their fix, SchemaShield-Lite, needs no training: it validates each call against the tool&#39;s schema, retries with the right tool list when the model names a tool that does not exist, and does one constrained repair. On a 200-task slice of the Berkeley Function Calling Leaderboard (a benchmark, which is a shared test set for comparing models) it lifted a small open Qwen model with 9 billion parameters (learned weights) from 58.0% to 80.5% accuracy, with the model itself left exactly as it was.</p><p>Quick recap. In <a href="https://medium.com/p/3e839ba288b8">Part 1</a> we saw that an agent is a loop: the model picks an action, the world executes it, the result comes back as an observation, and the model picks again until it is done or out of steps. We built that loop as tiny_agent.py, with a number-guessing game whose only action was the string &quot;guess 500&quot;, and then put a chat model in the policy seat, fishing &quot;guess 687&quot; out of its replies with a regular expression. That plain-string format works for exactly one action. It falls apart once the agent has two tools with their own arguments, and a model that sometimes writes &quot;three&quot; where you wanted 3.</p><p>So here is the question for Part 2: how does a model that only emits text ask for a function to run, how does your code know which function and which arguments, and what should happen when the model gets it wrong, which it will? My favourite example from today&#39;s demo is a hotel tool that multiplies the nightly price by the number of nights, handed the string &quot;3&quot; instead of the integer 3. Python happily repeats the string 120 times and returns a hotel bill of &#39;333333333333...&#39;, with no exception and no warning, which is about as confident and wrong as an invoice gets.</p><h3>The intuition: a diner who cannot cook</h3><p>Picture a restaurant where the customer is brilliant but cannot enter the kitchen. The customer is the model. To eat, they fill in an order slip with fixed boxes (dish, quantity, options), using a menu that says what each box accepts. A waiter checks the slip and takes it to the kitchen, and the plate comes back to the table.</p><p>Every part of tool calling has a spot in that picture.</p><ul><li><strong>The menu</strong> is the list of tool specs: each tool&#39;s name, a sentence on what it does, and a schema, which is a machine-readable description of a valid input (&quot;nights is an integer between 1 and 30&quot;).</li><li><strong>The order slip</strong> is the tool call, a small JSON message (JavaScript Object Notation, the curly-brace format that web APIs, the interfaces programs use to talk to each other, all speak) naming a tool and its arguments.</li><li><strong>The waiter</strong> is the harness, the ordinary code that parses the slip, checks it against the menu and decides whether the kitchen ever sees it.</li><li><strong>The kitchen</strong> is the tool: a Python function, an HTTP request, a database query. It has no idea a language model exists.</li><li><strong>The plate</strong> is the observation from <a href="https://medium.com/p/3e839ba288b8">Part 1</a>, the result the model reads next.</li></ul><p>The interesting part is what the waiter does with a bad slip, say &quot;three&quot; nights at a hotel, or a dish called &quot;convert&quot; that is not on the menu. A bad waiter either carries the nonsense straight to the kitchen, where the cook produces &#39;333333...&#39; and nobody notices, or throws the customer out (in code, an exception that kills the agent run). A good waiter walks back and says &quot;nights has to be a number, you wrote &#39;three&#39;&quot; or &quot;we have no convert, but we do have convert_currency&quot;, and the customer fixes the slip in one go.</p><p>Here is that happening in the real demo from later in this post, where a scripted stand-in plays the model and makes two mistakes on purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*syAhexSYs1wdfs_4UdKCYA.gif" /><figcaption><em>Two of the four calls never reach a tool. Each rejected call comes back as an observation, and the next call fixes exactly what the error named</em></figcaption></figure><h3>How it works</h3><p>A tool call is a round trip in four moves: you describe the tools, the model writes a call, the harness checks and runs it, and the result goes back as the next message.</p><p><strong>1. Describe the tools.</strong> Each tool gets a name, a description written for the model, and a parameter schema in JSON Schema, a standard vocabulary for saying &quot;this field is a string, that one is an integer of at least 1&quot;. Here is the hotel tool from today&#39;s demo, as the framework hands it to a model:</p><pre>{&quot;name&quot;: &quot;get_hotel_price&quot;,<br> &quot;description&quot;: &quot;Nightly hotel price in a city, times the number of nights, in EUR.&quot;,<br> &quot;parameters&quot;: {&quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {&quot;city&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [&quot;Lisbon&quot;, &quot;Porto&quot;]},<br>                               &quot;nights&quot;: {&quot;type&quot;: &quot;integer&quot;, &quot;minimum&quot;: 1, &quot;maximum&quot;: 30}},<br>                &quot;required&quot;: [&quot;city&quot;, &quot;nights&quot;], &quot;additionalProperties&quot;: false}}</pre><p><strong>2. The model writes a call.</strong> Modern models are fine-tuned (given extra training on examples) to answer with a structured call when a tool would help. <a href="https://arxiv.org/abs/2302.04761">Toolformer</a> (Schick and colleagues at Meta, February 2023) taught a model to insert API calls into its own text, and OpenAI added function calling to its API in June 2023. Today Anthropic&#39;s Messages API returns a tool_use block with an id, a name and an input object (and stop_reason &quot;tool_use&quot;), while OpenAI&#39;s Responses API returns a function_call item with a call_id, a name and the arguments as a JSON string you parse yourself.</p><p><strong>3. The harness checks it and runs it.</strong> This is the waiter. It parses the JSON, looks the name up in a registry (a dictionary from tool names to functions), validates the arguments against the schema, and only then calls the function.</p><p><strong>4. The result goes back.</strong> The result (or the error) goes back tagged with the call&#39;s id: a tool_result block with tool_use_id and an optional is_error flag for Anthropic, a function_call_output item with the matching call_id for OpenAI. Then the loop from <a href="https://medium.com/p/3e839ba288b8">Part 1</a> turns again.</p><h4>What the harness does with a bad call</h4><p>Step 3 is where the interesting design choice lives. Say a task needs k correct tool calls and the model malforms each call with probability p, independently. Compare three harnesses.</p><p>The <strong>abort</strong> harness raises an exception on the first bad call. The run survives only if all k calls are good on the first try:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*QbqrXsspQRNdJ3urgT8tGA.png" /></figure><p>This is the compounding error from <a href="https://medium.com/p/3e839ba288b8">Part 1</a> again. With p = 10% and k = 4, that is 0.9 to the fourth, about 66%.</p><p>The <strong>vague</strong> harness returns the word &quot;error&quot; and nothing else. The model knows something went wrong but not what, so the best it can do is write the call again and hope. Each needed call is then a coin that lands right with probability 1 - p, so it takes 1/(1 - p) attempts on average:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*qZtQhiHAfw_R1g6HbN1Hpw.png" /></figure><p>The <strong>specific</strong> harness returns the exact problem, such as &quot;arguments.nights must be integer, got str &#39;three&#39;&quot;. A model that reads it can fix that one field, so every bad call costs exactly one extra call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*GNfLNKUKn3gTVF_Op277zA.png" /></figure><p>To check this, I ran all three harnesses through tiny_agent.py itself, with a noisy scripted policy as the model. It needs 4 calls (two hotel lookups and two currency conversions), and each call it writes is malformed with probability p: a wrong type, a missing argument or a misspelled tool name. Under the specific harness it repairs exactly what the error names; under the vague one it can only redraw the call. Every run gets max_steps = 8, which leaves room for three mistakes. The noisy policy stands in for a language model, and its three mistakes are ones real models make; once the framework exists, I put a chat model in that seat. This is the whole experiment:</p><pre>&quot;&quot;&quot;How much does it matter what a harness does with a bad tool call?<br>A noisy scripted policy needs 4 correct tool calls. Each call it writes is<br>malformed with probability p (wrong type, missing argument, or wrong tool name).&quot;&quot;&quot;<br>import json, random<br>from tiny_agent import Agent, ToolRegistry, trip_tools<br><br>PLAN = [(&quot;get_hotel_price&quot;, {&quot;city&quot;: &quot;Lisbon&quot;, &quot;nights&quot;: 3}),<br>        (&quot;get_hotel_price&quot;, {&quot;city&quot;: &quot;Porto&quot;, &quot;nights&quot;: 2}),<br>        (&quot;convert_currency&quot;, {&quot;amount&quot;: 360, &quot;from_currency&quot;: &quot;EUR&quot;, &quot;to_currency&quot;: &quot;USD&quot;}),<br>        (&quot;convert_currency&quot;, {&quot;amount&quot;: 190, &quot;from_currency&quot;: &quot;EUR&quot;, &quot;to_currency&quot;: &quot;USD&quot;})]<br><br>def corrupt(name, args, rng):<br>    kind = rng.choice([&quot;type&quot;, &quot;missing&quot;, &quot;name&quot;])<br>    args = dict(args)<br>    key = next(iter(args))<br>    if kind == &quot;type&quot;: args[key] = str(args[key]) + &quot;!&quot;     # e.g. &quot;Lisbon!&quot; or &quot;3!&quot;<br>    elif kind == &quot;missing&quot;: del args[key]<br>    else: name = name.replace(&quot;_&quot;, &quot;&quot;)                      # getHotelPrice-ish typo<br>    return name, args<br><br>def make_policy(p, rng):<br>    def policy(goal, steps):<br>        done = sum(not s.is_error for s in steps)            # correct calls so far<br>        if done == len(PLAN):<br>            return (&quot;final&quot;, &quot;ok&quot;)<br>        name, args = PLAN[done]<br>        last = steps[-1] if steps else None<br>        specific = last is not None and last.is_error and last.observation != &quot;error&quot;<br>        if specific:                                         # a precise message names the problem,<br>            pass                                             # so the policy repairs that call<br>        elif rng.random() &lt; p:                               # otherwise: a fresh draw, may be bad again<br>            name, args = corrupt(name, args, rng)<br>        return json.dumps({&quot;tool&quot;: name, &quot;arguments&quot;: args})<br>    return policy<br><br>def success_rate(p, harness, trials=10_000, max_steps=8, seed=0):<br>    rng = random.Random(seed)<br>    tools = trip_tools if harness != &quot;vague&quot; else ToolRegistry(verbose_errors=False)<br>    if harness == &quot;vague&quot;: tools.tools = trip_tools.tools<br>    wins, calls = 0, 0<br>    for _ in range(trials):<br>        agent = Agent(make_policy(p, rng), tools=tools, max_steps=max_steps,<br>                      stop_on_tool_error=(harness == &quot;abort&quot;))<br>        t = agent.run(&quot;four lookups&quot;)<br>        wins += t.stopped_because == &quot;done&quot;<br>        calls += len(t.steps)<br>    return wins / trials, calls / trials<br><br>if __name__ == &quot;__main__&quot;:<br>    ps = [0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]<br>    out = {}<br>    for h in [&quot;abort&quot;, &quot;vague&quot;, &quot;specific&quot;]:<br>        out[h] = [success_rate(p, h) for p in ps]<br>    json.dump({&quot;ps&quot;: ps, **out}, open(&quot;results.json&quot;, &quot;w&quot;))<br>    print(f&quot;{&#39;p&#39;:&gt;5} | {&#39;abort&#39;:&gt;14} | {&#39;vague error&#39;:&gt;14} | {&#39;specific error&#39;:&gt;14}&quot;)<br>    for i, p in enumerate(ps):<br>        row = &quot; | &quot;.join(f&quot;{out[h][i][0]:6.1%} ({out[h][i][1]:.2f})&quot; for h in out)<br>        print(f&quot;{p:5.2f} | {row}&quot;)<br>    print(&quot;cells: success rate (mean tool calls per run); 4 calls needed, max_steps=8&quot;)</pre><p>The output:</p><pre>    p |         abort |   vague error | specific error<br> 0.00 | 100.0% (4.00) | 100.0% (4.00) | 100.0% (4.00)<br> 0.05 |  80.8% (3.70) | 100.0% (4.22) | 100.0% (4.21)<br> 0.10 |  65.5% (3.45) |  99.7% (4.45) | 100.0% (4.40)<br> 0.15 |  52.0% (3.18) |  98.9% (4.71) |  99.9% (4.61)<br> 0.20 |  40.6% (2.94) |  96.5% (5.01) |  99.8% (4.81)<br> 0.25 |  31.6% (2.73) |  92.7% (5.31) |  99.7% (5.01)<br> 0.30 |  24.1% (2.53) |  86.9% (5.63) |  99.3% (5.21)<br> 0.35 |  17.6% (2.33) |  79.1% (5.97) |  98.5% (5.42)<br> 0.40 |  12.7% (2.16) |  70.4% (6.29) |  97.4% (5.62)<br> 0.45 |   9.0% (2.02) |  60.7% (6.61) |  95.7% (5.81)<br> 0.50 |   6.3% (1.88) |  49.7% (6.91) |  93.5% (6.00)<br>cells: success rate (mean tool calls per run); 4 calls needed, max_steps=8</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxNjyvFYBVvOvzOsCA_36g.png" /><figcaption><em>Same model, same tools, three harnesses. Aborting follows (1 — p) to the fourth; precise errors stay above 93% even at a coin-flip error rate</em></figcaption></figure><p>The numbers follow the formulas. Abort tracks (1 - p)^4: 65.5% measured against 65.6% predicted at p = 10%. Specific needs 4(1 + p) calls on average, 4.40 at p = 10% and 6.00 at p = 50%. It loses a run only when all four first attempts are bad, because eight tool calls do not fit in a budget of seven (the eighth step is the final answer). That happens with probability p^4, 6.25% at p = 50%, hence the 93.5%.</p><p>At small p the vague harness is hard to tell apart from the specific one: its cost of 4/(1 - p) differs from 4(1 + p) by only about 4p^2, so at 10% you would never notice. At p = 50% it needs 8 calls on average against a budget of 7, and success drops to a coin flip, 49.7%. Mean calls also fall below the formula there, because the budget cuts the long runs short.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tuxr7cqq5fYVfXqAQXgyzw.png" /><figcaption><em>The measured cost of each harness against its formula. The vague curve peels away from 4/(1 — p) once the step budget starts cutting runs short</em></figcaption></figure><p>A real model will not repair errors as perfectly as a script, but the shape matches the <a href="https://arxiv.org/abs/2610.10062">Loud Failures, Quiet Failures</a> study (Kraishan, 7 October 2026), where six real models flagged a problem in 91.3% of trials when a tool returned an explicit error, but only 58.8% when it returned a plausible wrong value. Real models respond to explicit errors far more reliably than to silent wrong values.</p><h3>Building it from scratch: tiny_agent.py</h3><p>Our framework now gets a menu and a waiter. The file grows from about 60 to about 320 lines, still standard library only, so here are the new and changed parts and where they slot in. As in <a href="https://medium.com/p/3e839ba288b8">Part 1</a>, the &quot;model&quot; in every run shown is a scripted stand-in policy written in plain Python, not a real language model.</p><p>First, the loop. Step gains the structured call and an error flag, and when Agent has a tool registry, every action goes through it instead of a raw environment function. The <a href="https://medium.com/p/3e839ba288b8">Part 1</a> path still works, and stop_on_tool_error exists only to build the abort harness from the experiment.</p><pre>@dataclass<br>class Step:<br>    action: str<br>    observation: str<br>    call: &quot;ToolCall | None&quot; = None      # Part 2: the structured call, if any<br>    is_error: bool = False              # Part 2: did the tool call fail?<br><br>@dataclass<br>class Trajectory:<br>    goal: str<br>    steps: list = field(default_factory=list)<br>    answer: str | None = None<br>    stopped_because: str = &quot;&quot;<br><br>class Agent:<br>    &quot;&quot;&quot;policy(goal, steps) -&gt; an action, or (&quot;final&quot;, answer) to stop.<br>    Without tools, env(action) -&gt; observation string (Part 1 style).<br>    With a ToolRegistry, an action is a ToolCall or the JSON text of one (Part 2).&quot;&quot;&quot;<br>    def __init__(self, policy, env=None, max_steps=20, tools=None, stop_on_tool_error=False):<br>        self.policy, self.env, self.max_steps = policy, env, max_steps<br>        self.tools = tools<br>        self.stop_on_tool_error = stop_on_tool_error   # &quot;fail fast&quot; harness, for comparison<br><br>    def run(self, goal):<br>        traj = Trajectory(goal)<br>        for _ in range(self.max_steps):<br>            decision = self.policy(goal, traj.steps)          # decide<br>            if isinstance(decision, tuple) and decision[0] == &quot;final&quot;:<br>                traj.answer, traj.stopped_because = decision[1], &quot;done&quot;<br>                return traj<br>            if self.tools is None:                            # act (Part 1 path)<br>                traj.steps.append(Step(decision, self.env(decision)))<br>                continue<br>            step = self.tools.run(decision)                   # act (Part 2 path)<br>            traj.steps.append(step)                           # observe<br>            if step.is_error and self.stop_on_tool_error:<br>                traj.stopped_because = &quot;tool error&quot;<br>                return traj<br>        traj.stopped_because = &quot;out of steps&quot;<br>        return traj</pre><p>Next, the new Part 2 block, which sits right after the loop. It has four pieces: a Tool (name, description, schema, function), a ToolCall (what the model asked for), a small JSON Schema validator, and the ToolRegistry that ties them together.</p><pre>@dataclass<br>class Tool:<br>    name: str<br>    description: str            # what the model reads to decide when to use it<br>    parameters: dict            # a JSON-schema-style object schema<br>    fn: callable<br><br>    def spec(self):             # the provider-neutral spec we show to a model<br>        return {&quot;name&quot;: self.name, &quot;description&quot;: self.description,<br>                &quot;parameters&quot;: self.parameters}<br><br>@dataclass<br>class ToolCall:<br>    name: str<br>    arguments: dict<br>    id: str = &quot;&quot;                # providers attach an id so results can be matched to calls<br><br>class ToolError(Exception):<br>    pass<br><br>JSON_TYPES = {&quot;string&quot;: str, &quot;integer&quot;: int, &quot;number&quot;: (int, float),<br>              &quot;boolean&quot;: bool, &quot;array&quot;: list, &quot;object&quot;: dict}<br><br>def validate(value, schema, path=&quot;arguments&quot;):<br>    &quot;&quot;&quot;Check value against a small subset of JSON Schema. Returns a list of problems.&quot;&quot;&quot;<br>    problems = []<br>    t = schema.get(&quot;type&quot;)<br>    if t:<br>        ok = isinstance(value, JSON_TYPES[t])<br>        if t in (&quot;integer&quot;, &quot;number&quot;) and isinstance(value, bool):<br>            ok = False                                    # True is an int in Python, not in JSON<br>        if not ok:<br>            return [f&quot;{path} must be {t}, got {type(value).__name__} {value!r}&quot;]<br>    if &quot;enum&quot; in schema and value not in schema[&quot;enum&quot;]:<br>        problems.append(f&quot;{path} must be one of {schema[&#39;enum&#39;]}, got {value!r}&quot;)<br>    if &quot;minimum&quot; in schema and value &lt; schema[&quot;minimum&quot;]:<br>        problems.append(f&quot;{path} must be &gt;= {schema[&#39;minimum&#39;]}, got {value!r}&quot;)<br>    if &quot;maximum&quot; in schema and value &gt; schema[&quot;maximum&quot;]:<br>        problems.append(f&quot;{path} must be &lt;= {schema[&#39;maximum&#39;]}, got {value!r}&quot;)<br>    if t == &quot;array&quot; and &quot;items&quot; in schema:<br>        for i, item in enumerate(value):<br>            problems += validate(item, schema[&quot;items&quot;], f&quot;{path}[{i}]&quot;)<br>    if t == &quot;object&quot;:<br>        props = schema.get(&quot;properties&quot;, {})<br>        for key in schema.get(&quot;required&quot;, []):<br>            if key not in value:<br>                problems.append(f&quot;{path}.{key} is required&quot;)<br>        for key, item in value.items():<br>            if key in props:<br>                problems += validate(item, props[key], f&quot;{path}.{key}&quot;)<br>            elif schema.get(&quot;additionalProperties&quot;) is False:<br>                problems.append(f&quot;{path}.{key} is not a known parameter&quot;)<br>    return problems<br><br>def parse_tool_call(text):<br>    &quot;&quot;&quot;Turn model text like {&quot;tool&quot;: &quot;x&quot;, &quot;arguments&quot;: {...}} into a ToolCall.&quot;&quot;&quot;<br>    try:<br>        data = json.loads(text)<br>    except json.JSONDecodeError as e:<br>        raise ToolError(f&quot;could not parse tool call as JSON ({e.msg} at char {e.pos})&quot;)<br>    if not isinstance(data, dict) or &quot;tool&quot; not in data:<br>        raise ToolError(&#39;a tool call must be a JSON object with a &quot;tool&quot; key&#39;)<br>    args = data.get(&quot;arguments&quot;, {})<br>    if not isinstance(args, dict):<br>        raise ToolError(&#39;&quot;arguments&quot; must be a JSON object&#39;)<br>    return ToolCall(data[&quot;tool&quot;], args, data.get(&quot;id&quot;, &quot;&quot;))<br><br>class ToolRegistry:<br>    def __init__(self, verbose_errors=True):<br>        self.tools = {}<br>        self.verbose_errors = verbose_errors   # False = just say &quot;error&quot; (for comparison)<br><br>    def tool(self, description, parameters):<br>        &quot;&quot;&quot;Decorator: @registry.tool(&quot;what it does&quot;, {...schema...})&quot;&quot;&quot;<br>        def register(fn):<br>            self.tools[fn.__name__] = Tool(fn.__name__, description, parameters, fn)<br>            return fn<br>        return register<br><br>    def specs(self):<br>        return [t.spec() for t in self.tools.values()]<br><br>    def run(self, action):<br>        &quot;&quot;&quot;Execute one action. Never raises: every failure becomes an observation.&quot;&quot;&quot;<br>        call, text = None, action if isinstance(action, str) else &quot;&quot;<br>        try:<br>            call = action if isinstance(action, ToolCall) else parse_tool_call(action)<br>            text = text or json.dumps({&quot;tool&quot;: call.name, &quot;arguments&quot;: call.arguments})<br>            if call.name not in self.tools:<br>                raise ToolError(f&quot;unknown tool {call.name!r}; available: {&#39;, &#39;.join(self.tools)}&quot;)<br>            tool = self.tools[call.name]<br>            problems = validate(call.arguments, tool.parameters)<br>            if problems:<br>                raise ToolError(f&quot;invalid arguments for {call.name}: &quot; + &quot;; &quot;.join(problems))<br>            result = tool.fn(**call.arguments)<br>            return Step(text, json.dumps(result), call)<br>        except Exception as e:                         # ToolError or a bug inside the tool<br>            kind = &quot;&quot; if isinstance(e, ToolError) else f&quot;{type(e).__name__}: &quot;<br>            msg = f&quot;error: {kind}{e}&quot; if self.verbose_errors else &quot;error&quot;<br>            return Step(text, msg, call, is_error=True)</pre><ul><li><strong>The validator is about 30 lines</strong> and covers the slice of JSON Schema that tool specs use most: types, enums, bounds, required fields, array items and unknown keys. Note the bool check: in Python True is an int, so without it a model could book True nights.</li><li><strong>Errors carry a path</strong> such as arguments.nights, plus what was expected and what arrived. That is the whole difference between the vague and specific harnesses.</li><li><strong>ToolRegistry.run never raises.</strong> Bad JSON, unknown names, invalid arguments and even bugs inside a tool come back as a Step with is_error=True.</li></ul><p>Finally, the demo at the bottom of the file: two tools with toy prices and toy exchange rates (not live data), and a clumsy scripted policy that makes two classic mistakes and repairs each one only by reading the error text.</p><pre>trip_tools = ToolRegistry()<br>HOTEL_EUR = {&quot;Lisbon&quot;: 120, &quot;Porto&quot;: 95}                 # toy nightly prices<br>TOY_RATES = {(&quot;EUR&quot;, &quot;USD&quot;): 1.08, (&quot;USD&quot;, &quot;EUR&quot;): 0.93}  # toy rates, not live data<br><br>@trip_tools.tool(&quot;Nightly hotel price in a city, times the number of nights, in EUR.&quot;,<br>                 {&quot;type&quot;: &quot;object&quot;,<br>                  &quot;properties&quot;: {&quot;city&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: list(HOTEL_EUR)},<br>                                 &quot;nights&quot;: {&quot;type&quot;: &quot;integer&quot;, &quot;minimum&quot;: 1, &quot;maximum&quot;: 30}},<br>                  &quot;required&quot;: [&quot;city&quot;, &quot;nights&quot;], &quot;additionalProperties&quot;: False})<br>def get_hotel_price(city, nights):<br>    return {&quot;city&quot;: city, &quot;nights&quot;: nights, &quot;total&quot;: HOTEL_EUR[city] * nights, &quot;currency&quot;: &quot;EUR&quot;}<br><br>@trip_tools.tool(&quot;Convert an amount of money from one currency to another.&quot;,<br>                 {&quot;type&quot;: &quot;object&quot;,<br>                  &quot;properties&quot;: {&quot;amount&quot;: {&quot;type&quot;: &quot;number&quot;, &quot;minimum&quot;: 0},<br>                                 &quot;from_currency&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [&quot;EUR&quot;, &quot;USD&quot;]},<br>                                 &quot;to_currency&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [&quot;EUR&quot;, &quot;USD&quot;]}},<br>                  &quot;required&quot;: [&quot;amount&quot;, &quot;from_currency&quot;, &quot;to_currency&quot;],<br>                  &quot;additionalProperties&quot;: False})<br>def convert_currency(amount, from_currency, to_currency):<br>    rate = TOY_RATES[(from_currency, to_currency)]<br>    return {&quot;amount&quot;: round(amount * rate, 2), &quot;currency&quot;: to_currency}<br><br>def clumsy_trip_policy(goal, steps):<br>    &quot;&quot;&quot;Scripted stand-in for a model. It makes two classic mistakes and repairs<br>    each one only by reading the error message that comes back.&quot;&quot;&quot;<br>    if not steps:                                         # mistake 1: &quot;three&quot; is not an integer<br>        return &#39;{&quot;tool&quot;: &quot;get_hotel_price&quot;, &quot;arguments&quot;: {&quot;city&quot;: &quot;Lisbon&quot;, &quot;nights&quot;: &quot;three&quot;}}&#39;<br>    last = steps[-1]<br>    if last.is_error and &quot;nights must be integer&quot; in last.observation:<br>        return &#39;{&quot;tool&quot;: &quot;get_hotel_price&quot;, &quot;arguments&quot;: {&quot;city&quot;: &quot;Lisbon&quot;, &quot;nights&quot;: 3}}&#39;<br>    if not last.is_error and last.call.name == &quot;get_hotel_price&quot;:<br>        eur = json.loads(last.observation)[&quot;total&quot;]       # mistake 2: a tool that does not exist<br>        return json.dumps({&quot;tool&quot;: &quot;convert&quot;, &quot;arguments&quot;: {&quot;amount&quot;: eur, &quot;to&quot;: &quot;USD&quot;}})<br>    if last.is_error and &quot;unknown tool&quot; in last.observation:<br>        available = last.observation.split(&quot;available: &quot;)[1].split(&quot;, &quot;)<br>        name = [n for n in available if &quot;convert&quot; in n][0]   # pick the real name from the list<br>        eur = json.loads(steps[-2].observation)[&quot;total&quot;]<br>        return json.dumps({&quot;tool&quot;: name, &quot;arguments&quot;:<br>                           {&quot;amount&quot;: eur, &quot;from_currency&quot;: &quot;EUR&quot;, &quot;to_currency&quot;: &quot;USD&quot;}})<br>    usd = json.loads(last.observation)[&quot;amount&quot;]<br>    return (&quot;final&quot;, f&quot;3 nights in Lisbon cost about {usd:.2f} USD (toy prices)&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    for name, pol in [(&quot;bisect&quot;, bisect_policy), (&quot;blind&quot;, blind_policy)]:<br>        t = Agent(pol, number_env).run(&quot;Find the hidden number between 1 and 1000&quot;)<br>        calls = len(t.steps)<br>        print(f&quot;Part 1, {name} policy: {t.answer} ({t.stopped_because} after {calls} &quot;<br>              f&quot;tool call{&#39;s&#39; * (calls != 1)})&quot;)<br><br>    print(&quot;\n--- Part 2: tool calling ---&quot;)<br>    t = Agent(clumsy_trip_policy, tools=trip_tools).run(&quot;What do 3 nights in Lisbon cost in USD?&quot;)<br>    for i, s in enumerate(t.steps, 1):<br>        print(f&quot;step {i}: {s.action}\n     -&gt; {s.observation}&quot;)<br>    print(f&quot;answer: {t.answer} ({t.stopped_because} after {len(t.steps)} tool calls, &quot;<br>          f&quot;{sum(s.is_error for s in t.steps)} errors)&quot;)<br><br>    bill = get_hotel_price(&quot;Lisbon&quot;, &quot;3&quot;)[&quot;total&quot;]       # what skipping validation does<br>    print(f&quot;\nwithout validation, nights=&#39;3&#39; gives total = {bill[:12]!r}... ({len(bill)} characters)&quot;)</pre><p>Running python tiny_agent.py, with neither the anthropic nor the openai package installed, prints:</p><pre>Part 1, bisect policy: The number is 737 (done after 10 tool calls)<br>Part 1, blind policy: The number is 500 (done after 1 tool call)<br><br>--- Part 2: tool calling ---<br>step 1: {&quot;tool&quot;: &quot;get_hotel_price&quot;, &quot;arguments&quot;: {&quot;city&quot;: &quot;Lisbon&quot;, &quot;nights&quot;: &quot;three&quot;}}<br>     -&gt; error: invalid arguments for get_hotel_price: arguments.nights must be integer, got str &#39;three&#39;<br>step 2: {&quot;tool&quot;: &quot;get_hotel_price&quot;, &quot;arguments&quot;: {&quot;city&quot;: &quot;Lisbon&quot;, &quot;nights&quot;: 3}}<br>     -&gt; {&quot;city&quot;: &quot;Lisbon&quot;, &quot;nights&quot;: 3, &quot;total&quot;: 360, &quot;currency&quot;: &quot;EUR&quot;}<br>step 3: {&quot;tool&quot;: &quot;convert&quot;, &quot;arguments&quot;: {&quot;amount&quot;: 360, &quot;to&quot;: &quot;USD&quot;}}<br>     -&gt; error: unknown tool &#39;convert&#39;; available: get_hotel_price, convert_currency<br>step 4: {&quot;tool&quot;: &quot;convert_currency&quot;, &quot;arguments&quot;: {&quot;amount&quot;: 360, &quot;from_currency&quot;: &quot;EUR&quot;, &quot;to_currency&quot;: &quot;USD&quot;}}<br>     -&gt; {&quot;amount&quot;: 388.8, &quot;currency&quot;: &quot;USD&quot;}<br>answer: 3 nights in Lisbon cost about 388.80 USD (toy prices) (done after 4 tool calls, 2 errors)<br><br>without validation, nights=&#39;3&#39; gives total = &#39;333333333333&#39;... (120 characters)</pre><p>The first Part 2 call is rejected before get_hotel_price runs, with an error that names the field, the expected type and the value that arrived; the policy fixes it and gets 360 EUR. The second mistake is an invented tool name, and because the error lists the available tools, the policy picks convert_currency. The run still ends with the right answer after four calls, two of them errors. The last line is the quiet failure from the opening, the same function called with no validation.</p><h4>Putting a chat model in the loop</h4><p>Every run so far used a scripted policy that hands the registry JSON text directly. A real agent talks to a chat model behind an API, so here is the same trip from the model&#39;s side. With native tool calling, each request carries three things: a system prompt with standing instructions, the list of tool specs, and the transcript so far as messages tagged with roles (&quot;user&quot; for the person, &quot;assistant&quot; for the model). The reply is a list of content blocks. A text block is ordinary prose. A tool_use block is the order slip: an id, a tool name and an input object. The harness runs the tool and sends the result back in the next user message as a tool_result block with the same id, plus an is_error flag when the call failed. The model never runs anything; it only writes the slips.</p><p>I added exactly that to tiny_agent.py, in Anthropic&#39;s message shape because it maps one to one onto our Step. to_tool_messages turns the trajectory into that transcript, and ToolChatPolicy wraps any function llm(system, tools, messages) -&gt; blocks so the Agent can use it like any other policy. The scripted stand-in model sees only what a real model would see, and it makes the same two mistakes as before:</p><pre>TRIP_SYSTEM = (&quot;You help with travel costs. Use the tools instead of guessing prices or &quot;<br>               &quot;exchange rates. When you have the answer, reply with it in one sentence.&quot;)<br><br>def to_tool_messages(goal, steps):<br>    &quot;&quot;&quot;The transcript a tool-calling chat model sees (in Anthropic&#39;s message shape): the<br>    goal, then for every step the model&#39;s tool_use block and a user turn with its result.&quot;&quot;&quot;<br>    messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}]<br>    for s in steps:<br>        if s.call is None:                             # unreadable call: show it as text<br>            messages += [{&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: s.action or &quot;(empty)&quot;},<br>                         {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: s.observation}]<br>            continue<br>        messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: [<br>            {&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: s.call.id, &quot;name&quot;: s.call.name, &quot;input&quot;: s.call.arguments}]})<br>        messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [<br>            {&quot;type&quot;: &quot;tool_result&quot;, &quot;tool_use_id&quot;: s.call.id, &quot;content&quot;: s.observation,<br>             &quot;is_error&quot;: s.is_error}]})<br>    return messages<br><br>class ToolChatPolicy:<br>    &quot;&quot;&quot;Turns a tool-calling chat model into a policy. llm(system, tools, messages) -&gt; a list<br>    of content blocks. The tool specs go out with every request; a tool_use block in the<br>    reply becomes a ToolCall for the registry, and a reply with only text is the answer.&quot;&quot;&quot;<br>    def __init__(self, llm, registry, system=TRIP_SYSTEM):<br>        self.llm, self.system = llm, system<br>        self.tools = [{&quot;name&quot;: t[&quot;name&quot;], &quot;description&quot;: t[&quot;description&quot;],<br>                       &quot;input_schema&quot;: t[&quot;parameters&quot;]} for t in registry.specs()]<br>        self.requests = []                             # every transcript sent, for printing<br><br>    def __call__(self, goal, steps):<br>        messages = to_tool_messages(goal, steps)<br>        self.requests.append(messages)<br>        reply = self.llm(self.system, self.tools, messages)<br>        for block in reply:<br>            if block[&quot;type&quot;] == &quot;tool_use&quot;:            # the model asks for a tool<br>                return ToolCall(block[&quot;name&quot;], block[&quot;input&quot;], block[&quot;id&quot;])<br>        return (&quot;final&quot;, &quot;&quot;.join(b[&quot;text&quot;] for b in reply if b[&quot;type&quot;] == &quot;text&quot;))<br><br>def scripted_tool_llm(system, tools, messages):<br>    &quot;&quot;&quot;Scripted stand-in for a tool-calling chat model. Like a real one, it sees only the<br>    system prompt, the tool list and the messages, and it answers with content blocks.<br>    It makes the same two mistakes as clumsy_trip_policy and fixes each one only by<br>    reading what comes back.&quot;&quot;&quot;<br>    n = sum(m[&quot;role&quot;] == &quot;assistant&quot; for m in messages)            # tool calls so far<br>    def use(note, name, args):<br>        return [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: note},<br>                {&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: f&quot;toolu_{n + 1:02d}&quot;, &quot;name&quot;: name, &quot;input&quot;: args}]<br>    if n == 0:<br>        return use(&quot;First, the hotel price.&quot;, &quot;get_hotel_price&quot;, {&quot;city&quot;: &quot;Lisbon&quot;, &quot;nights&quot;: &quot;three&quot;})<br>    result = messages[-1][&quot;content&quot;][0]                             # the latest tool_result<br>    if result[&quot;is_error&quot;] and &quot;nights must be integer&quot; in result[&quot;content&quot;]:<br>        return use(&quot;nights must be a number, so 3.&quot;, &quot;get_hotel_price&quot;, {&quot;city&quot;: &quot;Lisbon&quot;, &quot;nights&quot;: 3})<br>    if result[&quot;is_error&quot;] and &quot;unknown tool&quot; in result[&quot;content&quot;]:<br>        name = [t[&quot;name&quot;] for t in tools if &quot;convert&quot; in t[&quot;name&quot;]][0]   # read the menu<br>        eur = json.loads(messages[-3][&quot;content&quot;][0][&quot;content&quot;])[&quot;total&quot;]<br>        return use(f&quot;No convert tool, but there is {name}.&quot;, name,<br>                   {&quot;amount&quot;: eur, &quot;from_currency&quot;: &quot;EUR&quot;, &quot;to_currency&quot;: &quot;USD&quot;})<br>    data = json.loads(result[&quot;content&quot;])<br>    if &quot;total&quot; in data:                                              # the hotel price is back<br>        return use(f&quot;{data[&#39;total&#39;]} EUR. Now to USD.&quot;, &quot;convert&quot;, {&quot;amount&quot;: data[&quot;total&quot;], &quot;to&quot;: &quot;USD&quot;})<br>    return [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: f&quot;3 nights in Lisbon cost about {data[&#39;amount&#39;]:.2f} USD (toy prices).&quot;}]</pre><p>The demo:</p><pre>import json<br>from tiny_agent import Agent, ToolChatPolicy, scripted_tool_llm, trip_tools<br><br>chat = ToolChatPolicy(scripted_tool_llm, trip_tools)<br>t = Agent(chat, tools=trip_tools).run(&quot;What do 3 nights in Lisbon cost in USD?&quot;)<br>print(&quot;Tools sent with every request:&quot;, [tool[&quot;name&quot;] for tool in chat.tools])<br>print(&quot;Messages sent on model call 3:&quot;)<br>for m in chat.requests[2]:<br>    print(f&quot;  {m[&#39;role&#39;]:&gt;9}: {json.dumps(m[&#39;content&#39;])}&quot;)<br>print(&quot;Its reply:&quot;, json.dumps(scripted_tool_llm(chat.system, chat.tools, chat.requests[2])))<br>print(f&quot;answer: {t.answer} ({t.stopped_because} after {len(t.steps)} tool calls, &quot;<br>      f&quot;{len(chat.requests)} model calls)&quot;)<br>tools_chars = len(json.dumps(chat.tools))<br>print(f&quot;characters per request: tools {tools_chars} +&quot;, [len(json.dumps(r)) for r in chat.requests])</pre><p>Output:</p><pre>Tools sent with every request: [&#39;get_hotel_price&#39;, &#39;convert_currency&#39;]<br>Messages sent on model call 3:<br>       user: &quot;What do 3 nights in Lisbon cost in USD?&quot;<br>  assistant: [{&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: &quot;toolu_01&quot;, &quot;name&quot;: &quot;get_hotel_price&quot;, &quot;input&quot;: {&quot;city&quot;: &quot;Lisbon&quot;, &quot;nights&quot;: &quot;three&quot;}}]<br>       user: [{&quot;type&quot;: &quot;tool_result&quot;, &quot;tool_use_id&quot;: &quot;toolu_01&quot;, &quot;content&quot;: &quot;error: invalid arguments for get_hotel_price: arguments.nights must be integer, got str &#39;three&#39;&quot;, &quot;is_error&quot;: true}]<br>  assistant: [{&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: &quot;toolu_02&quot;, &quot;name&quot;: &quot;get_hotel_price&quot;, &quot;input&quot;: {&quot;city&quot;: &quot;Lisbon&quot;, &quot;nights&quot;: 3}}]<br>       user: [{&quot;type&quot;: &quot;tool_result&quot;, &quot;tool_use_id&quot;: &quot;toolu_02&quot;, &quot;content&quot;: &quot;{\&quot;city\&quot;: \&quot;Lisbon\&quot;, \&quot;nights\&quot;: 3, \&quot;total\&quot;: 360, \&quot;currency\&quot;: \&quot;EUR\&quot;}&quot;, &quot;is_error&quot;: false}]<br>Its reply: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;360 EUR. Now to USD.&quot;}, {&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: &quot;toolu_03&quot;, &quot;name&quot;: &quot;convert&quot;, &quot;input&quot;: {&quot;amount&quot;: 360, &quot;to&quot;: &quot;USD&quot;}}]<br>answer: 3 nights in Lisbon cost about 388.80 USD (toy prices). (done after 4 tool calls, 5 model calls)<br>characters per request: tools 754 + [72, 434, 772, 1097, 1432]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZjFmD7eNmEpbWs7R8Ot9g.png" /><figcaption><em>The same trip through a chat model’s tool-calling interface. Results go back as user messages tied to the call’s id, and the tool list is sent again on every call</em></figcaption></figure><p>Three things are worth noticing. The failed call stays in the transcript with its error, so on call 3 the model can still see what went wrong two turns earlier. There were 5 model calls for 4 tool calls, because the final answer costs a call too. And the tool specs, 754 characters of JSON here, ride along on every request, so the request grew from 826 characters on the first call to 2,186 on the fifth. With a real model those characters are tokens (the word pieces a model reads and you pay for), which is one more reason a few clearly named tools beat a giant toolbox. The harness also drops the model&#39;s short text notes, such as &quot;360 EUR. Now to USD.&quot;; Part 3 keeps them.</p><p>Swapping in Claude is one small function, because ToolChatPolicy already speaks Anthropic&#39;s message shape:</p><pre><br>def anthropic_tool_llm(system, tools, messages):<br>    &quot;&quot;&quot;Needs `pip install anthropic`, ANTHROPIC_API_KEY and TINY_AGENT_MODEL.&quot;&quot;&quot;<br>    import anthropic<br>    resp = anthropic.Anthropic().messages.create(model=os.environ[&quot;TINY_AGENT_MODEL&quot;],<br>                                                 max_tokens=1024, system=system,<br>                                                 tools=tools, messages=messages)<br>    return [b.to_dict() for b in resp.content]       # text and tool_use blocks as dicts</pre><p>With it, Agent(ToolChatPolicy(anthropic_tool_llm, trip_tools), tools=trip_tools) runs the same trip with Claude. For OpenAI&#39;s format, and for a policy that keeps its own API client, use the two adapters below.</p><h4>Plugging in a real model</h4><p>The scripted policy already has the interface a real model needs: goal and steps in, a ToolCall or a final answer out, so a real model plugs in as one more policy. The two adapters below use each provider&#39;s native tool calling and follow the current docs for the <a href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls">Anthropic Messages API</a> and the <a href="https://developers.openai.com/api/docs/guides/function-calling">OpenAI Responses API</a>. They are untested placeholders, not run for this post; plug in your own key to try them. Each one imports its SDK (the provider&#39;s official Python package) only when you create it, and reads the key from ANTHROPIC_API_KEY or OPENAI_API_KEY and the model name from TINY_AGENT_MODEL, so the file still runs with the standard library alone.</p><pre>class AnthropicPolicy:<br>    &quot;&quot;&quot;UNTESTED placeholder. Needs `pip install anthropic`, ANTHROPIC_API_KEY and TINY_AGENT_MODEL.&quot;&quot;&quot;<br>    def __init__(self, registry, max_tokens=1024):<br>        import anthropic                                  # lazy import<br>        self.client = anthropic.Anthropic()               # reads ANTHROPIC_API_KEY<br>        self.model = os.environ[&quot;TINY_AGENT_MODEL&quot;]<br>        self.registry, self.max_tokens = registry, max_tokens<br>        self.tools = [{&quot;name&quot;: t[&quot;name&quot;], &quot;description&quot;: t[&quot;description&quot;],<br>                       &quot;input_schema&quot;: t[&quot;parameters&quot;]} for t in registry.specs()]<br><br>    def __call__(self, goal, steps):<br>        messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}]<br>        for s in steps:                                   # replay the trajectory<br>            if s.call is None:                            # unparseable action: show it as text<br>                messages += [{&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: s.action or &quot;(empty)&quot;},<br>                             {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: s.observation}]<br>                continue<br>            messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: [<br>                {&quot;type&quot;: &quot;tool_use&quot;, &quot;id&quot;: s.call.id, &quot;name&quot;: s.call.name,<br>                 &quot;input&quot;: s.call.arguments}]})<br>            messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [<br>                {&quot;type&quot;: &quot;tool_result&quot;, &quot;tool_use_id&quot;: s.call.id,<br>                 &quot;content&quot;: s.observation, &quot;is_error&quot;: s.is_error}]})<br>        resp = self.client.messages.create(model=self.model, max_tokens=self.max_tokens,<br>                                           tools=self.tools, messages=messages)<br>        for block in resp.content:                        # stop_reason == &quot;tool_use&quot;<br>            if block.type == &quot;tool_use&quot;:                  # first call only, one per step<br>                return ToolCall(block.name, dict(block.input), block.id)<br>        return (&quot;final&quot;, &quot;&quot;.join(b.text for b in resp.content if b.type == &quot;text&quot;))<br><br>class OpenAIPolicy:<br>    &quot;&quot;&quot;UNTESTED placeholder (Responses API). Needs `pip install openai`, OPENAI_API_KEY<br>    and TINY_AGENT_MODEL. Reasoning models may also want their reasoning items passed back.&quot;&quot;&quot;<br>    def __init__(self, registry):<br>        import openai                                     # lazy import<br>        self.client = openai.OpenAI()                     # reads OPENAI_API_KEY<br>        self.model = os.environ[&quot;TINY_AGENT_MODEL&quot;]<br>        self.tools = [{&quot;type&quot;: &quot;function&quot;, &quot;name&quot;: t[&quot;name&quot;], &quot;description&quot;: t[&quot;description&quot;],<br>                       &quot;parameters&quot;: t[&quot;parameters&quot;]} for t in registry.specs()]<br><br>    def __call__(self, goal, steps):<br>        items = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}]<br>        for s in steps:<br>            if s.call is None:<br>                items += [{&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: s.action or &quot;(empty)&quot;},<br>                          {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: s.observation}]<br>                continue<br>            items.append({&quot;type&quot;: &quot;function_call&quot;, &quot;call_id&quot;: s.call.id,<br>                          &quot;name&quot;: s.call.name, &quot;arguments&quot;: json.dumps(s.call.arguments)})<br>            items.append({&quot;type&quot;: &quot;function_call_output&quot;, &quot;call_id&quot;: s.call.id,<br>                          &quot;output&quot;: s.observation})<br>        resp = self.client.responses.create(model=self.model, tools=self.tools, input=items)<br>        for item in resp.output:<br>            if item.type == &quot;function_call&quot;:              # arguments arrive as a JSON string<br>                try:<br>                    args = json.loads(item.arguments)<br>                except json.JSONDecodeError:<br>                    args = {&quot;_unparsed&quot;: item.arguments}  # the registry will reject it<br>                return ToolCall(item.name, args, item.call_id)<br>        return (&quot;final&quot;, resp.output_text)</pre><p>Each adapter translates both ways: our specs into its API&#39;s shape (input_schema for Anthropic, a function tool with parameters for OpenAI), the Trajectory into call and result messages matched by id, and the native reply back into a ToolCall that the registry validates like any other. Usage: Agent(AnthropicPolicy(trip_tools), tools=trip_tools).run(&quot;What do 3 nights in Lisbon cost in USD?&quot;).</p><p>In Part 3, tiny_agent.py learns ReAct: a thought, action and observation format with a parser, so the agent writes down its reasoning between tool calls instead of jumping straight to the next one.</p><h3>Why practitioners should care</h3><p>Most agent frameworks contain some version of this registry, and much of the reliability work happens there.</p><ul><li><strong>Schemas are the shared language.</strong> The <a href="https://modelcontextprotocol.io/">Model Context Protocol</a> (MCP), introduced by Anthropic in November 2024, describes tool inputs with JSON Schema, the same vocabulary as our parameters dictionary. We will build a tiny MCP-style server in Part 14.</li><li><strong>Providers can constrain the model to the schema.</strong> OpenAI&#39;s strict mode, from its <a href="https://openai.com/index/introducing-structured-outputs-in-the-api/">Structured Outputs</a> release in August 2024, makes the arguments match your schema. It cannot check that Porto was the city the user meant, so validation still matters.</li><li><strong>Benchmarks measure this directly.</strong> The <a href="https://proceedings.mlr.press/v267/patil25a.html">Berkeley Function Calling Leaderboard</a> (Patil and colleagues, ICML 2025) is a benchmark, a shared test set for comparing models, that scores picking the right function with the right arguments.</li><li><strong>The tool list is part of the prompt.</strong> Distractor tools (irrelevant extras in the list the model reads before answering) did most of the damage in the interface-drift paper, so a few clearly named tools beat a giant toolbox.</li><li><strong>Validation only catches loud failures.</strong> A schema rejects &quot;three&quot;, but not 3 when the user said 4. That kind of recovery is Part 10.</li></ul><p>One caution to carry forward: a tool&#39;s output becomes text the model trusts, and a fetched web page can carry instructions aimed at the model. That is prompt injection, and it gets its own part later in the series.</p><h3>Closing</h3><p>So the model writes an order slip, a waiter with a clipboard checks it, and a kitchen that has never heard of language models does the cooking. The model gets the credit, but the waiter decides whether a typo ends the evening, wastes a few calls or quietly bills you &#39;333333...&#39; for a weekend in Lisbon. Ours is about a hundred lines of standard-library Python, and it lets a model that botches half its calls still finish more than nine tasks in ten, at least when the model listens. Next time, we make the model think out loud before it orders, with ReAct.</p><h3>References</h3><ol><li>A. Chattopadhyay, K. Halder, P. S. Roy. <em>Robust Function Calling for LLM Agents Under Interface Drift.</em> arXiv:2610.23342, 16 October 2026. <a href="https://arxiv.org/abs/2610.23342">https://arxiv.org/abs/2610.23342</a></li><li>O. Kraishan. <em>Loud Failures, Quiet Failures: Fault Detection and Recovery in Tool-Using Language Model Agents.</em> arXiv:2610.10062, 7 October 2026. <a href="https://arxiv.org/abs/2610.10062">https://arxiv.org/abs/2610.10062</a></li><li>T. Schick, J. Dwivedi-Yu, R. Dessì, R. Raileanu, M. Lomeli, L. Zettlemoyer, N. Cancedda, T. Scialom. <em>Toolformer: Language Models Can Teach Themselves to Use Tools.</em> arXiv:2302.04761, 2023. <a href="https://arxiv.org/abs/2302.04761">https://arxiv.org/abs/2302.04761</a></li><li>S. G. Patil et al. <em>The Berkeley Function Calling Leaderboard (BFCL): From Tool Use to Agentic Evaluation of Large Language Models.</em> ICML 2025, PMLR 267. <a href="https://proceedings.mlr.press/v267/patil25a.html">https://proceedings.mlr.press/v267/patil25a.html</a></li><li>Anthropic. <em>Handle tool calls</em> (Claude API documentation). <a href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls">https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls</a></li><li>OpenAI. <em>Function calling</em> (API documentation). <a href="https://developers.openai.com/api/docs/guides/function-calling">https://developers.openai.com/api/docs/guides/function-calling</a></li><li>OpenAI. <em>Introducing Structured Outputs in the API</em>, 6 August 2024. <a href="https://openai.com/index/introducing-structured-outputs-in-the-api/">https://openai.com/index/introducing-structured-outputs-in-the-api/</a></li><li>Model Context Protocol. <a href="https://modelcontextprotocol.io/">https://modelcontextprotocol.io/</a></li><li>AI Agents from Scratch, Part 1: An Agent Is a Loop. <a href="https://medium.com/p/3e839ba288b8">https://medium.com/p/3e839ba288b8</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b08b83a1ad50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents from Scratch, Part 1: An Agent Is a Loop]]></title>
            <link>https://medium.com/@srivatsa.n63/ai-agents-from-scratch-part-1-an-agent-is-a-loop-3e839ba288b8?source=rss-22246753979c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e839ba288b8</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Srivatsa Narasimha]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 21:30:16 GMT</pubDate>
            <atom:updated>2026-11-01T12:49:54.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNhtF5F4kNxkjaricwQFTw.png" /></figure><p>Everything has the word &quot;agent&quot; stapled to it this year. Your code editor has an agent, your browser has an agent, and I am fairly sure my toaster is in talks with a startup. Ask ten people what an agent actually is and you get ten answers, most of them involving the word &quot;autonomous&quot; and a slightly faraway look.</p><p>The research world has already moved on to the next layer. On 9 October 2026, Google Cloud AI Research posted <a href="https://arxiv.org/abs/2610.14224">Harness²</a>, a system that lets an agent rewrite its own <em>harness</em>, meaning the code wrapped around the model: its instructions, tools, memory and the routine that decides what to try next. With one round of self-editing, it reports gains of up to 11.5 points on an office-work benchmark (a standard test set) without touching the model&#39;s weights, its learned parameters. That is a big deal, and it is also a bit unfair to everyone who still has not been told what the thing inside the harness is.</p><p>So this is the start of a series, Agents from Scratch, where I build up agentic AI one concept per post, starting from zero. Today&#39;s concept is the one everything else hangs on. An agent is a language model (a model trained to predict the next word of text, like the ones behind ChatGPT or Claude) running in a loop. It looks at the world, decides on one action, takes it, looks at what happened, and goes around again until the job is done.</p><p>That sounds almost too small to deserve a post. But that loop is the difference between a 4% success rate and a 100% success rate in the little experiment below, on the exact same task with the exact same planner. By the end of this post you will know why, and you will be able to write the loop yourself in about fifteen lines.</p><h4>Printed directions versus a GPS</h4><p>If you are old enough, you remember printing driving directions before a trip. Turn left on Elm, go 2.3 miles, take exit 14. It worked beautifully until one road was closed. After that, every remaining instruction was confidently wrong, because the paper had no idea where you were.</p><p>A GPS does something much less impressive on paper. It only ever tells you the next turn. But after every turn it checks where you actually are and recomputes. Miss an exit and it says &quot;recalculating&quot; in that slightly judgemental voice, and you still get home.</p><p>A plain chatbot answering in one shot is the printed directions. It reads your request once and writes the whole answer from start to finish without ever checking anything against the world. An agent is the GPS. Here is the vocabulary I will use for the rest of the series:</p><ul><li><strong>Goal</strong>: what the user asked for (&quot;fix the failing test&quot;, &quot;book the cheapest flight&quot;).</li><li><strong>Environment</strong>: everything outside the model that it can affect, such as files, a browser, an API (a web service other programs can call) or a terminal.</li><li><strong>Action</strong>: one thing the model chooses to do, like running a command or calling a search tool.</li><li><strong>Observation</strong>: what comes back from the environment after an action, like the command output or the search results.</li><li><strong>Policy</strong>: the decision rule that picks the next action from everything seen so far. In a real agent, the policy is the language model.</li></ul><p>The loop is: observe, decide, act, repeat, and stop when the goal is met or the budget runs out. Anthropic&#39;s widely shared guide <a href="https://www.anthropic.com/research/building-effective-agents">Building effective agents</a> (December 2024) puts it plainly: agents &quot;are typically just LLMs using tools based on environmental feedback in a loop&quot; (LLMs being large language models). The same guide draws a useful line that I will lean on later. In a <em>workflow</em>, your code decides the sequence of steps and the model fills in the blanks. In an <em>agent</em>, the model itself decides what happens next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wUYMWGnOu4LsOTltmBqVw.png" /><figcaption><em>The agent loop. Most later posts in this series refine one of these boxes or arrows</em></figcaption></figure><p>Why start with a robot when everyone is building agents with language models? Because a robot makes the loop easy to see, and every piece of it has a direct counterpart in an LLM agent. The robot deciding its next move is the model choosing its next action. The maze is the environment, its walls are the constraints and rules the agent has to respect, and a slip is the model getting a step wrong. The code that feeds the robot its position and decides when to stop is the harness. A maze also makes mistakes easy to count, which the experiment below relies on. Swap the robot for a chat model that follows instructions and the loop stays exactly the same, which is what I do later in this post.</p><p>To see why the loop matters so much, I put two robots in a small maze. The floor is slippery: every step has a chance of sliding sideways instead of going where it was told. Both robots start with the same shortest-path plan. The orange one executes the plan blindly, like the printout. The blue one is an agent: after every step it looks at where it actually ended up and plans again from there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9zrBgZukNeM3Hgu9T5nsCw.gif" /><figcaption><em>Same maze, same 15% slip rate. The blind plan runs out of instructions far from the goal; the agent loop gets there in 36 steps</em></figcaption></figure><p>The blind robot&#39;s plan was optimal when the robot made it, but the robot never noticed the first slip, so every later move was correct for a position it was no longer in. The agent slipped plenty of times too, but it kept looking, so each slip cost it a step or two instead of the whole trip.</p><h4>The math</h4><p>Write the goal as g, the action at step t as aₜ and the observation that comes back as oₜ. An agent is a policy π that looks at the goal plus the whole history so far and picks the next action, and an environment that answers it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVjKOPk8ITQnLFdl_HxSlQ.png" /></figure><p>In a language model agent, that growing list (goal, action, observation, action, observation, …) is literally the conversation sitting in the model&#39;s context window, the text the model can see at once. The model reads the transcript and writes one more action. Keep that picture in mind, because a surprising number of later topics in this series (memory, context engineering, cost) are really about this list getting too long.</p><p>Now the open-loop version. It picks every action at time zero, before seeing any observation after the first. Suppose each step independently goes wrong with probability ε, and any uncorrected mistake ruins the task. Then an n-step plan succeeds only if every single step goes right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*4n88dlm46HwGJ6avY_u5SQ.png" /></figure><p>That is exponential decay in the task length. My maze&#39;s shortest path is 32 steps. With a 5% slip rate the formula gives 0.95³² ≈ 19.4%, and with 10% it gives 0.9³² ≈ 3.4%. So 90% per-step accuracy, which sounds great, gives a 32-step plan that almost never works end to end.</p><p>With the loop, success no longer needs every step to go right, only every mistake to be <em>noticed and repaired before the budget runs out</em>. A slip now costs a couple of extra moves, and the cost of an error stops multiplying and starts adding up. Here is the whole experiment. The plan function is a plain breadth-first search (BFS), which explores every square one step away, then two steps, and so on until it reaches the goal. It is standing in for the language model so that the comparison is exact and repeatable; after we build the framework, I put a language model in that seat.</p><pre>import numpy as np<br>from collections import deque<br>N = 12<br>WALLS = {(3, y) for y in range(0, 8)} | {(7, y) for y in range(4, 12)}<br>START, GOAL = (0, 0), (11, 11)<br>MOVES = {&quot;up&quot;: (0, 1), &quot;down&quot;: (0, -1), &quot;left&quot;: (-1, 0), &quot;right&quot;: (1, 0)}<br><br>class GridEnv:<br>    &quot;&quot;&quot;The world. Moves slip sideways with probability eps.&quot;&quot;&quot;<br>    def __init__(self, eps, rng):<br>        self.pos, self.eps, self.rng = START, eps, rng<br>    def step(self, action):<br>        dx, dy = MOVES[action]<br>        if self.rng.random() &lt; self.eps:          # slip: go sideways instead<br>            dx, dy = (dy, dx) if self.rng.random() &lt; .5 else (-dy, -dx)<br>        nx, ny = self.pos[0] + dx, self.pos[1] + dy<br>        if 0 &lt;= nx &lt; N and 0 &lt;= ny &lt; N and (nx, ny) not in WALLS:<br>            self.pos = (nx, ny)<br>        return self.pos                           # the observation<br><br>def plan(src, dst=GOAL):<br>    &quot;&quot;&quot;Shortest path by BFS (our stand-in for the model). Returns actions.&quot;&quot;&quot;<br>    prev, q = {src: None}, deque([src])<br>    while q:<br>        p = q.popleft()<br>        if p == dst: break<br>        for a, (dx, dy) in MOVES.items():<br>            n = (p[0] + dx, p[1] + dy)<br>            if 0 &lt;= n[0] &lt; N and 0 &lt;= n[1] &lt; N and n not in WALLS and n not in prev:<br>                prev[n] = (p, a); q.append(n)<br>    acts, p = [], dst<br>    while prev[p]: p, a = prev[p]; acts.append(a)<br>    return acts[::-1]<br><br>def open_loop(env, goal=GOAL):<br>    &quot;&quot;&quot;Plan once, then execute blindly.&quot;&quot;&quot;<br>    path = [env.pos]<br>    for a in plan(env.pos, goal):<br>        path.append(env.step(a))<br>    return path<br><br>def agent_loop(env, goal=GOAL, max_steps=60):<br>    &quot;&quot;&quot;Observe, decide, act, until done or out of budget.&quot;&quot;&quot;<br>    obs, path = env.pos, [env.pos]<br>    for _ in range(max_steps):<br>        if obs == goal: break                     # decide: am I done?<br>        action = plan(obs, goal)[0]               # decide: next action from the latest observation<br>        obs = env.step(action)                    # act, then observe the result<br>        path.append(obs)<br>    return path<br><br>for eps in [0.0, 0.05, 0.1, 0.2, 0.3]:<br>    rng = np.random.default_rng(0)<br>    o = [open_loop(GridEnv(eps, rng))[-1] == GOAL for _ in range(5000)]<br>    runs = [agent_loop(GridEnv(eps, rng)) for _ in range(5000)]<br>    c = [r[-1] == GOAL for r in runs]<br>    steps = np.mean([len(r) - 1 for r in runs if r[-1] == GOAL])<br>    print(f&quot;eps={eps:.2f}  open-loop {100*np.mean(o):5.1f}%  &quot;<br>          f&quot;agent loop {100*np.mean(c):5.1f}%  avg steps {steps:.1f}&quot;)</pre><p>Output:</p><pre>eps=0.00  open-loop 100.0%  agent loop 100.0%  avg steps 32.0<br>eps=0.05  open-loop  20.2%  agent loop 100.0%  avg steps 33.6<br>eps=0.10  open-loop   4.0%  agent loop 100.0%  avg steps 35.6<br>eps=0.20  open-loop   0.2%  agent loop  99.9%  avg steps 40.5<br>eps=0.30  open-loop   0.0%  agent loop  95.5%  avg steps 46.3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnS5wSiA-u-F1jQ83tVl3A.png" /></figure><p>The blind plan lands almost exactly on the formula column: 20.2% simulated against 19.4% predicted at a 5% slip rate, and 4.0% against 3.4% at 10%. It does slightly better than predicted because a slip is sometimes undone by accident: a later planned move pushes into a wall or the edge of the grid and the robot ends up back on its route, or a second slip cancels the first. That is the only kind of luck a blind robot gets. The agent loop, meanwhile, pays for its mistakes in steps: 35.6 steps on average at a 10% slip rate instead of the ideal 32.</p><p>To check the exponential shape directly, I moved the goal along the shortest path so the task took 4, 8, 12 and up to 32 steps, at a fixed 10% slip rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSsEuIAnueYgjD0XOtOxqQ.png" /><figcaption><em>Blind plans track the (1 − ε)ⁿ curve almost perfectly; the agent loop stays at 100% at every length</em></figcaption></figure><p>One row deserves a second look. At a 30% slip rate the agent loop drops to 95.5%, because some runs use up the 60-step budget while repairing slips. Every real agent has the same trade-off between letting it keep trying and stopping it before it burns your money, and I will give that its own post.</p><p>With a real language model in the decision seat, the loop keeps exactly this shape. The BFS becomes a model call, the grid becomes your tools, and the position becomes a tool result. I show what that looks like from the model&#39;s side in its own section below, once the framework exists.</p><h4>Building it from scratch: tiny_agent.py</h4><p>The maze was an experiment. Now I want a piece of code we can keep. Over this series I am going to build a small agent framework from scratch, one file, no libraries, adding one concept per part. Part 1 gives it its skeleton: a trajectory (the record of every action and observation), an Agent class that runs the loop, and a stop condition.</p><p>The design rule is that the agent does not care what the policy is. Today it is a scripted function; later in this post it becomes a chat model. The policy only ever sees the goal and the list of steps so far, which is exactly the transcript a model would see. It answers with either an action to run or a final answer.</p><pre>&quot;&quot;&quot;tiny_agent.py - Agents from Scratch, Part 1: the agent loop.&quot;&quot;&quot;<br>from dataclasses import dataclass, field<br><br>@dataclass<br>class Step:<br>    action: str<br>    observation: str<br><br>@dataclass<br>class Trajectory:<br>    goal: str<br>    steps: list = field(default_factory=list)<br>    answer: str | None = None<br>    stopped_because: str = &quot;&quot;<br><br>class Agent:<br>    &quot;&quot;&quot;policy(goal, steps) -&gt; an action string, or (&quot;final&quot;, answer) to stop.<br>    env(action) -&gt; an observation string.&quot;&quot;&quot;<br>    def __init__(self, policy, env, max_steps=20):<br>        self.policy, self.env, self.max_steps = policy, env, max_steps<br><br>    def run(self, goal):<br>        traj = Trajectory(goal)<br>        for _ in range(self.max_steps):<br>            decision = self.policy(goal, traj.steps)          # decide<br>            if isinstance(decision, tuple) and decision[0] == &quot;final&quot;:<br>                traj.answer, traj.stopped_because = decision[1], &quot;done&quot;<br>                return traj<br>            observation = self.env(decision)                  # act<br>            traj.steps.append(Step(decision, observation))    # observe<br>        traj.stopped_because = &quot;out of steps&quot;<br>        return traj<br><br># ---- a toy environment: a hidden number and one tool, guess(n) ----<br>SECRET = 737<br>def number_env(action):<br>    n = int(action.removeprefix(&quot;guess &quot;))<br>    if n &lt; SECRET: return &quot;too low&quot;<br>    if n &gt; SECRET: return &quot;too high&quot;<br>    return &quot;correct&quot;<br><br># ---- a scripted stand-in for the model: reads the history, picks the next action ----<br>def bisect_policy(goal, steps):<br>    lo, hi = 1, 1000<br>    for s in steps:                                       # everything it knows comes from observations<br>        n = int(s.action.removeprefix(&quot;guess &quot;))<br>        if s.observation == &quot;correct&quot;: return (&quot;final&quot;, f&quot;The number is {n}&quot;)<br>        if s.observation == &quot;too low&quot;: lo = n + 1<br>        else: hi = n - 1<br>    return f&quot;guess {(lo + hi) // 2}&quot;<br><br>def blind_policy(goal, steps):                            # ignores observations entirely<br>    return (&quot;final&quot;, &quot;The number is 500&quot;) if steps else &quot;guess 500&quot;<br><br>if __name__ == &quot;__main__&quot;:<br>    for name, pol in [(&quot;bisect&quot;, bisect_policy), (&quot;blind&quot;, blind_policy)]:<br>        t = Agent(pol, number_env).run(&quot;Find the hidden number between 1 and 1000&quot;)<br>        print(f&quot;--- {name} policy ---&quot;)<br>        for i, s in enumerate(t.steps, 1):<br>            print(f&quot;step {i}: {s.action:&lt;10} -&gt; {s.observation}&quot;)<br>        calls = len(t.steps)<br>        print(f&quot;answer: {t.answer}  ({t.stopped_because} after {calls} tool call{&#39;s&#39; * (calls != 1)})&quot;)</pre><p>Output:</p><pre>--- bisect policy ---<br>step 1: guess 500  -&gt; too low<br>step 2: guess 750  -&gt; too high<br>step 3: guess 625  -&gt; too low<br>step 4: guess 687  -&gt; too low<br>step 5: guess 718  -&gt; too low<br>step 6: guess 734  -&gt; too low<br>step 7: guess 742  -&gt; too high<br>step 8: guess 738  -&gt; too high<br>step 9: guess 736  -&gt; too low<br>step 10: guess 737  -&gt; correct<br>answer: The number is 737  (done after 10 tool calls)<br>--- blind policy ---<br>step 1: guess 500  -&gt; too low<br>answer: The number is 500  (done after 1 tool call)</pre><p>The bisecting policy halves the range on every observation and finds the number in 10 calls, which is about as good as it gets for 1,000 options, since 2¹⁰ = 1,024. The blind policy is the one-shot chatbot in miniature. It took an action, was told &quot;too low&quot;, and announced 500 anyway with total confidence. I have met people like this.</p><p>Notice what the framework already gives us for free: a full record of what happened (traj.steps), a reason for stopping (stopped_because), and a hard step limit so a confused policy cannot loop forever.</p><h4>Putting a language model in the loop</h4><p>So far the policy has been a plain Python function. In a real agent it is a chat model behind an API, so here is the same loop from the model&#39;s side. A chat model takes a list of messages, each tagged with a role (&quot;user&quot; for the person, &quot;assistant&quot; for the model&#39;s own earlier replies), plus an optional system prompt with standing instructions, and returns one new message. It keeps no memory between calls, and it cannot run anything itself.</p><p>Everything else is the job of the harness, the code around the model. On every turn the harness sends the whole transcript so far, reads an action out of the reply, runs that action against the environment, and appends the result as the next message. So in the observe, decide, act loop, the model only does the deciding, by writing text. Acting and observing are ordinary code.</p><p>I added exactly that to tiny_agent.py. to_messages turns the trajectory into a transcript, and ChatPolicy wraps any function llm(system, messages) -&gt; text so the Agent class can use it like any other policy:</p><pre>GUESS_SYSTEM = &quot;&quot;&quot;You are playing a guessing game. The user gives you the goal.<br>Each turn, reply with exactly one action on its own line:<br>  guess N (N is a whole number from 1 to 1000)<br>After each guess you will be told &quot;too low&quot;, &quot;too high&quot; or &quot;correct&quot;.<br>When you know the number, reply on its own line: final: &lt;your answer&gt;&quot;&quot;&quot;<br><br>def to_messages(goal, steps):<br>    &quot;&quot;&quot;The transcript a chat model sees: the goal, then every action it took<br>    (as its own earlier replies) and every observation (as the next user turn).&quot;&quot;&quot;<br>    messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}]<br>    for s in steps:<br>        messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: s.action})<br>        messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Observation: {s.observation}&quot;})<br>    return messages<br><br>class ChatPolicy:<br>    &quot;&quot;&quot;Turns a chat model into a policy. llm(system, messages) -&gt; reply text.<br>    The model keeps no memory between calls: every turn it is sent the whole transcript.&quot;&quot;&quot;<br>    def __init__(self, llm, system=GUESS_SYSTEM):<br>        self.llm, self.system = llm, system<br>        self.requests = []                             # every transcript sent, for printing<br><br>    def __call__(self, goal, steps):<br>        messages = to_messages(goal, steps)<br>        self.requests.append(messages)<br>        reply = self.llm(self.system, messages)        # the model writes one more message<br>        final = re.search(r&quot;^\s*final:\s*(.+)$&quot;, reply, re.I | re.M)<br>        if final:<br>            return (&quot;final&quot;, final.group(1).strip())<br>        guess = re.search(r&quot;^\s*guess\s+(\d+)\s*$&quot;, reply, re.I | re.M)<br>        if guess:                                      # the harness turns text into an action<br>            return f&quot;guess {guess.group(1)}&quot;<br>        return (&quot;final&quot;, f&quot;(gave up: could not read the reply {reply!r})&quot;)<br><br>def chat_llm(system, messages):<br>    &quot;&quot;&quot;it sees only the messages,<br>    so everything it knows about the number comes from the observations in them.&quot;&quot;&quot;<br>    lo, hi = 1, 1000<br>    for said, heard in zip(messages[1::2], messages[2::2]):   # (its reply, what came back)<br>        n = int(re.search(r&quot;\d+&quot;, said[&quot;content&quot;]).group())<br>        obs = heard[&quot;content&quot;].removeprefix(&quot;Observation: &quot;)<br>        if obs == &quot;correct&quot;:<br>            return f&quot;That was correct, so I am done.\nfinal: The number is {n}&quot;<br>        lo, hi = (n + 1, hi) if obs == &quot;too low&quot; else (lo, n - 1)<br>    return f&quot;The number is between {lo} and {hi}, so I will try the middle.\nguess {(lo + hi) // 2}&quot;</pre><p>The demo:</p><pre>from tiny_agent import Agent, ChatPolicy, chat_llm, number_env, GUESS_SYSTEM<br><br>chat = ChatPolicy(chat_llm)<br>t = Agent(chat, number_env).run(&quot;Find the hidden number between 1 and 1000&quot;)<br>print(&quot;What the model is sent on turn 4:&quot;)<br>for m in chat.requests[3]:<br>    print(f&quot;  {m[&#39;role&#39;]:&gt;9}: {m[&#39;content&#39;]}&quot;)<br>print(&quot;Its reply:&quot;, chat_llm(GUESS_SYSTEM, chat.requests[3]).replace(&quot;\n&quot;, &quot; | &quot;))<br>print(f&quot;answer: {t.answer} ({t.stopped_because} after {len(t.steps)} tool calls, &quot;<br>      f&quot;{len(chat.requests)} model calls)&quot;)<br>words = [sum(len(m[&quot;content&quot;].split()) for m in r) for r in chat.requests]<br>print(&quot;words sent per call:&quot;, words)</pre><p>Output:</p><pre>What the model is sent on turn 4:<br>       user: Find the hidden number between 1 and 1000<br>  assistant: guess 500<br>       user: Observation: too low<br>  assistant: guess 750<br>       user: Observation: too high<br>  assistant: guess 625<br>       user: Observation: too low<br>Its reply: The number is between 626 and 749, so I will try the middle. | guess 687<br>answer: The number is 737 (done after 10 tool calls, 11 model calls)<br>words sent per call: [8, 13, 18, 23, 28, 33, 38, 43, 48, 53, 57]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9f1CPe8yXO8RW-v3usTqrA.png" /><figcaption><em>The number game through a chat interface. Observations go back to the model as user messages written by the harness, and the whole transcript is sent again on every call</em></figcaption></figure><p>Three things are worth noticing. The harness pulled &quot;guess 687&quot; out of a reply that also held a sentence of reasoning, which is a first small taste of a real problem: models write prose, and programs need actions. There were 11 model calls for 10 tool calls, because the final answer costs a call too. And the transcript grew from 8 words to 57, since every turn re-sends everything before it. With a real model those words are tokens (the word pieces a model reads and you pay for) on every single call, which is why later parts of this series spend so much time on what goes into that list.</p><p>Swapping in a real model is one argument. These two functions plug Claude or an OpenAI model into ChatPolicy. Each reads its API key from the standard environment variable and the model name from TINY_AGENT_MODEL, and imports its SDK only when it is called, so tiny_agent.py still runs with nothing but the standard library:</p><pre> <br>def anthropic_chat_llm(system, messages):<br>    &quot;&quot;&quot;Needs `pip install anthropic`, ANTHROPIC_API_KEY and TINY_AGENT_MODEL.&quot;&quot;&quot;<br>    import anthropic<br>    resp = anthropic.Anthropic().messages.create(<br>        model=os.environ[&quot;TINY_AGENT_MODEL&quot;], max_tokens=256, system=system, messages=messages)<br>    return &quot;&quot;.join(b.text for b in resp.content if b.type == &quot;text&quot;)<br><br>def openai_chat_llm(system, messages):<br>    &quot;&quot;&quot;Needs `pip install openai`, OPENAI_API_KEY and TINY_AGENT_MODEL (Responses API).&quot;&quot;&quot;<br>    import openai<br>    resp = openai.OpenAI().responses.create(<br>        model=os.environ[&quot;TINY_AGENT_MODEL&quot;], instructions=system, input=messages)<br>    return resp.output_text</pre><p>With one of those, Agent(ChatPolicy(anthropic_chat_llm), number_env) plays the same game with Claude, and openai_chat_llm does the same with an OpenAI model. Asking a model to type &quot;guess 687&quot; on its own line and fishing it out with a regular expression works for one action, but it gets fragile fast once there are several tools with several arguments each. That is why, in <a href="https://medium.com/p/b08b83a1ad50">Part 2</a>, I replace the free-text actions with proper tool calls: structured requests that the model API itself understands.</p><h4>Why practitioners should care</h4><p>The loop is small, but it changes how you should think about building with language models in a few concrete ways.</p><ul><li><strong>An agent is only as good as what it can observe.</strong> The loop repairs errors it can see. My robot always knew its exact position, so every slip was visible one step later. Real agents are rarely that lucky. A coding agent that runs the test suite after each edit gets a crisp signal; one that never runs anything is back to printed directions, however many steps it takes. The Anthropic guide makes the same point: agents need &quot;ground truth&quot; from the environment at each step, such as tool results or code execution, to judge their progress.</li><li><strong>Silent errors still compound.</strong> If a step goes wrong in a way the observations do not reveal (a search result that is subtly outdated, a function that returns the wrong number without crashing), the loop carries on happily and the (1 − ε)ⁿ arithmetic comes back. A lot of real agent engineering is about turning silent errors into visible ones: tests, validators, assertions, a second model checking the first.</li><li><strong>You do not always need an agent.</strong> If you can write the steps down in advance (extract the fields, translate, summarise), a fixed workflow is cheaper and much easier to debug. The loop earns its cost when the right next step depends on what just happened, like debugging, research or navigating a website. My agent took 35.6 steps where the blind plan took 32, and each of those steps is a model call you pay for.</li><li><strong>The code around the loop matters as much as the model.</strong> That is the whole bet behind Harness²: the same model got noticeably better on professional tasks after its harness was edited, with the weights frozen. The loop, the tools it can reach, what goes into the history and when it stops are all design choices, and the rest of this series is about making them well.</li></ul><p>If you want to feel this in your hands, take the maze code, set max_steps=40, and watch what happens to the 30% row. Then let the robot look at its position only every eighth step. When I tried that at a 30% slip rate (2,000 runs), success fell from about 96% to about 33%, and the agent loop started to look a lot like the blind one.</p><h4>Closing thoughts</h4><p>So the next time a product page promises an autonomous agent, you can picture what is actually inside: a model, a list of tools and a for loop with a step limit, plus a lot of careful plumbing. I mean that kindly, since the GPS in your car is also just a loop, and I would still not trust myself to get anywhere without it. The interesting question is how the model turns &quot;what should I do next?&quot; into something a computer can actually run, and that is where <a href="https://medium.com/p/b08b83a1ad50">Part 2</a> picks up, with tool calling: how a model asks for a function to be executed and gets the result back.</p><h4>References</h4><ol><li>E. Schluntz and B. Zhang, <a href="https://www.anthropic.com/research/building-effective-agents"><em>Building effective agents</em></a>, Anthropic, December 2024.</li><li>R. Xu, Y. Chen, Z. CuiZhu, B. Dalvi Mishra, Y. Ming, H. Yu, R. Han, C.-Y. Lee and T. Pfister, <a href="https://arxiv.org/abs/2610.14224"><em>Harness²: Recursive Agent Harnessing for an Open World</em></a>, arXiv:2610.14224, October 2026.</li><li><a href="https://startupfortune.com/google-open-sources-harness2-letting-ai-agents-rewrite-their-own-playbook/"><em>Google open sources Harness2, letting AI agents rewrite their own playbook</em></a>, Startup Fortune, October 2026.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e839ba288b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention Is Not All You Need: How FNet Swapped It for a Fourier Transform]]></title>
            <link>https://medium.com/@srivatsa.n63/attention-is-not-all-you-need-how-fnet-swapped-it-for-a-fourier-transform-98e8b868aa80?source=rss-22246753979c------2</link>
            <guid isPermaLink="false">https://medium.com/p/98e8b868aa80</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Srivatsa Narasimha]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 05:39:26 GMT</pubDate>
            <atom:updated>2026-10-24T12:26:03.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>Attention Is <strong>NOT</strong> All You Need!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*1Z933GWlx_p2KNbySUIM3A.gif" /><figcaption>Circles spinning at different speeds, stacked tip to tail, trace out a drawing. Each circle is one Fourier frequency, and together they rebuild the whole shape.</figcaption></figure><p>When BERT was introduced in 2018, it revolutionised language understanding by replacing recurrence and convolution with self-attention. This mechanism allows each token in a sequence to dynamically “attend” to every other token. This innovation gave models an unprecedented ability to capture long-range dependencies: the relationship between the first word in a paragraph and the last one, the structure of syntax that spans clauses, and the coherence of entire sentences.</p><p>Mathematically, self-attention computes, for every token <em>i</em>, a context vector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*SEUwKmSe78uWF5VHR1Y_0g.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*qOqvICUWguI7Y5nuzeZJeA.png" /></figure><p>and,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*eAbU5C1LfTWB10RE6ImeJw.png" /></figure><p>are the input embeddings, <em>dₖ</em> is the key dimension, and <em>n</em> is the sequence length.</p><p>Powerful as it is, self-attention is expensive: its cost grows quadratically with sequence length:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*e4aT0gv3ClLats6cSHXwgw.png" /></figure><ul><li>Computing <em>QK^⊤</em> produces an <em>n×n</em> matrix of pairwise token interactions.</li><li>Each attention head must then multiply this by <em>V</em>, yielding <em>O(n²d)</em> time and memory complexity.</li></ul><p>As <em>n</em> grows, this quadratic scaling dominates every other part of the architecture. For example:</p><ul><li>A 512-token sequence requires 262,144 attention weights per head.</li><li>A 2048-token document expands that to over four million pairwise computations.</li></ul><p>That makes it inefficient for long documents, real-time tasks, and large-scale inference. When training or deploying massive models, this cost translates directly into GPU memory pressure, energy consumption, and latency.</p><h3>Enter <strong>FNet</strong>!</h3><p>FNet was introduced by Google Research in 2021 (Lee-Thorp et al.), achieving near-BERT performance without attention by replacing it with a Fourier Transform. The idea is to replace self-attention in the encoder with a simple linear (even parameter-free) mixing mechanism — specifically leveraging the Fourier Transform as a token-mixing strategy. The authors show that it trains 80% faster on GPUs and 70% faster on TPUs at the standard 512-token input length, while keeping 92% of BERT-Base’s accuracy on GLUE.</p><p>No attention heads, no learned pairwise weights, just deterministic global mixing: FNet mixes information across the sequence deterministically using the 2D Discrete Fourier Transform (DFT). They hypothesized that simpler token‐mixing mechanisms (i.e., linear transformations) might suffice, at least for encoder tasks like classification/fine‐tuning, and that attention may not always be the irreplaceable “secret sauce”.</p><p>A standard Transformer block consists of:</p><ol><li>Multi-Head Self-Attention</li><li>Feedforward Network (FFN)</li><li>Residual + LayerNorm</li></ol><p>FNet modifies this stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*qiPiQgsFYcGXJeuEGkEdyw.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*PyMgtLfxO9VEvuFwZelP3A.png" /></figure><p>is the token representation matrix. That is the only architectural change, and it works far better than you might expect.</p><h3>But first, what are Fourier Transforms?</h3><p>When you hear a guitar chord, it sounds like one smooth sound. But if you stop and really think, you will realise that one chord is actually made of many notes (frequencies), say, C, E, and G, all being played together. Your ears naturally separate those frequencies. But if you look at the waveform (the squiggly line you would see on an audio editor), it just looks like one messy curve.</p><p>You could describe a signal in two equivalent ways:</p><ol><li>Time domain — how the signal changes over time.</li><li>Frequency domain — what frequencies make up that signal (what you “hear”).</li></ol><p>These are two different but <em>mathematically equivalent</em> views of the same reality. The <a href="https://blog.endaq.com/fourier-transform-basics"><strong>Fourier Transform</strong></a> is a mathematical tool that enables you to transition between these two worlds.</p><p>So the Fourier Transform is like a superpower that lets us take that messy wave and figure out which individual notes are hiding inside it. Those notes correspond to frequencies which are pure sine and cosine waves. The Fourier<strong> </strong>Transform is the mathematical process that decomposes any signal into its constituent waves.</p><p>Formally:</p><blockquote>The Fourier Transform converts a function from the time (or spatial) domain into the frequency domain.</blockquote><p>Instead of describing what happens when, it describes which frequencies are present and how strong they are.</p><h4>Continuous Fourier Transform</h4><p>If you have a continuous function <em>f(t)</em>, the Fourier Transform <em>F(ω)</em> is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*CYQ5GhqUQUtk0N2fqEaGNg.png" /></figure><p>Here:</p><ul><li><em>ω</em> is the angular frequency (how fast a sine wave oscillates).</li><li><em>e^−iωt = cos(ωt)−i sin(ωt)</em> is Euler’s formula, representing a sinusoid.</li></ul><p>So <em>F(ω)</em> tells you:</p><ul><li>How much of the frequency <em>ω</em> is present in <em>f(t)</em>?</li><li>The amplitude (magnitude) and phase (timing offset) of that frequency component.</li></ul><p>The inverse transform reconstructs the original signal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*s1qL5KJWloUObx9Wet33bg.png" /></figure><p>Thus, <em>f(t) </em>can be written as a continuous sum of sine and cosine waves.</p><p>It says:</p><ul><li>The signal <em>f(t)</em> can be reconstructed by summing all possible sinusoids weighted by <em>F(ω)</em>.</li><li>Each <em>F(ω)</em> tells you “how much” of frequency <em>ω</em> is present in <em>f(t)</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*80ooxv4eLIwwqeiJ.png" /></figure><h4><strong>Discrete Fourier Transform (DFT)</strong></h4><p>In the real world, though, we work with discrete data like sampled audio, pixel grids, etc. DFT is the discrete analogue of the continuous transform.</p><p>For a finite sequence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*LYkyTKzAjZR4tFNLJYZ_rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*ro1-jH6sMn6Kss6M65iMPw.png" /></figure><p>This equation means:</p><ul><li>For each possible frequency <em>k</em>, multiply your signal by a complex sinusoid of frequency k/n.</li><li>Sum over all time steps <em>j, </em>and you will get the projection (dot product) onto that frequency.</li></ul><p>The inverse transform reconstructs the signal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*eJYKixuQt47OBAHWybuBAA.png" /></figure><p>The pair (<em>xⱼ</em>, <em>x̂ₖ</em>) are two equivalent representations of the same data:</p><ul><li><em>xⱼ</em> is the signal in the position space.</li><li><em>x̂ₖ is </em>the signal in frequency space.</li></ul><p>We can express this as a matrix multiplication:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*RWxzimWxnnT2FTGdFs8dkg.png" /></figure><p>where <em>Fₙ​</em>​ is the Fourier matrix, with elements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*zF9pXnaHMFRndlI9JGomMA.png" /></figure><p>Up to a scale factor, <em>Fₙ</em> is unitary: its inverse is Fₙ⁻¹ = (1/n) Fₙᴴ, where Fₙᴴ is the conjugate transpose, so (1/√n) Fₙ is exactly unitary. In other words, the DFT rotates the signal into frequency space (plus a uniform stretch), and no information is lost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*72e3TppAA8811knsFn0diQ.png" /></figure><h4>How does this all translate to NLP?</h4><p>Having explained this, how does it ultimately replace self-attention in transformers?</p><h4><strong>1. Frequency encodes structure!</strong></h4><ul><li>Smooth, slowly changing signals result in mostly low frequencies</li><li>Rough, rapidly changing signals result in more high frequencies.</li></ul><p>The combination of frequencies defines the overall shape of the signal!</p><p>In language, each token embedding <em>xⱼ</em> can be viewed as a sample in a temporal sequence. DFT decomposes this sequence into a combination of semantic frequency modes:</p><ul><li><em>k=0</em>: the average of all the tokens, a summary of the whole sequence (think of it as the overall topic)</li><li>small <em>k</em>: sentence-level rhythm and phrasing</li><li>large <em>k</em>: abrupt contextual or lexical changes</li></ul><p>Each embedding encodes meaning at a position, and the way those embeddings change from token to token defines the semantic<em> </em>rhythm of the text.</p><p><strong>Low frequencies</strong> indicate that changes occur slowly across tokens (smooth sentences, consistent topic). Low-frequency harmonics capture broad, slow-changing dependencies:</p><ol><li>Topic consistency (“climate” → “warming” → “planet”)</li><li>Long-range grammatical scaffolding (subject → verb → object)</li><li>Smooth transitions between phrases</li></ol><p>These correspond to the global linguistic structure, which is the backbone of meaning. Because of this, FNet can capture sentence-level coherence even without explicit attention, as the low frequency components already represent smooth, global relationships across tokens.</p><p><strong>Low frequency structure</strong></p><blockquote><em>“The </em>climate<em> is </em>warming<em> steadily across the </em>planet<em>.”</em></blockquote><p>The embeddings for ‘climate<em>’</em>, ‘warming<em>’</em>, and ‘planet<em>’</em> are semantically related and evolve gradually. If you took their sequence and projected it into frequency space, most energy would lie in low frequency components representing a smooth, coherent progression of meaning.</p><p><strong>High frequencies</strong> indicate that changes happen quickly (abrupt shifts, strong modifiers, punctuation, negations). High-frequency harmonics encode rapid local variations:</p><ol><li>Strong adjectives or adverbs modifying nouns (“utterly beautiful”, “terribly sad”)</li><li>Function-word shifts (“not”, “but”, “although”)</li><li>Punctuation and stylistic rhythm</li><li>Word boundaries in morphologically rich languages</li></ol><p>These components carry local grammatical contrast and fine semantic nuance.</p><p>Attention heads often learn similar distinctions; for example, heads that focus on adjacent words tend to capture these high-frequency relations.</p><p><strong>High frequency structure</strong></p><blockquote><em>“Hot! Cold! Rain! Drought!”</em></blockquote><p>Here, every token is semantically disjoint because of a rapid alternation of meanings. That sequence would have strong high frequency energy and sharp oscillations in semantic space.</p><p>This maps neatly onto the Fourier idea that the “semantic waveform” of a sentence has a spectrum of frequencies corresponding to how fast or slow meaning evolves. FNet employs this very principle, transforming token embeddings into frequency space, which allows the model to “see” the global structure of meaning across the entire sequence without explicit attention weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*m8VuCL2BneF2-EjBeKMHIA.png" /></figure><h4>2. The DFT lets every token talk to every other token</h4><p>Look at the DFT formula again. Every output x̂ₖ is a weighted sum over all n inputs, so after one transform each position holds a little bit of every token in the sequence. That is exactly the job attention does: global token mixing. The difference is where the weights come from. Attention computes its n×n weights from the tokens themselves, fresh for every input. The DFT uses the fixed weights e^(−2πijk/n), which are the same for every sentence ever written.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-mlroyduaSu1lnQwTalxw.png" /><figcaption><em>Two sentences give two different attention matrices (left and middle). The DFT matrix (right, real part) never changes</em></figcaption></figure><p>So attention is a learned, input-dependent mixing matrix, and the DFT is a frozen one. FNet bets that a frozen but thorough mix is good enough, as long as the layers after it are free to learn what to do with the mixed signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*I6f-G5HF2aUvhedqe2Eg6w.gif" /><figcaption><em>Switch on a single token and run the sequence-direction DFT: every output position responds, each with its own cosine weight</em></figcaption></figure><h4>3. Nothing is lost, so the feed-forward layer can untangle it</h4><p>Because the DFT is invertible, the mix does not throw information away. A token’s identity is still in there, smeared across all frequencies instead of sitting in one slot. The feed-forward network, which looks at one position at a time, then learns which combinations of these mixed signals are useful. Stack the pattern N times (mix, feed-forward, mix, feed-forward) and tokens get many chances to interact, just as they do across the layers of BERT. (Strictly speaking, FNet keeps only the real part of the result, which breaks exact invertibility. More on that below.)</p><h3>The FNet Layer, Precisely</h3><p>Let X be the n×d matrix of token representations: n tokens, each a d-dimensional vector. The FNet mixing sublayer is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*uAuD3apCLZwMcsKxrBBEoQ.png" /></figure><p>Two 1D transforms are applied: one along the hidden dimension (inside each token’s vector) and one along the sequence dimension (across tokens). Together they form a 2D DFT of the input matrix, and the order does not matter because the two transforms commute. Then only the real part is kept. Everything else is a normal Transformer encoder: residual connection and LayerNorm, a feed-forward network, another residual connection and LayerNorm, exactly as in the diagram above.</p><ul><li><strong>No parameters.</strong> The mixing sublayer has nothing to learn. FNet-Base has 83M parameters against BERT-Base’s 112M, and almost all of that gap is the attention projections it no longer needs.</li><li><strong>Why only the real part?</strong> Complex numbers would force every later layer to handle them. Taking the real part once, at the very end of the sublayer, lets the feed-forward layers stay completely ordinary. It is also what worked best in the authors’ experiments; throwing away the imaginary part earlier made the model less accurate and less stable.</li><li><strong>Why transform the hidden dimension too?</strong> The sequence transform is the part that replaces attention. The hidden transform also mixes features inside each token, and because the real part is taken only at the end, the two transforms interact: you cannot get the same output by running them separately and adding the results.</li></ul><p>Expand the complex exponentials into cosines and sines and the “Fourier” mystique evaporates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYMe1ubfFI3JpGss3Eqopg.png" /></figure><p>FNet’s token mixing is just X squeezed between fixed cosine and sine matrices, twice, with one result subtracted from the other. Nothing exotic, nothing learned.</p><h3>What It Costs</h3><p>Self-attention builds an n×n score matrix for every head, which costs O(n²d). The Fast Fourier Transform computes a length-n DFT in O(n log n), so the whole mixing sublayer costs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*teVtQs9Nu1fIOrcenbQc5w.png" /></figure><p>At 512 tokens, n² is about 57 times larger than n log₂ n. At 4,096 tokens it is about 341 times larger.</p><p>The hardware story has a twist. On GPUs, the FFT beat a plain matrix multiplication at every length the authors tried, from 512 to 8,192 tokens. On TPUs, which are built for matrix multiplication, it was faster to multiply by a cached n×n DFT matrix (the same O(n²) order as attention) for anything shorter than 4,096 tokens, and the authors switch to the FFT only above that. FNet still wins there: a fixed matrix product skips the query, key and value projections, skips the softmax, and has no mixing weights to update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30fQuZ0IiGWRpxE9OusQkw.png" /><figcaption><em>Left: time per pre-training step at 512 tokens. Right: peak GPU memory on the Long Range Arena. The Transformer runs out of memory at 4,096 tokens; FNet is still going at 8,192</em></figcaption></figure><h3>How Well Does It Work?</h3><p>Speed is worthless if the model forgets how to read, so here is the scorecard on GLUE, averaged over the validation sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*af057oGpAj9Ti4dkU-8sKA.png" /></figure><p>Three things jump out.</p><ol><li><strong>No attention, most of the accuracy.</strong> FNet-Base keeps 92% of BERT-Base’s score (76.7 against 83.3) and trains 80% faster on GPUs and 70% faster on TPUs at 512 tokens. At Large size the gap narrows to 81.9 against 84.7, about 97%, which the authors think is likely because FNet-Large trained more stably than BERT-Large.</li><li><strong>You need mixing, but not clever mixing.</strong> With no token mixing at all (FF-only) the score drops to 49.3. A random fixed matrix gets 56.6. A learned dense mixing matrix (Linear) gets 77.0, roughly the same as FNet. But Linear-Large collapsed to 59.8 because its training was unstable, while FNet, with no mixing weights at all, scaled without trouble.</li><li><strong>A little attention goes a long way.</strong> FNet-Hybrid replaces only the last two Fourier sublayers with attention and climbs to 80.6 at Base size and 83.6 at Large size, within about one point of BERT-Large.</li></ol><p>On the Long Range Arena, a benchmark built to stress long inputs, FNet averaged 55.3% accuracy against 55.8% for a Transformer trained the same way. It trained 2 to 3.2 times faster on GPUs at 512 to 2,048 tokens and needed a fraction of the memory.</p><h3>Where the Free Lunch Ends</h3><ul><li><strong>Encoder only.</strong> A causal language model must let each token see only the past. Attention does that with a mask. The DFT mixes everything with everything by design, and the paper notes that a causal version would need a causally masked Vandermonde matrix or a lower-level FFT implementation. FNet is a BERT replacement, not a GPT replacement.</li><li><strong>The mixing is blind to content.</strong> Attention can decide that “it” in a sentence refers to “the trophy”. The DFT applies the same mix whether the sentence is about trophies or tax law, so the feed-forward layers must recover any content-based routing on their own. Much of the GLUE gap is probably the price of that.</li><li><strong>No obvious cross-attention.</strong> Encoder-decoder models use attention to let the decoder look things up in the encoder’s output. There is no natural Fourier version of that lookup, and the authors leave it as an open question.</li><li><strong>The sequence is treated as a loop.</strong> The DFT assumes its input repeats, so the last token is a neighbour of the first. Padding a sequence also changes its spectrum. The model learns to live with this, but it is a strange inductive bias for text.</li></ul><h3>The Whole Thing in NumPy</h3><p>The mixing step really is one line. The rest of this snippet checks the claims above.</p><pre>import numpy as np<br><br>def fnet_mixing(X):<br>    # X: (n, d) token representations<br>    return np.fft.fft2(X).real   # 2D DFT, keep the real part<br><br>def dft_matrix(m):<br>    j = np.arange(m)<br>    return np.exp(-2j * np.pi * np.outer(j, j) / m)<br><br>n, d = 8, 4<br>rng = np.random.default_rng(0)<br>X = rng.standard_normal((n, d))<br><br># The same mix, written as two fixed matrix products<br>Fn, Fd = dft_matrix(n), dft_matrix(d)<br>print(np.allclose(fnet_mixing(X), (Fn @ X @ Fd).real))   # True<br><br># Nudge one token: every output token moves<br>X2 = X.copy()<br>X2[3] += rng.standard_normal(d)<br>moved = ~np.isclose(fnet_mixing(X), fnet_mixing(X2)).all(axis=1)<br>print(moved.sum(), &quot;of&quot;, n, &quot;output tokens changed&quot;)     # 8 of 8</pre><p>Drop fnet_mixing into a standard encoder block in place of attention, keep the residual connections, LayerNorm and feed-forward network, and you have FNet.</p><h3>Where FNet Sits Today</h3><p>FNet did not replace BERT, but it changed what people believed attention was for. It showed that much of what an encoder needs is simply global mixing, and that the mixing does not have to be learned. Two lines of work carried the idea further.</p><ul><li>Global Filter Networks (Rao et al., 2021) used the same trick for images but learned a filter in the frequency domain instead of using the plain DFT.</li><li>Long-convolution models such as Hyena (Poli et al., 2023) use the FFT to apply very long learned convolutions in O(n log n) time, and they work for causal language modelling, the one thing FNet never cracked.</li></ul><h3>Wrapping Up</h3><p>Attention is a learned, input-dependent way to mix tokens. FNet swaps it for a fixed one, the 2D Fourier transform, and keeps 92% of BERT-Base’s GLUE score while training 80% faster on GPUs at 512 tokens and using far less memory on long inputs. It cannot do causal decoding and it cannot route information by content, yet two attention layers at the top close most of the remaining gap. The lesson that outlived the model is hiding in its title: a lot of what attention does is just mixing, and mixing can be cheap.</p><h3>References</h3><ol><li>J. Lee-Thorp, J. Ainslie, I. Eckstein and S. Ontañón, <em>FNet: Mixing Tokens with Fourier Transforms</em>, NAACL 2022. arXiv:2105.03824</li><li>J. Devlin, M.-W. Chang, K. Lee and K. Toutanova, <em>BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</em>, NAACL 2019. arXiv:1810.04805</li><li>A. Vaswani et al., <em>Attention Is All You Need</em>, NeurIPS 2017. arXiv:1706.03762</li><li>Y. Tay et al., <em>Long Range Arena: A Benchmark for Efficient Transformers</em>, ICLR 2021. arXiv:2011.04006</li><li>Y. Rao, W. Zhao, Z. Zhu, J. Lu and J. Zhou, <em>Global Filter Networks for Image Classification</em>, NeurIPS 2021. arXiv:2107.00645</li><li>M. Poli et al., <em>Hyena Hierarchy: Towards Larger Convolutional Language Models</em>, ICML 2023. arXiv:2302.10866</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98e8b868aa80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: Attention with Linear Biases (ALiBi) - A Deep, Intuitive, and Mathematical Explanation]]></title>
            <link>https://medium.com/@srivatsa.n63/part-3-attention-with-linear-biases-alibi-a-deep-intuitive-and-mathematical-explanation-e2ed8bdf4f79?source=rss-22246753979c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2ed8bdf4f79</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Srivatsa Narasimha]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 19:35:10 GMT</pubDate>
            <atom:updated>2026-10-27T15:56:30.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNFTVyN6fYFHI5Vc9kWpKg.png" /></figure><p>BLOOM, the 176-billion-parameter open multilingual model, has no positional embeddings at all. Neither does MPT-7B, whose StoryWriter version MosaicML fine-tuned on 65,000-token inputs and then used to generate stories as long as 84,000 tokens. Both use ALiBi, short for Attention with Linear Biases, which Ofir Press, Noah Smith and Mike Lewis introduced in 2021 under the title &quot;Train Short, Test Long&quot; (it appeared at ICLR 2022). And in August 2026 a new paper showed that ALiBi has a numerical blind spot that had been overlooked for five years. We will get to that.</p><blockquote><strong>Recap of Parts 1 and 2</strong></blockquote><p>In <a href="https://medium.com/@srivatsa.n63/part-1-positional-embeddings-in-transformers-a-deep-intuitive-and-mathematical-explanation-de5c74731862">Part 1</a>, the original Transformer added sinusoidal encodings to its inputs, which gave every position a unique fingerprint but fell apart on inputs longer than the training length. In <a href="https://medium.com/@srivatsa.n63/part-2-rotary-positional-embeddings-rope-a-deep-intuitive-and-mathematical-explanation-2c0184430625">Part 2</a>, RoPE moved the same clocks into the attention score by rotating queries and keys, which made position relative by construction. But the slow clocks still pointed in unfamiliar directions past the training length, and a whole toolbox of interpolation tricks grew up around that problem.</p><p>ALiBi takes a much blunter route. It deletes the positional embedding completely and tells attention one simple thing: the further away a token is, the less you should look at it.</p><h3>The Idea: Delete the Embeddings, Penalize Distance</h3><p>Here is the entire method. Compute the usual attention scores between the query at position i and every key up to and including it. Then, before the softmax, subtract a penalty proportional to how far back each key is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*esu5H7bx1ezM7iFFTT9hDQ.png" /></figure><p>The key at the same position gets no penalty, the one right before it loses m, the one before that loses 2m, and so on in a straight line. In the paper&#39;s words, &quot;we do not add position embeddings at any point in the network.&quot; The slope m is a fixed number, not a learned weight, and the bias is just added to the attention mask, so it costs essentially nothing at run time. The values are never touched.</p><p>Draw the bias as a matrix and you get a staircase that darkens with distance. Every head gets its own slope, so some staircases are steep and some are almost flat:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNDmRsEfbaXyclF-VySR4Q.png" /><figcaption><em>The bias for 12 positions in four of the eight heads. Darker means a bigger penalty; the white triangle is the causal mask that hides future tokens</em></figcaption></figure><p>Notice what is missing. There is no vector that says &quot;I am token 37&quot;, no rotation, no lookup table. The only thing attention knows about position is how far apart two tokens are, and that it should prefer the closer one.</p><h3>Why Eight Different Slopes?</h3><p>If every head used the same slope, the whole model would have one fixed attention span. ALiBi instead gives the heads a geometric ladder of slopes. With n heads, the slopes start at 2^(−8/n) and keep multiplying by that same number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*BNa_4y49xTn6novfRd9neQ.png" /></figure><p>A handy way to read a slope is as a half-life. Before content enters the picture, the softmax turns a penalty of m · d into a weight proportional to e^(−m·d), so the weight halves every ln 2 / m tokens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*Jmk-spQxpfOsBfD3BKXEmQ.png" /></figure><p>For the eight standard slopes that gives half-lives of 1.4, 2.8, 5.5, 11, 22, 44, 89 and 177 tokens. So the steepest head is basically a &quot;look at the last word or two&quot; head, while the gentlest one still spreads its attention over a few hundred tokens. If all keys had equal content scores, the slope-1/2 head would put essentially 100% of its attention on the last 16 tokens, while the slope-1/256 head would put only 6% there and 63% on the last 256 tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*0O9MIMBG35D5vDx3NGtDmA.png" /><figcaption><em>How far back each head looks when every key has the same content score. The curves are evenly spaced on a log scale, because each slope is half the previous one</em></figcaption></figure><p>The authors also tried letting the model learn its slopes. It &quot;did not yield strong extrapolation results&quot; and made training 3% slower, so the slopes stay fixed.</p><h3>Why It Reads Longer Inputs</h3><p>Remember the problem from Part 2: past the training length, RoPE&#39;s slow clocks point in directions the model has never seen. ALiBi has no clocks. The only thing that changes when the input gets longer is that a few more keys appear far in the past, with even bigger penalties. The pattern a query sees around itself is exactly the same at position 500 as at position 5,000. In the NumPy code at the end, the bias row for query 1,000 over the previous 100 tokens is identical to the row for query 3,000 over its previous 100 tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*he1JuGH7vMhNw9yJyc0alg.gif" /><figcaption><em>A query slides past the training length of 1,024 tokens (green into orange). The attention shape of every head just slides along with it: nothing about it is new</em></figcaption></figure><p>The paper backs this up with real models. A 1.3-billion-parameter model trained on 1,024-token inputs with ALiBi matched the perplexity of a sinusoidal model trained on 2,048 tokens, when both were tested on 2,048 tokens, and it trained 11% faster while using 11% less memory. In smaller-scale comparisons on WikiText-103, ALiBi also beat sinusoidal embeddings, RoPE and the T5 relative bias at extrapolation.</p><p>That result is why ALiBi showed up in real models. The BLOOM team wrote that it &quot;directly attenuates the attention scores based on how far away the keys and queries are&quot;, and that it &quot;led to smoother training and better downstream performance&quot; than learned or rotary embeddings, even at the original length. MosaicML credited ALiBi with letting MPT-7B-StoryWriter &quot;extrapolate even beyond 65k tokens&quot;.</p><h3>The Fine Print</h3><p>ALiBi&#39;s built-in preference for nearby tokens has three consequences worth knowing before you reach for it.</p><blockquote><strong>It Is a Soft Sliding Window</strong></blockquote><p>The penalty only grows. A key 2,000 tokens back starts its competition for attention 7.8 points behind in the gentlest head (2,000 / 256) and 1,000 points behind in the steepest one. Content scores can fight back, but only so far. So &quot;reads longer inputs&quot; mostly means &quot;does not break on longer inputs&quot;: the model keeps predicting well because it leans on the recent past, not because it suddenly uses everything in a 50,000-token document. The paper itself describes the method as an inductive bias toward recency.</p><blockquote><strong>The Penalty Can Underflow</strong></blockquote><p>This is the blind spot from the opening. In August 2026, Schröder, Gienapp, Schlatt, Potthast and Heyer showed that ALiBi&#39;s &quot;linear bias scaling underflows floating-point precision&quot;: in long contexts, a large fraction of attention weights become exactly zero, so some heads literally cannot see some tokens. They found it in pretrained ALiBi models, with a big effect on retrieval tasks such as finding a passkey and a minor one on standard benchmarks.</p><p>You can reproduce the core of it in a few lines. Take a 4,096-token context, give every key the same content score, and count how many keys get a weight of exactly zero. With a float32 softmax, the slope-1/2 head ignores 3,890 of the 4,096 keys and even the slope-1/32 head ignores 880. In float16, every head has blind spots, and the gentlest head still ignores 1,081 keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*Kzvy5AJW_8ZjpmXCYyEyWA.png" /><figcaption><em>Keys that receive an attention weight of exactly 0 in a 4,096-token context, assuming equal content scores. Real content scores shift these numbers, but the far end of a steep head stays out of reach</em></figcaption></figure><blockquote><strong>There Is No Absolute Position</strong></blockquote><p>ALiBi only ever tells attention about distance. A causal language model can still pick up some sense of absolute position from the mask itself (Haviv et al., 2022, showed that models with no positional encoding at all still learn some positional information), but nothing in ALiBi says &quot;this is token 37&quot; directly.</p><p>None of this makes ALiBi a bad idea. It is a very different trade-off from RoPE: ALiBi gets length robustness almost for free by deciding in advance that far-away tokens matter less, while RoPE keeps every distance in play and pays for longer contexts with interpolation tricks. Most open-weight models released recently went the RoPE route.</p><h3>The Whole Thing in NumPy</h3><p>Here are the slopes, the bias, the shift check and the underflow count from above:</p><pre>import numpy as np<br><br>def alibi_slopes(n_heads):<br>    start = 2.0 ** (-8.0 / n_heads)            # 1/2 when there are 8 heads<br>    return start ** np.arange(1, n_heads + 1)  # 1/2, 1/4, ..., 1/256<br><br>def alibi_bias(n, slopes):<br>    dist = np.arange(n)[None, :] - np.arange(n)[:, None]   # key minus query<br>    bias = slopes[:, None, None] * dist                    # (heads, n, n)<br>    bias[:, dist &gt; 0] = -np.inf                            # causal mask<br>    return bias<br><br>def softmax(x):<br>    e = np.exp(x - x.max(axis=-1, keepdims=True))<br>    return e / e.sum(axis=-1, keepdims=True, dtype=x.dtype)<br><br>slopes = alibi_slopes(8)<br>print(slopes)                                   # 0.5 ... 0.0039<br><br>B = alibi_bias(4096, slopes[-1:])               # gentlest head only<br>print(np.allclose(B[0, 1000, 900:1001], B[0, 3000, 2900:3001]))  # True<br><br># equal content scores: where does each head look?<br>dist = np.arange(4096)[::-1]                    # 4095 ... 0<br>for m in slopes:<br>    w32 = softmax((-m * dist).astype(np.float32))<br>    w16 = softmax((-m * dist).astype(np.float16))<br>    print(f&quot;1/{1/m:.0f}: last 16 tokens {w32[-16:].sum():.3f}, &quot;<br>          f&quot;zero weights fp32 {(w32 == 0).sum()}, fp16 {(w16 == 0).sum()}&quot;)</pre><p>The last loop prints the numbers behind the chart: from &quot;1/2: last 16 tokens 1.000, zero weights fp32 3890, fp16 4063&quot; down to &quot;1/256: last 16 tokens 0.061, zero weights fp32 0, fp16 1081&quot;.</p><h3>So, How Do All Three Score?</h3><p>To close the series, here are the four criteria from Part 1 one last time, with every method side by side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBpwZN2bgVozeyEepIB-pw.png" /></figure><h3>Wrapping Up the Series</h3><p>We started with a bag of words that could not tell &quot;dog bites man&quot; from &quot;man bites dog&quot;. Sinusoidal encodings fixed that by stamping every position with a set of clocks. RoPE took those clocks and turned them into rotations of the queries and keys, so the attention score depends only on relative distance. ALiBi threw the clocks away and replaced them with one rule: closer tokens matter more.</p><p>Each step moved position information closer to the attention score and made it simpler. ALiBi is the simplest of all, a single straight line per head, and that simplicity is exactly why it handles longer inputs gracefully and also why it can go blind to tokens far away. If you are choosing today, RoPE with a scaling method is the common default for long-context models, and ALiBi remains a strong, nearly free option when robustness to longer inputs matters more than reaching every distant token.</p><h3>References</h3><ol><li>O. Press, N. A. Smith and M. Lewis, <em>Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation</em>, ICLR 2022. arXiv:2108.12409</li><li>BigScience Workshop, <em>BLOOM: A 176B-Parameter Open-Access Multilingual Language Model</em>, 2022. arXiv:2211.05100</li><li>MosaicML, <em>Introducing MPT-7B: A New Standard for Open-Source, Commercially Usable LLMs</em>, May 2023. <a href="https://www.databricks.com/blog/mpt-7b">https://www.databricks.com/blog/mpt-7b</a></li><li>C. Schröder, L. Gienapp, F. Schlatt, M. Potthast and G. Heyer, <em>When Attention Goes Blind: Numerical Failure in ALiBi Positional Encodings</em>, August 2026. arXiv:2608.03994</li><li>A. Haviv, O. Ram, O. Press, P. Izsak and O. Levy, <em>Transformer Language Models without Positional Encodings Still Learn Positional Information</em>, Findings of EMNLP 2022. arXiv:2203.16634</li><li>J. Su et al., <em>RoFormer: Enhanced Transformer with Rotary Position Embedding</em>, 2021. arXiv:2104.09864</li><li>A. Vaswani et al., <em>Attention Is All You Need</em>, NeurIPS 2017. arXiv:1706.03762</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2ed8bdf4f79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: Rotary Positional Embeddings (RoPE) - A Deep, Intuitive, and Mathematical Explanation]]></title>
            <link>https://medium.com/@srivatsa.n63/part-2-rotary-positional-embeddings-rope-a-deep-intuitive-and-mathematical-explanation-2c0184430625?source=rss-22246753979c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c0184430625</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Srivatsa Narasimha]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 18:29:29 GMT</pubDate>
            <atom:updated>2026-10-27T15:56:01.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9SXHeMngq007Z-cJKBdOA.png" /></figure><p>If you have used LLaMA, Qwen, Mistral or almost any open-weight language model released recently, every attention layer you ran was rotating its queries and keys before comparing them. That rotation is called RoPE, Rotary Position Embedding, and it was introduced by Jianlin Su and colleagues in 2021 in the <a href="https://arxiv.org/abs/2104.09864">RoFormer</a> paper. It has become the default way large language models know where each token is.</p><blockquote><strong>Recap of Part 1</strong></blockquote><p>In <a href="https://medium.com/p/de5c74731862">Part 1</a> we saw that self-attention, on its own, cannot tell &quot;dog bites man&quot; from &quot;man bites dog&quot;, and that the original Transformer fixed this by adding sinusoidal positional encodings to the token embeddings. We also found a hidden gem in that design: moving k tokens forward rotates every (sin, cos) pair by a fixed angle. And we ended with three weak spots. Relative distance only reaches the attention score tangled up with content, the raw similarity cannot tell &quot;before&quot; from &quot;after&quot;, and models trained on short inputs fall apart on long ones.</p><p>RoPE keeps the gem and throws away the rest. Instead of adding a rotation-friendly vector to the input once, it applies the rotation directly to the queries and keys inside every attention layer. That one change fixes the first two weak spots by construction and makes the third one much easier to manage.</p><h3>The Idea: Rotate, Do Not Add</h3><p>Start with the smallest possible case: queries and keys with just two dimensions, so each one is an arrow on a plane. RoPE takes the query of the token at position m and rotates it by an angle mθ. It takes the key of the token at position n and rotates it by nθ. Nothing is added to anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtPAAM9JoLJmfU3KcxgAdA.png" /></figure><p>Now look at what attention computes, the dot product of the rotated query and the rotated key. Rotations have two friendly properties: the transpose of a rotation is the rotation backwards, and two rotations combine by adding their angles. So:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q__h7ENTrPqQysybSMZBTA.png" /></figure><p>The absolute positions m and n have disappeared. Only their difference n − m is left. Each token is rotated by its own absolute position, but the attention score can only ever see the relative distance between the two tokens.</p><p>The picture makes this obvious. A dot product depends only on the lengths of the two arrows and the angle between them. If you shift both tokens by the same amount, both arrows turn by the same extra angle, so the angle between them does not change, and neither does the score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*dmuZuyznaoltkI69SJb6bg.gif" /><figcaption><em>The query at position m and the key at position n both turn as the pair slides along the sequence. The angle between them stays fixed, so the score stays at 0.7803 for every shift</em></figcaption></figure><h3>From 2 Dimensions to n Dimensions</h3><p>Real attention heads have 64 or 128 dimensions, not 2. RoPE handles that the same way the sinusoidal encoding did: it splits the vector into d/2 pairs and gives each pair its own clock speed. The full rotation is block-diagonal, one small 2 x 2 rotation per pair:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36r7ZapfyU5cPiRHr6aaPg.png" /></figure><p>Those are exactly the frequencies from Part 1. The fast pairs separate neighbouring tokens and the slow pairs track where you are in a long document. Because every block is its own rotation, the relative-position argument from the 2D case holds for each pair separately, and therefore for the whole vector.</p><p>Nobody builds that big sparse matrix in practice. Each pair only needs a cosine and a sine, so the rotation can be written as two element-wise products:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*CKeP-Uys8kzQ9pEDa3amkw.png" /></figure><blockquote><strong>A small trap when porting weights</strong></blockquote><p>The RoFormer paper pairs neighbouring dimensions (0 with 1, 2 with 3, and so on). The rotate_half form pairs dimension i with dimension i + d/2. Both are valid RoPE, but they are not interchangeable: if you load weights trained with one convention into code that uses the other, every pair is rotated wrongly, and the model quietly produces garbage.</p><h3>What RoPE Fixes</h3><p>Let us go back to the weak spots from Part 1 and see what the rotation does to each of them. I checked every claim below with the NumPy code in the next section, using a 64-dimensional head and random queries and keys.</p><blockquote><strong>Relative Position by Construction</strong></blockquote><p>With sinusoidal encodings, relative distance was something the model could learn to extract. With RoPE it is simply how the score is computed. For one random query and key, the score at positions (10, 3) is −5.8069. Shift both tokens by 1,000 or by 4,000 and the score is still −5.8069, with differences around 10⁻¹³, which is rounding error.</p><blockquote><strong>Direction Is Back</strong></blockquote><p>In Part 1, a token 10 positions before you and a token 10 positions after you got exactly the same similarity, because cosine is symmetric. A rotation by +Δ is not the same as a rotation by −Δ, so RoPE does not have that problem. For the same query and key, a key 7 positions before the query scores −5.81, and a key 7 positions after it scores −7.93. The model can tell &quot;before&quot; from &quot;after&quot; directly from the score.</p><blockquote><strong>Position Multiplies Instead of Adding</strong></blockquote><p>In Part 1, adding position to the input split the attention score into four terms, two of which mixed &quot;what this word is&quot; with &quot;where that word is&quot;. RoPE never adds anything, so there are no cross terms. The score is one term: the content of the query and the content of the key, compared through a rotation that depends only on their distance.</p><blockquote><strong>Lengths Are Untouched</strong></blockquote><p>A rotation never changes the length of a vector. Rotating a query to position 1,234 changes its length by exactly 0 in my test. RoPE moves information around inside each pair, but it never makes a token louder or quieter.</p><blockquote><strong>Far-Away Tokens Fade</strong></blockquote><p>The RoFormer paper shows that RoPE has a built-in long-term decay: as the distance grows, the attention between two tokens tends to shrink. You can see it by asking a token to attend to a copy of itself placed further and further away. Averaged over 200 random 64-dimensional queries, the score keeps 97% of its value at distance 1, 66% at distance 10, 49% at distance 50 and 20% at distance 500. The decay is not perfectly smooth (distance 100 scores a little higher than distance 50), but the trend is clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oRZjsRdc1j_GyOEpcp6Qg.png" /><figcaption><em>Left: the same content, placed further away, gets a smaller score on average. Right: for one random query and key, a negative and a positive distance of the same size give different scores</em></figcaption></figure><blockquote><strong>It Lives Inside Every Layer</strong></blockquote><p>Sinusoidal encodings are added once, at the input, and then have to survive dozens of layers. RoPE is applied to the queries and keys of every attention layer, every time, so position information is fresh wherever attention is computed. The values are never rotated, so what a token passes along is pure content.</p><h3>The Whole Thing in NumPy</h3><p>Here is RoPE in the rotate_half form, with the three checks from above:</p><pre>import numpy as np<br><br>def rope_angles(n_pos, d, base=10000.0):<br>    theta = base ** (-np.arange(0, d, 2) / d)          # same frequencies as Part 1<br>    return np.arange(n_pos)[:, None] * theta[None, :]  # (n_pos, d/2)<br><br>def rotate_half(x):<br>    x1, x2 = x[: len(x) // 2], x[len(x) // 2 :]<br>    return np.concatenate([-x2, x1])<br><br>def apply_rope(x, angles):<br>    cos = np.cos(np.concatenate([angles, angles]))<br>    sin = np.sin(np.concatenate([angles, angles]))<br>    return x * cos + rotate_half(x) * sin<br><br>rng = np.random.default_rng(0)<br>d = 64<br>ang = rope_angles(4096, d)<br>q, k = rng.standard_normal(d), rng.standard_normal(d)<br>score = lambda m, n: apply_rope(q, ang[m]) @ apply_rope(k, ang[n])<br><br>print(score(10, 3), score(1010, 1003), score(4010, 4003))   # identical<br>print(np.linalg.norm(apply_rope(q, ang[1234])) - np.linalg.norm(q))  # ~0<br>print(score(100, 93), score(100, 107))                      # different</pre><p>The first line prints −5.8069 three times, the second prints 0.0, and the third prints −5.8069 and −7.9305.</p><h3>Where RoPE Struggles: Longer Contexts</h3><p>RoPE is not a free pass to infinite context. Press, Smith and Lewis tested it in their ALiBi paper: a rotary model trained on 512-token inputs kept improving for up to about 200 extra tokens at test time, much better than the roughly 20 tokens a sinusoidal model managed, but still far from &quot;train short, test long&quot;. In their words, &quot;Though the rotary position method improves over the sinusoidal one, it still does not achieve satisfying results.&quot;</p><p>The clocks explain why. During training on 4,096 tokens, a fast pair spins around its circle hundreds of times and sees every possible angle. A slow pair moves only a little. With d = 128 and base 10,000, 46 of the 64 pairs complete at least one full turn during training, and the other 18 never do. When the model reads token 12,000, those 18 slow hands point in directions the model has never seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*iT86_P-5S6VanvOnC8Zq_g.gif" /><figcaption><em>Green marks the angles each pair reached during training on 4,096 tokens. Fast pairs have seen the whole circle. The slow pair (right) leaves the green slice after token 4,096 and turns orange: those angles are new to the model</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0eG2pPetvf6USx8zIRGEg.png" /><figcaption><em>For every frequency pair, the largest angle seen in training (blue) and the angle needed at 16,384 tokens (orange). The 18 pairs on the right, below the 2π line, never completed a turn in training</em></figcaption></figure><p>That diagnosis led to a family of fixes that most long-context models now use. The simplest one rescales the position before rotating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*880S728UZomOPb73XXwXSQ.png" /></figure><ul><li><strong>Position Interpolation.</strong> Chen et al. (2023) squeezed the positions instead of extending them: to reach a longer target length, multiply every position by L_train / L_target, so every angle stays inside the trained range. They extended LLaMA models (7B to 65B parameters) to context windows of up to 32,768 tokens with fine-tuning &quot;within 1000 steps&quot;. The cost is resolution: neighbouring tokens now sit closer together on the fast clocks.</li><li><strong>NTK-aware scaling and YaRN.</strong> The open-source community noticed that the fast pairs do not need squeezing at all, only the slow ones do. Increasing the base of the frequencies slows down the low-frequency clocks while leaving the fast ones nearly alone (this &quot;NTK-aware&quot; trick is described in the YaRN paper). YaRN (Peng et al., 2023) refines this per frequency band and reports needing 10x fewer tokens and 2.5x fewer training steps than earlier methods.</li><li><strong>A bigger base from the start.</strong> Llama 3 raised the RoPE base frequency to 500,000, which the authors say &quot;enables us to better support longer contexts&quot;. Slower clocks mean fewer pairs hit unseen angles at a given length.</li></ul><p>This is still an active area. Qwen3.6 27B, for example, is listed with a native 262,144-token context that can be stretched to roughly a million tokens with YaRN.</p><h3>So, How Does RoPE Score?</h3><p>Here are the four criteria from Part 1 again, with sinusoidal encodings next to RoPE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCJjgBdocmRGcTDNF0D8cQ.png" /></figure><h3>Wrapping Up</h3><p>RoPE takes the one beautiful property of sinusoidal encodings, that a shift in position is a rotation, and moves it to where it is used: the comparison between a query and a key. The result is an attention score that depends on content and relative distance and nothing else, knows which direction the other token is in, and tends to fade with distance. It costs no parameters, which is a big part of why most open-weight LLMs use it today.</p><p>Its weak spot is the slow clocks. Past the training length they point in directions the model has never seen, and a whole toolbox of interpolation tricks exists to keep them in familiar territory. In <a href="https://medium.com/p/e2ed8bdf4f79">Part 3</a> we will look at <strong>ALiBi</strong>, which takes a completely different route: no positional embeddings at all, just a penalty on the attention score that grows with distance. That simple idea is what let Press et al. train on short inputs and test on long ones.</p><h3>References</h3><ol><li>J. Su, Y. Lu, S. Pan, A. Murtadha, B. Wen and Y. Liu, <a href="https://arxiv.org/abs/2104.09864"><em>RoFormer: Enhanced Transformer with Rotary Position Embedding</em></a>, 2021. arXiv:2104.09864</li><li>A. Vaswani et al., <a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need</em></a>, NeurIPS 2017. arXiv:1706.03762</li><li>H. Touvron et al., <em>LLaMA: </em><a href="https://arxiv.org/abs/2302.13971"><em>Open and Efficient Foundation Language Models</em></a>, 2023. arXiv:2302.13971</li><li>O. Press, N. A. Smith and M. Lewis, <a href="https://arxiv.org/abs/2108.12409"><em>Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation</em></a>, ICLR 2022. arXiv:2108.12409</li><li>S. Chen, S. Wong, L. Chen and Y. Tian, <a href="https://arxiv.org/abs/2306.15595"><em>Extending Context Window of Large Language Models via Positional Interpolation</em></a>, 2023. arXiv:2306.15595</li><li>B. Peng, J. Quesnelle, H. Fan and E. Shippole, <a href="https://arxiv.org/abs/2309.00071"><em>YaRN: Efficient Context Window Extension of Large Language Models</em></a>, 2023. arXiv:2309.00071</li><li>Llama Team, AI @ Meta, <a href="https://arxiv.org/abs/2407.21783"><em>The Llama 3 Herd of Models</em></a>, 2024. arXiv:2407.21783</li><li><em>Qwen 3.6 27B: architecture overview</em>, Morph. <a href="https://www.morphllm.com/qwen-3-6">https://www.morphllm.com/qwen-3-6</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c0184430625" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Positional Embeddings in Transformers - A Deep, Intuitive, and Mathematical Explanation]]></title>
            <link>https://medium.com/@srivatsa.n63/part-1-positional-embeddings-in-transformers-a-deep-intuitive-and-mathematical-explanation-de5c74731862?source=rss-22246753979c------2</link>
            <guid isPermaLink="false">https://medium.com/p/de5c74731862</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Srivatsa Narasimha]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 09:26:49 GMT</pubDate>
            <atom:updated>2026-10-29T08:31:00.347Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*koUQAPuLsfCEN8beKXenig.png" /></figure><p>Transformers power almost every modern NLP model, yet one of their most critical components is often glossed over, positional embeddings!</p><p>Self-attention does not know sequence order because it only computes similarity between token embeddings. It works by comparing embeddings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*KxMYaBLhxKd4aIiOCo22dg.png" /></figure><ul><li><em>Q</em>, <em>K</em>, and <em>V </em>are functions of token embeddings only</li><li>There is no term involving a token index or position. There is no term like “<em>token i comes before token j</em>” or “<em>token i is 2 positions away from token j</em>”</li></ul><p>Imagine you take a sentence and remove all notions of time and sequence. You do not read it left to right. You do not know which word came first. You see all words at once. Place the words into a bowl, shuffle them and pick them one at a time, they can come out in any order:</p><pre>{ dog, bites, man }<br>{ man, dog, bites }<br>{ bites, man, dog }</pre><p>Now ask these questions:</p><ul><li>Which word came first?</li><li>Who is performing the action?</li><li>Who is receiving the action?</li></ul><p>From the bowl, there is no way to know if the dog is biting the man or if the man is biting the dog (very unlikely though)!</p><p>The set of embeddings is unchanged. And attention is permutation -invariant.</p><blockquote>Reordering tokens does not change the computation</blockquote><p>This is exactly how vanilla self-attention sees the input before positional embeddings are added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Wo9ubqUM28-jDMGl_HHyoA.gif" /><figcaption><em>Shuffle “dog bites man” and, without positional information, the attention output for “dog” does not change at all (orange). Add sinusoidal encodings and it does (blue)</em></figcaption></figure><h3><strong>Why so?</strong></h3><p>Transformers were intentionally built to ignore sequence structure, so they can process all tokens in parallel and model long-range dependencies efficiently.</p><p>Before transformers, earlier sequential models like Recurrent models (RNNs, LSTMs, GRUs) encode sequence order directly into their architecture by processing tokens one after another, where each hidden state depends on the previous one (<em>h1 → h2 → h3 → … </em>). This sequential dependency makes it impossible to compute tokens in parallel, leading to slow training and poor GPU utilization, especially for long sequences. In practice, this becomes a major scalability bottleneck as sequence length grows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*ZFRc_tVtTiNz2DoLRPjB-g.gif" /><figcaption><em>An RNN has to walk through the sentence one hidden state at a time. Self-attention connects every pair of tokens in a single parallel step</em></figcaption></figure><p>Beyond speed, this design also hurts learning. To relate distant words, information must propagate through many intermediate steps, causing gradients to weaken and important context to be forgotten, even in LSTMs. Additionally, RNNs compress the entire past into a single hidden vector at each step, creating an information bottleneck that forces the model to discard details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*FTrEfdhywX2wC7l8eD90Cw.png" /><figcaption><em>How much the last hidden state of a random 64-unit tanh RNN depends on earlier ones (20 runs per setting). Thirty tokens back, the signal has shrunk by a factor of roughly 10 ⁴ to 10 ⁶</em></figcaption></figure><p>Attention-based models remove this bottleneck by allowing every token to directly interact with every other token, enabling parallelized, efficient modeling of long-range dependencies without sequential constraints.</p><p>Every token can:</p><ul><li>Attend to every other token</li><li>In a single step</li><li>In parallel</li></ul><p>This is only possible if the model is order-agnostic by default. Self-attention computes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*pNNVA7SOH6VpKRkQgZmwjg.png" /></figure><p>This operation compares all tokens at once, uses matrix multiplication and runs efficiently on GPUs. If attention depended on sequence order internally, you would reintroduce dependencies, lose parallelism and be back to RNN-like behavior.</p><p>So the order had to be removed from the core computation.</p><h3>This is a problem, though!</h3><p>Without order:</p><ul><li>Syntax collapses</li><li>Causality disappears</li><li>Subject–object relationships break</li></ul><blockquote>Self-attention alone sees both “Dog bites man” and “Man bites dog” as {bites, man, dog }</blockquote><p>Since the architecture treats all permutations equally, training provides no signal to distinguish one order from another. This is not a matter of insufficient data or weak optimization, the required information simply never enters the system. In other words, the model cannot learn order because order is not part of its input, making positional information a necessity rather than an optional enhancement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3meGf4G1kHrUv5vSUaPVXg.png" /><figcaption><em>Attention weights for both sentences, computed with the same weights and no positional encoding. Every number reappears, just in a different cell</em></figcaption></figure><h3>Enter Positional Embeddings!</h3><p>So here is the trick that transformers use to encode positions!</p><blockquote>Order is information, not structure.</blockquote><p>Instead of hard-coding sequence order into the computation graph (as RNNs do), they treat order as just another feature of the input, similar to gender, syntax, or segment identity. These properties are not enforced by the architecture itself, instead, they are encoded as vectors and combined with token embeddings. Once added, self-attention operates on these enriched representations without needing to know why a feature exists, rather only that it influences similarity and relevance. This keeps the core attention mechanism simple, symmetric, and fully parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fx9Ja7K78EpMqhaL0MjgMg.png" /><figcaption><em>Both sentences use the same three word embeddings. Adding a positional encoding row by row turns “dog” at position 0 and “dog” at position 2 into two different input vectors, so order reaches attention as data</em></figcaption></figure><p>This separation gives transformers enormous flexibility. Because order is represented as data rather than control flow, the same architecture can be reused across domains: text, images, audio, graphs, or multimodal inputs, each with different notions of “position.” It also allows new forms of structure to be introduced without changing the attention computation itself. In essence, transformers treat structure as something to be learned and adapted, not something rigidly imposed, which is a key reason they scale so well and generalize across tasks.</p><p>Transformers follow a separation of concerns principle. The architecture (self-attention) is responsible only for modeling relationships, basically deciding which tokens attend to which others and how strongly, purely based on content similarity. Embeddings carry contextual signals.</p><ul><li>Meaning</li><li>Position</li><li>Segment</li><li>Modality</li></ul><p>This design choice is a brilliant trade-off because it moves complexity from the architecture to the data representation. Ignoring sequence order in the core computation creates a small, clean problem, i.e., missing order information that is easy to fix by adding positional embeddings. In contrast, the problems occurring in RNNs(lack of parallelism, poor long-range dependency modeling, and information bottlenecks) are deeply architectural and extremely hard to fix. Transformers accept a fixable weakness in exchange for scalability, flexibility, and efficiency.</p><p>This is similar to what Convolutional Neural Networks do. CNNs deliberately ignore absolute position when applying filters. A convolutional filter slides across the image and applies the same weights everywhere, meaning the filter does not know whether it is looking at the top-left corner or the center of the image. This position-agnostic design allows CNNs to detect patterns like edges, corners, or textures regardless of where they appear. Hard-coding absolute pixel locations into the convolution itself would break this generalization and dramatically increase parameters.</p><p>Yet CNNs still understand spatial structure because position is injected indirectly, not baked into the core operation. Padding defines boundaries, strides control resolution, and sometimes explicit coordinate channels (e.g., CoordConv) are added to embeddings. In other words, convolution focuses on “what pattern is present,” while spatial layout is supplied as input context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5BtZ9PTu39MvrDMrbunLw.png" /><figcaption><em>One convolution filter, applied everywhere, responds equally strongly to the same corner wherever it appears. Position is not part of the filter</em></figcaption></figure><p>Make the core operation as simple, symmetric, and parallel as possible and then inject structure as data.</p><p>Transformers apply the same philosophy to sequences: self-attention focuses purely on relationships between tokens, while positional embeddings supply order information externally. By keeping the core operation simple and position-agnostic, both CNNs and transformers gain scalability, generalization and flexibility, while still learning structured representations through the data they are given.</p><p>This is why transformers generalize so well beyond NLP:</p><ul><li>Vision</li><li>Audio</li><li>Graphs</li><li>Multimodal models</li></ul><h3>What Makes a Good Positional Encoding?</h3><p>A good positional encoding should:</p><ol><li>Encode Absolute Position - the model knows where a token appears</li><li>Support Relative Reasoning - the model understands the distance between tokens</li><li>Generalize to Longer Sequences - the model handles sequences longer than seen during training</li><li>Be Cheap and Stable - no heavy parameters, no training instability</li></ol><h3>So, which kind of positional encoding meets the above criteria?</h3><p>There are multiple encodings which are optimal. In “<a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need</em></a><em>”</em> by Vaswani et al., sinusoidal positional embeddings were chosen for pragmatic, architectural, and mathematical reasons, not because they were theoretically perfect, but because they best aligned with the design goals at the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pp1C2O8PpE61Wgqz6D5KXA.png" /></figure><p>Sinusoidal positional embeddings solve the “<em>order</em>” problem in the simplest, most general, and mathematically useful way, without adding trainable parameters or breaking the transformer’s architecture.</p><blockquote><strong>They Encode Position Continuously, Not as IDs</strong></blockquote><p>Instead of treating position as a discrete label (like position = 7), sinusoidal embeddings represent position as a smooth signal composed of sine and cosine waves at different frequencies. Nearby positions have similar representations, and distant positions differ gradually. This matches how language works, words closer together are usually more related than words far apart. A single integer index cannot capture this notion of distance, but wave patterns can.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7DwlDelTC-nOV6OoWmxiiw.png" /><figcaption><em>Similarity of every position to position 50. As an ID, position 51 is just as different as position 0. With sinusoidal encodings (d = 64), position 51 keeps a cosine similarity of 0.97</em></figcaption></figure><blockquote><strong>They Enable Relative Position Reasoning</strong></blockquote><p>The most important reason is a mathematical one. Sine and cosine have the special property that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*MfU_E188zmGh4QtlAoL9Lw.png" /></figure><p>can be expressed as linear combinations of <em>sin⁡(pos)</em> and <em>cos(pos)</em>. Because Transformers use linear layers everywhere, this means the model can learn relative distances (“<em>two tokens apart</em>”, “<em>ten tokens apart</em>”) using simple matrix operations without explicitly encoding relative positions.</p><p>Let’s say we want to compare positions pos and pos + k.</p><p>Using trigonometry:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*Yvzap-KeGjOHHV2HdUbgEg.png" /></figure><p>This implies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*yFtP5UEqyeb9pSSJFluWlg.png" /></figure><p>Where <em>Aₖ</em> depends only on k (relative distance), not pos.</p><p>It means that the model can infer relative distance using only linear transformations without explicitly encoding relative positions.</p><p>In other words, relative position information emerges naturally from absolute encodings. This is why sinusoidal embeddings generalize so well.</p><blockquote><strong>They Enable Multi Scale Distance Awareness</strong></blockquote><p>This is the most important insight! A single sine wave repeats, making different positions appear similar. Using multiple waves at various frequencies resolves this issue. High-frequency waves change rapidly and encode <em>local order,</em> such as adjacent words, grammar, and syntax. Low-frequency waves change slowly and represent <em>global position,</em> like early versus late or long-range structure. Combining multiple frequencies turns position into a multi-resolution signal. The transformer can perceive “near” and “far” by comparing patterns across different scales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cd4sPMEM80jl38SkE1NWSQ.png" /><figcaption><em>A single sine wave repeats, so positions 5, 21 and 37 look identical. Adding slower waves gives each position its own combination of values</em></figcaption></figure><p>Each dimension gives a different “view” of position. Together, they uniquely encode:</p><ul><li>Where a token is</li><li>How far is it from others</li></ul><p>This is like using seconds, minutes, and hours together to measure time.</p><blockquote><strong>They Need No Parameters and Work at Any Length</strong></blockquote><p>The encoding is a fixed function of the position. There is nothing to learn and no lookup table to store, and you can compute PE for position 10 or position 10,000 with the same two lines of code. Vaswani et al. actually tried learned positional embeddings as well and &quot;found that the two versions produced nearly identical results&quot;. They picked the sinusoidal version because it &quot;may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.&quot;</p><p>Notice the word <em>may</em>. We will come back to it at the end, because it turns out that it matters a lot.</p><h3>Where Do the Frequencies Come From?</h3><p>Write the formula from earlier with one frequency per pair of dimensions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhcEkBs0i5LERu8Q2a3FwA.png" /></figure><p>Each (sin, cos) pair is a point on a circle, so you can picture it as a clock hand. As the position grows, every hand turns, but each one at its own speed. The frequencies ω_i shrink geometrically from 1 down to 1/10000, so in the words of the paper, &quot;the wavelengths form a geometric progression from 2π to 10000·2π.&quot; The first pair completes a full turn every 6.3 tokens. The slowest ones approach 10000·2π, about 63,000 tokens, far longer than any sequence the original Transformer ever saw, so the slowest hands never wrap around.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*8gNOnHu5cNUEQKMRsCmqmg.gif" /><figcaption><em>Each (sin, cos) pair is a clock hand. Fast hands (orange) separate neighbouring tokens; slow hands (blue) tell you roughly where you are in a long sequence</em></figcaption></figure><p>This is the seconds-minutes-hours analogy made literal. The fast hands tell neighbouring tokens apart, and the slow hands tell the beginning of a document from the end. Plot all of them at once and you get the familiar picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*WME5zYZz4X9DrctFy4oh1g.png" /><figcaption><em>The sine half of the encoding for d = 128. Low frequency indices flicker from token to token, high ones stay almost constant across 128 positions</em></figcaption></figure><p>Why do we need so many hands? Try using only one. With a single frequency ω = 1, I computed the distance between position 0 and every position up to 2,047. Position 710 lands within 0.0001 of position 0, while two neighbouring positions are 0.96 apart. To that one clock, token 0 and token 710 are the same place. With all 64 frequency pairs of a 128-dimensional encoding, the closest pair of distinct positions in the same range turns out to be plain neighbours, 1.95 apart. No two positions collide.</p><h3>Opening Up Aₖ</h3><p>Earlier we wrote PE(pos + k) = Aₖ · PE(pos) and said Aₖ depends only on k. It is worth seeing what Aₖ actually is, because it is surprisingly simple. Apply the two trigonometric identities to one (sin, cos) pair:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*8GhZVkLyBr8pI8_EXEnbqA.png" /></figure><p>That 2 x 2 matrix is a rotation by the angle ω_i · k. So Aₖ is block-diagonal: d/2 small rotation matrices, one per clock hand, each turning its hand by a fixed angle. Moving k tokens forward turns every hand by its own amount, and the amount does not depend on where you started. That is the precise sense in which relative position &quot;emerges&quot; from absolute encodings.</p><p>I checked this numerically for a 128-dimensional encoding over 2,048 positions. One matrix per shift k maps every PE(pos) onto PE(pos + k), with a largest error of about 2 x 10⁻¹³ for k = 1, 5 and 50, which is just floating-point rounding.</p><p>Keep this rotation in mind. Part 2 of this series is about RoPE, and RoPE is what you get when you take this exact rotation and apply it to the queries and keys instead of adding it to the input.</p><h3>What Does Attention Actually See?</h3><p>Attention is built on dot products, so the natural question is what the dot product of two positional encodings looks like. Multiply the pairs out and use cos(a)cos(b) + sin(a)sin(b) = cos(a − b):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*cI-IRSWVYowYrAcJtGyLFw.png" /></figure><p>The position pos has vanished. The similarity between two encodings depends only on how far apart they are. For d = 128 the value is 64 at distance 0, 62.09 at distance 1, 47.19 at distance 5, 42.82 at distance 10, 34.96 at distance 50 and 30.54 at distance 100. Across all 2,048 starting positions those numbers vary by about 10⁻¹² at most, which is rounding error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*da4dWAV9RGNwRFjal7wZoQ.png" /><figcaption><em>The similarity falls off with distance and is a mirror image around k = 0</em></figcaption></figure><p>Two details in this picture are easy to miss.</p><ul><li><strong>It is symmetric.</strong> Cosine is an even function, so a token 10 positions before you and a token 10 positions after you get exactly the same similarity. The raw dot product knows how far away a token is, but not in which direction. The direction is still stored in the encoding (the sine components flip sign), so the learned projections can recover it, but the model has to learn that.</li><li><strong>It is not monotonic.</strong> The curve wiggles as it decays, so a token 280 positions away scores 22.67 while one 250 positions away scores only 19.65. Distance is encoded, but only roughly.</li></ul><p>There is a bigger catch. Attention never compares raw positional encodings. It compares queries and keys, which are projections of the sum of token embedding x and positional encoding p. Write W for the combined matrix W_Qᵀ W_K and expand the attention score between tokens i and j:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*Jlz1rE6vSVrjlXxrL6uZ3Q.png" /></figure><p>Only the last term is purely about position, and once W sits in the middle it is no longer guaranteed to depend on the distance alone. The two middle terms mix &quot;what this word is&quot; with &quot;where that word is&quot;. Ke, He and Liu (ICLR 2021) argued that this mixing adds unnecessary randomness to attention, and proposed computing the content and position correlations separately. So the neat relative-position property holds for the encodings themselves, but by the time it reaches the attention score it is tangled up with content.</p><h3>Why Add Instead of Concatenate?</h3><p>A common question is why the positional encoding is <em>added</em> to the token embedding instead of being stuck on the end. &quot;<em>The positional encodings have the same dimension d_model as the embeddings, so that the two can be summed.</em>&quot; Concatenation would widen every layer that follows, so every weight matrix in the model would grow just to carry position.</p><p>Addition works because high-dimensional space is roomy. Token embeddings and positional encodings can live in mostly different directions, and the projections W_Q and W_K can learn to read them apart. The paper also multiplies the token embedding weights by √d_model, and a common explanation is that this keeps word meaning from being drowned out by positional values that sit between −1 and 1. The cost of addition is the mixing we just saw in the four-term expansion.</p><h3>The Whole Thing in NumPy</h3><p>Here is the encoding, the Aₖ rotation and the two checks from above:</p><pre>import numpy as np<br><br>def sinusoidal_pe(n_pos, d, base=10000.0):<br>    pos = np.arange(n_pos)[:, None]<br>    omega = base ** (-np.arange(0, d, 2) / d)     # one frequency per pair<br>    pe = np.zeros((n_pos, d))<br>    pe[:, 0::2] = np.sin(pos * omega)<br>    pe[:, 1::2] = np.cos(pos * omega)<br>    return pe, omega<br><br>def shift_matrix(k, omega):<br>    &quot;&quot;&quot;A_k: block-diagonal 2x2 rotations by k * omega_i.&quot;&quot;&quot;<br>    A = np.zeros((2 * len(omega), 2 * len(omega)))<br>    for i, w in enumerate(omega):<br>        c, s = np.cos(k * w), np.sin(k * w)<br>        A[2*i:2*i+2, 2*i:2*i+2] = [[c, s], [-s, c]]<br>    return A<br><br>pe, omega = sinusoidal_pe(2048, 128)<br><br>for k in [1, 5, 50]:                              # PE(pos+k) = A_k PE(pos)<br>    err = np.abs(pe[:-k] @ shift_matrix(k, omega).T - pe[k:]).max()<br>    print(k, err)                                 # about 2e-13<br><br>dots = pe @ pe.T                                  # depends only on distance<br>for k in [0, 1, 5, 10, 50, 100]:<br>    print(k, np.diagonal(dots, offset=k).mean())  # 64.0, 62.09, 47.19, ...</pre><h3>So, How Did Sinusoidal Encodings Do?</h3><p>Let us go back to the four criteria for a good positional encoding and score the sinusoidal version honestly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jf2KFByRov7Y1yrRZL0xg.png" /></figure><p>The third row is where that word <em>may</em> comes back. The encoding can be computed for any position, but that does not mean a trained model knows what to do with positions it has never seen. Press, Smith and Lewis tested exactly this in their ALiBi paper (ICLR 2022). A sinusoidal model trained on 512-token inputs got better for roughly 20 extra tokens at test time, held steady until about 50, and then degraded. In one of their larger setups the sinusoidal model &quot;cannot extrapolate at all&quot;: it gets worse from the very first extra token. Being able to write down PE(5000) is not the same as having learned what it means.</p><h3>Wrapping Up</h3><p>Sinusoidal encodings are a beautifully cheap answer to the order problem. They give every position a unique fingerprint built from clocks running at different speeds, they make every shift a rotation, and they cost zero parameters. Their weak spots are just as clear: relative distance only survives in a tangled form inside attention, direction is lost in the raw similarity, and long inputs are a gamble.</p><p>The next two parts take those weak spots one at a time. In <a href="https://medium.com/@srivatsa.n63/part-2-rotary-positional-embeddings-rope-a-deep-intuitive-and-mathematical-explanation-2c0184430625">Part 2</a> we will look at <strong>RoPE</strong>, which keeps the rotation from Aₖ but applies it directly to queries and keys, so the attention score depends on relative position by construction. In <a href="https://medium.com/p/e2ed8bdf4f79">Part 3</a> we will look at <strong>ALiBi</strong>, which drops positional embeddings altogether and adds a simple distance penalty to the attention scores, the trick that let Press et al. train short and test long.</p><h3>References</h3><ol><li>A. Vaswani et al., <a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need</em>, NeurIPS 2017. arXiv:1706.03762</a></li><li>G. Ke, D. He and T.-Y. Liu, <a href="https://arxiv.org/abs/2006.15595"><em>Rethinking Positional Encoding in Language Pre-training</em>, ICLR 2021. arXiv:2006.15595</a></li><li>O. Press, N. A. Smith and M. Lewis, <a href="https://arxiv.org/abs/2108.12409"><em>Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation</em>, ICLR 2022. arXiv:2108.12409</a></li><li>J. Su et al., <em>RoFormer: </em><a href="https://arxiv.org/abs/2104.09864"><em>Enhanced Transformer with Rotary Position Embedding</em>, 2021. arXiv:2104.09864</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de5c74731862" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 1960 Learning Rule Hiding Inside Today's Linear Attention]]></title>
            <link>https://medium.com/@srivatsa.n63/the-1960-learning-rule-hiding-inside-todays-linear-attention-1273895c45e8?source=rss-22246753979c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1273895c45e8</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Srivatsa Narasimha]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 07:06:59 GMT</pubDate>
            <atom:updated>2026-10-27T16:11:08.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_6FR5yzEnVVcc0czzQEBtg.png" /></figure><p>If you ran <a href="https://www.morphllm.com/qwen-3-6">Qwen3.6</a> on your own machine this year, three out of every four of its sequence-mixing layers were not doing softmax attention. They were Gated DeltaNet layers: a kind of linear attention that keeps one fixed-size memory matrix per head instead of a KV cache that grows with every token. And on 19 October 2026, Sepp Hochreiter&#39;s group posted <a href="https://arxiv.org/abs/2610.26834">KronLSTM</a>, a linear attention model whose whole pitch is that it revises that memory with less interference than &quot;the (Gated) DeltaNet family&quot; and does better on long-context benchmarks.</p><p>So right now a lot of very smart people are arguing about one small thing: how a model should write a new fact into a matrix. The rule most of them are trying to beat is the &quot;delta&quot; in DeltaNet, and it comes from 1960. Bernard Widrow and Ted Hoff published it at the IRE WESCON convention to train ADALINE, a single adaptive neuron that Widrow&#39;s lab at Stanford built as real hardware. Engineers know it as LMS, the least mean squares filter, and it has been quietly cancelling echoes and equalizing modem signals for decades.</p><p>I went looking for the clever new trick inside a 2026 language model and found the algorithm from my signal processing textbook, the chapter I skimmed the night before the exam. The good news is that once you see it, two things that sound unrelated turn out to be the same equation: a recurrent layer reading your prompt, and one step of stochastic gradient descent on a tiny regression problem.</p><p>Think of the memory matrix as a shared whiteboard in a flat. Each token arrives with a key (a label: &quot;where Alice lives&quot;) and a value (the content: &quot;Pune&quot;). Plain linear attention writes every note on the same board, in pencil, right on top of everything already there. It never erases. To read, you hold up a key and the board answers with the note filed under it, plus a faint ghost of every other note, each one as faint as its key is different from yours.</p><p>With a 64-dimensional key you can fit 64 perfectly distinct labels, because that is how many mutually orthogonal directions 64 dimensions have. Note number 65 has to share a direction with somebody. After a few hundred notes the ghosts add up and the board mostly answers with noise. In my simulation below, past 64 random facts it answers worse than if it had said nothing at all.</p><p>The delta rule is the flatmate who reads the board before writing. Hold up the key, see what the board currently says, compute the difference between that and what it should say, and write only the difference. That difference is the &quot;delta&quot;. If the board already had it right, nothing changes. If Alice moved from Pune to Tokyo, the rule rubs out Pune under that key and writes Tokyo, instead of leaving you with a smudged average of both cities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*QPnYrD9ixqCCMFXIJ6US9g.gif" /><figcaption><em>Writing 128 random facts into a 64 x 64 memory. Each bar is how badly one fact is recalled (1.0 = as bad as answering with zeros). Linear attention (top) degrades every fact at once; the delta rule (bottom) keeps recent facts sharp and lets old ones fade</em></figcaption></figure><p>Watch the two panels. The top one rises everywhere at once, like a pot coming to the boil. The bottom one has a clean slope: the newest fact is always recalled exactly, and the damage piles up on the oldest notes, which is what you want from a memory with a fixed size.</p><h3>The math</h3><p>Linear attention keeps a d x d state matrix S. Each token writes the outer product of its value and key, and the output for a query q is a single matrix-vector product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*Z9tlp3BCi9eMhbjV26do1A.png" /></figure><p>That is the whole trick behind &quot;Transformers are RNNs&quot; (Katharopoulos et al., 2020): drop the softmax and attention becomes a running sum, so memory stays constant no matter how long the prompt is. It is also, almost word for word, the correlation-matrix associative memory of the early 1970s, which is itself Hebb&#39;s 1949 rule of &quot;strengthen the connection between things that fire together&quot;.</p><p>Now read back a stored fact using its own key k_j as the query. Assume unit-length keys and values, drawn at random:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBgoeuTefec9Z0nI-YbYHA.png" /></figure><p>The first term is the answer you wanted, and the sum is the ghosts. For two random unit vectors in d dimensions, the expected squared dot product is exactly 1/d, and the cross terms between different random values average to zero, so the crosstalk energy is (N - 1)/d. The recall error therefore grows like the square root of N/d. With d = 64 it hits 1.0, the error you would get by answering with a vector of zeros, at about N = 65.</p><p>The delta rule starts from a different question: what is the best single change to S for this one token? Treat each token as a tiny regression problem, &quot;S should map k_t to v_t&quot;, and take one gradient step on the squared error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BxJB5ap8oI_8phTZgXcixA.png" /></figure><p>The gradient of that loss with respect to S is (S k_t - v_t) k_t transposed, an outer product of the prediction error and the input. Each row of S is a single linear neuron, and this update is the Widrow-Hoff rule from 1960: new weights = old weights + learning rate x (target - prediction) x input. Schlag, Irie and Schmidhuber (2021) were the first to put this rule inside a linear transformer, which they described as a fast weight programmer. Rearranging gives the form you see in the DeltaNet papers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*8IFPc2wxeU9Qa0jD1-LalA.png" /></figure><p>Read it in two parts. The factor (I - β k kᵀ) first wipes out what S stored along the direction of k, then the second term writes the new value there. With a unit key and β = 1, that matrix is an exact projection, and afterwards S_t k_t = v_t on the nose: the newest fact is always recalled perfectly. Plain linear attention is the same formula with the erasing matrix deleted.</p><p>The 1960 paper also hands you a stability condition for free. Along the direction of k, the update multiplies the old memory by 1 - β‖k‖², so old content along k shrinks only when 0 &lt; β‖k‖² &lt; 2, and grows once β‖k‖² goes past 2. That is why Gated DeltaNet L2-normalizes its keys and squashes β through a sigmoid into (0, 1): it keeps a 66-year-old adaptive filter inside its safe zone. Gated DeltaNet (Yang, Kautz and Hatamizadeh, ICLR 2025) then adds a decay gate α_t in (0, 1) that lets the whole board fade a little at each step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*L52Q6q6ipXM58ll_ZTYV_g.png" /></figure><p>I checked all of this with NumPy: 64-dimensional random unit keys and values, N facts written one at a time, then every fact recalled with its own key. Each setting is averaged over 20 random seeds.</p><pre>import numpy as np<br>unit = lambda x: x / np.linalg.norm(x, axis=-1, keepdims=True)<br><br>def write(S, k, v, rule, beta=1.0, alpha=1.0):<br>    if rule == &quot;linear&quot;:                       # S += v k^T<br>        return S + np.outer(v, k)<br>    # delta rule (alpha &lt; 1 gives the Gated DeltaNet decay)<br>    return alpha * (S - beta * np.outer(S @ k, k)) + beta * np.outer(v, k)<br><br>def rms_error(rule, N, d=64, trials=20, **kw):<br>    errs = []<br>    for seed in range(trials):<br>        rng = np.random.default_rng(seed)<br>        K, V = unit(rng.standard_normal((2, N, d)))<br>        S = np.zeros((d, d))<br>        for k, v in zip(K, V):<br>            S = write(S, k, v, rule, **kw)<br>        errs.append(np.linalg.norm(K @ S.T - V, axis=1))<br>    return np.sqrt(np.mean(np.square(errs)))<br><br>for N in [16, 32, 64, 128, 256, 512]:<br>    print(N, round(rms_error(&quot;linear&quot;, N), 3), round(np.sqrt((N - 1) / 64), 3),<br>          round(rms_error(&quot;delta&quot;, N), 3),<br>          round(rms_error(&quot;delta&quot;, N, alpha=0.97), 3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6luF2zxvkknhUj6JHsdvJA.png" /><figcaption><em>RMS recall error over all stored facts, d = 64, 20 seeds per row. 1.0 is the error of answering with zeros</em></figcaption></figure><p>The square-root law matches the simulation to within 0.01 from N = 32 onward, which made me irrationally happy. Both delta variants beat linear attention at every load, but look at what the plain delta rule is doing at the high end. Averaged over all 512 facts its error is 1.32, above the answering-with-zeros line, because the oldest notes have been rubbed out on purpose. The 16 most recent facts in that same run are recalled with an RMS error of 0.47, while linear attention manages 2.84 on those same recent facts. The decay gate trades a bit of accuracy at low load for a smaller average error once the board is crowded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*IIma1H-lb6o995FpE2zWDg.png" /><figcaption><em>Linear attention sits right on the square-root law; the delta rule grows far more slowly, and its gated version flattens out near 1.0</em></figcaption></figure><p>The second experiment is the Alice-moved test. One key gets rewritten m times with a fresh random value, with 8 unrelated facts written between rewrites, and I measure the cosine between what comes back and the latest value (50 seeds). With a single write both rules do fine: 0.946 for linear attention and 0.931 for the delta rule. After 16 rewrites, linear attention is down to 0.212, close to the 1/√m you would predict for an average of m random vectors, while the delta rule still sits at 0.886.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*1XbvkuvzeX8KiPFDkmBTTw.png" /><figcaption><em>Rewrite the same key m times: linear attention returns the average of every version, the delta rule returns the latest one</em></figcaption></figure><h3>Why this matters if you train or run these models</h3><p>Once you read every linear-attention layer as &quot;a tiny regression model trained online, one token at a time&quot;, a lot of recent architecture news becomes much easier to follow.</p><ul><li><strong>The hybrid ratio is a capacity budget.</strong> A d-dimensional key gives each head room for roughly d clean facts (64 in my toy setup), and the table above shows what happens past that. Qwen3.6 keeps one full softmax-attention layer for every three Gated DeltaNet layers, so exact long-range lookups still have somewhere to go. You are buying constant memory with recall, and those numbers give a rough exchange rate, with the square-root law as the worst case for plain linear attention.</li><li><strong>The gates are learning-rate schedules.</strong> β is a per-token learning rate and α is weight decay on the memory. When a paper says its gating is &quot;data-dependent&quot;, read it as &quot;the layer picks its own step size and forgetting rate for every token&quot;, which is what adaptive-filter people have been doing since the 1960s with normalized LMS (divide the step by ‖k‖²) and variable step-size LMS.</li><li><strong>New layers are new optimizers.</strong> If one delta step is one SGD step, the obvious next move is a better optimizer. Longhorn (Liu et al.) derives its recurrence as an online learner, DeltaProduct (Siems et al.) takes several Householder-style delta steps per token, and Titans (Behrouz et al.) adds momentum to the memory update. KronLSTM, the paper from 19 October, changes which direction of the memory the update is allowed to touch to reduce interference with what is already stored.</li><li><strong>Training speed was the real blocker.</strong> The rule is from 1960, but you cannot train a language model with a Python loop over tokens. DeltaNet only became practical after Yang et al. (NeurIPS 2024) showed how to parallelize the products of (I - β k kᵀ) matrices over chunks of the sequence, which is what the flash-linear-attention kernels do on GPUs.</li><li><strong>Your keys need to be normalized.</strong> If you build one of these layers yourself and the loss explodes, check ‖k‖ before anything else. An unnormalized key can push β‖k‖² past 2, and then each write amplifies what was stored along k instead of correcting it.</li></ul><h4>References</h4><ol><li>B. Widrow and M. E. Hoff, <em>Adaptive Switching Circuits</em>, IRE WESCON Convention Record, Part 4, pp. 96 to 104, 1960. MIT Press reprint: <a href="https://direct.mit.edu/books/edited-volume/5431/chapter-abstract/3958517/1960-Bernard-Widrow-and-Marcian-E-Hoff-Adaptive">https://direct.mit.edu/books/edited-volume/5431/chapter-abstract/3958517/1960-Bernard-Widrow-and-Marcian-E-Hoff-Adaptive</a></li><li>D. O. Hebb, <em>The Organization of Behavior</em>, Wiley, 1949.</li><li>T. Kohonen, <em>Correlation Matrix Memories</em>, IEEE Transactions on Computers, 1972.</li><li>A. Katharopoulos, A. Vyas, N. Pappas and F. Fleuret, <em>Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention</em>, ICML 2020. arXiv:2006.16236</li><li>I. Schlag, K. Irie and J. Schmidhuber, <em>Linear Transformers Are Secretly Fast Weight Programmers</em>, ICML 2021. arXiv:2102.11174</li><li>S. Yang, B. Wang, Y. Zhang, Y. Shen and Y. Kim, <em>Parallelizing Linear Transformers with the Delta Rule over Sequence Length</em>, NeurIPS 2024. arXiv:2406.06484</li><li>S. Yang, J. Kautz and A. Hatamizadeh, <em>Gated Delta Networks: Improving Mamba2 with Delta Rule</em>, ICLR 2025. arXiv:2412.06464</li><li>B. Liu et al., <em>Longhorn: State Space Models are Amortized Online Learners</em>, ICLR 2025. ICLR proceedings: <a href="https://proceedings.iclr.cc/paper_files/paper/2025/hash/ee0e45ff4de76cbfdf07015a7839f339-Abstract-Conference.html">https://proceedings.iclr.cc/paper_files/paper/2025/hash/ee0e45ff4de76cbfdf07015a7839f339-Abstract-Conference.html</a></li><li>J. Siems et al., <em>DeltaProduct: Improving State-Tracking in Linear RNNs via Householder Products</em>, NeurIPS 2025. arXiv:2502.10297</li><li>A. Behrouz, P. Zhong and V. Mirrokni, <em>Titans: Learning to Memorize at Test Time</em>, 2024. arXiv:2501.00663</li><li>A.-R. Hartl, L. Zólyomi, M. List, G. Klambauer, S. Böck and S. Hochreiter, <em>Kronecker Delta Rule for Long Context Linear Attention</em> (KronLSTM), submitted 19 October 2026. arXiv:2610.26834</li><li><em>Qwen 3.6 27B: architecture overview</em> (Gated DeltaNet hybrid, 3:1 ratio), Morph. https://www.morphllm.com/qwen-3-6</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1273895c45e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>