11B.8 The Cost of Agents and Long Contexts, Prompt Caching per Provider, and the Cost of Running Evals

ProductionLesson 8 of 87,418 words7 parts
Module 11B · 0 of 8 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8

An agent that "works" in a demo can cost ten times what you expected in production, and the reason is usually arithmetic, not a bug. Every step re-sends the whole conversation. Every sub-agent pays for its own copy of the instructions. A long prompt can cross a price threshold and cost several times more per token. Prompt caching can claw most of that back, but only if your traffic and your prompt layout cooperate. And your evals are a workload too: judge calls, repeated epochs and CI runs can quietly become one of your biggest bills. This lesson gives you the formulas, the calculators and the strategy for all four. It is the third lesson of the A6 set: 11B.6 is about who may spend, 11B.7 is about speed limits and stopping, and this one is about what things cost and how to make them cost less.

What you'll learn

  • Why an agent's input cost grows faster than its number of steps, how to calculate it, and where its tail comes from
  • The multi-agent multiplier: why an orchestrator with workers costs a multiple of one agent, and what caching does and does not change
  • Long-context price tiers and the cliff when a request crosses a threshold (checked on 1 December 2026)
  • Prompt caching on OpenAI and Anthropic: a dated re-check of prices, usage fields and isolation (the mechanics are in 11B.4), and a simulator that tells you which lifetime pays for your traffic
  • A caching strategy you can apply across teams: who owns the prefix, how to measure hit rate, and how caching also buys throughput
  • The cost of running evals: the formula cases x epochs x trials x (1 + judged metrics), the levers that cut it, and a dedicated eval budget with a CI cap that fails the gate instead of passing a partial run
  • How to compare two designs by cost per successful task instead of cost per run

What you don't need

  • API keys. The calculators, the cache simulator, the eval planner and the tests are plain Python and run offline. The key-needing provider snippets for caching live in 11B.4, not here.
  • The details of how a prefix cache works (blocks, hash chains, KV caches): that is 11B.4, and this lesson links to it instead of repeating it. The price map is 11B.2.
  • Any evaluation framework. The eval-cost model here is framework-neutral; the DeepEval and Inspect specifics stay in their own lessons, which link back here.

Setup

Python 3.11+ and the standard library only. The eval budget in Part 6 reuses budget_ledger.py from 11B.6: save a copy next to the other files.

bash
uv init costs --bare --python 3.13 && cd costs
# nothing to install: every sample uses only the standard library
# copy budget_ledger.py from lesson 11B.6 into this folder

As of 1 December 2026. Prices and caching rules were read from the providers' pricing and documentation pages on that date, and the price rows in the code are marked with the page they came from. Prices are parameters, not constants: check the pricing page before you rely on a number, and keep prices in configuration.

Every code block starts with a comment giving its file name. Save the files in one folder and run them with python3.


What you must be able to do after this lesson#

  • Calculate what an agent run costs from its prefix size, tokens added per step and step count, with and without caching, and explain why the bill grows faster than the steps
  • Report agent cost as p50, p95 and cost per successful task, and explain why the mean hides the expensive runs
  • Estimate a multi-agent run against a single-agent run and decide whether the multiplier buys measurable success
  • Find a long-context price threshold, price a request on both sides of it, and guard against crossing it by accident
  • Choose a prompt-cache lifetime for a traffic pattern by simulating its arrival gaps, and own a shared prefix across teams
  • Plan the cost of an eval suite from cases, epochs, trials and judged metrics, and give evals a budget whose capped runs fail the gate

Why this matters for an AI engineer#

Cost is the part of an LLM system that most often surprises the people who built it. The surprises come from four places, and this lesson covers each.

You'll hear... You'll understand it after...
"Why did a 20-step agent cost 3x a 10-step one?" 1.1 Why the bill grows faster than the steps
"The multi-agent version is better but costs 3x." Part 2 and Part 7
"We crossed 100K tokens and the price jumped." Part 3
"Caching saves 90%." (it does not always) 4.2 Which lifetime pays for your traffic
"Who owns the shared prompt prefix?" Part 5
"Our nightly eval costs more than the feature." Part 6

Part 1: What an agent really costs#

1.1 Why the bill grows faster than the steps#

The model API is stateless: each call re-sends the whole conversation. With a fixed prefix of S tokens and a tokens added per step, N steps send:

text
total input tokens = N x S + a x N x (N - 1) / 2

The second term grows with the square of N, so a 20-step run costs more than twice a 10-step run. This is the quadratic growth that 11B.2 derives in full.

1.2 The calculator#

This calculator prices a loop with and without caching. The price rows were read on 1 December 2026 (Anthropic's pricing page for Claude Sonnet 5.5 and Haiku 5.5, OpenAI's for gpt-6.2-sol). The caching model assumes every step lands inside the cache lifetime, the first step writes the whole prefix at the cache-write price, and later steps read what was already sent and write only the new part. Save as agent_cost.py:

python
# agent_cost.py: what an agent run, a multi-agent run and a long prompt cost (lesson 11B.8)
"""Pure arithmetic. Prices are parameters (USD per million tokens), never constants of nature.
The rows below were read from the providers' pricing pages on 2026-12-01; re-read them before you rely on them."""
from __future__ import annotations

from dataclasses import dataclass


@dataclass(frozen=True)
class Price:
    name: str
    input: float
    output: float
    cache_read: float
    cache_write: float                 # per million tokens written to the cache
    long_threshold: int | None = None  # prompt tokens above which the long-context tier applies
    long_input: float = 0.0
    long_output: float = 0.0
    long_cache_read: float = 0.0
    long_cache_write: float = 0.0

    def tier(self, prompt_tokens: int) -> tuple[float, float, float, float]:
        if self.long_threshold is not None and prompt_tokens > self.long_threshold:
            return self.long_input, self.long_output, self.long_cache_read, self.long_cache_write
        return self.input, self.output, self.cache_read, self.cache_write


# Anthropic, platform.claude.com pricing page, 2026-12-01. Cache write = the 5-minute write price.
SONNET_55 = Price("claude-sonnet-5-5", 2.00, 10.00, 0.10, 2.50)
HAIKU_55 = Price("claude-haiku-5-5", 0.10, 0.50, 0.01, 0.125, long_threshold=100_000,
                 long_input=0.50, long_output=2.50, long_cache_read=0.05, long_cache_write=0.625)
# OpenAI, developers.openai.com pricing page, 2026-12-01: standard $2 / $10, cached input $0.10, long context
# (over 272K input tokens) $4 input and $15 output. The 30-minute write multiplier (1.25x) is from the prompt
# caching guide for GPT-5.6 and later. The long-context cached and write prices were NOT stated: left at 0.
GPT_62_SOL = Price("gpt-6.2-sol", 2.00, 10.00, 0.10, 2.50, long_threshold=272_000,
                   long_input=4.00, long_output=15.00)


def call_cost(p: Price, fresh: int = 0, write: int = 0, read: int = 0, out: int = 0) -> float:
    """One call. The tier is chosen by the WHOLE prompt (fresh + written + read tokens)."""
    i, o, r, w = p.tier(fresh + write + read)
    return (fresh * i + write * w + read * r + out * o) / 1e6


def agent_run(p: Price, steps: int, prefix: int, per_step: int, out_per_step: int, cached: bool) -> dict:
    """A loop where every step re-sends the whole transcript.
    step t sends prefix + (t-1)*per_step input tokens. With caching, the part already seen is READ,
    the part added since the last call is WRITTEN once, and only the very first call writes the prefix."""
    total_in = total_out = 0
    cost = 0.0
    for t in range(1, steps + 1):
        sent = prefix + (t - 1) * per_step
        total_in += sent
        total_out += out_per_step
        if not cached:
            cost += call_cost(p, fresh=sent, out=out_per_step)
        elif t == 1:
            cost += call_cost(p, write=sent, out=out_per_step)
        else:
            cost += call_cost(p, read=sent - per_step, write=per_step, out=out_per_step)
    return {"input_tokens": total_in, "output_tokens": total_out, "usd": cost}


