Odysseus
Part V · Knowing it works
Chapter 20

Cost: budgets, the ledger and where the money goes

How to reason about what an agent costs: tokens and context length, caching, metered services, a ledger derived from the journal by one function, estimates where vendors report no price, budgets that stop work, and design changes that pay for input once.

After this chapter you should be able to
  • Work out roughly what a model call costs from its token counts and a price table, and explain why a long conversation makes every later call dearer.
  • List every kind of paid call an agent makes, and say for each whether the vendor reports its price or the program has to estimate it.
  • Build a ledger that is derived from the journal by one function, so that the money spent cannot drift from the record of what was done.
  • Explain how a per-task budget and a per-day budget stop work, and where each falls short.
  • Recognise a design that pays for the same input many times, and move that work into a separate run that is paid for once.
  • Read a table of measured costs critically: what each figure measured, how many times, and what it leaves out.
This unit
Week
12 of 14
Before it
Chapter 2, Chapter 4 and Chapter 17; Definitions 1, 3, 8 and 9, Property 3 and the cost formula of the model.
Read first
[Anthropic 2026c]; [Kapoor et al. 2024].
Laboratory
5: measuring it
Problem set
5

20.1The problem: money that moves without anyone noticing

An agent spends money every time it calls a model, searches the web, opens a browser or reads from a paid service. Nobody sees an invoice per message. If the program does not count, the first sign of a fault is the monthly bill.

The case this chapter is built around: the owner sends a fourteen-page pitch deck, as a PDF, into the chat. In the design first built, so that the model could see the charts and logos that text recognition drops (Chapter 15), the PDF was placed in the conversation itself. The reply cost 12 cents. Later in the same long-running conversation the deck was sent again, and then a third time. The third sending cost 34 cents. Verified, one sending each. The deck was the same each time; the conversation before it was longer.

Explaining that number needs four ideas: what a model call is billed for, why a conversation's length dominates, which other services charge and how their price is learnt, and how a ledger and budgets turn prices into a decision to stop.

20.2The concepts

