08A.10 Agent Patterns: ReAct, Plan-and-Execute, Routing and Orchestrator-Workers

Agents & multimodalLesson 10 of 1511,918 words11 parts
Module 08A · 0 of 15 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15

08A.2 gave you the agent loop: call the model, run its tool calls, feed the results back, repeat until it answers or a budget says stop. This lesson is about what you put inside that loop. An agent pattern is a deliberate shape for the model's decisions: when it should reason out loud, when it should plan before acting, when it should hand work to a specialist, when it should stop and ask a human. You will meet the patterns that have names — ReAct, plan-and-execute, reflection, routing, orchestrator-workers — learn where each came from, implement each one over the same injectable call_model seam so it is testable without API keys, and finish with the control patterns (approval, permissions, budgets, loop detection, timeouts) that keep an agent from running away. The running example throughout is the module's support and operations assistant, plus a small research agent where a pattern fits it better.

This lesson has a companion. 08A.11 takes the three patterns that are only introduced here (reflection, parallel fan-out and agent-as-a-tool) and builds the production versions. Read 08A.10 first for the whole catalogue, then read 08A.11 next for the deeper reflection and the parallel patterns. 08A.12 and 08A.13 do the same for human approval and for background agents.

What you'll learn

  • What an agent pattern actually is — control flow, prompts and state, not a library — and the pattern spectrum from a single call to a free-running agent
  • ReAct: the 2022 paper, why native tool calling with interleaved reasoning replaced the text format, the scratchpad/"think" tool, and when explicit thoughts help or just cost tokens
  • Plan-and-execute: a planner that produces a step list, bounded executors per step, and a replanner that revises when reality disagrees — with full code
  • Reflection and self-critique (the Reflexion pattern) in its smallest bounded form, and verification loops that check results against the environment rather than the model's word. Score-aware reflection, parallel fan-out and agent-as-a-tool are catalogued here and built in the companion lesson 08A.11
  • Routing to specialists, orchestrator-workers with context isolation, the todo/task-list tool pattern used by coding agents, scratchpads and notes files
  • Awareness-level coverage of tree-of-thought/search agents (ToT, LATS) and self-consistency for agents
  • Control and safety patterns: human-in-the-loop approval with approve/edit/reject and resumable state (full code; 08A.12 goes deeper), permission models, budgets and circuit breakers, loop and stall detection, timeouts and cancellation, fallback to a human
  • How to prompt an agent: the system-prompt blueprint, three complete agent system prompts, tool-use prompting pitfalls, and reasoning effort per task
  • State machines as an alternative to free loops, and trajectory logging as the hook every evaluation builds on
  • A decision table for choosing a pattern, and a failure gallery for the ways each one breaks
  • Where to go next: 08A.11 (the pair of this lesson) for the deeper reflection and the parallel patterns, 08A.12 for approval gates, 08A.13 for unattended agents

What you don't need

  • API keys. Every pattern runs against a ScriptedModel test double that replays canned replies; all code in this lesson is pure Python 3.11+ standard library and runs locally. Samples that would call a provider are labelled and their outputs marked illustrative.
  • The tool-calling wire format. Lesson 03.5 owns one round trip per provider; lesson 08A.2 owns the production loop. This lesson plugs patterns into the call_model seam both of them use.
  • Memory systems. Short-term and long-term agent memory is lesson 08B.2; multi-agent architectures are lesson 08D.3; frameworks are lesson 08F.1; reliable/safe agents in depth is lesson 08A.14.

Setup

