08A.2 The Tool Loop: From One Round Trip to an Agent

Agents & multimodalLesson 2 of 158,790 words8 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

Lesson 03.5 taught you one complete tool round trip on every provider: define the tools, read the call the model returns, execute it safely, send the result back in the exact shape the provider demands, and read the final answer. This lesson takes the next step: wrapping that round trip in a loop that keeps going until the task is done. That loop — call the model, run the tools it asks for, feed the results back, repeat until a stop condition — is the core of every agent you'll build. You'll implement it by hand on all four providers, then build a provider-neutral version you can unit-test without any API key, budget it so it can't run away, stream it so users see progress, give it a human-approval hook, and learn what the providers' own SDK helpers automate (and what they hide).

What you'll learn

  • The agent loop as a state machine: call model → tool calls? → execute → append results → repeat, and the vocabulary (step, turn, trajectory, stop condition, budget) that Module 08A uses
  • What an "agent" is for this module — an LLM using tools in a loop to reach a goal, with the model controlling the flow — and what it isn't (not magic, not autonomous in the human sense, not always the right tool)
  • The loop implemented per provider with raw SDK calls: OpenAI Responses, Anthropic Messages, Gemini generate_content, and OpenRouter Chat Completions, including the state-handling differences that bite (reasoning items, thought signatures, pause_turn, max_tokens truncation, call IDs, parallel calls)
  • A canonical, provider-neutral loop over an injectable call_model with a ToolRegistry: schema generation from Pydantic, argument validation, timeouts, error results the model can read, and budgets (max steps, tokens, cost, wall-clock, per-tool limits) with stop conditions (final answer, finish tool, no calls, budget exhausted, loop detection, user cancel)
  • Bounded parallel execution (asyncio.gather with a semaphore, per 03.9), streaming a loop for a live UI (per 03.3), and tracing every step
  • The ScriptedModel fake: a scripted model that replays canned tool calls so the whole loop is unit-tested with real output and no API key
  • What the provider SDK helpers automate — Anthropic's tool_runner, the OpenAI Agents SDK, Gemini's automatic function calling — what they hide, and when to use them versus your own loop
  • The hard parts inside a loop: context growth from tool results, errors (tool exceptions, bad args, unknown tools, refusals, rate limits), idempotency of side-effect tools, and human approval hooks
  • Reasoning models inside loops (interleaved thinking, preserving reasoning data) and prompt caching across loop turns

What you don't need

  • API keys. The canonical loop, the registry, the budgets and all the tests run against a scripted fake model with pure Python — real output, no network. The per-provider samples are complete and runnable; their outputs are labelled illustrative.
  • Tool design judgement (naming, granularity, descriptions): that's 08A.6. This lesson builds a small working tool set so the loop has something real to call.
  • Workflows, agent patterns, memory, MCP, frameworks: 08A.9 onward. This lesson builds the loop those lessons stand on.

Setup

The samples need Python 3.11+, the module's provider SDKs and Pydantic. If you haven't created the shared project folder yet, run uv init llm-apis --bare --python 3.13 && cd llm-apis first (see lesson 03.1, Part 4), then add this lesson's packages:

bash
uv add openai anthropic google-genai pydantic python-dotenv
# or: pip install openai anthropic google-genai pydantic python-dotenv

These samples were written and checked against openai 3.42.1, anthropic 2.4.0, google-genai 2.34.0 and pydantic 2.14.3 as of November 2026. A plain install gives you the newest release, so if a newer SDK has renamed or retyped something, run uv pip list to see what you have and check the SDK's changelog before debugging the sample.

Keys go in .env as usual (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY). Part 2's per-provider samples and Part 5's helper samples need them; everything else runs with no key at all. No keys? Lesson 03.1, Part 12 sets up a free local stand-in.

