IamBishal

Chapter 16 · Part IV: Capstone

Capstone III, Harden: error handling, cost limits and a small eval suite

Makes the research assistant fail safely and measurably. You sort failures into transient and permanent, retry search with backoff and jitter inside the run's time left, keep one retry layer for model calls and enforce the money budget from configured prices with cost_limit. A stopped run names its limit and lists what it gathered, unchecked. Then you run the eval over repeated trials, write LIMITATIONS.md and decide whether the assistant is ready to share.

40 min read · from Agentic AI Foundations

At the end of Chapter 15, Capstone II, Build, the research assistant answers the question Sam Adeyemi, Kestrel's CTO, asked for: which carriers had the most late deliveries last quarter, and what do public sources say about their service? It counts rows in the shipment export, searches the web, checks every citation against the run's citable set and prints an answer, a cost line and a trace. Every check so far exercised a path where things go right, or where the model got something wrong. This chapter covers the paths where the world goes wrong: a search service that is down, a provider that is overloaded, a key that is rejected, a run that is about to cost more than it should.

By the end you will be able to:

  • sort a failure into transient or permanent, and say who can fix a permanent one;
  • retry transient failures with exponential backoff and jitter, bounded by attempts and by the run's time left, and explain how retries in our code relate to the SDK's own;
  • enforce the money budget from configured prices, with an eighth StopCause, cost_limit;
  • end a stopped run with a result that names the limit and lists, unchecked, what the tools returned before the stop;
  • run Chapter 13's eval over the golden tasks, read pass rate, cost and steps per task, and decide whether the assistant is ready to share.

Every model message in this chapter is fake-model output, scripted by hand and labelled that way. Counts come from the seeded exports, and search results come from Chapter 15's hand-written fixture. Deployment, observability and security hardening belong to Books 6 to 8; this chapter keeps to what one agent run needs.

1. What can go wrong while answering one question

Follow Sam's question through one run. The loop sends it with the system prompt and the four tool definitions. The model calls count_rows on shipments.csv for late shipments per carrier in Q4 2025, then search_web about the top two carriers, then writes a FinalAnswer, which the loop validates and citation-checks. It could also read_file a page of an export or calculate a rate.

sequenceDiagram
    participant L as Agent loop
    participant M as Model
    participant T as Tools
    L->>M: model call ✗ rate limit, overload, timeout, rejected key
    L->>T: count_rows ✗ unknown column
    L->>T: search_web ✗ 503, timeout, dropped connection, refused key
    L->>T: read_file ../kestrel.sqlite ✗ outside the sandboxed folder
    M-->>L: FinalAnswer ✗ invalid JSON or a citation no tool returned
    Note over L: ✗ the money runs out before the answer

Chapter 15 already handles part of this. Tool failures come back to the model as error results instead of crashing the loop (Chapter 6). A final answer that fails validation or citation checking gets one retry, then the run is rejected. Steps, tokens and wall time stop a run with a named StopCause. Three things are missing. Every failure gets the same treatment, so a search that timed out once and a key that will never work look alike. Nothing retries a tool. And RUN_MAX_COST_USD sits in Settings, but nothing enforces it.

2. Transient or permanent

Before writing any retry code, ask one question about a failure: if I send exactly the same request again, could the result be different?

A transient failure is one where the same request may succeed after a wait. The cause sits on the other side of the connection and passes on its own: a rate limit, an overloaded service, a timeout, a connection dropped halfway through a response. The request was fine; the timing was bad.

A permanent failure fails the same way every time until something changes. It helps to ask who has to change it:

  • The model, by sending a different request. A path outside the sandboxed folder, an unknown column for count_rows, a division by zero in calculate and a FinalAnswer with a citation no tool returned are all refused every time, but the next request can be different. This is why tool errors have come back as results since Chapter 6, and why Chapter 5's validate-and-retry adds feedback before asking again.
  • A person, by fixing the setup. A rejected API key, a search key the service refuses and a price missing from models.toml will not get better within the run, however the model phrases its next request.

Only transient failures are worth retrying in code, with the same request. Resending a permanent one costs time, and money on model calls, and changes nothing. Here are the failures this chapter handles, sorted:

FailureWhereKindWhat happens
503 or any 5xx, 429, 408, timeout, dropped connectionsearch_webTransientRetried in code; if it keeps failing, one error result
400 or 422: the query itself was rejectedsearch_webPermanent (the model)One request; the error result invites one plainer query
401, 403, 404 or another 4xxsearch_webPermanent (a person)One request, one error result: "retrying won't help"
{"results": null} or a body without resultssearch_webPermanent (a person)One error result
Path outside the sandboxed folderread_file, count_rowsPermanent (the model)Error result; the file is never opened
Unknown column, bad date, bad expressioncount_rows, calculatePermanent (the model)Error result naming what to change
Timeout, rate limit, overload, connection failure (also in a token count or a compaction call)model callTransientThe SDK retries once; then model_error, "try again later"
Rejected key, invalid requestmodel callPermanent (a person)model_error, "fix the setup first"
Invalid FinalAnswer or a citation no tool returnedmodel outputPermanent (the model)One retry message; then outcome rejected (Chapter 15)
Reply cut off at the output capmodel outputNot retriedtruncated, or the budget that shrank the cap (token_limit, cost_limit)
Not enough money left for the next callrun budgetA limit, not a failureStop with cost_limit

