08A.3 Loop Control, Budgets and Stagnation Detection in the Raw Loop

Agents & multimodalLesson 3 of 157,900 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

An agent loop that can run forever will, sooner or later, run forever. This lesson teaches the controls that stop it, in the raw tool loop from 08A.2 and before any framework appears: stop conditions, step limits, per-run token and money budgets, deadlines, and detection of a loop that is busy but going nowhere. 08A.2, Part 3 gave you a Budget class and identical-call detection. Here you build on them: budgets with a reserve so a stopped run can still say something useful, deadlines that really cancel work, stagnation detectors that notice progress rather than just repeats, and a stop that returns partial work instead of an error. You will also read the usage and stop signals the OpenAI and Anthropic APIs give you, because a loop can only enforce what it can measure. Everything runs offline against a scripted fake model.

What you'll learn

  • The loop-control questions every agent must answer: is it done, may it continue, is it still making progress, and what does it return when it stops
  • A stop-reason taxonomy that maps your loop's decisions to the providers' own stop signals
  • How to read usage (OpenAI Responses, Anthropic Messages) into one shape and turn it into a money figure, including the cache-token trap
  • Gauges with reserves: one idea that covers steps, tokens, money and time, plus soft warnings and why the call that crosses a limit still happens
  • Deadlines: per-tool timeouts, a run deadline, and real cancellation with asyncio, so that partial work survives
  • Stagnation detection beyond identical calls: ping-pong cycles, results that add no new information, writes that change nothing, and why a nudge should come before a stop
  • Graceful degradation: a tools-off wrap-up call, a no-model digest, and what a partial result must contain
  • How frameworks expose the same controls, after you have built them by hand

What you don't need

  • API keys. The loop, the detectors and every scenario run against a scripted fake model with no network. The two provider loops are illustrative (they need keys), but their control flow is also tested here against stand-in clients.
  • Docker or any service. Everything is in-memory Python.
  • Org-level budgets, quotas and chargeback. This lesson owns the per-run limits of a single loop; the organization-level limits are in 11B.6 and 11B.7.

Setup

Python 3.11 or newer, standard library only, for every offline sample. As of 1 December 2026 the optional provider loops in 6.3 would need openai and/or anthropic (package names only, install with uv add openai anthropic or pip install openai anthropic), but you can run everything else without them. Save each code block under the file name in its first comment, in one folder, and run it with python3 <file>. The outputs below were produced with Python 3.14. The prices in the samples are made-up round numbers used to show arithmetic; take real prices from the provider pricing pages.


What you must be able to do after this lesson#

  • Name every way a run can stop and map each stop to a status and a reason
  • Normalize OpenAI and Anthropic usage into one shape and price it without counting cached tokens twice
  • Build gauges for steps, tokens, money and time with a reserve so a stopped run can still wrap up
  • Enforce a run deadline with real cancellation so partial work survives
  • Detect stagnation (paraphrased repeats, cycles, writes that change nothing) and nudge before stopping
  • Return a partial result with status, reason, findings, spend and the writes already made
  • Score stagnation detectors on labelled traces for recall, delay and false alerts

Why this matters for an AI engineer#

An agent loop has two ways to fail expensively: it can run too long, or it can run in circles. The first is a budget problem and the second is a progress problem, and a bill or an outage is how you find out. Loop control is also what makes agents shippable: a run that always ends, within a known cost and time, with an honest result, is something you can put behind a product.

You'll hear... You'll understand it after...
"Why did that one run cost forty dollars?" Part 3: The meter
"It hit the token limit and just died with no answer." Part 6: Graceful degradation
"The input tokens are different on OpenAI and Anthropic." 2.3 One Usage shape
"The agent kept searching the same thing with different words." Part 5: Stagnation beyond identical calls
"It ignored the timeout." Part 4: Deadlines
"What does max_turns do in the SDK?" Part 7: How frameworks do it
"Who owns the budget, the loop or the platform team?" 1.4 Per-run versus organization limits

Part 1: What you have, and what is missing#

1.1 What the earlier lessons already control#

This lesson extends four earlier pieces of loop control: the Budget and identical-call detection of 08A.2, 3.3 and 3.4; the stalled and circuit_breaker stops of 08A.10, Part 6; the policy view in 08A.14, 2.6, 5.2 and 5.5; and the repeat counter in 08A.4, 3.4. It does not repeat them.

What those lessons leave open, and this lesson builds:

  1. Deadlines that cancel. Wall-clock budgets are checked between steps. A single slow tool can blow far past them. Real deadlines need cancellation.
  2. A reserve for the end. A loop that stops at its limit has nothing left to explain itself. A reserve keeps one affordable call for a wrap-up.
  3. Progress, not just repetition. Identical calls are the easy case. Paraphrased searches, A-B-A-B cycles and "successful" writes that change nothing all slip through.
  4. A contract for partial work. What exactly does a stopped run return?
  5. Provider usage and stop signals, read correctly, because the meter is only as good as its inputs.

1.2 The four questions loop control answers#

Every iteration of a well-controlled loop asks four things, in this order:

  1. Is it done? The model answered with no tool calls, or called a finish tool. (A truncated answer is not done; see 2.2.)
  2. May it continue? Are steps, tokens, money and time all within their limits, with the reserve intact?
  3. Is it still making progress? Is it finding something new, changing something, or trying something different?
  4. If we stop, what do we hand back? A status, a reason, whatever was found, and what is missing.

1.3 A stop-reason taxonomy#

A run must never end silently. Name every way it can end. The first column is this lesson's vocabulary; the second maps it onto the status values of 08A.2, 3.3; the third shows which stops the provider reports and which only you can decide.

Our status / reason 08A.2 status Who knows
completed / model answered completed The provider: no tool call and a complete response
stopped / steps budget budget_exhausted Only your loop
stopped / tokens or money budget budget_exhausted Only your loop (the provider reports usage; the limit is yours)
stopped / time budget budget_exhausted Only your loop
stopped / stagnation (which detector) loop_detected Only your loop
output cut off (max_tokens, incomplete) raised as an error by the adapter The provider
refusal error The provider (Anthropic refusal; see 2.2)
context window full raised by the adapter The provider (Anthropic model_context_window_exceeded)

The provider cannot tell you that your loop has used enough money or is going in circles. Those are the stops you must implement, and they are the subject of this lesson.

1.4 Per-run versus organization limits#

Two kinds of limit get confused.

  • Per-run limits apply to one execution of one loop: at most 12 steps, 40,000 tokens, 5 cents and 60 seconds. They live inside the loop, are enforced before each model call, and are the loop author's job. This lesson owns them.
  • Organization limits apply across many runs, users and teams: a monthly team budget, a daily tenant cap, rate limits across services, alerts and a kill switch. They live in a gateway or platform layer. 11B.6 and 11B.7 own them.

You need both. A per-run limit stops one runaway; an organization limit stops a thousand slightly-too-expensive runs. Neither replaces the other.


Part 2: Reading provider usage and stop signals#

A loop cannot enforce a limit it cannot measure. Every model response carries usage numbers and a stop signal, and the two providers name and count them differently. Published lessons already document the field-by-field rules, so this Part keeps only what the loop needs: the summary below, and the small Usage shape in 2.3 that Part 3's code imports. For the full tables see 03.7, Part 3 (usage fields and pricing, including the cache fields) and 03.8, 10.1 (the stop signals that arrive inside a 200 response).

2.1 OpenAI Responses#