Every runnable block starts with a comment giving its file name (# agent.py, # oai_loop.py, ...). Save each under that name in one folder and run it with uv run python <file>; this lesson's checks live in test_agent.py, a self-checking script — run it with uv run python test_agent.py (pytest collects nothing from it; later lessons that ship real pytest suites say so). The running example is a support and operations assistant for the fictional company from this module: it looks up orders, searches the docs (a stand-in for the Module 07 retriever), creates tickets, issues refunds behind an approval step, and runs reports. Every tool is a local Python function over in-memory fake data, so the whole module stays testable without services. Later lessons extend this same running example; where one ships a redesigned support_tools.py (different tool names or registry shape — 08A.6 gives the tools production-style names like orders_get), its intro says so — treat each lesson's file as authoritative for that lesson.


What you must be able to do after this lesson#

  • Build a provider-neutral tool loop with a step budget and stop condition
  • Explain the loop as call model, run tools, append results, repeat
  • Handle tool errors, bad arguments and unknown tools by returning results the model can read
  • Test a loop without an API key using a scripted fake model
  • Decide when to use a provider SDK helper instead of your own loop

Why this matters for an AI engineer#

One round trip answers one question with one batch of tool calls. Real work — "find order A17's status, check the refund policy, issue the refund if it's allowed, and open a ticket if it isn't" — needs many rounds, decisions between them, and hard limits so it can't spiral. The loop is where all of that lives, and it's where production agents succeed or fail.

You'll hear... You'll understand it after...
"It's not an agent, it's a loop with tools." 1.3 What an agent is — and what it isn't
"Why did the loop burn through our budget?" 3.3 Budgets and stop conditions
"The model kept calling the same tool forever." 3.4 Loop detection
"Why does the second provider call 400 on thinking blocks?" 2.5 The differences that bite
"We test the loop with a fake model, no API." 3.5 The ScriptedModel fake and 3.6 Unit tests
"Why not just use the SDK's agent runner?" Part 5: Provider SDK helpers
"A web page told the agent to email the database dump." 6.1 Context growth and 6.4 Human approval
"Our refund tool ran twice and the customer got two refunds." 6.3 Idempotency and retries

Part 1: From one round trip to a loop#

1.1 What 03.5 left you with#

Lesson 03.5 ended with its Part 17 preview: ten lines that wrap the round trip in for step in range(5). That preview was deliberately minimal — it had a step cap and nothing else. A production loop needs a great deal more, and this lesson builds it piece by piece. If the mechanics of one round trip (definitions, call IDs, result shapes, tool_choice, strict schemas, parallel calls) are fuzzy, re-read 03.5 first; this lesson assumes them and links back rather than re-teaching them.

1.2 The agent loop#

Strip away the provider differences and every tool-using agent is the same state machine:

flowchart TD
    A["User message + system prompt + tool definitions"] --> B["Call the model<br/>(one billed request)"]
    B --> C{"Stop signal says<br/>tool calls?"}
    C -->|"no: final answer or refusal"| D{"Stop condition<br/>met?"}
    C -->|"yes"| E["Append the WHOLE assistant turn<br/>(reasoning + calls, unchanged)"]
    E --> F["For each call: validate args,<br/>check permissions, run with timeout"]
    F --> G["Collect results (errors as data)"]
    G --> H["Append results in call order,<br/>matched by call ID"]
    H --> I{"Any stop condition?<br/>budget / loop / cancel"}
    I -->|"yes"| J["Return what we have:<br/>partial answer + trace"]
    I -->|"no"| B
    D -->|"yes"| K["Return the final answer + trace"]
    D -->|"no"| B

Five vocabulary words carry through the whole module:

  • Step (or turn): one model call plus the tool executions it triggered. Step 0 is the first call after the user's message.
  • Trajectory: the full record of steps — every model call, every tool call with its arguments, every result, every token count and latency. A trajectory is what you debug, evaluate and trace. 08A.14 makes trajectories first-class; this lesson starts the habit.
  • Stop condition: the rule that ends the loop. There are good ones (the model answered, the model called a finish tool, the user cancelled) and bad ones (budget exhausted, loop detected) — the loop must handle both.
  • Budget: the hard limits on steps, tokens, money and wall-clock time. A loop without a budget is a while True that can spend your entire quarterly API budget in an afternoon.
  • Tool result: what your code sends back per call — data on success, an error result on failure, never an exception (that's 03.5, Part 7).

1.3 What an agent is — and what it isn't#

For this module, an agent is: an LLM using tools in a loop to achieve a goal, with the model controlling the flow. Anthropic's "Building effective agents" post draws the same line — workflows follow predefined code paths, agents let the model direct its own process and tool use — and OpenAI's practical guide to building agents defines an agent as a system that "independently accomplish[es] tasks on your behalf", built from a model, tools and instructions.

What that definition rules out:

  • A single tool round trip is not an agent. It's a workflow step (08A.9 owns the distinction).
  • A loop over tools is not necessarily autonomous. If your code decides the order of calls and the model only fills arguments, that's a workflow wearing a loop's clothes. The agent part is the model choosing the next action.
  • An agent is not a separate kind of model. It's the same stateless LLM from Module 02/03, wrapped in code that gives it tools and lets it iterate. Every "agent" you ship is prompt + tools + this loop + guardrails.
  • An agent is not reliable because it's smart. Per-step success compounds: at 95% per step, a 20-step run succeeds about 36% of the time (02.10, Part 18 shows the arithmetic). The loop's job is to make failures visible and recoverable, not to assume they won't happen.

1.4 Why loops need budgets from line one#

The preview loop in 03.5, Part 17 ended with the warning: never ship an uncapped loop. This lesson makes the warning concrete. A runaway agent doesn't just loop — each step is a full-price model call with the whole history re-sent as input (03.5, 1.3), so costs grow superlinearly: step 10's request costs roughly what step 1's did, plus nine turns of accumulated context. A 50-step runaway on a long conversation can cost more than a thousand normal chat messages. Every loop in this lesson — including the very first sample — carries explicit budgets and a stop condition.


Part 2: The loop on every provider, with raw SDK calls#

The per-provider loop is 03.5, Part 4's round trip with the if replaced by a while. Before the four samples, the shared skeleton they all follow:

text
history = [user message]
for step in range(max_steps):
    response = call_model(history, tools)          # billed request
    append the WHOLE assistant turn to history     # reasoning data included, unchanged
    if no tool calls: return the answer
    results = execute every call (validate, timeout, errors as data)
    append all results in call order, matched by call ID
else:
    raise BudgetExhausted                          # never exit the loop silently

The differences that matter inside a loop (03.5 covers each in depth; here's what bites when you repeat it):

Concern What repeats badly if you get it wrong
Assistant-turn echo Dropping reasoning items / thinking blocks / thought signatures on any step poisons every later step, not just the next one (2.5)
Result shape One malformed result (missing ID, wrong slot, text before tool_result) is a 400 that kills the whole run mid-task
Stop signals pause_turn, max_tokens truncation and refusals aren't "tool calls" and aren't clean finishes — each needs its own branch (2.5)
Cost Every step resends the whole history: tools + system + all prior turns (03.5, 1.3)

The samples use the module's running example. First, the tools — a compact version of the pattern from 03.5, 2.1, now for the support assistant. Save this file next to the samples:

python
# support_tools.py
"""support_tools.py: the support assistant's tools, validated and dispatched safely (no network).

Same pattern as 03.5's weather_tools.py, for the Module 08A running example:
  1. argument models (Pydantic) are the single source of truth for each tool's schema;
  2. the functions are fake backends over in-memory data (the lesson needs no services);
  3. run_tool() parses -> validates -> runs with a timeout -> (output_text, is_error). Never raises;
  4. converter functions write the same tools in each provider's wire format.
"""
from __future__ import annotations

import json
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
from dataclasses import dataclass
from typing import Any, Callable, Literal

from pydantic import BaseModel, ConfigDict, Field, ValidationError


# --- 1. Argument models ------------------------------------------------------------------
class LookupOrder(BaseModel):
    """Look up an order by its ID. Returns status, items, total and tracking."""
    model_config = ConfigDict(extra="forbid")
    order_id: str = Field(description="Order ID like 'A17' or 'B22'")


class SearchDocs(BaseModel):
    """Search the company documentation and policy docs. Returns matching passages."""
    model_config = ConfigDict(extra="forbid")
    query: str = Field(description="What to search for, e.g. 'refund' or 'warranty'")
    max_results: int = Field(default=3, ge=1, le=10, description="How many passages to return")


class CreateTicket(BaseModel):
    """Open a support ticket for a customer issue."""
    model_config = ConfigDict(extra="forbid")
    subject: str = Field(description="Short ticket title")
    description: str = Field(description="What happened, in the customer's words")
    priority: Literal["low", "normal", "high", "urgent"] = "normal"


class IssueRefund(BaseModel):
    """Issue a refund on an order. WRITE action: requires human approval before running."""
    model_config = ConfigDict(extra="forbid")
    order_id: str = Field(description="Order to refund")
    amount: float = Field(gt=0, description="Refund amount in the order's currency")
    reason: str = Field(description="Why the refund is being issued")


class RunReport(BaseModel):
    """Run a canned operations report (open tickets by priority, refund totals, ...)."""
    model_config = ConfigDict(extra="forbid")
    report_name: Literal["open_tickets", "refund_totals", "order_backlog"]
    days: int = Field(default=7, ge=1, le=90, description="Look-back window in days")


class SubmitAnswer(BaseModel):
    """Submit the final answer to the user. Call this when the task is complete."""
    model_config = ConfigDict(extra="forbid")
    answer: str = Field(description="The complete final answer for the user")


# --- 2. The functions (fake backends; deterministic so outputs are stable) ----------------
_ORDERS = {
    "A17": {"status": "delivered", "total": 84.50, "items": ["USB-C hub"], "tracking": "1Z8842"},
    "B22": {"status": "returned", "total": 129.00, "items": ["Keyboard"], "tracking": None},
    "C09": {"status": "in_transit", "total": 45.99, "items": ["Webcam"], "tracking": "9X1120"},
}
_DOCS = [
    ("refunds", "Refunds are allowed within 30 days of delivery for unused items."),
    ("refunds", "Refunds over $100 require manager approval in addition to the standard check."),
    ("shipping", "Standard shipping takes 3-5 business days; express takes 1-2."),
    ("warranty", "All electronics carry a 1-year manufacturer warranty."),
]
_TICKETS: dict[str, dict[str, Any]] = {}
_refund_log: list[dict[str, Any]] = []


def lookup_order(order_id: str) -> dict[str, Any]:
    order = _ORDERS.get(order_id.strip().upper())
    if order is None:
        raise LookupError(f"no order {order_id!r}; known orders: {sorted(_ORDERS)}")
    return {"order_id": order_id.strip().upper(), **order}


def search_docs(query: str, max_results: int = 3) -> dict[str, Any]:
    q = query.lower()
    hits = [{"topic": t, "text": x} for t, x in _DOCS if q in t or q in x.lower()][:max_results]
    return {"query": query, "results": hits, "count": len(hits)}


def create_ticket(subject: str, description: str, priority: str = "normal") -> dict[str, Any]:
    ticket_id = f"T-{len(_TICKETS) + 1001}"
    _TICKETS[ticket_id] = {"subject": subject, "description": description, "priority": priority}
    return {"ticket_id": ticket_id, "status": "open", "priority": priority}


def issue_refund(order_id: str, amount: float, reason: str) -> dict[str, Any]:
    """WRITE tool: your approval layer must have cleared this call before it runs."""
    order = _ORDERS.get(order_id.strip().upper())
    if order is None:
        raise LookupError(f"no order {order_id!r}")
    if amount > order["total"]:
        raise ValueError(f"refund {amount} exceeds order total {order['total']}")
    refund = {"order_id": order_id.strip().upper(), "amount": amount, "reason": reason}
    _refund_log.append(refund)
    return {"refund_id": f"R-{len(_refund_log)}", **refund, "status": "issued"}


def run_report(report_name: str, days: int = 7) -> dict[str, Any]:
    if report_name == "open_tickets":
        by_priority = {}
        for t in _TICKETS.values():
            by_priority[t["priority"]] = by_priority.get(t["priority"], 0) + 1
        return {"report": report_name, "window_days": days, "open_tickets": len(_TICKETS),
                "by_priority": by_priority}
    if report_name == "refund_totals":
        return {"report": report_name, "window_days": days,
                "refunds_issued": len(_refund_log),
                "total_refunded": round(sum(r["amount"] for r in _refund_log), 2)}
    return {"report": report_name, "window_days": days,
            "orders": {k: v["status"] for k, v in _ORDERS.items()}}


def submit_answer(answer: str) -> dict[str, Any]:
    return {"answer": answer, "submitted": True}


# --- 3. Registry + safe dispatcher ---------------------------------------------------------
@dataclass(frozen=True)
class ToolSpec:
    args_model: type[BaseModel]
    fn: Callable[..., Any]
    risk: str = "read"          # read | write | destructive — drives approval (Part 6.4)
    timeout_s: float = 5.0

    @property
    def name(self) -> str:
        return _snake(self.args_model.__name__)   # LookupOrder -> lookup_order

    @property
    def description(self) -> str:
        return " ".join((self.args_model.__doc__ or "").split())


def _snake(class_name: str) -> str:
    out = []
    for i, ch in enumerate(class_name):
        if ch.isupper() and i:
            out.append("_")
        out.append(ch.lower())
    return "".join(out)


# The dispatch table: explicit names -> specs. The model can only ever reach these.
REGISTRY: dict[str, ToolSpec] = {
    "lookup_order": ToolSpec(LookupOrder, lookup_order),
    "search_docs": ToolSpec(SearchDocs, search_docs),
    "create_ticket": ToolSpec(CreateTicket, create_ticket, risk="write"),
    "issue_refund": ToolSpec(IssueRefund, issue_refund, risk="write"),
    "run_report": ToolSpec(RunReport, run_report),
    "submit_answer": ToolSpec(SubmitAnswer, submit_answer),
}
_pool = ThreadPoolExecutor(max_workers=8)


def run_tool(name: str, raw_args: str | dict[str, Any] | None) -> tuple[str, bool]:
    """Run one tool call. Returns (output_text, is_error); never raises."""
    spec = REGISTRY.get(name)
    if spec is None:
        return f"Error: unknown tool {name!r}. Available tools: {sorted(REGISTRY)}.", True
    if isinstance(raw_args, str):
        try:
            raw_args = json.loads(raw_args or "{}")
        except json.JSONDecodeError as exc:
            return f"Error: arguments are not valid JSON ({exc.msg}). Send a JSON object.", True
    try:
        args = spec.args_model.model_validate(raw_args or {})
    except ValidationError as exc:
        problems = "; ".join(f"{'.'.join(map(str, e['loc'])) or 'arguments'}: {e['msg']}"
                             for e in exc.errors())
        return f"Error: invalid arguments for {name}: {problems}. Fix them and call again.", True
    future = _pool.submit(spec.fn, **args.model_dump())
    try:
        # NB: this stops WAITING, not the work — the thread keeps running (6.3).
        result = future.result(timeout=spec.timeout_s)
    except FutureTimeout:
        return f"Error: {name} timed out after {spec.timeout_s:g} s. Try again later.", True
    except Exception as exc:
        return f"Error: {name} failed: {type(exc).__name__}: {exc}", True
    return json.dumps(result), False


# --- 4. The same tools in each provider's wire format ---------------------------------------
_BOUNDS = ("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum")


def json_schema(model: type[BaseModel]) -> dict[str, Any]:
    """A strict-mode-safe JSON Schema from a Pydantic model.

    The providers' strict modes accept a *subset* of JSON Schema (03.4): OpenAI wants every
    property listed in `required`, and Anthropic rejects numeric bounds (`minimum`, ...) with a
    400. So: drop cosmetic `title`s and `default`s, list every property as required, and move
    numeric bounds into the description. Pydantic still enforces the real bounds and defaults
    when run_tool validates the arguments, which is why the model-facing schema can be looser.
    """
    def walk(node: Any) -> Any:
        if isinstance(node, list):
            return [walk(v) for v in node]
        if not isinstance(node, dict):
            return node
        out: dict[str, Any] = {}
        for key, value in node.items():
            if key == "properties" and isinstance(value, dict):
                out[key] = {name: walk(sub) for name, sub in value.items()}  # names are data
            elif key == "default" or (key == "title" and isinstance(value, str)):
                continue
            else:
                out[key] = walk(value)
        bounds = {k: out.pop(k) for k in _BOUNDS if k in out}
        if bounds:
            note = ", ".join(f"{k}={v}" for k, v in bounds.items())
            out["description"] = f"{out.get('description', '')} ({note})".strip()
        if out.get("type") == "object" and "properties" in out:
            out["required"] = list(out["properties"])
            out["additionalProperties"] = False
        return out

    schema = walk(model.model_json_schema())
    schema.pop("description", None)
    return schema


def openai_responses_tools() -> list[dict[str, Any]]:
    return [{"type": "function", "name": n, "description": s.description,
             "parameters": json_schema(s.args_model), "strict": True}
            for n, s in REGISTRY.items()]


def openai_chat_tools() -> list[dict[str, Any]]:
    return [{"type": "function", "function": {"name": n, "description": s.description,
             "parameters": json_schema(s.args_model), "strict": True}}
            for n, s in REGISTRY.items()]


def anthropic_tools() -> list[dict[str, Any]]:
    return [{"name": n, "description": s.description,
             "input_schema": json_schema(s.args_model), "strict": True}
            for n, s in REGISTRY.items()]


def gemini_function_declarations() -> list[dict[str, Any]]:
    return [{"name": n, "description": s.description,
             "parameters_json_schema": json_schema(s.args_model)} for n, s in REGISTRY.items()]

The whole turn, every step, in one picture:

sequenceDiagram
    participant U as User
    participant App as Your loop
    participant M as Model
    participant T as Tools (your code)
    U->>App: task + history
    loop until a stop condition
        App->>M: history + tool definitions (billed request)
        M-->>App: assistant turn: text? + tool calls?
        App->>App: append WHOLE turn (reasoning included)
        alt tool calls present
            App->>T: validate args, approve if risky, run (bounded parallel)
            T-->>App: results or error-results, in call order
            App->>App: append results matched by call ID
        else no tool calls
            App-->>U: final answer + trace
        end
        App->>App: check budgets / loop detection / cancel
    end

2.1 OpenAI Responses#

The loop for the Responses API. The load-bearing lines: history += response.output appends every output item (reasoning items included — required on reasoning models, see Part 7); results go back as function_call_output items keyed by call_id; and the loop exits on max_steps, on no calls, or on a non-completed status.

python
# oai_loop.py
"""The agent loop on OpenAI Responses, raw SDK. Needs OPENAI_API_KEY in .env."""
import json
import sys
import time
from typing import Any

from dotenv import load_dotenv
from openai import OpenAI

from support_tools import openai_responses_tools, run_tool

load_dotenv()
client = OpenAI(timeout=120.0, max_retries=2)
MODEL = "gpt-6-luna"
MAX_STEPS = 8

SYSTEM = ("You are the support operations assistant for Acme. Use the tools to look things up "
          "and act. Issue refunds only after checking the order and the refund policy. "
          "When the task is done, answer the user in one short paragraph.")


def call_model(history: list[Any]) -> Any:
    return client.responses.create(
        model=MODEL, instructions=SYSTEM, input=history,
        tools=openai_responses_tools(), store=False,
        max_output_tokens=4_000,
    )


def run_agent(user_message: str) -> str:
    history: list[Any] = [{"role": "user", "content": user_message}]
    trace = []                                   # the trajectory: every step, logged
    for step in range(MAX_STEPS):
        t0 = time.perf_counter()
        response = call_model(history)
        latency_ms = round((time.perf_counter() - t0) * 1000)
        if response.status != "completed":       # incomplete at max_output_tokens, failed, ...
            raise RuntimeError(f"step {step}: response.status={response.status} "
                               f"{response.incomplete_details}")
        calls = [i for i in response.output if i.type == "function_call"]
        trace.append({"step": step, "calls": [c.name for c in calls],
                      "output_tokens": response.usage.output_tokens if response.usage else None,
                      "latency_ms": latency_ms})
        history += response.output               # reasoning items + calls, unchanged
        if not calls:
            return response.output_text
        for call in calls:
            output, is_error = run_tool(call.name, call.arguments)   # JSON string
            print(f"  step {step}: {call.name}({call.arguments}) -> {'ERR' if is_error else 'ok'}")
            history.append({"type": "function_call_output",
                            "call_id": call.call_id, "output": output})
    raise RuntimeError(f"step limit {MAX_STEPS} reached without a final answer; trace={trace}")


if __name__ == "__main__":
    question = sys.argv[1] if len(sys.argv) > 1 else (
        "Order A17 arrived damaged. Check the refund policy, then refund it and open a ticket.")
    print(run_agent(question))
Example output · illustrative6 lines
  step 0: search_docs({"query":"refund","max_results":3}) -> ok
  step 1: lookup_order({"order_id":"A17"}) -> ok
  step 2: issue_refund({"order_id":"A17","amount":84.5,"reason":"arrived damaged"}) -> ok
  step 3: create_ticket({"subject":"Damaged order A17","description":"Customer reports damage on delivery","priority":"high"}) -> ok
I checked the refund policy (30-day window), verified order A17 ($84.50, delivered), issued the
refund, and opened ticket T-1001 to follow up on the damage claim.

Two loop-specific points. First, store=False keeps the request stateless: the history you resend is the state, which is what makes the loop portable across providers (03.2, Part 7 covers the chained alternative and why it doesn't make steps cheaper). Second, the trace list is the embryo of the trajectory you'll log in production — keep it even in small loops.

2.2 Anthropic Messages#

python
# claude_loop.py
"""The agent loop on Anthropic Messages, raw SDK. Needs ANTHROPIC_API_KEY in .env."""
import json
import sys
import time
from typing import Any

import anthropic
from dotenv import load_dotenv

from support_tools import anthropic_tools, run_tool

load_dotenv()
client = anthropic.Anthropic(timeout=120.0, max_retries=2)
MODEL = "claude-haiku-5-5"
MAX_STEPS = 8
MAX_PAUSE_TURNS = 4                       # cap pause_turn resumes (server-tool loops)

SYSTEM = ("You are the support operations assistant for Acme. Use the tools to look things up "
          "and act. Issue refunds only after checking the order and the refund policy. "
          "When the task is done, answer the user in one short paragraph.")


def call_model(messages: list[Any], container: str | None = None) -> Any:
    return client.messages.create(
        model=MODEL, max_tokens=8_000, system=SYSTEM,
        tools=anthropic_tools(), messages=messages,
        container=container,                      # echo a paused turn's container id (5.4)
    )


def run_agent(user_message: str) -> str:
    messages: list[Any] = [{"role": "user", "content": user_message}]
    pauses = 0
    for step in range(MAX_STEPS):
        t0 = time.perf_counter()
        message = call_model(messages)
        latency_ms = round((time.perf_counter() - t0) * 1000)
        # pause_turn: the server-side tool loop paused; send the turn back unchanged (03.5, 5.4)
        container_id = None
        while message.stop_reason == "pause_turn" and pauses < MAX_PAUSE_TURNS:
            pauses += 1
            messages.append({"role": "assistant", "content": message.content})
            if message.container is not None:      # keep the same container or files are lost
                container_id = message.container.id
            message = call_model(messages, container=container_id)
        if message.stop_reason == "pause_turn":
            raise RuntimeError(f"pause_turn cap ({MAX_PAUSE_TURNS}) hit; "
                               "the server-tool loop is not converging")
        if message.stop_reason == "refusal":
            return "[refused] " + "".join(b.text for b in message.content if b.type == "text")
        if message.stop_reason == "max_tokens":
            # Truncated turn: a trailing tool_use may have cut-off input — never run it (03.5, 5.4)
            raise RuntimeError("reply truncated at max_tokens; raise the limit and retry")
        if message.stop_reason == "model_context_window_exceeded":
            raise RuntimeError("context window exceeded mid-run; compact history and retry")
        uses = [b for b in message.content if b.type == "tool_use"]
        print(f"  step {step}: stop={message.stop_reason} calls="
              f"{[(u.name, u.input) for u in uses]} {latency_ms}ms")
        messages.append({"role": "assistant", "content": message.content})  # thinking blocks too
        if not uses:
            return "".join(b.text for b in message.content if b.type == "text")
        results = []
        for block in uses:
            output, is_error = run_tool(block.name, block.input)   # input is a dict
            results.append({"type": "tool_result", "tool_use_id": block.id,
                            "content": output, "is_error": is_error})
        messages.append({"role": "user", "content": results})      # one message, results first
    raise RuntimeError(f"step limit {MAX_STEPS} reached; pauses={pauses}")


if __name__ == "__main__":
    print(run_agent(sys.argv[1] if len(sys.argv) > 1 else
                    "Order B22 was returned. Why can't I get a refund?"))
Example output · illustrative6 lines
  step 0: stop=tool_use calls=[('search_docs', {'query': 'refund', 'max_results': 3})] 812ms
  step 1: stop=tool_use calls=[('lookup_order', {'order_id': 'B22'})] 640ms
  step 2: stop=end_turn calls=[] 701ms
Order B22 was marked returned, but the refund policy only covers unused items within 30 days,
and a return already implies the item came back. I couldn't find a refund record for it — if it
was never refunded, please open a ticket and I'll escalate.

The Anthropic-specific traps inside a loop, all covered in 03.5: messages.append({"role": "assistant", "content": message.content}) must carry the whole content list — thinking blocks with signatures included — or later requests 400; all tool_result blocks go in one user message, first; and pause_turn (server-side tools like web search hitting their iteration cap) resumes by sending the paused turn back unchanged with the same tools — capped here by MAX_PAUSE_TURNS because a turn that pauses repeatedly is a cost runaway, and echoing the response's container id when there is one, or files from earlier in the turn are lost. Three more stop signals get their own branches: refusal returns marked text, while max_tokens and model_context_window_exceeded raise — a truncated or over-window reply must never be executed or returned as if complete (03.5, 5.4); retry with a larger max_tokens or a compacted history. On Claude 5.1+ models, changing tools mid-run invalidates thinking blocks (03.5, 14.5) — so declare the full tool set up front.

2.3 Gemini generate_content#

python
# gemini_loop.py
"""The agent loop on Gemini generate_content, raw SDK. Needs GEMINI_API_KEY in .env."""
import json
import sys
import time
from typing import Any

from dotenv import load_dotenv
from google import genai
from google.genai import types

from support_tools import gemini_function_declarations, run_tool

load_dotenv()
client = genai.Client()
MODEL = "gemini-3.8-flash"
MAX_STEPS = 8

SYSTEM = ("You are the support operations assistant for Acme. Use the tools to look things up "
          "and act. Issue refunds only after checking the order and the refund policy. "
          "When the task is done, answer the user in one short paragraph.")

config = types.GenerateContentConfig(
    system_instruction=SYSTEM,
    tools=[types.Tool(function_declarations=[
        types.FunctionDeclaration(**d) for d in gemini_function_declarations()])],
    max_output_tokens=4_000,
)


def call_model(contents: list[types.Content]) -> Any:
    return client.models.generate_content(model=MODEL, contents=contents, config=config)


def run_agent(user_message: str) -> str:
    contents: list[types.Content] = [types.Content(
        role="user", parts=[types.Part.from_text(text=user_message)])]
    for step in range(MAX_STEPS):
        t0 = time.perf_counter()
        response = call_model(contents)
        latency_ms = round((time.perf_counter() - t0) * 1000)
        candidate = response.candidates[0] if response.candidates else None
        if candidate is None or candidate.finish_reason not in (
                types.FinishReason.STOP, types.FinishReason.MAX_TOKENS):
            raise RuntimeError(f"step {step}: blocked or failed: "
                               f"{candidate.finish_reason if candidate else response.prompt_feedback}")
        if candidate.finish_reason == types.FinishReason.MAX_TOKENS:
            # Truncated turn: any function calls it carries have cut-off arguments —
            # never run them (03.5, 5.4). Raise the limit and retry the step.
            raise RuntimeError("reply truncated at max_output_tokens; raise the limit and retry")
        calls = response.function_calls or []
        model_turn = candidate.content
        print(f"  step {step}: finish={candidate.finish_reason} "
              f"calls={[(c.name, c.args) for c in calls]} {latency_ms}ms")
        if model_turn:
            contents.append(model_turn)              # thought signatures intact
        if not calls:
            return response.text or ""
        parts: list[types.Part] = []
        for call in calls:
            output, is_error = run_tool(call.name or "", call.args)
            payload = {"error": output} if is_error else {"output": json.loads(output)}
            parts.append(types.Part(function_response=types.FunctionResponse(
                id=call.id, name=call.name, response=payload)))
        contents.append(types.Content(role="user", parts=parts))   # all in one turn, call order
    raise RuntimeError(f"step limit {MAX_STEPS} reached without a final answer")


if __name__ == "__main__":
    print(run_agent(sys.argv[1] if len(sys.argv) > 1 else
                    "How many open tickets do we have? Run the report."))
Example output · illustrative4 lines
  step 0: finish=FinishReason.STOP calls=[('run_report', {'report_name': 'open_tickets', 'days': 7})] 690ms
  step 1: finish=FinishReason.STOP calls=[] 540ms
There are currently 0 open tickets in the system for the last 7 days (the ticket store starts
empty; tickets created during this conversation would appear here).

Gemini's loop quirks: the finish reason stays STOP even when the model calls functions, so you detect calls from response.function_calls, not the finish reason; function_response parts go in one user Content after all calls, in call order, with id echoed when present; and the model Content you append carries thought_signature data the next request needs (Part 7). A MAX_TOKENS finish means the reply was cut off — the code raises before touching any calls, because a truncated call's arguments can't be trusted; raise max_output_tokens and retry the step (03.5, 5.4).

2.4 OpenRouter (Chat Completions)#

OpenRouter's primary format is Chat Completions, so its loop is the same shape as OpenAI's Chat API with a different base URL and a vendor/model ID. Tool support is per-model — check supported_parameters for the model you route to (03.5, 2.7):

python
# or_loop.py
"""The agent loop through OpenRouter (Chat Completions). Needs OPENROUTER_API_KEY in .env."""
import os
import sys
from typing import Any

from dotenv import load_dotenv
from openai import OpenAI

from support_tools import openai_chat_tools, run_tool

load_dotenv()
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
    default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "Support assistant"},
)
MODEL = "anthropic/claude-haiku-5.5"       # any vendor/model with tool support
MAX_STEPS = 8

SYSTEM = "You are the support operations assistant for Acme. Use tools to look things up and act."


def run_agent(user_message: str) -> str:
    messages: list[Any] = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": user_message},
    ]
    for step in range(MAX_STEPS):
        completion = client.chat.completions.create(
            model=MODEL, messages=messages,
            tools=openai_chat_tools(), max_completion_tokens=4_000)
        choice = completion.choices[0]
        if choice.finish_reason == "length":
            raise RuntimeError("reply truncated at max_completion_tokens; raise the limit and retry")
        if choice.finish_reason not in ("stop", "tool_calls"):   # e.g. content_filter: not an answer
            raise RuntimeError(f"step {step}: unexpected finish_reason={choice.finish_reason!r}")
        calls = choice.message.tool_calls or []
        print(f"  step {step}: finish={choice.finish_reason} "
              f"calls={[(c.function.name, c.function.arguments) for c in calls]}")
        messages.append(choice.message.model_dump(exclude_none=True))
        if choice.finish_reason != "tool_calls" or not calls:
            return choice.message.content or ""
        for call in calls:
            output, is_error = run_tool(call.function.name, call.function.arguments)
            messages.append({"role": "tool", "tool_call_id": call.id, "content": output})
    raise RuntimeError(f"step limit {MAX_STEPS} reached without a final answer")


if __name__ == "__main__":
    print(run_agent(sys.argv[1] if len(sys.argv) > 1 else "Look up order C09 and tell me its status."))
Example output · illustrative3 lines
  step 0: finish=tool_calls calls=[('lookup_order', '{"order_id": "C09"}')]
  step 1: finish=stop calls=[]
Order C09 is a webcam order for $45.99, currently in transit with tracking number 9X1120.

The OpenRouter caveats that matter in a loop: the underlying provider's quirks pass through (a Claude model behind OpenRouter may return reasoning_details you must echo — Part 7); strict on tool schemas may be stripped unless the right beta header is sent (03.5, Part 10), so your validation layer is the real guarantee; and which models accept parallel_tool_calls varies — check supported_parameters. One more: the sample checks finish_reason against an allow-list (stop, tool_calls) and raises on anything else, not only on "length" — a content_filter finish would otherwise surface filtered or empty text as a normal answer.

2.5 The differences that bite, collected#

Difference OpenAI Responses Anthropic Gemini generate_content OpenRouter (Chat)
Detect calls by function_call items in output stop_reason == "tool_use" function_calls parts (finish_reason stays STOP) finish_reason == "tool_calls"
Arguments arrive as JSON string dict dict JSON string
ID to echo call_id (not id) tool_use.id function_call.id + name tool_calls[].id
Results go function_call_output items tool_result blocks, one user msg function_response parts, one turn role:"tool" messages
Whole-turn echo history += response.output content incl. thinking model Content incl. signatures model_dump(exclude_none=True)
Loop extras status != "completed" pause_turn, refusal, max_tokens mid-call MAX_TOKENS, MALFORMED_FUNCTION_CALL finish_reason == "length"
tool_choice auto/required/none/named auto/any/tool/none (+ disable_parallel_tool_use) AUTO/ANY/NONE/VALIDATED per-model

None of the four samples sets tool_choice — they all let the model decide (auto), which is right for a general assistant. Inside a loop it earns its place at the boundaries: "none"/NONE on the last allowed step forces an answer instead of another call (better a plain answer than a budget_exhausted), "required"/"any"/ANY suits a classification-first step, and a named choice pins the finish tool when you want the answer in a fixed shape. The wire shapes (03.5, Part 3 has the full table and caveats):

python
# tool_choice is a per-request parameter — pass it on call_model, e.g. to force
# submit_answer on the final step or "none" to forbid further calls:
#
#   OpenAI Responses :  tool_choice="required"  or  {"type": "function", "name": "submit_answer"}
#   Anthropic        :  tool_choice={"type": "any"}  or  {"type": "tool", "name": "submit_answer"}
#   Gemini           :  types.ToolConfig(function_calling_config=types.FunctionCallingConfig(
#                          mode="ANY", allowed_function_names=["submit_answer"]))
#   OpenRouter/Chat  :  tool_choice="required"  or  {"type": "function", "function": {"name": "submit_answer"}}
#
# Caveats: forced choice skips thinking-prefill on Claude; changing tool_choice
# mid-run breaks Anthropic prompt caching (03.5, 3.3-3.5). And the four samples
# run a batch's calls sequentially for clarity — the wire format is identical;
# execute them concurrently as in 4.1.

The pattern to internalize: the loop is identical; the adapter isn't. Part 3 exploits exactly that.


Part 3: The canonical loop — provider-neutral, testable, budgeted#

The four Part-2 loops share one shape. This part factors that shape into a single run_agent function that works with any model backend: a hosted provider (through a thin adapter), the local stand-in, or a scripted fake in tests. The design has four pieces:

  • ChatAdapter — the provider seam. Four methods translate between the loop's canonical events and the provider's wire format. Part 2's samples are adapters written inline; here they become a protocol.
  • ToolRegistry — the support_tools.REGISTRY mapping (name → ToolSpec) plus the execution path: validate → approve → run with timeout → truncate → error-as-data.
  • Budget + stop conditions — every limit the loop enforces, checked every step.
  • run_agent / resume_agent — the loop itself, plus tracing and the approval pause/resume.

3.1 The adapter seam#

python
# agent.py (1 of 3): types, budget, adapter protocol — provider-neutral
"""agent.py: the canonical tool loop. Provider-neutral core + budgets + approvals + tracing.

The loop never imports a provider SDK. A ChatAdapter turns "our history" into "one model
turn" and knows where assistant turns and tool results go on the wire. Part 2's four
samples are adapters written inline; OpenAIResponsesAdapter below is the same code as
a class. ScriptedModel (scripted.py) is a third adapter that replays canned turns.
"""
from __future__ import annotations

import asyncio
import json
import logging
import time
from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable, Mapping, Protocol

from support_tools import REGISTRY, ToolSpec

log = logging.getLogger("agent")


@dataclass
class ToolCall:
    """One normalized tool call, whatever the provider called it."""
    id: str
    name: str
    arguments: dict[str, Any]          # already parsed (raw string was json.loads'ed)
    native: Any = None                 # provider-native call object, for audit/echo
    argument_error: str | None = None  # set when the raw args weren't a JSON object;
                                       # _execute_one turns it into an error result


@dataclass
class ToolResult:
    call_id: str
    name: str
    output: str
    is_error: bool


@dataclass
class ModelTurn:
    """One normalized model turn: text, tool calls, and the native payload to replay."""
    text: str = ""
    tool_calls: list[ToolCall] = field(default_factory=list)
    finish_reason: str = ""
    usage: dict[str, int] = field(default_factory=dict)   # input_tokens / output_tokens / ...
    native: Any = None                # provider-native assistant turn, appended unchanged
    refusal: bool = False


@dataclass
class Budget:
    """Every hard limit the loop enforces. There is no 'unlimited' option on purpose."""
    max_steps: int = 8                          # model calls per run
    max_output_tokens: int = 60_000             # summed output tokens over all steps
    max_total_tokens: int | None = None         # opt-in: input+output summed — the real
                                                # runaway guard, since input dominates loop cost
    max_seconds: float = 300.0                  # wall clock for the whole run
    max_calls_per_tool: int = 6                 # one tool can't be hammered
    max_parallel_calls: int = 4                 # bound on asyncio.gather
    loop_threshold: int = 3                     # identical call signature -> stop
    max_result_chars: int = 8_000               # truncate giant tool outputs
    finish_tool: str | None = "submit_answer"   # calling it ends the loop with its output
    max_cost_usd: float | None = None           # optional; needs price_per_mtok
    price_per_mtok: dict[str, float] | None = None   # {"input": x, "output": y} USD/1M tokens


class ChatAdapter(Protocol):
    """The provider seam. `history` is provider-native; the loop only sees ModelTurn/ToolResult.

    Contract for `call`: enforce the provider's stop signals *inside* the adapter — raise on
    incomplete/truncated/failed responses (the loop lets adapter errors propagate to your retry
    layer, 03.8), set `refusal=True` for refusals, and only return a call-free `ModelTurn` for a
    genuinely complete answer. `finish_reason` is recorded for the trace; the loop trusts the
    adapter to have acted on it."""
    def initial_history(self, user_message: str) -> list[Any]: ...
    async def call(self, history: list[Any]) -> ModelTurn: ...
    def append_assistant(self, history: list[Any], turn: ModelTurn) -> None: ...
    def append_results(self, history: list[Any], turn: ModelTurn, results: list[ToolResult]) -> None: ...


# --- results -------------------------------------------------------------------------------
@dataclass
class PendingApproval:
    call_id: str
    name: str
    arguments: dict[str, Any]
    risk: str


@dataclass
class TraceEntry:
    step: int
    model_latency_ms: float
    usage: dict[str, int]
    calls: list[dict[str, Any]]
    approvals: list[str]
    note: str = ""


@dataclass
class AgentResult:
    status: str                    # completed | awaiting_approval | budget_exhausted
                                   # | loop_detected | cancelled | error
    answer: str = ""
    steps: int = 0
    trace: list[TraceEntry] = field(default_factory=list)
    state: dict[str, Any] | None = None     # resume state when awaiting_approval
    pending: PendingApproval | None = None
    spent: dict[str, Any] = field(default_factory=dict)


class _Deferred(Exception):
    """Internal: a tool call needs human approval before the batch can finish."""
    def __init__(self, pending: PendingApproval) -> None:
        self.pending = pending
        super().__init__(f"approval deferred for {pending.name}")

3.2 The loop#

python
# agent.py (2 of 3): execution, budgets, stop conditions, the loop itself
_APPROVER = Callable[[PendingApproval], Awaitable[str]]   # "approve" | "deny" | "defer"


def _signature(call: ToolCall) -> str:
    """Identity of a call for loop detection: same tool + same args = same signature."""
    return call.name + "|" + json.dumps(call.arguments, sort_keys=True, default=str)


def _truncate(text: str, limit: int) -> str:
    """Head+tail elision with a marker the model can read (04.7, 5.2's 'truncate with markers')."""
    if len(text) <= limit:
        return text
    head = text[: limit * 2 // 3]
    tail = text[-limit // 3 :]
    elided = len(text) - len(head) - len(tail)
    return f"{head}\n[... {elided:,} chars elided — result truncated at {limit:,} chars ...]\n{tail}"


async def _execute_one(call: ToolCall, spec: ToolSpec | None, budget: Budget,
                       approver: _APPROVER | None) -> ToolResult:
    """Validate -> approve -> run -> truncate. Every failure becomes an error result.
    Validation runs *before* approval so the human reviews the parsed arguments,
    not raw model output — and a malformed call never burns an approval."""
    if spec is None:
        return ToolResult(call.id, call.name,
                          f"Error: unknown tool {call.name!r}.", True)
    if call.argument_error is not None:
        return ToolResult(call.id, call.name,
                          f"Error: {call.name} arguments were not valid JSON: "
                          f"{call.argument_error}. Resend them as a JSON object.", True)
    try:
        args = spec.args_model.model_validate(call.arguments or {})
    except Exception as exc:                       # pydantic ValidationError
        problems = "; ".join(
            f"{'.'.join(map(str, e['loc'])) or 'arguments'}: {e['msg']}" for e in exc.errors())
        return ToolResult(call.id, call.name,
                          f"Error: invalid arguments for {call.name}: {problems}. "
                          f"Fix them and call again.", True)
    if spec.risk in ("write", "destructive"):
        if approver is None:
            # No approver configured means NOBODY approved, not "everything is
            # approved": a write tool never runs by default.
            return ToolResult(call.id, call.name,
                              f"Error: {call.name} is a {spec.risk} tool and this run has no "
                              f"approver, so it was not run. Tell the user it needs approval.",
                              True)
        pending = PendingApproval(call.id, call.name, args.model_dump(), spec.risk)
        decision = await approver(pending)
        if decision == "defer":
            raise _Deferred(pending)
        if decision == "deny":
            return ToolResult(call.id, call.name,
                              f"Error: {call.name} was denied by the reviewer. Do not retry it; "
                              f"tell the user it needs approval.", True)
    try:
        # NB: wait_for stops WAITING, not the work — the thread keeps running to
        # completion. For side-effect tools a "timed out" call may still commit;
        # that's why idempotency keys live inside the tool (6.3), not in this timeout.
        output = await asyncio.wait_for(
            asyncio.to_thread(spec.fn, **args.model_dump()), timeout=spec.timeout_s)
        text = output if isinstance(output, str) else json.dumps(output)
        return ToolResult(call.id, call.name, _truncate(text, budget.max_result_chars), False)
    except asyncio.TimeoutError:
        return ToolResult(call.id, call.name,
                          f"Error: {call.name} timed out after {spec.timeout_s:g} s.", True)
    except Exception as exc:
        return ToolResult(call.id, call.name,
                          f"Error: {call.name} failed: {type(exc).__name__}: {exc}", True)


async def _execute_calls(turn: ModelTurn, tools: Mapping[str, ToolSpec], budget: Budget,
                         approver: _APPROVER | None) -> list[ToolResult]:
    """Run one batch of calls. Bounded parallelism; results stay in CALL ORDER."""
    sem = asyncio.Semaphore(budget.max_parallel_calls)

    async def one(call: ToolCall) -> ToolResult:
        async with sem:
            return await _execute_one(call, tools.get(call.name), budget, approver)

    # gather preserves order; return_exceptions shouldn't trigger (errors are data)
    return list(await asyncio.gather(*(one(c) for c in turn.tool_calls)))

The loop itself. Note what it does not do: it never parses provider responses, never builds wire messages, never retries a model call (that's 03.8's layer — wrap adapter.call).

python
# agent.py (3 of 3): run_agent, resume_agent, OpenAIResponsesAdapter, tracing
async def run_agent(
    adapter: ChatAdapter,
    user_message: str | None = None,
    *,
    tools: Mapping[str, ToolSpec] = REGISTRY,
    budget: Budget | None = None,
    approver: _APPROVER | None = None,
    cancel_event: asyncio.Event | None = None,
    resume_state: dict[str, Any] | None = None,
    resume_decision: str = "approve",
) -> AgentResult:
    """Run the tool loop until a stop condition. Returns an AgentResult, never raises for
    expected stops (budget/loop/cancel/approval); unexpected adapter errors propagate.
    Pass resume_state + resume_decision (or use resume_agent) to continue a paused run.
    Without an `approver`, write and destructive tools are refused, not run."""
    budget = budget or Budget()
    trace: list[TraceEntry] = []
    signatures: dict[str, int] = {}
    call_counts: dict[str, int] = {}
    spent_in = 0
    spent_out = 0
    spent_cost = 0.0
    started = time.monotonic()
    start_step = 0
    turn: ModelTurn | None = None

    async def finish_early(status: str, answer: str = "", pending=None) -> AgentResult:
        state = None
        if status == "awaiting_approval":
            state = {
                "history": history, "turn": _turn_to_state(turn),
                "pending_calls": [_call_to_state(c) for c in turn.tool_calls],
                "pending_call_id": pending.call_id if pending else None,
                "step": step, "signatures": signatures, "call_counts": call_counts,
                "spent_input": spent_in, "spent_output": spent_out, "spent_cost": spent_cost,
                "trace": [vars(t) for t in trace],
            }
        return AgentResult(status=status, answer=answer, steps=step + 1, trace=trace,
                           state=state, pending=pending,
                           spent={"input_tokens": spent_in, "output_tokens": spent_out,
                                  "cost_usd": round(spent_cost, 6)})

    if resume_state is not None:
        # --- resume a run paused at awaiting_approval -------------------------------------
        history = resume_state["history"]
        signatures.update(resume_state["signatures"])
        call_counts.update(resume_state["call_counts"])
        spent_in = resume_state.get("spent_input", 0)
        spent_out = resume_state["spent_output"]
        spent_cost = resume_state["spent_cost"]
        trace.extend(TraceEntry(**t) for t in resume_state["trace"])
        ts = resume_state["turn"]
        turn = ModelTurn(text=ts["text"], finish_reason=ts["finish_reason"],
                         usage=ts["usage"], refusal=ts["refusal"],
                         tool_calls=[ToolCall(id=c["id"], name=c["name"], arguments=c["arguments"],
                                              argument_error=c.get("argument_error"))
                                     for c in resume_state["pending_calls"]])
        pid = resume_state.get("pending_call_id")

        async def resolved(p: PendingApproval) -> str:
            if p.call_id == pid:                     # the call a human just decided on
                return resume_decision
            return await approver(p) if approver else "deny"   # no approver: nobody approved

        try:
            results = await _execute_calls(turn, tools, budget, resolved)
        except _Deferred as d:                       # a DIFFERENT call in the batch also needs review
            return AgentResult(status="awaiting_approval",
                               steps=resume_state["step"] + 1, trace=trace,
                               state={**resume_state, "pending_call_id": d.pending.call_id},
                               pending=d.pending)
        adapter.append_results(history, turn, results)
        final = next((r for r in results if r.name == budget.finish_tool and not r.is_error), None)
        if final is not None:
            try:
                answer = json.loads(final.output).get("answer", final.output)
            except Exception:
                answer = final.output
            return AgentResult(status="completed", answer=str(answer),
                               steps=resume_state["step"] + 1, trace=trace,
                               spent={"input_tokens": spent_in, "output_tokens": spent_out,
                                      "cost_usd": round(spent_cost, 6)})
        start_step = resume_state["step"] + 1        # continue the loop where it paused
    else:
        history = adapter.initial_history(user_message)

    step = start_step - 1
    for step in range(start_step, budget.max_steps):
        if cancel_event is not None and cancel_event.is_set():
            return await finish_early("cancelled")
        if time.monotonic() - started > budget.max_seconds:
            return await finish_early("budget_exhausted", "Time budget exceeded.")
        if spent_out >= budget.max_output_tokens:
            return await finish_early("budget_exhausted", "Token budget exceeded.")
        if budget.max_total_tokens is not None and spent_in + spent_out >= budget.max_total_tokens:
            return await finish_early("budget_exhausted", "Total token budget exceeded.")
        if budget.max_cost_usd is not None and spent_cost >= budget.max_cost_usd:
            return await finish_early("budget_exhausted", "Cost budget exceeded.")

        t0 = time.perf_counter()
        turn = await adapter.call(history)               # may raise: caller's retry layer
        latency_ms = (time.perf_counter() - t0) * 1000
        spent_in += turn.usage.get("input_tokens", 0)
        spent_out += turn.usage.get("output_tokens", 0)
        if budget.price_per_mtok:
            spent_cost += (turn.usage.get("input_tokens", 0) * budget.price_per_mtok.get("input", 0)
                           + turn.usage.get("output_tokens", 0) * budget.price_per_mtok.get("output", 0)) / 1e6

        adapter.append_assistant(history, turn)          # whole turn, reasoning included
        calls = turn.tool_calls
        trace.append(TraceEntry(step, round(latency_ms, 1), dict(turn.usage),
                                [{"name": c.name, "args": c.arguments} for c in calls], []))

        if turn.refusal:
            return await finish_early("error", "[refused] " + turn.text)
        if not calls:
            return await finish_early("completed", turn.text)

        # --- stop conditions evaluated BEFORE executing -------------------------------
        for c in calls:
            sig = _signature(c)
            signatures[sig] = signatures.get(sig, 0) + 1
            call_counts[c.name] = call_counts.get(c.name, 0) + 1
            if signatures[sig] >= budget.loop_threshold:
                return await finish_early(
                    "loop_detected",
                    f"Loop detected: {c.name}{c.arguments} repeated {signatures[sig]} times.")
            if call_counts[c.name] > budget.max_calls_per_tool:
                return await finish_early(
                    "budget_exhausted",
                    f"Tool {c.name} exceeded its per-tool call limit.")

        # --- execute the batch ----------------------------------------------------------
        try:
            results = await _execute_calls(turn, tools, budget, approver)
        except _Deferred as d:
            return await finish_early("awaiting_approval", pending=d.pending)

        # finish tool: its output IS the answer
        final = next((r for r in results if r.name == budget.finish_tool and not r.is_error), None)
        adapter.append_results(history, turn, results)
        if final is not None:
            try:
                answer = json.loads(final.output).get("answer", final.output)
            except Exception:
                answer = final.output
            return await finish_early("completed", str(answer))

    return AgentResult(status="budget_exhausted",
                       answer=f"Step limit {budget.max_steps} reached.",
                       steps=budget.max_steps, trace=trace,
                       spent={"input_tokens": spent_in, "output_tokens": spent_out,
                              "cost_usd": round(spent_cost, 6)})


async def resume_agent(state: dict[str, Any], adapter: ChatAdapter, decision: str,
                       *, tools: Mapping[str, ToolSpec] = REGISTRY,
                       budget: Budget | None = None,
                       approver: _APPROVER | None = None,
                       cancel_event: asyncio.Event | None = None) -> AgentResult:
    """Continue a run paused at `awaiting_approval`. `decision` ("approve"/"deny") answers
    the pending call; every other risky call in the batch is re-checked by `approver`.
    Sibling calls may have already run once — keep tools idempotent (6.3)."""
    return await run_agent(adapter, resume_state=state, resume_decision=decision,
                           tools=tools, budget=budget, approver=approver,
                           cancel_event=cancel_event)


def _turn_to_state(turn: ModelTurn) -> dict[str, Any]:
    return {"text": turn.text, "finish_reason": turn.finish_reason,
            "usage": turn.usage, "refusal": turn.refusal}


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


def _parse_call_arguments(raw: str | None) -> tuple[dict[str, Any], str | None]:
    """function_call.arguments is a JSON *string*. A malformed one must not kill the run —
    it becomes an error result the model can read and fix (errors are data, 6.2)."""
    if not raw:
        return {}, None
    try:
        parsed = json.loads(raw)
    except json.JSONDecodeError as exc:
        return {}, f"{exc.msg} (at char {exc.pos})"
    if not isinstance(parsed, dict):
        return {}, "arguments must be a JSON object"
    return parsed, None


# --- the OpenAI Responses adapter (the same wire code as 2.1, as a class) -------------------
class OpenAIResponsesAdapter:
    """ChatAdapter over the Responses API. history = the `input` item list."""
    def __init__(self, client: Any, model: str, system: str, tools: list[dict[str, Any]],
                 max_output_tokens: int = 4_000) -> None:
        self.client, self.model, self.system = client, model, system
        self.tools, self.max_output_tokens = tools, max_output_tokens

    def initial_history(self, user_message: str) -> list[Any]:
        return [{"role": "user", "content": user_message}]

    async def call(self, history: list[Any]) -> ModelTurn:
        response = await self.client.responses.create(
            model=self.model, instructions=self.system, input=history,
            tools=self.tools, store=False, max_output_tokens=self.max_output_tokens)
        if response.status != "completed":
            raise RuntimeError(f"response.status={response.status} {response.incomplete_details}")
        calls = []
        for i in response.output:
            if i.type != "function_call":
                continue
            args, arg_err = _parse_call_arguments(i.arguments)
            calls.append(ToolCall(id=i.call_id, name=i.name, arguments=args,
                                  argument_error=arg_err, native=i))
        return ModelTurn(
            text=response.output_text,
            tool_calls=calls,
            finish_reason=response.status,
            usage={"input_tokens": response.usage.input_tokens if response.usage else 0,
                   "output_tokens": response.usage.output_tokens if response.usage else 0},
            native=list(response.output))

    def append_assistant(self, history: list[Any], turn: ModelTurn) -> None:
        history.extend(turn.native or [])            # reasoning items + calls, unchanged

    def append_results(self, history: list[Any], turn: ModelTurn, results: list[ToolResult]) -> None:
        history.extend({"type": "function_call_output", "call_id": r.call_id, "output": r.output}
                       for r in results)

3.3 Budgets and stop conditions#

Every limit lives in Budget, and every stop is a named status on AgentResult — a run never ends silently:

Stop condition status Trigger
Final answer completed A turn with no tool calls (or a finish_tool result)
Refusal error The model declined (turn.refusal)
Step limit budget_exhausted max_steps model calls used
Token limit budget_exhausted Summed output_tokens ≥ max_output_tokens
Total tokens budget_exhausted input + output tokens ≥ max_total_tokens (opt-in)
Cost limit budget_exhausted Estimated spend ≥ max_cost_usd (needs price_per_mtok)
Wall clock budget_exhausted max_seconds elapsed
Per-tool limit budget_exhausted One tool called > max_calls_per_tool times
Loop detected loop_detected Identical (name, args) signature ≥ loop_threshold
Human needed awaiting_approval A write/destructive call deferred by the approver
User cancel cancelled cancel_event set between steps

Four design choices worth noting:

  • Loop detection counts signatures, not just repeats. lookup_order({"order_id":"A17"}) three times in a row is almost certainly a loop; the same signature at steps 1, 5 and 9 with different calls between might be legitimate re-checking — the threshold (default 3) is the knob, and 08A.14 adds stall detection on top.
  • Budgets are checked before each model call, so a run that hits its limit never makes one more billed request than necessary.
  • max_output_tokens counts only what the model writes. Input tokens — the whole history resent every step, which is where a runaway loop actually bleeds — are only counted if you set max_total_tokens (or max_cost_usd with a price table). Set max_total_tokens in production: it's the honest runaway guard.
  • max_cost_usd is opt-in because it needs a price table; 03.7 owns real cost accounting — wire price_per_mtok from there in production rather than hard-coding prices here.

3.4 Loop detection#

python
# loop_detect.py — the signature mechanism, standalone (pure Python, real output below)
import json

def signature(name: str, arguments: dict) -> str:
    return name + "|" + json.dumps(arguments, sort_keys=True, default=str)

calls = [
    ("lookup_order", {"order_id": "A17"}),
    ("search_docs", {"query": "refund"}),
    ("lookup_order", {"order_id": "A17"}),   # same signature as step 0 — count = 2
    ("lookup_order", {"order_id": "A17"}),   # count = 3 -> loop_detected at threshold 3
]
counts: dict[str, int] = {}
for name, args in calls:
    sig = signature(name, args)
    counts[sig] = counts.get(sig, 0) + 1
    print(f"{counts[sig]}x  {sig}")
print("loop_detected:", any(n >= 3 for n in counts.values()))
Output5 lines
1x  lookup_order|{"order_id": "A17"}
1x  search_docs|{"query": "refund"}
2x  lookup_order|{"order_id": "A17"}
3x  lookup_order|{"order_id": "A17"}
loop_detected: True

sort_keys=True matters: {"a":1,"b":2} and {"b":2,"a":1} are the same call. Arguments that don't serialize (rare — the adapter parses JSON first) fall back to default=str.

3.5 The ScriptedModel fake#

The whole point of the adapter seam: tests need no API. ScriptedModel replays a queue of canned turns — text answers and tool calls — and records everything it was sent, so tests can assert on the trajectory.

python
# scripted.py
"""scripted.py: ScriptedModel — a ChatAdapter that replays canned turns. No network, ever.

Each scripted turn is either:
  ("text", "the final answer")                    -> a ModelTurn with no calls
  ("calls", [(name, args_dict), ...])             -> a ModelTurn with those tool calls
  ("refuse", "reason")                            -> a refusal turn
Optional per-turn usage: ("calls", [...], {"output_tokens": 42})
The adapter records `seen` (every history it was called with) for assertions.
"""
from __future__ import annotations

import json
from typing import Any

from agent import ChatAdapter, ModelTurn, ToolCall


class ScriptedModel:
    def __init__(self, script: list[tuple]) -> None:
        self._queue = list(script)
        self.seen: list[list[Any]] = []           # every history passed to call()
        self.history: list[Any] = []

    # -- ChatAdapter -------------------------------------------------------------------------
    def initial_history(self, user_message: str) -> list[Any]:
        # Canonical fake history: plain dicts, Chat-Completions-flavoured.
        self.history = [{"role": "system", "content": "You are a test agent."},
                        {"role": "user", "content": user_message}]
        return self.history

    async def call(self, history: list[Any]) -> ModelTurn:
        self.seen.append([dict(m) if isinstance(m, dict) else m for m in history])
        if not self._queue:
            return ModelTurn(text="[script exhausted — the model had nothing left to say]",
                            finish_reason="stop",
                            usage={"input_tokens": 10, "output_tokens": 5})
        turn = self._queue.pop(0)
        kind = turn[0]
        usage = turn[2] if len(turn) > 2 else {"input_tokens": 100, "output_tokens": 20}
        if kind == "text":
            return ModelTurn(text=turn[1], finish_reason="stop", usage=usage,
                            native={"role": "assistant", "content": turn[1]})
        if kind == "refuse":
            return ModelTurn(text=turn[1], finish_reason="refusal", usage=usage,
                            refusal=True, native={"role": "assistant", "content": turn[1]})
        # "calls": build ToolCalls with stable ids
        calls = [ToolCall(id=f"call_{i}_{len(self.seen)}", name=n,
                          arguments=a if isinstance(a, dict) else json.loads(a))
                 for i, (n, a) in enumerate(turn[1])]
        return ModelTurn(text="", tool_calls=calls, finish_reason="tool_calls",
                         usage=usage,
                         native={"role": "assistant", "content": "",
                                 "tool_calls": [{"id": c.id, "name": c.name,
                                                 "arguments": c.arguments} for c in calls]})

    def append_assistant(self, history: list[Any], turn: ModelTurn) -> None:
        if turn.native is not None:
            history.append(turn.native)

    def append_results(self, history: list[Any], turn: ModelTurn, results: list) -> None:
        for r in results:                            # one tool message per result, call order
            history.append({"role": "tool", "tool_call_id": r.call_id,
                            "name": r.name, "content": r.output})

3.6 Unit tests with real output#

python
# test_agent.py — run: uv run python test_agent.py  (a self-checking script, not pytest)
"""Tests for the canonical loop. Real output, no network, no keys."""
import asyncio
import json

from agent import AgentResult, Budget, PendingApproval, run_agent
from scripted import ScriptedModel
from support_tools import REGISTRY

PASS = []


def check(name: str, cond: bool, detail: str = "") -> None:
    PASS.append((name, cond))
    print(("PASS" if cond else "FAIL"), name, ("- " + detail if detail else ""))


async def main() -> None:
    # 1. Happy path: look up, search, answer ---------------------------------------------
    model = ScriptedModel([
        ("calls", [("lookup_order", {"order_id": "A17"}),
                   ("search_docs", {"query": "warranty", "max_results": 2})]),
        ("text", "Order A17 is delivered; electronics carry a 1-year warranty."),
    ])
    res = await run_agent(model, "Is order A17 still under warranty?")
    check("happy: completed", res.status == "completed")
    check("happy: answer", "warranty" in res.answer)
    check("happy: 2 steps", res.steps == 2, f"steps={res.steps}")
    check("happy: results reached model", any(
        m.get("role") == "tool" and "delivered" in str(m.get("content"))
        for m in model.history), "tool result in history")
    check("happy: trace", len(res.trace) == 2 and res.trace[0].calls[0]["name"] == "lookup_order")

    # 2. Error result fed back: unknown tool ----------------------------------------------
    model = ScriptedModel([
        ("calls", [("delete_everything", {})]),
        ("text", "I can't do that; there is no such tool."),
    ])
    res = await run_agent(model, "Delete everything.")
    err = [m for m in model.history if m.get("role") == "tool"]
    check("unknown tool -> error result", res.status == "completed"
          and err and "unknown tool" in err[0]["content"])

    # 3. Loop detection --------------------------------------------------------------------
    model = ScriptedModel([("calls", [("lookup_order", {"order_id": "A17"})])] * 5)
    res = await run_agent(model, "Check A17.", budget=Budget(loop_threshold=3))
    check("loop detected", res.status == "loop_detected" and res.steps == 3,
          f"status={res.status} steps={res.steps}")

    # 4. Step budget ------------------------------------------------------------------------
    model = ScriptedModel([("calls", [("run_report", {"report_name": "open_tickets"})])] * 10)
    res = await run_agent(model, "Report.", budget=Budget(max_steps=2))
    check("step budget", res.status == "budget_exhausted" and res.steps == 2)

    # 5. Approval: deny ----------------------------------------------------------------------
    async def deny_all(p: PendingApproval) -> str:
        return "deny"
    model = ScriptedModel([
        ("calls", [("issue_refund", {"order_id": "A17", "amount": 10.0, "reason": "test"})]),
        ("text", "The refund was denied; I have not issued it."),
    ])
    res = await run_agent(model, "Refund A17.", approver=deny_all)
    tool_msgs = [m for m in model.history if m.get("role") == "tool"]
    check("approval deny -> error result", res.status == "completed"
          and tool_msgs and "denied" in tool_msgs[0]["content"])

    # 6. Finish tool ------------------------------------------------------------------------
    model = ScriptedModel([
        ("calls", [("submit_answer", {"answer": "All done — nothing else needed."})]),
    ])
    res = await run_agent(model, "Do the thing.")
    check("finish tool ends loop", res.status == "completed"
          and "All done" in res.answer and res.steps == 1)

    # 7. Parallel batch stays in call order --------------------------------------------------
    model = ScriptedModel([
        ("calls", [("lookup_order", {"order_id": "A17"}),
                   ("lookup_order", {"order_id": "B22"})]),
        ("text", "Both orders checked."),
    ])
    res = await run_agent(model, "Check A17 and B22.")
    tools = [m for m in model.history if m.get("role") == "tool"]
    check("parallel results in order", res.status == "completed"
          and len(tools) == 2 and "A17" in tools[0]["content"] and "B22" in tools[1]["content"])

    # 8. Truncation ---------------------------------------------------------------------------
    from pydantic import BaseModel, ConfigDict
    from support_tools import ToolSpec

    class BigOut(BaseModel):
        model_config = ConfigDict(extra="forbid")
        q: str = ""

    def big_tool(q: str = "") -> str:
        return "x" * 20_000

    tools = dict(REGISTRY)
    tools["big_tool"] = ToolSpec(BigOut, big_tool)
    model = ScriptedModel([
        ("calls", [("big_tool", {"q": "x"})]),
        ("text", "got it"),
    ])
    res = await run_agent(model, "Big?", tools=tools, budget=Budget(max_result_chars=1_000))
    tool_msg = [m for m in model.history if m.get("role") == "tool"][0]["content"]
    check("giant result truncated", "chars elided" in tool_msg and len(tool_msg) < 1_500)

    # 9. Approval defer -> resume -------------------------------------------------------------
    from agent import resume_agent

    async def human_then(p: PendingApproval) -> str:
        return "defer"

    model = ScriptedModel([
        ("calls", [("issue_refund", {"order_id": "A17", "amount": 10.0, "reason": "damaged"}),
                   ("lookup_order", {"order_id": "A17"})]),
        ("text", "Refund issued and the order verified."),
    ])
    res = await run_agent(model, "Refund A17 and verify it.", approver=human_then)
    check("defer -> awaiting_approval", res.status == "awaiting_approval"
          and res.pending is not None and res.pending.name == "issue_refund")
    res2 = await resume_agent(res.state, model, "approve", approver=human_then)
    check("resume completes", res2.status == "completed"
          and "Refund issued" in res2.answer, f"status={res2.status}")

    # No approver means nobody approved: the write tool is refused, not run.
    model = ScriptedModel([
        ("calls", [("issue_refund", {"order_id": "A17", "amount": 10.0, "reason": "test"})]),
        ("text", "I could not refund that without an approver."),
    ])
    res = await run_agent(model, "Refund A17.")
    tool_msgs = [m for m in model.history if m.get("role") == "tool"]
    check("write tool without approver -> refused", res.status == "completed"
          and any("no approver" in str(m) for m in tool_msgs))
    # Resuming without an approver must not auto-approve the OTHER risky call in the batch.
    model = ScriptedModel([
        ("calls", [("issue_refund", {"order_id": "A17", "amount": 10.0, "reason": "a"}),
                   ("create_ticket", {"subject": "s", "description": "d"})]),
        ("text", "done"),
    ])
    first = await run_agent(model, "Do both.", approver=human_then)
    second = await resume_agent(first.state, model, "approve")      # no approver passed
    check("resume: sibling risky call denied without approver", second.status == "completed"
          and any("denied" in str(m) for m in model.history if m.get("role") == "tool"))

    print(f"\n{sum(1 for _, c in PASS if c)}/{len(PASS)} checks passed")
    assert all(c for _, c in PASS), "some checks failed"


asyncio.run(main())
Output · real — uv run python test_agent.py18 lines
PASS happy: completed
PASS happy: answer
PASS happy: 2 steps - steps=2
PASS happy: results reached model - tool result in history
PASS happy: trace
PASS unknown tool -> error result
PASS loop detected - status=loop_detected steps=3
PASS step budget
PASS approval deny -> error result
PASS finish tool ends loop
PASS parallel results in order
PASS giant result truncated
PASS defer -> awaiting_approval
PASS resume completes - status=completed
PASS write tool without approver -> refused
PASS resume: sibling risky call denied without approver

16/16 checks passed

Part 4: Running calls well inside the loop#

4.1 Parallel tool calls, bounded#

When the model emits several calls in one turn (03.5, Part 8), _execute_calls runs them concurrently under asyncio.Semaphore(budget.max_parallel_calls) — the same bounded-concurrency pattern as 03.9, Part 4, at a much smaller scale (a handful of calls, not thousands of requests). Three rules:

  • Results stay in call order. asyncio.gather preserves submission order, and every provider requires results matched by call ID anyway — order matters for readability, IDs matter for correctness.
  • Parallelism is per-batch, not global. Calls within one turn run together; the next model call can't start until all results are in (the model needs them to decide). Don't pipeline across steps.
  • A failure doesn't sink the batch. Each call returns a ToolResult with is_error=True; siblings still run. A timeout on one tool shouldn't cancel four healthy ones.

Side-effect tools are the exception: if two calls in one batch both write (two issue_refunds), think about whether they should run concurrently at all — 6.3 covers the dedupe story.

4.2 Streaming the loop for a live UI#

A 10-step agent run takes 30+ seconds; users need progress, not a spinner. The loop emits the same events a single streamed call does, one model call at a time (03.3 owns the wire mechanics):

text
step_started(step=0) -> text_delta* -> tool_call_delta* -> tool_call_done
-> tool_started(name, args_summary) -> tool_finished(name, latency_ms, is_error)
-> step_started(step=1) -> ... -> final_text_delta* -> run_finished(status, spent)

Map each adapter.call to a streaming variant (call_stream) that yields TextDelta/ToolCallDelta events; yield tool_started/tool_finished around each _execute_one; yield run_finished with the AgentResult.status and spent. Two cautions: tool-call arguments still arrive as JSON fragments (03.3, 6.2) — show "calling lookup_order…" from the name delta, not parsed args; and a mid-stream model error (03.3, Part 7) is a step failure — decide whether to retry that step (03.8) or end the run with partial results.

4.3 Tracing every step#

AgentResult.trace is the embryo of the trajectory 08A.14 will formalize. Each TraceEntry records step number, model latency, token usage, the calls made (name + arguments — summarized, not raw, per 03.10, 4.1: log order_id, never a full document), and approvals. Add a run_id/trace_id at the top and emit one structured log line per step plus a final summary — that's enough to debug "why did it loop" and "what did it cost" in production. Don't log tool outputs verbatim at INFO; they're the biggest and most sensitive payloads in the system.


Part 5: Provider SDK helpers — what they automate and what they hide#

Deep-dive

Every provider now ships an agent-loop helper. They all implement the same state machine as Part 3 — with different amounts of rope.

5.1 Anthropic tool runner#

client.beta.messages.tool_runner (beta as of November 2026) takes @beta_tool-decorated functions — type hints + docstring become the schema — and iterates BetaMessages, running tools and feeding results back automatically. It manages the conversation state for you (you can take over the message history inside the loop when you need to), caps iterations with max_iterations, catches a tool's exception and returns it to Claude as a tool result with is_error: true (in Python, the exception's type and message, not the stack trace), and works with server-side compaction through the context_management request parameter. runner.until_done() consumes the rest of the run and returns the final message (Anthropic's tool-runner page, checked 11 November 2026).

python
# claude_runner.py — illustrative (needs ANTHROPIC_API_KEY)
import anthropic
from anthropic import beta_tool

client = anthropic.Anthropic()

@beta_tool
def lookup_order(order_id: str) -> str:
    """Look up an order by ID. Returns status, items, total and tracking."""
    ...  # your backend

runner = client.beta.messages.tool_runner(
    model="claude-haiku-5-5", max_tokens=8_000,
    tools=[lookup_order],                       # more @beta_tool functions
    messages=[{"role": "user", "content": "Where is order A17?"}],
    max_iterations=8,                           # the budget the helper gives you
)
for message in runner:
    print(message.stop_reason, message.usage)

What it hides that you must reclaim: no token/cost budget (only max_iterations), no loop detection, no per-tool timeouts beyond your function's, no human-approval pause (Anthropic's docs say drop to the manual loop for HITL — exactly the approver hook in Part 3), and — check your installed SDK version — how it treats pause_turn (the server-tool pause from 2.2) has differed across releases (Anthropic's tool-runner docs). For a support assistant that issues refunds, you want the approval hook the runner doesn't give you.

5.2 OpenAI Agents SDK (preview — owned by 08F.1)#

The OpenAI Agents SDK wraps the Responses API in Agent + Runner: agents have instructions and tools, Runner.run_sync drives the loop until final_output, max_turns caps it (MaxTurnsExceeded on breach), and it adds handoffs, guardrails and built-in tracing. It's the most batteries-included option — and the most opinionated: it owns the loop, the session model and the tracing format. 08F.1 evaluates it against the alternatives; for this lesson the point is that Runner is run_agent with the provider fixed to OpenAI and extras bolted on.

5.3 Gemini automatic function calling#

google-genai can run the loop for you: pass Python callables (not just FunctionDeclarations) in tools, and the SDK's automatic function calling (AFC) executes them and continues until the model stops — on chats.create/send_message, capped by automatic_function_calling.maximum_remote_calls (default 10). automatic_function_calling.disable=True turns it off. AFC is Python-SDK-only, meant for the chat surface (the SDK warns against using it via models.generate_content directly), and each AFC step is a billed model call just like yours. Version note (as of November 2026): this works on google-genai 2.x (the samples were checked against 2.34.0); the SDK's README warns that in the next major (>=3.0.0) AFC can no longer be invoked from direct Models.generate_content calls — only from Chats — so if you installed a 3.x release, check the changelog before using it (python-genai README). It has no budgets, no approvals, no tracing — same story as the others: the helper removes the loop, not the engineering around it.

5.4 OpenRouter#

No agent helper — OpenRouter is a router, not a runtime. Its tool support is per-model Chat Completions; your loop (2.4 or the canonical one) is the agent. That's a feature: one loop, many models.

5.5 Helper vs your own loop — decision table#

You need… Raw loop (Part 2/3) Provider helper Framework (08F.1)
Budgets beyond step count (tokens, cost, wall-clock) ✅ Budget ⚠️ iterations only ⚠️ varies
Human approval / pause-resume ✅ approver ❌ manual loop required ⚠️ some support it
Loop detection, per-tool limits ✅ ❌ ⚠️
Multi-provider portability ✅ adapter ❌ one provider ⚠️ varies
Streaming control, custom tracing ✅ ⚠️ ⚠️ opinionated
Fastest path to a working agent on one provider more code ✅ ✅
Provider-specific features (interleaved thinking, server tools) ✅ full control ✅ sometimes hidden ⚠️

Rule of thumb: start with the canonical loop — it's ~150 lines you've now read — and adopt a helper only when its hidden behaviour matches what you need and you can still inject your budgets/approvals around it. A helper you can't budget is a helper you can't ship.


Part 6: The hard parts inside a loop#

6.1 Context growth: tool results flood the window#

Every step resends the entire history, and tool results are the biggest thing in it — a single search or report can outweigh the whole conversation (04.7, Part 5: results are "large, re-fetchable, and usually only needed once"). Three defences, in order of effort:

  1. max_result_chars truncation (already in Budget): head+tail elision with a readable marker — the model knows content was removed and can re-call with a narrower query.
  2. Result policy over time: keep recent results verbatim, stub older ones ([cleared: search_docs #3, 4,102 tokens]), never orphan a call from its result — 04.7, 5.4 has the full policy and the "handles" pattern for just-in-time re-fetch.
  3. Smaller results at the source: this is a tool design problem — search_docs returning 3 passages beats returning 30. 08A.6 owns it; the loop just pays the bill.

6.2 Errors inside the loop#

The loop sees four error layers, each owned elsewhere:

Layer Examples Owner
Model call fails 429, 529, timeout, mid-stream error 03.8 — wrap adapter.call; a retried step isn't a new step
Malformed call bad JSON args, unknown tool, wrong types _execute_one → error result; the model reads it and self-corrects (03.5, 7.4)
Tool fails exception, timeout, bad output error result, is_error=True; model decides retry/different approach
Loop pathologies repeats, stalls, budget exhaustion Budget + loop detection → named status, partial answer + trace returned

The one rule: errors are data inside the loop, exceptions at the boundary. A tool exception must never crash the run; a model-call exception after retries should propagate (or end the run with status="error" and whatever partial answer exists).

6.3 Idempotency and retries for tools with side effects#

issue_refund, create_ticket, send_email — calls that do something. Three rules:

  • Idempotency keys. LLM APIs have no idempotency keys (03.8, 11.1); your tool layer dedupes. Derive a key from (run_id, tool_name, canonical_args) — a resumed or retried run that re-issues the same call hits the dedupe table and returns the original result instead of a second refund. lookup_order needs none (reads are naturally idempotent).
  • Retries belong below the loop. Retry a failed tool call inside _execute_one (with backoff, per 03.8) — never retry by letting the model re-issue it blindly, and never let a timeout retry double-execute a non-idempotent write.
  • Reversibility beats prevention. Prefer tools that can be undone (a ticket can be closed; a refund can't be un-sent) — 02.10, Part 18 lists this among the agent mitigations.

6.4 Human approval hooks: pause and resume#

The approver callback is the seam: it's async, sees a PendingApproval (tool, args, risk level), and returns "approve", "deny", or "defer". "defer" pauses the whole run — AgentResult(status="awaiting_approval", state=…, pending=…) — and resume_agent(state, adapter, "approve"|"deny") picks up exactly where it stopped: the pending batch re-executes with the human's decision applied to the deferred call and the approver re-consulted for any other risky call in the same batch.

python
# approval_gate.py — a console approver (pure Python; wire to Slack/UI in production)
import asyncio
from agent import PendingApproval, run_agent, resume_agent
from scripted import ScriptedModel

async def console_approver(p: PendingApproval) -> str:
    print(f"\n  APPROVAL NEEDED: {p.name}{p.arguments}  (risk={p.risk})")
    return "approve" if input("  approve? [y/N] ").strip().lower() == "y" else "deny"

async def main() -> None:
    model = ScriptedModel([
        ("calls", [("issue_refund", {"order_id": "A17", "amount": 84.5,
                                     "reason": "arrived damaged"})]),
        ("text", "Refund issued."),
    ])
    res = await run_agent(model, "Refund order A17.", approver=console_approver)
    # approve/deny are answered inline here. To PAUSE instead, have the approver return
    # "defer": the run returns awaiting_approval + state, and resume_agent(res.state,
    # adapter, decision) continues it — that's test 9's path.
    print(res.status, res.answer)

asyncio.run(main())

Output (real — run uv run python approval_gate.py and type y at the prompt; typing anything else denies the refund, and the scripted model then reports completed all the same, because it replays its canned text):

text
  APPROVAL NEEDED: issue_refund{'order_id': 'A17', 'amount': 84.5, 'reason': 'arrived damaged'}  (risk=write)
  approve? [y/N] y
completed Refund issued.

Design rules for approval in production (deferred to 08A.10 and 08A.14 for depth): approval gates go on risk, not tool name — risk="write"|"destructive" in the registry is the hook; approvals should show the human what will happen (tool, args, blast radius), not just "allow?"; and timeouts matter — a run paused for approval must not hold a worker or expire its budget silently. One storage caveat: AgentResult.state is in-process state, not a serialisable snapshot — history holds whatever the adapter appended (for OpenAIResponsesAdapter, provider-native items; for a real Anthropic adapter, ContentBlock objects), none of which JSON-encodes. You can't park awaiting_approval state in a database for a human who approves hours later; durable pause/resume across processes is 08A.9's problem — persist the trajectory (tool, args, decision, result), not the native history, and rebuild the conversation on resume. Anthropic's tool-runner docs make the same point from the other side: drop to a manual loop when you need HITL.


Part 7: Reasoning models and caching in loops#

Deep-dive

7.1 Reasoning data must survive every step#

A reasoning model inside a loop thinks between tool calls (interleaved thinking, 02.8, 8.1). The rule from 02.8, 8.2 applies with double force: append the whole assistant turn, unchanged, every step — OpenAI reasoning items, Anthropic thinking blocks with signatures, Gemini thought signatures, OpenRouter reasoning_details. Dropping them doesn't just lose reasoning; on Anthropic it can 400 (prefix binding) and on Gemini it can corrupt signed parts. The canonical loop's append_assistant(history, turn) is exactly this rule, which is why ModelTurn.native exists.

7.2 Effort per step#

Not every step needs the same reasoning effort: the planning step after the user message usually wants high; digesting a tool result often wants low (02.8, 8.3). Expose reasoning_effort on your adapter's call (the 03.11 Request already models it as off|low|medium|high) and let the loop or caller step it down after the first call — but measure first; some models get worse at tool use with thinking off.

7.3 Prompt caching across loop turns#

The loop is a caching dream and a caching trap. The trap: any change near the front of the prompt invalidates everything after it — editing the system prompt, reordering tools, or trimming old history mid-run breaks the cache for the whole conversation (03.7, 04.6, Part 10). The dream: the prefix — system + tools + early turns — is identical across steps, so each step's request hits the cache for everything except the new tool results appended at the end. On Anthropic that's automatic prompt caching; on OpenAI, prompt_cache_key keeps each tenant's cache accounting separate on GPT-5.6 and later (and routed requests to a warm node on earlier models — 03.7, 7.2); on Gemini, implicit caching just works on long prefixes. Practical rules: declare the full tool list up front (never add tools mid-run — it changes the prefix and invalidates Anthropic thinking blocks, 03.5, 14.5); append, never edit; and put tool results at the end where they belong. A 10-step run can be dramatically cheaper than 10 independent calls — if you keep the prefix stable.


Reference

8.1 Decision table: which loop do you build?#

Situation Build
One question, one lookup, done A single call + tool_choice — no loop (03.5)
Fixed sequence of steps, model fills slots A workflow — code owns the order (08A.9)
Open-ended task, model must decide next action The agent loop — this lesson
Agent on one provider, speed matters Provider helper (Part 5) if you can still budget + approve
Multi-provider, testable, owned Canonical run_agent + adapters (Part 3)
Teams, tracing, handoffs, guardrails at scale A framework — evaluate in 08F.1

The module's guiding principle — use the simplest thing that works: single call → workflow → agent, adding autonomy only when it earns its cost.

Failure What it looks like Defence in this lesson
Runaway loop Same call forever, bill climbing max_steps, loop_threshold, per-tool limits → loop_detected/budget_exhausted
Lost tool call IDs Results can't be matched → 400 mid-run IDs echoed verbatim; call_id/tool_use_id/id per provider (03.5, 5.3)
Dropped reasoning items 400s on thinking signatures, or silent quality loss append_assistant appends turn.native unchanged
Giant tool results Context fills, costs explode, early instructions decay max_result_chars truncation + 04.7 result policy
Ignored errors Model retries a failing call blindly Error results carry "fix and retry" guidance; loop detection catches thrash
Premature finish Model claims done having done nothing submit_answer finish tool + verify-before-claim prompting; evals in Module 10A
Approval bypass Write tool runs without review risk levels + approver gate; deny → error result, not silent skip
Double side effects Resumed run sends two refunds Idempotency keys (6.3)
Runaway cost 50 steps × growing context max_cost_usd + max_seconds + token budget
Stale context Model acts on last-hour's data Tool results are fresh by construction; staleness is a tool-design problem (08A.6)

Common misconceptions#

  • "An agent is a model that decides what to do." The model decides each next action; your code decides everything else — budgets, validation, permissions, what's allowed to run. The loop is infrastructure, not intelligence.
  • "If the model is smart, the loop will be fine." Per-step success compounds (02.10, Part 18): 95% per step → ~36% over 20 steps. The loop's job is making failures bounded and visible.
  • "Tool errors should raise exceptions." Inside the loop they're data: is_error results the model reads and routes around. Exceptions are for the boundary (your API returning 500 to the user).
  • "Parallel tool calls are free speed." They're concurrent within a turn only; the next model call still waits for all results. And parallel writes need idempotency thinking.
  • "The SDK's agent runner handles the hard parts." It handles the loop; budgets, approvals, loop detection, cost control and tracing are still yours (Part 5).
  • "A bigger max_steps makes a better agent." It makes a more expensive failure. Budgets are features; tune them from traces, not hopes.
  • "The loop is provider-specific." The state machine is identical on all four; only the adapter differs. That's the whole point of Part 3.

Key takeaways#

  • The agent loop is a state machine: call → tool calls? → execute → append results → repeat, until a stop condition — final answer, finish tool, refusal, budget, loop detection, cancel, or approval needed.
  • The model decides actions; your code decides everything else. Validation, timeouts, permissions, budgets and approvals all live in the loop, not the prompt.
  • Every loop ships with budgets from line one: max steps, tokens, cost, wall-clock, per-tool limits — plus loop detection on call signatures. A loop without them is a while True that spends money.
  • Errors are data inside the loop. Tool failures become is_error results; model-call failures are the retry layer's problem (03.8); expected stops return a named status, never silence.
  • The whole assistant turn is appended unchanged — reasoning items, thinking blocks, thought signatures — or later steps break (or 400).
  • Test the loop with a scripted fake. ScriptedModel replays canned turns; the canonical loop, registry, budgets and approvals are all unit-tested with real output and no API key.
  • Provider helpers remove the loop, not the engineering. Anthropic's tool_runner, the OpenAI Agents SDK and Gemini AFC automate iteration — budgets, approvals and tracing remain yours.
  • Context grows fastest where results accumulate. Truncate large outputs, stub old ones, and keep the prompt prefix stable so prompt caching works across steps.
  • Side-effect tools need idempotency keys and approval gates keyed on risk, with pause/resume for human decisions.
  • Start simple: single call → workflow → agent. The loop earns its cost only when the task genuinely needs the model choosing each step (08A.9).

Terms introduced in this lesson#

Term Meaning
Agent loop The call-model → execute-tools → feed-results-back cycle that repeats until a stop condition
Step / turn One model call plus the tool executions it triggered
Trajectory The full record of a run: every call, result, token count and latency
Stop condition The rule ending a loop — good (answer, finish tool, cancel) or bad (budget, loop detected)
Budget Hard limits on steps, tokens, cost, wall-clock and per-tool calls
Loop detection Stopping when an identical (tool, args) signature repeats past a threshold
Error result A tool failure returned to the model as data (is_error), not raised
ChatAdapter The provider seam: four methods translating canonical events to wire format
ScriptedModel A fake ChatAdapter replaying canned turns for tests without an API
Finish tool A tool (e.g. submit_answer) whose successful call ends the loop with its output
Approver The async callback deciding approve/deny/defer for risky tool calls
Idempotency key A dedupe token so a retried/resumed run can't double-execute a side effect
Interleaved thinking Reasoning between tool calls within one assistant turn (02.8)

Exercises#

  1. Budget audit. Run test_agent.py's scenarios with Budget(max_steps=3, max_cost_usd=0.001, price_per_mtok={"input": 1.0, "output": 5.0}) and a scripted model that reports realistic usage. Which stop fires first? Adjust until each budget type triggers once. Hint: with the default scripted usage (100 input, 20 output tokens) a step costs (100 × 1.0 + 20 × 5.0) / 1,000,000 = $0.0002, so three steps cost $0.0006 and max_steps fires before the $0.001 cap; pass a per-turn usage such as {"input_tokens": 500, "output_tokens": 100} (exactly $0.001 per step) on a script whose first turn is a tool call, so the cost limit fires before the second model call (step 1).
  2. Adapter for Anthropic. Write AnthropicAdapter implementing ChatAdapter (history = messages list; call wraps client.messages.create; append_assistant appends {"role":"assistant","content": turn.native}; append_results appends one user message of tool_result blocks). Run the happy-path test against it with a mocked client. Hint: the mock only needs messages.create returning an object with .content (blocks with .type, .id, .name, .input), .stop_reason and .usage; call must turn those into a ModelTurn and raise on max_tokens, as the Part 2.2 sample does.
  3. Loop-detection tuning. Script a model that legitimately re-checks lookup_order at steps 0, 3 and 6 (different calls between). At loop_threshold=3 does it false-positive? Propose a better signature (e.g. include step distance or require consecutive repeats) and implement it. Hint: it does false-positive, because signatures counts the whole run; track the previous step's signatures and reset a counter when a different call intervenes.
  4. Idempotency. Give issue_refund a dedupe table keyed on (run_id, order_id, amount). Show that a resumed run (test 9) can't double-refund, and that two different amounts still both go through. Hint: keep a _refund_dedupe: dict[tuple, dict] in support_tools.py; on a hit return the stored result, and assert len(_refund_log) is 1 after the resume.
  5. Streaming shim. Wrap OpenAIResponsesAdapter.call in a streaming variant yielding text/tool-call deltas, and emit the step_started/tool_finished events from Part 4.2 for a two-step scripted run. Hint: an async def run_agent_events(...) generator that yields dicts; for the scripted run, assert the event order step_started, tool_started, tool_finished, step_started, run_finished.
  6. Helper vs loop. Port the happy path to client.beta.messages.tool_runner (or Gemini AFC) and list every Budget feature you lost. Which would you keep if you could only have three? Hint: the usual keepers are a token or cost cap, the approval hook for issue_refund and loop detection; there is no single right answer, but justify yours from the failure gallery in 8.2.

Check yourself#

  1. Why must the whole assistant turn — including reasoning items and thinking blocks — be appended each step, and what breaks if you append only the text?
  2. What's the difference between a workflow and an agent, and why does the module make you earn the agent's cost?
  3. Name four stop conditions and the status each produces. Which are "good" stops and which are failure stops?
  4. Why are tool errors returned as results rather than raised, and where should exceptions propagate?
  5. How does loop detection work, and what's a case where identical calls are legitimate?
  6. What does the approver callback see, what are its three decisions, and what happens on "defer"?
  7. Why do provider SDK helpers (tool_runner, Agents SDK, AFC) not remove the need for budgets and approvals?
  8. A 10-step run resends full history each step — why does prompt caching still help, and what single change would break it?
  9. Why do side-effect tools need idempotency keys, and where in the loop should the dedupe happen?
  10. What does ScriptedModel let you test that a real API can't, and what does it not prove about provider wire behaviour?

Further resources#

← 08A.1 — Agent Definitions, the Autonomy Spectrum and Agent Anatomy | Module 08A overview | 08A.3 — Loop Control, Budgets and Stagnation Detection in the Raw Loop →

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