The question I could not answer

A title-research application I run calls a hosted language model to interpret deeds, read index pages, extract flowcharts and handle intake requests. In August I wanted to know what that was costing, per call, and I could not say. Every call site built its own client and returned .text, discarding the usage object that carries the token counts. The application ran two providers at the time, Anthropic and Gemini, behind a provider abstraction with fallback chains, so the answer also had to hold across both.

The ledger

One table, one function, one report. Each row records the time, provider, model, operation, case name, input tokens, output tokens, cached input tokens, an estimated cost, whether the call succeeded, and a short error text when it did not. record_usage() is called on the way out of every provider call. A normalizer flattens the two SDKs' usage objects into one shape, since they name the same three numbers differently and neither is guaranteed to be present. A failed call has no usage at all. usage_summary() rolls the window up by model, by operation and by day, counts failures and unpriced calls, and the application exposes it at a system endpoint.

Invariant one: recording never raises. A deed interpretation must not fail because the spend ledger could not be written. Every entry point swallows its own exceptions and logs a warning. The test points the database path at a directory that does not exist and calls record_usage(); it has to return. The call site wraps it in a second try anyway, because metering must never break analysis.

Invariant two: cost only where a price is configured. Prices live in a table, dollars per million tokens, with cached input billed at a tenth of the input rate. A model absent from the table records its tokens with a null cost, and the report returns cost_is_complete: false and names the models it could not price. A guessed number in a spend report is worse than an honest blank.

def estimate_cost(model: str, tokens: Dict[str, int]) -> Optional[float]:
    price = config.MODEL_PRICES.get(model)
    if not price:
        return None
    cached = tokens.get("cached_input_tokens", 0)
    fresh = max(0, tokens.get("input_tokens", 0) - cached)
    per_token_in = price["input"] / 1_000_000
    per_token_out = price["output"] / 1_000_000
    return round(
        fresh * per_token_in
        + cached * per_token_in * config.CACHE_READ_DISCOUNT
        + tokens.get("output_tokens", 0) * per_token_out,
        6,
    )

The tests are small and specific: a million input and a million output tokens on Opus 5 come to thirty dollars, cached input costs less than fresh, cost never goes negative when the cached count exceeds the input count, garbage token values coerce to zero, and the summary survives a missing database.

What it measured on the first day

The first thing the ledger paid for was a model decision. Same deed, same prompt, two models:

ModelInputOutputCostTime
claude-opus-53,4173,819$0.112645.1 s
claude-sonnet-53,4173,035$0.055831.2 s

Half the cost, 31 percent faster. Both agreed on every load-bearing field: no title passed, all minerals, no surface, medium confidence, the same quoted defeasance language. Opus was tighter on the list of reservations and exceptions. Sonnet hedged a fractional interest more explicitly. The abstractor verifies every interpretation, so that trade is worth the halved bill, and Sonnet became the default.

The second decision was effort, the parameter that governs how much the model thinks, and thinking bills as output. Same deed, Sonnet 5:

EffortOutputCostTimeContent
high3,753$0.066537.7 s5,791 chars
medium2,119$0.042021.9 s5,402 chars
low1,749$0.036519.4 s4,433 chars

Minerals, confidence and "no title conveyed" were identical at every level. But only high typed a church gift-over as a condition rather than a reservation, which is the right category in a title abstract, and only high caught a special power of appointment. A missed power of appointment is not a rounding error on a title opinion. So effort is per operation: medium globally for the bulk paths, high pinned on deed interpretation, the lowest-volume call in the application, for about 2.4 cents more per click. One more rule: not every model accepts the parameter, and sending it to one that does not is an HTTP 400 that would break the fallback hop onto that model. The config returns it only for models on a known list, and a per-call override cannot smuggle it onto anything else.

Three traps the switch exposed

1. The first content block is not the answer. resp.content[0].text was correct until a thinking-capable model became the default. With adaptive thinking on, content[0] is a thinking block, which carries .thinking and has no .text at all. The reader now collects text blocks only and concatenates them.

2. max_tokens caps thinking and output together. A budget of 4,096 or 8,192 sized for a bare answer could be spent thinking and return truncated JSON. The Anthropic paths now use 16,000.

3. A key for one vendor sent to the other looks like success. Six endpoints defaulted their key to the Gemini environment variable and passed it to whichever provider was configured. After the default moved, a Gemini-shaped key went to Anthropic and got a 401. The error classifier correctly refused to fall back on an auth failure, so the request returned HTTP 200 with no interpretation and via None in the log. A status-code monitor would never have caught it; only the log did. One resolver now picks the key by the SDK the call will use, and a header key shaped for the other SDK is discarded rather than sent. The two vendors' key prefixes differ, which makes the shape test trivial.

The blank that hid a bill

The deliberate blank in invariant two cut the other way once. Gemini prices were absent from the table on purpose. Meanwhile 2,197 small Gemini calls, all from one operation, drained that vendor's prepaid balance to zero on 8 September. The spend report said $1.80 and meant "of what I could price." I added list prices as estimates and wrote reprice_unpriced(), which recomputes only null costs from the token counts already in the ledger and never revises a recorded cost. The invariant was right. The incompleteness flag belongs next to the total, where the reader's eye lands, not under it. In the other direction, the ledger priced Sonnet at list during an introductory rate, so it over-reported for three weeks. An upper bound is the honest side to err on.

What the ledger said in October

In October I asked whether Gemini had been removed. It had not. Only the default had flipped in August. Six places still named Gemini as their default, the browser remembered it as the user's choice, the fallback chains ended on it by design, and the health probe called it at every boot and had been logging a payment error since the balance ran out. The ledger settled what to do. Six days with any model calls at all, 10 August to 8 September. 2,776 calls, $2.96 in total. 2,197 of them on the Gemini flash model, $1.16, all from one operation. Zero calls in the previous thirty days. Nothing was invoking a model.

That made the clean-up easy, because there was nothing to protect. One vendor, one key resolver, fallbacks within one SDK, every provider default pointing at one config value, the other key commented out of the environment. The health check now reports "no key" for the retired vendor instead of failed.

If you are adding one

  • Record on the way out of every call, in one function that cannot raise.
  • Store tokens always, cost only when you have a price, and flag incompleteness by model name next to the total.
  • Keep a reprice routine for null rows. Tokens are facts; prices change.
  • Read text blocks, not the first block. Size max_tokens for thinking plus output. Resolve keys by SDK.
  • A report of zero calls is a finding. Mine chose a model, set effort per operation, and retired a vendor, each on measured numbers.