Field details: 03.7, 3.2. For a loop, three facts matter (checked on 1 December 2026). usage.input_tokens includes the cached and cache-write tokens, and usage.output_tokens includes reasoning tokens. A response with status: "incomplete" at max_output_tokens "might occur before any visible output tokens are produced" (OpenAI's reasoning guide), so you can pay for reasoning and get no text; leave room. And max_tool_calls caps only calls to built-in tools in one response, not your own function tools, so it is not a loop limit.

2.2 Anthropic Messages#

The fields are in 03.7, 3.3. Three facts matter to a loop (checked on 1 December 2026).

  • usage.input_tokens counts only the tokens after the last cache breakpoint. Total input is input_tokens + cache_read_input_tokens + cache_creation_input_tokens.
  • The per-call cap is max_tokens. As with OpenAI, it limits one response, not the run.
  • The stop_reason tells the loop what to do next (03.5, 5.4 covers pause_turn and truncated calls in depth):
stop_reason What a loop should do
end_turn The model finished: this can be a final answer
tool_use Run the tools and continue
max_tokens Truncated. Not a final answer. If the last block is an incomplete tool_use, retry with a higher max_tokens
pause_turn A server-tool loop hit its iteration limit. Resend the assistant content unchanged to continue, and count it against your own step budget
refusal The model declined. This is a normal 200 response; stop_details says why
model_context_window_exceeded The response filled the context window. Treat as truncated

2.3 One Usage shape for the loop#

The loop should not know which provider it is talking to. Give it one Usage shape and one adapter function per provider. This is the same normalize-first convention as 03.7, 3.1, cut down to the four buckets a budget needs. The adapters read the real field names above; the demo feeds them objects shaped like the SDKs' usage types.

python
# usage_fields.py
"""One Usage shape for the loop, and two adapters that read real provider usage objects.

The field names come from the official SDK types and API docs (checked 1 December 2026):
  OpenAI Responses : response.usage.input_tokens (INCLUDES cached tokens),
                     .input_tokens_details.cached_tokens, .input_tokens_details.cache_write_tokens,
                     .output_tokens (INCLUDES reasoning tokens), .output_tokens_details.reasoning_tokens
  Anthropic        : message.usage.input_tokens (EXCLUDES cache reads and writes),
                     .cache_read_input_tokens, .cache_creation_input_tokens, .output_tokens
"""
from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Usage:
    fresh_input: int = 0      # input tokens billed at the normal input price
    cache_read: int = 0       # input tokens served from a prompt cache
    cache_write: int = 0      # input tokens written to a prompt cache
    output: int = 0           # output tokens, reasoning tokens included

    @property
    def total(self) -> int:
        return self.fresh_input + self.cache_read + self.cache_write + self.output

    def __add__(self, other: "Usage") -> "Usage":
        return Usage(self.fresh_input + other.fresh_input, self.cache_read + other.cache_read,
                     self.cache_write + other.cache_write, self.output + other.output)


@dataclass
class Prices:
    """USD per 1,000,000 tokens. Copy real numbers from the provider's pricing page."""
    input: float
    output: float
    cache_read: float | None = None     # None -> assume the full input price (a safe over-estimate)
    cache_write: float | None = None

    def cost(self, u: Usage) -> float:
        read = self.input if self.cache_read is None else self.cache_read
        write = self.input if self.cache_write is None else self.cache_write
        return (u.fresh_input * self.input + u.cache_read * read
                + u.cache_write * write + u.output * self.output) / 1_000_000


def from_openai(u) -> Usage:
    """OpenAI: input_tokens already contains cached and cache-write tokens, so split them out."""
    d = u.input_tokens_details
    cached = getattr(d, "cached_tokens", 0) or 0
    written = getattr(d, "cache_write_tokens", 0) or 0
    return Usage(fresh_input=u.input_tokens - cached - written, cache_read=cached,
                 cache_write=written, output=u.output_tokens)


def from_anthropic(u) -> Usage:
    """Anthropic: input_tokens is only the part AFTER the last cache breakpoint."""
    return Usage(fresh_input=u.input_tokens,
                 cache_read=getattr(u, "cache_read_input_tokens", 0) or 0,
                 cache_write=getattr(u, "cache_creation_input_tokens", 0) or 0,
                 output=u.output_tokens)
python
# usage_demo.py
from types import SimpleNamespace as NS

from usage_fields import Prices, from_anthropic, from_openai

# Objects shaped like the SDKs' usage types (offline stand-ins, not real API replies).
openai_usage = NS(input_tokens=12_000, output_tokens=900,
                  input_tokens_details=NS(cached_tokens=4_000, cache_write_tokens=0),
                  output_tokens_details=NS(reasoning_tokens=600))
anthropic_usage = NS(input_tokens=50, output_tokens=900,
                     cache_read_input_tokens=11_950, cache_creation_input_tokens=0)

# Made-up round prices, only to show the arithmetic. Use your provider's pricing page.
prices = Prices(input=2.00, output=10.00, cache_read=0.20)

for name, usage in [("openai", from_openai(openai_usage)), ("anthropic", from_anthropic(anthropic_usage))]:
    print(f"{name:9s} {usage}  total={usage.total}  cost=${prices.cost(usage):.5f}")
Output · real, run with Python 3.14 on 1 December 20262 lines
openai    Usage(fresh_input=8000, cache_read=4000, cache_write=0, output=900)  total=12900  cost=$0.02580
anthropic Usage(fresh_input=50, cache_read=11950, cache_write=0, output=900)  total=12900  cost=$0.01149

Both responses used 12,900 tokens, but the OpenAI figure costs more here because only 4,000 of its 12,000 input tokens came from the cache, against 11,950 of 12,000 on the Anthropic side. The point is the arithmetic, not the prices: normalize first, then price.

2.4 Turning tokens into money#

Money is fresh_input x input_price + cache_read x cache_read_price + cache_write x cache_write_price + output x output_price, divided by 1,000,000. Take real prices from config, never from a lesson (OpenAI, Anthropic; 03.7, Part 4 keeps them in a table, 11B.1 covers cost accounting). Over-estimate by default (Prices charges cache tokens at the full input price when no cache price is given), fail closed on a model with no price (budget in tokens only, or refuse to run), and remember that reasoning tokens are output tokens.


Part 3: The meter: gauges, reserves and soft limits#

This Part extends the Budget of 08A.2, 3.3 and the budget table of 08A.14, 2.6. Those give one limit per resource and a stop when it is hit. This Part adds the reserve, the soft warning and the wrap-up.

3.1 One idea for steps, tokens, money and time#

08A.2's Budget holds one field per limit. The same idea fits all four resources: a gauge with a limit, an amount used, and a reserve.

  • exhausted(): true when what is left is at or below the reserve. Normal work stops here.
  • hard_exhausted(): true when nothing is left. Not even the wrap-up call may run.
  • fraction(): how much of the limit is used, for the soft warning.

The reserve is the new idea. If a run stops exactly at its limit, there is nothing left to pay for a summary, so the user gets an error. With a reserve, normal work stops a little early and the saved amount buys one tools-off call that says what was found and what is missing.

3.2 The loop#

The loop below is the 08A.2 loop reduced to what loop control needs, with the model and the clock injected. It is not a replacement for 08A.2's run_agent: it has no approvals, no tracing and no provider adapter, because those are other lessons. What it adds is the meter, the soft warning, the detectors, the nudge-then-stop policy and the wrap-up. Read Gauge, Limits and run_agent; the detectors come in Part 5.

python
# loopctl.py
"""Loop control for a raw tool loop: gauges (steps, tokens, money, time), stagnation detectors,
graceful wrap-up, and partial results. Standard library only. The model is injected."""
from __future__ import annotations

import hashlib
import json
import re
from dataclasses import dataclass, field
from typing import Any, Callable

from usage_fields import Prices, Usage


# ---------- time: injected, so deadlines are testable ----------------------------------------
class FakeClock:
    def __init__(self) -> None:
        self.t = 0.0

    def now(self) -> float:
        return self.t

    def advance(self, seconds: float) -> None:
        self.t += seconds


# ---------- what the model returns, and what we record ---------------------------------------
@dataclass
class Turn:
    text: str = ""
    calls: list[tuple[str, dict]] = field(default_factory=list)     # [(tool_name, args), ...]
    usage: Usage = field(default_factory=lambda: Usage(fresh_input=1000, output=100))


@dataclass
class CallRecord:
    name: str
    sig: str                  # name + canonical JSON of args
    result: str
    is_error: bool
    is_write: bool


@dataclass
class StepRecord:
    step: int
    calls: list[CallRecord]
    state_hash: str           # fingerprint of the world AFTER this step


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


def words(text: str) -> set[str]:
    return {w for w in re.findall(r"[a-z0-9]+", text.lower()) if len(w) >= 3}


# ---------- stagnation detectors: pure functions over the step history ------------------------
def repeated_call(history: list[StepRecord], window: int = 8, threshold: int = 3) -> str | None:
    """The same (tool, args) at least `threshold` times within the last `window` calls."""
    sigs = [c.sig for s in history for c in s.calls][-window:]
    for sig in set(sigs):
        if sigs.count(sig) >= threshold:
            return f"repeated call x{sigs.count(sig)}: {sig[:50]}"
    return None


def ping_pong(history: list[StepRecord]) -> str | None:
    """A cycle of 2 or 3 different calls that has just gone round twice: A B A B or A B C A B C."""
    sigs = [c.sig for s in history for c in s.calls]
    for k in (2, 3):
        pattern = sigs[-k:]
        if len(sigs) >= 2 * k and sigs[-2 * k:] == pattern * 2 and len(set(pattern)) > 1:
            return f"cycle of {k} calls went round twice"
    return None


def result_novelty(history: list[StepRecord]) -> list[float]:
    """Per step: the share of result words never seen in an earlier step's results."""
    seen: set[str] = set()
    out = []
    for s in history:
        got = set().union(*[words(c.result) for c in s.calls if not c.is_error]) if s.calls else set()
        out.append(1.0 if not got else len(got - seen) / len(got))
        seen |= got
    return out


def no_new_information(history: list[StepRecord], window: int = 3, floor: float = 0.15) -> str | None:
    """`window` steps in a row whose results added (almost) nothing the agent did not already have."""
    nov = result_novelty(history)
    if len(nov) > window and all(n <= floor for n in nov[-window:]):
        return f"no new information for {window} steps (novelty {[round(n, 2) for n in nov[-window:]]})"
    return None


def writes_change_nothing(history: list[StepRecord], window: int = 3) -> str | None:
    """`window` steps in a row that wrote, while the world fingerprint never moved."""
    if len(history) <= window:
        return None
    tail = history[-window:]
    hashes = {s.state_hash for s in history[-window - 1:]}
    if all(any(c.is_write for c in s.calls) for s in tail) and len(hashes) == 1:
        return f"{window} write steps changed nothing in the world"
    return None


DETECTORS: dict[str, Callable[[list[StepRecord]], str | None]] = {
    "repeated_call": repeated_call, "ping_pong": ping_pong,
    "no_new_information": no_new_information, "writes_change_nothing": writes_change_nothing,
}


# ---------- gauges: one idea for steps, tokens, money and time --------------------------------
@dataclass
class Gauge:
    name: str
    limit: float | None
    reserve: float = 0.0          # kept back for the wrap-up call; normal work may not touch it
    used: float = 0.0

    def fraction(self) -> float:
        return 0.0 if self.limit is None else self.used / self.limit

    def exhausted(self) -> bool:                       # stop normal work
        return self.limit is not None and self.limit - self.used <= self.reserve

    def hard_exhausted(self) -> bool:                  # not even the wrap-up call is allowed
        return self.limit is not None and self.limit - self.used <= 0


@dataclass
class Limits:
    max_steps: int | None = 10
    max_total_tokens: int | None = 20_000
    max_cost_usd: float | None = 0.05
    deadline_s: float | None = 60.0
    soft_fraction: float = 0.8
    reserve_steps: int = 1
    reserve_tokens: int = 2_000
    reserve_cost_usd: float = 0.005
    reserve_s: float = 10.0
    max_nudges: int = 1


@dataclass
class RunResult:
    status: str                    # completed | stopped
    reason: str
    answer: str
    partial: bool
    findings: list[str]
    steps: int
    spent: dict[str, Any]
    log: list[str]
    history: list[StepRecord] = field(default_factory=list)


# ---------- the loop -------------------------------------------------------------------------
def run_agent(model: Callable[[list[dict], bool], Turn], tools: dict[str, tuple[Callable[..., str], bool]],
              task: str, limits: Limits, clock: FakeClock, prices: Prices,
              snapshot: Callable[[], str] = lambda: "", detectors: list[str] | None = None) -> RunResult:
    detectors = list(DETECTORS) if detectors is None else detectors
    messages: list[dict] = [{"role": "user", "content": task}]
    history: list[StepRecord] = []
    log: list[str] = []
    used = Usage()
    t0 = clock.now()
    gauges = {
        "steps": Gauge("steps", limits.max_steps, limits.reserve_steps),
        "tokens": Gauge("tokens", limits.max_total_tokens, limits.reserve_tokens),
        "cost": Gauge("cost", limits.max_cost_usd, limits.reserve_cost_usd),
        "time": Gauge("time", limits.deadline_s, limits.reserve_s),
    }
    warned = False
    nudges = 0

    def refresh() -> None:
        gauges["steps"].used = len(history)
        gauges["tokens"].used = used.total
        gauges["cost"].used = prices.cost(used)
        gauges["time"].used = clock.now() - t0

    def spent() -> dict[str, Any]:
        refresh()
        return {"steps": len(history), "tokens": used.total, "cost_usd": round(prices.cost(used), 5),
                "seconds": round(clock.now() - t0, 1)}

    def findings() -> list[str]:                       # a no-model digest of what the run learned
        out = []
        for s in history:
            for c in s.calls:
                if not c.is_error:
                    out.append(f"step {s.step}: {c.name} -> {c.result[:60]}")
        return out

    def stop(reason: str) -> RunResult:
        """Graceful degradation: one last tools-off call if budget allows, else a digest."""
        nonlocal used
        refresh()
        if not any(g.hard_exhausted() for g in gauges.values()):
            messages.append({"role": "user", "content":
                             f"Stop using tools ({reason}). Reply with what you found and what is still missing."})
            turn = model(messages, False)
            used = used + turn.usage
            log.append(f"wrap-up call made (tools off); text={turn.text[:50]!r}")
            return RunResult("stopped", reason, turn.text, True, findings(), len(history), spent(), log, history)
        log.append("no budget left for a wrap-up call; returning the digest")
        digest = "Stopped early (" + reason + "). Found so far: " + " | ".join(findings()) if findings() \
            else "Stopped early (" + reason + "). Nothing found yet."
        return RunResult("stopped", reason, digest, True, findings(), len(history), spent(), log, history)

    while True:
        refresh()
        hit = next((g for g in gauges.values() if g.exhausted()), None)
        if hit:
            return stop(f"{hit.name} budget")
        if not warned and any(g.fraction() >= limits.soft_fraction for g in gauges.values()):
            warned = True
            left = {n: round(g.limit - g.used, 3) for n, g in gauges.items() if g.limit is not None}
            messages.append({"role": "user", "content": f"Budget warning, left: {left}. Wrap up soon."})
            log.append("soft warning injected")
        turn = model(messages, True)
        used = used + turn.usage
        if not turn.calls:
            refresh()
            return RunResult("completed", "model answered", turn.text, False, findings(), len(history) + 1,
                             spent(), log, history)
        records = []
        for name, args in turn.calls:
            fn, is_write = tools[name]
            try:
                out, err = fn(**args), False
            except Exception as exc:                   # errors are data, not crashes (08A.2)
                out, err = f"{type(exc).__name__}: {exc}", True
            records.append(CallRecord(name, signature(name, args), out, err, is_write))
            messages.append({"role": "tool", "name": name, "content": out})
        history.append(StepRecord(len(history) + 1, records, snapshot()))
        for det in detectors:
            why = DETECTORS[det](history)
            if why:
                if nudges < limits.max_nudges:
                    nudges += 1
                    messages.append({"role": "user", "content": f"You seem stuck ({why}). Change approach."})
                    log.append(f"nudge after step {len(history)}: [{det}] {why}")
                    break
                return stop(f"stagnation [{det}]: {why}")

Five design choices, each tied to a line above:

  • Checks come before the model call. A limit that is already hit never makes one more billed request.
  • The soft warning is injected once when any gauge passes soft_fraction, so the model can wrap up gracefully. 08A.14, 5.2 calls this the graceful deadline.
  • Tool exceptions become results. The loop never crashes on a tool failure (08A.2).
  • The clock is injected. FakeClock makes deadlines testable. Real code passes time.monotonic.
  • The history is returned. RunResult.history is the full step record. Detectors are pure functions over it, which means you can replay any production trace through new detectors without calling a model.

3.3 Scenarios 1 to 3: finish, steps, money#

The scenario file wires fake tools and a scripted model to the loop. Every model reply is canned, every price is made up, nothing leaves your machine.

python
# scenarios.py
"""Scripted scenarios for loopctl.run_agent. Every model reply is canned; nothing is sent anywhere."""
from __future__ import annotations

import hashlib

from loopctl import DETECTORS, FakeClock, Limits, Turn, run_agent
from usage_fields import Prices, Usage

PRICES = Prices(input=1.00, output=5.00)        # made-up round numbers, USD per million tokens

DOCS = {
    "refund": "refund policy: refunds allowed within 30 days of delivery for damaged items",
    "return": "refund policy: refunds allowed within 30 days of delivery for damaged items",
    "shipping": "shipping times: standard shipping takes 3 to 5 business days across the country",
    "warranty": "warranty terms: electronics carry a one year limited warranty against defects",
    "privacy": "privacy notice: customer data is stored for 24 months then deleted automatically",
}
CLOCK = FakeClock()
TICKET = {"status": "open"}


def search_docs(query: str) -> str:
    CLOCK.advance(2)
    for key, text in DOCS.items():
        if key in query.lower():
            return text
    return "no results"


def read_page(page_id: str) -> str:
    CLOCK.advance(2)
    return DOCS.get(page_id, "no such page")


def slow_report(name: str) -> str:
    CLOCK.advance(20)                              # a slow tool: 20 simulated seconds
    return f"report {name}: 3 open orders"


def set_status(status: str, note: str = "") -> str:
    CLOCK.advance(1)
    JOB["writes"] += 1
    TICKET["status"] = status                      # `note` is ignored: it only changes the call's args
    return f"ticket status set to {status} (request r{JOB['writes']:03d})"   # looks like success


JOB = {"polls": 0, "writes": 0}
JOB_REPLIES = ["job j1 progress 040 percent", "job j1 progress 070 percent", "job j1 finished"]


def check_job() -> str:
    CLOCK.advance(1)
    JOB["polls"] += 1
    return JOB_REPLIES[min(JOB["polls"], 3) - 1]


def fail_tool() -> str:
    raise RuntimeError("backend unavailable")


TOOLS = {"search_docs": (search_docs, False), "read_page": (read_page, False),
         "slow_report": (slow_report, False), "set_status": (set_status, True),
         "fail_tool": (fail_tool, False),
         "check_job": (check_job, False)}


def snapshot() -> str:
    return hashlib.sha1(repr(sorted(TICKET.items())).encode()).hexdigest()[:8]


def call(tool: str, /, tokens: tuple[int, int] = (1000, 100), **args) -> Turn:
    return Turn(calls=[(tool, args)], usage=Usage(fresh_input=tokens[0], output=tokens[1]))


def say(text: str, tokens: tuple[int, int] = (1000, 100)) -> Turn:
    return Turn(text=text, usage=Usage(fresh_input=tokens[0], output=tokens[1]))


class Scripted:
    """Replays turns in order. Turns for tools-off wrap-up calls are marked with wrapup=True."""

    def __init__(self, turns: list[Turn], wrapup: Turn | None = None) -> None:
        self.turns, self.wrapup = list(turns), wrapup

    def __call__(self, messages: list[dict], tools_on: bool) -> Turn:
        if not tools_on:
            return self.wrapup or say("(wrap-up) I stopped early; see the findings.")
        return self.turns.pop(0) if self.turns else say("(script exhausted)")


def reset() -> None:
    CLOCK.t = 0.0
    TICKET["status"] = "open"
    JOB["polls"] = 0
    JOB["writes"] = 0


def run(title: str, turns: list[Turn], limits: Limits, wrapup: Turn | None = None,
        detectors: list[str] | None = None, quiet: bool = False):
    reset()
    r = run_agent(Scripted(turns, wrapup), TOOLS, "Answer the customer's question.", limits, CLOCK,
                  PRICES, snapshot, detectors)
    if quiet:
        return r
    print(f"-- {title}")
    print(f"   status={r.status} reason={r.reason!r} partial={r.partial}")
    print(f"   spent={r.spent}")
    for line in r.log:
        print("   log:", line)
    print(f"   answer: {r.answer[:110]}")
    return r


if __name__ == "__main__":
    lim = Limits(max_steps=4)
    # 1. The happy path.
    run("1 happy path", [call("search_docs", query="refund policy"), say("Refunds: 30 days if damaged.")], lim)
    # 2. Step budget with graceful wrap-up. Every call is different, so no stagnation fires.
    run("2 step budget", [call("search_docs", query="refund"), call("search_docs", query="shipping"),
                          call("search_docs", query="warranty"), call("search_docs", query="privacy"),
                          call("search_docs", query="never reached")], lim,
        wrapup=say("Found refund, shipping, warranty rules; still missing: privacy details."))
    # 3. Token and money budget. Big contexts make each step expensive.
    big = (6000, 400)
    run("3 money budget", [call("search_docs", tokens=big, query="refund"),
                           call("search_docs", tokens=big, query="shipping"),
                           call("search_docs", tokens=big, query="warranty")],
        Limits(max_steps=10, max_total_tokens=None, max_cost_usd=0.02, reserve_cost_usd=0.004),
        wrapup=say("Partial: refund and shipping rules found.", tokens=(500, 50)))
    # 4a. Deadline: slow tools push the clock to the reserve; a wrap-up call still fits.
    run("4a deadline with wrap-up", [call("slow_report", name="alpha"), call("slow_report", name="bravo"),
                                     call("slow_report", name="charlie"), call("slow_report", name="delta"),
                                     call("slow_report", name="echo")],
        Limits(max_steps=10, deadline_s=90, reserve_s=10, soft_fraction=0.6),
        wrapup=say("Four of five reports done."))
    # 4b. Deadline: one tool call eats the whole deadline; no wrap-up call is allowed, so we return a digest.
    run("4b deadline blown, digest only", [call("search_docs", query="refund"), call("slow_report", name="xray")],
        Limits(max_steps=10, deadline_s=20, reserve_s=5))
Output · real, run with Python 3.14 on 1 December 202625 lines
-- 1 happy path
   status=completed reason='model answered' partial=False
   spent={'steps': 1, 'tokens': 2200, 'cost_usd': 0.003, 'seconds': 2.0}
   answer: Refunds: 30 days if damaged.
-- 2 step budget
   status=stopped reason='steps budget' partial=True
   spent={'steps': 3, 'tokens': 4400, 'cost_usd': 0.006, 'seconds': 6.0}
   log: wrap-up call made (tools off); text='Found refund, shipping, warranty rules; still miss'
   answer: Found refund, shipping, warranty rules; still missing: privacy details.
-- 3 money budget
   status=stopped reason='cost budget' partial=True
   spent={'steps': 2, 'tokens': 13350, 'cost_usd': 0.01675, 'seconds': 4.0}
   log: wrap-up call made (tools off); text='Partial: refund and shipping rules found.'
   answer: Partial: refund and shipping rules found.
-- 4a deadline with wrap-up
   status=stopped reason='time budget' partial=True
   spent={'steps': 4, 'tokens': 5500, 'cost_usd': 0.0075, 'seconds': 80.0}
   log: soft warning injected
   log: wrap-up call made (tools off); text='Four of five reports done.'
   answer: Four of five reports done.
-- 4b deadline blown, digest only
   status=stopped reason='time budget' partial=True
   spent={'steps': 2, 'tokens': 2200, 'cost_usd': 0.003, 'seconds': 22.0}
   log: no budget left for a wrap-up call; returning the digest
   answer: Stopped early (time budget). Found so far: step 1: search_docs -> refund policy: refunds allowed within 30 day

Reading scenarios 1 to 3:

  • 1, happy path: the model searched once and answered. status=completed, partial=False.
  • 2, step budget: the limit is 4 steps with a reserve of 1, so normal work stopped after 3 steps and the 4th call went to the wrap-up. Because every search was different, no stagnation detector fired, so this stop is purely the step budget. The wrap-up text names what was found and what is missing.
  • 3, money budget: each step costs 0.008 (6,000 fresh input tokens at 1.00 per million plus 400 output at 5.00). After two steps 0.016 was spent; with a 0.02 limit and a 0.004 reserve, normal work stopped. The wrap-up call (500 input, 50 output tokens) cost a little more, so the final figure is 0.01675, under the limit. That is the reserve doing its job.

3.4 The call that crosses the limit still happens#

A check before a call can only see what has been spent so far, not what the next call will cost. So a run can finish a call that takes it past the limit. Two real systems say so in their documentation:

  • The Claude Agent SDK's max_budget_usd is compared with spend "after model responses arrive", so "spend can therefore pass the cap by up to the cost of that one response" (checked 1 December 2026 on the SDK's agent-loop page, which advises leaving headroom).
  • 10B.15, 7.4 (optional) shows the same thing in Inspect.