A transient failure that runs out of retries ends up where a permanent one does: as an error result for a tool, or a stopped run for a model call. Retries buy time; they never change what happens when time runs out.

Two rows need a second look. Retrying a model-fixable failure is still a bounded retry, but of a different kind: Chapter 5's validate-and-retry changes the request by adding feedback, once, and needs no wait, because nothing on the other side has to recover. And a 429 is not always transient. Secondary write-ups about the Anthropic API describe a 429 sent when a usage tier's monthly spend cap is reached, with no Retry-After header, which keeps failing until the month rolls over or the tier changes; an agent that treats it as an ordinary rate limit spends its retries on every request. Check your provider's error reference, and if the adapter can tell such an error apart, map it to a permanent kind there. The capstone limits the damage either way: model calls get one SDK retry and no retry of ours, so a misread spend cap costs one extra request and a "try again later" that should have said "fix the setup first". The context window is the other quiet limit. Chapter 9's per-result cap and Chapter 10's compaction keep each request well inside it, and the compaction summary is a model call paid from the same run budget, money included.

3. Classifying failures in code

The kinds live in ch16/failures.py, and everything that needs a kind calls the same classify(). It never imports a provider SDK. Since Chapter 3, each model-client adapter has turned its provider's errors into a ModelError with a kind (timeout, rate_limited, auth, bad_request, provider_error), so classify() reads that kind. The search backend now raises SearchHTTPError for an error status instead of a ToolError, so search_web can decide whether to retry.

ch16-capstone-harden/ch16/failures.py (excerpt)
class FailureKind(StrEnum):
    TRANSIENT = "transient"  # the same request may succeed after a wait
    PERMANENT = "permanent"  # the same request fails until the request or the setup changes


class SearchHTTPError(Exception):
    """The search service answered with an error status. Raised by HttpSearchBackend."""

    def __init__(self, status: int, retry_after_s: float | None = None) -> None:
        super().__init__(f"the search service answered HTTP {status}")
        self.status = status
        self.retry_after_s = retry_after_s  # from a Retry-After header in seconds, if any


TRANSIENT_STATUS = {408, 429}  # request timeout, rate limit; and every 5xx
TRANSIENT_MODEL_ERRORS = {"timeout", "rate_limited", "provider_error"}  # from Chapter 3


def classify(exc: BaseException) -> FailureKind:
    if isinstance(exc, ModelError):  # the adapter already mapped the SDK's error to a kind
        transient = exc.kind in TRANSIENT_MODEL_ERRORS
        return FailureKind.TRANSIENT if transient else FailureKind.PERMANENT
    if isinstance(exc, SearchHTTPError):
        transient = exc.status in TRANSIENT_STATUS or exc.status >= 500
        return FailureKind.TRANSIENT if transient else FailureKind.PERMANENT
    if isinstance(exc, httpx.TransportError):  # timeouts, refused or dropped connections
        return FailureKind.TRANSIENT
    return FailureKind.PERMANENT  # a ToolError, or anything we don't understand: never retry

The last line matters most. A ToolError (bad input, a sandbox refusal) is permanent, and so is any exception the code doesn't recognise, because retrying something nobody understands can only repeat it. Who has to act is not in the kind; it is in the error result's wording, written for the model or for a person. tests/test_retry.py runs seventeen cases through classify(), from a 529 overload to a KeyError. The httpx cases in it are what the tests observe in the pinned httpx 0.28: a timeout, a refused connection, a read error and a broken response all derive from httpx.TransportError.

4. Retries with exponential backoff and jitter

An immediate retry fails exactly when you need it. A service that answers 503 is usually overloaded, and retrying at once adds load at the worst moment. Many clients doing the same thing turn a short slowdown into a long one.

Exponential backoff fixes the timing. The first retry waits base, the second base × 2, the third base × 4, up to a cap. The cap bounds each wait, and a maximum number of attempts bounds how many retries happen at all. But clients that fail at the same moment and use the same formula also retry at the same moment, so the pile-up only moves later. Jitter adds randomness to spread them out. With full jitter, each wait is a random amount between zero and the capped backoff; equal jitter keeps half the backoff fixed and randomises the rest, and decorrelated jitter bases each wait on the previous one. This chapter uses full jitter, the simplest to reason about and to test. AWS simulated 100 clients competing for one resource and found that adding jitter more than halved the total number of calls and clearly shortened the time to finish, compared with backoff alone. Take the direction of that result rather than its exact numbers; it is one simulation with its own assumptions.