def multi_agent_run(p: Price, workers: int, worker_steps: int, worker_prefix: int, per_step: int,
                    out_per_step: int, orch_steps: int, orch_prefix: int, summary_tokens: int,
                    cached: bool) -> dict:
    """An orchestrator plus `workers` sub-agents. Each worker pays for its own prefix and its own history;
    the orchestrator re-sends its transcript, which grows by one worker summary per worker."""
    cost = 0.0
    tokens = 0
    for _ in range(workers):
        r = agent_run(p, worker_steps, worker_prefix, per_step, out_per_step, cached)
        cost += r["usd"]
        tokens += r["input_tokens"] + r["output_tokens"]
    r = agent_run(p, orch_steps, orch_prefix, summary_tokens * workers // max(orch_steps, 1), out_per_step, cached)
    return {"tokens": tokens + r["input_tokens"] + r["output_tokens"], "usd": cost + r["usd"]}

Save the driver as demo_agent_cost.py:

python
# demo_agent_cost.py: three questions about agent cost (lesson 11B.8). Run: python3 demo_agent_cost.py
from agent_cost import GPT_62_SOL, HAIKU_55, SONNET_55, agent_run, call_cost, multi_agent_run

print("1. Cost of one agent run grows faster than the number of steps (Sonnet 5.5; prefix 6,000, +800 tokens/step, 400 out)")
print(f"{'steps':>5} {'input tokens':>13} {'uncached $':>11} {'cached $':>9} {'cached/uncached':>16}")
for steps in (5, 10, 20, 40, 80):
    u = agent_run(SONNET_55, steps, 6_000, 800, 400, cached=False)
    c = agent_run(SONNET_55, steps, 6_000, 800, 400, cached=True)
    print(f"{steps:>5} {u['input_tokens']:>13,} {u['usd']:>11.4f} {c['usd']:>9.4f} {c['usd'] / u['usd']:>16.2f}")
u10, u20 = (agent_run(SONNET_55, n, 6_000, 800, 400, False) for n in (10, 20))
print(f"doubling steps 10 -> 20 multiplies uncached cost by {u20['usd'] / u10['usd']:.2f}, not 2.00")

print("\n2. One agent against an orchestrator with 4 workers (Sonnet 5.5, uncached vs cached)")
single = agent_run(SONNET_55, 12, 6_000, 800, 400, cached=False)
single_c = agent_run(SONNET_55, 12, 6_000, 800, 400, cached=True)
multi = multi_agent_run(SONNET_55, workers=4, worker_steps=8, worker_prefix=5_000, per_step=800, out_per_step=400,
                        orch_steps=6, orch_prefix=4_000, summary_tokens=1_000, cached=False)
multi_c = multi_agent_run(SONNET_55, workers=4, worker_steps=8, worker_prefix=5_000, per_step=800, out_per_step=400,
                          orch_steps=6, orch_prefix=4_000, summary_tokens=1_000, cached=True)
print(f"single agent, 12 steps : ${single['usd']:.4f} uncached, ${single_c['usd']:.4f} cached")
print(f"orchestrator + 4 workers: ${multi['usd']:.4f} uncached, ${multi_c['usd']:.4f} cached "
      f"({multi['usd'] / single['usd']:.1f}x and {multi_c['usd'] / single_c['usd']:.1f}x the single agent)")

print("\n3. The long-context cliff: one call with 1,000 output tokens, uncached, at different prompt sizes")
print(f"{'prompt tokens':>14} {'Haiku 5.5':>10} {'x base rate':>15}   {'gpt-6.2-sol':>12} {'x base rate':>15}")
for n in (50_000, 100_000, 100_001, 200_000, 272_000, 272_001, 400_000):
    h = call_cost(HAIKU_55, fresh=n, out=1_000)
    g = call_cost(GPT_62_SOL, fresh=n, out=1_000)
    h_lin = (n * HAIKU_55.input + 1_000 * HAIKU_55.output) / 1e6
    g_lin = (n * GPT_62_SOL.input + 1_000 * GPT_62_SOL.output) / 1e6
    print(f"{n:>14,} {h:>10.4f} {h / h_lin:>14.1f}x   {g:>12.4f} {g / g_lin:>14.2f}x")
Output22 lines
1. Cost of one agent run grows faster than the number of steps (Sonnet 5.5; prefix 6,000, +800 tokens/step, 400 out)
steps  input tokens  uncached $  cached $  cached/uncached
    5        38,000      0.0960    0.0459             0.48
   10        96,000      0.2320    0.0813             0.35
   20       272,000      0.6240    0.1581             0.25
   40       864,000      1.8880    0.3357             0.18
   80     3,008,000      6.3360    0.7869             0.12
doubling steps 10 -> 20 multiplies uncached cost by 2.69, not 2.00

2. One agent against an orchestrator with 4 workers (Sonnet 5.5, uncached vs cached)
single agent, 12 steps : $0.2976 uncached, $0.0960 cached
orchestrator + 4 workers: $0.7192 uncached, $0.2997 cached (2.4x and 3.1x the single agent)

3. The long-context cliff: one call with 1,000 output tokens, uncached, at different prompt sizes
 prompt tokens  Haiku 5.5     x base rate    gpt-6.2-sol     x base rate
        50,000     0.0055            1.0x         0.1100           1.00x
       100,000     0.0105            1.0x         0.2100           1.00x
       100,001     0.0525            5.0x         0.2100           1.00x
       200,000     0.1025            5.0x         0.4100           1.00x
       272,000     0.1385            5.0x         0.5540           1.00x
       272,001     0.1385            5.0x         1.1030           1.99x
       400,000     0.2025            5.0x         1.6150           1.99x

Reading the first table. With a 6,000-token prefix and 800 new tokens per step, a 10-step run costs $0.23 uncached and a 20-step run $0.62: 2.69 times, not 2. At 80 steps the uncached run reads 3 million input tokens and costs $6.34. Caching does not remove the quadratic token count; it lowers the price of the re-read (to 5% on Sonnet 5.5), so the bill still grows faster than linearly but with a much smaller coefficient: the cached/uncached ratio falls from 0.48 at 5 steps to 0.12 at 80. Short runs benefit least, because one cache write premium is a larger share of a small bill.

1.3 What drives the per-step growth#

The a in the formula is what you can control. It is dominated by:

  • Tool results. One unbounded search result or file read can add thousands of tokens that every later step re-reads. Truncate and summarise them at the tool boundary (08A.7).
  • The model's own output, especially reasoning. Reasoning tokens bill as output and may be carried forward (11B.1, 4.4).
  • History you no longer need. Compaction or clearing old tool results turns the growth towards linear; the trade-off is a one-time cache miss (08B.3 and 04.7).
  • The number of steps itself. A hard cap and stagnation detection (08A.3) bound N.

1.4 The tail matters more than the mean#

Averages hide the runs that hurt. Agent cost is fat-tailed: most tasks are cheap and a few loop, retry or fan out. Always report:

  • p50 and p95 (or p99) cost per task, not only the mean;
  • cost per successful task, which is total spend on all attempts divided by the number that succeeded. A cheap agent that fails half the time is more expensive per success than it looks (10A.7, 5.6);
  • the share of runs that hit a budget stop (08A.3 names the stop reasons).

The product formula that turns this into a pricing decision (cost per started task divided by the success rate) is in 13A.6, 6.2.

At the organization level, the per-run budget from 08A.3 bounds the worst run, and the hierarchy from 11B.6 bounds the team. Reserve a run's worst case (maximum steps times a worst-case step) at the feature level before the run starts, so one run cannot silently consume a team's day.


Part 2: The multi-agent multiplier#

Deep-dive

2.1 Where the multiplier comes from#

A multi-agent setup (an orchestrator that hands work to workers, 08D.1) costs more than a single agent for four separate reasons:

  1. Every worker pays for its own prefix. Each worker re-sends its system prompt and tool definitions, and (without caching) re-pays for them at the full input price.
  2. Every worker has its own history, with its own quadratic growth. Four workers of 8 steps each re-read less than one agent of 32 steps would (the quadratic term is smaller for shorter loops), but you now have four of them.
  3. The orchestrator re-reads everything the workers return. Each summary it receives is added to a transcript the orchestrator re-sends every step.
  4. Parallelism concentrates rate-limit pressure. Four workers start at once, which is four times the tokens per minute for a short while (11B.7, including ramp limits).

The second calculator compares one agent doing a 12-step job with an orchestrator and four workers (8 steps each, plus 6 orchestrator steps). The shapes are assumptions for illustration, not measurements. Replace them with your traces. The output is in the second table above:

text
single agent, 12 steps : $0.2976 uncached, $0.0960 cached
orchestrator + 4 workers: $0.7192 uncached, $0.2997 cached (2.4x and 3.1x the single agent)

Two things to notice. The multi-agent run costs 2.4 times as much uncached. And the multiple is higher when cached (3.1x), because caching helps one long loop more than several short ones: each worker's first call pays a cache write premium on its own prefix, and short loops have few steps to earn it back. (If the workers share an identical prefix, a shared cache can serve them all, but only if it is warmed before the workers fan out, and only within one workspace on Anthropic: see Part 5.)

2.2 When the multiplier is worth paying#

The multiplier is not a verdict against multi-agent designs. It is a price tag to put against what you get. Pay it when workers genuinely work in parallel on independent sub-tasks, when separate contexts keep each worker focused, or when a cheaper model can do the worker steps (08D.1 gives the decision rules). Then measure whether you got value: the right metric is cost per successful task, and 08D.2 builds exactly this comparison. Part 7 gives a tiny version.


Part 3: Long contexts and the price cliff#

3.1 What the providers charge for long prompts#

A long context is not just more tokens at the same price. Some models switch to a higher price tier for the whole request once the prompt crosses a threshold. As of 1 December 2026:

Provider and model Threshold What changes Source
Anthropic, Claude 4.6 and later (except Haiku 5.5), and Claude Mythos Preview None The full 1M-token context window is "at standard pricing: a 900k-token request is billed at the same per-token rate as a 9k-token request." Caching and batch discounts apply at standard rates across the window Anthropic pricing page
Anthropic, Claude Haiku 5.5 Prompt over 100,000 tokens Input and output both five times the base price: $0.10 to $0.50 input and $0.50 to $2.50 output per million tokens. A request's prompt length counts cache reads and cache writes, so a cache hit does not keep you under the line. Each request is priced on its own Anthropic pricing page
OpenAI, models with long-context pricing (for example gpt-6.2-sol) Over 272K input tokens Higher rates: for gpt-6.2-sol, input from $2.00 to $4.00 and output from $10.00 to $15.00 per million tokens OpenAI pricing page
Gemini Over 200K tokens on Gemini 3.1 Pro (as recorded in 11B.2) About 2x input and 1.5x output Recorded in 11B.2 on 20 November 2026; not re-checked for this lesson

Two details were not stated on the pages read, so they are unverified as of 1 December 2026: whether OpenAI's long-context tier counts cached tokens toward the threshold, and the cached-input and cache-write price at OpenAI's long-context rate. Check before you rely on them.

3.2 The cliff in numbers#

The third table in the output above prices one call with 1,000 output tokens at different prompt sizes, using the Price rows for Haiku 5.5 and gpt-6.2-sol. Look at the rows around each threshold:

text
 prompt tokens  Haiku 5.5     x base rate    gpt-6.2-sol     x base rate
        50,000     0.0055            1.0x         0.1100           1.00x
       100,000     0.0105            1.0x         0.2100           1.00x
       100,001     0.0525            5.0x         0.2100           1.00x
       200,000     0.1025            5.0x         0.4100           1.00x
       272,000     0.1385            5.0x         0.5540           1.00x
       272,001     0.1385            5.0x         1.1030           1.99x
       400,000     0.2025            5.0x         1.6150           1.99x

One extra token at the threshold multiplies the call's cost. On Haiku 5.5, a 100,000-token prompt costs $0.0105 and a 100,001-token prompt costs $0.0525. On gpt-6.2-sol the same 1-token step takes the call from $0.554 to $1.103. A thin margin on the wrong side of a threshold is an expensive bug.

3.3 What to do about it#

  • Count before you send, with the tier in mind. The estimate in 11B.6, 2.1 must use the tier the prompt size selects, or the reservation will be a fraction of the real cost. The Price.tier() method above does this.
  • Guard the threshold. In a wrapper, if a prompt is within a few percent of a threshold, trim it (drop old history, retrieve fewer chunks) or route it to a model without the cliff. Alert on requests that cross a threshold (03.7, 12.5 lists it).
  • Retrieval or stuffing? A full document in context, cached, costs about read price x document tokens per question after the first. Retrieving k chunks costs k x chunk tokens x input price per question plus the retrieval infrastructure. For a large corpus retrieval wins by a wide margin; for one document asked many times within the cache lifetime, a cached full document can be competitive and simpler (11B.1, 4.8 and 07.1 cover the trade-off). A large context is also slower and can be less accurate, so cost is not the only axis (08B.5 covers context rot).
  • Flat pricing is not free. Even where the per-token price is the same at 900K as at 9K, a 900K prompt costs 100 times a 9K one, and an agent loop re-sends it every step.

Part 4: Prompt caching per provider#

Deep-dive

Caching lets a provider reuse the work it already did on the start of your prompt, and bills that part at a fraction of the input price. How it works inside (the KV cache, why the prefix must match exactly, blocks and hash chains, what invalidates it) is 11B.4, Parts 1 to 3, and its comparison table covers more providers than this lesson. This part adds two things: a dated check of what OpenAI and Anthropic document today, and a simulator that answers the question every team asks: "which lifetime should we pay for?"

4.1 What OpenAI and Anthropic document today (1 December 2026)#

11B.4, 4.6b holds the comparison table across providers (written on 20 November 2026), and 03.7, Parts 6 and 7 give the field-by-field detail. A re-check of the providers' own pages on 1 December 2026 agreed with them. This is what the simulator in 4.2 needs, and what the re-check added:

  • Anthropic prices: write 1.25x base input (5-minute lifetime, the default, refreshed free each time the entry is used) or 2x (1 hour); read 0.1x, 0.05x on Claude Opus 5.5 and Sonnet 5.5, 0.025x on Fable 5.1, 5.2 and Mythos 5.1, 5.2. Multipliers stack with batch and data-residency pricing.
  • OpenAI prices: on GPT-5.6 and later, write 1.25x (30 minutes, the default) or 2.5x (12 hours), read 0.1x (0.05x on some models). Earlier models cache automatically with no write charge and a model-dependent cached-input price.
  • Usage fields differ. On Anthropic input_tokens counts only the tokens after the last breakpoint, so total input is input_tokens + cache_creation_input_tokens + cache_read_input_tokens. On OpenAI input_tokens is the whole input and input_tokens_details.cached_tokens is a subset of it (cache_write_tokens on GPT-5.6 and later).
  • Isolation. Organizations never share a cache. Anthropic isolates per workspace on the Claude API, Claude Platform on AWS and Microsoft Foundry, and per organization on Amazon Bedrock and Google-managed Claude on Vertex AI. On GPT-5.6 and later, prompt_cache_key gives separate cache accounting per customer, user or workspace.
  • Added by the re-check. On Amazon Bedrock's bedrock-runtime a top-level cache_control returns 400, so use explicit breakpoints there. OpenAI's guide says organizations without Zero Data Retention default prompt_cache_retention to 24h and ZDR organizations to in_memory (unverified whether this is the default for every listed model). Whether a cache hit extends an OpenAI entry's lifetime was not stated on the page read, so the simulator does not assume it does.
  • Parameter spellings. Anthropic's top-level cache_control is shown in 11B.4, 6.2 and OpenAI's prompt_cache_options in 11B.4, 6.6. Re-check both against the SDK you install.

4.2 Which lifetime pays for your traffic#

A longer lifetime costs more to write and survives longer gaps. Whether it pays depends on how your requests arrive. The simulator replays arrival times against each option and prices the cached prefix relative to not caching (1.00 means no saving, below 1.00 saves, above 1.00 loses). The multipliers are the ones in 4.1: Anthropic write 1.25x for 5 minutes and 2x for 1 hour, read 0.05x as on Sonnet 5.5; OpenAI write 1.25x for 30 minutes and 2.5x for 12 hours, read 0.1x. Save as cache_strategy.py:

python
# cache_strategy.py: which cache lifetime pays for YOUR traffic? (lesson 11B.8)
"""Replays request arrival times against a prefix cache and prices each lifetime option.
Multipliers (verified 2026-12-01): Anthropic write 1.25x (5 min) or 2x (1 hour), read 0.05x on Claude Sonnet 5.5
(0.1x on most other models), a hit refreshes the entry for free. OpenAI GPT-5.6 and later: write 1.25x (30 min)
or 2.5x (12 hours), read 0.1x on most models. For OpenAI the TTL is described as a MINIMUM lifetime and the docs
read do not say a hit extends it, so the OpenAI rows below do not refresh (conservative). Standard library only."""
import random
from dataclasses import dataclass


@dataclass(frozen=True)
class Option:
    name: str
    ttl_s: float
    write_x: float
    read_x: float
    refresh: bool


OPTIONS = [
    Option("Anthropic 5 min", 300, 1.25, 0.05, True),
    Option("Anthropic 1 hour", 3600, 2.00, 0.05, True),
    Option("OpenAI 30 min (no refresh)", 1800, 1.25, 0.10, False),
    Option("OpenAI 12 hours (no refresh)", 43_200, 2.50, 0.10, False),
]


def simulate(arrivals: list[float], opt: Option) -> dict:
    """Cost in units of 'one uncached read of the prefix' (so 1.0 per request when nothing is cached)."""
    expires, cost, hits = None, 0.0, 0
    for t in arrivals:
        if expires is not None and t < expires:
            hits += 1
            cost += opt.read_x
            if opt.refresh:
                expires = t + opt.ttl_s
        else:
            cost += opt.write_x
            expires = t + opt.ttl_s
    return {"relative_cost": cost / len(arrivals), "hit_rate": hits / len(arrivals)}


def patterns() -> dict[str, list[float]]:
    rng = random.Random(2)
    steady = [i * 90.0 for i in range(80)]                                    # 1 request every 90 s for 2 h
    bursty = [b * 1500.0 + rng.uniform(0, 120) for b in range(5) for _ in range(10)]   # 10 in 2 min, then 23 min quiet
    bursty.sort()
    sparse = [i * 720.0 for i in range(10)]                                    # 1 request every 12 min
    return {"steady (every 90 s)": steady, "bursty (10 per 25 min)": bursty, "sparse (every 12 min)": sparse}


if __name__ == "__main__":
    print("Relative cost of the cached prefix per request (1.00 = no caching; lower is better; hit rate in brackets)")
    print(f"{'traffic':<26}" + "".join(f"{o.name:>30}" for o in OPTIONS))
    for label, arrivals in patterns().items():
        row = f"{label:<26}"
        for o in OPTIONS:
            r = simulate(arrivals, o)
            row += f"{r['relative_cost']:>23.2f} [{r['hit_rate']:>4.0%}]"
        print(row)
Output5 lines
Relative cost of the cached prefix per request (1.00 = no caching; lower is better; hit rate in brackets)
traffic                                  Anthropic 5 min              Anthropic 1 hour    OpenAI 30 min (no refresh)  OpenAI 12 hours (no refresh)
steady (every 90 s)                          0.06 [ 99%]                   0.07 [ 99%]                   0.16 [ 95%]                   0.13 [ 99%]
bursty (10 per 25 min)                       0.17 [ 90%]                   0.09 [ 98%]                   0.17 [ 94%]                   0.15 [ 98%]
sparse (every 12 min)                        1.25 [  0%]                   0.24 [ 90%]                   0.56 [ 60%]                   0.34 [ 90%]

Reading it, row by row.

  • Steady traffic (every 90 seconds). Every option hits 95% or more, and the cheapest is the short Anthropic lifetime (0.06), because the 5-minute entry is refreshed for free on every use and its write premium is the smallest. Do not buy a longer lifetime for traffic that keeps the short one warm.
  • Bursty traffic (10 requests in two minutes, then 23 quiet minutes). The 5-minute entry expires between bursts and every burst starts with a fresh write: it saves 83% (0.17), but the 1-hour entry survives the gaps and saves 91% (0.09). The longer lifetime pays.
  • Sparse traffic (one request every 12 minutes). The 5-minute option has 0% hits and costs 1.25: you pay the write premium on every request and never read. That is worse than not caching at all. The 1-hour entry hits 90% and costs 0.24. On OpenAI, the 30-minute option (no refresh assumed) hits 60% and costs 0.56, while the 12-hour option hits 90% and costs 0.34.

4.3 Provider snippets#

The complete Anthropic and OpenAI snippets (automatic top-level cache_control with a 1-hour lifetime, and a per-tenant prompt_cache_key) are in 11B.4, Part 6, so they are not repeated here. Both need a key and are illustrative there. What this lesson adds is how to read the result in one place: on Anthropic, hit ratio = cache_read_input_tokens / (input_tokens + cache_creation_input_tokens + cache_read_input_tokens), and on OpenAI, hit ratio = input_tokens_details.cached_tokens / input_tokens. Using one formula for both is the usual mistake, because of the different meaning of input_tokens. 03.7 normalises both.


Part 5: A caching strategy for an organization#

Deep-dive

11B.4, Part 7 is the checklist for one prompt: tools first, constants in the system prompt, volatile content last, append-only history, do not toggle settings mid-conversation, warm before fanning out. Follow it. This part is the checklist for an organization with many teams and prompts. The per-feature strategy it builds on (stable prefix, lifetime choice, warm-up, multi-turn layout, tenancy) is 11B.3, Part 2.

  1. Give the shared prefix an owner. If ten services start with the same company policy text and tool set, someone must own that block, version it, and change it deliberately. A change invalidates every cache that includes it, so treat it like a deploy.
  2. Standardise the layout. Every team uses the same order: tools, system, static reference and few-shot examples, then history, then volatile content. A layout rule in a shared client library beats a wiki page (03.11).
  3. Decide where cache boundaries meet tenant boundaries. A shared cache saves money but crosses trust boundaries. Both providers isolate caches (OpenAI between organizations, Anthropic between organizations and, on the Claude API, between workspaces). Per-tenant prompt_cache_key values on OpenAI give you separate cache accounting per customer. Where you must keep tenants apart, separate keys cost you hit rate; where you can share a public prefix, share it. 11B.4, 4.6 notes the timing side channel on shared caches.
  4. Choose the lifetime per feature from its traffic gaps, using the simulator above. Different features on the same provider can and should use different lifetimes.
  5. Warm once before a fan-out, and do not change the prefix mid-session. The per-prompt rules (warm before parallel requests, no toggling of model, tools, tool_choice, effort or thinking, compaction costs one miss) are 11B.4, Part 7. Put them in the shared client library so every team gets them.
  6. Batch and caching together. Anthropic's discounts stack: batch (50% off) with caching. Because batches can take longer than five minutes to process, Anthropic recommends the 1-hour lifetime for batches with shared context, and max_tokens: 0 pre-warming is not supported inside a batch.
  7. Plan for no hits. Caching is an optimisation, not a guarantee. Budget and rate-limit with the uncached cost as the worst case (11B.6, 2.1).

5.1 Measure it as a KPI#

Define the cache hit ratio per feature as cached read tokens / total input tokens, track it daily with the cost data from 11B.6, and alert when it falls below its baseline. 11B.3, 2.6 and 03.7, Part 10 own the metrics and the analyser, and 11B.4, Part 8 the debugging guide. A sudden drop is nearly always a deploy that changed the prefix.

5.2 Caching also buys throughput (Anthropic)#

On Anthropic, cache reads do not count toward your input-tokens-per-minute (ITPM) limit; uncached input and cache writes do (rate limits page, 1 December 2026). The page's own example: with a 2,000,000 ITPM limit and an 80% cache hit rate, you can process about 10,000,000 total input tokens per minute. So a good hit rate raises your effective rate limit without a tier change, which makes it a lever for the fair-share design in 11B.7 as well as for cost. Whether OpenAI's rate limits treat cached tokens differently was not confirmed for this lesson (unverified as of 1 December 2026).


Part 6: The cost of running evals#

An eval is a workload like any other, and it is easy to build one that costs more than the feature it tests. The concept is taught here. How a particular framework counts and caps those calls stays in the framework's own lessons, which link back: 10B.12, 13.5 (optional) and 10B.15, 7.6 (optional) for Inspect, and the DeepEval cost sections linked in Part 7.

6.1 The formula#

text
calls = cases x epochs x trials x (1 generator call + 1 judge call per LLM-judged metric)
  • Cases are the rows of your dataset.
  • Epochs are repeated samples of the same case in one run, used to measure variance or pass^k (10A.7, 5.1).
  • Trials are repeats of the whole suite: a CI re-run, a flake check, an A/B arm, a pre-release matrix.
  • Judged metrics are the metrics scored by a model rather than by code. Each adds one judge call per case, and a judge prompt contains the rubric plus the generator's input and output, so it is often larger than the generator's call (10A.8, 3.3 says judge scoring is often several times the generator's token count).
  • Multi-turn and simulated-user evals multiply again: each conversation is many model calls, and a simulator is another model.

Factors multiply. 300 cases, 3 epochs, 2 trials and 3 judged metrics is 300 x 3 x 2 x 4 = 7,200 calls for one release check.

6.2 The planner#

The planner turns a suite description into calls, tokens and dollars before you run anything, and applies the levers that change the price: a cheaper judge, cached judge rubric, batch. Save as eval_cost.py (it imports agent_cost.py above and budget_ledger.py from 11B.6):

python
# eval_cost.py: plan an eval's bill before running it, then cap it with its own budget (lesson 11B.8)
"""calls = cases x epochs x trials x (1 generator call + one judge call per LLM-judged metric).
The planner turns that into tokens and dollars; EvalRun spends from a dedicated budget scope in the
11B.6 ledger and stops cleanly, marking what did not run. Standard library only."""
from __future__ import annotations

from dataclasses import dataclass

from agent_cost import Price, call_cost
from budget_ledger import Ledger, usd


@dataclass(frozen=True)
class EvalSpec:
    name: str
    cases: int
    epochs: int = 1                 # repeated samples of the same case (variance, pass^k)
    trials: int = 1                 # whole-suite repeats (CI re-runs, flake checks, A/B arms)
    judged_metrics: int = 1         # metrics scored by an LLM judge (code graders are free)
    gen_in: int = 3_000             # generator input tokens per call
    gen_out: int = 500
    judge_in: int = 3_500           # judge prompt = rubric + the generator's input and output
    judge_out: int = 300
    judge_cache_hit: float = 0.0    # share of judge input that is a cached rubric prefix
    batch: bool = False             # use a batch API: 50% off (verified for OpenAI and Anthropic, 2026-12-01)


def plan(spec: EvalSpec, gen: Price, judge: Price) -> dict:
    runs = spec.cases * spec.epochs * spec.trials
    gen_calls = runs
    judge_calls = runs * spec.judged_metrics
    gen_usd = gen_calls * call_cost(gen, fresh=spec.gen_in, out=spec.gen_out)
    cached = int(spec.judge_in * spec.judge_cache_hit)
    judge_usd = judge_calls * call_cost(judge, fresh=spec.judge_in - cached, read=cached, out=spec.judge_out)
    total = (gen_usd + judge_usd) * (0.5 if spec.batch else 1.0)
    return {"calls": gen_calls + judge_calls, "gen_calls": gen_calls, "judge_calls": judge_calls,
            "gen_usd": gen_usd, "judge_usd": judge_usd, "usd": total}


class EvalRun:
    """Runs cases one by one against a budget scope. When the next case's WORST-CASE cost does not fit,
    the run stops and reports `complete=False`: a gate must treat that as a failure, not a pass."""
    def __init__(self, ledger: Ledger, path: tuple[str, ...], spec: EvalSpec, gen: Price, judge: Price) -> None:
        self.ledger, self.path, self.spec, self.gen, self.judge = ledger, path, spec, gen, judge

    def run(self, outcomes: list[bool]) -> dict:
        s = self.spec
        per_case = plan(EvalSpec(**{**s.__dict__, "cases": 1, "epochs": 1, "trials": 1}), self.gen, self.judge)["usd"]
        done = passed = 0
        for ok in outcomes:                                   # one entry per (case, epoch) to run
            d = self.ledger.reserve(self.path, per_case, kind="eval", suite=s.name)
            if not d.ok:
                break
            self.ledger.settle(d.reservation, per_case * 0.95)     # pretend the case cost 95% of its worst case
            done += 1
            passed += ok
        return {"planned": len(outcomes), "done": done, "not_run": len(outcomes) - done, "passed": passed,
                "complete": done == len(outcomes)}

Save the driver as demo_eval_cost.py:

python
# demo_eval_cost.py: what do three eval tiers cost, and what does a budget stop? (lesson 11B.8)
import random

from agent_cost import HAIKU_55, SONNET_55
from budget_ledger import FakeClock, Ledger, usd
from eval_cost import EvalRun, EvalSpec, plan

tiers = [
    ("PR smoke", EvalSpec("smoke", cases=20, judged_metrics=1, judge_cache_hit=0.6), SONNET_55, HAIKU_55),
    ("nightly", EvalSpec("nightly", cases=300, epochs=3, judged_metrics=3, judge_cache_hit=0.6, batch=True), SONNET_55, HAIKU_55),
    ("nightly, strong judge", EvalSpec("nightly", cases=300, epochs=3, judged_metrics=3, judge_cache_hit=0.6, batch=True), SONNET_55, SONNET_55),
    ("release", EvalSpec("release", cases=300, epochs=5, trials=2, judged_metrics=3, judge_cache_hit=0.6, batch=True), SONNET_55, SONNET_55),
]
print("(generator and judge columns are list price; the last column applies the 50% batch discount where the tier uses it)")
print(f"{'tier':<24} {'calls':>7} {'judge calls':>12} {'generator $':>12} {'judge $':>9} {'run $ (batch)':>14}")
for label, spec, gen, judge in tiers:
    p = plan(spec, gen, judge)
    print(f"{label:<24} {p['calls']:>7,} {p['judge_calls']:>12,} {p['gen_usd']:>12.2f} {p['judge_usd']:>9.2f} {p['usd']:>14.2f}")

print("\nA month of CI (22 working days): 40 PRs x 3 pushes on the smoke tier, 22 nightlies, 2 releases")
smoke = plan(tiers[0][1], SONNET_55, HAIKU_55)["usd"]
night = plan(tiers[1][1], SONNET_55, HAIKU_55)["usd"]
rel = plan(tiers[3][1], SONNET_55, SONNET_55)["usd"]
month = 40 * 3 * smoke + 22 * night + 2 * rel
print(f"smoke {40 * 3 * smoke:,.2f} + nightly {22 * night:,.2f} + release {2 * rel:,.2f} = ${month:,.2f}")

print("\nA dedicated eval budget: the nightly gets $3.00 a day; today someone raised epochs from 3 to 10")
clock = FakeClock()
ledger = Ledger(clock)
EVAL = ("acme", "evals", "nightly")
ledger.set_limit(("acme", "evals"), 10.00)
ledger.set_limit(EVAL, 3.00)
spec = EvalSpec("nightly", cases=300, epochs=10, judged_metrics=3, judge_cache_hit=0.6)
print(f"planned: {plan(spec, SONNET_55, HAIKU_55)['usd']:.2f} USD (before the budget check)")
rng = random.Random(5)
outcomes = [rng.random() < 0.82 for _ in range(300 * 10)]
res = EvalRun(ledger, EVAL, spec, SONNET_55, HAIKU_55).run(outcomes)
print(res)
print("spent:", usd(ledger.report(EVAL)["used"]), "of", usd(ledger.report(EVAL)["limit"]))
verdict = "FAIL: run incomplete, pass rate not trustworthy" if not res["complete"] else "pass-rate gate applies"
print("gate verdict:", verdict)
print(f"pass rate on the {res['done']} cases that ran: {res['passed'] / res['done']:.3f} (do not report this as the suite's rate)")
Output16 lines
(generator and judge columns are list price; the last column applies the 50% batch discount where the tier uses it)
tier                       calls  judge calls  generator $   judge $  run $ (batch)
PR smoke                      40           20         0.22      0.01           0.23
nightly                    3,600        2,700         9.90      0.84           5.37
nightly, strong judge      3,600        2,700         9.90     16.23          13.06
release                   12,000        9,000        33.00     54.09          43.55

A month of CI (22 working days): 40 PRs x 3 pushes on the smoke tier, 22 nightlies, 2 releases
smoke 27.15 + nightly 118.14 + release 87.09 = $232.37

A dedicated eval budget: the nightly gets $3.00 a day; today someone raised epochs from 3 to 10
planned: 35.80 USD (before the budget check)
{'planned': 3000, 'done': 264, 'not_run': 2736, 'passed': 211, 'complete': False}
spent: $2.9927 of $3.0000
gate verdict: FAIL: run incomplete, pass rate not trustworthy
pass rate on the 264 cases that ran: 0.799 (do not report this as the suite's rate)

Reading it. A PR smoke run (20 cases, one judged metric, cheap judge) costs $0.23, so even 120 pushes a month cost about $27. The nightly suite (300 cases, 3 epochs, 3 judged metrics, batch discount) costs $5.37 with a cheap judge and $13.06 with a strong judge: the judge model is the biggest single choice (the judge column goes from $0.84 to $16.23 at list price). The release tier with 5 epochs and 2 trials is $43.55. A month of CI comes to about $232. None of these are scary alone; the surprise comes when someone changes epochs=3 to epochs=10 for "more confidence" and nobody notices.

6.3 The levers, in the order to try them#

Lever What it does Trade-off Where it is taught
Tiered suites A small smoke tier per PR, a full suite nightly, a release tier with epochs Small tiers catch breakage, not small regressions 10A.8, 3.1
A cheaper judge first A small model or code grader on everything; a strong judge only on disagreements or a sampled audit You must measure the cheap judge's agreement with the strong one first 10A.8, 3.4, 10A.5
Fewer epochs where variance is low Spend epochs only on cases or metrics that are noisy Needs a variance measurement first 10A.7, 5.4
Record and replay Reuse model responses for unchanged (model, prompt, case) Replays must never be reported as fresh measurements; stale answers after silent model updates 10A.8, 3.2
Provider prompt caching Cache the judge's rubric prefix and the generator's shared system prompt (Part 4) Needs a stable prefix and enough hits per lifetime This lesson, 11B.4
Batch 50% off on both OpenAI and Anthropic (checked 1 December 2026), including the judge calls Hours of latency; never for the PR smoke tier 10A.8, 3.3
Sampling Run a stratified subset on PRs, the full set nightly Smaller samples have wider intervals (10A.8, 2.4) 10A.8 Part 2
Skip unchanged work Re-run only the cases affected by a change (hash the prompt, tools and case) Needs a trustworthy dependency map You build it
Stop early Stop a run once the interval clearly clears or fails the threshold Sequential testing needs care to avoid false calls 10A.8, 2.6

A reasonable order: tier the suite, put a cheap judge in front, cache the rubric prefix, batch the nightly and release tiers, and only then reach for sampling or skip logic.

6.4 A dedicated eval budget#

Give evals their own budget scope, separate from production, for two reasons. Production must not starve the eval (a gate that cannot run is a blind release), and the eval must not eat production's budget (a runaway epochs=100 should not take the support bot down).

Use the ledger from 11B.6: give acme / evals a daily limit, and each suite a path under it (acme / evals / nightly). Reserve each case's worst-case cost before running it, as EvalRun.run() above does. Two rules make the cap safe to use as a gate:

  • A capped run is incomplete, and an incomplete run fails. The demo gives the nightly suite $3.00 a day, then someone raises epochs from 3 to 10 (planned cost $35.80). The run stops after 264 of 3,000 case-epochs with complete: False, spends $2.9927, and the gate says FAIL: run incomplete, pass rate not trustworthy. The pass rate on the 264 cases that did run is real but must not be reported as the suite's rate. A cap that quietly passes a partial run is worse than no cap.
  • Schedule epoch-major. Run epoch 1 of every case first, then epoch 2, and so on. If the budget stops the run, you have at least one sample of every case instead of ten samples of the first 26.

This is the same pattern as the Budget(max_calls, max_cost_usd) in the eval runner of 10A.8, 3.5, which also refuses a cost function it cannot trust. Add the CI cap to the pipeline too: the workflow fails if the planned cost of the run, computed by plan() before it starts, exceeds the cap. That catches the epochs=10 change in the pull request, before any money is spent.

6.5 Eval spend in your cost reports#

Tag eval calls (kind=eval, suite=nightly) with the same tags as production (11B.6, Part 5), and charge a suite to the team that owns it. Judge calibration and shared datasets are platform costs: allocate them as shared costs (11B.6, 6.3). Use separate provider projects or workspaces for evals if you can, so the provider's own reports separate them, and remember the caching trade-off in 11B.6, Part 5.


Part 7: Evaluate it#

This lesson's topic is cost, so "evaluating it" means two things: evaluating your cost controls, and using cost as one metric when you compare designs. Modules 10A and 10B teach evaluation in general. Start with the concept lessons in 10A, then the DeepEval lessons in 10B, then the optional Inspect lessons.

What to measure for this lesson's topic

  1. Cost per successful task and p95 cost per task for each agent design (10A.7, 5.6 and 6.3).
  2. Tokens per step, to see the growth term a in Part 1 and whether compaction helped.
  3. Multi-agent multiplier versus quality gain (10A.12).
  4. Cache hit ratio per feature and its baseline.
  5. Requests crossing a long-context threshold per day.
  6. Eval cost per run versus the eval budget, and whether any run was incomplete.

A concrete tiny eval: is the multi-agent version worth it? Inputs: per-task records (cost in USD, passed) for the single-agent design A and the orchestrator design B, 120 tasks each (here synthetic and seeded; use your own logs). Metrics: success rate with a Wilson 95% interval, cost per successful task, p95 cost per task. Pass rule for adopting B: success up by at least 10 points and cost per successful task no more than 1.5 times A's. Save as cost_per_success.py:

python
# cost_per_success.py: compare two agent designs on cost per SUCCESSFUL task (lesson 11B.8)
"""Inputs: per-task records (cost in USD, passed or not) for each design. Output: success rate with a Wilson 95%
interval, cost per successful task, and p95 cost per task. The traces below are SYNTHETIC and seeded; replace
them with your own logs. Pass rule for adopting B over A: success up by at least 10 points AND cost per
successful task no more than 1.5x A's. Standard library only."""
import math
import random


def wilson(passed: int, n: int, z: float = 1.96) -> tuple[float, float]:
    p = passed / n
    centre = (p + z * z / (2 * n)) / (1 + z * z / n)
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
    return centre - half, centre + half


def p95(values: list[float]) -> float:
    ordered = sorted(values)
    return ordered[min(len(ordered) - 1, math.ceil(0.95 * len(ordered)) - 1)]


def summarise(name: str, tasks: list[tuple[float, bool]]) -> dict:
    n, passed = len(tasks), sum(ok for _, ok in tasks)
    total = sum(c for c, _ in tasks)
    lo, hi = wilson(passed, n)
    return {"name": name, "n": n, "success": passed / n, "ci": (lo, hi),
            "cost_per_success": total / passed, "cost_per_run": total / n, "p95_cost": p95([c for c, _ in tasks])}


def synth(seed: int, n: int, p_ok: float, mean_cost: float, loop_rate: float) -> list[tuple[float, bool]]:
    rng = random.Random(seed)
    out = []
    for _ in range(n):
        cost = rng.lognormvariate(math.log(mean_cost), 0.35)
        if rng.random() < loop_rate:
            cost *= 6                                            # the loop-and-fan-out tail
        out.append((cost, rng.random() < p_ok))
    return out


def main() -> None:
    a = summarise("A: single agent", synth(1, 120, 0.72, 0.30, 0.03))
    b = summarise("B: orchestrator + workers", synth(2, 120, 0.85, 0.72, 0.06))
    for r in (a, b):
        print(f"{r['name']:<28} success {r['success']:.0%} (95% interval {r['ci'][0]:.0%} to {r['ci'][1]:.0%})  "
              f"cost/run ${r['cost_per_run']:.2f}  cost/success ${r['cost_per_success']:.2f}  p95 cost/task ${r['p95_cost']:.2f}")
    gain = b["success"] - a["success"]
    ratio = b["cost_per_success"] / a["cost_per_success"]
    print(f"\nsuccess gain {gain:+.0%}, cost per successful task x{ratio:.2f}")
    print("adopt B?", "YES" if gain >= 0.10 and ratio <= 1.5 else "NO", "(rule: gain >= 10 points and cost per success <= 1.5x)")
    overlap = b["ci"][0] < a["ci"][1]
    print("note: the two success intervals", "overlap" if overlap else "do not overlap",
          "- with 120 tasks each, you " + ("cannot tell the designs apart on success" if overlap else "can tell them apart"))


if __name__ == "__main__":
    main()
Output6 lines
A: single agent              success 77% (95% interval 68% to 83%)  cost/run $0.36  cost/success $0.47  p95 cost/task $0.65
B: orchestrator + workers    success 79% (95% interval 71% to 85%)  cost/run $0.94  cost/success $1.19  p95 cost/task $1.54

success gain +2%, cost per successful task x2.51
adopt B? NO (rule: gain >= 10 points and cost per success <= 1.5x)
note: the two success intervals overlap - with 120 tasks each, you cannot tell the designs apart on success

On this synthetic data B costs 2.5 times as much per successful task, gains only 2 points of success, and the two intervals overlap, so the answer is no. Change the numbers in synth() to see the answer flip. The point is the shape of the decision: a design that costs more must buy measurable success, and with 120 tasks each you often cannot even tell the designs apart on success, which is itself a finding (10A.7, 5.2).

The tests for this lesson (15 tests: the quadratic formula, the long-context tiers, the cache simulator, the eval planner, the capped run, and the statistics helpers) are the evaluation of the calculators themselves. Save as test_cost.py:

python
# test_cost.py: the formulas in this lesson, checked (lesson 11B.8). Run: python3 -m unittest -v
import unittest

from agent_cost import GPT_62_SOL, HAIKU_55, SONNET_55, agent_run, call_cost
from budget_ledger import FakeClock, Ledger
from cache_strategy import OPTIONS, patterns, simulate
from cost_per_success import p95, wilson
from eval_cost import EvalRun, EvalSpec, plan


class AgentCostTests(unittest.TestCase):
    def test_input_tokens_follow_the_quadratic_formula(self):
        n, s, a = 20, 3_200, 750
        run = agent_run(SONNET_55, n, s, a, 100, cached=False)
        self.assertEqual(run["input_tokens"], n * s + a * n * (n - 1) // 2)

    def test_uncached_cost_matches_the_closed_form(self):
        run = agent_run(SONNET_55, 3, 1_000, 500, 200, cached=False)
        expected = (1_000 + 1_500 + 2_000) * 2.00 / 1e6 + 3 * 200 * 10.00 / 1e6
        self.assertAlmostEqual(run["usd"], expected, places=10)

    def test_caching_never_changes_token_counts_only_their_price(self):
        a = agent_run(SONNET_55, 10, 6_000, 800, 400, cached=False)
        b = agent_run(SONNET_55, 10, 6_000, 800, 400, cached=True)
        self.assertEqual(a["input_tokens"], b["input_tokens"])
        self.assertLess(b["usd"], a["usd"])

    def test_one_step_cached_costs_more_than_uncached_because_of_the_write_premium(self):
        a = agent_run(SONNET_55, 1, 10_000, 800, 0, cached=False)
        b = agent_run(SONNET_55, 1, 10_000, 800, 0, cached=True)
        self.assertGreater(b["usd"], a["usd"])

    def test_long_context_tier_switches_above_the_threshold_only(self):
        self.assertAlmostEqual(call_cost(HAIKU_55, fresh=100_000), 0.01)
        self.assertAlmostEqual(call_cost(HAIKU_55, fresh=100_001), 100_001 * 0.50 / 1e6)
        self.assertAlmostEqual(call_cost(GPT_62_SOL, fresh=272_001, out=1_000), 272_001 * 4.0 / 1e6 + 1_000 * 15.0 / 1e6)

    def test_threshold_counts_cached_tokens_too(self):
        # Anthropic: a request's prompt length counts cache reads and writes (pricing page, 2026-12-01).
        self.assertGreater(call_cost(HAIKU_55, fresh=1_000, read=100_000), call_cost(HAIKU_55, fresh=1_000, read=90_000) * 2)


class EvalCostTests(unittest.TestCase):
    def test_calls_equal_cases_epochs_trials_times_one_plus_judged_metrics(self):
        p = plan(EvalSpec("x", cases=10, epochs=3, trials=2, judged_metrics=4), SONNET_55, HAIKU_55)
        self.assertEqual(p["calls"], 10 * 3 * 2 * (1 + 4))

    def test_batch_halves_the_bill(self):
        a = plan(EvalSpec("x", cases=10), SONNET_55, HAIKU_55)["usd"]
        b = plan(EvalSpec("x", cases=10, batch=True), SONNET_55, HAIKU_55)["usd"]
        self.assertAlmostEqual(b, a / 2)

    def test_a_capped_run_is_marked_incomplete_and_never_overspends(self):
        ledger = Ledger(FakeClock())
        path = ("o", "evals", "ci")
        ledger.set_limit(path, 0.05)
        spec = EvalSpec("x", cases=100, judged_metrics=2)
        res = EvalRun(ledger, path, spec, SONNET_55, HAIKU_55).run([True] * 100)
        self.assertFalse(res["complete"])
        self.assertGreater(res["not_run"], 0)
        self.assertLessEqual(ledger.report(path)["used"], 50_000)

    def test_a_budget_that_fits_completes(self):
        ledger = Ledger(FakeClock())
        path = ("o", "evals", "ci")
        ledger.set_limit(path, 5.0)
        res = EvalRun(ledger, path, EvalSpec("x", cases=20), SONNET_55, HAIKU_55).run([True] * 20)
        self.assertTrue(res["complete"])


class CacheStrategyTests(unittest.TestCase):
    def test_sparse_traffic_loses_money_on_a_five_minute_cache(self):
        five_min = OPTIONS[0]
        r = simulate(patterns()["sparse (every 12 min)"], five_min)
        self.assertAlmostEqual(r["relative_cost"], 1.25)       # every request pays a fresh write

    def test_one_hour_cache_wins_on_sparse_traffic(self):
        sparse = patterns()["sparse (every 12 min)"]
        self.assertLess(simulate(sparse, OPTIONS[1])["relative_cost"], 0.5)

    def test_steady_traffic_is_nearly_all_hits(self):
        self.assertGreater(simulate(patterns()["steady (every 90 s)"], OPTIONS[0])["hit_rate"], 0.95)


class StatsTests(unittest.TestCase):
    def test_wilson_interval_contains_the_estimate_and_narrows_with_n(self):
        lo1, hi1 = wilson(8, 10)
        lo2, hi2 = wilson(80, 100)
        self.assertTrue(lo1 < 0.8 < hi1)
        self.assertLess(hi2 - lo2, hi1 - lo1)

    def test_p95_of_twenty_values_is_the_nineteenth(self):
        self.assertEqual(p95(list(range(1, 21))), 19)


if __name__ == "__main__":
    unittest.main()

Real output of python3 -m unittest -v:

text
test_caching_never_changes_token_counts_only_their_price (test_cost.AgentCostTests.test_caching_never_changes_token_counts_only_their_price) ... ok
test_input_tokens_follow_the_quadratic_formula (test_cost.AgentCostTests.test_input_tokens_follow_the_quadratic_formula) ... ok
test_long_context_tier_switches_above_the_threshold_only (test_cost.AgentCostTests.test_long_context_tier_switches_above_the_threshold_only) ... ok
test_one_step_cached_costs_more_than_uncached_because_of_the_write_premium (test_cost.AgentCostTests.test_one_step_cached_costs_more_than_uncached_because_of_the_write_premium) ... ok
test_threshold_counts_cached_tokens_too (test_cost.AgentCostTests.test_threshold_counts_cached_tokens_too) ... ok
test_uncached_cost_matches_the_closed_form (test_cost.AgentCostTests.test_uncached_cost_matches_the_closed_form) ... ok
test_one_hour_cache_wins_on_sparse_traffic (test_cost.CacheStrategyTests.test_one_hour_cache_wins_on_sparse_traffic) ... ok
test_sparse_traffic_loses_money_on_a_five_minute_cache (test_cost.CacheStrategyTests.test_sparse_traffic_loses_money_on_a_five_minute_cache) ... ok
test_steady_traffic_is_nearly_all_hits (test_cost.CacheStrategyTests.test_steady_traffic_is_nearly_all_hits) ... ok
test_a_budget_that_fits_completes (test_cost.EvalCostTests.test_a_budget_that_fits_completes) ... ok
test_a_capped_run_is_marked_incomplete_and_never_overspends (test_cost.EvalCostTests.test_a_capped_run_is_marked_incomplete_and_never_overspends) ... ok
test_batch_halves_the_bill (test_cost.EvalCostTests.test_batch_halves_the_bill) ... ok
test_calls_equal_cases_epochs_trials_times_one_plus_judged_metrics (test_cost.EvalCostTests.test_calls_equal_cases_epochs_trials_times_one_plus_judged_metrics) ... ok
test_p95_of_twenty_values_is_the_nineteenth (test_cost.StatsTests.test_p95_of_twenty_values_is_the_nineteenth) ... ok
test_wilson_interval_contains_the_estimate_and_narrows_with_n (test_cost.StatsTests.test_wilson_interval_contains_the_estimate_and_narrows_with_n) ... ok

----------------------------------------------------------------------
Ran 15 tests in 0.001s

OK

Where to go next in Modules 10A and 10B


Common misconceptions#

  • "Caching saves 90%." It saves on the cached prefix, when your traffic reuses it within the lifetime. Sparse traffic on a short lifetime can cost 1.25 times more than not caching.
  • "Caching removes the quadratic cost." It lowers the price of re-reading, not the number of tokens re-read.
  • "Multi-agent is just more of the same agent." Each worker pays its own prefix and history, and the orchestrator re-reads every summary. The multiple is often higher with caching.
  • "The price per token is the price." Some models switch the whole request to a higher tier at a threshold, and on Haiku 5.5 a cache hit still counts toward the threshold.
  • "Flat pricing at 1M tokens means long context is cheap." Per token it is flat; per request it is 100 times a 9K prompt, and a loop re-sends it every step.
  • "Evals are overhead, not a workload." Judge calls, epochs and CI re-runs multiply, and the judge model is often the largest single choice.
  • "A budget cap on evals protects us." Only if an incomplete run fails the gate. A capped run that passes is a silent hole.
  • "Cost per run is the number to track." Track cost per successful task, and the p95.

Key takeaways#

  • Input tokens over a loop are N x S + a x N(N-1)/2: quadratic in steps. Control a, N and the price of the re-read.
  • Report cost per successful task and p95, never only the mean per run.
  • A multi-agent run costs more for four separate reasons (prefix per worker, history per worker, orchestrator re-reads, parallel rate pressure). Pay it only for measured value.
  • Long-context tiers are cliffs. Estimate with the tier, guard the threshold, alert on crossings.
  • Choose the cache lifetime from your traffic gaps: short for steady traffic, long for bursty or sparse, and never a lifetime you will not reuse within.
  • Own the shared prefix, standardise the layout, warm before fan-out, and track the hit ratio as a KPI. On Anthropic, cache reads do not count toward ITPM.
  • Eval calls = cases x epochs x trials x (1 + judged metrics). Cut them with tiers, a cheap judge first, record and replay, caching, batch and sampling.
  • Give evals their own budget scope; a capped run is incomplete and fails the gate; schedule epoch-major.

Terms introduced in this lesson#

Term Meaning
Quadratic cost growth Input tokens that grow with the square of the number of steps because each step re-sends the history
Per-step growth The tokens each step adds to the transcript (tool result plus model output)
Cost per successful task Total spend on all attempts divided by the number that succeeded
p95 cost The cost under which 95% of tasks fall; shows the loop tail that the mean hides
Multi-agent multiplier How many times more a multi-agent run costs than a single-agent run of the same job
Long-context tier A higher price for the whole request once the prompt crosses a token threshold
Price cliff The jump in cost when a request crosses a long-context threshold
Prompt cache A provider-side store of the processed start of a prompt, reused at a lower price
Cache breakpoint The place in a prompt up to which you ask the provider to cache
TTL (cache lifetime) How long a cache entry survives; for Anthropic 5 minutes or 1 hour, refreshed on use
Cache write premium The extra price (1.25x or more of base input) paid when content is first written to a cache
Cache hit ratio Cached read tokens divided by total input tokens
Warm the cache Send one request and wait for its first response before fanning out, so later requests hit
Eval call count cases x epochs x trials x (1 + judged metrics)
Epoch A repeated sample of the same case within one run
Trial A repeat of the whole eval suite
Judge call A model call that scores an output against a rubric
Eval budget A dedicated spending cap for evals, separate from production
Incomplete run A run stopped by a budget; it must fail the gate and never be reported as the suite's score
Epoch-major scheduling Running every case once before any case is repeated

Exercises#

  1. Your own agent. Take a real trace (or invent one) and fit S, a and N. Use agent_run() to predict its cost with and without caching, then compare to the real bill. Hint: tokens per step come from the usage fields in the trace; ignore the first step when estimating a.
  2. Find the break-even step. Using agent_run(), find the smallest number of steps at which a cached run is cheaper than an uncached one for Sonnet 5.5 with a 6,000-token prefix. Explain why it is above 1. Hint: compare cached=True and cached=False for N from 1 upward; the write premium is paid once.
  3. Add a new option to the cache simulator. Add an "Anthropic 5 min with keep-warm pings every 4 minutes" option that sends a refresh read when the entry is about to expire during a gap, and compare it to the 1-hour option on the sparse pattern. Hint: a ping costs the read multiplier on the prefix and refreshes the entry; count pings as requests in the cost but not in the hit rate.
  4. A threshold guard. Write a function that, given a prompt's token count and a Price, returns "trim to N tokens" when the count is within 5% above the threshold and the saving from crossing back is more than 20%. Test it on Haiku 5.5. Hint: use Price.long_threshold and compare call_cost just under and just over.
  5. Cap an eval in CI. Add a script that reads a suite description (cases, epochs, judged metrics, judge model) from a YAML or JSON file, calls plan(), and exits non-zero if the planned cost exceeds a cap. Demonstrate it catching epochs: 10. Hint: print the planned cost and the cap in the failure message so the author sees both.
  6. Judge choice. For the nightly suite, compute the cost with a cheap judge for every case and a strong judge on a 10% audit sample. What agreement rate between judges would you need to justify it, and how would you measure it? Hint: see 10A.5 for judge calibration.

Check yourself#

  1. Why does doubling the number of agent steps more than double the input cost?
  2. What does prompt caching change about the quadratic growth, and what does it not change?
  3. Give two reasons a multi-agent run costs more than a single agent, and one reason caching can raise the multiple.
  4. What happens to the price of a Claude Haiku 5.5 request whose prompt is 100,001 tokens, even if most of it is a cache hit?
  5. Why can a 5-minute Anthropic cache cost 1.25 times more than no caching?
  6. When does the 1-hour lifetime beat the 5-minute one?
  7. Why is the Anthropic input_tokens field misleading when you compute a cache hit ratio?
  8. Why does a good cache hit ratio raise your effective rate limit on Anthropic?
  9. Write the formula for the number of calls in an eval, and name the biggest single price lever.
  10. Why must an eval run stopped by its budget fail the gate, and why schedule epoch-major?

Further resources#

Existing lessons:

Official documentation (read on 1 December 2026):


← 11B.7 — Rate Limits Across Teams, Throughput Options, Kill Switches and Spend Alerts | Module 11B overview | Module 11C: Deployment, Reliability and Model Lifecycle →

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