Your two defences are the reserve (so the overshoot lands inside it) and a per-call cap (max_output_tokens or max_tokens) that bounds how large any one overshoot can be.


Part 4: Deadlines that actually cancel#

This Part extends 08A.14, 5.2, which says every layer needs a timeout and that cancellation must propagate, with runnable code for the run deadline. Choosing a timeout for each individual tool is covered in 08A.6; this lesson owns the deadline for the whole run.

4.1 Three clocks#

A deadline is really three timers.

Clock What it bounds Set by
Per-call timeout One model request (HTTP) The SDK client's timeout setting (03.8)
Per-tool timeout One tool execution Your loop; a hung tool becomes an error result the model can read. How to size it per tool, and how it interacts with idempotency keys, is in 08A.6
Run deadline The whole run, tools and model calls together Your loop; checked between steps and enforced by cancellation

A soft deadline asks the model to wrap up (the warning in 3.2); a hard deadline cancels. You want both, with a time reserve so the wrap-up call fits.

4.2 Scenarios 4a and 4b: the deadline in the meter#

The two deadline scenarios in the output above use the fake clock, so they are exact:

  • 4a, deadline with wrap-up: each slow_report takes 20 simulated seconds against a 90-second deadline and a 10-second reserve. A soft warning was injected once 60% was used (at 60 seconds), then normal work stopped after four reports at 80 seconds (90 minus 80 is 10, equal to the reserve), and the tools-off wrap-up produced "Four of five reports done".
  • 4b, deadline blown: the first tool took 2 seconds and the second took 20 against a 20-second deadline. Time was over, so even a wrap-up call was not allowed (hard_exhausted). The loop returned a digest built without a model: "Found so far: step 1: ...". This is the fallback when there is no budget for a model call.