Decide what may be retried before writing the helper. AWS's Well-Architected guidance is to retry calls to services that are idempotent and where retries improve availability. All four capstone tools only read, so repeating a search changes nothing on Kestrel's side. A write tool such as Chapter 8's create_return_authorisation can be retried only because it derives an idempotency key from its inputs; a write without one must never go through this helper.

ch16-capstone-harden/ch16/retry.py (excerpt)
@dataclass(frozen=True)
class RetryPolicy:
    max_attempts: int = 3  # SEARCH_RETRY_ATTEMPTS: the first try plus two retries
    base_s: float = 0.5  # SEARCH_RETRY_BASE_S
    cap_s: float = 4.0  # SEARCH_RETRY_CAP_S: no single wait is longer


def backoff_s(retry: int, policy: RetryPolicy, rng: random.Random) -> float:
    """Full jitter: a random wait between 0 and min(cap, base * 2**retry); retry counts from 0."""
    return rng.uniform(0.0, min(policy.cap_s, policy.base_s * 2**retry))


def retry_call[T](
    attempt: Callable[[float], T],  # takes this attempt's timeout in seconds
    policy: RetryPolicy,
    attempt_timeout_s: float,
    time_left: Callable[[], float],  # the run's remaining seconds (BudgetTracker)
    sleep: Callable[[float], None] = time.sleep,
    rng: random.Random | None = None,
) -> T:
    rng = rng or random.Random()
    for n in range(policy.max_attempts):
        try:
            return attempt(min(attempt_timeout_s, time_left()))
        except Exception as exc:
            if classify(exc) is FailureKind.PERMANENT or n + 1 == policy.max_attempts:
                raise  # permanent: retrying can't help; transient: out of attempts
            wait = backoff_s(n, policy, rng)
            hinted = getattr(exc, "retry_after_s", None)  # the server knows its own state
            if hinted is not None:
                wait = max(wait, hinted)
            if wait + MIN_ATTEMPT_S > time_left():  # no time to wait and then make an attempt
                raise
            sleep(wait)
    raise ValueError("policy.max_attempts must be at least 1")

attempt is a function that takes the timeout for one try, so the helper decides how long each try may wait. Four rules are worth reading slowly:

  1. A permanent failure is raised at once, after one try. So is a transient one on the last attempt.
  2. Each try gets min(attempt timeout, time left). A retry never gets a fresh full timeout late in a run.
  3. A Retry-After header from the server replaces our backoff if it asks for longer, because the server knows its own state better than our formula does.
  4. If the wait plus one useful second of attempt (MIN_ATTEMPT_S) doesn't fit in the time left, the helper gives up now instead of sleeping into the deadline.

sleep and rng are parameters, so the tests pass a fake clock and a seeded random generator and check exact numbers without waiting:

ch16-capstone-harden/tests/test_retry.py (excerpt)
def test_each_attempt_gets_only_the_time_left() -> None:
    clock = FakeClock(left=12.0)  # the run has 12 s left; SEARCH_TIMEOUT_S is 10
    attempt, timeouts = failing([httpx.ReadTimeout("stalled")] * 3, clock, took=10.0)
    with pytest.raises(httpx.ReadTimeout):
        retry_call(attempt, RetryPolicy(), 10.0, clock.time_left, clock.sleep, random.Random(1))
    assert timeouts[0] == 10.0
    assert timeouts[1] < 2.0  # not a fresh full timeout
    assert clock.left >= 0.0  # never past the run's time left

The run has 12 seconds left and SEARCH_TIMEOUT_S is 10. The first attempt uses its full 10 seconds and times out; the retry gets under 2 seconds, not another 10, and the run never goes past its time left.

5. Retrying search, and giving the model one clear error

search_web is the only tool that crosses a network, so it is the only tool that retries. Its function still takes its validated arguments only. build_registry binds the rest with functools.partial, as Chapter 14 wrote it, and the one new bound value is SearchRetries: the attempt timeout, the retry policy and the run's BudgetTracker. The registry is built once per run, so binding the run's tracker keeps Chapter 14's convention.

ch16-capstone-harden/ch16/tools.py (excerpt)
@dataclass
class SearchRetries:
    """New in Chapter 16: how search_web spends the run budget."""

    timeout_s: float = 10.0  # SEARCH_TIMEOUT_S, per attempt, cut to the run's time left
    policy: RetryPolicy = field(default_factory=RetryPolicy)  # SEARCH_RETRY_* settings
    tracker: BudgetTracker | None = None  # the run's time left and money; None in unit tests
    sleep: Callable[[float], None] = time.sleep

    def time_left(self) -> float:
        return self.tracker.remaining_seconds() if self.tracker else self.timeout_s


QUERY_REJECTED = {400, 422}  # the request itself was wrong; other 4xx are the setup's problem
NO_MONEY = (
    "The run's money budget can't cover another search request. Answer from what you have "
    "and list what needed the web under `missing`."
)