The code needs Python 3.11+ only — no packages, no keys, no services. If you haven't created a project yet, run uv init agent-patterns --bare --python 3.13 && cd agent-patterns first (see lesson 03.1, Part 4). Then create these seven files next to each other. Each file is printed complete in the lesson — the code blocks carry a # <file>.py banner and appear in file order, so copy each file's blocks in sequence and you assemble the whole runnable file (every definition is shown; only module docstrings and # ---- section banners are omitted for readability):

  • agent_loop.py — the minimal canonical loop, ToolRegistry, Budget, ScriptedModel, pause/resume (Part 1)
  • support_tools.py — the running example's tools over in-memory fake data (Part 1)
  • patterns.py — ReAct, plan-and-execute, reflection, verification, routing, orchestrator-workers, todo/notes (Parts 2–5)
  • approval.py — permission policy and the approval gate (Part 6)
  • statemachine.py — the tiny state-machine runner (Part 8)
  • trajectory.py — event logging and summaries (Part 9)
  • demo.py — the consolidated demo that exercises every pattern (Part 11)

Every demo is asyncio.run(main())-style and python3 demo.py prints real output you can reproduce:

bash
python3 demo.py

What you must be able to do after this lesson#

  • Explain what an agent pattern is: control flow, prompts and state
  • Implement ReAct with native tool calling
  • Build plan-and-execute with a bounded executor and a replanner
  • Add verification and reflection to an agent run
  • Name parallel fan-out and agent-as-a-tool as catalogue patterns, and know that 08A.11 is the lesson to read next for them and for score-aware reflection
  • Add human approval to an agent loop
  • Choose a pattern with the decision table
  • Say where the control patterns continue: approval gates in 08A.12, unattended runs in 08A.13

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Let's do this ReAct-style." Part 2 — and why nobody writes the text format any more
"Have the model plan first, then execute." Part 3
"Add a critic pass / self-reflection." Part 4, then 08A.11 for the gate and score-aware version
"Fan the searches out in parallel." 1.5, then 08A.11, Part 3
"Make the researcher a tool of the manager agent." 1.5, then 08A.11, Part 4
"Route cheap queries to a small model." Part 5
"Spawn a sub-agent for the research part." Part 5.3 and 08D.3
"Make it ask before it refunds." Part 6, then 08A.12
"The agent is looping — how do we stop it?" 6.3–6.5
"Write the agent's system prompt." Part 7
"Model the flow explicitly instead of looping." Part 8
"Log the trajectory for evals." Part 9

Part 1: The loop and the pattern catalogue#

1.1 What a pattern is (and isn't)#

A pattern in this lesson is a recipe for the control flow around call_model: which calls happen in which order, what state is kept between them, what the prompts say, and which stop conditions apply. It is deliberately not a framework — the same ReAct loop runs on OpenAI, Anthropic, Gemini or OpenRouter because call_model hides the provider (03.11 builds that abstraction; 08A.2 wires it to real SDKs).

The spectrum from 08A.9 still applies: a single call → chained calls → routed calls → an agent loop → an agent with planning and delegation. Patterns are points inside the agent region of that spectrum. The module's guiding principle holds here too: use the simplest thing that works. A pattern earns its extra calls, latency and cost only when the task needs the flexibility.

1.2 The seam every pattern shares#

Everything below plugs into one function signature. In production call_model is an adapter over a provider SDK; in tests it is a ScriptedModel that replays canned replies:

python
CallModel = Callable[..., Awaitable[ModelReply]]
# call_model(messages, tool_specs, **model_kwargs) -> ModelReply

model_kwargs carries whatever the adapter needs (model id, reasoning effort, max tokens). Patterns never inspect it.

1.3 agent_loop.py: types, registry, budget, loop, test double#

This is the file every other file imports. It is deliberately smaller than 08A.2's production loop — no streaming, no parallel tool execution, no provider adapters — but it has the same shape: injectable call_model, a ToolRegistry that validates and dispatches, a Budget of hard limits, stop conditions, and a gate hook where approval and permission policies attach.

python
# agent_loop.py — the minimal canonical agent loop (lesson 08A.10).
from __future__ import annotations

import asyncio
import hashlib
import json
import time
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any


@dataclass
class ToolCall:
    """One tool call the model asked for. `arguments` is already-parsed JSON."""
    id: str
    name: str
    arguments: dict[str, Any] = field(default_factory=dict)


@dataclass
class Message:
    """A provider-neutral message. Adapters translate to each provider's wire format."""
    role: str  # "system" | "user" | "assistant" | "tool"
    content: str | None = None
    tool_calls: list[ToolCall] = field(default_factory=list)
    tool_call_id: str | None = None  # set on role="tool" results
    name: str | None = None          # tool name on role="tool" results


@dataclass
class Usage:
    input_tokens: int = 0
    output_tokens: int = 0

    def __add__(self, other: "Usage") -> "Usage":
        return Usage(self.input_tokens + other.input_tokens,
                     self.output_tokens + other.output_tokens)


@dataclass
class ModelReply:
    """What `call_model` returns: text, the tool calls it wants, and why it stopped."""
    text: str | None
    tool_calls: list[ToolCall] = field(default_factory=list)
    finish_reason: str = "stop"  # "stop" | "tool_calls" | "length" | ...
    usage: Usage | None = None


CallModel = Callable[..., Awaitable[ModelReply]]


@dataclass
class Tool:
    """One callable the model may use. `parameters` is the JSON Schema it sees."""
    name: str
    description: str
    parameters: dict[str, Any]
    fn: Callable[..., Any]
    risk: str = "read"  # "read" | "write" | "destructive" — Part 6 goes deep
    timeout: float | None = None  # per-tool override of ToolRegistry.call's default

    def spec(self) -> dict[str, Any]:
        return {"name": self.name, "description": self.description,
                "parameters": self.parameters}

The registry is where tool calls become results. Two details matter for everything later: unknown tool names and exceptions are returned to the model as error text, never raised — the model can read {"error": ...} and recover (the same contract as 03.5, Part 7.4); and subset() gives routing and least-privilege patterns a filtered tool list:

python
class ToolRegistry:
    """The set of tools one agent may call. Lookup, dispatch and error wrapping live here."""

    def __init__(self) -> None:
        self._tools: dict[str, Tool] = {}

    def add(self, tool: Tool) -> Tool:
        if tool.name in self._tools:
            raise ValueError(f"duplicate tool name: {tool.name}")
        self._tools[tool.name] = tool
        return tool

    def register(self, fn=None, *, name=None, description=None,
                 parameters=None, risk="read"):
        """Decorator form: @registry.register(parameters={...}, risk="write")"""
        def wrap(f):
            self.add(Tool(
                name=name or f.__name__,
                description=description or (f.__doc__ or "").strip().split("\n\n")[0],
                parameters=parameters or {"type": "object", "properties": {}},
                fn=f, risk=risk))
            return f
        return wrap(fn) if fn is not None else wrap

    def get(self, name: str) -> Tool | None:
        return self._tools.get(name)

    def names(self) -> list[str]:
        return sorted(self._tools)

    def specs(self) -> list[dict[str, Any]]:
        return [t.spec() for t in self._tools.values()]

    def subset(self, names) -> "ToolRegistry":
        """A registry containing only the named tools (routing, least privilege)."""
        sub = ToolRegistry()
        for n in names:
            t = self._tools.get(n)
            if t is not None:
                sub.add(t)
        return sub

    async def call(self, call: ToolCall, *, timeout: float = 30.0) -> str:
        """Run one tool call; always return a string the model can read.

        Errors are *returned*, not raised: the model sees {"error": ...} as the
        tool result and can recover or ask for help (03.5, Part 7.4).
        """
        tool = self.get(call.name)
        if tool is None:
            return json.dumps({"error": f"unknown tool {call.name!r}; "
                                         f"available: {self.names()}"})
        try:
            limit = tool.timeout if tool.timeout is not None else timeout
            result = tool.fn(**(call.arguments or {}))
            if asyncio.iscoroutine(result):
                result = await asyncio.wait_for(result, limit)
            return _to_result_text(result)
        except asyncio.TimeoutError:
            return json.dumps({"error": f"tool {call.name} timed out after {limit}s"})
        except Exception as exc:  # a tool bug becomes a model-visible error
            return json.dumps({"error": f"{type(exc).__name__}: {exc}"})


def _to_result_text(result: Any) -> str:
    if isinstance(result, str):
        return result
    return json.dumps(result, default=str)

The Budget is the first safety pattern, present from the first sample as the module rules require. Every run gets hard limits; the loop checks them before each model call:

python
@dataclass
class Budget:
    """Hard limits for one agent run. Checked before every model call."""
    max_steps: int = 12               # model calls allowed
    max_input_tokens: int = 200_000
    max_output_tokens: int = 30_000
    max_cost_usd: float = 1.0
    max_seconds: float = 600.0
    input_usd_per_1m: float = 0.0     # 0 disables cost accounting
    output_usd_per_1m: float = 0.0
    max_calls_per_tool: int = 5       # per-tool circuit breaker


@dataclass
class GateVerdict:
    """What a `gate` callback decides for one tool call (Part 6)."""
    action: str = "proceed"                    # "proceed" | "replace" | "pause"
    result: str | None = None                  # "replace": text fed back as tool result
    payload: dict[str, Any] | None = None      # "pause": JSON-safe request for the caller


# A gate inspects a tool call before it runs: permissions, approvals, arg policies.
Gate = Callable[[ToolCall, "Tool | None"], Awaitable[GateVerdict]]

Now the loop itself. Read it once carefully — nearly every later section refers back to it. The structure is: drain queued tool calls (with gate checks, loop detection, stall detection, circuit breaker) → check budgets → call the model → append the assistant message → stop on length or a text-only reply → otherwise queue its tool calls:

python
@dataclass
class AgentResult:
    answer: str | None
    stop_reason: str            # see _STOP_REASONS below
    messages: list[Message]
    steps: int = 0
    usage: Usage = field(default_factory=Usage)
    cost_usd: float = 0.0
    events: list[dict[str, Any]] = field(default_factory=list)
    pending_calls: list[ToolCall] = field(default_factory=list)  # set when paused
    pause_payload: dict[str, Any] | None = None


_STOP_REASONS = {
    "answered", "truncated", "max_steps", "max_tokens", "max_cost", "max_seconds",
    "model_timeout", "model_error", "loop_detected", "stalled", "circuit_breaker",
    "paused",
}


def _ev(state: dict, on_event, type_: str, **fields) -> dict[str, Any]:
    """Append an event to state["events"] and forward it to on_event."""
    event = {"type": type_, "ts": round(time.monotonic() - state["t0"], 4),
             "step": state["steps"], **fields}
    state["events"].append(event)
    if on_event is not None:
        on_event(event)
    return event


def _call_key(call: ToolCall) -> str:
    return f"{call.name}|{json.dumps(call.arguments, sort_keys=True)}"


def _is_error_result(text: str) -> bool:
    try:
        obj = json.loads(text)
    except (json.JSONDecodeError, TypeError):
        return False
    # truthiness, not key presence: {"error": null, "data": ...} is not a failure
    return isinstance(obj, dict) and bool(obj.get("error"))


def _preview(text: str, n: int = 300) -> str:
    return text if len(text) <= n else text[:n] + f"…(+{len(text) - n} chars)"


async def _drive(call_model, registry, messages, budget, state, *,
                 model_kwargs, gate, on_event, timeout_per_call,
                 max_identical_calls, pending) -> AgentResult:
    """The loop. `pending` holds tool calls left over from a paused turn."""
    todo = list(pending or [])
    call_counts: dict[str, int] = {}
    tool_counts: dict[str, int] = {}
    result_hashes: list[str] = []

    def finish(stop_reason: str, answer: str | None = None) -> AgentResult:
        return AgentResult(
            answer=answer, stop_reason=stop_reason, messages=messages,
            steps=state["steps"], usage=Usage(**state["usage"]),
            cost_usd=state["cost"], events=state["events"],
            pending_calls=list(todo) if stop_reason == "paused" else [],
            pause_payload=state.get("pause_payload"))

    while True:
        # ---- drain queued tool calls from the open assistant turn ----
        if todo:
            call = todo.pop(0)
            key = _call_key(call)
            call_counts[key] = call_counts.get(key, 0) + 1
            if call_counts[key] > max_identical_calls:
                _ev(state, on_event, "loop_detected", tool=call.name,
                    args=call.arguments)
                return finish("loop_detected")
            tool = registry.get(call.name)
            tool_counts[call.name] = tool_counts.get(call.name, 0) + 1
            if tool_counts[call.name] > budget.max_calls_per_tool:
                result_text = json.dumps(
                    {"error": f"per-tool call limit reached for {call.name!r}"})
                _ev(state, on_event, "tool_denied", tool=call.name,
                    reason="call_limit")
            else:
                verdict = await gate(call, tool) if gate else GateVerdict()
                if verdict.action == "pause":
                    todo.insert(0, call)
                    state["pause_payload"] = verdict.payload or {}
                    _ev(state, on_event, "paused", tool=call.name,
                        payload=state["pause_payload"])
                    return finish("paused")
                if verdict.action == "replace":
                    result_text = verdict.result or ""
                    _ev(state, on_event, "tool_denied", tool=call.name,
                        result=_preview(result_text))
                else:
                    _ev(state, on_event, "tool_call", tool=call.name,
                        args=call.arguments, risk=getattr(tool, "risk", None))
                    result_text = await registry.call(call)
                    _ev(state, on_event, "tool_result", tool=call.name,
                        result=_preview(result_text))
            if _is_error_result(result_text):
                state["consecutive_errors"] += 1
                if state["consecutive_errors"] >= 3:
                    _ev(state, on_event, "circuit_breaker")
                    return finish("circuit_breaker")
            else:
                state["consecutive_errors"] = 0
            digest = hashlib.sha256(result_text.encode()).hexdigest()[:12]
            result_hashes.append(digest)
            if len(result_hashes) >= 3 and \
                    result_hashes[-3:] == [digest] * 3:
                _ev(state, on_event, "stalled", detail="same result 3x")
                return finish("stalled")
            messages.append(Message(role="tool", tool_call_id=call.id,
                                    name=call.name, content=result_text))
            continue

        # ---- no pending tool calls: budget checks, then ask the model ----
        if state["steps"] >= budget.max_steps:
            return finish("max_steps")
        if state["usage"]["input_tokens"] >= budget.max_input_tokens or \
                state["usage"]["output_tokens"] >= budget.max_output_tokens:
            return finish("max_tokens")
        if state["cost"] >= budget.max_cost_usd:
            return finish("max_cost")
        if time.monotonic() - state["t0"] > budget.max_seconds:
            return finish("max_seconds")

        _ev(state, on_event, "model_call", tools=len(registry.specs()))
        try:
            reply = await asyncio.wait_for(
                call_model(list(messages), registry.specs(),
                           **(model_kwargs or {})),
                timeout=timeout_per_call)
        except asyncio.TimeoutError:
            _ev(state, on_event, "model_timeout", timeout=timeout_per_call)
            return finish("model_timeout")
        except asyncio.CancelledError:
            raise   # cancellation must propagate — never swallow it here
        except Exception as exc:
            _ev(state, on_event, "model_error", error=repr(exc))
            return finish("model_error")

        state["steps"] += 1
        if reply.usage is not None:
            state["usage"]["input_tokens"] += reply.usage.input_tokens
            state["usage"]["output_tokens"] += reply.usage.output_tokens
            state["cost"] += (
                reply.usage.input_tokens * budget.input_usd_per_1m
                + reply.usage.output_tokens * budget.output_usd_per_1m
            ) / 1_000_000
        _ev(state, on_event, "model_reply", finish_reason=reply.finish_reason,
            tool_calls=[c.name for c in reply.tool_calls],
            text=_preview(reply.text or ""),
            input_tokens=(reply.usage.input_tokens if reply.usage else None),
            output_tokens=(reply.usage.output_tokens if reply.usage else None),
            cost_usd=round(state["cost"], 6))

        messages.append(Message(role="assistant", content=reply.text,
                                tool_calls=list(reply.tool_calls)))

        # A truncated reply may carry half-formed tool calls: don't execute them.
        if reply.finish_reason == "length":
            return finish("truncated")
        if not reply.tool_calls:
            return finish("answered", reply.text or "")
        todo = list(reply.tool_calls)

Two public wrappers sit on _drive. run_agent is the entry point; resume_agent continues a paused run after a human decision — the mechanics Part 6 uses for approval:

python
async def run_agent(call_model, registry, messages, *,
                    budget: Budget | None = None,
                    model_kwargs: dict[str, Any] | None = None,
                    gate: Gate | None = None,
                    on_event: Callable[[dict[str, Any]], None] | None = None,
                    timeout_per_call: float = 120.0,
                    max_identical_calls: int = 3,
                    pending: list[ToolCall] | None = None) -> AgentResult:
    """Run the agent loop until the model answers or a stop condition fires.

    `messages` is mutated in place (the full trajectory stays inspectable).
    `pending` is for internal use by resume_agent.
    """
    budget = budget or Budget()
    state = {"t0": time.monotonic(), "steps": 0,
             "usage": {"input_tokens": 0, "output_tokens": 0},
             "cost": 0.0, "events": [], "consecutive_errors": 0}
    return await _drive(call_model, registry, messages, budget, state,
                        model_kwargs=model_kwargs, gate=gate,
                        on_event=on_event, timeout_per_call=timeout_per_call,
                        max_identical_calls=max_identical_calls,
                        pending=pending)


async def resume_agent(call_model, registry, paused: AgentResult, decision: dict,
                       *, budget: Budget | None = None,
                       model_kwargs: dict[str, Any] | None = None,
                       gate: Gate | None = None,
                       on_event: Callable[[dict[str, Any]], None] | None = None,
                       timeout_per_call: float = 120.0,
                       max_identical_calls: int = 3) -> AgentResult:
    """Continue a run that stopped with stop_reason="paused".

    `decision` is one of:
      {"action": "approve"}                      run the pending call as-is
      {"action": "edit", "arguments": {...}}     run it with edited arguments
      {"action": "reject", "reason": "..."}      feed a rejection back instead

    The caller owns persistence: snapshot the AgentResult (helpers below) before
    handing the pause payload to a human, then resume from the snapshot later.
    """
    if paused.stop_reason != "paused" or not paused.pending_calls:
        raise ValueError("resume_agent needs a result with stop_reason='paused'")
    messages = list(paused.messages)
    pending = list(paused.pending_calls)
    call = pending.pop(0)
    action = decision.get("action", "approve")
    if action == "approve":
        result_text = await registry.call(call)
    elif action == "edit":
        edited = ToolCall(id=call.id, name=call.name,
                          arguments=decision.get("arguments") or {})
        result_text = await registry.call(edited)
        result_text = json.dumps({"edited_by_user": True,
                                  "result": json.loads(result_text)
                                  if result_text.startswith(("{", "[")) else result_text})
    elif action == "reject":
        reason = decision.get("reason", "no reason given")
        result_text = json.dumps({
            "error": f"the user rejected {call.name!r}: {reason}. "
                     "Do not retry the same call; ask the user or choose "
                     "a different approach."})
    else:
        raise ValueError(f"unknown decision action {action!r}")
    messages.append(Message(role="tool", tool_call_id=call.id,
                            name=call.name, content=result_text))
    state = {"t0": time.monotonic(), "steps": paused.steps,
             "usage": {"input_tokens": paused.usage.input_tokens,
                       "output_tokens": paused.usage.output_tokens},
             "cost": paused.cost_usd, "events": list(paused.events),
             "consecutive_errors": 0, "pause_payload": None}
    return await _drive(call_model, registry, messages, budget or Budget(),
                        state, model_kwargs=model_kwargs, gate=gate,
                        on_event=on_event, timeout_per_call=timeout_per_call,
                        max_identical_calls=max_identical_calls,
                        pending=pending)

Persistence helpers make pause/resume survive a process restart — the same job LangGraph's checkpointer does (verified November 2026: interrupt() + Command resume, see Part 8):

python
def _tc_to_dict(c: ToolCall) -> dict[str, Any]:
    return {"id": c.id, "name": c.name, "arguments": c.arguments}


def _tc_from_dict(d: dict[str, Any]) -> ToolCall:
    return ToolCall(id=d["id"], name=d["name"], arguments=d.get("arguments") or {})


def _msg_to_dict(m: Message) -> dict[str, Any]:
    return {"role": m.role, "content": m.content,
            "tool_calls": [_tc_to_dict(c) for c in m.tool_calls] or None,
            "tool_call_id": m.tool_call_id, "name": m.name}


def _msg_from_dict(d: dict[str, Any]) -> Message:
    return Message(role=d["role"], content=d.get("content"),
                   tool_calls=[_tc_from_dict(c) for c in d.get("tool_calls") or []],
                   tool_call_id=d.get("tool_call_id"), name=d.get("name"))


def snapshot(result: AgentResult) -> dict[str, Any]:
    """JSON-safe snapshot of a run — store it, resume it after a human decision."""
    return {
        "answer": result.answer, "stop_reason": result.stop_reason,
        "messages": [_msg_to_dict(m) for m in result.messages],
        "steps": result.steps,
        "usage": {"input_tokens": result.usage.input_tokens,
                  "output_tokens": result.usage.output_tokens},
        "cost_usd": result.cost_usd, "events": result.events,
        "pending_calls": [_tc_to_dict(c) for c in result.pending_calls],
        "pause_payload": result.pause_payload,
    }


def restore(snap: dict[str, Any]) -> AgentResult:
    return AgentResult(
        answer=snap["answer"], stop_reason=snap["stop_reason"],
        messages=[_msg_from_dict(m) for m in snap["messages"]],
        steps=snap["steps"],
        usage=Usage(**snap["usage"]), cost_usd=snap["cost_usd"],
        events=list(snap.get("events") or []),
        pending_calls=[_tc_from_dict(c) for c in snap.get("pending_calls") or []],
        pause_payload=snap.get("pause_payload"))


def resume_from_snapshot(call_model, registry, snap: dict[str, Any],
                         decision: dict, **kwargs):
    """Convenience: restore a snapshot, then resume_agent on it."""
    return resume_agent(call_model, registry, restore(snap), decision, **kwargs)

(ScriptedModel records requests through the same _msg_to_dict helper, which is why the helpers are defined before it:)

python
class ScriptedModel:
    """A `call_model` test double: replays canned replies in order.

    Each entry in `replies` may be:
      - a ModelReply (returned as-is)
      - a dict with ModelReply's fields (tool_calls as dicts are coerced)
      - a callable(messages, tools, **kwargs) -> reply   (dynamic fake)
      - an Exception instance                            (raised)

    Every request is recorded in `.requests` so tests can assert on them.
    """

    def __init__(self, replies: list[Any]) -> None:
        self._replies = list(replies)
        self.requests: list[dict[str, Any]] = []

    async def __call__(self, messages, tools, **kwargs) -> ModelReply:
        self.requests.append({
            "messages": [_msg_to_dict(m) for m in messages],
            "tools": tools, "kwargs": kwargs})
        if not self._replies:
            raise AssertionError(
                "ScriptedModel ran out of replies — the loop asked the model "
                "for more than you scripted")
        reply = self._replies.pop(0)
        if isinstance(reply, BaseException):
            raise reply
        if callable(reply) and not isinstance(reply, ModelReply):
            reply = reply(messages, tools, **kwargs)
        return _coerce_reply(reply)


def _coerce_reply(reply: Any) -> ModelReply:
    if isinstance(reply, ModelReply):
        return reply
    if isinstance(reply, dict):
        data = dict(reply)
        tcs = [ToolCall(**t) if isinstance(t, dict) else t
               for t in data.pop("tool_calls", [])]
        usage = data.pop("usage", None)
        return ModelReply(text=data.pop("text", None), tool_calls=tcs,
                          finish_reason=data.pop("finish_reason", "stop"),
                          usage=Usage(**usage) if isinstance(usage, dict) else usage)
    raise TypeError(f"cannot use {type(reply).__name__} as a scripted reply")

1.4 The running example's tools#

support_tools.py gives the support assistant its five tools over in-memory fake data — a deliberately self-contained variant of the module's running example: 08A.6 designs the production versions of these tools (its orders_get/refunds_issue/docs_search registry with amount_cents, execute=false dry-runs and customer_email scoping), and 08A.2 wires its own minimal set into the production loop. The names and signatures differ on purpose — this lesson's job is the patterns, not re-litigating tool design — but the shape is the same, and the risk tags agree with 08A.6's taxonomy: lookup_order, search_docs and run_report are read; create_ticket is write; issue_refund is destructive. Part 6's approval policy keys off exactly these tags.

python
# support_tools.py — the complete file
from __future__ import annotations

import json
from datetime import date, timedelta
from typing import Any

ORDERS: dict[str, dict[str, Any]] = {
    "A-1001": {"order_id": "A-1001", "customer": "R. Iyer", "email": "riyer@example.com",
               "status": "delivered", "total": 84.50, "currency": "USD",
               "items": [{"sku": "KB-87", "qty": 1, "price": 79.00},
                         {"sku": "CB-10", "qty": 1, "price": 5.50}],
               "delivered_on": "2026-10-18"},
    "A-1002": {"order_id": "A-1002", "customer": "M. Okafor", "email": "mokafor@example.com",
               "status": "shipped", "total": 132.00, "currency": "USD",
               "items": [{"sku": "MS-15", "qty": 1, "price": 132.00}],
               "delivered_on": None},
    "A-1003": {"order_id": "A-1003", "customer": "S. Lindqvist", "email": "slindqvist@example.com",
               "status": "delivered", "total": 47.25, "currency": "USD",
               "items": [{"sku": "CB-10", "qty": 3, "price": 15.75}],
               "delivered_on": "2026-11-02"},
}

DOCS: list[dict[str, str]] = [
    {"title": "Refund policy", "text": "Refunds are issued for delivered orders "
     "within 30 days of delivery. Orders still in transit must be refused or "
     "returned first. Partial refunds are allowed at agent discretion up to "
     "the item price."},
    {"title": "Shipping times", "text": "Standard shipping takes 3-5 business "
     "days domestically and 7-14 internationally. Express shipping takes 1-2 "
     "business days domestically."},
    {"title": "Warranty claims", "text": "Hardware carries a 12-month warranty "
     "from delivery. File a ticket with the order ID and a photo of the fault; "
     "do not promise a replacement before the warranty team confirms."},
]

TICKETS: list[dict[str, Any]] = []
REFUNDS: list[dict[str, Any]] = []
NEXT_TICKET = 5000


def _next_ticket_id() -> str:
    global NEXT_TICKET
    NEXT_TICKET += 1
    return f"T-{NEXT_TICKET}"


def lookup_order(order_id: str) -> dict[str, Any]:
    """Look up an order by its ID (e.g. 'A-1001'). Returns status, items, totals."""
    order = ORDERS.get(order_id.strip().upper())
    if order is None:
        return {"error": f"no order found with id {order_id!r}; "
                         "check the format (letter, dash, four digits)"}
    return dict(order)


def search_docs(query: str) -> list[dict[str, str]]:
    """Search the internal policy docs. Returns the top matching passages."""
    terms = {t for t in query.lower().replace("?", " ").split() if len(t) > 3}
    scored = []
    for doc in DOCS:
        hay = (doc["title"] + " " + doc["text"]).lower()
        score = sum(hay.count(t) for t in terms)
        if score:
            scored.append((score, doc))
    scored.sort(key=lambda x: -x[0])
    return [{"title": d["title"], "text": d["text"][:300]} for _, d in scored[:2]]


def create_ticket(subject: str, body: str, order_id: str = "") -> dict[str, Any]:
    """Open a support ticket. Returns the new ticket ID."""
    ticket = {"ticket_id": _next_ticket_id(), "subject": subject,
              "body": body, "order_id": order_id or None, "status": "open"}
    TICKETS.append(ticket)
    return {"ticket_id": ticket["ticket_id"], "status": "open"}


def issue_refund(order_id: str, amount: float, reason: str) -> dict[str, Any]:
    """Issue a refund against a delivered order. DESTRUCTIVE tool — needs approval."""
    order = ORDERS.get(order_id.strip().upper())
    if order is None:
        return {"error": f"no order found with id {order_id!r}"}
    if order["status"] != "delivered":
        return {"error": f"order {order_id} is {order['status']}, not delivered; "
                         "refunds require a delivered order"}
    if not (0 < amount <= order["total"]):
        return {"error": f"amount must be between 0 and {order['total']}"}
    record = {"refund_id": f"R-{len(REFUNDS) + 1:04d}", "order_id": order["order_id"],
              "amount": amount, "reason": reason, "status": "issued"}
    REFUNDS.append(record)
    return dict(record)


def run_report(kind: str = "weekly") -> dict[str, Any]:
    """Run a canned ops report over the fake data."""
    if kind == "weekly":
        today = date(2026, 11, 5)
        week_ago = today - timedelta(days=7)
        recent = [o for o in ORDERS.values()
                  if o.get("delivered_on") and
                  week_ago.isoformat() <= o["delivered_on"] <= today.isoformat()]
        return {"report": "weekly", "orders_delivered": len(recent),
                "refunds_issued": len(REFUNDS),
                "open_tickets": sum(1 for t in TICKETS if t["status"] == "open")}
    return {"error": f"unknown report kind {kind!r}; try 'weekly'"}


ORDER_SCHEMA = {
    "type": "object",
    "properties": {
        "order_id": {"type": "string", "description": "Order ID like 'A-1001'"},
    },
    "required": ["order_id"],
}
QUERY_SCHEMA = {
    "type": "object",
    "properties": {
        "query": {"type": "string", "description": "What to search for"},
    },
    "required": ["query"],
}
TICKET_SCHEMA = {
    "type": "object",
    "properties": {
        "subject": {"type": "string"},
        "body": {"type": "string", "description": "Full description for the team"},
        "order_id": {"type": "string", "description": "Related order, if any"},
    },
    "required": ["subject", "body"],
}
REFUND_SCHEMA = {
    "type": "object",
    "properties": {
        "order_id": {"type": "string"},
        "amount": {"type": "number", "description": "Refund amount in USD"},
        "reason": {"type": "string"},
    },
    "required": ["order_id", "amount", "reason"],
}
REPORT_SCHEMA = {
    "type": "object",
    "properties": {"kind": {"type": "string", "enum": ["weekly"]}},
}


def build_registry(include_refund: bool = True):
    """The support assistant's registry. Kept here so every demo uses one tool set."""
    from agent_loop import Tool, ToolRegistry

    reg = ToolRegistry()
    reg.add(Tool("lookup_order", "Look up an order by ID: status, items, totals, delivery date.",
                 ORDER_SCHEMA, lookup_order, risk="read"))
    reg.add(Tool("search_docs", "Search internal policy docs (refunds, shipping, warranty).",
                 QUERY_SCHEMA, search_docs, risk="read"))
    reg.add(Tool("create_ticket", "Open a support ticket for the ops team.",
                 TICKET_SCHEMA, create_ticket, risk="write"))
    if include_refund:
        reg.add(Tool("issue_refund", "Issue a refund on a delivered order. Has real-world effect.",
                     REFUND_SCHEMA, issue_refund, risk="destructive"))
    reg.add(Tool("run_report", "Run a canned operations report.",
                 REPORT_SCHEMA, run_report, risk="read"))
    return reg


def state_dump() -> str:
    """Deterministic view of mutable fake state, for demos and tests."""
    return json.dumps({"tickets": TICKETS, "refunds": REFUNDS}, indent=2)
python
# demo_native_loop — the baseline every pattern in this lesson modifies.
# A fragment: it runs inside `async def main()` in demo.py (Part 11), where REG = build_registry().
# The labelled output below comes from the demo's print statements, not from this fragment.
model = ScriptedModel([
    ModelReply(text=None, finish_reason="tool_calls",
               tool_calls=[ToolCall(id="c0", name="lookup_order",
                                    arguments={"order_id": "A-1001"})],
               usage=Usage(800, 120)),
    ModelReply(text="Order A-1001 was delivered on 2026-10-18 for $84.50.",
               usage=Usage(800, 120)),
])
msgs = [Message("system", "You are a support agent. Use tools, then answer."),
        Message("user", "When was order A-1001 delivered?")]
res = await run_agent(model, REG, msgs, budget=Budget(max_steps=6))

Real values from the demo run (demo.py prints them as three separate show blocks; condensed here into one listing):

text
answer:      Order A-1001 was delivered on 2026-10-18 for $84.50.
stop_reason: answered
steps:       2
usage:       input 1600, output 240
trajectory:  system → user → assistant(lookup_order) → tool(lookup_order) → assistant

Two model calls, one tool call, a clean trajectory. Everything from here changes how many calls happen, who decides the next call, and what happens when things go wrong.

1.5 The pattern catalogue#

flowchart LR
    subgraph simple ["Increasing autonomy → increasing cost and risk"]
        A["Single call<br/>(no tools)"] --> B["Tool loop<br/>(ReAct native)"]
        B --> C["Routed specialist<br/>(routing agent)"]
        C --> D["Plan-and-execute<br/>(planner + executor + replanner)"]
        D --> E["Orchestrator-workers<br/>(dynamic delegation)"]
        E --> H["Parallel fan-out and<br/>agent-as-a-tool<br/>(08A.11)"]
        H --> F["Free agent +<br/>reflection / verification"]
    end
    B -. "control patterns wrap any of these" .-> G["approval · permissions ·<br/>budgets · loop detection ·<br/>state machine"]
Pattern Model decides You decide Extra calls per task Best for
ReAct (native) next action each step tools, budget, stop rules 1–2× steps open-ended tool tasks, the default
Plan-and-execute plan once, replan on failure plan schema, step budgets +1 plan, +1 replan/step multi-step tasks with known shape
Reflection / self-critique (deeper: 08A.11, Part 2) draft + critique rounds critic prompt, max rounds ×(1+rounds) quality-sensitive outputs, bounded
Verification loop draft; environment judges the verifier (your code) +1 retry claims checkable against the world
Routing which specialist route table +1 classify many distinct task types
Orchestrator-workers when/how to delegate worker specs, delegation cap +1 per worker parallelisable or context-heavy subtasks
Parallel fan-out and aggregate (08A.11, Part 3) how each branch works (each is a small loop) branch count, per-branch timeouts, quorum, shared token pool, aggregator +1 loop per branch (cost is the sum, latency is the slowest branch) independent subtasks where breadth or latency matters
Agent-as-a-tool (08A.11, Part 4) when to call the specialist, and with what task child budget slice, depth limit, structured result, tool and permission set +1 loop per call a self-contained specialist skill the parent should see as one function
Todo/scratchpad its own task list the tools ~0 (same loop) long tasks needing working memory
State machine nothing (you script flow) every transition 0–n flows you can enumerate

The rest of the lesson implements each row, except the two new ones. Parallel fan-out and agent-as-a-tool are catalogued here so you can recognise them, and 08A.11 (the companion of this lesson) builds them with timeouts, quorum, budget slices and depth limits. 08A.11, Part 2 does the same for score-aware reflection. Orchestrator-workers (5.3 below) is the first, simple form of agent-as-a-tool. Parts 2–5 are the reasoning and delegation patterns; Part 6 is the control layer that wraps any of them; Parts 7–9 are prompting, explicit control flow, and observability; Part 10 is where you choose.


Part 2: ReAct — reason and act#

2.1 Where ReAct came from#

ReAct (Reason + Act) is the 2022 pattern from Yao et al., "ReAct: Synergizing Reasoning and Acting in Language Models" (arXiv:2210.03629, ICLR 2023). The idea: instead of asking the model to produce a final answer directly (which invites hallucination on multi-step tasks) or to emit bare actions (which gives no insight into why), interleave reasoning traces ("Thought: ...") with actions ("Action: ...") and observations (the environment's reply). Reasoning helps the model plan and recover from errors; actions ground it in real information. The paper showed ReAct beating reasoning-only and acting-only baselines on question answering (HotpotQA, Fever) and interactive decision-making benchmarks (ALFWorld, WebShop) — the latter by absolute success-rate margins of roughly 34 and 10 points with only one or two in-context examples.

2.2 The original text format — and why you won't write it#

The 2022 implementation was pure text. The model was prompted (few-shot) to emit:

text
Thought: I need to find the order status for A-1001.
Action: lookup_order
Action Input: {"order_id": "A-1001"}

Observation: {"order_id": "A-1001", "status": "delivered", ...}

Thought: It was delivered on 2026-10-18, within the 30-day window.
Final Answer: Yes, A-1001 is still refundable.

Your code parsed the Action:/Action Input: blocks, ran the tool, and appended the observation as the next prompt. It worked, but it has three problems that native tool calling fixed: the format is fragile (models drift, add prose, or emit invalid JSON inside the text), reasoning and action are entangled in one string you must re-parse every turn, and nothing validates the action name or arguments before execution.

For completeness, here is the text-format loop — patterns.py's first function. It is the honest way to see what ReAct was. patterns.py opens with its imports and the shared call_for_json helper (shown in §3.2, where the planner first needs it):

python
# patterns.py — the complete file's header
from __future__ import annotations

import asyncio
import json
import re
import time
from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable

from agent_loop import (AgentResult, Budget, Gate, GateVerdict, Message,
                        ModelReply, Tool, ToolCall, ToolRegistry, Usage,
                        run_agent)

First the parser react_text_loop depends on (parse_react_step uses JSONDecoder.raw_decode to find the Action Input: object even when it spans lines, and takes the last Action: block — earlier ones are history the model echoed back):

python
# patterns.py — text-format ReAct (the 2022 original)
_ACTION_INPUT = re.compile(r"Action Input:\s*")
_FINAL = re.compile(r"Final Answer:\s*(.*)", re.S)
_THOUGHT = re.compile(r"Thought:\s*(.*?)(?=\n(?:Action|Final Answer):|\Z)", re.S)


@dataclass
class ReactResult:
    answer: str | None
    stop_reason: str
    trajectory: list[dict[str, Any]] = field(default_factory=list)


def parse_react_step(text: str) -> tuple[str | None, str | None,
                                      dict | None, str | None]:
    """Parse one ReAct reply -> (thought, action, action_input, final_answer)."""
    thoughts = _THOUGHT.findall(text)   # like the action: the last thought wins
    thought = thoughts[-1].strip() if thoughts else None
    final_m = _FINAL.search(text)
    if final_m:
        return thought, None, None, final_m.group(1).strip()
    # the LAST "Action:" block wins — earlier ones are history the model echoed
    action = args = None
    for m in re.finditer(r"Action:\s*([^\n]+)", text):
        name = m.group(1).strip()
        tail = text[m.end():]
        inp_m = _ACTION_INPUT.search(tail)
        if not inp_m:
            continue
        start = m.end() + inp_m.end()
        try:
            obj, _ = json.JSONDecoder().raw_decode(text, start)
        except json.JSONDecodeError:
            continue
        if isinstance(obj, dict):
            action, args = name, obj
    return thought, action, args, None


REACT_SYSTEM = """You are a methodical agent. To solve the task, alternate
reasoning and acting. Reply in EXACTLY this format, one step per reply:

Thought: <what you are reasoning about right now>
Action: <tool name>
Action Input: <a JSON object of arguments>

When you have enough information, reply instead:

Thought: <your final reasoning>
Final Answer: <the answer>

Rules: never invent tool results — always wait for the Observation. Use one
action per reply. If a tool returns an error, read it and adjust."""


async def react_text_loop(call_model, registry, goal, *, max_steps: int = 8,
                          model_kwargs=None, gate=None,
                          on_event=None) -> ReactResult:
    """The original ReAct loop: reasoning and acting interleaved *in text*.

    No tool schemas are sent — the model writes "Action: name / Action Input:
    {json}" as prose and we parse it. This is the 2022 format; Part 2.3 shows
    why native tool calling replaced it. `gate` (Part 6) is honoured before
    each tool call, same as in run_agent.
    """
    messages = [Message("system", REACT_SYSTEM), Message("user", goal)]
    trajectory: list[dict[str, Any]] = []
    for step in range(max_steps):
        reply = await call_model(messages, [], **(model_kwargs or {}))
        text = reply.text or ""
        thought, action, args, final = parse_react_step(text)
        trajectory.append({"step": step, "thought": thought,
                           "action": action, "args": args, "final": final})
        if on_event:
            on_event({"type": "react_step", "step": step, "thought": thought,
                      "action": action})
        if final is not None:
            return ReactResult(final, "answered", trajectory)
        if action is None:
            messages += [Message("assistant", text),
                         Message("user", "Format error: use Thought/Action/"
                                 "Action Input or Final Answer.")]
            continue
        call = ToolCall(id=f"react_{step}", name=action, arguments=args or {})
        verdict = await gate(call, registry.get(call.name)) \
            if gate else GateVerdict()
        if verdict.action == "pause":
            return ReactResult(None, "paused", trajectory)
        if verdict.action == "replace":
            result_text = verdict.result or ""
        else:
            result_text = await registry.call(call)
        messages += [Message("assistant", text),
                     Message("user", f"Observation: {result_text}")]
    return ReactResult(None, "max_steps", trajectory)

Tested output with a ScriptedModel (two scripted replies: an action step, then a final answer):

text
step 0: thought="I need the delivery date of A-1001.",
        action=lookup_order, args={"order_id": "A-1001"}
step 1: thought="The order was delivered 2026-10-18.",
        final="Order A-1001 was delivered on 2026-10-18."

2.3 ReAct with native tool calling — what you actually ship#

Modern providers give the model native tool calling: it emits structured tool_calls (name + JSON arguments, validated against your schema where strict mode applies — 03.4, 03.5) instead of writing Action: as prose. On current reasoning models you also get interleaved thinking: the model reasons between tool calls inside a single response stream (02.8, Part 8, 03.5, Part 12). That is ReAct — reason, act, observe, reason — just with the reasoning in a dedicated channel and the actions in a validated structure rather than parsed text.

So "implementing ReAct" today means: run the agent loop with tools, on a reasoning-capable model, and let interleaved thinking do the reasoning. The run_agent call from Part 1 is the implementation — there is no separate ReAct function needed:

ReAct ingredient (2022) Native equivalent (2026)
Thought: text reasoning/thinking channel (or the assistant's content on non-reasoning models)
Action: + Action Input: text tool_calls[] with schema-checked arguments
Observation: appended to prompt role: "tool" result message
Few-shot prompt teaches the format tool definitions + system prompt teach when to call
Hand-rolled parser provider SDK / ToolRegistry.call

2.4 The scratchpad and the "think" tool#

Two related ideas worth separating:

  • Scratchpad / notes: a place the agent writes to that survives across steps — a file, a todo list, or simply its own growing message history. Part 5.4 covers NotesFile and TodoList.
  • The "think" tool: a deliberate no-op tool that lets the model externalise reasoning as a tool call rather than hidden thinking. Some agent frameworks expose this so the reasoning lands in your trajectory log where you can inspect it. make_think_tool in 5.4 is the whole implementation — a Tool whose function appends the model's thought argument to a scratchpad list and returns "noted" — grouped there with the other working-memory tools (TodoList, NotesFile) it belongs to.

2.5 ReAct failure modes#

The pattern fails in recognisable ways, all visible in AgentResult.stop_reason and the events log: loop_detected (same call repeated), stalled (same result 3×), circuit_breaker (3 consecutive tool errors), max_steps (never converged), truncated (finish_reason="length" mid-tool-call). Part 6 formalises the detectors; the failure gallery at the end collects them per pattern.


Part 3: Plan-and-execute#

3.1 The idea#

ReAct decides each next action locally — it can wander, forget the goal, or burn steps rediscovering the plan. Plan-and-execute separates the two jobs: a planner produces the whole step list up front; an executor works one step at a time; a replanner checks after each step whether the plan still holds and revises it when reality disagrees. The lineage is direct: Plan-and-Solve prompting (Wang et al., arXiv:2305.04091, ACL 2023) showed explicit planning beats "think step by step" on multi-step reasoning; BabyAGI (github.com/yoheinakajima/babyagi; its README says the March 2023 original is now archived in a separate babyagi_archive repo, as of November 2026) turned the idea into a task-creation/execution/prioritisation agent loop; LangGraph's plan-and-execute tutorial made planner→agent→replan a standard architecture (LangChain blog, Feb 2024).

flowchart TD
    G([goal]) --> P["planner:<br/>goal → steps[]"]
    P --> E["executor:<br/>bounded agent loop<br/>for step i"]
    E --> R{"replanner:<br/>continue / revise / respond?"}
    R -- "continue" --> E
    R -- "revise" --> P2["replace remaining steps"] --> E
    R -- "respond" --> A([final answer])
    E -- "step failed" --> R

3.2 The plan is state, not context#

The crucial engineering choice: the plan lives in a list[PlanStep] you own — inspectable, persistable, resumable — not buried in the message history where context trimming can silently drop it (04.7). Each step records its status and result, so the replanner sees structured progress rather than re-reading a transcript.

python
@dataclass
class PlanStep:
    id: str
    description: str
    needed_tools: list[str] = field(default_factory=list)
    status: str = "pending"  # pending | done | failed | skipped
    result: str | None = None


@dataclass
class PlanExecuteResult:
    answer: str | None
    stop_reason: str
    steps: list[PlanStep]
    replans: int
    usage: Usage
    cost_usd: float
    events: list[dict[str, Any]]

The planner and replanner are single call_for_json calls — cheap, structured-output prompts (JSON mode per 03.4); the executor is a bounded run_agent per step with its own small budget and a restricted tool subset (registry.subset(step.needed_tools)). call_for_json is patterns.py's shared JSON-extraction helper — the planner, replanner and router all use it:

python
# patterns.py — shared helpers (top of the file)
async def call_for_json(call_model, messages, *, tools=None,
                        model_kwargs=None, timeout=120.0) -> tuple[dict, Usage]:
    """One model call that must return a JSON object; returns (obj, usage).

    Finds the first {...} in the reply with JSONDecoder.raw_decode, so prose
    before or after the object doesn't matter. Raises ValueError on failure —
    callers decide whether to repair, retry or escalate.
    """
    reply = await asyncio.wait_for(
        call_model(list(messages), tools or [], **(model_kwargs or {})),
        timeout=timeout)
    text = reply.text or ""
    dec = json.JSONDecoder()
    for i, ch in enumerate(text):
        if ch != "{":
            continue
        try:
            obj, _ = dec.raw_decode(text, i)
        except json.JSONDecodeError:
            continue
        if isinstance(obj, dict):
            return obj, reply.usage or Usage()
    raise ValueError(f"model did not return a JSON object: {text[:200]!r}")


def _last_user_text(messages) -> str:
    for m in reversed(messages):
        if m.role == "user" and m.content:
            return m.content[:2000]
    return "(none)"

The planner-side helpers turn the planner's JSON into PlanSteps (_plan_from_obj caps at 8 steps and rejects malformed entries with ValueError), attach the tool menu to the prompt (_tools_brief), and make the plan/replan calls (_plan_call makes one repair attempt on unparseable JSON; _replan_call summarises done/pending steps into a compact prompt):

python
# patterns.py — plan-and-execute helpers
def _plan_from_obj(obj: dict) -> list[PlanStep]:
    steps = obj.get("steps")
    if not isinstance(steps, list) or not steps:
        raise ValueError("plan has no 'steps' list")
    out = []
    for i, s in enumerate(steps[:8], 1):
        if not isinstance(s, dict) or not s.get("description"):
            raise ValueError(f"step {i} lacks a description")
        out.append(PlanStep(
            id=str(s.get("id", i)), description=str(s["description"]),
            needed_tools=[str(t) for t in s.get("needed_tools") or []]))
    return out


def _tools_brief(registry: ToolRegistry) -> str:
    return "\n".join(f"- {t.name}: {t.description}"
                     for t in (registry.get(n) for n in registry.names())
                     if t is not None)


async def _plan_call(call_model, system: str, goal: str, registry,
                     model_kwargs, usage_acc, model_calls) -> tuple[list[PlanStep], Usage]:
    tools_note = _tools_brief(registry)
    messages = [Message("system", system + "\n\nAvailable tools:\n" + tools_note),
                Message("user", goal)]
    try:
        obj, usage = await call_for_json(call_model, messages,
                                         model_kwargs=model_kwargs)
        model_calls[0] += 1
    except ValueError:
        # one repair attempt: feed the failure back
        messages += [Message("assistant", "(unparseable)"),
                     Message("user", "Reply with ONLY the JSON object, no prose.")]
        obj, usage = await call_for_json(call_model, messages,
                                         model_kwargs=model_kwargs)
        model_calls[0] += 1
    usage_acc[0] = usage_acc[0] + usage
    return _plan_from_obj(obj), usage


async def _replan_call(call_model, goal, steps, latest, model_kwargs,
                       usage_acc, model_calls) -> tuple[dict, Usage]:
    done = [f"{s.id}. {s.description} -> {s.result}" for s in steps if s.status == "done"]
    pending = [f"{s.id}. {s.description}" for s in steps if s.status == "pending"]
    user = (f"Goal: {goal}\n\nCompleted:\n" + ("\n".join(done) or "(none)") +
            "\n\nRemaining:\n" + ("\n".join(pending) or "(none)") +
            f"\n\nLatest step result:\n{latest}")
    messages = [Message("system", REPLANNER_SYSTEM), Message("user", user)]
    try:
        obj, usage = await call_for_json(call_model, messages,
                                         model_kwargs=model_kwargs)
        model_calls[0] += 1
    except ValueError:
        obj = {"action": "continue"}
        usage = Usage()
    usage_acc[0] = usage_acc[0] + usage
    return obj, usage

3.3 Full implementation#

python
PLANNER_SYSTEM = """You are the planner for a support-operations agent. Given a
goal, produce a step-by-step plan. Reply with ONLY a JSON object:

{"steps": [{"id": "1", "description": "...", "needed_tools": ["tool_name"]}]}

Rules: 3-8 steps, ordered, each independently executable by a worker agent
that sees only that step plus a short summary of prior results. Use only the
tools listed below. End with a verification step when the goal produces a
report, refund or ticket."""

EXECUTOR_SYSTEM = """You are executing ONE step of a larger plan for a support
agent. Complete only this step using the tools. Report what you did and the
concrete result: IDs, amounts, statuses. Do not do the other steps and do not
answer the overall goal — the planner handles that."""

REPLANNER_SYSTEM = """You are the replanner. You get the goal, the plan's status
and the latest step result. Reply with ONLY a JSON object:

{"action": "continue"}                      — keep executing remaining steps
{"action": "revise", "steps": [...same shape as plan...]}  — replace remaining steps
{"action": "respond", "answer": "..."}      — the goal is met; give the final answer

Revise only when a step failed or the result changed what remains to be done."""


async def plan_and_execute(call_model, registry, goal, *,
                           budget: Budget | None = None,
                           model_kwargs=None, executor_kwargs=None,
                           step_budget: Budget | None = None,
                           max_replans: int = 4, gate=None,
                           on_event=None) -> PlanExecuteResult:
    """Plan once, execute step by step, replan when reality disagrees.

    Two budget layers, deliberately: `budget` bounds the WHOLE run — the
    plan call, every replan, all executor steps and the final-answer call —
    while `step_budget` bounds each executor's run_agent individually.
    `over_budget()` is checked before every plan-boundary and executor model
    call; exhausting `budget` stops the run with
    stop_reason="budget_exhausted" and skips the final-answer call (an
    exhausted budget stays exhausted). Cost is estimated from the run's
    accumulated Usage against `budget`'s own price fields — set
    input_usd_per_1m/output_usd_per_1m to enforce max_cost_usd (the 0.0
    defaults disable it, same as run_agent); the default step_budget
    inherits those prices, so `PlanExecuteResult.cost_usd` covers the planner, replanner and
    final-answer calls as well as the executors.

    `gate` (Part 6) is passed through to every executor run_agent, so approval
    and permission policies reach delegated step work.
    """
    budget = budget or Budget(max_steps=40, max_seconds=900)
    step_budget = step_budget or Budget(
        max_steps=6, max_seconds=180, max_cost_usd=0.25,
        input_usd_per_1m=budget.input_usd_per_1m,
        output_usd_per_1m=budget.output_usd_per_1m)
    usage_acc = [Usage()]      # everything: plan + replans + final + executor runs
    exec_usage = Usage()       # the executor runs alone (already priced by step_budget)
    cost = [0.0]
    events: list[dict[str, Any]] = []
    replans = 0
    model_calls = [0]          # plan/replan/final call_for_json + executor steps
    t0 = time.monotonic()

    def ev(type_, **kw):
        events.append({"type": type_, **kw})
        if on_event:
            on_event(events[-1])

    def over_budget() -> bool:
        """The outer budget, checked before each model call the pattern makes."""
        est_cost = (usage_acc[0].input_tokens * budget.input_usd_per_1m
                    + usage_acc[0].output_tokens * budget.output_usd_per_1m
                    ) / 1_000_000
        return (model_calls[0] >= budget.max_steps
                or time.monotonic() - t0 > budget.max_seconds
                or usage_acc[0].input_tokens >= budget.max_input_tokens
                or usage_acc[0].output_tokens >= budget.max_output_tokens
                or est_cost >= budget.max_cost_usd)

    # 1. PLAN (with one repair attempt on unparseable JSON)
    steps, _ = await _plan_call(call_model, PLANNER_SYSTEM, goal, registry,
                                model_kwargs, usage_acc, model_calls)
    ev("plan_created", steps=[{"id": s.id, "description": s.description}
                              for s in steps])

    # 2. EXECUTE + REPLAN
    answer, stop = None, "plan_exhausted"
    idx = 0
    while idx < len(steps):
        step = steps[idx]
        if step.status != "pending":
            idx += 1
            continue
        if over_budget():
            stop = "budget_exhausted"
            ev("budget_exhausted", step=step.id)
            break
        ev("step_start", id=step.id, description=step.description)
        prior = "\n".join(f"- {s.description}: {s.result}"
                          for s in steps[:idx] if s.result)
        exec_user = (f"Overall goal: {goal}\n\nYour step: {step.description}\n\n"
                     f"Relevant tools for this step: "
                     f"{', '.join(step.needed_tools) or 'any'}\n\n"
                     f"Prior results:\n{prior or '(none)'}")
        res = await run_agent(
            call_model,
            registry.subset(step.needed_tools) if step.needed_tools else registry,
            [Message("system", EXECUTOR_SYSTEM), Message("user", exec_user)],
            budget=step_budget, model_kwargs=executor_kwargs, gate=gate,
            on_event=lambda e, _ev=ev, _sid=step.id: _ev(
                "executor", step_id=_sid, event=e))
        usage_acc[0] = usage_acc[0] + res.usage
        exec_usage = exec_usage + res.usage
        cost[0] += res.cost_usd
        model_calls[0] += res.steps
        step.result = (res.answer or f"[step ended: {res.stop_reason}]")[:800]
        step.status = "done" if res.stop_reason == "answered" else "failed"
        ev("step_end", id=step.id, status=step.status,
           result=step.result[:200])

        if over_budget():
            # don't spend a replan call on a run that is already over
            stop = "budget_exhausted"
            ev("budget_exhausted", step=step.id)
            break

        # 3. REPLAN after every step — one cheap call at the plan boundary
        if replans < max_replans:
            decision, _ = await _replan_call(
                call_model, goal, steps, step.result, model_kwargs,
                usage_acc, model_calls)
            replans += 1
            action = decision.get("action")
            if action == "respond":
                answer, stop = str(decision.get("answer", "")), "answered"
                break
            if action == "revise" and decision.get("steps"):
                try:
                    new_steps = _plan_from_obj({"steps": decision["steps"]})
                    # "revise" REPLACES the remaining steps: old pending
                    # steps are marked skipped — kept for the audit trail,
                    # invisible to the replanner's pending list — and the new
                    # plan takes their place. Nothing obsolete still runs.
                    for s in steps[idx + 1:]:
                        if s.status == "pending":
                            s.status = "skipped"
                    steps = steps[:idx + 1] + new_steps + steps[idx + 1:]
                    ev("plan_revised", steps=len(new_steps))
                except ValueError:
                    pass  # keep the old plan; the next step still runs
        idx += 1

    # if the loop ended without a respond, ask once for the final answer —
    # unless the budget is already spent
    if answer is None and stop == "plan_exhausted":
        if over_budget():
            stop = "budget_exhausted"
            ev("budget_exhausted", detail="before final answer")
        else:
            summary = "\n".join(f"- {s.description}: {s.result}"
                                for s in steps if s.status != "skipped")
            try:
                obj, usage = await call_for_json(
                    call_model,
                    [Message("system", "You are composing the final answer to a "
                                       "support task from the results of its "
                                       "completed steps. Reply with ONLY a JSON "
                                       'object: {"answer": "..."}'),
                     Message("user", f"Goal: {goal}\n\nAll step results:\n{summary}\n\n"
                                      "Give the final answer to the goal now.")],
                    model_kwargs=model_kwargs)
                model_calls[0] += 1
                answer = str(obj.get("answer") or obj.get("result") or obj)
                usage_acc[0] = usage_acc[0] + usage
                stop = "answered"
            except ValueError:
                answer, stop = None, "no_answer"

    # cost = executor runs (priced by step_budget) + the plan/replan/final calls
    # (everything else in usage_acc), priced by the outer budget
    overhead_in = usage_acc[0].input_tokens - exec_usage.input_tokens
    overhead_out = usage_acc[0].output_tokens - exec_usage.output_tokens
    total_cost = cost[0] + (overhead_in * budget.input_usd_per_1m
                            + overhead_out * budget.output_usd_per_1m) / 1_000_000
    return PlanExecuteResult(answer=answer, stop_reason=stop, steps=steps,
                             replans=replans, usage=usage_acc[0],
                             cost_usd=round(total_cost, 6), events=events)

Real output on the support task "A customer wants a refund on A-1002 which hasn't arrived; check the order and refund policy, then advise" (ScriptedModel — demo.py's demo_plan_execute):

text
plan_created:  steps 1 "Look up order A-1002 status" (done),
               step 2 "Check refund policy for in-transit orders" (pending)
step 1 → done: "Order A-1002 status: shipped, not yet delivered."
replan → respond after step 1 (step 2 never ran — the goal was already answered)
answer: "A-1002 is still in transit; per policy it must be refused or
         returned before any refund."
replans: 1, usage: 1300 in / 210 out

Note what the replanner bought: the executor for step 2 (search_docs on refund policy) never ran, because after step 1's result the replanner judged the goal already answerable — respond short-circuits the remaining plan. That early exit is the pattern's real saving grace: you pay for the plan and the steps actually needed, not the whole list.

3.4 Cost/benefit vs ReAct — and when each wins#

ReAct (native loop) Plan-and-execute
Model calls 1 per step + 1 final 1 plan + 1 executor-loop per step + 1 replan per step
Context per call whole growing transcript executor sees goal + one step + result summaries
Failure mode wanders, forgets goal, loops stale plan, replanner thrash, plan never revised
Best when steps unpredictable, environment guides steps enumerable up front, want inspectable progress
Latency lower for short tasks higher (serial plan boundaries)

Plan-and-execute typically costs more total tokens than a tight ReAct loop on the same task — the LangChain team's own framing is that it trades calls for structure (planning-agents post). It earns that cost when the task has a clear multi-step shape (onboard a customer, process a refund end-to-end, run a monthly report) or when you need the plan as an auditable artifact. For a two- or three-tool task it is overkill — the decision table in Part 10 makes this concrete.

A subtle benefit: the executor can run a cheaper model (executor_kwargs={"model": "..."}) while the planner/replanner use the strong one — a cost split ReAct can't express because every step is the same call.


Part 4: Reflection, verification and self-critique#

This Part is the short introduction to checking an agent's work. It gives you the core idea and the smallest working versions, because the later Parts and the consolidated demo use them. There are two ways to check, and they are different tools. Reflection asks a critic (a second model call) to judge a draft and asks the agent to revise it. Verification checks the result against the world with code you wrote. Both are bounded: a fixed number of rounds, so a check that cannot converge still stops.

The deeper treatment lives in the companion lesson, 08A.11. Read it next for reflection as a gate on the final answer (Part 2.2), score-aware reflection that returns the best draft (2.3), and how to measure whether reflection helped (2.5). The same lesson builds the two parallel patterns that appear in the catalogue: parallel fan-out and agent-as-a-tool. Verification (4.2) is only covered here.

4.1 Reflection / self-critique / Reflexion#

Reflexion (Shinn et al., arXiv:2303.11366, NeurIPS 2023) showed an agent improves across retries when it verbally reflects on failure feedback and stores the reflection — "verbal reinforcement learning" without weight updates. The production-shaped version is a bounded critique loop: generate a draft, have a critic check it, feed actionable feedback back, repeat a capped number of rounds. Its direct ancestor is Self-Refine (Madaan et al., arXiv:2303.17651, NeurIPS 2023) — the same generate→feedback→refine loop with a single model playing all three roles; Reflexion adds the episodic memory buffer and environment feedback on top. Two things separate the pattern from naive "ask again":

  1. The critic is a separate call with a different prompt (and optionally a different/cheaper model), judging against explicit criteria — not the generator grading its own homework.
  2. Rounds are bounded (max_rounds), because reflection that can't converge just burns tokens and can make answers worse (the failure gallery covers this).
python
CRITIC_SYSTEM = """You are a strict reviewer for a support agent's work. Given
the task, the draft answer and any tool evidence gathered, check: factual
correctness against the tool evidence provided (when present), completeness
vs the task, and policy/safety issues. Reply with ONLY a JSON object:

{"verdict": "pass" | "revise",
 "issues": ["..."],
 "feedback": "one paragraph of actionable critique the agent can act on"}"""


@dataclass
class ReviseResult:
    answer: str | None
    stop_reason: str
    rounds: int
    critiques: list[dict[str, Any]]
    usage: Usage
    cost_usd: float
python
async def critique_and_revise(call_model, task_messages, *,
                              registry: ToolRegistry | None = None,
                              budget: Budget | None = None,
                              max_rounds: int = 2,
                              model_kwargs=None, critic_kwargs=None,
                              produce=None, gate=None,
                              on_event=None) -> ReviseResult:
    """Generate, critique, revise — bounded. The Reflexion pattern, in-context.

    `produce` defaults to run_agent over task_messages; pass your own producer
    for single-shot answers. Critiques accumulate in `reflections` — the
    'episodic memory buffer' of the Reflexion paper — and are fed back each
    round. Each revision round continues from the draft run's full trajectory
    (res.messages), so the reviser can see the tool evidence it gathered; a
    compact digest of those results also goes to the critic. Bounded by
    max_rounds: reflection that can't converge must stop.
    """
    budget = budget or Budget(max_steps=10)
    registry = registry or ToolRegistry()
    reflections: list[str] = []
    critiques: list[dict[str, Any]] = []
    usage = Usage()
    cost = 0.0
    messages = list(task_messages)
    task_text = _last_user_text(messages)   # the original ask, not a critique
    answer = None

    for round_ in range(max_rounds + 1):
        if produce is not None:
            res = await produce(messages)
            draft, u, c = res.answer, res.usage, res.cost_usd
        else:
            res = await run_agent(call_model, registry, list(messages),
                                  budget=budget, model_kwargs=model_kwargs,
                                  gate=gate)
            draft, u, c = res.answer, res.usage, res.cost_usd
        usage = usage + u
        cost += c
        answer = draft
        if round_ == max_rounds or not draft:
            break
        # critique — the critic sees the task, the draft and a digest of the
        # tool evidence the draft run gathered (res.messages ends with the
        # assistant's draft, so the critique continues that trajectory)
        evidence = _tool_evidence(getattr(res, "messages", None) or [])
        critique_user = (f"Task:\n{task_text}\n\n"
                         f"Draft answer:\n{draft}\n\n"
                         + (f"Tool evidence gathered:\n{evidence}\n\n"
                            if evidence else "")
                         + (f"Prior critiques:\n" + "\n".join(reflections) + "\n\n"
                            if reflections else ""))
        try:
            verdict, u2 = await call_for_json(
                call_model,
                [Message("system", CRITIC_SYSTEM), Message("user", critique_user)],
                model_kwargs=critic_kwargs)
        except ValueError:
            break  # unparseable critique: keep the draft, don't loop forever
        usage = usage + u2
        critiques.append(verdict)
        if verdict.get("verdict") != "revise":
            break
        feedback = str(verdict.get("feedback", ""))
        reflections.append(feedback)
        traj = getattr(res, "messages", None)
        messages = (list(traj) if traj else messages + [Message("assistant", draft)])
        messages = messages + [
            Message("user", f"A reviewer critiqued your answer: {feedback}\n"
                            "Revise the answer. Keep what was right; fix the issues.")]
        if on_event:
            on_event({"type": "critique", "round": round_,
                      "verdict": verdict.get("verdict"),
                      "issues": verdict.get("issues")})
    return ReviseResult(answer=answer, stop_reason="answered" if answer else "failed",
                        rounds=len(critiques), critiques=critiques,
                        usage=usage, cost_usd=cost)


def _tool_evidence(messages, max_chars: int = 4000) -> str:
    """Compact digest of tool results — evidence for the critic, not the
    whole transcript. One line per tool message, each truncated."""
    parts = [f"- {m.name}: {(m.content or '')[:300]}"
             for m in messages if m.role == "tool" and m.content]
    return "\n".join(parts)[:max_chars]

reflections accumulating across rounds is the Reflexion paper's "episodic memory buffer" in miniature — 08B.2 owns real memory; here it is just a list fed back into the prompt. Real output (ScriptedModel — demo.py's demo_reflect; note it takes two revise rounds and exits on max_rounds, not on a pass):

text
rounds: 2
critique 1: {"verdict": "revise", "issues": ["no order ID cited"],
             "feedback": "Cite the order ID and delivery date explicitly."}
critique 2: {"verdict": "revise", ...same...}   # ScriptedModel replays it
final answer: "Order A-1001 (delivered 2026-10-18) qualifies for a refund
               under the 30-day policy."

A scripted critic can't converge — every round gets the same revise verdict — which is exactly why max_rounds is a hard bound, not a suggestion.

4.2 Verification loops — check the world, not the model#

Reflection judges the answer text; verification checks the result against the environment: recompute the total, run the tests, validate the schema, diff the file, re-query the API. The verifier is your code, not a model — that's what makes it trustworthy where a critic isn't. verify_and_retry runs the agent, calls verifier(res) -> problem | None, and feeds a failure back for one bounded retry:

python
async def verify_and_retry(call_model, registry, task_messages, verifier, *,
                           budget: Budget | None = None,
                           model_kwargs=None, max_attempts: int = 2,
                           gate=None, on_event=None) -> tuple[AgentResult, str | None]:
    """Run the agent, then check the result against the *environment*.

    `verifier(res) -> str | None` returns None if the result is acceptable, or
    a problem description to feed back. `max_attempts` is clamped to >= 1 —
    0 would leave `res` unbound.
    """
    budget = budget or Budget()
    max_attempts = max(1, max_attempts)
    messages = list(task_messages)
    last_problem = None
    for attempt in range(1, max_attempts + 1):
        res = await run_agent(call_model, registry, messages, budget=budget,
                              model_kwargs=model_kwargs, gate=gate,
                              on_event=on_event)
        problem = verifier(res)
        if problem is None:
            return res, None
        last_problem = problem
        if on_event:
            on_event({"type": "verification_failed", "attempt": attempt,
                      "problem": problem[:300]})
        messages = res.messages + [
            Message("user", f"Verification failed: {problem}\n"
                            "Fix the problem and produce a corrected answer. "
                            "Do not just restate the same claims.")]
    return res, last_problem

A worked verifier for the support agent recomputes the weekly report from the fake DB rather than trusting the model's summary — the same "test-based feedback" Reflexion uses for code, applied to a business claim:

python
def verifier(res):
    from support_tools import ORDERS
    from datetime import date, timedelta
    today = date(2026, 11, 5); week_ago = today - timedelta(days=7)
    real = sum(1 for o in ORDERS.values() if o.get("delivered_on")
               and week_ago.isoformat() <= o["delivered_on"] <= today.isoformat())
    if real != 1 or "1 delivery" not in (res.answer or ""):
        return f"report mismatch: DB shows {real} deliveries this week"
    return None

Demo trace: attempt 1 the model claims "3 deliveries" → verifier recomputes real=1 → feeds back "report mismatch: DB shows 1 deliveries this week" → attempt 2 claims "1 delivery" → problem=None. The agent didn't get luckier — it got checked.

4.3 When reflection helps — and when it hurts#

Reflection helps when the output has checkable quality (drafts, reports, code with tests), the first draft has failure modes a critic can name, rounds are bounded to 1–3 and a real verifier backs the critic. It hurts or is wasted on subjective taste with no criteria, when the critic shares the generator's blind spot, when the critic is weaker than the generator (it rubber-stamps or nitpicks), and in unbounded "keep improving" loops.

The failure mode to watch: a critic that always says "revise" produces an agent that rewrites forever without converging, and a critic can be wrong and demand changes that break a correct answer. max_rounds and a "keep what was right" instruction are the guardrails, and logging every critique (Part 9) lets you measure whether the loop helps on your task. The full pitfall table is in 08A.11, 2.6, and the fixed-versus-broken measurement is in 08A.11, 2.5. Module 10A owns evaluation methodology.


Part 5: Routing, orchestrator-workers and working memory#

Deep-dive

5.1 Routing agents and handoffs#

A routing agent is a classifier in front of specialists: one cheap call decides which agent (or prompt, or tool set, or model) handles the request, then control transfers. Two flavours matter:

  • Route-and-run (what route_and_run implements): classify once, run the chosen specialist to completion, return its answer. Control stays with the caller.
  • Handoffs: control transfers — the specialist takes over the conversation and its answer becomes the response. This is how OpenAI's Agents SDK models it: handoffs are represented as tools named transfer_to_<agent> (OpenAI Agents SDK docs, verified November 2026), and Claude Agent SDK does the equivalent with subagents the main agent spawns via the Agent tool (subagents docs). Lesson 08F.1 compares the SDKs; here the pattern is the same either way.

The implementation is small because the machinery already exists — call_for_json for the classification, registry.subset() for least-privilege tools, Route carrying instructions and per-route model settings:

python
@dataclass
class Route:
    """One specialist: its own instructions and its own subset of tools."""
    name: str
    description: str            # what the classifier sees
    instructions: str           # system prompt for the specialist agent
    tool_names: list[str]       # subset of the shared registry
    model_kwargs: dict[str, Any] = field(default_factory=dict)


ROUTER_SYSTEM = """You are a router. Classify the user's request into exactly
one of the routes below, or "general" if none fits. Reply with ONLY JSON:
<<JSON>>

Routes:
<<ROUTES>>"""


async def route_and_run(call_model, registry, routes: dict[str, Route],
                        messages, *, budget: Budget | None = None,
                        fallback: str = "general", model_kwargs=None,
                        gate=None, on_event=None) -> tuple[AgentResult, str]:
    """Classify once, then run the chosen specialist with its own tools.

    `gate` is applied inside the specialist's run_agent, so approval and
    permission policies reach the routed work (Part 6).
    """
    budget = budget or Budget()
    route_list = "\n".join(f"- {r.name}: {r.description}" for r in routes.values())
    router_prompt = (ROUTER_SYSTEM
                     .replace("<<JSON>>", '{"route": "<name>", "reason": "<one line>"}')
                     .replace("<<ROUTES>>", route_list))
    try:
        verdict, _ = await call_for_json(
            call_model,
            [Message("system", router_prompt),
             Message("user", _last_user_text(messages))],
            model_kwargs=model_kwargs)
        name = str(verdict.get("route", ""))
    except ValueError:
        name = ""
    route = routes.get(name) or routes.get(fallback)
    if route is None:
        raise ValueError(f"router picked unknown route {name!r} and no "
                         f"fallback {fallback!r} exists")
    sub = registry.subset(route.tool_names)
    # The specialist gets exactly one system message — the route's instructions
    # replace any system prompt already in `messages` (providers disagree on
    # whether two system messages are legal; 03.2/03.5 own the wire rules).
    run_messages = [Message("system", route.instructions)] + [
        m for m in messages if m.role != "system"]
    res = await run_agent(call_model, sub, run_messages, budget=budget,
                          model_kwargs={**(model_kwargs or {}),
                                        **route.model_kwargs},
                          gate=gate, on_event=on_event)
    return res, route.name

The router prompt template uses <<JSON>>/<<ROUTES>> placeholders — literal braces would break .format(), which is why the code uses str.replace. Rendered for the demo's three routes it reads:

text
You are a router. Classify the user's request into exactly one of the routes
below, or "general" if none fits. Reply with ONLY JSON:
{"route": "<name>", "reason": "<one line>"}

Routes:
- orders: order status, delivery, refunds on orders
- policy: questions about refund/shipping/warranty policy
- general: anything else

Real output: the router classified "Where is my order A-1002?" → orders, and the specialist ran with only lookup_order and issue_refund in its tool list — the smaller tool set is the accuracy win (fewer ways to pick wrong, per 08A.6's tool-count guidance and 03.5, 14.3). A general fallback route catches anything the classifier can't place — never let an unknown route crash the request.

5.2 When to route vs when to give one agent all tools#

Route when... Don't route when...
Task types are genuinely distinct (orders vs policy vs billing) Tasks share tools and context anyway
Specialists need different system prompts or models One prompt covers everything cleanly
You want per-route budgets/models/cost control The classifier itself becomes the failure point
Compliance wants least-privilege tool sets per domain Latency budget can't afford +1 call

Routing is also a cost lever: the classifier and cheap routes can run a small model (Route.model_kwargs) while hard routes escalate — the same cascade idea as 02.9's model routing applied at the agent level.

5.3 Orchestrator-workers as agents#

Orchestrator-workers is Anthropic's name for the pattern where a central model decomposes a task into subtasks it can't predict in advance, delegates each to a worker, and synthesises the results (Building effective agents, verified November 2026 — 08A.9 covers it as a workflow; here it is an agent because the lead decides dynamically when and whether to delegate). The implementation trick: delegate is just another tool the lead can call, and each delegation spins up a fresh run_agent with isolated context.

python
@dataclass
class WorkerSpec:
    name: str
    description: str
    instructions: str
    tool_names: list[str]
    budget: Budget = field(default_factory=lambda: Budget(max_steps=6,
                                                        max_seconds=180))
    model_kwargs: dict[str, Any] = field(default_factory=dict)


async def orchestrate(call_model, registry, goal, workers: dict[str, WorkerSpec],
                      *, lead_tool_names: list[str] | None = None,
                      budget: Budget | None = None,
                      max_delegations: int = 4,
                      worker_result_chars: int = 2000,
                      lead_system: str | None = None,
                      gate=None, on_event=None) -> AgentResult:
    """A lead agent that delegates subtasks to worker sub-agents.

    Context isolation: each worker sees ONLY its task prompt and its own tools —
    never the lead's conversation (04.7, Part 7). Workers return a condensed
    answer; the lead synthesises. This is the agent form of Anthropic's
    'orchestrator-workers' workflow; 08D.3 goes deeper into multi-agent systems.

    `gate` is passed to BOTH the lead's run_agent and every worker's run_agent,
    so approval/permission policies reach delegated work (Part 6).
    """
    budget = budget or Budget(max_steps=15, max_seconds=600)
    stats = {"delegations": 0, "worker_calls": 0}
    worker_menu = "\n".join(f"- {w.name}: {w.description}"
                            for w in workers.values())

    async def delegate(task: str, worker: str = "") -> str:
        if stats["delegations"] >= max_delegations:
            return json.dumps({"error": "delegation budget exhausted; "
                                       "answer with what you have"})
        spec = workers.get(worker)
        if spec is None:
            if len(workers) == 1:
                spec = next(iter(workers.values()))
            else:
                return json.dumps({"error": f"unknown worker {worker!r}; "
                                             f"choose one of: {sorted(workers)}"})
        stats["delegations"] += 1
        stats["worker_calls"] += 1
        if on_event:
            on_event({"type": "delegation", "worker": spec.name,
                      "task": task[:200]})
        sub = registry.subset(spec.tool_names)
        sub_messages = [Message("system", spec.instructions),
                        Message("user", task)]
        res = await run_agent(call_model, sub, sub_messages, budget=spec.budget,
                              model_kwargs=spec.model_kwargs, gate=gate,
                              on_event=lambda e: on_event(
                                  {"type": "worker_event", "worker": spec.name,
                                   "event": e}) if on_event else None)
        stats["worker_calls"] += res.steps
        if res.stop_reason == "paused":
            # A worker's approval pause cannot reach a human from in here: this
            # function returns a string to the lead. Say so explicitly. Nothing
            # was executed, because the gate paused BEFORE the tool ran.
            if on_event:
                on_event({"type": "worker_paused", "worker": spec.name,
                          "tool": (res.pause_payload or {}).get("tool")})
            return json.dumps({"error": f"worker {spec.name} needs human approval for "
                                        f"{(res.pause_payload or {}).get('tool')!r} and "
                                        "cannot continue; nothing was executed. Tell the "
                                        "user the action is pending approval."})
        text = res.answer or f"[worker {spec.name} stopped: {res.stop_reason}]"
        return text[:worker_result_chars]

    lead_reg = ToolRegistry()
    for n in (lead_tool_names if lead_tool_names is not None else registry.names()):
        t = registry.get(n)
        if t is not None:
            lead_reg.add(t)
    lead_reg.add(Tool(
        # risk="write", not "read": delegation can trigger side effects inside
        # the worker. With an approval policy attached, the delegation boundary
        # itself pauses — the finer per-tool approvals still apply inside.
        "delegate", "Delegate a self-contained subtask to a specialist worker. "
        "The worker cannot see this conversation; include everything it needs.",
        {"type": "object",
         "properties": {
             "task": {"type": "string",
                      "description": "Complete, self-contained task description"},
             "worker": {"type": "string",
                        "description": f"Worker name. Options: {sorted(workers)}"}},
         "required": ["task"]},
        delegate, risk="write",
        # a worker may legitimately run for its whole budget: don't let the
        # registry's 30 s default per-tool timeout cut the delegation short
        timeout=max((w.budget.max_seconds for w in workers.values()),
                    default=30.0) + 5))

    system = lead_system or (
        "You are the lead agent for a support-operations team. Delegate "
        "specialist subtasks with the delegate tool, then synthesise the "
        "results into one answer for the user. Workers:\n" + worker_menu)
    return await run_agent(call_model, lead_reg,
                           [Message("system", system), Message("user", goal)],
                           budget=budget, gate=gate, on_event=on_event)

Key properties, each deliberate:

  • Context isolation: the worker gets [system: worker instructions, user: task] — nothing else. The lead's whole conversation (which may contain irrelevant orders, PII, dead ends) never enters the worker's context. This is 04.7's delegation pattern applied to agents, and the main reason multi-agent systems stay tractable: each worker's context stays small and focused.
  • Condensed return: only the worker's final answer (truncated to worker_result_chars) goes back to the lead — not its transcript. Full worker trajectories are not lost: each worker event reaches on_event wrapped as {"type": "worker_event", "worker": ..., "event": {...}}.
  • Bounded fan-out: max_delegations caps how many workers the lead can spawn; each worker has its own smaller Budget. Without these a confused lead can spawn workers recursively until the bill arrives.
  • Self-contained tasks: the delegate tool description tells the lead the worker "cannot see this conversation" — the single most common orchestration bug is delegating a task that references context the worker never received.

Approval composition. Because orchestrate forwards gate into every run_agent it creates — the lead's and each worker's — a PermissionPolicy/policy_gate attached at the top reaches inside delegations automatically. Two levels of control result: the delegate tool itself is classed risk="write" (a worker can cause side effects), so a policy that pauses on writes pauses at the delegation boundary before the worker even starts; and inside the worker, its own tool calls pass through the same gate with their own risk classes. If you want the boundary unchecked but the worker's issue_refund checked, pass a gate that inspects tool.name == "delegate" differently — the gate signature makes that a five-line policy, not a redesign.

Real output: lead delegated "status and total of A-1001" to order_analyst (which saw only lookup_order), got back "Delivered 2026-10-18, total $84.50, within refund window", and synthesised the final answer in 2 lead steps.

5.4 The todo/task-list tool and scratchpads#

Long-horizon agents (coding agents especially) keep an explicit task list in context: a structured list they write, re-read, and update — working memory that survives context trimming better than prose plans. Claude Code's Task/Todo-style tools are the canonical example (08A.15 goes deep on coding agents). The pattern is two trivial tools over a small store:

python
class TodoList:
    """The task list a coding-style agent maintains in its own context."""
    VALID = {"pending", "in_progress", "done"}

    def __init__(self, path: str | None = None, max_items: int = 20):
        self.items: list[dict[str, Any]] = []
        self.path = path
        self.max_items = max_items

    def write(self, items: list[dict[str, Any]]) -> str:
        # over the cap is an explicit error, not a silent truncation — the model
        # must learn to split the work into phases rather than lose items quietly
        if len(items) > self.max_items:
            return json.dumps({"error": f"{len(items)} items exceeds "
                                         f"max_items={self.max_items}; "
                                         "split the work into phases"})
        clean = []
        for i, it in enumerate(items, 1):
            status = it.get("status", "pending")
            if status not in self.VALID:
                return json.dumps({"error": f"bad status {status!r}; "
                                             f"use one of {sorted(self.VALID)}"})
            clean.append({"id": str(it.get("id", i)),
                          "content": str(it.get("content", "")),
                          "status": status})
        self.items = clean
        if self.path:
            with open(self.path, "w") as fh:
                json.dump(self.items, fh, indent=2)
        return json.dumps({"todos": self.items, "count": len(self.items)})

    def read(self) -> str:
        if not self.items:
            return "(todo list is empty)"
        return "\n".join(f"[{i}] ({t['status']}) {t['content']}"
                         for i, t in enumerate(self.items, 1))

    def tools(self) -> list:
        from agent_loop import Tool
        return [
            Tool("todo_write", "Replace the task list. Items: "
                 "{id?, content, status: pending|in_progress|done}.",
                 {"type": "object",
                  "properties": {"items": {"type": "array", "items": {
                      "type": "object",
                      "properties": {"id": {"type": "string"},
                                     "content": {"type": "string"},
                                     "status": {"type": "string"}},
                      "required": ["content", "status"]}}},
                  "required": ["items"]},
                 self.write, risk="read"),
            Tool("todo_read", "Read the current task list.",
                 {"type": "object", "properties": {}}, self.read, risk="read"),
        ]


class NotesFile:
    """A scratchpad file the agent appends to — durable working memory."""

    def __init__(self, path: str = "agent_notes.md", max_chars: int = 8000):
        self.path = path
        self.max_chars = max_chars

    def append(self, text: str) -> str:
        with open(self.path, "a") as fh:
            fh.write(text.rstrip() + "\n")
        return json.dumps({"appended": len(text), "path": self.path})

    def read(self, offset: int = 0) -> str:
        try:
            with open(self.path) as fh:
                data = fh.read()
        except FileNotFoundError:
            return "(no notes yet)"
        return data[offset:offset + self.max_chars] or "(end of notes)"

    def tools(self) -> list:
        from agent_loop import Tool
        return [
            Tool("append_note", "Append a note to your scratchpad file. Use it "
                 "for facts, decisions and dead ends worth keeping.",
                 {"type": "object",
                  "properties": {"text": {"type": "string"}},
                  "required": ["text"]},
                 self.append, risk="write"),
            Tool("read_notes", "Read your scratchpad (optionally from char offset).",
                 {"type": "object",
                  "properties": {"offset": {"type": "integer"}},
                  },
                 self.read, risk="read"),
        ]


def make_think_tool(scratchpad: list[str]):
    """A no-op 'think' tool: the model writes reasoning into the trajectory.

    Explicit thoughts are visible in your logs — useful for debugging — but see
    04.3 Part 4: shown reasoning may be unfaithful, and on reasoning models the
    provider already thinks for you (02.8).
    """
    from agent_loop import Tool

    def think(thought: str) -> str:
        scratchpad.append(thought)
        return "noted"

    return Tool("think", "Record a private reasoning note. Does not change "
                "anything; use it to think out loud before acting.",
                {"type": "object",
                 "properties": {"thought": {"type": "string"}},
                 "required": ["thought"]},
                think, risk="read")

NotesFile is the humbler sibling — an append-only scratchpad (append_note/read_notes) the agent uses for facts, decisions and dead ends worth keeping across a long run. make_think_tool rounds out the working-memory toolkit: a no-op tool that gives the model a place to write reasoning the trajectory then records. Demo: the agent emitted two tool calls in a single turn — executed in order here; 08A.2 covers running them concurrently — and todos after run showed the list persisted.

5.5 Awareness: search/tree-of-thought and self-consistency#

Two neighbouring ideas deserve a mention without full implementation:

  • Tree-of-thought / search agents: instead of one reasoning path, explore a tree of candidate steps — generate several "thoughts", evaluate them, keep the promising branches, backtrack when stuck. The canonical papers are ToT (Yao et al., arXiv:2305.10601, NeurIPS 2023 — GPT-4 solved 74% of Game of 24 vs 4% with plain CoT) and LATS (Zhou et al., arXiv:2310.04406, ICML 2024 — Monte Carlo Tree Search over reasoning+acting+reflection). These are research-grade: combinatorial cost, complex bookkeeping, and today's frontier reasoning models already do much of the lookahead internally. Know they exist; reach for them only when a task genuinely needs search over alternatives and you can bound the branching.
  • Self-consistency for agents: run the same task N times with sampling, take the majority answer — Wang et al., arXiv:2203.11171, ICLR 2023 (+17.9% on GSM8K). For agents it means N parallel runs and a vote; useful for high-stakes one-shot answers, expensive for tool-using loops because each run re-executes tools (and side effects). 04.3, 2.4/2.7 covers the prompting-level versions; treat agent-level self-consistency as an eval-time technique, not a default.

Part 6: Control and safety patterns#

Deep-dive

Autonomy without guardrails is a liability. These patterns wrap any of the reasoning patterns above — they attach at the gate seam or the Budget, not inside a specific pattern. Two companion lessons go deeper: 08A.12 treats human approval as a pattern in its own right (risk tiers, timeouts, approval fatigue), and 08A.13 covers what changes when nobody is watching the run.

6.1 Human-in-the-loop approval#

This section is the compact version, with full code. 08A.12 is the dedicated lesson: risk tiers (which calls need a human), the four decisions, pause and resume with persisted state, timeouts and default-deny and approval fatigue. A run that no human is watching needs different rules: see 08A.13, Part 9.

The requirement: before a risky tool runs, pause the whole run, show a human exactly what the agent wants to do, and resume with their decision — approve, edit (change the arguments), or reject. The mechanism is the gate callback returning GateVerdict(action="pause"), which makes run_agent return stop_reason="paused" with pending_calls and a JSON-safe pause_payload; resume_agent applies the decision and continues the loop. State survives because snapshot()/restore() serialise the whole run — the same job LangGraph's checkpointer + interrupt()/Command does (interrupts docs, verified November 2026) and Claude Agent SDK's canUseTool/hooks do (permissions, hooks).

sequenceDiagram
    participant U as Your code
    participant A as run_agent
    participant H as Human
    U->>A: run_agent(..., gate=policy_gate(policy))
    A->>A: model calls issue_refund(amount=30)
    A->>U: stop_reason="paused" + pause_payload
    U->>H: show approval card (tool, args, risk)
    H-->>U: approve / edit / reject
    U->>A: resume_agent(paused, decision)
    A->>A: execute (or reject) → continue loop → answer

approval.py builds the policy and gate — three pieces: _err (the auto-deny result format), policy_gate (policy → gate), and the run_agent_approved/resume_approved wrappers that attach the gate and re-attach it after a human decision:

python
# approval.py — the complete file
import json
from dataclasses import dataclass, field
from typing import Any, Callable

from agent_loop import (AgentResult, Budget, CallModel, Gate, GateVerdict,
                        Message, Tool, ToolCall, ToolRegistry, resume_agent,
                        run_agent)


def _err(msg: str) -> str:
    return json.dumps({"error": msg})


@dataclass
class PermissionPolicy:
    """Declarative rules evaluated before every tool call.

    allow_tools=None means 'everything registered'; deny_tools always wins;
    approval_risks lists Tool.risk values that pause for a human; extra_check
    is an escape hatch for argument-level rules (e.g. refund > $200).
    """
    allow_tools: set[str] | None = None
    deny_tools: set[str] = field(default_factory=set)
    approval_risks: set[str] = field(default_factory=lambda: {"write", "destructive"})
    extra_check: Callable[[ToolCall, Tool | None], str | None] | None = None


def policy_gate(policy: PermissionPolicy, *, trace_id: str = "") -> Gate:
    """Build a gate from a PermissionPolicy."""

    async def gate(call: ToolCall, tool: Tool | None) -> GateVerdict:
        if policy.allow_tools is not None and call.name not in policy.allow_tools:
            return GateVerdict("replace", result=_err(
                f"tool {call.name!r} is not permitted for this agent"))
        if call.name in policy.deny_tools:
            return GateVerdict("replace", result=_err(
                f"tool {call.name!r} is denied by policy"))
        if policy.extra_check is not None:
            reason = policy.extra_check(call, tool)
            if reason:
                return GateVerdict("replace", result=_err(reason))
        if tool is not None and tool.risk in policy.approval_risks:
            return GateVerdict("pause", payload={
                "kind": "tool_approval",
                "trace_id": trace_id,
                "tool": call.name,
                "arguments": call.arguments,
                "risk": tool.risk,
                "description": tool.description,
            })
        return GateVerdict()

    return gate


async def run_agent_approved(call_model, registry, messages, *,
                             policy: PermissionPolicy,
                             budget: Budget | None = None,
                             model_kwargs=None, trace_id: str = "",
                             on_event=None,
                             timeout_per_call: float = 120.0) -> AgentResult:
    """run_agent with a permission/approval gate attached."""
    return await run_agent(
        call_model, registry, messages, budget=budget,
        model_kwargs=model_kwargs, gate=policy_gate(policy, trace_id=trace_id),
        on_event=on_event, timeout_per_call=timeout_per_call)


async def resume_approved(call_model, registry, paused: AgentResult,
                          decision: dict, *,
                          policy: PermissionPolicy,
                          budget: Budget | None = None,
                          model_kwargs=None, trace_id: str = "",
                          on_event=None) -> AgentResult:
    """resume_agent that re-attaches the policy gate for subsequent calls.

    `policy` is required on purpose: a default of None would silently drop the
    gate for every tool call after the human's decision.
    """
    return await resume_agent(call_model, registry, paused, decision,
                              budget=budget, model_kwargs=model_kwargs,
                              gate=policy_gate(policy, trace_id=trace_id),
                              on_event=on_event)

Three verdict kinds, three different jobs: proceed (run it), replace (auto-deny with an error the model reads — the model can then ask the user or pick another path), pause (wait for a human). Real output from the demo — the agent tried issue_refund(order_id="A-1001", amount=30.0, reason="damaged on arrival"), the gate paused it, and the payload handed to the human was:

json
{"kind": "tool_approval", "trace_id": "t-42", "tool": "issue_refund",
 "arguments": {"order_id": "A-1001", "amount": 30.0, "reason": "damaged on arrival"},
 "risk": "destructive", "description": "Issue a refund on a delivered order. Has real-world effect."}

After resume_approved(..., {"action": "approve"}) the run continued and finished: "Refund R-0001 issued for $30 on A-1001." — and REFUNDS shows the record. The edit path re-runs the tool with human-corrected arguments; reject feeds {"error": "the user rejected 'issue_refund': <reason>. Do not retry the same call; ask the user or choose a different approach."} back so the model responds gracefully instead of looping.

6.2 Permission models#

PermissionPolicy is deliberately tiny; production policies add argument-level rules via extra_check (the demo used one: "refunds over $50 need manager sign-off" — evaluated as a replace verdict, so the model sees a denial it can route around by escalating, rather than a pause). The layering, cheapest first:

  1. Tool allow-lists per agent/route — registry.subset() already does this for routing and workers; a policy's allow_tools does it globally.
  2. Risk classes on tools — Tool.risk (read/write/destructive) declared once at registration (08A.6 owns the taxonomy).
  3. Argument rules — extra_check for "refund > $X", "only these order IDs", "dry-run first".
  4. Human approval — approval_risks pauses; the strongest gate, also the slowest. 08A.12, Part 2 shows how to choose which calls get it.

Never let the model's own say-so grant permission — the policy is your code evaluating its request, which is the whole point of the gate sitting outside the loop.

6.3 Budgets, circuit breakers and cost#

Already wired into run_agent: Budget caps steps, tokens, cost and wall-clock; max_calls_per_tool caps any single tool; the same call (same tool, same arguments) requested a fourth time in one run (max_identical_calls=3, counted across the whole run, not only back-to-back) → loop_detected; three identical results in a row → stalled; three consecutive tool errors → circuit_breaker. Cost accounting uses Usage × per-million prices you supply — set them from 03.7's price table, and remember agent cost is roughly steps × (prompt + completion) so loops multiply fast. A circuit breaker should also feed an alert — a breaker tripping repeatedly is a signal the tool or prompt is broken, not bad luck. For runs nobody watches, budgets and a kill switch matter more: 08A.13, Part 8.

6.4 Timeouts and cancellation#

Two clocks, both already in the loop: timeout_per_call wraps each call_model in asyncio.wait_for (a hung provider call becomes model_timeout, not a hung agent), and registry.call has its own per-tool timeout (30 s by default; a Tool can override it with timeout=, which orchestrate does for delegate so a worker is not cut off at 30 s). budget.max_seconds is the run-level deadline. For cancellation (user hits stop, request dies), cancel the asyncio.Task running run_agent: CancelledError propagates out of _drive — the messages/events accumulated so far are inspectable via the trajectory logger, and a durable system can snapshot-style persist them for resume (the same resumability story as 03.3, Part 8 and LangGraph checkpoints). Don't swallow CancelledError inside the loop — let it propagate and clean up at the boundary.

6.5 Fallback to a human#

Every non-answered stop reason is a candidate for escalation: max_steps, max_cost, loop_detected, circuit_breaker, model_error — package pause_payload-style context (goal, last events, partial answer) into a handoff object for a human queue or a simpler workflow. The graceful-degradation rule: an agent that can't finish should produce a useful partial result plus a clear reason, never silence. 08A.14 builds the full fallback/escalation chain; the pattern here is just: detect the stop reason, attach the trajectory, route to a person. Two details live elsewhere: a human who never answers needs a deadline and a default (08A.12, Part 5), and a background run needs a way to tell the user it stopped (08A.13, Part 7).


Part 7: Prompting the agent#

7.1 The agent system prompt blueprint#

04.5 owns system-prompt craft; an agent prompt adds duties a chat prompt doesn't have. The blueprint:

  1. Role + goal — who it is and what "done" looks like.
  2. Tool policy — which tools exist, when to use each, when not to.
  3. When to ask vs when to act — the autonomy dial, stated explicitly.
  4. When to stop — the finish condition and what to do at budgets.
  5. Output format — what the final answer looks like.
  6. Error recovery — what to do on tool errors, empty results, contradictions.
  7. Safety rules — what it must never do, what needs approval.
  8. Verification expectations — check before claiming (links Part 4).

A. The support agent (ReAct default):

text
You are the support operations agent for Northwind Supply. You help agents
resolve customer issues using your tools.

TOOLS: lookup_order (order status/items), search_docs (policy), create_ticket
(ops team), issue_refund (money — requires human approval, the system pauses
automatically), run_report (ops metrics).

RULES:
- Always look up the order before discussing it; never invent order details.
- For policy questions, search_docs first and cite the policy title.
- Refunds: only for delivered orders within 30 days of delivery; partial
  refunds up to the item price are allowed. Anything else → create_ticket.
- If a tool returns an error, read it and adjust — don't retry identically.
- When you have the answer, state it plainly with the order/ticket IDs.
- If you cannot resolve it after reasonable effort, create a ticket and say so.

B. The research agent (orchestrator-workers lead):

text
You are the research lead. You answer complex questions by delegating focused
subtasks to specialist workers, then synthesising their findings.

WORKERS: web_analyst (search + fetch pages), data_analyst (compute over
numbers), summarizer (condense long text).

RULES:
- Delegate with self-contained tasks — workers cannot see this conversation.
- Give each worker everything it needs: the question, relevant IDs, constraints.
- Delegate independent subtasks; don't serialise work that can run in parallel.
- Synthesise: reconcile disagreements explicitly, cite which worker said what.
- If workers return conflicting facts, delegate a tie-breaker or say so.
- Stop when you can answer with citations, or when the delegation budget ends.

C. The todo-using long-horizon agent:

text
You are an operations agent handling multi-step requests. You maintain a todo
list with todo_write/todo_read — keep it current: mark items in_progress when
you start, done when finished, and re-read it before each new step.

RULES:
- On a multi-step request, write the todo list FIRST, then execute it.
- One in_progress item at a time.
- Append durable facts to your notes file; don't rely on memory across steps.
- If the todo list and reality disagree, trust reality and update the list.
- Finish by summarising what was done per todo item.

7.3 Prompting-for-tool-use pitfalls#

Pitfall Fix
Over-calling tools (lookup for everything) "Use tools when they add information you don't have; answer directly when you can."
Under-calling (guessing instead of checking) "Never state order/policy facts without a tool result."
Wrong parallelism instructions Say "make independent calls together" only if your loop executes them concurrently (08A.2); otherwise serial is fine
"Be proactive" vs "ask first" State the autonomy dial explicitly per tool risk (Part 6)
Vague stop condition "Stop when you can answer with citations / when the report is verified"
Instructions that drift over long runs Re-inject the critical rules; 04.7, Part 8 covers instruction drift and re-injection

Reasoning effort per task: cheap classification/routing calls want low effort, hard planning/synthesis want high — set it per call via model_kwargs (02.8, Part 3). Keeping instructions alive over long runs is 04.7's problem; the agent-specific note is that your system prompt is resent every loop turn, so it must be compact enough to survive the context budget.


Part 8: State machines and graphs#

Deep-dive

8.1 When explicit control flow beats a free loop#

A free run_agent loop is right when the path is genuinely unpredictable. When you can enumerate the flow — intake → extract → policy check → approve → execute → confirm — encoding it as explicit states and transitions buys you: visible paths, per-node testing, no wandering, and natural pause points for humans. This is the same instinct behind LangGraph's StateGraph and Google ADK's workflow agents (SequentialAgent, ParallelAgent, LoopAgent — ADK workflow-agents docs, verified November 2026; note ADK 2.0 has superseded these templated workflow agents with graph-based and dynamic workflows for Python and Go — the docs themselves carry a note saying template workflows are "superseded" from ADK 2.0 for Python and Go, not formally deprecated); lesson 08F.1 compares frameworks. Here is the smallest honest version — statemachine.py, complete:

python
# statemachine.py — the complete file
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable


@dataclass
class Command:
    """What a node returns: where to go next, and what to merge into state."""
    goto: str | None = None          # None = stop
    update: dict[str, Any] = field(default_factory=dict)


Node = Callable[[dict[str, Any]], Awaitable[Command]]


class StateMachine:
    """Nodes are async functions state -> Command. `state` is a plain dict."""

    def __init__(self, nodes: dict[str, Node], start: str, *,
                 max_steps: int = 50):
        if start not in nodes:
            raise ValueError(f"start state {start!r} is not a node")
        self.nodes = nodes
        self.start = start
        self.max_steps = max_steps

    async def run(self, state: dict[str, Any] | None = None) -> dict[str, Any]:
        state = dict(state or {})
        current = self.start
        for _ in range(self.max_steps):
            cmd = await self.nodes[current](state)
            state.update(cmd.update)
            if cmd.goto is None:
                return state
            if cmd.goto not in self.nodes:
                raise ValueError(f"node returned unknown goto {cmd.goto!r}")
            current = cmd.goto
        raise RuntimeError(f"state machine exceeded max_steps={self.max_steps}")

The refund flow as explicit states — deterministic nodes for policy, an agent node where judgement is needed:

python
# A fragment: it runs inside `async def demo_statemachine()` in demo.py (Part 11),
# which wraps these nodes and the `await` below.
async def intake(state):      # extraction model call in production
    return Command(goto="policy",
                   update={"order_id": "A-1001", "amount": 30.0, "reason": "damaged"})
async def policy(state):      # deterministic check against the DB
    from support_tools import ORDERS
    order = ORDERS[state["order_id"]]
    ok = order["status"] == "delivered" and state["amount"] <= order["total"]
    return Command(goto="approve" if ok else "reject", update={"policy_ok": ok})
async def approve(state):     # in production: pause for a human (Part 6)
    return Command(goto="execute", update={"approved": True})
async def execute(state):
    from support_tools import issue_refund
    return Command(goto="confirm",
                   update={"result": issue_refund(state["order_id"],
                                                  state["amount"], state["reason"])})
async def confirm(state):
    return Command(goto=None,
                   update={"final": f"Refund {state['result'].get('refund_id')} issued."})
async def reject(state):
    return Command(goto=None, update={"final": "Refund denied by policy."})

sm = StateMachine({"intake": intake, "policy": policy, "approve": approve,
                   "execute": execute, "confirm": confirm, "reject": reject},
                  start="intake")
out = await sm.run()

Real output: {"policy_ok": true, "approved": true, "final": "Refund R-0002 issued."} (three keys of the final state, which passed through five of the six nodes — reject is the branch not taken; policy read the real order data — R-0002 because demo_approval already issued R-0001 earlier in the same process; run demo_statemachine alone and it prints R-0001). The approve node is where a Part-6 pause would slot in — a state machine makes human checkpoints visible as nodes rather than hidden in loop state.


Part 9: Evaluation hooks — trajectory logging#

Deep-dive

Every pattern above emits events through on_event — that is not decoration, it is the evaluation hook. An agent's quality lives in its trajectory (the sequence of model calls, tool calls, arguments and results), not just its final answer, and 08A.14 + Module 10A own trajectory evals. trajectory.py is the minimal collector:

python
# trajectory.py — the complete file
from __future__ import annotations

import json
import time
from typing import Any


class TrajectoryLogger:
    """Collects run_agent events; optionally writes them as JSONL."""

    def __init__(self, path: str | None = None):
        self.events: list[dict[str, Any]] = []
        self._fh = open(path, "a") if path else None

    def __call__(self, event: dict[str, Any]) -> None:
        stamped = {"wall": round(time.time(), 3), **event}
        self.events.append(stamped)
        if self._fh:
            self._fh.write(json.dumps(stamped, default=str) + "\n")
            self._fh.flush()

    def close(self) -> None:
        if self._fh:
            self._fh.close()
            self._fh = None

    def summary(self) -> dict[str, Any]:
        """Roll the events up into the numbers an eval or dashboard needs."""
        by_type: dict[str, int] = {}
        tools: dict[str, int] = {}
        tokens_in = tokens_out = 0
        cost = 0.0
        errors = 0
        for e in self.events:
            t = e.get("type", "?")
            by_type[t] = by_type.get(t, 0) + 1
            if t == "tool_call":
                tools[e.get("tool", "?")] = tools.get(e.get("tool", "?"), 0) + 1
            if t == "model_reply":
                tokens_in += e.get("input_tokens") or 0
                tokens_out += e.get("output_tokens") or 0
                cost += e.get("cost_usd") or 0.0
            if t in ("model_error", "tool_denied", "loop_detected",
                     "stalled", "circuit_breaker", "verification_failed"):
                errors += 1
        return {"events": len(self.events), "by_type": by_type,
                "tool_calls": tools, "input_tokens": tokens_in,
                "output_tokens": tokens_out, "cost_usd": round(cost, 6),
                "error_events": errors}


def trajectory_summary(events: list[dict[str, Any]]) -> dict[str, Any]:
    """Same rollup for a plain event list (e.g. AgentResult.events)."""
    logger = TrajectoryLogger()
    for e in events:
        logger(e)
    return logger.summary()

Wire it as on_event=TrajectoryLogger("run.jsonl") on any run_agent/pattern call — trajectory_summary(res.events) gives the same rollup for a finished run without a logger attached. Real summary from the demo run (demo_todo_trajectory):

json
{"events": 8,
 "by_type": {"model_call": 2, "model_reply": 2, "tool_call": 2, "tool_result": 2},
 "tool_calls": {"todo_write": 1, "lookup_order": 1},
 "input_tokens": 1600, "output_tokens": 240, "cost_usd": 0.0, "error_events": 0}

What to capture per step (the fields already in the events): model call + finish reason, tool name + arguments, result preview, tokens, cost, denials, pauses, stop reason. Redact secrets/PII before persisting (03.10, 4.5); correlate with trace_id (03.10, 4.4). The same events feed live UI progress, post-hoc debugging, and the eval harnesses of Module 10A — log once, use everywhere.


Reference

10.1 Which pattern when#

Your situation Start with Add when earned
Single tool-using task, unpredictable steps ReAct loop (run_agent) todo list if it runs long; think tool if non-reasoning model
Enumerable multi-step task (onboarding, report, refund flow) Plan-and-execute cheaper executor model; replan on failure only
Many independent tool calls, latency-bound LLMCompiler-style DAG scheduling (awareness — 08A.2's parallel calls are the primitive) planner-emitted dependency graph
Token-cost-bound multi-step task, plan stable up front ReWOO-style plan-then-fill (awareness) #E-style placeholders, worker+solver split
Draft needs quality gate before shipping critique_and_revise (1–2 rounds) deterministic verifier instead of critic where possible; 08A.11, Part 2 for the final-answer gate and score-aware reflection
Result checkable against the world (totals, tests, schema) verify_and_retry —
Many distinct request types sharing tools route_and_run per-route models/budgets; handoffs if control should transfer
Subtasks need isolation or run in parallel orchestrate max_delegations, worker budgets, condensed returns
Independent subtasks, latency or breadth matters Parallel fan-out and aggregate (08A.11, Part 3) per-branch timeouts, quorum, shared token pool, honest partial results
Self-contained specialist the parent should call like a function Agent-as-a-tool (08A.11, Part 4) child budget slice, depth limit, structured result
Flow you can fully enumerate StateMachine agent nodes only where judgement is needed
Anything with side effects + approval gate, permissions, budgets always — these are not optional; 08A.12 for the gate, 08A.13 when the run is unattended

The meta-rule from 08A.9 and Anthropic's guide: simplest thing that works. Every row above the first adds calls, latency and cost; add them one at a time and measure (Module 10A).

Failure Pattern Symptom Guard
Plan never revised plan-and-execute executor results ignored; stale steps run anyway replanner after every step; plan_revised events; cap max_replans
Reflection loops making answers worse critique_and_revise each round drifts further from truth max_rounds, "keep what was right", log critiques, prefer deterministic verifier
Tool thrashing any loop same call or same result repeated loop_detected / stalled / max_calls_per_tool in _drive
Premature stop ReAct, routing model answers before checking facts system prompt "never state facts without a tool result"; verifier retry
Runaway cost any pattern bill grows with steps × context Budget (steps/tokens/cost/seconds), per-tool caps, delegation caps, cost in every event
Router misclassification routing wrong specialist, wrong tools general fallback route; log route + reason; escalate ambiguous to human
Worker context starvation orchestrator worker lacks info the lead had self-contained task descriptions; include IDs/constraints in delegate
Approval fatigue HITL human rubber-stamps everything tighten extra_check rules; risk-class tools so only destructive pauses (08A.12, Part 6)
State machine deadlock statemachine node returns unknown goto validate transitions; max_steps bound; test each node

The common thread: every failure is visible in stop_reason and the event log before it is visible in the answer. That is why Part 9's trajectory logging is not optional — it is how you tell which row of this table you're in.


Part 11: demo.py — the consolidated demo#

Reference

Every pattern in this lesson, exercised end-to-end against ScriptedModel fakes and the in-memory support tools. Run python3 demo.py — the output is deterministic and every block labelled Real output earlier in the lesson comes from this file (plus its own per-section test snippets). The handlers route on the system prompt and last message so one ScriptedModel can play planner, executor, critic, router, worker and specialist depending on who's asking.

python
# demo.py — the complete file
import asyncio
import json
import sys
sys.path.insert(0, ".")

from agent_loop import (Budget, Message, ModelReply, ScriptedModel, ToolCall,
                        Usage, run_agent, snapshot, restore, resume_agent)
from support_tools import build_registry, state_dump
from patterns import (react_text_loop, plan_and_execute, critique_and_revise,
                      verify_and_retry, route_and_run, orchestrate, Route,
                      WorkerSpec, TodoList, NotesFile, make_think_tool,
                      call_for_json)
from approval import PermissionPolicy, run_agent_approved, resume_approved
from statemachine import StateMachine, Command
from trajectory import TrajectoryLogger

REG = build_registry()


def ureply(text=None, calls=None, reason="stop"):
    return ModelReply(text=text,
                      tool_calls=[ToolCall(id=f"c{i}", name=n, arguments=a)
                                  for i, (n, a) in enumerate(calls or [])],
                      finish_reason=reason if calls else "stop",
                      usage=Usage(800, 120))


def show(title, obj):
    print(f"\n{'='*70}\n### {title}\n{'='*70}")
    print(obj if isinstance(obj, str) else json.dumps(obj, indent=2, default=str))


async def demo_native_loop():
    """Native tool-call ReAct: the modern form."""
    model = ScriptedModel([
        ureply(calls=[("lookup_order", {"order_id": "A-1001"})], reason="tool_calls"),
        ureply("Order A-1001 was delivered on 2026-10-18 for $84.50."),
    ])
    msgs = [Message("system", "You are a support agent. Use tools, then answer."),
            Message("user", "When was order A-1001 delivered?")]
    res = await run_agent(model, REG, msgs, budget=Budget(max_steps=6))
    show("native loop: answer", res.answer)
    show("stop_reason / steps / usage", {
        "stop_reason": res.stop_reason, "steps": res.steps,
        "usage": res.usage.__dict__})
    show("trajectory (roles + tool names)",
         [(m.role, m.name or (m.tool_calls[0].name if m.tool_calls else None))
          for m in res.messages])


async def demo_text_react():
    """Original text-format ReAct."""
    replies = [
        "Thought: I need the delivery date of A-1001.\n"
        "Action: lookup_order\nAction Input: {\"order_id\": \"A-1001\"}",
        "Thought: The order was delivered 2026-10-18.\n"
        "Final Answer: Order A-1001 was delivered on 2026-10-18.",
    ]
    model = ScriptedModel([lambda *a, _r=r, **k: ModelReply(text=_r, usage=Usage(500, 80))
                           for r in replies])
    res = await react_text_loop(model, REG, "When was order A-1001 delivered?")
    show("text ReAct answer", res.answer)
    show("parsed steps", res.trajectory)


async def demo_plan_execute():
    """Plan-and-execute over the support tools."""
    def planner_or_executor(messages, tools, **kw):
        sysmsg = messages[0].content if messages else ""
        if sysmsg.startswith("You are the replanner"):
            return ModelReply(text=json.dumps({"action": "respond",
                "answer": "A-1002 is still in transit; per policy it must be refused "
                          "or returned before any refund."}), usage=Usage(400, 60))
        if sysmsg.startswith("You are the planner"):
            return ModelReply(text=json.dumps({"steps": [
                {"id": "1", "description": "Look up order A-1002 status",
                 "needed_tools": ["lookup_order"]},
                {"id": "2", "description": "Check refund policy for in-transit orders",
                 "needed_tools": ["search_docs"]},
            ]}), usage=Usage(600, 100))
        # executor step 1
        if "Look up order A-1002" in str(messages[-1].content):
            return ModelReply(text="Order A-1002 status: shipped, not yet delivered.",
                              usage=Usage(300, 50))
        # executor step 2
        return ModelReply(text="Policy: in-transit orders must be refused or "
                               "returned before refund.", usage=Usage(300, 50))
    model = ScriptedModel([planner_or_executor] * 12)
    res = await plan_and_execute(model, REG,
        "A customer wants a refund on order A-1002 which hasn't arrived yet. "
        "Check the order and the refund policy, then advise.")
    show("plan-and-execute answer", res.answer)
    show("plan steps", [{"id": s.id, "desc": s.description[:50], "status": s.status}
                        for s in res.steps])
    show("replans / usage", {"replans": res.replans,
                             "usage": res.usage.__dict__})


async def demo_reflect():
    """Critique-and-revise, bounded."""
    def handler(messages, tools, **kw):
        sysmsg = (messages[0].content or "") if messages else ""
        if "strict reviewer" in sysmsg:
            return ModelReply(text=json.dumps({
                "verdict": "revise", "issues": ["no order ID cited"],
                "feedback": "Cite the order ID and delivery date explicitly."}),
                usage=Usage(200, 40))
        last = messages[-1].content or ""
        if "critiqued your answer" in last:
            return ModelReply(text="Order A-1001 (delivered 2026-10-18) qualifies "
                                   "for a refund under the 30-day policy.",
                              usage=Usage(300, 60))
        return ModelReply(text="The order qualifies for a refund.", usage=Usage(300, 60))
    model = ScriptedModel([handler] * 12)
    res = await critique_and_revise(model,
        [Message("user", "Does order A-1001 qualify for a refund?")],
        registry=REG, max_rounds=2)
    show("reflection rounds / critiques", {"rounds": res.rounds,
                                           "critiques": res.critiques})
    show("final answer", res.answer)


async def demo_verify():
    """Verification loop: environment re-checks the model's claim."""
    calls = {"n": 0}
    def handler(messages, tools, **kw):
        calls["n"] += 1
        if calls["n"] == 1:
            return ureply(calls=[("run_report", {"kind": "weekly"})], reason="tool_calls")
        if calls["n"] == 2:
            return ureply("Weekly report: 3 deliveries this week, 0 refunds, 0 open tickets.")
        return ureply("Weekly report: 1 delivery this week, 0 refunds, 0 open tickets.")
    model = ScriptedModel([handler] * 10)

    def verifier(res):
        # deterministic re-check against the fake DB, not the model's word
        from support_tools import ORDERS, REFUNDS, TICKETS
        from datetime import date, timedelta
        today = date(2026, 11, 5); week_ago = today - timedelta(days=7)
        real = sum(1 for o in ORDERS.values() if o.get("delivered_on")
                   and week_ago.isoformat() <= o["delivered_on"] <= today.isoformat())
        claimed = "1 delivery" in (res.answer or "")
        if real != 1 or not claimed:
            return f"report mismatch: DB shows {real} deliveries this week"
        return None
    res, problem = await verify_and_retry(
        model, REG,
        [Message("system", "You are a support agent. Use tools, then answer."),
         Message("user", "Run the weekly report and summarise it.")],
        verifier, max_attempts=2)
    show("verify result", {"answer": res.answer, "problem": problem})


async def demo_router():
    """Routing to specialists."""
    routes = {
        "orders": Route("orders", "order status, delivery, refunds on orders",
                        "You are the orders specialist. Use lookup_order and issue_refund carefully.",
                        ["lookup_order", "issue_refund"]),
        "policy": Route("policy", "questions about refund/shipping/warranty policy",
                        "You are the policy specialist. Use search_docs only.",
                        ["search_docs"]),
        "general": Route("general", "anything else",
                         "You are a general support agent.",
                         ["create_ticket", "run_report"]),
    }
    def handler(messages, tools, **kw):
        sysmsg = (messages[0].content or "") if messages else ""
        if "router" in sysmsg.lower():
            return ModelReply(text=json.dumps({"route": "orders",
                                               "reason": "asks about an order"}),
                              usage=Usage(150, 20))
        return ModelReply(text="Order A-1002 is shipped, due within 3-5 business days.",
                          usage=Usage(300, 50))
    model = ScriptedModel([handler] * 8)
    res, name = await route_and_run(model, REG, routes,
        [Message("user", "Where is my order A-1002?")])
    show("router chose", name)
    show("specialist answer", res.answer)
    show("tools the specialist saw", sorted({t["name"] for t in model.requests[-1]["tools"]}))


async def demo_orchestrator():
    """Orchestrator-workers with context isolation."""
    workers = {
        "order_analyst": WorkerSpec(
            name="order_analyst", description="analyzes order status and totals",
            instructions="You are the order analyst. Use lookup_order only.",
            tool_names=["lookup_order"]),
        "policy_analyst": WorkerSpec(
            name="policy_analyst", description="answers policy questions",
            instructions="You are the policy analyst. Use search_docs only.",
            tool_names=["search_docs"]),
    }
    def handler(messages, tools, **kw):
        sysmsg = (messages[0].content or "") if messages else ""
        user = messages[-1].content or ""
        if "lead agent" in sysmsg:
            if "delegate" not in user and len(messages) < 4:
                return ureply(calls=[("delegate",
                    {"task": "What is the status and total of order A-1001?",
                     "worker": "order_analyst"})], reason="tool_calls")
            return ureply("Synthesis: A-1001 was delivered 2026-10-18, total $84.50; "
                          "it is within the 30-day refund window.")
        # worker agents
        if "analyst" in sysmsg:
            return ureply("Delivered 2026-10-18, total $84.50, within refund window.")
        return ureply("ok")
    model = ScriptedModel([handler] * 20)
    res = await orchestrate(model, REG,
        "Can the customer on order A-1001 still get a refund?", workers,
        lead_tool_names=[])
    show("orchestrator answer", res.answer)
    show("stop/steps", {"stop": res.stop_reason, "steps": res.steps})


async def demo_approval():
    """HITL approval: pause, snapshot, human decides, resume."""
    policy = PermissionPolicy(
        approval_risks={"destructive"},
        extra_check=lambda call, tool: (
            "refunds over $50 need manager sign-off"
            if call.name == "issue_refund" and (call.arguments or {}).get("amount", 0) > 50
            else None))

    def handler(messages, tools, **kw):
        sysmsg = (messages[0].content or "") if messages else ""
        if "support agent" in sysmsg:
            last = messages[-1]
            if last.role == "tool":
                return ureply("Refund R-0001 issued for $30 on A-1001.")
            if not any(m.role == "assistant" and m.tool_calls for m in messages):
                return ureply(calls=[("issue_refund",
                    {"order_id": "A-1001", "amount": 30.0,
                     "reason": "damaged on arrival"})], reason="tool_calls")
        return ureply("done")
    model = ScriptedModel([handler] * 12)
    msgs = [Message("system", "You are a support agent. Use tools, then answer."),
            Message("user", "Refund $30 on order A-1001, it arrived damaged.")]
    res = await run_agent_approved(model, REG, msgs, policy=policy,
                                   budget=Budget(max_steps=6), trace_id="t-42")
    if res.stop_reason == "paused":
        show("PAUSED — approval request", res.pause_payload)
        snap = snapshot(res)
        # simulate a human clicking approve in another process
        resumed = await resume_approved(model, REG, restore(snap),
                                        {"action": "approve"}, policy=policy,
                                        budget=Budget(max_steps=6))
        show("after approval", {"stop": resumed.stop_reason,
                                "answer": resumed.answer})
        show("refunds issued", json.loads(state_dump())["refunds"])


async def demo_statemachine():
    """Refund flow as explicit states."""
    async def intake(state):
        # deterministic stand-in for an extraction model call
        return Command(goto="policy", update={
            "order_id": "A-1001", "amount": 30.0, "reason": "damaged"})

    async def policy(state):
        from support_tools import ORDERS
        order = ORDERS[state["order_id"]]
        ok = order["status"] == "delivered" and state["amount"] <= order["total"]
        return Command(goto="approve" if ok else "reject",
                       update={"policy_ok": ok})

    async def approve(state):
        # in production this node would pause for a human (Part 6)
        return Command(goto="execute", update={"approved": True})

    async def execute(state):
        from support_tools import issue_refund
        out = issue_refund(state["order_id"], state["amount"], state["reason"])
        return Command(goto="confirm", update={"result": out})

    async def confirm(state):
        return Command(goto=None, update={
            "final": f"Refund {state['result'].get('refund_id')} issued."})

    async def reject(state):
        return Command(goto=None, update={"final": "Refund denied by policy."})

    sm = StateMachine({"intake": intake, "policy": policy, "approve": approve,
                       "execute": execute, "confirm": confirm, "reject": reject},
                      start="intake")
    out = await sm.run()
    show("state machine trace", {k: out[k] for k in ("policy_ok", "approved", "final")})


async def demo_todo_trajectory():
    """Todo tools + trajectory logger on a real run."""
    todos = TodoList()
    scratch = []
    reg = build_registry()
    for t in todos.tools() + [make_think_tool(scratch)]:
        reg.add(t)

    def handler(messages, tools, **kw):
        sysmsg = (messages[0].content or "") if messages else ""
        if "think" in sysmsg or "support" in sysmsg:
            last = messages[-1]
            if last.role == "tool":
                return ureply("Done. Order A-1001 delivered 2026-10-18; refund "
                              "window open until 2026-11-17.")
            if not any(m.tool_calls for m in messages if m.role == "assistant"):
                return ureply(calls=[
                    ("todo_write", {"items": [
                        {"content": "look up order", "status": "in_progress"},
                        {"content": "check refund window", "status": "pending"}]}),
                    ("lookup_order", {"order_id": "A-1001"})],
                    reason="tool_calls")
        return ureply("ok")
    model = ScriptedModel([handler] * 12)
    log = TrajectoryLogger()
    msgs = [Message("system", "You are a support agent with todo_write, "
                     "todo_read, think and order tools."),
            Message("user", "Is order A-1001 still refundable?")]
    res = await run_agent(model, reg, msgs, budget=Budget(max_steps=8),
                          on_event=log)
    show("todo-aware answer", res.answer)
    show("todos after run", todos.read())
    show("trajectory summary", log.summary())


async def main():
    await demo_native_loop()
    await demo_text_react()
    await demo_plan_execute()
    await demo_reflect()
    await demo_verify()
    await demo_router()
    await demo_orchestrator()
    await demo_approval()
    await demo_statemachine()
    await demo_todo_trajectory()

asyncio.run(main())

Two things to notice in the handlers: (1) ScriptedModel entries can be callables — the demo uses them for stateful multi-role fakes (planner vs executor vs critic vs router distinguished by the system prompt they receive); (2) demo_approval demonstrates the durable pause path: snapshot(res) serialises the paused run to JSON-safe dict, and resume_approved(..., restore(snap), ...) continues it — the same flow a web app uses when a human approves in a different request.


Common misconceptions#

Misconception Reality
"ReAct means writing Thought/Action/Observation as text." That was the 2022 format. Today it's native tool calls + interleaved reasoning; the text loop is a teaching artefact (2.3).
"An agent pattern is a framework you install." It's a control-flow recipe over call_model. The same code runs on any provider (1.1).
"Plan-and-execute is always better than ReAct." It costs more calls and a stale plan can be worse than local reasoning. Use it when steps are enumerable (3.4).
"Reflection always improves the answer." Unbounded critique loops drift and cost; a shared blind spot means the critic can't catch it. Bound rounds, log critiques (4.3).
"The model verified its own work." Only your verifier (recompute, run tests, check the DB) is evidence. A model-as-judge inherits the model's failure modes (4.2).
"More agents = more capable." Each worker is a full agent loop with its own cost and failure modes; delegation needs isolation and budgets to earn its keep (5.3, 08D.3).
"A bigger system prompt makes a better agent." Agents resend the system prompt every turn; bloated prompts cost tokens every step and drift. Compact rules beat exhaustive ones (7.1).
"The agent asked for approval, so it's safe." Approval must gate before execution, show real arguments, and decide scope — the demo's policy_gate runs inside _drive before registry.call (6.1).
"If it didn't crash, the agent worked." Check stop_reason, the trajectory and the verifier — answered can still be wrong (9).
"State machines are old-fashioned compared to agents." They're complementary: deterministic nodes for checkable steps, agent nodes for judgement — the hybrid is how production flows are built (8.1).

Key takeaways#

  • A pattern is choreography around call_model: control flow + prompts + state + budgets. Everything here is provider-agnostic because the seam is.
  • ReAct today = the native tool loop on a reasoning model. The 2022 text format is history; interleaved thinking replaced it. Know the lineage, ship the loop.
  • Plan-and-execute trades extra calls for an inspectable plan-as-state and per-step bounded executors; worth it for enumerable multi-step tasks, overkill for short ones.
  • Reflection and verification are different tools: a critic judges prose; a verifier checks the world. Use bounded rounds and deterministic verifiers wherever possible.
  • Parallel fan-out and agent-as-a-tool are catalogue patterns here and built in the companion lesson 08A.11, together with score-aware reflection. Read it next.
  • Routing buys focused prompts, smaller tool lists and per-route models for +1 classify call; orchestrator-workers buys context isolation and parallelism for +1 agent loop per delegation — both need budgets and fallbacks.
  • Control patterns wrap any pattern: permission policies, risk-classed tools, human approval with approve/edit/reject and resumable snapshots, budgets, circuit breakers, loop/stall detection, timeouts — wire them at the gate/Budget seam from day one. 08A.12 goes deeper on approval gates and 08A.13 on unattended runs.
  • Prompt the agent like an operator: goal, tool policy, autonomy dial, stop condition, output format, error recovery, safety, verification — eight duties a chat prompt doesn't have.
  • State machines make enumerable flows visible and testable; hybrid deterministic/agent nodes are the production shape.
  • Log the trajectory: every pattern already emits events; that stream is your debugging tool, your UI feed and your eval data.

Terms introduced in this lesson#

Term One-line definition
Agent pattern A named recipe for the control flow around call_model: ordering, prompts, state and stop conditions
ReAct Yao et al. 2022 pattern interleaving reasoning traces, actions and observations; today realised as native tool calls + interleaved thinking
Thought / Action / Observation The three text blocks of original ReAct; superseded by reasoning channel, tool_calls, tool-result messages
Interleaved thinking Reasoning that happens between tool calls inside one response, on reasoning models (02.8)
Scratchpad / think tool A no-op tool or notes store letting the agent externalise reasoning into the trajectory
Plan-and-execute Planner → bounded executor per step → replanner; the plan is explicit state, not context
Replanner The cheap call after each step deciding continue / revise / respond
Reflection / self-critique A critic call judging a draft; Reflexion adds verbal feedback across retries
Self-Refine Madaan et al. 2023 — the generate→feedback→refine loop Reflexion extends
ReWOO Plan the whole trajectory before any tool runs; workers fill #E placeholders (awareness)
LLMCompiler Planner emits a DAG of tool calls; independent calls run in parallel (awareness)
Episodic memory buffer Reflexion's store of past reflections fed into later attempts
Verification loop Re-checking an agent's result against the environment (recompute, tests, DB) with bounded retries
Routing agent / handoff Classify-then-dispatch to a specialist; handoff = control transfers to it
Orchestrator-workers Lead agent dynamically delegates subtasks to isolated worker agents and synthesises results
Context isolation Workers see only their task + own tools, never the lead's conversation (04.7)
Todo/task-list tool Agent-maintained structured task list as working memory (coding-agent pattern)
Permission policy Declarative allow/deny/approval rules evaluated before each tool call
Gate The gate(call, tool) -> GateVerdict hook where policies and approvals attach
Human-in-the-loop approval Pause before risky tools; approve / edit / reject; resume from a snapshot
Circuit breaker Stop the run after N consecutive tool errors
Loop / stall detection Stop on repeated identical calls or repeated identical results
State machine Explicit nodes/transitions modelling an agent flow instead of a free loop
Trajectory The recorded sequence of model calls, tool calls, args, results and events
call_model / ScriptedModel The injectable model seam and its canned-reply test double

Exercises#

  1. ReAct by hand (2.2): run react_text_loop with a ScriptedModel whose first reply forgets the Action Input: line. What does the loop do, and how many model calls does recovery cost?
  2. Native vs text (2.3): take the demo_native_loop script and re-implement it as react_text_loop with equivalent scripted replies. Compare the message shapes in ScriptedModel.requests — which carries more structure?
  3. Plan-and-execute (3.3): change the planner's JSON to return 9 steps. What does _plan_from_obj do, and why is the cap there?
  4. Replan (3.3): make the executor for step 2 return stop_reason="max_steps". Trace what the replanner sees and what the final answer becomes.
  5. Reflection bound (4.1): set max_rounds=0 in critique_and_revise. How many model calls happen, and what does rounds report?
  6. Verifier (4.2): write a second verifier that checks the refund amount against issue_refund's own validation rules instead of the DB count. Which is more robust and why?
  7. Routing (5.1): add a fourth route refunds and a request that should hit it. What happens to registry.subset if you list a tool name that doesn't exist?
  8. Orchestrator (5.3): set max_delegations=1 and script the lead to delegate twice. What does the second delegate call return, and how does the lead recover?
  9. Approval (6.1): resume a paused run with {"action": "edit", "arguments": {"amount": 20.0, ...}}. What lands in the tool message, and does the refund record show 20 or 30?
  10. State machine (8.1): add a node between policy and approve that calls the model to draft the customer-facing explanation. Where does the LLM call belong — node or edge?
  11. Trajectory (9): run any pattern with TrajectoryLogger("run.jsonl"), kill it mid-run, and inspect which events made it to disk.
  12. Free path: every demo runs with ScriptedModel — pick one pattern and write the callable replies your real provider adapter would need to produce for the same task.
  13. Gate passthrough (5.3/6.1): attach a PermissionPolicy that pauses on write and run orchestrate with a worker whose tools include create_ticket. Where does the run pause first — at the lead's delegate call or inside the worker — and what does res.stop_reason/pending_calls look like at each level? Then pre-approve delegate (let it through in your gate) and see what the lead receives when the worker's create_ticket pauses. Finally, factor the lead-registry construction out of orchestrate so you can pass it to resume_agent after approving the delegate pause.
  14. ReWOO sketch (3.1): without implementing it, describe how you'd turn plan_and_execute into a ReWOO-style planner→worker→solver: which function disappears, what replaces needed_tools, and what does the #E1-style placeholder buy?
Hints for the exercises
  1. parse_react_step returns action=None, so the loop appends the reply plus a "Format error: use Thought/Action/Action Input or Final Answer." user message and calls the model again; recovery costs one extra model call (the corrective turn), not a crash.
  2. Compare ScriptedModel.requests: the native loop's messages carry tool_calls (name, arguments) and role="tool" results with tool_call_id; the text loop carries only strings, with Observation: ... as a user message. The native form is the structured one.
  3. _plan_from_obj reads only the first 8 entries (steps[:8]), so the ninth step is dropped without an error. The cap bounds a runaway planner (every step costs an executor run plus a replan call); the planner prompt also asks for 3-8 steps. Consider whether silent truncation is what you want and raise instead if not.
  4. The step becomes failed with result "[step ended: max_steps]". The replanner's prompt lists only done steps as completed and pending ones as remaining, so it sees the failure only through the "Latest step result" line; it can revise to retry or respond. If it says continue, the final-answer call summarises every non-skipped step, failed one included.
  5. max_rounds=0 runs the draft once and breaks before any critique: one run_agent (two model calls if it uses a tool) and no critic call, and rounds is 0 because it counts critiques.
  6. A verifier that re-applies issue_refund's own rules (delivered order, 0 < amount <= total) is more robust than a count comparison because it checks the policy itself, not one number that happens to match.
  7. registry.subset skips unknown names silently, so a typo leaves the specialist without that tool and nothing complains. Validate the names when building the Route (raise on any name not in registry.names()).
  8. The second delegate returns {"error": "delegation budget exhausted; answer with what you have"} as a normal tool result; the lead should answer from what it already has. Three such errors in a row would trip the circuit_breaker.
  9. The tool message is {"edited_by_user": true, "result": {...}} with the refund record showing 20.0, because resume_agent ran the edited call. Note that the assistant message still shows the original 30.0 arguments, which is why the edited_by_user flag is there.
  10. In a node. Nodes do work (including model calls); the transitions (goto) stay plain deterministic code so the path stays inspectable.
  11. Each event is written and flushed as it happens, so every event up to the last completed one is on disk; the event in flight is lost. (Flushing is not the same as fsync; a power cut can still lose the tail.)
  12. Start from the ModelReply shape in agent_loop.py: text, tool_calls (id, name, parsed arguments), finish_reason and usage; your adapter maps the provider's response onto it and raises on truncation.
  13. The lead's delegate call pauses first (stop_reason="paused", pending_calls=[delegate call]). A pause inside the worker does not propagate: the lead receives the explicit "needs human approval... nothing executed" error and the worker's create_ticket is not run.
  14. The #E1-style placeholder lets a later step name an earlier step's output before it exists, so the whole plan can be written in one planner call; the per-step executor/replanner loop disappears, needed_tools becomes a tool name plus argument template, and a final solver call composes the answer from the filled-in evidence.

Check yourself#

  1. What is an "agent pattern" in this lesson's sense, and what three ingredients does each one combine?
  2. Why did native tool calling replace the ReAct text format, and what carries the "thought" role on reasoning models today?
  3. What does stop_reason="truncated" protect you from, and why doesn't the loop execute the tool calls in that reply?
  4. In plan-and-execute, what is the difference between the plan (list of PlanStep) and the executor's message history — and why does that matter for context limits?
  5. Name the three replanner actions and when each fires.
  6. What does critique_and_revise's reflections list correspond to in the Reflexion paper, and what bounds the loop?
  7. Why is a verifier written in your code more trustworthy than a model critic, and what's an example deterministic verifier for the support agent?
  8. What does registry.subset(route.tool_names) buy a routed specialist, and what should the router do when it picks an unknown route?
  9. In orchestrate, why can't a worker see the lead's conversation, and what does the lead actually receive back?
  10. What are the three GateVerdict actions and which one pauses the whole run for a human?
  11. What do loop_detected, stalled and circuit_breaker each catch that max_steps doesn't?
  12. When would you choose a state machine over run_agent, and what's the hybrid pattern?
  13. What does TrajectoryLogger capture that a final-answer eval misses?
  14. Every pattern function in patterns.py accepts gate= — why does orchestrate pass it to both the lead's run_agent and each worker's, and what risk class does the delegate tool itself carry?
  15. How do ReWOO and LLMCompiler differ from plan_and_execute — which call does each one eliminate or parallelise?

Further resources#

← 08A.9 — Workflows vs Agents | Module 08A overview | 08A.11 — Reflection, Parallel Fan-Out and Agent-as-a-Tool →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close