The lesson of 4b: a time check between steps cannot stop a long tool. It noticed after the 20 seconds had passed. To stop work during a step you need cancellation.

4.3 Real cancellation with asyncio#

asyncio.timeout (Python 3.11 and newer) cancels the work inside it when the time runs out. Two details matter. First, a per-tool timeout should turn into an error result the model can read, not a crash. Second, the partial work must live outside the cancelled scope, so it survives. The sample keeps done in the caller.

python
# deadline_async.py
"""Real deadlines need cancellation. asyncio.timeout (Python 3.11+) stops an in-flight call,
and the partial work must live OUTSIDE the cancelled scope so it survives."""
import asyncio


async def tool(name: str, seconds: float) -> str:
    await asyncio.sleep(seconds)                      # stands in for a slow API call
    return f"{name} finished"


async def call_tool_with_timeout(name: str, seconds: float, limit: float) -> tuple[str, bool]:
    """Per-tool timeout: a hung tool becomes an error RESULT the model can read, not a crash."""
    try:
        async with asyncio.timeout(limit):
            return await tool(name, seconds), False
    except TimeoutError:
        return f"{name} timed out after {limit}s; try a smaller request or another tool", True


async def run_plan(done: list[str], plan: list[tuple[str, float]]) -> None:
    for name, seconds in plan:
        out, is_error = await call_tool_with_timeout(name, seconds, limit=0.2)
        done.append(("ERROR " if is_error else "") + out)