def search_web(args: SearchWebArgs, backend: SearchBackend, search: SearchRetries) -> list[dict]:
    def attempt(timeout_s: float) -> list[SearchResult]:
        if search.tracker and not search.tracker.charge_search():  # charged when sent
            raise ToolError(NO_MONEY)
        return backend.search(args.query, args.max_results, timeout_s)

    try:
        results = retry_call(
            attempt, search.policy, search.timeout_s, search.time_left, search.sleep
        )
    except (SearchHTTPError, httpx.TransportError) as exc:  # what is left after the retries
        raise ToolError(search_failure(exc, search.policy)) from exc
    return [r.model_dump() for r in results[: args.max_results]]


def search_failure(exc: Exception, policy: RetryPolicy) -> str:
    """One error result for the model: what failed, and that calling again won't help."""
    what = f"HTTP {exc.status}" if isinstance(exc, SearchHTTPError) else type(exc).__name__
    if isinstance(exc, SearchHTTPError) and exc.status in QUERY_REJECTED:  # the model can fix it
        return (
            f"The search service rejected this query ({what}). Try one shorter, plainer query, "
            "or answer from the exports and list what needed the web under `missing`."
        )
    if classify(exc) is FailureKind.PERMANENT:
        said = f"search_web was refused ({what}); retrying won't help."
    else:
        said = f"search_web failed ({what}) after up to {policy.max_attempts} tries in code."
    return (
        f"{said} Don't call search_web again in this run. Answer from the exports and "
        "list what needed the web under `missing`."
    )

Each attempt is charged to the run's money budget before it is sent, and refused if the money left can't cover it. Whatever failure is left after the retries becomes one ToolError with a message written for the model: what failed, that code already retried or that retrying can't help, and what to do instead. Chapter 15's registry asked the model to "retry once" after a timeout; that line now says only that the tool timed out, because retries happen in the tool.

The backend changes in two places:

ch16-capstone-harden/ch16/tools.py (HttpSearchBackend.search, excerpt)
        if response.status_code != 200:  # new: search_web decides whether to retry
            raise SearchHTTPError(response.status_code, retry_after_s(response))
        try:
            items = response.json()["results"]
        except (ValueError, KeyError, TypeError):
            raise ToolError("The search service returned a response without results.") from None
        if not isinstance(items, list):  # new: {"results": null} is an error, not a crash
            raise ToolError("The search service returned no results list.")
        fitted = (fit_result(i) for i in items if isinstance(i, dict))
        return [r for r in fitted if r is not None][:max_results]

An error status becomes SearchHTTPError, so classify() can tell a 503 from a 401. retry_after_s reads a Retry-After header only in its seconds form and ignores the date form. A response whose results is null used to raise a TypeError deep in the parsing, which the registry reported as "search_web failed (TypeError)"; it is now an error result that says what was wrong.

A 400 or 422 means the query itself was rejected, which the model can fix, so that error result invites one plainer query instead. Why not have the registry disable a tool after a refusal? It would change the registry's contract for one tool. The message has nearly the same effect, and if the model ignores it, the step and money budgets bound the cost. The search-refused demo shows the result: every request gets HTTP 401, each search is tried once, and the fake model answers from the exports with the web half under missing.

fake-model output: python -m ch16.cli --demo search-refused (excerpt)
ANSWERED  (confidence: high)
Harbour Express had the most late deliveries in Q4 2025 (139), then Swiftway Parcel (93). Public sources could not be searched.
Claims:
  1. In Q4 2025, Harbour Express had 139 late deliveries and Swiftway Parcel 93, the two highest. [1]
Citations:
  [1] shipments.csv  (late shipments per carrier, Q4 2025)
Missing: what public sources say about the carriers: search_web unavailable

Run: finished after 3 steps (answer retries: 0, search requests: 2)

That is a partial answer written by the model, in Chapter 14's shape: answered, every claim cited, and missing naming what it could not cover. The search-flaky demo is the transient case: the first request gets a 503, the retry succeeds, and the run reports three search requests for two searches.

6. Model calls: one retry layer, and timeouts that fit the run

Model calls already have a retry layer: the provider's SDK. For the Anthropic adapter, as of November 2026, the Python SDK documentation says the SDK retries connection errors, 408, 409, 429 and 500-and-above errors twice by default, with a short exponential backoff, and that requests time out after 10 minutes unless you set a timeout. Chapter 11's OpenAI-compatible adapter has no SDK; it retries MAX_RETRIES times itself, immediately, with the same timeout on each try. Chapter 3 set MODEL_TIMEOUT_S (30 seconds) so a hung call can't take the whole run, and Chapter 7 set MAX_RETRIES to 1 inside a loop.