Definition
Token
The unit in which a model reads and writes text, roughly a word or part of one. Vendors bill per million tokens read (input) and, at a higher price, written (output). A PDF page shown as a picture also becomes tokens.
Definition
Context
Everything the model is shown in one call: instructions, the conversation so far, tool results, files and the new message. A model keeps nothing between calls, so the context is sent, and billed as input, every time.
Definition
Prompt cache
A vendor feature that stores the start of a context sent repeatedly, so that later calls beginning with the same text pay much less to read it. Writing to the cache costs a little more than ordinary input. (A general description; the program's figures are in the price table below.)
Definition
Metered service
An outside service that charges per use: per search, per browser run, per page recognised, per minute transcribed, per item returned. A flat subscription is not metered.
Definition
Ledger
The program's running account of money spent per calendar day. Here it is not stored: it is computed from the journal (the append-only record of every step, introduced in Chapter 4).
Definition
Budget
A limit that changes what the program does when spending reaches it: a task is ended, or not started. A figure that is only displayed is not a budget.

Why the conversation's length dominates

A task is several model calls (Chapter 2), and each call sends the whole context. The input billed for a task is therefore roughly the context's size times the number of calls, and the context includes every earlier message.

Output is dearer per token but small. Input is cheaper per token but large and growing, and in a conversation kept for weeks (Chapter 7) it wins. Anything placed in the conversation is paid for again by every later call until the library condenses the conversation or the owner sends /new.

The price table the program uses is in odysseus/agent.py:

# Dollars per million tokens: input, output, cache read, cache write.
# Used only to end a task early; the recorded cost is the SDK's own figure.
# All four were checked against the maker's price list (cache writes are the five-minute rate); prices change.
# Not in the table: the small model costs five times as much on a prompt over 100,000 tokens, so an estimate
# for such a prompt on that model is too low. No prompt this program builds for it comes near that size.
PRICES = {
    "claude-sonnet-5-5": (2.00, 10.00, 0.10, 2.50),
    "claude-opus-5-5": (4.00, 20.00, 0.20, 5.00),
    "claude-haiku-5-5": (0.10, 0.50, 0.01, 0.125),
}
HOUR_WRITE = 2.0     # a cache write kept for an hour, as a multiple of the plain input price
DEAREST = max(PRICES.values())   # used for a model not in the table, so the estimate errs high

A cache read is priced at a twentieth of ordinary input for the two larger models and a tenth for the small one. Caching softens the cost of a long context; it does not remove it, since on the main model twenty cached readings cost as much as one uncached. The comment also says where the figures came from and what the table leaves out. The cache-write figures were once an assumption (1.25 times input) and were later checked against the price list, which also offers a one-hour cache at twice the input price: an alternative to beginning a new conversation after a pause. The program has a setting for it, off by default, and its effect on a bill has not been measured.

Illustration: arithmetic, not a measurement

Suppose, for the arithmetic only, that a PDF page shown to the model costs two to three thousand tokens (an assumed figure: the program has never measured it). Then fourteen pages are about 28,000 to 42,000. At $2 per million that is about 6 to 8 cents per model call uncached, or 0.3 to 0.4 cents read from a cache. A task of three calls in a conversation holding three copies of the deck pays for nine readings of fourteen pages. This shows the shape of the problem, not how the 34 cents was made up: the split between cached and uncached tokens was not measured.

20.3The design

Every paid call leaves a line, and one function prices the line

Each way of spending money writes a journal line when it happens. One function, cost_of, returns what a line cost, and the ledger is that function applied to every line. Nothing else adds to it.

task_end: library's figure event: watch check tool: search, reported tool: paid read, estimated file: pages x fixed price voice: minutes x fixed price tool "browse": counted as 0 journal.jsonlappend only cost_of(line)one definition Ledgersum per owner's day daily budget check/statusqueued messages
Figure 20.1. Where the ledger's numbers come from. The amber boxes are estimates made by the program, not prices reported by a vendor. A browser run writes a line but is priced at zero: its cost is already inside the task_end of the task that ran it.

Reported, estimated, or not counted

Some vendors return a price with every answer; for the rest the program estimates.

Table 20.1. What the ledger counts, where each figure comes from, and how well it is known.
SpendingFigure taken fromGrade
A conversation task or a routineThe agent library's own figure, plus any browser run inside the taskMaker's claim, not checked against an invoice
A check of an incoming event against the watchesThe sameMaker's claim
A web searchThe price the search service returns with each answerMaker's claim
A paid read of a connected service (X)Items returned times the service's published priceAn estimate, marked as one in the journal
The page reader for a PDFThe library's figure for that separate runMaker's claim
A file read by text recognition$0.002 a page, written in the codeAn estimate from the maker's price list, not measured
A voice note transcribed$0.003 a minute, written in the codeAn estimate from the maker's price list, not measured
A task ended by forceThe program's own estimate from token countsAn estimate, marked estimated in the journal
Mail, calendar and app connectorNot countedBilled by subscription, not per call

Budgets: three limits, and why the program counts for itself

Chapter 4 introduced the three limits: 25 steps and $0.50 per task, $3.00 per day. The day's limit is read from the ledger before a task starts, so a refused task costs nothing, and it is checked again as each model call arrives: a task is ended when its own spending reaches what was left of the day, counting what other running tasks are spending. The two per-task figures are marks, not walls. A task that passes one carries on while it is getting somewhere, up to a ceiling four times higher (the setting task_stretch: $2.00 and 100 steps). A task that is getting nowhere, having asked for the same call with the same inputs three times or had four tool calls in a row fail, is ended at once as stuck, whatever it has cost (odysseus/progress.py). All of these are checked as each model call arrives, and cannot use the library's figure, which comes only at the end of a run and as a running total. So the program estimates as it goes, uses the estimate only to decide when to stop, and records the library's figure afterwards.

Unattended work has a fourth kind of limit: with no owner to ask, a routine may make only a fixed number of reads of a paid service per run (eight for X, in odysseus/mcpapp.py). And an incoming event that no watch covers calls no model at all.

20.4The mechanism

The one definition

The whole ledger rests on this function in odysseus/journal.py:

OCR_USD_PER_PAGE = 0.002
VOICE_USD_PER_MINUTE = 0.003


def cost_of(rec: dict[str, Any]) -> float:
    ...
    kind = rec.get("kind")
    try:
        if kind in ("task_end", "event"):
            return float(rec.get("cost_usd") or 0.0)
        if kind == "tool" and rec.get("name") != "browse":      # a web search at the price the service reported; a paid read of a
            return float(rec.get("cost_usd") or 0.0)             # connected service, as estimated. A browser run is in its task_end.
        if kind == "file" and rec.get("ok") and rec.get("pages"):
            return float(rec["pages"]) * OCR_USD_PER_PAGE
        if kind == "voice" and rec.get("ok"):
            return float(rec.get("seconds") or 0) / 60 * VOICE_USD_PER_MINUTE
    except (TypeError, ValueError):
        pass
    return 0.0

(The docstring, omitted, lists the same cases in words.) Every kind not named returns zero, so a new kind of line is not counted by accident. A malformed number returns zero instead of crashing start-up. And there is exactly one place to look when asking "is this counted?".

The ledger applies it:

        self._by_day: dict[str, float] = {}
        for rec in journal.read():
            self._count(rec)
        journal.listeners.append(self._count)

    def _count(self, rec: dict[str, Any]) -> None:
        usd = cost_of(rec)
        if usd:
            day = datetime.fromtimestamp(rec["ts"], self._zone).date().isoformat()
            self._by_day[day] = self._by_day.get(day, 0.0) + usd

At start-up it reads the whole journal, then listens for new lines; the same function sees every line both times, so the figure survives a restart. The day is computed in the owner's time zone, from a setting. Without that, a server elsewhere would reset the owner's budget in the middle of their afternoon.

From a running total to a task's cost

The library reports a running total for the conversation. The cost of one task is the difference (odysseus/agent.py):

        total = float(result.total_cost_usd or 0.0)
        continued = bool(result.session_id) and result.session_id == self.session_id
        cost = max(0.0, total - self._session_cost) if continued else total
        if result.session_id and result.session_id != self.session_id:
            self.session_id = result.session_id
            self._save_session()
        self._session_cost = max(total, self._session_cost) if continued else total

In the same conversation, the task's cost is the new total minus the last one seen; in a new one, the whole total. The max calls guard against a total that goes backwards. Without this, summing running totals overstates spending more as the conversation grows.

Estimating during the task

def estimate_usd(model: str, usage: dict[str, Any]) -> float:
    p_in, p_out, p_read, p_write = PRICES.get(model, DEAREST)
    # A write kept for an hour (Settings.cache_1h) costs twice the plain input price, not the five-minute rate. The
    # usage says how many of the written tokens were of that kind; without that it is all taken as five-minute.
    written = usage.get("cache_creation_input_tokens") or 0
    kinds = usage.get("cache_creation")
    hour = min(written, int((kinds.get("ephemeral_1h_input_tokens") if isinstance(kinds, dict) else 0) or 0))
    return (
        (usage.get("input_tokens") or 0) * p_in
        + (usage.get("output_tokens") or 0) * p_out
        + (usage.get("cache_read_input_tokens") or 0) * p_read
        + (written - hour) * p_write
        + hour * p_in * HOUR_WRITE
    ) / 1_000_000

Each model call reports four kinds of token count, each with its price, and a write kept for an hour is priced at HOUR_WRITE, twice the input price. A model not in the table gets the dearest row, so a new model ends tasks early rather than late: an unfinished task is the cheaper mistake. The test test_cost_estimate_from_token_counts checks one case by hand: a million input tokens, a hundred thousand output tokens and a million cache-read tokens on the main model cost $2.00 + $1.00 + $0.10.

Estimating a service that does not report its price

X's server does not say what a call cost. The program estimates from what came back (odysseus/mcpapp.py):

def estimate(spec: dict[str, Any], name: str, text: str) -> float:
    """What one read probably cost, from how many items came back. Zero for a service that does not charge by the item."""
    price = spec.get("price")
    if not price or name in price.get("free", ()):
        return 0.0
    try:
        data = json.loads(text).get("data")
    except (ValueError, AttributeError):
        return 0.0
    items = len(data) if isinstance(data, list) else (1 if data else 0)
    each = price["default"]
    for key in ("own", "people"):
        rate, marks = price.get(key, (None, ()))
        if rate is not None and any(m in name for m in marks):
            each = rate
            break
    return round(items * each, 4)

The service's entry prices an item at $0.005 by default (a post), $0.010 for a profile, $0.001 for the owner's own data, and nothing for the credit check; its comment reads "An estimate: the bill is X's, not this table's." The figure goes to the journal with estimated=True, so a reported price can always be told from a guessed one. The model is also told the prices in words and asked to request small pages of twenty to fifty items: a cost control too, though one the model may or may not follow.

Reading a file's pages once

This is the repair for the opening case, in odysseus/pages.py:

    runner = AgentRunner(settings, journal, server, client_factory, model=model or settings.model, system_prompt=PROMPT, allowed_tools=frozenset())
    ...
    async def read(data: bytes, text: str) -> tuple[str, float]:
        await runner.forget_session()
        try:
            outcome = await asyncio.wait_for(runner.run(f"THE TEXT ALREADY READ FROM THE FILE\n{text}\nEND OF TEXT", noop,
                                                        images=[("application/pdf", data)]), PAGES_TIMEOUT_S)
        except asyncio.TimeoutError:
            outcome = Outcome("error", cost_usd=runner.estimate, detail="timeout")
        except Exception as e:
            outcome = Outcome("error", cost_usd=runner.estimate, detail=type(e).__name__)
        finally:
            await runner.forget_session()
        notes = (outcome.text or "").strip() if outcome.status == "done" else ""
        if notes.strip(" .\"'`").upper() == NOTHING:
            notes = ""
        # The ledger counts any tool line's cost, so the day's budget includes this run.
        journal.write("tool", name="see_pages", ok=outcome.status == "done", cost_usd=round(outcome.cost_usd, 4), chars=len(notes),
                      **({} if outcome.status == "done" else {"error": outcome.detail or outcome.status}))
        return notes[:MAX_NOTES], outcome.cost_usd

A second runner is built with no tools at all, and forget_session throws its conversation away before and after each file. Its notes, at most 9,000 characters of text, are what the owner's conversation receives (Chapter 22 covers their content). A run that fails or times out is still costed from the running estimate: a failure is not free on the bill, so it is not free in the ledger.

20.5Worked examples

The deck, before and after

Before: the file lives in the conversation deck (PDF) messages deck again messages deck again first sending 12c; the thirdcarries all three copies: 34c After: the file is looked at once, elsewhere deck (PDF) page reader: no tools,thrown away after text + page notes(at most 9,000 chars) owner's conversation paid once (8c on the real deck)carries text only (12c)
Figure 20.2. The same deck under the two designs. The two figures come from single runs in different conversations (12 cents for a first sending in a long conversation, 20 cents with the separate reader in a fresh one), so they do not show which design costs more on first use; the saving the new design promises is on every later message, and that has not been measured over several decks.

Step by step, after the repair, for the real fourteen-page deck in a conversation started afresh:

  1. The owner sends the PDF with no message. The control layer checks the sender, then sends the file to text recognition, which returns the text with each page numbered. The journal gets a file line with pages: 14; cost_of prices it at 14 × $0.002 = 2.8 cents by the fixed estimate (a figure computed by the program, and not part of the measured 20 cents below).
  2. The file is a PDF of at most 25 pages and 12 MB, and the day's budget has room, so the page reader runs. It sees the PDF and the text, and writes notes such as the two figures on a benchmark chart where the company's model is behind. It is thrown away. The journal gets a tool line named see_pages. Verified: 8 cents.
  3. The conversation receives the file's text and the reader's notes as one block of text inside the owner's message, and the model writes its take. Verified: 12 cents for the conversation, 20 cents in all.
  4. Every later message in the conversation carries that block of text, but not the fourteen page images.

Two things were given up: the conversation's model no longer sees a page, so later questions about a chart are answered from the notes; and a second model now stands between page and reader, one more place for a mistake. One thing was gained besides money: a reader with no tools can at worst describe a page wrongly, whatever the page says to it (Chapter 9).

The reader's model is a setting. On an invented eleven-page deck the small model cost a third of a cent and the main model five and a half cents, and both reported the same chart and planted line. Verified, one run each. The main model stays the default, because one drawn chart is no basis for trusting the small one with real slides.

A day's ledger, line by line

The test test_the_ledger_is_the_journal_and_counts_every_service_that_is_paid_per_use in tests/test_stage0.py writes these lines and checks the total. It is the clearest worked example of cost_of:

Table 20.2. Journal lines and what the ledger makes of each.
Line writtenCountedWhy
task_end, cost_usd=0.01$0.010A conversation task, at the library's figure
task_end, cost_usd=0.004, routine="a1b2"$0.004A routine's run
scheduled_run, outcome="delivered", cost_usd=0.004$0The same routine again; this kind is not priced, so it is not counted twice
event, outcome="quiet", cost_usd=0.002$0.002A check of incoming mail against the watches
tool, name="web_search", cost_usd=0.007$0.007The price the search service reported
tool, name="browse", cost_usd=0.04$0Already inside its task's task_end
file, ok=True, pages=3$0.0063 pages × $0.002, estimated
voice, ok=True, seconds=120$0.0062 minutes × $0.003, estimated
task_end, status="stopped", forced=True, cost_usd=0.03, estimated=True$0.030A forced stop, at the program's own estimate
Total$0.065The same after a restart, because it is recomputed from the same lines

Two lines carry a cost and are deliberately not counted, because some facts are recorded twice. The pricing function, not the writer of the line, decides which record is the paid one.

20.6Design decisions driven by cost

  • A cheaper model for unattended work. Scheduled routines run on a background model, claude-haiku-5-5 by default in odysseus/config.py, priced in the table at a twentieth of the main model. A routine has a narrow job, nobody watching, and runs whether or not it finds anything; measured runs cost about $0.0015 (Chapter 6). Work whose judgement the owner will act on (a meeting brief, the page reader) uses the main model.
  • Code instead of a model. A reminder is sent by code and costs nothing; an email no watch covers is dropped by code; commands are answered by code.
  • Refusals before any model call. A stranger's message, a task when the day's budget is spent, and the page reader for a file that is too long or arrives when the budget is spent are all refused before any model call.
  • A conversation that begins again after a pause. The price of a message is, roughly, the size of the whole conversation behind it. The cache softens that only while messages follow one another within a few minutes; after a longer gap the whole conversation is written to the cache again, at more than the ordinary input price. A personal assistant is mostly used in exactly that way: a message, then nothing for an hour. So code, not the model, decides when to begin a new conversation: after two hours without a message, or after ten idle minutes (an hour, if the cache is kept for an hour) once the last call sent the model more than 40,000 tokens. The new conversation is given the last three exchanges in words, cut where long, and the saved memory. A file's text is not carried: its first line stands for it. A web search's results, which stay in the conversation for as long as it lasts, are cut to 12,000 characters. The mechanism is in Chapter 4. Closing the old conversation with a summary costs about two hundredths of a cent on the small model (Chapter 5), against several cents for every later message that would otherwise have carried the whole of it.
  • Look only where there is something to see. A long PDF's pages are not all shown to the page reader. Code picks the pages with pictures from what text recognition already returned, and only those are looked at: six pages of an invented forty-five-page deck, for three cents (Chapter 15).
  • The cheapest model that does the job, shown by measurement. The second reader of outgoing actions was tried on the small model and the main one. Both caught every planted fault with no false alarm; the small one costs a twentieth as much, so it is used (Chapter 8).
  • The cheapest route that reaches the information. For a morning digest of posts, X's interface would cost about 15 cents a morning (worked out from its published prices, not measured), web search under a cent a search, and a hosted browser 4 to 8 cents a run. Web search became the fallback when X refuses, being cheaper and able to run unattended (Chapter 23).
  • A setting that was measured and left off. The model's maker offers a dial for how hard the model thinks between steps, and suggests a middle value for work in several steps with tools. It was tried on the fund suite, 52 cases three times each, against the same suite without it. Score: 0.7 points lower, inside the noise (interval from 2.4 lower to 0.8 higher). Calls to the model per run: 3.0 against 3.0. Cost per run: the same to a tenth of a cent. Seconds were 4 higher, but the machine was busy with other work during that run, so seven cases were timed again one at a time, twice each way: three of the four passes came in near 8.4 seconds whichever way the dial was set, and the fourth was slow for a reason the test could not name. Nothing moved that could be told from chance, so the dial is a setting the owner can turn and the program leaves alone. A change that is recommended and plausible is still a change with no evidence until it is measured here, and seconds measured on a shared machine are a measurement of the machine.
  • Tools sent by name only, measured and left off. The agent library can hold back every tool's description and let the model look a tool up when it wants one. The model's maker recommends it for long lists of tools. Here the list is 18 tools weighing about 5,000 tokens, beside 6,600 for the instructions; holding them back took the opening of a conversation from about 16,000 tokens to about 8,000. It was tried on the group of cases that turn on one tool, the one that does a funding round's sums by code: seven cases, three times each, against the same cases run six times with every tool in view. With the tools in view the model called that tool in 36 runs of the 36 that needed it, and every answer was right. With the tools held back it called it in 5 of 18, did the sums itself in the rest, and got 4 of 21 runs wrong. Those runs were 15% cheaper and took fewer calls, for the reason that makes the saving worthless: the work that was skipped was the check. Nothing became unsafe. A tool the model is not shown is a tool it does not think to use, and a tool that exists to stop the model doing arithmetic is the first to go. The setting stays in the program, off (ODYSSEUS_TOOLS_ON_DEMAND). The library has no way, in the language this program is written in, to hold back some tools and always show others; with one, the test would be worth running again.
  • Know which regime a measurement is in. A fund-suite run costs about two cents, and its journals say where the two cents go: 53% on writing new material to the cache (the message, the opening facts, what the tools returned), 31% on reading the fixed part back, about 15,000 tokens on each of 3.3 calls, and 16% on what the model writes. That is the price of a message that arrives while the cache is warm, because the suite's cases follow one another within seconds. The owner's own use is different. In a week of it, 79 messages, the 51 that came within five minutes of the last cost a cent each at the median and $1.59 in all; the 28 that came later cost 9 to 16 cents each and $3.70 in all. A third of the messages were 70% of the money, and no case in the suite is one of them. A change that saves a tenth of a warm message is worth less than one that makes fewer messages cold, and the suite can price only the first kind.
  • The message after a pause, measured by waiting. Three cases were added that the ordinary suite does not hold (python -m evals.fund --cold). Each builds a conversation of two questions about the pipeline, waits five and a half minutes by the clock, and sends a third; only the third is marked, and its cost is kept apart. They run one at a time, because two conversations running together keep each other's shared opening in the cache. With the cache kept for five minutes, 18 runs: the third message cost 5.5 cents, against about a cent for a message that arrives in time, and the two before it 4.0 cents. With the cache kept for an hour (ODYSSEUS_CACHE_1H), 9 runs: the third message cost 1.3 cents, 76% less (4.2 cents less; interval 3.9 to 4.4), and the two before it 5.3 cents, a third more (1.3 cents more; interval 0.5 to 2.5), because every write to the longer cache costs more. The whole conversation: 9.5 cents against 6.6, 30% less. Every answer was right both ways, nothing was unsafe, and the first word came no sooner (4.8 seconds against 4.7). So the hour-long cache pays when about one message in seven arrives between five minutes and an hour after the last; in the owner's week it was one in five. What the trial cannot say is what the owner's own week would have cost: there the conversations are longer, and one message in six came more than an hour late, which the longer cache makes dearer and not cheaper. The setting is off until a week with it on has been set beside a week with it off.
  • Trimming what tools returned, not available. The model's maker offers a way to drop old tool results from a long conversation as it grows. The agent library this program is built on does not pass it on, and each trim discards the cache from that point. Having it would mean replacing the library's loop with one written here. The rule that begins a large conversation again after a pause does much of the same work and is already built, so this was not pursued.
  • The same suite twice. The second run of the tools-by-name trial was found afterwards to have run with the setting off, so it was the first run again: 58 cases, three times each, on unchanged code. The score differed by 1.0 point (interval from 0.1 lower to 2.7 higher), the cost per run by 0.7%, the calls per run by 0.006. That is what no change looks like on this suite, and a difference of that size between two versions is not a finding. Its cause is its own lesson: the run's journals, not its command line, say what a run was, and they were read only after the money was spent.

20.7What real runs cost

Every measured cost is collected here. Read the third column before the second: almost every figure is one run, often on an invented example, and none has been compared with an invoice.

Table 20.3. Measured costs, with what each measured and how often. All Verified as the services reported them; none checked against a bill.
What was runCostWhat it measured, and the sample
A question needing one web search$0.0145One conversation task, one sample
A trivial follow-up questionabout $0.001One sample
Three trivial questions in one conversation$0.0029 in allRunning totals $0.0013, $0.0026, $0.0029; one run
A typical search, or a typical connector read, in a taskabout 1 cent"Typical" across early live runs; not a controlled measure
One web search, by itself0.7 centsThe price the search service reported, in one routine run
A hosted browser runabout 4 cents; 8 cents for one taskThree runs at 20 to 50 seconds; the 8-cent task, on the simplest possible page, took 54 seconds and ran the browser twice
A scheduled routine on the small model$0.0013 (quiet), $0.0018 (delivered)Two runs in one live test, with the clock moved forward by hand
A routine reading the owner's mail, small model$0.0005One run, found nothing urgent
A morning digest routineabout 1.3 cents (0.6 model, 0.7 search)One run, 38 seconds, with X refusing every read for lack of credit
A brief before a meeting, main model7 centsOne run, 47 seconds, on an invented meeting; one search by code, eleven reads by the model
Filing an investment in the firm's database$0.13, $0.13, $0.10Three live requests, 43 to 46 seconds each
First real-model run against the database, all changes declined7 centsOne run
A change plan for an existing record, declined5 centsOne run, 25 seconds
A forwarded passage filed from the chat, plan approved6 centsOne run, 80 seconds, about half of it waiting for the tap
An invented 11-page deck, pages in the conversation13 centsOne run, 39 seconds, nothing asked
A real 14-page deck, pages in a long conversation12 cents first sending; 34 cents third sendingOne sending each; the rise is the earlier copies carried forward
Page reader on the invented decka third of a cent (small model); 5.5 cents (main model)One run each
The real deck with the separate page reader20 cents (8 reader, 12 conversation)One run, in a conversation started afresh
A DocSend link read in a browser, address asked for15 cents; in further runs 14 to 18 centsThree good runs, about two minutes each
The same, address verified by email6 centsFour good runs, two and a half to three minutes; why it is cheaper was not looked into
A DocSend run cut off when the browsing service's credit ran out16 centsOne run, paid for and not completed
Evaluation suites (private errands)65 cents; $1.76; $5.28; $5.75120, 201, 567 and 581 runs respectively
A third message sent five and a half minutes after the second5.5 cents (cache kept five minutes); 1.3 cents (kept an hour)18 and 9 runs of three invented cases, conversations of about 19,000 tokens
Evaluation suites (a partner's errands)about $2.60; $0.60; $0.92112 runs over three rounds; 28 runs; 34 runs including three deck errands

The table supports orders of magnitude: a cent or two for a question, a fraction of a cent for a routine on the small model, five to twenty cents for a deck or a browser, a few dollars for an evaluation. It supports no average, rate or monthly figure. The three-dollar daily budget is a guess, not derived from these figures, and it is the default in the code.

20.8The theory

This section derives, from the cost formula of the model, what a conversation costs with and without a cache and when a cache that expires pays, and states each decision of the chapter as a reduction of one term.

Properties and measurements. The properties concern the ledger, derived state in the sense of Definition 8, so by Property 3 a restart leaves what it has recorded unchanged. Two qualifications follow from the same property. What a running task has spent enters the day's figure only as an estimate held in the process, so a task cut off by a restart writes no task_end and its spending is never recorded. And the day's budget is checked before a task starts, so a refused task calls no model. The limits during a task are checked after each model call, on the program's estimate: the task's figure is a mark, and its ceiling is task_stretch times the mark, so a task that makes progress may spend up to $2.00 and one that repeats a call or keeps failing is ended below the mark; the day's limit ends a task once its estimate reaches what is left. Each therefore bounds spending only up to the call that crossed it, and only for what the estimate sees. The table of real runs holds measurements, mostly single runs. The derivations are arithmetic on the price table: they give the shape of costs and leave their size to measurement.

Derivation: a conversation with and without a cache

Let call t of a conversation send c₀ + tδ input tokens, as in the model. With no cache its input costs

Cnone(m) = pin · (m·c₀ + δ·m(m+1)/2)

If every call follows the last within the cache's lifetime and writes what it adds, call 1 writes c₀ + δ and call t > 1 reads c₀ + (t − 1)δ and writes δ. Summing,

Cwarm(m) = pcw · (c₀ + m·δ) + pcr · ((m − 1)·c₀ + δ·m(m − 1)/2)

The square of m survives, with pcr in place of pin: in the program's table, a twentieth on the two larger models and a tenth on the small one. If the cache has expired before every call, each call writes everything, and

Ccold(m) = (pcw / pin) · Cnone(m)

which in the table is 1.25 times the cost of no cache at all.

When a cache that expires pays. A prefix of n tokens written once and read r times before expiry costs n·(pcw + r·pcr), against n·(1 + r)·pin uncached. Writing pays when

r > (pcw − pin) / (pin − pcr)

At the five-minute rate on the main model that is 0.50 / 1.90 ≈ 0.26, so one read repays the write. For a one-hour lifetime written at twice the input price and read at the same price it is 2.00 / 1.90 ≈ 1.05: two reads are needed. Within a task, several calls in quick succession, the cache pays. Between tasks the owner's habit (a message, then nothing for an hour) leaves the next task's first call paying pcw on the whole conversation behind it.

Beginning again. Split a conversation of m = m₁ + m₂ calls at a pause, and let the second part start from c₀ + s, where s is what is carried. With no cache the input saved is

δ·m₁·m₂ − s·m₂ = m₂ · (δ·m₁ − s)

so beginning again pays when the history dropped, δ·m₁, exceeds what is carried, and pays on each of the m₂ later calls. The closing summary, about two hundredths of a cent on the small model, costs as much as writing about 80 tokens to the cache at the main model's price and hardly moves the condition. The code's thresholds agree with this without being derived from it; a message's cost before and after the rule is unmeasured.

Each decision as a term. Reading a file's pages in a separate run reduces δ: notes arrive in place of pages and are what every later call carries. Cutting a search's results to 12,000 characters reduces δ. Beginning again reduces m per conversation at the price of s added to the next c₀, and leaving a file's text out keeps s small. Code in place of a model, and refusals before any call, reduce m. The cap of eight paid reads bounds a routine's metered reads and with them its calls. Looking only at pages with pictures reduces c₀ of the reader's run. Two decisions fit no term: a cheaper model scales all three through the prices, and preferring web search to X changes a metered price outside the formula. The model's sentence holds for decisions about tokens; price is a fourth lever. Budgets bound m and the day's total and reduce nothing on average.

The hypotheses fail where the chapter says: δ is not constant (a file is a spike, the opening case), the library condenses a long conversation, which bounds t·δ, and the table omits the small model's higher price above 100,000 tokens.

Claim in this chapterKindHow it is known
The ledger is the same before and after a restartPropertyProperty 3; the nine-line test
A task refused by the day's budget calls no modelPropertyArgued from the order of the checks; tested
Uncached input grows with the square of the number of callsDerivationFrom the model; not measured here
The deck's third sending cost 34 cents against 12MeasurementOne sending each; cached and uncached tokens not separated
A day's spending cannot exceed $3.00False as statedEach task is ended after the call that crossed what was left, on an estimate that does not see a browser run or the page reader until their lines are written
The separate reader keeps a conversation's cost flat over several decksNeither yetNot tested

20.9What goes wrong

A total read as a cost

Case note

The first version added the library's reported cost to the day after each task. Three trivial questions reported $0.0013, $0.0026 and $0.0029, and the ledger recorded $0.0068 for work that cost $0.0029, because the figure was a running total for the conversation. The tests had passed, because the stand-in for the library reported costs the way the authors believed the library did. The first live run found it.

Before summing a number, find out what it is a number of: a call, a run, a session or a billing period.

A ledger that left things out

A later reading of the whole program (Chapter 19) found that the ledger counted model calls and browser runs and nothing else. Searches, files and voice notes were not counted. Checks of incoming events were counted until the next restart and then forgotten. A forced stop cost nothing. "Today" ended at the machine's midnight. One move fixed all of these: one pricing function over every line.

A wider rule that counted one thing twice

Case note

The ledger at first priced one kind of tool line, web search. Making it price "any tool line that reports a cost" was a one-line change, made so that paid reads of X would count. It doubled the cost of every browser run, because a browser run's cost is already added to the task_end of the task it belongs to. An existing browser test failed, reading 0.07 where it expected 0.04. The rule now names its one exception, and a test asserts that a browse line is priced at zero.

A derived ledger moves the risk from forgetting to count to counting twice. The defence is a test for each case that must not be counted, beside those that must.

Budgets that act after the call that crosses them

The day's budget is checked before a task starts and again after each of its model calls, so a task that begins a cent under the limit is ended after one more call, not at its own $0.50. Both checks act only after the call that crossed the limit has been paid for, and both rest on an estimate that leaves out the small model's higher price for very long prompts, a browser run inside the task and a reading of a file's pages, which are counted only when their lines are written. The agent library's own hard cap is not set. The per-task mark lets a task that is getting somewhere run to four times its figure, and the signs of getting nowhere see only a call repeated with the same inputs or failures in a row: a task that makes different calls each time and still goes round in circles is ended only by the ceiling. These are known and not repaired.

Costs nobody reconciled

Every figure here is what a service said or what the program estimated. The code itself says the per-page and per-minute prices "should be checked against an invoice". X's estimate has never met a read that returned posts. Whether the running total continues correctly after a conversation is resumed from disk has not been measured.

20.10How to test it

A test of cost handling must check that each paid kind of line is priced and each that must not be (a browser line, a scheduling record) is priced at zero; that the ledger after a restart equals the ledger before it; that a day ends at the owner's midnight; that a task's cost is a difference of running totals; that each budget ends or refuses work, the daily one with no model call; that an estimate errs high for an unknown model; and that a separate run writes its own cost line.

The existing tests do these with stand-ins. Verified, unit tests: the nine-line ledger above and its equality after a restart, and the owner's midnight (tests/test_stage0.py); a search's reported price reaching the ledger (same file); running-total differences, the token estimate, both per-task limits and the daily refusal (tests/test_slice.py); X's estimate by item type, and a browser line priced at zero (tests/test_mcpapp.py); a browser run's cost added to its task (tests/test_browser.py); the page reader shown the file, given no tools, and its cost counted (tests/test_ocr.py).

Verified, unit tests (tests/test_fresh.py): half an hour's pause continues the same conversation and three hours' begins a new one that carries the last exchanges and the memory; a large conversation begins again after fifteen idle minutes and not after four, and a small one does not; a file's text is left out of what is carried; the rule can be switched off; a search's results are cut.

What none of them can show is whether the prices are right. A test can prove that the ledger adds what the journal says. Only an invoice can prove that the journal says what was charged.

What is proven and what is not

Verified by unit tests: the ledger's single definition and everything listed above. Verified live, once each: the deck's 12 and 34 cents in a long conversation, and 20 cents with the separate reader in a fresh one; the reader's cost on each of two models; and the other single runs in the table of measured costs.

Not tested: whether the cost of a conversation stays flat across several decks with the separate reader, which is the claim the design rests on; any reconciliation of the ledger with a vendor's invoice; X's per-item estimate against a read that returned items; what a message costs before and after the rule that begins a new conversation after a pause, and whether the three exchanges it carries are enough for the owner not to notice; whether costs are counted correctly across a resumed conversation. The daily budget's value was a guess and remains one.

20.11Where this sits in the literature

The prices behind this chapter's arithmetic come from the model maker's documentation. [Anthropic 2026c] describes caching a prompt's prefix with a five-minute or a one-hour lifetime, writes at 1.25 or 2 times the input price, and reads at a tenth of it or less. The program's table agrees for writes and records reads at a twentieth for the two larger models, which is within that range. The derivations in the theory section follow from those ratios alone. The one-hour lifetime is a setting here, off by default and unmeasured, and the break-even above says when it would pay: two reads of the same prefix within the hour.

On how costs should be reported, [Kapoor et al. 2024] argue that evaluations of agents should report cost alongside accuracy, guard against overfitting with held-out sets, and fix problems of reproducibility. The decision about the thinking dial follows the first point: score, calls and cost were measured together, and the dial was left alone because none moved. The table of real runs falls short of the paper's standard: most figures are single runs, so they carry no interval in the sense of Definition 9, and none can be compared with another system's. [Kapoor et al. 2025] describe shared infrastructure for running agent evaluations in a standardised way across benchmarks, which is what such a comparison needs and what this program does not have. Here the published work is plainly stronger.

The design decisions have counterparts in practitioners' accounts of managing context. [Anthropic 2025a] describe just-in-time retrieval, compaction and sub-agents. The page reader is a sub-agent whose context is thrown away; beginning again with three exchanges in words is a compaction done by code at a time code chooses; and the files kept for the owner are fetched only when asked for. [Anthropic 2025d] describe a tool that discovers tools on demand instead of loading every definition, which is an attack on c₀, since tool descriptions belong to the fixed part s of Definition 1. This chapter never measures how much of c₀ is tool descriptions, so it cannot say whether that would matter here. [Packer et al. 2023] let the model itself move information between the context and outside storage through function calls. This program keeps that decision in code, where it costs nothing and can be tested, and gives up the model's judgment of what is worth keeping.

Two further readings bear on what is lost. [Liu et al. 2023c] found that a model's accuracy depends on where in a long context the relevant information sits, and is often lower in the middle. A shorter context may therefore be better as well as cheaper, though this program has not measured whether beginning again changes the quality of answers. That question, how much of a conversation can be dropped before the owner notices, is not settled by any of these readings.

The ledger itself is event sourcing: [Fowler 2005] records every change as an ordered event and rebuilds state by replaying the events, and the ledger is the journal replayed through cost_of. The chapter's case of the browser counted twice shows the risk this moves, from forgetting to record to counting one record twice. Budgets borrow less well. [SRE book, embracing risk] introduce error budgets, a stated amount of unreliability derived from an objective so that change can proceed. The three-dollar daily budget is a limit of the same form with no objective behind it: the chapter says it is a guess.

Summary
  • A model call is billed by tokens in and out. Every call re-sends the whole context, so in a long conversation the input side dominates, and anything placed in the conversation is paid for again by every later call.
  • Caching cuts the price of re-reading a context to between a tenth and a twentieth in the program's table. It softens the cost of a long conversation; it does not remove it.
  • Every paid call writes a journal line. One function, cost_of, prices a line; the ledger is that function summed per owner's day. The figure cannot drift from the record.
  • Some prices are reported by the vendor, some estimated by the program, and the journal marks which. None has been checked against an invoice. Cost also drives design: a cheaper model for unattended work, code before models, refusing before spending.
  • Budgets stop work: per task as model calls arrive, at a ceiling four times the task's mark or at once when it is getting nowhere; per day before a task starts and after each of its calls. Neither is a hard ceiling: each acts after the call that crossed it.
  • A PDF kept in the conversation cost 34 cents on its third sending against 12 on its first. Reading its pages once, in a throwaway run with no tools, and passing on only text, is the fix; its long-run saving is not measured.
Problems

Review

  1. Using the price table, work out the estimated cost of a model call that reports 40,000 input tokens, 600 output tokens and no cached tokens on the main model. Then work it out again with 38,000 of those input tokens read from the cache. What fraction of the first figure is the second?
  2. Why does cost_of price a browse line at zero but a see_pages line at its full cost, when both are separate runs of another model or service? What would go wrong if the page reader's cost were added to the conversation task's task_end instead?
  3. The daily budget is checked during a task as well as before it: AgentRunner.within in odysseus/agent.py ends a task when its estimate reaches what is left of the day, less what other running tasks are spending. List what the day can still be overspent by, from the code, and say for each whether a change could close it. What failure mode does ending a task this way introduce for a task that is halfway through changing the owner's records, and what does the owner see?
  4. The text-recognition price is a fixed estimate in the code. Design a way to reconcile the ledger with a vendor's monthly invoice. What would you do with a discrepancy: change past journal lines, add new ones, or change the function? Defend your answer in terms of the rule that the journal is append-only.

Analysis

  1. A conversation starts with c₀ = 20,000 tokens and adds δ = 1,500 per call, over m = 40 calls on the main model (input $2.00 a million tokens, cache write $2.50, cache read $0.10). Count input only. (a) With no cache, find the total input tokens and their cost. (b) With a cache kept warm throughout, as in the derivation, find the cost. (c) With no cache, the conversation is split after 20 calls into two of 20 calls each, and the second starts from c₀ + s with s = 3,000. Find the total input tokens and the cost, and check your answer against the formula for the saving. (d) With a cache that has expired before every call, find the cost, and say what this does to the claim that caching makes a conversation cheaper.
  2. (a) Derive the break-even number of reads r for a cache that expires, and evaluate it from the program's table for the five-minute rate on the main model and on the small model, and for a one-hour lifetime written at twice the input price and read at the price in the table. (b) On the main model, the owner sends a message every 50 minutes, and each task makes three calls within a minute on a context of n tokens; ignore growth. Assume that a read inside the lifetime keeps the cached prefix alive at no extra charge. In steady state, find the cost of one task's input under the five-minute lifetime and under the one-hour lifetime, in dollars per million tokens times n. (c) Which assumption in (b) would you check first in the documentation, and what happens to your answer if it is false?
  3. The model states that every design decision in this chapter is a smaller c₀, a smaller δ or a smaller m. Find the decisions in the chapter for which that is false, and state the lever each uses. Then prove that, with no cache, beginning again after m₁ calls saves input exactly when δ·m₁ > s, and construct a conversation in which the rule in the code begins again and costs more than continuing would have. Name the hypothesis of the derivation that your example breaks.
  4. Prove from Property 3 and the code of Ledger._count that the day's figure after a restart equals the figure before it. Then give two changes that alter the figure for a past day without violating Property 3, and one change to the program that would violate it. The first version of the ledger, which added the library's running totals, is one candidate; say whether it is of the first kind or the second.

Design

  1. A vendor offers the model at a flat monthly price, with a limit on calls a minute in place of a price per token. Redesign the ledger, cost_of and the three budgets for that world. Say what a budget then guarantees, which of this chapter's design decisions still matter and which become pointless, and what is given up if the vendor's limit is reached in the middle of a task that is changing the owner's records.
  2. Design the cost report for one evaluation suite (Definition 9), meeting the demand that cost be reported alongside accuracy. Say which figures are derived state that can be recomputed from the journal, which are measurements that need an interval, how the interval is computed over cases, and how a reader would tell a change in cost from noise. Then say what your report could not show without an invoice.

Reading

  1. [Anthropic 2026c]. In about four hundred words: what the document claims about lifetimes and prices; why it matters for the rule that begins a new conversation after a pause and for the one-hour lifetime, which is a setting left off by default; where you were not convinced that the derivation in this unit captures how the cache behaves; and what you would measure next, with the journal's token counts.
  2. [Kapoor et al. 2024]. In about four hundred words: what the paper claims; why it matters for the table of real runs and for the decision to leave the thinking dial alone; where you were not convinced, for a system used by one person; and what you would measure or build next so that this program's costs could be compared with another's.

Open

  1. Hard, open: the claim behind the page reader is that a file's cost stays flat over a long conversation. Design an experiment that would test it fairly: how many decks, in what kind of conversation, compared with what, measuring which numbers, and what result would make you go back to putting pages in the conversation.
  2. Find how much of a conversation can be dropped before its owner notices. Define "notices" as something that can be counted (a repeated question, a correction, a worse answer judged blind), propose a rule for what to carry that is cheaper than three exchanges in words, and design the measurement that would place it on a curve of cost against that count, with intervals over cases. Progress would be a rule that is cheaper at the same count, outside the noise floor.