async def main() -> None:
    done: list[str] = []                              # partial work, owned by the caller
    plan = [("search", 0.05), ("fetch", 0.5), ("summarise", 0.05), ("report", 0.05), ("email", 0.05)]
    try:
        async with asyncio.timeout(0.33):             # the RUN deadline: stops everything in flight
            await run_plan(done, plan)
        status = "completed"
    except TimeoutError:
        status = "run deadline hit"
    print("status:", status)
    for line in done:
        print("  ", line)


asyncio.run(main())
Output · real, run with Python 3.14 on 1 December 20264 lines
status: run deadline hit
   search finished
   ERROR fetch timed out after 0.2s; try a smaller request or another tool
   summarise finished

The first tool finished, the second hung and was cut off at its own 0.2-second limit (the model would read "timed out; try a smaller request"), the third finished, and then the 0.33-second run deadline cancelled the fourth in flight. The caller still holds the three results. 08A.14, 5.2 adds two production notes: cancellation must also stop in-flight model streams, and a model call that times out on your side may still complete and bill on the provider's side, so log request IDs for reconciliation (03.8, Part 12).


Part 5: Stagnation detection beyond identical calls#

This Part extends three published detectors: the identical-call count in 08A.2, 3.4, the stalled and circuit_breaker stops in 08A.10, Part 6, and the repeat counter in 08A.4, 3.4. It adds detectors that notice missing progress rather than repeated text.

5.1 Busy is not the same as progressing#

08A.2's detector counts identical (tool, arguments) signatures. That catches one failure: the model repeating a call verbatim. Real stalls look different.

Stall What it looks like Why identical-call counting misses it
Paraphrased repeats search("refund"), search("return"), search("refund policy") Every call is different; the results are the same
Ping-pong cycle search, read, search, read No single call repeats three times
Phantom writes update_ticket(status="open", note="retry 1"), note="retry 2", ... Arguments differ; the world does not change
Error thrash the same failing tool with tweaked arguments Different arguments (08A.10's circuit breaker catches the consecutive-error case)

All of these share one property: nothing new is learned and nothing changes. So define progress directly. A step makes progress if at least one is true:

  1. New information: its results contain facts the agent did not already have.
  2. A changed world: a write actually changed the state it was meant to change.
  3. A new action: it tried something it has not tried recently.

A loop is stagnating when several steps in a row make no progress by any of these measures.

5.2 Four detectors#

Each detector is a pure function over the step history, defined in loopctl.py above.

Detector Idea Defaults
repeated_call The same signature at least 3 times within the last 8 calls (a window, so a call repeated across a long run does not count) window 8, threshold 3
ping_pong A cycle of 2 or 3 different calls that has just gone round twice (A B A B, or A B C A B C) cycle length 2 to 3, 2 rounds
no_new_information Compute each step's novelty: the share of result words never seen in earlier steps. Fire when the last 3 steps are all at or below 0.15 window 3, floor 0.15
writes_change_nothing The last 3 steps each wrote, while a fingerprint of the world (a hash your tools or a snapshot function supply) did not move window 3

Novelty is a crude but cheap proxy for "did we learn something". It uses word sets (words of three or more letters), so paraphrased queries that return the same document score near zero. The fingerprint for writes_change_nothing is whatever cheaply summarizes the state your tools change: a hash of a file, a row's updated_at, a ticket's status.

5.3 Replaying the detectors#

Because detectors are pure functions, the best way to see them is to run the loop once per case with detectors off (so it records every step), then feed each history to each detector on its own. The demo covers four stuck patterns plus one legitimate repeat (polling a job whose progress changes).

python
# stagnation_demo.py
"""Four kinds of stuck, one legitimate repeat, and which detector sees which."""
from loopctl import DETECTORS, Limits
from scenarios import call, run, say

FINAL = say("done")
CASES = {
    "A identical call x3": [call("search_docs", query="refund")] * 3,
    "B ping-pong A,B,A,B": [call("search_docs", query="refund"), call("read_page", page_id="shipping")] * 2,
    "C paraphrased searches": [call("search_docs", query=q) for q in
                               ("refund", "return", "refund policy", "return policy")],
    "D writes change nothing": [call("set_status", status="open", note=f"retry {i}") for i in range(1, 5)],
    "E legit polling (should NOT stop)": [call("check_job")] * 3,
}

# Stubborn versions: the model ignores the nudge and keeps going, so the second trigger stops the run.
STUBBORN = {
    "A identical call x3": [call("search_docs", query="refund")] * 6,
    "B ping-pong A,B,A,B": [call("search_docs", query="refund"), call("read_page", page_id="shipping")] * 4,
    "C paraphrased searches": [call("search_docs", query=q) for q in
                               ("refund", "return", "refund policy", "return policy", "refunds", "returns")],
    "D writes change nothing": [call("set_status", status="open", note=f"retry {i}") for i in range(1, 8)],
    "E legit polling (should NOT stop)": [call("check_job")] * 3,
}
print("Part 1: the full loop, all detectors on, one nudge allowed, then stop")
for title, script in STUBBORN.items():
    run(title, script + [FINAL], Limits(max_steps=12, max_nudges=1),
        wrapup=say("Stopped as stuck; here is what I have."))

print()
print("Part 2: replay each history through every detector on its own")
names = list(DETECTORS)
print(f"{'case':36s}" + "".join(f"{n:>24s}" for n in names))
for title, script in CASES.items():
    r = run(title, script + [FINAL], Limits(max_steps=12), detectors=[], quiet=True)
    cells = ["FIRES" if DETECTORS[n](r.history) else "-" for n in names]
    print(f"{title:36s}" + "".join(f"{c:>24s}" for c in cells))
Output · real, run with Python 3.14 on 1 December 202638 lines
Part 1: the full loop, all detectors on, one nudge allowed, then stop
-- A identical call x3
   status=stopped reason='stagnation [repeated_call]: repeated call x4: search_docs|{"query": "refund"}' partial=True
   spent={'steps': 4, 'tokens': 5500, 'cost_usd': 0.0075, 'seconds': 8.0}
   log: nudge after step 3: [repeated_call] repeated call x3: search_docs|{"query": "refund"}
   log: wrap-up call made (tools off); text='Stopped as stuck; here is what I have.'
   answer: Stopped as stuck; here is what I have.
-- B ping-pong A,B,A,B
   status=stopped reason='stagnation [repeated_call]: repeated call x3: search_docs|{"query": "refund"}' partial=True
   spent={'steps': 5, 'tokens': 6600, 'cost_usd': 0.009, 'seconds': 10.0}
   log: nudge after step 4: [ping_pong] cycle of 2 calls went round twice
   log: wrap-up call made (tools off); text='Stopped as stuck; here is what I have.'
   answer: Stopped as stuck; here is what I have.
-- C paraphrased searches
   status=stopped reason='stagnation [no_new_information]: no new information for 3 steps (novelty [0.0, 0.0, 0.0])' partial=True
   spent={'steps': 5, 'tokens': 6600, 'cost_usd': 0.009, 'seconds': 10.0}
   log: nudge after step 4: [no_new_information] no new information for 3 steps (novelty [0.0, 0.0, 0.0])
   log: wrap-up call made (tools off); text='Stopped as stuck; here is what I have.'
   answer: Stopped as stuck; here is what I have.
-- D writes change nothing
   status=stopped reason='stagnation [writes_change_nothing]: 3 write steps changed nothing in the world' partial=True
   spent={'steps': 5, 'tokens': 6600, 'cost_usd': 0.009, 'seconds': 5.0}
   log: nudge after step 4: [writes_change_nothing] 3 write steps changed nothing in the world
   log: wrap-up call made (tools off); text='Stopped as stuck; here is what I have.'
   answer: Stopped as stuck; here is what I have.
-- E legit polling (should NOT stop)
   status=completed reason='model answered' partial=False
   spent={'steps': 3, 'tokens': 4400, 'cost_usd': 0.006, 'seconds': 3.0}
   log: nudge after step 3: [repeated_call] repeated call x3: check_job|{}
   answer: done

Part 2: replay each history through every detector on its own
case                                           repeated_call               ping_pong      no_new_information   writes_change_nothing
A identical call x3                                    FIRES                       -                       -                       -
B ping-pong A,B,A,B                                        -                   FIRES                       -                       -
C paraphrased searches                                     -                       -                   FIRES                       -
D writes change nothing                                    -                       -                       -                   FIRES
E legit polling (should NOT stop)                      FIRES                       -                       -                       -

The matrix is the result worth studying.

  • Each stuck pattern is caught by exactly the detector designed for it, and by no other. repeated_call alone would have caught only case A.
  • Case D (phantom writes) was caught only by the world-state detector. The tool answered "ticket status set to open (request r001)", which looks like success and carries a new request number each time, so the novelty detector saw something new. Only the unmoving fingerprint reveals the truth. That is the strongest argument for checking state, not text.
  • Case E, legitimate polling, is a false positive for repeated_call: polling check_job three times is correct behaviour, because the progress it reports changes (40 percent, 70 percent, finished). The progress-based detectors stayed quiet. This is why the policy below nudges first instead of killing the run.

5.4 Nudge first, then stop#

A stagnation alert is a hypothesis, not proof. The loop's policy in run_agent is: on the first alert, inject a message that says what looks wrong and asks the model to change approach, and let the run continue; if another alert fires after the nudge, stop with stagnation [detector] and go to the wrap-up.

You can see both outcomes in the output above. In case E the nudge was ignored harmlessly, the job finished, and the run completed. In cases A to D the scripted model ignored the nudge and kept going, so the next alert stopped the run with a wrap-up. (In B the second alert came from repeated_call rather than ping_pong: after the nudge, the model repeated a call a third time, and a different detector tripped first. Either way the run stopped and said so.) max_nudges is the knob; zero makes every alert a stop, and the legitimate polling run would have been killed.

5.5 Tuning, and what the detectors cannot see#

  • Tune from traces, not from the lesson. Windows and thresholds are guesses until you replay real histories. Part 8 shows the measurement.
  • A tool with chatty, changing output (timestamps, request IDs) defeats the novelty detector, as case D showed. Strip volatile tokens before comparing, or lean on the world fingerprint.
  • A tool with terse, repetitive output (a long report that always says "3 open orders") will trip the novelty detector even when it is fine. You can see it yourself: rename the reports in scenario 4a to single letters ("a", "b", ...). Words shorter than three letters are ignored, so the five results look identical and the detector nudges.
  • Semantic stalls are invisible. An agent that confidently pursues the wrong goal makes plenty of progress by these measures. Detectors find loops and idling; they do not find wrongness. That needs verification (08A.10, 4.2) and evals.
  • Asking a model "are you making progress?" is itself a detector. It costs a call and the model can be wrong, so use it sparingly, as a tiebreak behind the cheap deterministic ones.

Part 6: Graceful degradation and partial work#

This Part extends the fallback ladder in 08A.14, 5.5 ("partial results beat errors") with the exact contract for a partial result and the controls on the raw provider APIs.

6.1 The ladder#

When a limit or a detector says stop, do not just raise an error. Step down a ladder, stopping at the first rung that works.

  1. Nudge (stagnation only): one chance to change approach.
  2. Wrap-up call with tools off: one reserved call that says what was found and what is missing. This is stop() in the loop: it sends a "stop using tools" instruction and the model replies in text. (Providers let you forbid tools for one call: tool_choice="none" for OpenAI, {"type": "none"} for Anthropic, see 6.3.)
  3. A no-model digest: if the reserve is gone, summarize the trace in code, as scenario 4b did.
  4. Hand to a human with the trace and the reason (08A.12).
  5. Resume later from a checkpoint (08C.3).

6.2 What a partial result must contain#

A stopped run is useful only if the caller can act on it. RunResult carries the contract:

Field Why
status and reason The caller must be able to branch: retry, escalate, show a banner
partial = True An unmistakable flag, so downstream code never treats it as complete
answer The wrap-up text or the digest
findings The facts gathered, so a human or a retry does not start from zero
spent Steps, tokens, money and seconds, so cost is accounted even for failures
log and history How it ended, for the trace and for replaying detectors

If the run performed writes before stopping, list them too, and make the tools idempotent so a retry does not repeat them (08A.7, 08A.2, 6.3). A partial result that hides a half-finished refund is worse than an error.

6.3 The same controls on the raw provider APIs#

Here are the two raw loops with the meter wired in: check before each call, read usage after it, honour the provider's own stop signal, and spend the last call on a tools-off wrap-up. This code needs a key, so the output is illustrative. The wrap-up instruction goes in the system prompt rather than as a trailing user message, which avoids putting loose text next to tool results (Anthropic's stop-reason guide warns against text blocks right after tool_result blocks).