Why not wrap model calls in retry_call too? Because retry layers multiply. With the SDK making up to MAX_RETRIES + 1 tries per call, wrapping it in our own three attempts turns one transient failure into as many as six requests, each with its own timeout, before the loop hears about it. Keep exactly one retry layer per call. For model calls that layer is the adapter's own (the SDK's, for the Anthropic adapter), configured by MAX_RETRIES; for search it is retry_call, because HttpSearchBackend builds its httpx client with no retry setting, so nothing below search_web retries a request. The layer you give up has a cost: the adapter's retries leave no record in the trace, and there is no fail-over to a second model. Both belong to production systems, which Books 6 to 8 cover. When a model call still fails, classify() reads the error's kind and the run stops with model_error and advice: "try again later" for a transient error, "fix the setup first" for a permanent one.

The SDK's retry does affect our time budget. From Chapter 7, the loop passes each call min(MODEL_TIMEOUT_S, time left). Both adapters use that timeout once per try, out of our sight, so a call that started with 20 seconds left could wait close to 40. Chapter 16 divides the time left by the number of tries:

ch16-capstone-harden/ch16/agent.py (excerpt)
def call_timeout(limits: CallLimits, tracker: BudgetTracker) -> float:
    """MODEL_TIMEOUT_S, or the time left shared by the SDK's attempts if that is less."""
    return min(limits.timeout_seconds, tracker.remaining_seconds() / limits.attempts)

CallLimits.attempts is MAX_RETRIES + 1, set by run_research. With the defaults nothing changes until fewer than 60 seconds are left; after that, both tries together fit in the time left. The SDK's short sleep between tries is still outside our control (Chapter 11's adapter doesn't sleep), so a run can end that much past RUN_MAX_SECONDS. The loop's check before every step stops it there.

Every wait takes its limit from the time left in the run budget, so retries can't push the run past it.

So every wait in the run takes its limit from one place, the time left in the run budget: model calls through call_timeout, search attempts and their sleeps through retry_call, and the loop's own checks before each model call and right after each round of tool calls.

7. Enforcing the money budget from configured prices

Chapter 14 put RUN_MAX_COST_USD in the budget with a default of $0.50, and this chapter enforces it. Asking the model to stay within a budget would not work: it can't see the bill, and an instruction is only a request. Like steps, tokens and wall time, the loop enforces the limit in code.

Two prices feed it, and both come from configuration. The model's price per million input and output tokens comes from the configuration's [config.price] table in models.toml, the single price source since Chapter 11. The search price is SEARCH_USD_PER_QUERY. A live run refuses to start without a model price, because a configuration with no price can't enforce a money budget; with SEARCH_ENDPOINT set, it also needs SEARCH_USD_PER_QUERY. A self-hosted model you don't pay per token can carry a price of 0. The demos and the offline eval use illustrative prices, $1 and $5 per million tokens and $0.005 per search request, labelled as such wherever they appear; copy real ones from your providers' pricing pages.

The tracker that already counted tokens and time now counts money:

ch16-capstone-harden/ch16/budget.py (BudgetTracker, excerpt)
    def affordable_output_tokens(self, input_tokens: int) -> int | None:
        """Output tokens the money left can pay for after this input; None: no money limit."""
        left = self.remaining_usd()
        if left is None or self.price is None:
            return None
        input_usd = cost_of(input_tokens, 0, self.price)
        if input_usd >= left:
            return 0
        if self.price.output_per_mtok == 0:  # a free model: output never runs out of money
            return None
        return int((left - input_usd) * MTOK / self.price.output_per_mtok)

    def charge_search(self) -> bool:
        """Before a search request is sent: charge it, or return False if money can't cover it."""
        left = self.remaining_usd()
        price = self.search_usd_per_query or Decimal(0)
        if left is not None and price > left:
            return False
        self.search_requests += 1
        return True

Search requests are charged when sent, whether or not the service bills a failed one, so the total is an upper bound. Model calls are charged from the usage each response reports. The check that matters comes before each model call:

ch16-capstone-harden/ch16/agent.py (run_agent, excerpt)
            # New in Chapter 16: the money check. Price the worst case of one more call
            # (estimated input plus the output cap) and shrink the cap to what money can pay.
            out_cap = min(limits.max_output_tokens, tracker.remaining_tokens())
            affordable = tracker.affordable_output_tokens(fixed_tokens + tokens)
            if affordable is not None and affordable < MIN_CALL_TOKENS:
                cause = StopCause.COST_LIMIT
                break
            money_capped = affordable is not None and affordable < out_cap
            call_limits = CallLimits(
                max_output_tokens=affordable if money_capped else out_cap,
                timeout_seconds=call_timeout(limits, tracker),
            )

fixed_tokens is a local estimate of the system prompt and tool definitions, made once per run; tokens is the history count from Chapter 9's count_tokens. The loop prices the input, works out how many output tokens the money left can pay for, and shrinks this call's output cap to fit, the same way Chapter 7 shrinks it to the tokens left. If fewer than 256 output tokens are affordable, a useful reply can't fit, and the run stops with cost_limit. A reply cut off by a money-shrunk cap also reports cost_limit, just as Chapter 7 reports token_limit for a cap the token budget shrank.

The pre-call check stops an overspend before it happens; the charge after the call keeps the total exact.

A check after the call would only notice an overspend once it had happened. The check before it can still be wrong in one direction: the input side is an estimate. Chapter 7 already checks the run budget before each model call, and the same rule applies to money: a budget is hard in the sense that no new call starts once the limit is reached and each call is capped, so the last call can take a run over by at most that one call. tests/test_money_and_stops.py demonstrates it with a budget of $0.0196: the third call is affordable with a cap of 309 output tokens, the fake model reports more input than the loop estimated, and the run finishes $0.0007 over, less than the one call's $0.0047.

The test for a clean stop does the arithmetic in its comments:

ch16-capstone-harden/tests/test_money_and_stops.py (excerpt)
def test_cost_limit_stops_before_the_call_it_cannot_afford(exports: Path) -> None:
    # Illustrative prices: $1 in, $5 out per million tokens; $0.005 per search request.
    # Steps 1 and 2: 2,400 in + 80 out each = $0.0028 each; two searches = $0.0100.
    # Spent before step 3: $0.0156 of $0.0160. The input alone would cost more than $0.0004.
    result, client = research(exports, carriers(), max_cost="0.016")
    assert result.run.cause is StopCause.COST_LIMIT and result.outcome == "stopped"
    assert len(client.calls) == 2  # the third call was never sent
    assert (result.model_usd, result.search_usd) == (Decimal("0.0056"), Decimal("0.010"))
    assert result.run.stop_detail.startswith("money budget: $0.0156 of $0.0160 spent")
    assert "shipments.csv" in result.gathered  # unchecked, never printed as an answer

How large should RUN_MAX_COST_USD be? Size it from evidence, not from hope, and not from the offline table below, whose prices and token counts are invented. My rule of thumb: take the most expensive trial of any ordinary golden task from a live eval, add 50 to 100 percent headroom, because cost per step grows as the context fills, then re-run the eval and check that no ordinary task ends on cost_limit. Chapter 14's $0.50 is a design value to recompute once you have live numbers. Watch the output cap's share of the worst case too: with small budgets, the price of 1,024 possible output tokens can be most of what is left, so a run may stop with cost_limit while a typical reply would still have fitted. That is the price of a check that never lets a call start without the money to finish it.

Two costs stay outside the total. A model call that fails reports no usage, so nothing is charged, although a provider may still bill for it. And a model that bills extra token types or discounts cached input needs a richer Price before you trust the totals.

8. Stopped runs that name the limit

A run that stops early still owes the person an honest account. Chapter 7's rule stands: only finished is a real answer. Chapter 15's rule stands too: code never writes a FinalAnswer on the model's behalf, so a stopped run gets no synthesized answer and no needs_info written by code. What it gets is two new fields. RunResult.stop_detail names the limit with its numbers, or the model error with advice, and ResearchResult.gathered lists the locations tools returned before the stop. The command line prints both, labelled:

fake-model output: python -m ch16.cli --demo carriers-tight-money
STOPPED: cost_limit (money budget: $0.0156 of $0.0160 spent, too little left for another model call)
PARTIAL, unchecked: no answer was written. Tools returned these locations:
  - https://news.example.com/2025/11/harbour-express-weekend
  - https://reviews.example.com/harbour-express
  - https://reviews.example.com/swiftway-parcel
  - shipments.csv
They are not claims; the trace has every tool result.

Run: cost_limit after 2 steps (answer retries: 0, search requests: 2)
Tokens: 4,800 in / 160 out
Cost: $0.0156 of the $0.0160 budget ($0.0056 model at an illustrative price + $0.0100 search)
Trace: traces/cli/<time>-carriers-tight-money.jsonl

When nothing was gathered, the stopped result says so and still names the cause:

fake-model output: python -m ch16.cli --demo key-rejected (excerpt)
STOPPED: model_error (model error, permanent (auth): the API key was rejected; fix the setup first)
No answer: the run stopped before any tool returned a result.

Why not ask the model for a summary after the limit fires? That call would spend money after the money budget said stop, and it could add claims no checker has seen. A list of locations is less pleasant to read, but every line in it is true. The trace keeps every tool result for anyone who wants the details.

The words partial answer and refusal stay reserved for what the model writes. The four outcomes and exit codes are Chapter 15's: 0 answered (a model-written partial answer is answered with missing), 3 needs_info, 4 rejected, and 5 stopped, which now includes cost_limit. CLI traces stay at traces/cli/<run id>.jsonl, as in Chapter 15, where cli takes the place of Chapter 13's eval id.

9. Running the eval suite over repeated runs

The unit tests show that each path works when a script forces it. The eval asks a different question: across a fixed set of golden tasks, how often does the assistant do the right thing, at what cost and in how many steps? ch16/eval.py is Chapter 13's harness pointed at the capstone. Each trial is a fresh run_research with its own run budget and its own trace at traces/<eval_id>/<task_id>-t<trial>.jsonl, graded by Chapter 15's grade(). EVAL_TRIALS sets the trials per task, and EVAL_MAX_COST_USD caps the whole eval, separately from each run's RUN_MAX_COST_USD. A trial's status (passed, failed, error, skipped) stays separate from the run's StopCause.