python
# provider_loops.py
"""Loop control on the two raw provider APIs. ILLUSTRATIVE: needs OPENAI_API_KEY / ANTHROPIC_API_KEY.

Each loop checks the meter BEFORE every model call, reads usage AFTER it, reacts to the provider's
own stop signal, and spends its reserved last call on a tools-off wrap-up. The wrap-up instruction goes
in the system prompt, so no stray text lands next to the tool results. `client` is injected so the
control flow can be tested without a key (see provider_loops_test.py).
"""
from __future__ import annotations

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

from usage_fields import Prices, Usage, from_anthropic, from_openai

SYSTEM = "You are a support agent."
WRAPUP = "Stop using tools. Say what you found and what is still missing."


@dataclass
class Meter:
    prices: Prices
    budget_usd: float = 0.05
    max_steps: int = 6
    reserve_usd: float = 0.005
    used: Usage = field(default_factory=Usage)
    steps: int = 0

    def add(self, usage: Usage) -> None:
        self.used = self.used + usage
        self.steps += 1

    @property
    def cost(self) -> float:
        return self.prices.cost(self.used)

    def stop_reason(self) -> str | None:           # normal work stops early, leaving the reserve
        if self.steps >= self.max_steps - 1:
            return "steps"
        if self.cost >= self.budget_usd - self.reserve_usd:
            return "money"
        return None


def openai_loop(client, model: str, task: str, tools: list[dict], run_tool: Callable[[str, dict], str],
                meter: Meter) -> dict[str, Any]:
    history: list[Any] = [{"role": "user", "content": task}]
    while True:
        reason = meter.stop_reason()
        last = reason is not None
        resp = client.responses.create(
            model=model, input=history, instructions=SYSTEM + (" " + WRAPUP if last else ""),
            tools=tools, tool_choice="none" if last else "auto",     # tools off on the wrap-up call
            max_output_tokens=2_000, store=False)                    # per-call cap, reasoning included
        meter.add(from_openai(resp.usage))
        if resp.status != "completed":                               # e.g. incomplete: max_output_tokens
            why = resp.incomplete_details.reason if resp.incomplete_details else resp.status
            return {"status": "stopped", "reason": f"provider status {resp.status}: {why}",
                    "partial": True, "cost": meter.cost}
        calls = [i for i in resp.output if i.type == "function_call"]
        if last or not calls:
            return {"status": "stopped" if last else "completed", "reason": reason or "model answered",
                    "answer": resp.output_text, "partial": last, "cost": meter.cost}
        history += resp.output                                       # whole turn, unchanged (08A.2)
        for c in calls:
            history.append({"type": "function_call_output", "call_id": c.call_id,
                            "output": run_tool(c.name, json.loads(c.arguments))})


def anthropic_loop(client, model: str, task: str, tools: list[dict], run_tool: Callable[[str, dict], str],
                   meter: Meter) -> dict[str, Any]:
    messages: list[dict] = [{"role": "user", "content": task}]
    while True:
        reason = meter.stop_reason()
        last = reason is not None
        resp = client.messages.create(
            model=model, max_tokens=2_000, tools=tools,              # max_tokens is the per-call cap
            system=SYSTEM + (" " + WRAPUP if last else ""),
            tool_choice={"type": "none"} if last else {"type": "auto"}, messages=messages)
        meter.add(from_anthropic(resp.usage))
        text = "".join(b.text for b in resp.content if b.type == "text")
        if resp.stop_reason in ("max_tokens", "refusal", "model_context_window_exceeded"):
            return {"status": "stopped", "reason": f"stop_reason={resp.stop_reason}", "answer": text,
                    "partial": True, "cost": meter.cost}
        uses = [b for b in resp.content if b.type == "tool_use"]
        if resp.stop_reason == "pause_turn":                         # a server-tool loop hit its cap: resend
            messages.append({"role": "assistant", "content": resp.content})
            continue
        if last or resp.stop_reason != "tool_use":
            return {"status": "stopped" if last else "completed", "reason": reason or "end_turn",
                    "answer": text, "partial": last, "cost": meter.cost}
        messages.append({"role": "assistant", "content": resp.content})
        messages.append({"role": "user", "content": [
            {"type": "tool_result", "tool_use_id": u.id, "content": run_tool(u.name, u.input)} for u in uses]})

We cannot call the real APIs in this lesson, but we can test our own control flow. The next file hands the loops stand-in clients shaped like the SDK objects and checks that the meter stops the run, the last call has tools off, and the wrap-up instruction reached the system prompt. This proves our logic, not the providers' wire behaviour (that needs a real key; see 08A.2, Part 2).

python
# provider_loops_test.py
"""Exercise the control flow of provider_loops.py with stand-in clients shaped like the SDK objects.
This checks OUR logic (meter, wrap-up, stop signals). It says nothing about the real wire behaviour."""
from types import SimpleNamespace as NS

from provider_loops import Meter, anthropic_loop, openai_loop
from usage_fields import Prices

PRICES = Prices(input=2.0, output=10.0)        # made-up round numbers
TOOLS: list[dict] = []


def run_tool(name: str, args: dict) -> str:
    return f"{name} ok"


class FakeOpenAI:
    def __init__(self) -> None:
        self.calls: list[dict] = []
        self.responses = NS(create=self._create)

    def _create(self, **kw):
        self.calls.append(kw)
        usage = NS(input_tokens=1000, output_tokens=100, input_tokens_details=NS(cached_tokens=0, cache_write_tokens=0))
        if kw["tool_choice"] == "none":
            return NS(status="completed", incomplete_details=None, usage=usage, output=[], output_text="Partial: found two facts.")
        item = NS(type="function_call", call_id=f"c{len(self.calls)}", name="search", arguments='{"q": "x"}')
        return NS(status="completed", incomplete_details=None, usage=usage, output=[item], output_text="")


class FakeAnthropic:
    def __init__(self) -> None:
        self.calls: list[dict] = []
        self.messages = NS(create=self._create)

    def _create(self, **kw):
        self.calls.append(kw)
        usage = NS(input_tokens=1000, output_tokens=100, cache_read_input_tokens=0, cache_creation_input_tokens=0)
        if kw["tool_choice"]["type"] == "none":
            return NS(stop_reason="end_turn", usage=usage, content=[NS(type="text", text="Partial: found two facts.")])
        block = NS(type="tool_use", id=f"t{len(self.calls)}", name="search", input={"q": "x"})
        return NS(stop_reason="tool_use", usage=usage, content=[block])


for name, loop, client in [("openai", openai_loop, FakeOpenAI()), ("anthropic", anthropic_loop, FakeAnthropic())]:
    out = loop(client, "model-name", "task", TOOLS, run_tool, Meter(PRICES, max_steps=3))
    print(name, {k: out[k] for k in ("status", "reason", "partial")}, "cost=%.4f" % out["cost"])
    for c in client.calls:
        tc = c["tool_choice"]
        sysmsg = c.get("instructions") or c.get("system")
        print("   call: tool_choice=%s, wrap-up in system prompt=%s" % (tc, "Stop using tools" in sysmsg))
Output · real, run with Python 3.14 on 1 December 20268 lines
openai {'status': 'stopped', 'reason': 'steps', 'partial': True} cost=0.0090
   call: tool_choice=auto, wrap-up in system prompt=False
   call: tool_choice=auto, wrap-up in system prompt=False
   call: tool_choice=none, wrap-up in system prompt=True
anthropic {'status': 'stopped', 'reason': 'steps', 'partial': True} cost=0.0090
   call: tool_choice={'type': 'auto'}, wrap-up in system prompt=False
   call: tool_choice={'type': 'auto'}, wrap-up in system prompt=False
   call: tool_choice={'type': 'none'}, wrap-up in system prompt=True

Both loops made two normal calls, then a third with tool_choice set to none and the wrap-up instruction in the system prompt, and returned partial=True with reason steps. With a real key the output would look the same in shape, with real text and real costs; label any such run as illustrative and do not paste keys.


Part 7: How frameworks do it#

Reference

Now that you have built the controls by hand, here is what the frameworks expose. All details below were checked against each project's documentation on 1 December 2026.

Framework Step or turn limit Spend limit What happens at the limit
OpenAI Agents SDK max_turns on Runner.run, run_sync and run_streamed (None disables it) Not covered in the page we checked Raises MaxTurnsExceeded, unless you pass error_handlers={"max_turns": handler}; the handler returns a RunErrorHandlerResult whose final_output becomes the result, so you can return a controlled partial answer (docs)
Claude Agent SDK max_turns / maxTurns max_budget_usd / maxBudgetUsd (includes subagent spend) Returns a result with subtype error_max_turns or error_max_budget_usd and no result field; every result carries total_cost_usd, usage and num_turns (docs)
LangGraph recursion_limit in the run config None built in Raises GRAPH_RECURSION_LIMIT when the graph reaches the maximum number of steps before a stop condition (docs); the page we checked does not state the default value