ch16-capstone-harden/ch16/eval.py (run_eval, excerpt)
    eval_dir = traces_dir / datetime.now(UTC).strftime("%Y%m%dT%H%M%S%fZ")  # the eval id
    results: list[TrialResult] = []
    spent = Decimal(0)
    for trial in range(1, trials + 1):  # trial-major: a cap hit thins every task evenly
        for task in tasks:
            if spent >= settings.eval_max_cost_usd:
                skipped = TrialResult(
                    task_id=task.id, trial=trial, status="skipped", failures=["eval cap reached"]
                )
                results.append(skipped)
                continue
            path = eval_dir / f"{task.id}-t{trial}.jsonl"
            result = run_trial(task, trial, setup_for, settings, price, path, model_name, sleep)
            results.append(result)
            spent += result.cost_usd
    return results, spent

Trials run trial-major, so if the cap is reached, the skipped trials are spread across tasks instead of piling up on the last ones. The cap is checked before each trial, so the eval can go over it by at most one trial.

The grader checks each run's result in code, never the answer's wording; trial status stays separate from StopCause.

Golden tasks stay in TOML. This chapter adds one, which also shows the two new optional fields, expected_stop and a per-task run_max_cost_usd:

ch16-capstone-harden/golden_tasks.toml (excerpt)
# New in Chapter 16: the money budget. The limit is sized for the offline run (illustrative
# prices: $1 / $5 per million tokens, $0.005 per search request); scale it to your prices.
# The run must stop with cost_limit before the third model call, after both searches.
[[task]]
id = "carriers-tight-money"
input = """Which carriers had the most late deliveries last quarter, \
and what do public sources say about their service?"""
today = 2026-01-15
required_tool_calls = [{ tool = "count_rows" }]
expected_status = "stopped"
expected_stop = "cost_limit"
run_max_cost_usd = "0.016"
max_steps = 8

Offline, each task runs its fake-model script, and on trials 2 and 4 the search service answers 503 to its first request, so the report shows what retries cost. The service in ch16/offline.py serves the hand-written fixture through the real HttpSearchBackend and an httpx.MockTransport, so the request, status and retry code all run with no network.

bash
cd ch16-capstone-harden
uv run python -m ch16.eval                                     # fake model, no key
uv run --env-file .env python -m ch16.eval --live --config hosted-sdk
fake-model output: python -m ch16.eval (5 trials per task)
[fake model: scripted replies and token counts, hand-written search results,
 illustrative prices; tool results come from the seeded exports]
task                         pass  pass^k  avg cost  max cost  avg steps stop causes
carriers-late-last-quarter   5/5   yes     $0.0223   $0.0253   3.0       finished=5
lost-by-one-carrier          5/5   yes     $0.0075   $0.0075   2.0       finished=5
zero-in-a-covered-month      5/5   yes     $0.0075   $0.0075   2.0       finished=5
quarter-not-covered          5/5   yes     $0.0075   $0.0075   2.0       finished=5
sandbox-probe                5/5   yes     $0.0075   $0.0075   2.0       finished=5
carriers-tight-money         5/5   yes     $0.0156   $0.0156   2.0       cost_limit=5
overall                      30/30 6/6     spent $0.3395 of the $0.50 eval cap, 0 skipped

Read it per row. carriers-late-last-quarter passes every trial in three steps; its average cost, $0.0223, sits above its usual $0.0203 because the two faulty trials each paid for one extra search request, and the maximum column shows that trial at $0.0253. The other four tasks each take two steps, one tool call and a final answer, and cost $0.0075. carriers-tight-money passes because it stops with cost_limit, exactly as its task expects, at $0.0156 against a $0.016 budget. The whole eval spent $0.3395 of its $0.50 cap and skipped nothing.

Now the honest part. The scripts are written to pass, so this run proves the harness, the checks and the failure handling work together; it says nothing about how a real model behaves. Every offline trial of a task is identical by construction, which is why every pass rate is 5/5. Only a live eval measures a model, and there the trials will differ, because sampling varies (Chapter 2).

10. Known limitations

Write down what the assistant does not do. Without that list, a reader who sees 30 of 30 may assume it does more.

ch16-capstone-harden/LIMITATIONS.md
# Known limitations of the research assistant (Chapter 16)

What the assistant does not do, as of the end of *Agentic AI Foundations*. Lines marked
"Next" point to a later book in the series.

- One agent loop, one model, four read-only tools (search_web, read_file, count_rows,
  calculate). No design patterns beyond the agent loop. Next: Book 4.
- One agent: no hand-offs between agents. Next: Book 5.
- No retrieval over Kestrel's internal documents and no state between questions: every run
  starts with an empty conversation. Next: Book 2.