What stands out is what these documented controls are: step caps, spend caps and an error at the limit. The reserve-based wrap-up, progress-based stagnation detection and the partial-work contract in this lesson are not among the options on the pages we checked, so plan to build them on top (the Agents SDK's error handler is the closest hook). The same goes for approvals, idempotency and tracing. That is the lesson of 08A.2, Part 5: helpers remove the loop, not the engineering.


Part 8: Evaluate it#

Loop control is only as good as its numbers. This part says what to measure, then gives a tiny eval of the detectors you built.

8.1 Where to read first#

Concept lessons first:

Then the tooling (required unless marked optional):

8.2 What to measure#

Metric How Why
Stop-reason distribution Count runs by status and reason A rising steps budget share means the limit is too tight or the agent got worse
Budget-hit rate Share of runs ending on any budget Near zero means limits may be too loose to protect you; high means too tight
Stuck-run recall and delay Of runs that were really stuck, how many a detector caught, and how many steps after onset A detector that fires at step 40 saved little
False-alert rate Healthy runs that triggered an alert (and how many were then wrongly stopped) Wrongly killed work is a product bug
Overshoot Spend beyond the limit (money, seconds) Tells you how big the reserve must be
Partial-result usefulness Of stopped runs, the share whose findings let a human or retry finish faster The reason for graceful degradation
Cost per successful task Money divided by successes (10A.7, 5.6) Budgets must not just trade cost for failures

8.3 A concrete tiny eval: score the detectors#

Inputs: seven labelled traces: four stuck (identical, ping-pong, paraphrased, phantom writes) and three healthy (four different topics, a write that really moves, and legitimate polling). Metric: per stuck trace, the first step at which any detector alerts; per healthy trace, whether any detector alerts. Pass rule (for a real suite): at least 90% of stuck runs caught within 2 steps of onset, and at most 5% of healthy runs alerted, measured on enough traces to have a meaningful interval (10A.7, Part 5); seven is only a demo. Because the detectors are pure functions of the history, the eval replays each trace one step at a time with no model calls.

python
# detector_eval.py
"""Score the stagnation detectors on labelled traces: how many stuck runs do they catch, and how soon,
and how many healthy runs would they wrongly stop? Replay needs no model calls at all."""
from loopctl import DETECTORS, Limits
from scenarios import call, run, say

# (label, is_stuck, script). `onset` = the step where the run really became stuck (1-based).
CASES = [
    ("same call x5",          True, 1, [call("search_docs", query="refund")] * 5),
    ("ping-pong x3",          True, 1, [call("search_docs", query="refund"), call("read_page", page_id="shipping")] * 3),
    ("paraphrases x5",        True, 2, [call("search_docs", query=q) for q in
                                        ("refund", "return", "refund policy", "return policy", "refunds")]),
    ("phantom writes x5",     True, 1, [call("set_status", status="open", note=f"n{i}") for i in range(5)]),
    ("healthy: 4 topics",     False, 0, [call("search_docs", query=q) for q in ("refund", "shipping", "warranty", "privacy")]),
    ("healthy: write moves",  False, 0, [call("set_status", status="pending"), call("set_status", status="closed"),
                                         call("search_docs", query="refund")]),
    ("healthy: polling job",  False, 0, [call("check_job")] * 3),
]

stuck = [c for c in CASES if c[1]]
healthy = [c for c in CASES if not c[1]]
print(f"{'case':24s}{'first alert at step':>22s}  which detector")
caught, delays, false_stops = 0, [], 0
for label, is_stuck, onset, script in CASES:
    r = run(label, script + [say("done")], Limits(max_steps=20), detectors=[], quiet=True)
    first = None
    for n in range(1, len(r.history) + 1):          # replay the trace one step at a time
        hit = [d for d in DETECTORS if DETECTORS[d](r.history[:n])]
        if hit:
            first = (n, hit[0])
            break
    print(f"{label:24s}{(str(first[0]) if first else '-'):>22s}  {first[1] if first else ''}")
    if is_stuck and first:
        caught += 1
        delays.append(first[0] - onset)
    if not is_stuck and first:
        false_stops += 1
print()
print(f"stuck runs caught: {caught}/{len(stuck)}   mean delay after onset: {sum(delays) / len(delays):.1f} steps")
print(f"healthy runs that would be alerted: {false_stops}/{len(healthy)}  (an alert means a nudge, not a stop)")
Output · real, run with Python 3.14 on 1 December 202611 lines
case                       first alert at step  which detector
same call x5                                 3  repeated_call
ping-pong x3                                 4  ping_pong
paraphrases x5                               4  no_new_information
phantom writes x5                            4  writes_change_nothing
healthy: 4 topics                            -  
healthy: write moves                         -  
healthy: polling job                         3  repeated_call

stuck runs caught: 4/4   mean delay after onset: 2.5 steps
healthy runs that would be alerted: 1/3  (an alert means a nudge, not a stop)

All four stuck patterns were caught, on average 2.5 steps after onset (onset was set by hand per case; the alerts came at steps 3 and 4). One of three healthy runs raised an alert: the polling run, as expected from 5.3. Under the pass rule above this would fail the false-alert criterion, and the fix is a design change rather than a threshold tweak: a legitimate-repeat allowance (for example, do not count repeated_call when the results differ), or keep the alert as a nudge only. That is what evaluation is for. Change the detector, rerun the replay, and keep the labelled traces as a regression set (10A.8).


Common misconceptions#

  • "max_steps is enough." It caps the number of calls, not their cost, their duration or whether they accomplish anything. A 10-step run with 100,000-token contexts can cost more than a 50-step one with small contexts.
  • "The provider's max_tokens is a budget." It caps one response. A run is many responses.
  • "input_tokens means the same thing everywhere." OpenAI includes cached tokens in it; Anthropic does not. Normalize before you add.
  • "Stopping at the limit is safe." Checks are before the call, and the call that crosses the limit still completes. Keep a reserve.
  • "A timeout stops the work." A timeout check between steps cannot stop a long tool, and a client-side timeout may still bill. You need cancellation, and you need to expect the bill.
  • "If calls differ, it is not looping." Paraphrased searches, cycles and phantom writes all differ call by call. Track progress, not just repeats.
  • "A detector alert means stop." It is a hypothesis. Nudge first; stop on the second alert.
  • "A stopped run should return an error." It should return partial work with a status, a reason and what is missing.

Key takeaways#

  • Loop control answers four questions: done? may it continue? is it progressing? what do we return on stop?
  • Name every stop in a stop-reason taxonomy. Budget, time and stagnation stops are yours alone; the provider reports truncation, refusal and context-full.
  • Read usage into one shape, then price it. OpenAI's input_tokens includes cached tokens; Anthropic's excludes them. Prices go in config, from the pricing page.
  • Gauges with reserves unify steps, tokens, money and time. Normal work stops early so a wrap-up call still fits. The call that crosses a limit still happens, so size the reserve and cap each call.
  • Deadlines need cancellation. Per-tool timeouts become error results; the run deadline cancels in-flight work; partial work must live outside the cancelled scope.
  • Stagnation is the absence of progress: no new information, no changed state, no new action. Use detectors that match each failure and keep them as pure functions over the history so you can replay traces.
  • Nudge, then stop. The first alert is a hypothesis.
  • A stopped run returns partial work with status, reason, findings, spend and the writes it made.
  • This lesson owns per-run limits; organization limits belong to 11B.6 and 11B.7.
  • Frameworks give you step and spend caps with an error at the limit; the rest is yours.

Terms introduced in this lesson#

Term Meaning
Stop condition A rule that ends the loop, named so the run never ends silently
Stop reason The recorded cause of a stop: completed, a budget, a deadline, stagnation or a provider signal
Per-run budget A limit on one execution of one loop (steps, tokens, money, time)
Gauge A limit, an amount used and a reserve, used for each resource
Reserve The part of a limit kept back for the wrap-up call; normal work may not use it
Soft limit A fraction of a limit at which the model is warned to wrap up
Hard limit The point at which work is cancelled or refused
Usage normalization Converting each provider's usage fields into one shape before pricing
Prompt-cache tokens Input tokens read from, or written to, a prompt cache, priced differently from fresh input
Deadline A time limit for a run, enforced between steps and by cancellation
Per-tool timeout A limit on one tool call; a timeout becomes an error result
Stagnation A run that stays busy without making progress
Progress New information, a changed world, or a new action
Ping-pong cycle A repeating pattern of two or three different calls
Result novelty The share of a step's result words not seen in earlier steps
World fingerprint A hash of the state the tools change, used to tell whether a write did anything
Phantom write A write that reports success but changes nothing
Nudge A message telling the model it looks stuck and should change approach
Wrap-up call The reserved final model call, with tools off, that summarizes what was found and what is missing
Digest A summary of the trace built in code, with no model call
Partial result The output of a stopped run: status, reason, findings, spend and a flag saying it is incomplete
Overshoot Spend beyond a limit caused by the call that crossed it

Exercises#

  1. Tune the reserve. In scenario 3, set reserve_cost_usd to 0 and then to 0.01. What happens to the final spend and to the wrap-up call in each case? Find the smallest reserve that still lets the wrap-up run. Hint: with a zero reserve the loop only stops once what is left is zero or less, so the model may be allowed one more full step before the wrap-up; with 0.01 it stops after one step. Compare spent and the log line.
  2. A fifth detector. Add error_streak: fire when the last 3 steps each contained a tool error. Add a tool-error scenario using fail_tool and show the matrix row. Hint: write a function over history that checks c.is_error for every call in the last three steps, register it in DETECTORS, and add a case to CASES in stagnation_demo.py.
  3. Fix the false positive. Make repeated_call ignore a repeat when the call's results are different each time, and re-run detector_eval.py. What is the false-alert rate now, and what did you lose? Hint: compare the results of the repeated signature's occurrences; if the result texts differ, do not count them. You will lose detection of a stuck loop whose results contain a changing timestamp, which is the same trade-off as in 5.5.
  4. Cancel mid-tool. Extend deadline_async.py so the run deadline also records which tool was running when it fired. Hint: have each tool append its name to a running list on entry and remove it in a finally block; after the timeout, whatever is still in the list was cancelled mid-flight.
  5. A usage test. Write three tests for from_openai and from_anthropic with objects whose cache fields are missing or None. Hint: use SimpleNamespace objects like usage_demo.py; the adapters use getattr(..., 0) or 0 so a missing field counts as zero. Decide whether treating a missing field as zero is safe for a budget, and what you would do instead.
  6. Replay production traces. Suppose your tracing records one JSON line per step with the tool name, arguments, result text and a state hash. Write a function that rebuilds StepRecords from such lines and runs every detector, so you can score new detectors on last week's runs. Hint: signature() and StepRecord are already pure data; the only job is parsing. This is the offline-replay idea behind 11A.4.

Check yourself#

  1. Name the four questions loop control answers on every iteration.
  2. Why does a run need a reserve, and what does it buy?
  3. OpenAI reports input_tokens = 12,000 with cached_tokens = 4,000. How many fresh input tokens is that? What is the Anthropic equivalent if input_tokens = 50 and cache_read_input_tokens = 11,950?
  4. Why is max_tokens (or max_output_tokens) not a per-run budget?
  5. Why can a run still overshoot a money budget that is checked before every call?
  6. What is the difference between a per-tool timeout and a run deadline, and what does each produce?
  7. Why must partial work live outside the cancelled scope?
  8. Give three kinds of stall that identical-call counting misses, and the detector for each.
  9. Why nudge before stopping on a stagnation alert?
  10. List what a partial result must contain and why it should flag any writes already made.

Further resources#


← 08A.2 — The Tool Loop: From One Round Trip to an Agent | Module 08A overview | 08A.4 — Harness Engineering: Everything Around the Model →

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