- The tools are local Python functions. No other program can call them; they are not exposed
  over MCP. Next: Book 3.
- The file sandbox is a path check, not process isolation. Delimiting tool results reduces the
  risk from instructions hidden in web snippets; it does not remove it. Next: Books 6 to 8.
- No deployment, monitoring or fail-over: the SDK's retries leave no record in the trace, and
  there is no second model to fall back to. Next: Books 6 to 8.
- The assistant can cite only what search_web returned. For carriers the web says nothing
  about, the answer lists the web half under `missing`.
- The search backend is illustrative: adapt HttpSearchBackend to your service's API before
  trusting its error handling.
- Prices are configuration and they drift. Recheck `[config.price]` in models.toml and
  SEARCH_USD_PER_QUERY before trusting a cost or a money budget.
- The money check before each call uses an estimate of the input, so the last call can go over
  the money budget by at most that one call. Every search request is charged when sent, which
  may overstate what a provider bills for a failed request.
- A model call that fails returns no usage, so it is not charged, although a provider may still
  bill for it. A 429 is classified as transient; a provider's spend-cap 429 is really permanent,
  so check your provider's error reference and map it in the adapter if it can be told apart.
- A stopped run prints what the tools returned, unchecked, and no answer. It never asks the
  model for a summary after a limit is hit.
- The offline eval runs fake-model scripts: it tests the harness, the checks and the failure
  handling, not a model. Only a live eval (`python -m ch16.eval --live`) measures a model, and
  six golden tasks are a small sample.

Lines marked "Next" point to later books. On the autonomy spectrum the assistant stays at point 4, an agent with narrow tools and a tight budget, and that is a choice: four read-only tools, no writes to any Kestrel system, a known maximum cost per question. Point 5 would mean wider tools, and nothing in Sam's request needs them.

11. Is it ready to share?

Decide your bar before you read results. For an internal assistant that Sam's team will try, a reasonable bar is: every golden task passes at least four trials in five, no ordinary task ends on a limit, no citation falls outside the citable set and nothing is read outside the sandboxed folder. The last two are rules, not rates: one invented citation is enough to fail.

Apply it to the evidence in this chapter. Offline, every task passes 5 of 5, the only task ending on a limit is the one designed to, the citation checker accepted only tool-returned locations and the file sandbox refused every path outside the exports. So the harness, the budgets and the failure handling are ready to share: Sam's team can run the folder, read the traces and trust that a run stops where its budget says. The assistant's answers are not yet ready to share, because no live eval has been run in this book. The next step is to run python -m ch16.eval --live with your model, under an eval cap you are comfortable with, apply the same bar, and add golden tasks from the questions Sam's team actually asks. Six tasks are a start, not proof.

12. Exercises

Each exercise uses ch16-capstone-harden/ and needs no API key. Run uv run pytest after each change.

1. Classify five failures. Give the kind and who must act for: a search 403, a search 429 with Retry-After: 2, a model timeout after the SDK's retry, count_rows with an unknown column, and read_file("../kestrel.sqlite"). Verify: add one case per failure to the test_classify table in tests/test_retry.py.

2. Try equal jitter. Change backoff_s to return half the capped backoff plus a random amount up to the other half. Verify: test_full_jitter_stays_under_the_capped_backoff still passes; print both sequences with the same seed and explain what never waiting close to zero does for clients that retry together.

3. Make the eval cap bite. Run EVAL_MAX_COST_USD=0.10 uv run python -m ch16.eval. Verify: every task still runs at least one trial, the skipped trials are counted in the last line, and the spend goes over $0.10 by less than one trial.

4. Break the fake script. In ch16/eval.py, change the faulty trials' statuses to [503, 503, 503]. Verify: the two faulty carriers trials now show as errors. Explain why: the script can't adapt to a failed search the way a model could.

13. Chapter summary and where the series goes next

The research assistant now fails the way it was designed to. Every failure is transient or permanent, and a permanent one is fixed either by the model, through an error result, or by a person, through a clear message. Search retries transient failures with exponential backoff and full jitter, bounded by attempts and by the time left, and gives the model one clear error when retries run out. Model calls keep exactly one retry layer, the SDK's, and each call's timeout leaves room for its retry. Money is checked before every model call from configured prices, charged after it from reported usage and charged per search request, and cost_limit stops a run that can't afford its next call. A stopped run names its limit and lists what it gathered, unchecked, or says that it gathered nothing. The eval turns all of it into one row per golden task: pass rate, cost and steps.

That completes the book. You started with a single model call and finished with an agent you can read line by line, whose budgets are enforced in code and whose eval report and LIMITATIONS.md say what it can and can't do. Book 2, Context, Memory and Retrieval, starts from the second limitation: retrieval over Kestrel's internal documents and state that lasts between runs, built on the same model client, loop, run budget and eval. Book 3 exposes tools over MCP so other programs can use them, and Book 4 covers the design patterns this book deliberately left out.

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.