03.7 Token Counting, Cost Tracking and Prompt Caching

Understand LLMsLesson 7 of 1329,374 words13 parts
Module 03 · 0 of 13 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13

Every LLM call has a price, and the price is only known for certain after the call has finished, in the response's usage object. Module 02 explained what tokens, prices and caches are. This lesson is the engineering on top: counting tokens before you send with each provider's counting endpoint, turning any provider's usage object into an exact dollar figure (cache reads and writes, reasoning tokens, long-context rates, batch, flex and fast tiers, regional uplifts), keeping prices in a dated table instead of in code, recording the cost of every call with who and what it was for, and using every prompt-caching API (Anthropic's breakpoints and lifetimes, OpenAI's prompt_cache_key and prompt_cache_options, Gemini's explicit caches, OpenRouter's pass-through and sticky routing) well enough to measure the hit rate and prove the saving. It ends with budgets, guards and alerts, and with reconciling your own numbers against the providers' usage and cost APIs.

What you'll learn

  • When a pre-flight token count is worth a network call, and how to call OpenAI's, Anthropic's and Gemini's counting endpoints in production code (their own rate limits, what they can't count, caching counts for stable prefixes), plus Gemini's offline LocalTokenizer and its real limits
  • The exact billing rule behind every usage field on every provider, implemented as one cost calculator that's tested against the providers' own worked examples, with one written-down convention for what "input tokens" means across the four providers
  • How to keep prices in a dated, validated price table, where to refresh it from (official pages, OpenRouter's catalogue, LiteLLM's community file) and how to detect drift automatically
  • How to build a cost tracker that takes any provider's response, records cost with attribution (feature, hashed customer, environment) and never breaks the request it's measuring, then answer "which feature, which customer, which day?" from its log
  • Prompt caching APIs in depth: Anthropic's automatic and explicit breakpoints, the 20-block lookback, mixed lifetimes, the invalidation hierarchy, pre-warming and cache diagnostics; OpenAI's prompt_cache_key, prompt_cache_options, prompt_cache_breakpoint, pre-warming and diagnostics; Gemini's implicit caching and the full explicit-cache lifecycle; OpenRouter's cache_control pass-through and sticky routing
  • How to measure caching from your logs (hit rate, token hit ratio, money saved or lost), diagnose misses, and build requests whose prefix stays byte-identical
  • Cache economics in code: break-even per provider, and when not to cache
  • How to control spend: output ceilings, per-request cost guards that downgrade or refuse, per-user and per-feature budgets, provider-side limits and alerts
  • How to read your organization's usage and costs from OpenAI's, Anthropic's and OpenRouter's admin APIs (and what Google offers instead), and how to reconcile them with your tracker

What you don't need

  • Any API key. The cost calculator, price table, hit-rate analyser, break-even calculator, cost guard and reconciliation all run offline on real-shaped data; the SDK parsing of usage fields runs against a mock server; and the cost tracker runs against the free local stand-in. Gemini has no local stand-in, so its samples are hosted-only (they need GEMINI_API_KEY) and were not run, and neither counting endpoint (Anthropic's or Gemini's) can be practised locally.
  • The concepts from Module 02, re-explained. This lesson links to them: tokens and the usage field table (02.2, Part 6), price structure and service tiers (02.9, Part 6), and how prompt caching works and how to design for it (02.7, Part 7).
  • Cost strategy: model routing, cascades, response and semantic caching are Module 11B's subject. This lesson gives you the measurements those strategies need.

Setup

The samples use Python 3.11+, the three official SDKs, Pydantic and PyYAML. Lessons 03.1 to 03.9 share one project folder, llm-apis. If you haven't created it yet, follow lesson 03.1, Part 4; the short version is:

bash
uv init llm-apis --bare --python 3.13 && cd llm-apis    # --python matters: see lesson 03.1, 4.2
uv add openai anthropic "google-genai[local-tokenizer]" python-dotenv pydantic pyyaml httpx pytest tiktoken
# or, without uv: pip install openai anthropic "google-genai[local-tokenizer]" python-dotenv pydantic pyyaml httpx pytest tiktoken

The samples were written and checked against openai 3.42.1, anthropic 2.4.0 and google-genai 2.34.0 as of November 2026; a newer major version may change names, fields or defaults (google-genai 3.x already does), so check the SDK's changelog if a sample does not match.

Keys go in a .env file as in lesson 03.1, 3.4: OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY. Part 13 also uses admin keys (OPENAI_ADMIN_KEY, ANTHROPIC_ADMIN_KEY) and an OpenRouter management key (OPENROUTER_MANAGEMENT_KEY). Keep those out of your application's environment entirely; only a reporting job should hold them.

tiktoken is optional (only 2.7 uses it). httpx2, which the mock-server samples import, is installed with openai and anthropic: you don't add it yourself (lesson 03.1 explains why these SDKs left httpx). The httpx in the uv add line is deliberate: the samples that call plain HTTP endpoints (s4_price_drift.py, s9_openrouter.py, s13_admin_usage.py) import it, and with google-genai 3.x httpx is no longer installed with the SDK (2.34.0, the version the samples were checked against, still pulled it in; see 03.1, 4.5).

Several samples import three small modules that this lesson builds: prices.py and prices.yaml (Part 4), cost_calc.py (Part 3) and cost_tracker.py (Part 5). Save them next to the samples; each part gives its module in full. Every listing starts with the file name to save it as, and 1.3 lists them all.

No keys? Set up the local stand-in from lesson 03.1, Part 12: Ollama with qwen2.5:0.5b and the model aliases. Gemini has no local stand-in (Ollama doesn't speak Gemini's API: 03.1, 12.4), so the Gemini samples are hosted-only. The stand-in runs the API calls but doesn't cache, doesn't count like the real providers, and returns no costs, so this lesson uses it for the mechanics (the tracker, the counting call shape) and uses real-shaped fixtures for everything about cache usage and prices. Every sample says which it is.

Versions used in this lesson (November 2026): openai 3.42.1, anthropic 2.4.0, google-genai 2.34.0, pydantic 2.14.3, PyYAML 6.0 and Ollama 0.32.5. Models: gpt-6-luna, gpt-6.1-terra, gpt-6.1-sol and gpt-6-astra; claude-haiku-5-5, claude-sonnet-5-5, claude-opus-5-5, claude-fable-5-2 (released 9 November 2026) and its legacy predecessor claude-fable-5-1; gemini-3.5-flash-lite, gemini-3.8-flash and gemini-4-argon; and OpenRouter's anthropic/claude-haiku-5.5.


What you must be able to do after this lesson#

  • Count tokens before you send a request
  • Compute the exact cost of a call
  • Track cost on real calls
  • Turn on prompt caching and read the cache fields
  • Measure whether caching saved money
  • Set a spending control

Why this matters for an AI engineer#

An LLM feature's cost isn't a line in a contract; it's the sum of millions of small, variable charges that depend on prompt length, caching, hidden reasoning and which tier actually served each request. Teams that don't measure it find out from the invoice. Teams that measure it badly (logging only part of the input, ignoring cache writes, pricing with last quarter's numbers) find out later, and argue about whose numbers are right.

You'll hear... You'll understand it after...
"Count the tokens before we send it, so we don't blow the context window." Part 2: Counting tokens before you send
"Our dashboard says $4k, the invoice says $5k." 3.3 Anthropic and 13.5 Reconciling
"Is input_tokens the total, or only what wasn't cached?" 3.1, the one convention this lesson uses
"Gemini's thinking tokens aren't in the output count." 3.4 Gemini
"We asked for Fast mode; were we actually charged for it?" 3.2 OpenAI
"Don't hard-code prices: Gemini's introductory price ends next month." Part 4: The price table as configuration
"Which customer is costing us the most?" 5.7 Answering the questions
"Put the breakpoint on the last block that doesn't change." 6.2 Where breakpoints go
"We fired 50 requests at once and none of them hit the cache." 6.6 Concurrency: warm the cache first
"Changing tool_choice broke our cache." 6.5 What invalidates what
"Set a prompt_cache_key per tenant." 7.2 prompt_cache_key
"The docs say 12h, but pyright says only 30m." 7.4 Lifetimes
"We created a Gemini cache and forgot to delete it." 8.2 Explicit caches: the full lifecycle
"OpenRouter already applied the discount; don't subtract it again." 9.3 usage.cost and the generation endpoint
"Our hit rate dropped to zero after Tuesday's deploy." Part 10: Measuring caching
"Is caching even worth it for this feature?" Part 11: Cache economics in code
"Cap each user at $5 a day." Part 12: Controlling spend

Part 1: The cost pipeline#

1.1 What Module 02 gave you, and what this lesson adds#

You already know the ideas this lesson is built on, so here they are as links, not lessons:

  • Tokens and how to count them, the three accuracy levels (estimate, exact count, billed truth) and the per-provider usage field table: 02.2, Part 6, especially 6.1 and 6.6.
  • How prices are structured: input, output, cached input, cache writes, reasoning tokens, tiers, long-context surcharges, regional uplifts and introductory prices: 02.9, Part 6, with a monthly cost model in 6.13.
  • Why history makes chats expensive: 02.7, Part 6.
  • How prompt caching works, the module's provider overview table and the design rules for cache-friendly prompts: 02.7, Part 7, sections 7.2, 7.3 and 7.4.
  • Reasoning tokens are billed as output: 02.8, 5.1.

Module 02's calculators take prices and token counts as parameters and answer "roughly what will this cost?". This lesson answers "exactly what did this call cost, who was it for, and does that agree with the invoice?", and it does so with the real response objects from the real SDKs.

1.2 Four moments to know the cost#

There are four moments at which you can know something about a call's cost, and a production system uses all four:

flowchart LR
    subgraph before ["Before the call"]
        E["Estimate tokens locally"] --> C{"Near a limit or<br/>an expensive call?"}
        C -- "yes" --> CT["Counting endpoint<br/>(cached per prefix)"]
        C -- "no" --> G
        CT --> G["Cost guard:<br/>worst case vs budget"]
    end
    G -- "send / downgrade" --> API["Provider API call"]
    G -- "refuse" --> R["Tell the user,<br/>log the refusal"]
    subgraph after ["After the call"]
        API --> U["usage object"]
        U --> N["Normalize usage"]
        N --> P["Price it with the<br/>dated price table"]
        P --> L["Record with attribution:<br/>feature, customer, env"]
    end
    L --> D["Dashboards, budgets,<br/>alerts, hit rates"]
    L --> REC["Daily reconciliation"]
    ADM["Provider usage and<br/>cost APIs"] --> REC
  1. Before the call (estimate and count). You know the input exactly, at least in principle, and the output only as a ceiling (max_output_tokens). This is where you enforce limits and budgets (Part 2, Part 12).
  2. Right after the call (usage). The usage object is the provider's statement of what it will bill. You price it and record it (Part 3, Part 5).
  3. Minutes to hours later (provider records). OpenRouter's generation endpoint and the admin usage and cost APIs give you the provider's own aggregated view (9.3, Part 13).
  4. Month end (the invoice). The number your finance team pays. Your tracker should agree with it within a few percent, and you should know why it doesn't when it doesn't (13.5).

1.3 The files you'll build#

File Part What it does
s2_count_openai.py, s2_count_anthropic.py, s2_count_gemini.py 2.2-2.4 The counting endpoints, one per provider
s2_local_tokenizer.py 2.5 Gemini's offline tokenizer, with a fallback
s2_token_budgeter.py 2.7 Estimate locally, confirm remotely, cache the counts
prices.yaml, prices.py 4 Dated price table and a validated loader
cost_calc.py 3 Normalizes every provider's usage into one Usage shape and prices it into line items
s3_cost_examples.py, s3_mock_usage.py 3.6, 3.8 Priced examples; the SDKs parsing usage from a mock server
test_cost_calc.py, test_cost_tracker.py 3.7, 5.8 Tests against the providers' worked examples; one record of every response type
s4_price_drift.py 4.4 Price table vs OpenRouter's and LiteLLM's feeds
cost_tracker.py, prices_fake_local.yaml 5 Records cost and attribution for every call, as JSON Lines
s5_tracker_local.py, s5_tracker_hosted.py 5.3, 5.5 The tracker on the stand-in and on real providers
s5_stream_local.py, s5_stream_incomplete.py, s5_stream_gemini.py 5.4 Cost from streams, including a capped OpenAI stream
s5_report.py, s5_tracker_modes.py 5.7, 5.8 Spend reports; batch, regional, Interactions and OpenRouter-Responses calls
s6_auto_chat.py, s6_anthropic_caching.py, s6_cold_start.py 6 Anthropic caching: automatic, explicit, cold start
s7_ttl_typecheck.py, s7_openai_caching.py 7 OpenAI caching and the 12h type gap
s8_gemini_cache.py 8.2 Gemini explicit-cache lifecycle
s9_openrouter.py 9.3 OpenRouter caching, cost and generation stats
make_fixture_log.py 10.2 Generates the fixture log usage_log.jsonl
s10_hit_rate.py, s10_request_builder.py 10 Cache hit-rate analyser; cache-aware request builder
s11_break_even.py 11 Cache break-even per provider
s12_cost_guard.py 12 Per-request cost guard and per-user budgets
s13_admin_usage.py 13 Provider usage and cost APIs
s13_reconcile.py 13 Your numbers vs the provider's

Part 2: Counting tokens before you send#

2.1 When counting is worth a call#

02.2, 6.1 gave the reasons to count (limits, cost, rate limits, routing) and the three levels of accuracy. In production, the question is narrower: when is an exact count worth an extra network round trip? The counting endpoints are fast and (on Anthropic) free, but they're still a request: tens to hundreds of milliseconds added to the user's wait, another thing that can fail, and their own rate limit.

Situation Count remotely? Why
A short chat turn, far from any limit No A local estimate with a safety margin is enough; usage tells you the truth afterwards
A request whose estimate is near the context window or your input budget Yes Being wrong means a failed request (400) or a trimmed prompt you didn't need to trim
An expensive request (a 300K-token document, a top-tier model) Yes An exact count lets a cost guard decide before you spend dollars, not after
Choosing between models by input size (routing) Usually estimate; count only near the boundary Routing on an estimate is fine away from the threshold
The same large, stable prefix on every request Count it once and cache the count The count of a fixed system prompt + tools doesn't change; recount when they do
Requests with images, PDFs or tools Count (when it matters) Local tokenizers can't count media, tool schemas or message formatting. 03.6, 3.3 shows counting an image on all three providers

The rest of this part shows each provider's endpoint in production form (timeouts, error handling, a fallback), then the patterns that keep counting cheap.

2.2 OpenAI: responses.input_tokens.count#

OpenAI's counting endpoint is POST /v1/responses/input_tokens, exposed as client.responses.input_tokens.count(...). It takes the same request fields as responses.create (model, instructions, input, tools, tool_choice, text, reasoning, conversation, previous_response_id, truncation and a few more; output settings like max_output_tokens aren't part of it) and returns an InputTokenCountResponse with input_tokens. OpenAI's token-counting guide says it handles "text, messages, images, files, tools, or conversations" and that "the count includes formatting tokens used to represent request structure, such as message roles and boundaries".

The production version counts the whole request (instructions, tools and input) and falls back gracefully:

Save as s2_count_openai.py:

python
"""Count a Responses request's input tokens before sending it (OpenAI)."""
import openai
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                                   # reads OPENAI_API_KEY from .env
client = OpenAI(timeout=10.0, max_retries=2)    # counting should be fast: fail fast too

TOOLS = [{
    "type": "function", "name": "get_order", "strict": True,
    "description": "Look up an order by its ID.",
    "parameters": {"type": "object", "additionalProperties": False, "required": ["order_id"],
                   "properties": {"order_id": {"type": "string", "description": "e.g. ORD-1042"}}},
}]

request = {
    "model": "gpt-6-luna",
    "instructions": "You are Acme's support assistant. Be brief.",
    "tools": TOOLS,
    "input": [{"role": "user", "content": "Where is order ORD-1042?"}],
}


def count_input_tokens(req: dict) -> int | None:
    """Exact input count for a Responses payload, or None if counting failed."""
    try:
        # Same keyword arguments as responses.create; output settings are simply not sent
        return client.responses.input_tokens.count(
            model=req["model"], instructions=req.get("instructions"),
            tools=req.get("tools", []), input=req["input"],
        ).input_tokens
    except (openai.APIConnectionError, openai.APIStatusError) as e:   # APIStatusError covers RateLimitError
        print(f"count failed ({type(e).__name__}); fall back to a local estimate")
        return None


with_tools = count_input_tokens(request)
without_tools = count_input_tokens({**request, "tools": []})
print("input tokens, with tools:   ", with_tools)
print("input tokens, without tools:", without_tools)
if with_tools is not None and without_tools is not None:
    print("one tool definition costs:  ", with_tools - without_tools, "input tokens on EVERY request")
Example output · illustrative3 lines
input tokens, with tools:    93
input tokens, without tools: 31
one tool definition costs:   62 input tokens on EVERY request

Not supported locally: Ollama has no counting endpoint, so against the stand-in the code takes its fallback path (count failed (NotFoundError); fall back to a local estimate). That's a useful test of the fallback in itself.

What to know, as of November 2026:

  • The count is exact, and it takes media. OpenAI's guide says the endpoint "returns the exact count the model will receive", and accepts images (by file_id, URL or base64 data URL) and PDFs (file_id, file_url or file_data) as well as text, tools and conversations; 03.6, 3.3 counts an image with it. "Exact" is about the request: what you pay is that total split into uncached, cache-read and cache-write tokens (Part 3).
  • It's Responses-shaped. There's no Chat Completions counting endpoint. If your code uses Chat Completions, either convert the messages to Responses input items for counting, or estimate with tiktoken (02.2, 6.2).
  • Cost and rate limits aren't stated on the API reference or the token-counting guide. Treat it as a normal API request that counts toward your request rate limits, check your organization's limits page, and design for it to fail (2.7).
  • conversation and previous_response_id are counted as part of the input: the API reference says a conversation's items "are prepended to input_items", so you can count the real size of a stateful turn (lesson 03.2).

2.3 Anthropic: messages.count_tokens#

Anthropic's endpoint is POST /v1/messages/count_tokens, exposed as client.messages.count_tokens(...). It accepts the same inputs as messages.create (model, messages, system, tools, tool_choice, thinking, output_config, speed and others; there's no max_tokens) and returns a MessageTokensCount with input_tokens.

Save as s2_count_anthropic.py:

python
"""Count a Messages request's input tokens before sending it (Anthropic)."""
import anthropic
from dotenv import load_dotenv

load_dotenv()                                   # reads ANTHROPIC_API_KEY from .env
client = anthropic.Anthropic(timeout=10.0, max_retries=2)

TOOLS: list[anthropic.types.ToolUnionParam] = [{
    "name": "get_order", "description": "Look up an order by its ID.",
    "input_schema": {"type": "object", "required": ["order_id"],
                     "properties": {"order_id": {"type": "string", "description": "e.g. ORD-1042"}}},
}]
SYSTEM = "You are Acme's support assistant. Be brief."
MESSAGES: list[anthropic.types.MessageParam] = [{"role": "user", "content": "Where is order ORD-1042?"}]


def count_input_tokens(tools: list[anthropic.types.ToolUnionParam]) -> int | None:
    """Anthropic's own estimate of the input tokens, or None if it can't be counted."""
    try:
        return client.messages.count_tokens(
            model="claude-haiku-5-5", system=SYSTEM, tools=tools, messages=MESSAGES,
        ).input_tokens
    except anthropic.BadRequestError as e:
        # e.g. server tools (web search), the MCP connector, or url/file image sources
        print("not countable:", e.message)
    except (anthropic.RateLimitError, anthropic.APIConnectionError) as e:
        # count_tokens has its OWN requests-per-minute limit; don't let it block the real call
        print(f"count failed ({type(e).__name__}); fall back to a local estimate")
    return None


with_tools = count_input_tokens(TOOLS)
without_tools = count_input_tokens([])
print("input tokens, with tools:   ", with_tools)
print("input tokens, without tools:", without_tools)
Example output · illustrative2 lines
input tokens, with tools:    379
input tokens, without tools: 31

The jump is bigger than the tool definition alone, because whenever tools is present Anthropic adds a tool-use system prompt: 286 tokens on Claude Haiku 5.5 with tool_choice auto or none, and 406 with any or tool, per Anthropic's pricing page (November 2026). You pay for those tokens on every request that carries tools.

What Anthropic's token-counting page says, as of November 2026:

  • Free, with its own rate limit. Requests per minute by tier: Start 5,000, Build 10,000, Scale 20,000. "Token counting and message creation have separate and independent rate limits."
  • It's an estimate. "The actual number of input tokens used when creating a message might differ by a small amount." Counts "might include tokens added automatically by Anthropic for system optimizations", and "you are not billed for system-added tokens".
  • It returns invalid_request_error for server tools (web search, web fetch, code execution, tool search; the advisor tool is the exception), the MCP connector, and image or document blocks with a url or file source. Send images and PDFs as base64 to count them, or rely on usage afterwards.
  • A successful count isn't a limit check for media. The endpoint "estimates an image's token cost from its dimensions without fully processing it, so a successful count doesn't mean the image is within the Messages API's request limits" (03.6, 3.3). A count can succeed for an image the real request then rejects.
  • No caching logic. You can include cache_control in a count request, but "prompt caching only occurs during actual message creation". The count is the total, not "what would be billed at cache prices".
  • Count with the model you'll use. Claude 4.7 and later use a tokenizer that produces about 30% more tokens for the same text, so counts from older models don't transfer.

2.4 Gemini: models.count_tokens and its gaps#

client.models.count_tokens(model=..., contents=...) returns a CountTokensResponse with total_tokens (and cached_content_token_count when relevant). It counts text, images, audio, video and PDFs in contents, as 02.2, 6.4 showed.

The gap is everything that isn't contents. In google-genai 2.34.0, CountTokensConfig has system_instruction, tools and generation_config fields, but on the Gemini Developer API (an API key from AI Studio) the SDK refuses them before anything is sent:

Save as s2_count_gemini.py:

python
"""Count a generate_content request's input tokens before sending it (Gemini)."""
from dotenv import load_dotenv
from google import genai
from google.genai import errors, types

load_dotenv()                                   # reads GEMINI_API_KEY from .env
client = genai.Client(http_options=types.HttpOptions(timeout=10_000))   # milliseconds; no default!

contents = [types.Content(role="user", parts=[types.Part(text="Where is order ORD-1042?")])]

try:
    count = client.models.count_tokens(model="gemini-3.8-flash", contents=contents)
    print("input tokens (contents only):", count.total_tokens)
except errors.APIError as e:
    print(f"count failed ({e.code}); fall back to a local estimate")

# On the Gemini Developer API, google-genai 2.34.0 refuses to count a system
# instruction, tools or generation config, before any request is sent:
try:
    client.models.count_tokens(
        model="gemini-3.8-flash", contents=contents,
        config=types.CountTokensConfig(system_instruction="You are Acme's support assistant."),
    )
except ValueError as e:
    print("ValueError:", e)
Example output · illustrative2 lines
input tokens (contents only): 9
ValueError: system_instruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.

The ValueError line is real: it's raised inside the SDK before any network call, so you'll see exactly this message. The sample is hosted-only, because Gemini has no local stand-in (03.1, 12.4).

What this means for you:

  • On the Developer API, the SDK counts contents only. System instructions and tool declarations add tokens you can't count with count_tokens in this SDK version. Count them once by passing their text as contents (an approximation: the role wrapping differs slightly), add that to each request's count, and treat usage_metadata.prompt_token_count as the truth afterwards.
  • The REST endpoint can do more than the SDK exposes. The countTokens API reference documents a generateContentRequest field that carries the full request ("system instructions, and/or function declarations"), mutually exclusive with contents. google-genai 2.34.0 always sends contents, so using it means a hand-written HTTP call. If your counts must include tools, that's the route; test it against the real API.
  • Timeouts and retries are yours. models.* calls in google-genai have no default timeout and don't retry (lesson 03.1), which is why the sample sets HttpOptions(timeout=...) (in milliseconds).
  • Google's pages don't state a separate price or rate limit for countTokens as of November 2026. Treat it like any other request against your project's limits.
  • Interactions: there's no Interactions-specific counting call. Count with models.count_tokens using the same contents, and read usage.total_input_tokens on the interaction afterwards.

2.5 Gemini offline: LocalTokenizer#

google-genai ships an experimental offline tokenizer, google.genai.local_tokenizer.LocalTokenizer (install the extra: google-genai[local-tokenizer]). 02.2, 6.4 introduced it. Here's what it does in practice, checked against version 2.34.0's source and by running it:

  • It downloads the tokenizer model once, from a fixed GitHub URL, verifies its SHA-256 hash, and caches it in your system temp folder (<tempdir>/vertexai_tokenizer_model/). The first construction took about 76 seconds on this machine. After that it works with no network at all: with the network blocked by an unreachable proxy, construction and counting took 0.03 seconds. With the network blocked and an empty temp folder, it failed with a ProxyError. So: offline after the first download, as long as the temp folder survives (containers and CI runners often start with an empty one; bake the file into the image or warm it in a setup step).
  • It doesn't know the current models. Its model map covers Gemini 2.0, 2.5, 3 Flash Preview, 3 Pro Preview, 3.1 Flash-Lite, 3.1 Pro Preview and 3.5 Flash. gemini-3.8-flash and gemini-4-argon raise ValueError: Model ... is not supported. The 3.5 Flash, 3.1 Flash-Lite and 3.1 Pro Preview entries also need the transformers package and a download from Hugging Face.
  • Text only. Its docstring: "Only supports text based tokenization and no multimodal tokenization." It can include types.Tool and types.Schema objects in the count, not Python functions or Pydantic models.

So the production pattern is a wrapper that tries it and falls back:

Save as s2_local_tokenizer.py:

python
"""Offline Gemini token estimates with google-genai's experimental LocalTokenizer."""
import warnings

from google.genai import local_tokenizer

warnings.filterwarnings("ignore", message=".*experimental.*")   # it warns on every call

TEXT = "Explain the difference between input tokens and output tokens in two sentences."


def local_count(model: str, text: str) -> tuple[int, str]:
    """Return (tokens, method). Falls back to ~4 characters per token (Google's rule of thumb)."""
    try:
        tok = local_tokenizer.LocalTokenizer(model_name=model)
        return tok.count_tokens(text).total_tokens or 0, "LocalTokenizer"
    except ValueError:                       # model not in this SDK version's tokenizer map
        return round(len(text) / 4), "len/4 estimate"


for model in ["gemini-3-flash-preview", "gemini-2.5-flash", "gemini-3.8-flash", "gemini-4-argon"]:
    n, how = local_count(model, TEXT)
    print(f"{model:24s} {n:3d} tokens  ({how})")

Output (run with the network blocked, after one earlier online run downloaded the tokenizer file):

text
gemini-3-flash-preview    13 tokens  (LocalTokenizer)
gemini-2.5-flash          13 tokens  (LocalTokenizer)
gemini-3.8-flash          20 tokens  (len/4 estimate)
gemini-4-argon            20 tokens  (len/4 estimate)

Notice the fallback over-estimated by about 50% on this sentence. That's the safe direction for limit checks, and it's exactly why the next section confirms remotely near a limit.

2.6 OpenRouter: no counting endpoint#

As of November 2026, OpenRouter documents no token-counting endpoint, and its usage counts use "the model's native tokenizer". The options are the ones 02.2, 6.5 listed:

  • Use the underlying provider's method when you also hold a key there (Anthropic's count_tokens for anthropic/... models, OpenAI's endpoint for openai/... models).
  • Estimate locally with the right tokenizer family. OpenRouter's public model list tells you which (architecture.tokenizer: GPT, Claude, Gemini and so on).
  • Read usage afterwards, and feed it back into your estimates: the ratio of billed prompt tokens to your local estimate, per model, is a correction factor you can learn from your own logs.

2.7 Production patterns: estimate, confirm, cache, rate-limit#

Put together, the patterns look like this: estimate the whole payload locally (system, tools and messages, not just the user's text), confirm remotely only near a limit, count a large stable prefix once and cache the count by a fingerprint of its content, and never let the counting endpoint's own rate limit block a real request. This runs offline, with a stand-in function where the real counting call would go:

Save as s2_token_budgeter.py:

python
"""Count tokens in production: estimate locally, confirm remotely only when it matters,
cache counts of stable prefixes, and respect the counting endpoint's own rate limit."""
import hashlib
import json
import statistics
import time
import warnings
from collections import OrderedDict
from typing import Callable

warnings.filterwarnings("ignore", message=".*experimental.*")   # LocalTokenizer warns on every use
try:
    import tiktoken                              # optional: uv add tiktoken
except ImportError:
    tiktoken = None

CONTEXT_LIMIT = 200_000         # input tokens you allow for this feature
CONFIRM_ABOVE = 0.7             # confirm remotely once an estimate passes 70% of the limit
SAFETY = 1.15                   # margin on top: code, JSON and non-English text tokenize worse than prose

# Characters per token for English prose, per provider (02.2, 6.7). The "4 characters per token" rule is for
# OpenAI-style tokenizers: Anthropic's current tokenizer is nearer 2.5. These are starting points, not truth:
# learn your own from your logs (learn_ratio below).
CHARS_PER_TOKEN = {"openai": 4.0, "anthropic": 2.5, "gemini": 4.0, "openrouter": 2.5}


def _gemini_tokens(text: str) -> int | None:
    """Offline count with google-genai's LocalTokenizer. It doesn't know gemini-3.8-flash or
    gemini-4-argon (03.7, 2.5), so this uses an OLDER model's tokenizer: a rough guide only."""
    try:
        from google.genai import local_tokenizer
        return local_tokenizer.LocalTokenizer(model_name="gemini-3-flash-preview").count_tokens(text).total_tokens
    except Exception:                            # missing extra, unsupported model, first download failed
        return None


def estimate(payload: dict, provider: str, correction: float = 1.0) -> int:
    """Cheap local estimate of the WHOLE payload: system, tools and messages, not just user text.
    `correction` is your learned billed/estimated ratio for this model (1.0 until you have logs)."""
    text = json.dumps(payload, ensure_ascii=False)
    exact: int | None = None
    if provider == "openai" and tiktoken is not None:
        exact = len(tiktoken.get_encoding("o200k_base").encode(text))     # a close proxy, not the endpoint
    elif provider == "gemini":
        exact = _gemini_tokens(text)
    n = exact if exact is not None else len(text) / CHARS_PER_TOKEN[provider]
    return round(n * SAFETY * correction)


def learn_ratio(pairs: list[tuple[int, int]]) -> float:
    """From logged (local estimate, billed input tokens) pairs: the typical billed/estimated ratio."""
    return statistics.median(billed / est for est, billed in pairs if est)


def fingerprint(obj: object) -> str:
    """Stable hash: same content -> same key, whatever the dict order."""
    return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()).hexdigest()


class TokenBucket:
    """Allow `rate_per_min` calls per minute; never block, just say no."""
    def __init__(self, rate_per_min: int) -> None:
        self.capacity, self.tokens, self.rate = rate_per_min, float(rate_per_min), rate_per_min / 60
        self.last = time.monotonic()

    def try_take(self) -> bool:
        now = time.monotonic()
        self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
        self.last = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False


class Counter:
    def __init__(self, remote: Callable[[dict], int], rpm: int, provider: str = "anthropic",
                 cache_size: int = 1024) -> None:
        self.remote, self.bucket, self.provider = remote, TokenBucket(rpm), provider
        self.prefix_cache: OrderedDict[str, int] = OrderedDict()
        self.cache_size = cache_size
        self.stats = {"estimated_only": 0, "remote": 0, "prefix_cache_hit": 0, "rate_limited": 0}

    def _prefix_tokens(self, prefix: dict) -> int:
        key = fingerprint(prefix)
        if key in self.prefix_cache:                 # stable system prompt + tools: count once
            self.prefix_cache.move_to_end(key)
            self.stats["prefix_cache_hit"] += 1
            return self.prefix_cache[key]
        if not self.bucket.try_take():               # counting endpoint has its OWN limit
            self.stats["rate_limited"] += 1
            return estimate(prefix, self.provider)
        n = self.remote(prefix)
        self.stats["remote"] += 1
        self.prefix_cache[key] = n
        if len(self.prefix_cache) > self.cache_size:
            self.prefix_cache.popitem(last=False)
        return n

    def count(self, payload: dict) -> tuple[int, str]:
        guess = estimate(payload, self.provider)
        if guess < CONFIRM_ABOVE * CONTEXT_LIMIT:    # far from the limit: the estimate is enough
            self.stats["estimated_only"] += 1
            return guess, "estimate"
        prefix = {"system": payload["system"], "tools": payload["tools"]}
        suffix = {"messages": payload["messages"]}
        # Prefix counted exactly (and cached); the changing suffix estimated. Re-count the whole
        # payload remotely if you need exactness right at the limit.
        return self._prefix_tokens(prefix) + estimate(suffix, self.provider), "prefix exact + suffix estimate"


def fake_remote_count(payload: dict) -> int:
    """Stands in for messages.count_tokens / responses.input_tokens.count in this demo."""
    return round(len(json.dumps(payload)) / 3.6)


if __name__ == "__main__":
    system = "You are Acme's contracts assistant. " + "Clause text. " * 50_000   # a big, stable prefix
    tools = [{"name": "search_clauses", "input_schema": {"type": "object", "properties": {}}}]
    text = "Explain the difference between input tokens and output tokens in two sentences."
    for provider in CHARS_PER_TOKEN:
        print(f"estimate for {provider:10s}: {estimate({'m': text}, provider):3d} tokens")
    print("learned correction:", round(learn_ratio([(100, 131), (400, 502), (50, 70)]), 2))
    counter = Counter(fake_remote_count, rpm=5)
    small = {"system": "Be brief.", "tools": [], "messages": [{"role": "user", "content": "Hi"}]}
    print("small request:", counter.count(small))
    for i in range(8):                                 # eight questions about the same contract
        big = {"system": system, "tools": tools,
               "messages": [{"role": "user", "content": f"Question {i} about clause {i}?"}]}
        n, how = counter.count(big)
        print(f"big request {i}: {n:,} tokens ({how})")
    other = {"system": system + " Updated.", "tools": tools, "messages": []}
    for _ in range(6):                                 # prefixes that keep changing exhaust the RPM budget
        other["system"] += "x"
        counter.count(other)
    print(counter.stats)

Output (the first four lines are each provider's local estimate of one sentence: Anthropic's 2.5 characters per token gives about 1.6 times OpenAI's 4, and the Gemini line uses the older tokenizer from 2.5, so it is a rough guide only):

text
estimate for openai    :  21 tokens
estimate for anthropic :  40 tokens
estimate for gemini    :  21 tokens
estimate for openrouter:  40 tokens
learned correction: 1.31
small request: (39, 'estimate')
big request 0: 180,629 tokens (prefix exact + suffix estimate)
big request 1: 180,629 tokens (prefix exact + suffix estimate)
big request 2: 180,629 tokens (prefix exact + suffix estimate)
big request 3: 180,629 tokens (prefix exact + suffix estimate)
big request 4: 180,629 tokens (prefix exact + suffix estimate)
big request 5: 180,629 tokens (prefix exact + suffix estimate)
big request 6: 180,629 tokens (prefix exact + suffix estimate)
big request 7: 180,629 tokens (prefix exact + suffix estimate)
{'estimated_only': 1, 'remote': 5, 'prefix_cache_hit': 7, 'rate_limited': 2}

Fifteen count requests cost five remote calls. The small request never left the process. Eight questions about the same contract counted the contract once. And when a burst of changing prefixes used up this demo's five-per-minute budget, the counter fell back to the estimate instead of making the user wait. What to take into real code:

  • Count the whole payload. Tools, system prompt, images and the message formatting are all input. Counting only the user's text under-counts every request, sometimes by thousands of tokens.
  • Key cached counts by content, not by name. A fingerprint of the canonical JSON changes the moment someone edits the system prompt, so a stale count can't survive a deploy. Re-count when you change models: counts are per tokenizer.
  • Give the counting call a short timeout and a fallback. It's an optimization, not a dependency.
  • Use each provider's own ratio, not one rule. 02.2, 6.7 and its 6.1 warning explain why: current Claude models produce about 1.5 times as many tokens as o200k_base for the same English prose, so len / 4 is about a third too low for Claude. estimate() takes the provider, counts OpenAI text with tiktoken when it's installed, tries LocalTokenizer for Gemini, and otherwise divides by that provider's characters per token.
  • Learn the ratio from your own logs. learn_ratio() divides the billed input tokens you logged (Part 5) by your local estimate for the same request and takes the median; pass it back in as correction. Six lines turn a guess into a measurement, per model and per feature (the example's three pairs give 1.31).
  • Share the bucket across your processes (Redis, or your rate limiter from lesson 03.8) if many workers count against the same organization's limit.

2.8 Counts, estimates and the bill#

Even an exact pre-flight count is not the bill:

  • Anthropic calls its count an estimate (and for an image it works from the dimensions alone, 2.3), may include system-added tokens you're not billed for, and ignores caching: the bill splits the same tokens into uncached, cache-write and cache-read lines at different prices (3.3).
  • OpenAI bills cached, written and uncached input at different rates; the count is exact for the request but is a total only. OpenAI also says some hidden system content is added on its side and doesn't count toward the caching minimum (Part 7).
  • Gemini's count (on the Developer API, via the SDK) misses system instructions and tools (2.4).
  • Output is unknown until the end, and reasoning tokens make it larger than the visible text. Budget with the ceiling, max_output_tokens (12.1).

Use counts to decide; use usage to account.


Part 3: Computing the exact cost of a call#

3.1 From usage to line items#

The usage object tells you how many tokens of each kind a call used; 02.2, 6.6 has the field names for every provider. What it doesn't tell you is which price applies to each token. That depends on billing rules spread across pricing pages, caching guides and footnotes: which fields overlap, which tier actually served the request, whether a threshold moved the whole request onto higher rates, and whether a regional endpoint added an uplift.

The approach that survives contact with real invoices is the one finance systems use:

  1. Normalize each provider's usage into one shape, with every token in exactly one bucket: uncached input, cache reads, cache writes (by lifetime), output (including reasoning).
  2. Look up the rates in force for that provider, model, day, tier and size.
  3. Produce line items (tokens × rate per bucket) and sum them.

Line items matter because they're what the providers' own cost reports use (OpenAI's Costs API groups by line_item, Anthropic's cost endpoint by token_type, Part 13), so you can reconcile bucket by bucket instead of arguing about one total.

The one convention this lesson uses. The four providers disagree about what their raw input field means, and the disagreement is the commonest source of wrong cost dashboards. So every Usage in this lesson says the same thing: input is uncached input, the tokens billed at the plain input rate. Cache reads and cache writes sit in their own fields.

Provider Raw field Does the raw field include cached and written tokens? Source
OpenAI input_tokens (Responses), prompt_tokens (Chat Completions) Yes. The guide's example: 12,000 input = 4,000 reads + 7,000 writes + 1,000 ordinary Prompt caching guide
Anthropic input_tokens No. It counts only the tokens after the last breakpoint; total = input_tokens + cache_creation_input_tokens + cache_read_input_tokens Rate limits, "Cache-aware ITPM"
Gemini prompt_token_count (Interactions: total_input_tokens) Yes for generate_content: "When cached_content is set, this also includes the number of tokens in the cached content" (SDK 2.34.0 field description). For Interactions Google doesn't say; 3.4 explains the assumption google-genai 2.34.0 types
OpenRouter prompt_tokens (Responses: input_tokens) Yes, by inference. The usage-accounting page never defines the field, but its example (prompt_tokens 194 with cache_write_tokens 100) only adds up if cached and written tokens are inside it. Check it on your first cached call Usage accounting

The conversion rule, in one line: total_input = input + cached + written, which is the Usage.total_input property in cost_calc.py. Going the other way, each from_* function subtracts what the provider includes (OpenAI, Gemini, OpenRouter) and leaves alone what it excludes (Anthropic). The trap is any code that logs a raw field under the name input_tokens: it means "total" for three providers and "uncached" for one.

The next four sections are the rules, provider by provider. 3.6 implements them. For what images, audio and PDFs cost in tokens, see lesson 03.6; this part is about pricing the tokens once they're counted.

3.2 OpenAI#

For the Responses API (response.usage, a ResponseUsage) and Chat Completions (completion.usage, a CompletionUsage), as of November 2026:

Rule Detail
Cached and written tokens are inside input_tokens input_tokens is all input. input_tokens_details.cached_tokens "counts billed reads and excludes tokens charged as writes", and OpenAI's caching guide says cache-write pricing "is not an additive fee: input tokens use the uncached-input, cached-input, or cache-write rate". So uncached = input_tokens − cached_tokens − cache_write_tokens. The guide's own example: 12,000 input = 4,000 reads + 7,000 writes + 1,000 ordinary tokens
Cache writes have two prices On GPT-5.6 and later, cache_write_tokens are billed at 1.25× the input rate for the default 30-minute lifetime and 2.5× for 12 hours. The split is in input_tokens_details.cache_write_tokens_details: ttl_30m_tokens and ttl_12h_tokens, which "do not overlap and sum to cache_write_tokens"
Reasoning is inside output_tokens output_tokens_details.reasoning_tokens is informational; don't add it again
Long context moves the whole request Per the gpt-6-luna model page: "Prompts with more than 272K input tokens are priced at 2x input and cache rates and 1.5x output for the full request" (the GPT-6 and 6.1 models, per the pricing page's long-context table)
Read the tier from the response response.service_tier is "the processing mode actually used to serve the request", which "may be different from the value set in the parameter". If you ask for fast or priority, the response says priority. Fast mode can fall back to default under ramp limits and is then billed at standard rates; flex is billed at Batch rates (50%); ultrafast (6× the standard rate, listed on the pricing page for gpt-6-astra and gpt-6.1-sol only) is a tier like any other. A service_tier value the calculator doesn't recognize raises an error instead of being priced as standard
Batch is 50%, and the response doesn't say so Batch results come from a batch job (lesson 03.9); your tracker knows it from context, not from service_tier
Regional processing adds 10% "Regional processing (data residency) endpoints are charged a 10% uplift for models released on or after March 5, 2026", and from 1 November 2026 FedRAMP endpoints too. The response doesn't tell you: it depends on which endpoint your client called (the SDK's data_residency= option, or a regional base URL), so record that with the call
Hosted tools are billed per call response.tool_usage.web_search.num_requests "counts billable searches" ($10 per 1,000 as of November 2026); the search results also arrive as input tokens. File search (per-call fees and storage) and the code interpreter and hosted shell (per-container-session fees) are billed too: the pricing page lists them. Usage doesn't model those, so a tracker built on it under-bills any feature that uses them; reconcile those lines against OpenAI's Costs API (13.1)

Chat Completions follows the same rules with different names: prompt_tokens (with prompt_tokens_details.cached_tokens and .cache_write_tokens), completion_tokens (with completion_tokens_details.reasoning_tokens), and service_tier on the completion.

3.3 Anthropic#

For message.usage (a Usage from anthropic.types), as of November 2026:

Rule Detail
Input is split three ways, with no overlap "Total input tokens in a request is the summation of input_tokens, cache_creation_input_tokens, and cache_read_input_tokens." input_tokens is only "the tokens that come after the last cache breakpoint". If you log only input_tokens, you under-report input whenever caching is on
Writes have two prices usage.cache_creation.ephemeral_5m_input_tokens at 1.25× the base input price and ephemeral_1h_input_tokens at 2×; cache_creation_input_tokens "equals the sum of the values in the cache_creation object"
Reads depend on the model 0.1× base on most models, 0.05× on Opus 5.5 and Sonnet 5.5, 0.025× on Fable 5.2 and Fable 5.1 (the table has a row for each, and 3.6 prices a call on Fable 5.2)
Thinking is inside output_tokens output_tokens_details.thinking_tokens is informational
Fast mode is its own price list speed: "fast" on Opus 5.5 costs $8 / $40 per MTok instead of $4 / $20, and on Fable 5.2 $16 / $80 instead of $8 / $40 (usage.speed reports "fast"). Caching multipliers and data residency "apply on top of fast mode pricing"; fast mode isn't available in batches
US-only inference is 1.1× inference_geo: "us" "incurs a 1.1x multiplier on all token pricing categories, including input tokens, output tokens, cache writes, and cache reads" on Claude 4.6 and later; usage.inference_geo says which applied. Earlier models reject the parameter with a 400
Batch is 50%, and stacks usage.service_tier is "batch"; the discount stacks with caching multipliers
Priority Tier is committed capacity usage.service_tier: "priority" means the request ran under a Priority Tier commitment, whose fee is billed separately (13.2). The price table carries priority: 1.0 for these models, so the tokens are priced at list: an upper bound, since the analytics API shows zero token cost for them
Haiku 5.5 has a size step Prompts over 100,000 tokens pay $0.50 / $2.50 instead of $0.10 / $0.50 (and higher cache prices). "A request's prompt length counts all of its input tokens, including cache reads and cache writes", and the step applies to the whole request. Other current Claude models bill the full 1M window at standard rates
Server tools cost extra usage.server_tool_use.web_search_requests at $10 per 1,000 searches, plus the result tokens as input; web_fetch_requests costs nothing beyond tokens. Code execution is billed by container time (1,550 free hours a month per organization, then $0.05 an hour), and is free when used with the current web search or web fetch tool versions

3.4 Gemini#

For response.usage_metadata (a GenerateContentResponseUsageMetadata), as of November 2026:

Rule Detail
The prompt count includes the cached part prompt_token_count: "When cached_content is set, this also includes the number of tokens in the cached content." So uncached = prompt_token_count − cached_content_token_count; the same applies to implicit cache hits
Thinking is NOT inside candidates_token_count thoughts_token_count is separate, and billed at the output rate ("Output price (including thinking tokens)"). Add it, or you'll under-bill every thinking request. total_token_count "is the sum of prompt_token_count, candidates_token_count, tool_use_prompt_token_count, and thoughts_token_count"
Tool results are input tool_use_prompt_token_count counts "the results from tool executions, which are provided back to the model as input"; bill them as input. Google's Gemini 4 Argon pricing note: "Every token the model processes is counted and billed, including thinking tokens and internal tool system instructions and function declarations when using grounding"
Per-modality detail prompt_tokens_details, cache_tokens_details and candidates_tokens_details are lists of ModalityTokenCount(modality, token_count). from_gemini puts the uncached non-text tokens in Usage.modality_input, and price() bills a modality at an input_<modality> rate (for example input_audio) if the model's row has one. As of November 2026 none of the table's models does: Google's pricing page lists one input rate for text, image, video and audio on 3.5 Flash-Lite and doesn't split input by modality for 3.8 Flash or 4 Argon. So audio is priced at the text rate, and Cost.notes says so out loud. What media costs in tokens is 03.6's subject
Explicit caches cost storage per hour Not in usage at all. You pay cache.usage_metadata.total_token_count × hours alive × the storage rate ($0.50 per million tokens per hour on Gemini 3.8 Flash through 31 December 2026, $1.00 from 1 January 2027), on top of the cached-read rate per request. storage_cost() in cost_calc.py prices it, and the tracker records it as its own event (8.3)
Tiers Batch and Flex are 50%; Priority is "75-100% more than Standard" (1.8× on the 3.8 Flash and 4 Argon price tables). Priority requests over your priority limits are "automatically and gracefully downgraded to Standard processing" and "billed at the standard rate". Google says to watch the x-gemini-service-tier response header. On the Developer API that header is the signal: the SDK documents usage_metadata.traffic_type as "not supported in Gemini API", so read response.sdk_http_response.headers and pass the value to from_gemini(..., service_tier=) (the tracker does it for you). Interactions responses carry service_tier (standard, flex, priority, deferred) on the interaction. A value with no per-token price (deferred, or Vertex's ON_DEMAND_OFFPEAK and PROVISIONED_THROUGHPUT) raises, so the tracker records "unknown" instead of guessing "standard"
Interactions uses other names interaction.usage: total_input_tokens, total_cached_tokens, total_output_tokens, total_thought_tokens (again separate from output: Google's streaming example reports 11 input + 90 output + 245 thought = 346 total), total_tool_use_tokens, grounding_tool_count and *_by_modality lists. Google doesn't document whether total_input_tokens includes total_cached_tokens (Understand and count tokens is silent). from_gemini_interaction assumes it does, as prompt_token_count does, and treats cached > total as proof it can't. On your first cached Interactions call, compare it with the sum of input_tokens_by_modality, and pass total_includes_cached=False if the numbers say the cached tokens are separate. A wrong guess misprices every cached Interactions call. The type also has initial_input_tokens, which this lesson doesn't use because Google doesn't explain it for billing
Prices have end dates Gemini 4 Argon: $2 / $10 "through November 30, 2026", then $4 / $20. Gemini 3.8 Flash: $0.75 / $3.75 through 31 December 2026, then $1.50 / $7.50 (02.9, 6.8). The same usage costs twice as much a few weeks later
Grounding with Google Search 5,000 free search requests a month shared across Gemini 3 and newer models, then $14 per 1,000, with a daily cap of 1,500 requests. The pricing page's footnote says you're "charged for each individual search query performed", so one request can cost several. from_gemini counts grounding_metadata.web_search_queries and from_gemini_interaction the google_search entries of grounding_tool_count; both are priced at list, because the monthly free allowance can't be known per call (an upper bound)

3.5 OpenRouter#

OpenRouter makes the arithmetic someone else's job, as long as you let it. Data governance: OpenRouter is a gateway, so your prompts may be routed to third-party providers you did not pick; check the gateway's and the upstream providers' data policies, retention and zero-data-retention (ZDR) options before sending enterprise data.

  • usage.cost is always returned, on every response, streaming or not. The old usage: {include: true} and stream_options: {include_usage: true} parameters "are deprecated and have no effect". It's "the total amount charged to your account", in credits, which OpenRouter denominates in US dollars (the /key endpoint reports the same spending "in USD").
  • It already includes the provider's discounts. Cache reads, cache-write premiums, the tier and any long-context step are already priced in. Don't apply cache discounts on top, and don't re-price OpenRouter calls with your own table: record cost as reported.
  • cost_details.upstream_inference_cost is what the upstream provider charged. On Chat Completions it splits into upstream_inference_prompt_cost and upstream_inference_completions_cost; on the Responses API, upstream_inference_input_cost and upstream_inference_output_cost.
  • is_byok says whether the call used your own provider key (BYOK, "bring your own key"). Then the provider bills you directly, cost is OpenRouter's fee, and the generation endpoint's upstream_inference_cost "is only available for BYOK" requests.
  • Token fields follow the API you called: prompt_tokens_details.cached_tokens and cache_write_tokens on Chat Completions, input_tokens_details on Responses. cost is in both: from_openrouter reads it from a Chat Completions object and from_openrouter_response from the Responses-compatible API's Response.
  • The SDK doesn't declare these fields. With the openai SDK they arrive in completion.usage.model_extra (cost, cost_details, is_byok), exactly as lesson 03.1 showed.
  • If cost is missing (a broken stream, or a client that dropped unknown fields), fetch it afterwards from the generation endpoint (9.3). Never fill in zero.

3.6 The calculator: cost_calc.py#

Here's the whole module. It has one normalizer per provider and API, each built on the SDK's own response types, and one price() function that applies the rules above using the price table from Part 4. Save it as cost_calc.py. Its docstring states the convention from 3.1: Usage.input is uncached input.

python
"""cost_calc.py: turn any provider's usage object into billed line items and a dollar cost.

The convention of this module, and of lessons 03.7, 03.10 and 03.11: `Usage.input` is UNCACHED input,
the tokens billed at the plain input rate. Providers disagree about their raw input fields (see
lesson 03.7, 3.1), so these `from_*` functions are the ONE place that converts them. Call them,
don't copy them:  total_input = input + cached_input + sum(cache_writes.values())  (`Usage.total_input`).
"""
from __future__ import annotations

import datetime as dt
from dataclasses import dataclass, field
from typing import Any

from anthropic.types import Message
from anthropic.types.beta import BetaMessage
from google.genai import types as gtypes
from openai.types.chat import ChatCompletion
from openai.types.responses import Response, ResponseUsage

from prices import PriceTable


@dataclass
class Usage:
    """One call's usage, in the same shape for every provider."""
    provider: str
    model: str
    input: int = 0                     # UNCACHED input, billed at the input rate (not the raw field!)
    cached_input: int = 0              # cache reads
    cache_writes: dict[str, int] = field(default_factory=dict)   # lifetime -> tokens
    output: int = 0                    # visible output + reasoning/thinking
    reasoning: int = 0                 # informational: already inside `output`
    tier: str = "standard"             # standard | batch | flex | fast | ultrafast | priority
    geo: str | None = None             # Anthropic inference_geo
    regional: bool = False             # OpenAI data-residency endpoint
    web_searches: int = 0              # OpenAI web_search calls, Anthropic web_search requests
    grounding_searches: int = 0        # Gemini "grounding with Google Search" queries
    modality_input: dict[str, int] = field(default_factory=dict)  # uncached input by non-text modality
    reported_cost: float | None = None   # OpenRouter usage.cost (credits)

    @property
    def uncached_input(self) -> int:
        """A readable alias for `input`, for code that wants the name to say what it means."""
        return self.input

    @property
    def total_input(self) -> int:
        """Every prompt token, however it was billed: what long-context thresholds look at,
        and what lesson 03.2's conversation store keeps as `input_tokens`."""
        return self.input + self.cached_input + sum(self.cache_writes.values())


# ---------- normalizers: provider response -> Usage ----------

# Strict on purpose: an unrecognized tier is an error, not "standard" (unknown is never zero)
_OPENAI_TIERS = {"default": "standard", "auto": "standard", "scale": "standard", "flex": "flex",
                 "priority": "fast", "fast": "fast", "ultrafast": "ultrafast"}
_GEMINI_TIERS = {"standard": "standard", "flex": "flex", "priority": "priority"}
_GEMINI_TRAFFIC = {"": "standard", "TRAFFIC_TYPE_UNSPECIFIED": "standard", "ON_DEMAND": "standard",
                   "ON_DEMAND_PRIORITY": "priority", "ON_DEMAND_FLEX": "flex"}   # others: no per-token price


def _openai_tier(service_tier: str | None) -> str:
    key = service_tier or "default"
    if key not in _OPENAI_TIERS:
        raise ValueError(f"unrecognized OpenAI service_tier {service_tier!r}: add it to _OPENAI_TIERS")
    return _OPENAI_TIERS[key]


def _openai_writes(details: Any, written: int) -> dict[str, int]:
    """Cache-write tokens by lifetime. The SDK type lags the API: read the split from model_extra."""
    extra = (details.model_extra or {}).get("cache_write_tokens_details") or {} if details else {}
    writes = {"30m": extra.get("ttl_30m_tokens", written), "12h": extra.get("ttl_12h_tokens", 0)}
    return {k: v for k, v in writes.items() if v}


def from_openai_usage(u: ResponseUsage, model: str, service_tier: str | None = None, *,
                      batch: bool = False, regional: bool = False) -> Usage:
    cached = u.input_tokens_details.cached_tokens or 0
    written = u.input_tokens_details.cache_write_tokens or 0
    return Usage(
        provider="openai", model=model,
        input=u.input_tokens - cached - written,     # cached and written tokens are inside input_tokens
        cached_input=cached, cache_writes=_openai_writes(u.input_tokens_details, written),
        output=u.output_tokens,                       # reasoning tokens are inside output_tokens
        reasoning=u.output_tokens_details.reasoning_tokens or 0,
        # the tier that actually SERVED the request, which can differ from the one you asked for
        tier="batch" if batch else _openai_tier(service_tier),
        regional=regional,
    )


def from_openai_response(resp: Response, *, batch: bool = False, regional: bool = False) -> Usage:
    """Also valid for status "incomplete" (a capped stream): usage is present, and it was billed."""
    if resp.usage is None:
        raise ValueError("response has no usage (a stream that never finished?): record it as unknown")
    usage = from_openai_usage(resp.usage, resp.model, resp.service_tier, batch=batch, regional=regional)
    if resp.tool_usage is not None:                   # hosted tools are billed per call, on top
        usage.web_searches = resp.tool_usage.web_search.num_requests
    return usage


def from_anthropic(msg: Message | BetaMessage) -> Usage:
    """`Message` (client.messages) and `BetaMessage` (client.beta.messages) carry the same usage fields."""
    u = msg.usage
    reads = u.cache_read_input_tokens or 0
    created = u.cache_creation_input_tokens or 0
    if u.cache_creation is not None:              # split by lifetime: 5m and 1h are priced differently
        writes = {"5m": u.cache_creation.ephemeral_5m_input_tokens,
                  "1h": u.cache_creation.ephemeral_1h_input_tokens}
    else:
        writes = {"5m": created}
    tier = u.service_tier or "standard"           # standard | priority | batch (Literal in the SDK)
    return Usage(
        provider="anthropic", model=msg.model,
        input=u.input_tokens,                         # only the tokens AFTER the last breakpoint
        cached_input=reads, cache_writes={k: v for k, v in writes.items() if v},
        output=u.output_tokens,                       # thinking tokens are inside output_tokens
        reasoning=u.output_tokens_details.thinking_tokens if u.output_tokens_details else 0,
        tier="fast" if u.speed == "fast" else tier,
        geo=u.inference_geo,
        web_searches=u.server_tool_use.web_search_requests if u.server_tool_use else 0,
    )


def from_gemini(resp: gtypes.GenerateContentResponse, model: str, *, batch: bool = False,
                service_tier: str | None = None) -> Usage:
    """`service_tier`: the `x-gemini-service-tier` response header (`resp.sdk_http_response.headers`).
    `usage_metadata.traffic_type` is documented as not supported on the Gemini Developer API."""
    u = resp.usage_metadata
    if u is None:
        raise ValueError("response has no usage_metadata: record it as unknown")
    prompt = u.prompt_token_count or 0            # INCLUDES cached tokens when cached_content is set
    cached = u.cached_content_token_count or 0
    tool_prompt = u.tool_use_prompt_token_count or 0
    thoughts = u.thoughts_token_count or 0        # NOT inside candidates_token_count: add it
    traffic = u.traffic_type.name if u.traffic_type else ""
    if service_tier is not None:
        tier = _GEMINI_TIERS.get(service_tier.lower())
    else:
        tier = _GEMINI_TRAFFIC.get(traffic)
    if tier is None:
        raise ValueError(f"no per-token price for Gemini traffic type / tier {service_tier or traffic!r}")
    queries = sum(len(c.grounding_metadata.web_search_queries or [])
                  for c in resp.candidates or [] if c.grounding_metadata)
    return Usage(
        provider="gemini", model=model,
        input=prompt - cached + tool_prompt, cached_input=cached,
        output=(u.candidates_token_count or 0) + thoughts, reasoning=thoughts,
        tier="batch" if batch else tier, grounding_searches=queries,
        modality_input=_uncached_by_modality(u),
    )


def _uncached_by_modality(u: gtypes.GenerateContentResponseUsageMetadata) -> dict[str, int]:
    """Uncached prompt tokens per NON-text modality, e.g. {"audio": 4000}. Priced only if the price
    table has an `input_<modality>` rate; otherwise they stay at the text rate (see price())."""
    cached = {(d.modality.name if d.modality else ""): d.token_count or 0 for d in u.cache_tokens_details or []}
    out: dict[str, int] = {}
    for d in u.prompt_tokens_details or []:
        name = d.modality.name if d.modality else ""
        n = (d.token_count or 0) - cached.get(name, 0)
        if name and name != "TEXT" and n > 0:
            out[name.lower()] = n
    return out


def from_gemini_interaction(obj: Any, model: str | None = None, *, total_includes_cached: bool = True,
                            service_tier: str | None = None) -> Usage:
    """Interactions API naming. `obj` is an `Interaction` (its usage, model and service_tier are read)
    or just its `usage`. Google doesn't document whether `total_input_tokens` includes the cached part;
    this assumes it does, as prompt_token_count does. If cached > total, it plainly can't, and the cached
    tokens are treated as separate. Pass total_includes_cached=False once a real response proves it."""
    usage = getattr(obj, "usage", obj)
    if usage is None:
        raise ValueError("interaction has no usage (an Interactions stream?): record it as unknown")
    model = model or getattr(obj, "model", None)
    if not model:
        raise ValueError("no model name: pass model=")
    service_tier = service_tier or getattr(obj, "service_tier", None)
    tier = {"standard": "standard", "flex": "flex", "priority": "priority"}.get(service_tier or "standard")
    if tier is None:
        raise ValueError(f"no per-token price for Interactions service_tier {service_tier!r}")
    total, cached = usage.total_input_tokens or 0, usage.total_cached_tokens or 0
    includes = total_includes_cached and cached <= total
    thoughts = usage.total_thought_tokens or 0          # separate from total_output_tokens here too
    grounding = sum(g.count or 0 for g in usage.grounding_tool_count or [] if g.type == "google_search")
    return Usage(provider="gemini", model=model,
                 input=(total - cached if includes else total) + (usage.total_tool_use_tokens or 0),
                 cached_input=cached, output=(usage.total_output_tokens or 0) + thoughts,
                 reasoning=thoughts, tier=tier, grounding_searches=grounding)


def from_openai_chat(completion: ChatCompletion, *, batch: bool = False, regional: bool = False) -> Usage:
    """OpenAI Chat Completions: same rules as Responses, different field names."""
    u = completion.usage
    if u is None:
        raise ValueError("no usage in response (streaming without include_usage?)")
    p, c = u.prompt_tokens_details, u.completion_tokens_details
    cached = (p.cached_tokens if p else 0) or 0
    written = (p.cache_write_tokens if p else 0) or 0
    return Usage(provider="openai", model=completion.model, input=u.prompt_tokens - cached - written,
                 cached_input=cached, cache_writes=_openai_writes(p, written),
                 output=u.completion_tokens, reasoning=(c.reasoning_tokens if c else 0) or 0,
                 tier="batch" if batch else _openai_tier(completion.service_tier), regional=regional)


def from_openrouter(completion: ChatCompletion) -> Usage:
    """OpenRouter Chat Completions. `prompt_tokens` includes cached and written tokens, like OpenAI's."""
    u = completion.usage
    if u is None:
        raise ValueError("no usage in response")
    extra = u.model_extra or {}                   # cost, cost_details, is_byok: OpenRouter-only fields
    p, c = u.prompt_tokens_details, u.completion_tokens_details
    cached = (p.cached_tokens if p else 0) or 0
    written = (p.cache_write_tokens if p else 0) or 0
    return Usage(
        provider="openrouter", model=completion.model,
        input=u.prompt_tokens - cached - written, cached_input=cached,
        cache_writes={"default": written} if written else {},
        output=u.completion_tokens, reasoning=(c.reasoning_tokens if c else 0) or 0,
        reported_cost=extra.get("cost"),
    )


def from_openrouter_response(resp: Response) -> Usage:
    """OpenRouter's Responses-compatible API (stateless): `input_tokens` includes cached and written
    tokens, and the OpenRouter-only `cost` arrives in usage.model_extra, as on Chat Completions."""
    u = resp.usage
    if u is None:
        raise ValueError("no usage in response")
    cached = u.input_tokens_details.cached_tokens or 0
    written = u.input_tokens_details.cache_write_tokens or 0
    return Usage(
        provider="openrouter", model=resp.model,
        input=u.input_tokens - cached - written, cached_input=cached,
        cache_writes={"default": written} if written else {},
        output=u.output_tokens, reasoning=u.output_tokens_details.reasoning_tokens or 0,
        reported_cost=(u.model_extra or {}).get("cost"),
    )


# ---------- pricing: Usage -> line items -> cost ----------

@dataclass
class LineItem:
    name: str
    tokens: int
    usd_per_m: float

    @property
    def usd(self) -> float:
        return self.tokens * self.usd_per_m / 1_000_000


@dataclass
class Cost:
    usd: float
    items: list[LineItem]
    notes: list[str]


def price(usage: Usage, table: PriceTable, on: dt.date | None = None) -> Cost:
    on = on or dt.date.today()
    spec = table.model(usage.provider, usage.model)
    if spec.use_reported_cost:
        if usage.reported_cost is None:
            raise ValueError("OpenRouter response without usage.cost: fetch /api/v1/generation")
        return Cost(usage.reported_cost, [], ["provider-reported cost (already includes discounts)"])

    period = table.period(usage.provider, usage.model, on)
    rates, notes = period.rates, []
    if usage.tier == "fast" and period.fast_rates:           # Anthropic fast mode: its own price list
        rates, notes = period.fast_rates, ["fast-mode rates"]
    if period.long_context and usage.total_input > period.long_context.above_input_tokens:
        rates = period.long_context.rates                      # the WHOLE request moves up
        notes.append(f"long-context rates (> {period.long_context.above_input_tokens:,} input tokens)")

    multiplier = 1.0
    own_fast_rates = usage.tier == "fast" and period.fast_rates
    if usage.tier != "standard" and not own_fast_rates:
        if usage.tier not in spec.tiers:                       # unknown is an error, not "standard"
            raise KeyError(f"{usage.provider}/{usage.model} has no '{usage.tier}' tier in the table")
        multiplier *= spec.tiers[usage.tier]
        notes.append(f"{usage.tier} tier x{spec.tiers[usage.tier]}")
    if usage.geo and usage.geo in spec.geo_multipliers:
        multiplier *= spec.geo_multipliers[usage.geo]
        notes.append(f"inference_geo {usage.geo} x{spec.geo_multipliers[usage.geo]}")
    if usage.regional and spec.regional_uplift:
        multiplier *= 1 + spec.regional_uplift
        notes.append(f"regional processing +{spec.regional_uplift:.0%}")

    def rate(name: str) -> float:
        if name not in rates:
            raise KeyError(f"{usage.provider}/{usage.model} has no '{name}' rate in the table")
        return rates[name] * multiplier

    text_input = usage.input
    items: list[LineItem] = []
    for modality, n in usage.modality_input.items():          # e.g. audio, if the table has input_audio
        if f"input_{modality}" in rates:
            items.append(LineItem(f"input_{modality}", n, rate(f"input_{modality}")))
            text_input -= n
        else:
            notes.append(f"{modality} input tokens priced at the text rate (no input_{modality} rate)")
    items = [LineItem("input", text_input, rate("input")),
             LineItem("cached_input", usage.cached_input, rate("cached_input") if usage.cached_input else 0.0),
             LineItem("output", usage.output, rate("output"))] + items
    items += [LineItem(f"cache_write_{ttl}", n, rate(f"cache_write_{ttl}"))
              for ttl, n in usage.cache_writes.items()]
    total = sum(i.usd for i in items)
    if usage.web_searches:
        total += usage.web_searches * spec.web_search_per_1000 / 1000
        notes.append(f"{usage.web_searches} web search(es)")
    if usage.grounding_searches:        # list price: the 5,000 free queries a month are NOT modelled
        total += usage.grounding_searches * spec.grounding_per_1000 / 1000
        notes.append(f"{usage.grounding_searches} grounding quer(ies) at list price")
    return Cost(total, items, notes)


def storage_cost(provider: str, model: str, tokens: int, start: dt.datetime, end: dt.datetime,
                 table: PriceTable) -> float:
    """What a Gemini explicit cache cost to KEEP: tokens x hours alive x the storage rate. It is in no
    response's usage. Splits the lifetime across price periods (a cache that spans 1 Jan 2027 pays
    two rates); period boundaries are taken as midnight UTC."""
    total = 0.0
    for p in table.model(provider, model).periods:
        p_start = dt.datetime.combine(p.start, dt.time.min, tzinfo=dt.timezone.utc)
        p_end = (dt.datetime.combine(p.end, dt.time.min, tzinfo=dt.timezone.utc) + dt.timedelta(days=1)
                 if p.end else dt.datetime.max.replace(tzinfo=dt.timezone.utc))
        lo, hi = max(start, p_start), min(end, p_end)
        if hi > lo:
            if "cache_storage_per_hour" not in p.rates:
                raise KeyError(f"{provider}/{model} has no cache_storage_per_hour rate in the table")
            total += tokens / 1_000_000 * (hi - lo).total_seconds() / 3600 * p.rates["cache_storage_per_hour"]
    return total


def describe(cost: Cost) -> str:
    lines = [f"  {i.name:16s} {i.tokens:>9,} x ${i.usd_per_m:<8g}/M = ${i.usd:.6f}"
             for i in cost.items if i.tokens]
    lines.append(f"  {'TOTAL':16s} ${cost.usd:.6f}" + (f"   ({'; '.join(cost.notes)})" if cost.notes else ""))
    return "\n".join(lines)

Design choices worth copying:

  • One bucket per token. Every normalizer subtracts overlaps (OpenAI's cached and written tokens out of input_tokens, Gemini's cached tokens out of prompt_token_count) and adds what's reported separately (Gemini's thoughts and tool results). After that, pricing is the same for every provider.
  • The tier comes from the response. from_openai_usage reads the tier that served the request; from_anthropic reads usage.speed, service_tier and inference_geo. What you asked for is only a hint. from_gemini reads the x-gemini-service-tier header you pass it. What no response says (a batch job, a regional endpoint) comes from your code: the tracker takes it as an argument (5.8).
  • Unknown is an error, not zero. A model missing from the table, a rate missing for a line item, a tier or traffic type with no price, a response without usage: all raise, and the tracker in Part 5 records "unknown" instead of $0.
  • reasoning is kept, but not billed twice. It's inside output already. Keeping it separately lets you see what thinking costs per feature.

Now price some real-shaped usage objects, built with the SDKs' own Pydantic types and filled with the providers' documented example values. No network. Save as s3_cost_examples.py:

python
"""Price real-shaped usage objects, built with the SDKs' own types (no network)."""
import datetime as dt

from anthropic.types import Message
from google.genai import types as gtypes
from openai.types.chat import ChatCompletion
from openai.types.responses import ResponseUsage

from cost_calc import describe, from_anthropic, from_gemini, from_openai_usage, from_openrouter, price
from prices import PriceTable

table = PriceTable.load("prices.yaml")
DAY = dt.date(2026, 11, 4)

# 1. OpenAI: the usage example from OpenAI's prompt-caching guide (12,000 input tokens:
#    4,000 cache reads, 7,000 cache writes split 3,000 at 30m and 4,000 at 12h)
openai_usage = ResponseUsage.model_validate({
    "input_tokens": 12_000,
    "input_tokens_details": {"cached_tokens": 4_000, "cache_write_tokens": 7_000,
                             "cache_write_tokens_details": {"ttl_30m_tokens": 3_000, "ttl_12h_tokens": 4_000}},
    "output_tokens": 900, "output_tokens_details": {"reasoning_tokens": 600},
    "total_tokens": 12_900,
})
print("OpenAI gpt-6.1-sol, served on service_tier='default':")
print(describe(price(from_openai_usage(openai_usage, "gpt-6.1-sol", "default"), table, DAY)))
print("Same usage, but the response says service_tier='priority' (Fast mode):")
print(describe(price(from_openai_usage(openai_usage, "gpt-6.1-sol", "priority"), table, DAY)))


def claude(model: str, **usage) -> Message:
    return Message.model_validate({"id": "msg_x", "type": "message", "role": "assistant", "model": model,
                                   "content": [], "stop_reason": "end_turn", "usage": usage})


# 2. Anthropic: the worked example on Anthropic's pricing page (Opus 5.5, 50,000 input tokens of
#    which 40,000 are cache reads, 15,000 output tokens; the page adds $0.08 session runtime on top)
print("\nAnthropic claude-opus-5-5, the pricing page's cached example:")
print(describe(price(from_anthropic(claude("claude-opus-5-5", input_tokens=10_000,
                     cache_read_input_tokens=40_000, cache_creation_input_tokens=0,
                     output_tokens=15_000)), table, DAY)))

# claude-fable-5-2 was released on 9 November 2026, so its price period starts then: price it on a later day
print("Anthropic claude-fable-5-2: cache reads cost 0.025x input ($0.20 per million, against Opus 5.5's 0.05x):")
print(describe(price(from_anthropic(claude("claude-fable-5-2", input_tokens=2_000,
                     cache_read_input_tokens=50_000, cache_creation_input_tokens=0,
                     output_tokens=1_000)), table, dt.date(2026, 11, 11))))

print("Anthropic claude-haiku-5-5, 2,000 new tokens + 110,000 cache reads (crosses 100K):")
print(describe(price(from_anthropic(claude("claude-haiku-5-5", input_tokens=2_000,
                     cache_read_input_tokens=110_000, cache_creation_input_tokens=0,
                     output_tokens=800)), table, DAY)))

print("Anthropic claude-sonnet-5-5, 1h + 5m writes, inference_geo='us', one web search:")
print(describe(price(from_anthropic(claude("claude-sonnet-5-5", input_tokens=40,
                     cache_creation_input_tokens=9_000, cache_read_input_tokens=0,
                     cache_creation={"ephemeral_1h_input_tokens": 6_000, "ephemeral_5m_input_tokens": 3_000},
                     inference_geo="us", server_tool_use={"web_search_requests": 1, "web_fetch_requests": 0},
                     output_tokens=500)), table, DAY)))

# 3. Gemini: thinking tokens are reported OUTSIDE candidates_token_count
gem = gtypes.GenerateContentResponse(usage_metadata=gtypes.GenerateContentResponseUsageMetadata(
    prompt_token_count=5_000, cached_content_token_count=4_000,   # prompt INCLUDES the cached part
    candidates_token_count=300, thoughts_token_count=1_200, total_token_count=6_500))
u = from_gemini(gem, "gemini-3.8-flash")
print("\nGemini gemini-3.8-flash (implicit cache hit, thinking on):")
print(describe(price(u, table, DAY)))
u.output -= u.reasoning
print(f"  ...if you forgot thoughts_token_count:  ${price(u, table, DAY).usd:.6f}  (under-billed)")
print("Same request priced on 2027-01-01, after the introductory price ends:")
print(describe(price(from_gemini(gem, "gemini-3.8-flash"), table, dt.date(2027, 1, 1))))

# 4. OpenRouter: usage.cost is what you were charged. Read it; don't re-price it.
orc = ChatCompletion.model_validate({
    "id": "gen-123", "object": "chat.completion", "created": 1793750000,
    "model": "anthropic/claude-haiku-5.5", "choices": [],
    "usage": {"prompt_tokens": 10_339, "completion_tokens": 60, "total_tokens": 10_399,
              "prompt_tokens_details": {"cached_tokens": 10_318, "cache_write_tokens": 0},
              "cost": 0.00013508, "is_byok": False,
              "cost_details": {"upstream_inference_cost": None}},
})
print("\nOpenRouter anthropic/claude-haiku-5.5:")
print(describe(price(from_openrouter(orc), table, DAY)))
Output51 lines
OpenAI gpt-6.1-sol, served on service_tier='default':
  input                1,000 x $2       /M = $0.002000
  cached_input         4,000 x $0.1     /M = $0.000400
  output                 900 x $10      /M = $0.009000
  cache_write_30m      3,000 x $2.5     /M = $0.007500
  cache_write_12h      4,000 x $5       /M = $0.020000
  TOTAL            $0.038900
Same usage, but the response says service_tier='priority' (Fast mode):
  input                1,000 x $4       /M = $0.004000
  cached_input         4,000 x $0.2     /M = $0.000800
  output                 900 x $20      /M = $0.018000
  cache_write_30m      3,000 x $5       /M = $0.015000
  cache_write_12h      4,000 x $10      /M = $0.040000
  TOTAL            $0.077800   (fast tier x2.0)

Anthropic claude-opus-5-5, the pricing page's cached example:
  input               10,000 x $4       /M = $0.040000
  cached_input        40,000 x $0.2     /M = $0.008000
  output              15,000 x $20      /M = $0.300000
  TOTAL            $0.348000
Anthropic claude-fable-5-2: cache reads cost 0.025x input ($0.20 per million, against Opus 5.5's 0.05x):
  input                2,000 x $8       /M = $0.016000
  cached_input        50,000 x $0.2     /M = $0.010000
  output               1,000 x $40      /M = $0.040000
  TOTAL            $0.066000
Anthropic claude-haiku-5-5, 2,000 new tokens + 110,000 cache reads (crosses 100K):
  input                2,000 x $0.5     /M = $0.001000
  cached_input       110,000 x $0.05    /M = $0.005500
  output                 800 x $2.5     /M = $0.002000
  TOTAL            $0.008500   (long-context rates (> 100,000 input tokens))
Anthropic claude-sonnet-5-5, 1h + 5m writes, inference_geo='us', one web search:
  input                   40 x $2.2     /M = $0.000088
  output                 500 x $11      /M = $0.005500
  cache_write_5m       3,000 x $2.75    /M = $0.008250
  cache_write_1h       6,000 x $4.4     /M = $0.026400
  TOTAL            $0.050238   (inference_geo us x1.1; 1 web search(es))

Gemini gemini-3.8-flash (implicit cache hit, thinking on):
  input                1,000 x $0.75    /M = $0.000750
  cached_input         4,000 x $0.075   /M = $0.000300
  output               1,500 x $3.75    /M = $0.005625
  TOTAL            $0.006675
  ...if you forgot thoughts_token_count:  $0.002175  (under-billed)
Same request priced on 2027-01-01, after the introductory price ends:
  input                1,000 x $1.5     /M = $0.001500
  cached_input         4,000 x $0.15    /M = $0.000600
  output               1,500 x $7.5     /M = $0.011250
  TOTAL            $0.013350

OpenRouter anthropic/claude-haiku-5.5:
  TOTAL            $0.000135   (provider-reported cost (already includes discounts))

Read the numbers:

  • OpenAI: the 1,000 ordinary input tokens are what's left of 12,000 after taking out 4,000 reads and 7,000 writes. The 4,000 twelve-hour writes cost more than everything else combined: a long lifetime is a bet that the prefix will be reused.
  • Fast mode doubled the call. The only difference between the two OpenAI blocks is the service_tier the response reported. If your code had requested fast but logged only what it requested, it would be wrong whenever OpenAI fell back to default, in either direction.
  • Anthropic's worked example matches the pricing page: $0.04 + $0.008 + $0.30 = $0.348 in tokens (the page adds $0.08 of Managed Agents session runtime for its $0.428 total).
  • Fable's cache reads are a fortieth of its input price (0.025×, on Fable 5.2 and on the legacy Fable 5.1): 50,000 tokens read cost $0.01, while the 2,000 uncached tokens next to them cost more ($0.016). On Opus 5.5 the same read would be at 0.05×. This call is priced on 11 November 2026 because the Fable 5.2 row's period starts on its release date, 9 November: on DAY (4 November) price() would raise KeyError: no anthropic/claude-fable-5-2 prices in force on 2026-11-04.
  • The Haiku request crossed 100,000 tokens only because of its cache reads, and the whole request moved to the higher rates, cache reads included.
  • The 1.1× US-inference multiplier applied to every token line, but not to the web search fee.
  • Forgetting Gemini's thinking tokens under-billed the request by two thirds.
  • The same Gemini usage costs twice as much on 1 January 2027. Nothing in the response changed; the date did.

3.7 Test it against the providers' worked examples#

A cost calculator is business logic that moves money. Test it, preferably against numbers the providers themselves published, so a test failure means your code is wrong, not your arithmetic in the test. Save as test_cost_calc.py. Beyond the providers' worked examples it pins the rules that were easiest to get wrong: Fable's 0.025× reads, an unrecognized tier raising, Gemini's tier header, BetaMessage parsing, a non-zero cached count on Interactions (under both readings of the field), grounding, per-modality pricing and storage that spans a price change:

python
"""Check cost_calc against the providers' own worked examples. Run: pytest -q test_cost_calc.py"""
import datetime as dt

import pytest
from anthropic.types import Message
from anthropic.types.beta import BetaMessage
from google.genai import types as gtypes
from openai.types.responses import ResponseUsage

from cost_calc import (Usage, from_anthropic, from_gemini, from_gemini_interaction, from_openai_usage,
                       price, storage_cost)
from prices import PriceTable

table = PriceTable.load("prices.yaml")
DAY = dt.date(2026, 11, 4)


def claude(model: str, **usage) -> Message:
    return Message.model_validate({"id": "m", "type": "message", "role": "assistant", "model": model,
                                   "content": [], "stop_reason": "end_turn", "usage": usage})


def test_anthropic_pricing_page_worked_example():
    # Anthropic pricing page: Opus 5.5, 10,000 uncached + 40,000 cache reads + 15,000 output
    # = $0.04 + $0.008 + $0.30 in tokens, plus $0.08 session runtime = $0.428
    msg = claude("claude-opus-5-5", input_tokens=10_000, cache_read_input_tokens=40_000,
                 cache_creation_input_tokens=0, output_tokens=15_000)
    tokens_usd = price(from_anthropic(msg), table, DAY).usd
    assert tokens_usd == pytest.approx(0.348)
    assert tokens_usd + 0.08 == pytest.approx(0.428)


def test_openai_guide_usage_split():
    # OpenAI prompt-caching guide: 12,000 input = 4,000 reads + 7,000 writes + 1,000 ordinary
    u = ResponseUsage.model_validate({
        "input_tokens": 12_000, "output_tokens": 0, "total_tokens": 12_000,
        "input_tokens_details": {"cached_tokens": 4_000, "cache_write_tokens": 7_000,
                                 "cache_write_tokens_details": {"ttl_30m_tokens": 3_000, "ttl_12h_tokens": 4_000}},
        "output_tokens_details": {"reasoning_tokens": 0}})
    usage = from_openai_usage(u, "gpt-6.1-sol", "default")
    assert usage.input == 1_000
    assert usage.cache_writes == {"30m": 3_000, "12h": 4_000}


def test_anthropic_5m_cache_pays_off_after_one_read():
    # "caching pays off after one cache read for the 5-minute duration (1.25x write)"
    prefix = 100_000
    cold = Usage("anthropic", "claude-sonnet-5-5", input=prefix)
    write = Usage("anthropic", "claude-sonnet-5-5", cache_writes={"5m": prefix})
    read = Usage("anthropic", "claude-sonnet-5-5", cached_input=prefix)
    two_uncached = 2 * price(cold, table, DAY).usd
    write_then_read = price(write, table, DAY).usd + price(read, table, DAY).usd
    assert write_then_read < two_uncached


def test_long_context_applies_to_the_whole_request():
    small = Usage("openai", "gpt-6-luna", input=272_000, output=1_000)
    large = Usage("openai", "gpt-6-luna", input=272_001, output=1_000)
    assert price(small, table, DAY).usd == pytest.approx((272_000 * 0.10 + 1_000 * 0.50) / 1e6)
    assert price(large, table, DAY).usd == pytest.approx((272_001 * 0.20 + 1_000 * 0.75) / 1e6)


def test_haiku_threshold_counts_cache_reads():
    # "A request's prompt length counts all of its input tokens, including cache reads and cache writes"
    u = Usage("anthropic", "claude-haiku-5-5", input=1_000, cached_input=100_000)
    assert price(u, table, DAY).items[0].usd_per_m == 0.50


def test_batch_halves_and_stacks_with_caching():
    u = Usage("anthropic", "claude-sonnet-5-5", input=1_000_000, cached_input=1_000_000, tier="batch")
    assert price(u, table, DAY).usd == pytest.approx(1.00 + 0.05)


def test_introductory_price_ends():
    u = Usage("gemini", "gemini-4-argon", input=1_000_000)
    assert price(u, table, dt.date(2026, 11, 30)).usd == pytest.approx(2.00)
    assert price(u, table, dt.date(2026, 12, 1)).usd == pytest.approx(4.00)


def test_unknown_model_fails_loudly():
    with pytest.raises(KeyError):
        price(Usage("openai", "gpt-9-nova", input=10), table, DAY)


def test_gemini_interactions_example_adds_thoughts():
    # Google's streaming example: total_tokens 346 = 11 input + 90 output + 245 thought tokens
    from types import SimpleNamespace
    from cost_calc import from_gemini_interaction
    u = from_gemini_interaction(SimpleNamespace(
        total_tokens=346, total_input_tokens=11, total_cached_tokens=0, total_output_tokens=90,
        total_tool_use_tokens=0, total_thought_tokens=245, grounding_tool_count=None), "gemini-3.8-flash")
    assert u.input + u.cached_input + u.output == 346
    assert u.output == 335            # 90 visible + 245 thinking, all billed at the output rate


def test_fable_reads_cost_a_fortieth_of_input():
    # Pricing page footnote 1: cache hits on Claude Fable 5.2 and 5.1 are 0.025x the base input price
    u = Usage("anthropic", "claude-fable-5-1", cached_input=1_000_000)
    assert price(u, table, DAY).usd == pytest.approx(0.25)          # $10 x 0.025
    u2 = Usage("anthropic", "claude-fable-5-2", cached_input=1_000_000)
    assert price(u2, table, dt.date(2026, 11, 11)).usd == pytest.approx(0.20)   # $8 x 0.025 (released 9 Nov)
    assert price(Usage("anthropic", "claude-opus-5-5", cached_input=1_000_000), table, DAY).usd == pytest.approx(0.20)


def test_terra_reads_and_12h_writes():
    # gpt-6.1-terra: $1.00 input, $0.05 cached (0.05x), $2.50 12-hour writes (2.5x)
    u = Usage("openai", "gpt-6.1-terra", cached_input=200_000, cache_writes={"12h": 50_000})
    assert price(u, table, DAY).usd == pytest.approx(0.2 * 0.05 + 0.05 * 2.50)


def test_unrecognized_tiers_are_errors_not_standard():
    # Unknown is an error, not zero: neither an unrecognized OpenAI tier nor a tier the table lacks
    u = ResponseUsage.model_validate({"input_tokens": 10, "output_tokens": 1, "total_tokens": 11,
        "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0}, "output_tokens_details": {"reasoning_tokens": 0}})
    with pytest.raises(ValueError):
        from_openai_usage(u, "gpt-6-luna", "turbo")
    with pytest.raises(KeyError):                                  # luna has no ultrafast price
        price(Usage("openai", "gpt-6-luna", input=10, tier="ultrafast"), table, DAY)


def test_gemini_traffic_types_without_a_per_token_price_raise():
    resp = gtypes.GenerateContentResponse(usage_metadata=gtypes.GenerateContentResponseUsageMetadata(
        prompt_token_count=10, candidates_token_count=5, traffic_type=gtypes.TrafficType.PROVISIONED_THROUGHPUT))
    with pytest.raises(ValueError):
        from_gemini(resp, "gemini-3.8-flash")


def test_gemini_service_tier_header_beats_the_missing_traffic_type():
    # On the Developer API traffic_type isn't filled in: the x-gemini-service-tier header is the signal
    resp = gtypes.GenerateContentResponse(usage_metadata=gtypes.GenerateContentResponseUsageMetadata(
        prompt_token_count=1_000_000, candidates_token_count=0))
    usage = from_gemini(resp, "gemini-3.8-flash", service_tier="priority")
    assert price(usage, table, DAY).usd == pytest.approx(0.75 * 1.8)


def test_beta_message_is_read_like_message():
    beta = BetaMessage.model_validate({"id": "m", "type": "message", "role": "assistant",
        "model": "claude-sonnet-5-5", "content": [], "stop_reason": "end_turn",
        "usage": {"input_tokens": 10, "output_tokens": 5, "cache_read_input_tokens": 100,
                  "cache_creation_input_tokens": 0}})
    assert from_anthropic(beta).cached_input == 100


def test_interactions_cached_tokens_inside_total_input():
    # Assumption (documented): total_input_tokens includes total_cached_tokens, like prompt_token_count
    from types import SimpleNamespace
    usage = SimpleNamespace(total_input_tokens=5_000, total_cached_tokens=4_000, total_output_tokens=300,
                            total_thought_tokens=1_200, total_tool_use_tokens=0, grounding_tool_count=None)
    u = from_gemini_interaction(usage, "gemini-3.8-flash")
    assert (u.input, u.cached_input, u.output) == (1_000, 4_000, 1_500)
    # ...and if a real response proves the opposite, say so; cached > total can only mean "separate"
    assert from_gemini_interaction(usage, "gemini-3.8-flash", total_includes_cached=False).input == 5_000
    odd = SimpleNamespace(**{**vars(usage), "total_input_tokens": 1_000})
    assert from_gemini_interaction(odd, "gemini-3.8-flash").input == 1_000


def test_grounding_is_priced_per_query():
    u = Usage("gemini", "gemini-3.8-flash", grounding_searches=1_000)
    assert price(u, table, DAY).usd == pytest.approx(14.0)


def test_audio_is_priced_only_when_the_table_has_a_rate():
    usage = Usage("gemini", "gemini-3.8-flash", input=1_000_000, modality_input={"audio": 400_000})
    assert price(usage, table, DAY).usd == pytest.approx(0.75)           # no input_audio rate: text rate
    assert any("audio" in n for n in price(usage, table, DAY).notes)      # ...and it says so
    custom = PriceTable({"version": "t", "gemini": {"m": {"source": "test", "periods": [
        {"from": "2026-01-01", "rates": {"input": 1.0, "input_audio": 3.0, "cached_input": 0.1, "output": 2.0}}]}}})
    assert price(Usage("gemini", "m", input=1_000_000, modality_input={"audio": 400_000}),
                 custom, DAY).usd == pytest.approx(0.6 * 1.0 + 0.4 * 3.0)


def test_storage_cost_splits_across_the_price_change():
    # 200,000 tokens held from 2026-12-31 20:00 to 2027-01-01 04:00 UTC: 4 h at $0.50, 4 h at $1.00 per M per hour
    utc = dt.timezone.utc
    cost = storage_cost("gemini", "gemini-3.8-flash", 200_000, dt.datetime(2026, 12, 31, 20, tzinfo=utc),
                        dt.datetime(2027, 1, 1, 4, tzinfo=utc), table)
    assert cost == pytest.approx(0.2 * 4 * 0.50 + 0.2 * 4 * 1.00)


def test_openai_chat_12h_writes_are_read_from_the_split():
    from openai.types.chat import ChatCompletion
    from cost_calc import from_openai_chat
    c = ChatCompletion.model_validate({"id": "c", "object": "chat.completion", "created": 1, "model": "gpt-6.1-sol",
        "choices": [], "usage": {"prompt_tokens": 12_000, "completion_tokens": 10, "total_tokens": 12_010,
        "prompt_tokens_details": {"cached_tokens": 4_000, "cache_write_tokens": 7_000,
            "cache_write_tokens_details": {"ttl_30m_tokens": 3_000, "ttl_12h_tokens": 4_000}}}})
    assert from_openai_chat(c).cache_writes == {"30m": 3_000, "12h": 4_000}

Run it with uv run pytest -q test_cost_calc.py.

Output · the SDKs' own types, no network; the timing will differ2 lines
....................                                                     [100%]
20 passed in 0.89s

When a provider changes a rule (a new lifetime, a new threshold, a new usage field), add the example from its documentation as a test first, then change the code until it passes.

3.8 See the SDK parse it (mocked)#

Two claims in this part are about the SDKs, not the APIs: that openai 3.42.1 keeps the undeclared cache_write_tokens_details in model_extra, and that anthropic 2.4.0 parses cache_creation, service_tier, inference_geo, speed and the cache diagnostics into typed fields. This sample checks both with the real SDKs and a mock server: an httpx2.MockTransport that answers every request with a fixture shaped like the documented response (lesson 03.10 covers mock transports). Nothing leaves your machine. Save as s3_mock_usage.py:

python
"""See how the real openai and anthropic SDKs parse usage fields, using a mock server (no key)."""
import json

import anthropic
import httpx2
from openai import OpenAI

# Fixture shaped like OpenAI's documented Responses object. The server here is a mock.
OPENAI_BODY = {
    "id": "resp_123", "object": "response", "created_at": 1793750000, "status": "completed",
    "model": "gpt-6.1-sol", "service_tier": "default",      # asked for "fast", served on "default"
    "output": [{"type": "message", "id": "msg_1", "role": "assistant", "status": "completed",
                "content": [{"type": "output_text", "text": "Done.", "annotations": []}]}],
    "parallel_tool_calls": True, "tool_choice": "auto", "tools": [],
    "usage": {"input_tokens": 12000, "output_tokens": 900, "total_tokens": 12900,
              "input_tokens_details": {"cached_tokens": 4000, "cache_write_tokens": 7000,
                                       "cache_write_tokens_details": {"ttl_30m_tokens": 3000,
                                                                      "ttl_12h_tokens": 4000}},
              "output_tokens_details": {"reasoning_tokens": 600}},
}

ANTHROPIC_BODY = {
    "id": "msg_01", "type": "message", "role": "assistant", "model": "claude-sonnet-5-5",
    "content": [{"type": "text", "text": "Done."}], "stop_reason": "end_turn", "stop_sequence": None,
    "usage": {"input_tokens": 42, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 41850,
              "cache_creation": {"ephemeral_5m_input_tokens": 41850, "ephemeral_1h_input_tokens": 0},
              "output_tokens": 210, "service_tier": "standard", "inference_geo": "global",
              "speed": "standard"},
    "diagnostics": {"cache_miss_reason": {"type": "system_changed", "cache_missed_input_tokens": 41850}},
}


def mock(body: dict) -> httpx2.Client:
    return httpx2.Client(transport=httpx2.MockTransport(
        lambda request: httpx2.Response(200, json=body)))


oai = OpenAI(api_key="sk-test", http_client=mock(OPENAI_BODY))
resp = oai.responses.create(model="gpt-6.1-sol", input="hi", service_tier="fast")
d = resp.usage.input_tokens_details if resp.usage else None
print("OpenAI served tier:      ", resp.service_tier)
print("cache_write_tokens:      ", d.cache_write_tokens if d else None)
print("declared in the SDK type?", d is not None and "cache_write_tokens_details" in type(d).model_fields)
print("model_extra:             ", json.dumps(d.model_extra if d else None))

claude = anthropic.Anthropic(api_key="sk-test", http_client=mock(ANTHROPIC_BODY))
msg = claude.messages.create(model="claude-sonnet-5-5", max_tokens=300,
                             messages=[{"role": "user", "content": "hi"}])
u = msg.usage
total_in = u.input_tokens + (u.cache_creation_input_tokens or 0) + (u.cache_read_input_tokens or 0)
print("\nAnthropic input_tokens:  ", u.input_tokens, "<- only what came after the last breakpoint")
print("total input:             ", total_in)
print("cache_creation:          ", u.cache_creation)
print("tier / geo / speed:      ", u.service_tier, u.inference_geo, u.speed)
print("diagnostics:             ", msg.diagnostics)
Output10 lines
OpenAI served tier:       default
cache_write_tokens:       7000
declared in the SDK type? False
model_extra:              {"cache_write_tokens_details": {"ttl_30m_tokens": 3000, "ttl_12h_tokens": 4000}}

Anthropic input_tokens:   42 <- only what came after the last breakpoint
total input:              41892
cache_creation:           CacheCreation(ephemeral_1h_input_tokens=0, ephemeral_5m_input_tokens=41850)
tier / geo / speed:       standard global standard
diagnostics:              Diagnostics(cache_miss_reason=CacheMissSystemChanged(cache_missed_input_tokens=41850, type='system_changed'))

Three things to notice. The request asked for service_tier="fast", and the (mocked) response says default: read the response, as 3.2 said. The TTL split is present but not declared, so typed code must reach into model_extra. And Anthropic's input_tokens is 42 out of 41,892 total input tokens: a dashboard built on input_tokens alone would under-report this request a thousandfold.


Part 4: The price table as configuration#

Deep-dive

4.1 Why prices don't belong in code#

02.9, 6.13 made the point with a cost model that takes prices as parameters, and 6.8 showed why: prices change, sometimes on a published date. In an application, "prices as parameters" means a price table as configuration:

  • Prices live in one file (or one database table), never as constants inside business logic. A price change is a reviewed data change, not a code change scattered across modules.
  • Every price has a period. Rows say "from this date, to that date". Introductory prices end (Gemini 4 Argon on 30 November 2026, Gemini 3.8 Flash on 31 December 2026), and a table without dates is silently wrong the next morning.
  • Old periods stay. You'll re-price old logs (to fix a bug, or to compare months); you need the prices that applied then.
  • Every model has a source. The URL a human checked, so the next reviewer knows where to look.
  • A missing price fails loudly. A new model shipped to production without a price row should produce an alert, not a silent $0.

4.2 The table: prices.yaml#

YAML keeps it readable for reviewers. Every line item from Part 3 has a rate; tiers, regional uplifts and geography are multipliers; long-context steps and Anthropic's fast mode are separate rate sets, because the providers publish them as separate price lists. Save as prices.yaml:

yaml
# prices.yaml: list prices in USD per 1M tokens, keyed by provider and model.
# Copied from the official pricing pages on 2026-11-04, plus the claude-fable-5-2 row (released 9 November),
# added on 2026-11-11 from the same Anthropic page. Prices change: re-check the
# `source` page before you rely on a number, and add a new period instead of editing an old one.
#
# Line items (all USD per 1M tokens):
#   input          uncached input tokens
#   cached_input   cache reads (OpenAI "cached input", Anthropic "cache hits", Gemini "context caching")
#   cache_write_*  cache writes, one rate per lifetime (Anthropic 5m/1h, OpenAI 30m/12h)
#   output         output tokens, including reasoning/thinking tokens
#   cache_storage_per_hour   Gemini explicit caches only (USD per 1M tokens per hour); used by storage_cost()
# Model-level keys: tiers (multipliers), geo_multipliers, regional_uplift, web_search_per_1000,
#   grounding_per_1000, min_cacheable_tokens (the smallest prefix the provider caches; absent = not published).
version: 2026-11-04

openai:
  gpt-6-luna:
    source: https://developers.openai.com/api/docs/pricing
    periods:
      - from: 2026-01-01          # first date this table vouches for, not the launch date
        rates: {input: 0.10, cached_input: 0.01, cache_write_30m: 0.125, cache_write_12h: 0.25, output: 0.50}
        long_context:             # "more than 272K input tokens ... for the full request"
          above_input_tokens: 272000
          rates: {input: 0.20, cached_input: 0.02, cache_write_30m: 0.25, cache_write_12h: 0.50, output: 0.75}
    tiers: {batch: 0.5, flex: 0.5, fast: 2.0}
    regional_uplift: 0.10         # data-residency endpoints, models released on/after 2026-03-05
    web_search_per_1000: 10.00
    min_cacheable_tokens: 1024
  gpt-6.1-terra:
    source: https://developers.openai.com/api/docs/pricing
    periods:
      - from: 2026-01-01
        rates: {input: 1.00, cached_input: 0.05, cache_write_30m: 1.25, cache_write_12h: 2.50, output: 5.00}
        long_context:
          above_input_tokens: 272000
          rates: {input: 2.00, cached_input: 0.10, cache_write_30m: 2.50, cache_write_12h: 5.00, output: 7.50}
    tiers: {batch: 0.5, flex: 0.5, fast: 2.0}      # the page lists Ultrafast for astra and sol only
    regional_uplift: 0.10         # assumed, as for luna and sol: the page gives no release date to check
    web_search_per_1000: 10.00
    min_cacheable_tokens: 1024
  gpt-6.1-sol:
    source: https://developers.openai.com/api/docs/pricing
    periods:
      - from: 2026-01-01
        rates: {input: 2.00, cached_input: 0.10, cache_write_30m: 2.50, cache_write_12h: 5.00, output: 10.00}
        long_context:
          above_input_tokens: 272000
          rates: {input: 4.00, cached_input: 0.20, cache_write_30m: 5.00, cache_write_12h: 10.00, output: 15.00}
    tiers: {batch: 0.5, flex: 0.5, fast: 2.0, ultrafast: 6.0}
    regional_uplift: 0.10
    web_search_per_1000: 10.00
    min_cacheable_tokens: 1024
  gpt-6-astra:
    source: https://developers.openai.com/api/docs/pricing
    periods:
      - from: 2026-01-01
        rates: {input: 10.00, cached_input: 1.00, cache_write_30m: 12.50, cache_write_12h: 25.00, output: 50.00}
        long_context:
          above_input_tokens: 272000
          rates: {input: 20.00, cached_input: 2.00, cache_write_30m: 25.00, cache_write_12h: 50.00, output: 75.00}
    tiers: {batch: 0.5, flex: 0.5, fast: 2.0, ultrafast: 6.0}
    regional_uplift: 0.10         # assumed, as for luna and sol: the page gives no release date to check
    web_search_per_1000: 10.00
    min_cacheable_tokens: 1024

anthropic:
  claude-haiku-5-5:
    source: https://platform.claude.com/docs/en/about-claude/pricing
    periods:
      - from: 2026-01-01
        rates: {input: 0.10, cache_write_5m: 0.125, cache_write_1h: 0.20, cached_input: 0.01, output: 0.50}
        long_context:             # prompt length counts input + cache reads + cache writes
          above_input_tokens: 100000
          rates: {input: 0.50, cache_write_5m: 0.625, cache_write_1h: 1.00, cached_input: 0.05, output: 2.50}
    tiers: {batch: 0.5, priority: 1.0}   # Priority Tier: commitment fee billed separately; tokens at list
    geo_multipliers: {us: 1.1}    # inference_geo "us"; "global" is standard
    web_search_per_1000: 10.00
    min_cacheable_tokens: 512
  claude-sonnet-5-5:
    source: https://platform.claude.com/docs/en/about-claude/pricing
    periods:
      - from: 2026-01-01
        rates: {input: 2.00, cache_write_5m: 2.50, cache_write_1h: 4.00, cached_input: 0.10, output: 10.00}
    tiers: {batch: 0.5, priority: 1.0}
    geo_multipliers: {us: 1.1}
    web_search_per_1000: 10.00
    min_cacheable_tokens: 512
  claude-opus-5-5:
    source: https://platform.claude.com/docs/en/about-claude/pricing
    periods:
      - from: 2026-01-01
        rates: {input: 4.00, cache_write_5m: 5.00, cache_write_1h: 8.00, cached_input: 0.20, output: 20.00}
        fast_rates:               # speed "fast": $8 / $40; caching multipliers apply on top
          {input: 8.00, cache_write_5m: 10.00, cache_write_1h: 16.00, cached_input: 0.40, output: 40.00}
    tiers: {batch: 0.5, priority: 1.0}
    geo_multipliers: {us: 1.1}
    web_search_per_1000: 10.00
    min_cacheable_tokens: 512
  claude-fable-5-2:               # released 9 November 2026; row added on 2026-11-11 from the same pricing page
    source: https://platform.claude.com/docs/en/about-claude/pricing
    periods:
      - from: 2026-11-09          # the release date: unlike the rows above, this period has a real start
        # cache reads are 0.025x input on Fable 5.2 and 5.1 (0.1x on most models, 0.05x on Opus/Sonnet 5.5)
        rates: {input: 8.00, cache_write_5m: 10.00, cache_write_1h: 16.00, cached_input: 0.20, output: 40.00}
        fast_rates:               # speed "fast": $16 / $80; caching multipliers apply on top
          {input: 16.00, cache_write_5m: 20.00, cache_write_1h: 32.00, cached_input: 0.40, output: 80.00}
    tiers: {batch: 0.5, priority: 1.0}
    geo_multipliers: {us: 1.1}
    web_search_per_1000: 10.00
    min_cacheable_tokens: 512
  claude-fable-5-1:               # legacy since 9 November 2026, still available: keep the row to re-price old logs
    source: https://platform.claude.com/docs/en/about-claude/pricing
    periods:
      - from: 2026-01-01
        # cache reads are 0.025x input on Fable 5.1 (0.1x on most models, 0.05x on Opus/Sonnet 5.5)
        rates: {input: 10.00, cache_write_5m: 12.50, cache_write_1h: 20.00, cached_input: 0.25, output: 50.00}
    tiers: {batch: 0.5, priority: 1.0}
    geo_multipliers: {us: 1.1}
    web_search_per_1000: 10.00
    min_cacheable_tokens: 512

gemini:
  gemini-3.8-flash:
    source: https://aistudio.google.com/docs/pricing
    periods:
      - from: 2026-01-01          # introductory price "through December 31, 2026"
        to: 2026-12-31
        rates: {input: 0.75, cached_input: 0.075, output: 3.75, cache_storage_per_hour: 0.50}
      - from: 2027-01-01
        rates: {input: 1.50, cached_input: 0.15, output: 7.50, cache_storage_per_hour: 1.00}
    tiers: {batch: 0.5, flex: 0.5, priority: 1.8}
    grounding_per_1000: 14.00     # per search query; 5,000 free a month shared across Gemini 3+ (not modelled)
    min_cacheable_tokens: 4096
  gemini-3.5-flash-lite:
    source: https://aistudio.google.com/docs/pricing
    periods:                      # no end date listed; the caching page gives no minimum for this model
      - from: 2026-01-01
        rates: {input: 0.30, cached_input: 0.03, output: 2.50, cache_storage_per_hour: 1.00}
    tiers: {batch: 0.5, flex: 0.5, priority: 1.8}
    grounding_per_1000: 14.00
  gemini-4-argon:
    source: https://aistudio.google.com/docs/pricing
    periods:
      - from: 2026-10-13
        to: 2026-11-30            # "through November 30, 2026"
        rates: {input: 2.00, cached_input: 0.10, output: 10.00}   # implicit caching only
      - from: 2026-12-01
        rates: {input: 4.00, cached_input: 0.20, output: 20.00}
    tiers: {batch: 0.5, flex: 0.5, priority: 1.8}
    grounding_per_1000: 14.00
    min_cacheable_tokens: 4096

openrouter:
  "*":
    source: https://openrouter.ai/docs/cookbook/administration/usage-accounting
    use_reported_cost: true       # usage.cost is the amount charged; never re-price it

These are list prices from the official pricing pages on 4 November 2026 (OpenAI, Anthropic, Google). Negotiated discounts, credits and committed-use contracts aren't in any public list; if you have them, add them as your own rows with your contract as the source.

The table covers every model this module's samples use: gpt-6-luna, gpt-6.1-terra, gpt-6.1-sol and gpt-6-astra; claude-haiku-5-5, claude-sonnet-5-5, claude-opus-5-5, claude-fable-5-2 and claude-fable-5-1; gemini-3.5-flash-lite, gemini-3.8-flash and gemini-4-argon. Details worth reading in it: Fable 5.2's cache reads are $0.20 (0.025× its $8 input; Fable 5.1's are $0.25 on $10, and its row stays so old logs can be re-priced), the Fable 5.2 period starts on its release date, 9 November 2026, where the older rows start on the table's own first day, Terra's are $0.05 (0.05×), Gemini 3.5 Flash-Lite has no end date on its prices, and the OpenAI regional uplift for Terra and Astra is assumed from the Luna and Sol rows, because the pricing page gives no release dates to check the March 2026 cut-off against.

The model-level keys are all configuration too: tiers and geo_multipliers (multipliers), regional_uplift, web_search_per_1000, grounding_per_1000, cache_storage_per_hour (used by storage_cost(), 8.3) and min_cacheable_tokens, the smallest prefix the provider caches (6.4 states each provider's rule). The hit-rate analyser and the break-even calculator read these from the table instead of repeating them, so a provider change is a one-line edit here. A model whose minimum isn't published (3.5 Flash-Lite) simply has no key, and the analyser makes no claim about it.

4.3 The loader: prices.py#

The loader validates the file with Pydantic (overlapping periods are an error), resolves a dated snapshot name to its alias, and answers one question: "which rates applied to this provider and model on this day?". Save as prices.py, next to prices.yaml:

python
"""prices.py: load a dated price table and look up the rates in force on a given day."""
from __future__ import annotations

import datetime as dt
import re
from pathlib import Path

import yaml
from pydantic import BaseModel, Field, model_validator


DEFAULT_PATH = Path(__file__).with_name("prices.yaml")   # keep the table next to this module


class LongContext(BaseModel):
    above_input_tokens: int                 # the whole request switches rates above this
    rates: dict[str, float]


class Period(BaseModel):
    start: dt.date = Field(alias="from")
    end: dt.date | None = Field(default=None, alias="to")   # inclusive; None = open-ended
    rates: dict[str, float]                  # USD per 1M tokens, by line item
    long_context: LongContext | None = None
    fast_rates: dict[str, float] | None = None


class ModelPrices(BaseModel):
    source: str
    periods: list[Period] = []
    tiers: dict[str, float] = {}             # multiplier on every token rate, e.g. batch: 0.5
    geo_multipliers: dict[str, float] = {}   # e.g. Anthropic inference_geo "us": 1.1
    regional_uplift: float = 0.0             # e.g. OpenAI data-residency endpoints: 0.10
    web_search_per_1000: float = 0.0
    grounding_per_1000: float = 0.0          # Gemini grounding with Google Search, per search query
    min_cacheable_tokens: int | None = None  # smallest prefix the provider caches; None = not published
    use_reported_cost: bool = False          # OpenRouter: trust usage.cost

    @model_validator(mode="after")
    def periods_do_not_overlap(self) -> "ModelPrices":
        ordered = sorted(self.periods, key=lambda p: p.start)
        for a, b in zip(ordered, ordered[1:]):
            if a.end is None or a.end >= b.start:
                raise ValueError(f"overlapping price periods starting {a.start} and {b.start}")
        return self


class PriceTable:
    def __init__(self, data: dict) -> None:
        self.version = str(data.get("version"))
        self._models: dict[tuple[str, str], ModelPrices] = {}
        for provider, models in data.items():
            if provider == "version":
                continue
            for model, spec in models.items():
                self._models[(provider, model)] = ModelPrices.model_validate(spec)

    @classmethod
    def load(cls, path: str | Path = DEFAULT_PATH) -> "PriceTable":
        return cls(yaml.safe_load(Path(path).read_text()))

    def model(self, provider: str, model: str) -> ModelPrices:
        # Responses often name a dated snapshot ("gpt-6-luna-2026-09-22"): fall back to the alias
        alias = re.sub(r"-\d{4}-\d{2}-\d{2}$", "", model)
        found = (self._models.get((provider, model)) or self._models.get((provider, alias))
                 or self._models.get((provider, "*")))
        if found is None:
            # Fail loudly: a silent $0 is how cost dashboards end up wrong for months
            raise KeyError(f"no prices for {provider}/{model}: add it to the price table")
        return found

    def period(self, provider: str, model: str, on: dt.date) -> Period:
        for p in self.model(provider, model).periods:
            if p.start <= on and (p.end is None or on <= p.end):
                return p
        raise KeyError(f"no {provider}/{model} prices in force on {on}")


if __name__ == "__main__":
    table = PriceTable.load()
    print("price table version:", table.version)
    for day in [dt.date(2026, 11, 30), dt.date(2026, 12, 1), dt.date(2027, 1, 1)]:
        argon = table.period("gemini", "gemini-4-argon", day).rates
        flash = table.period("gemini", "gemini-3.8-flash", day).rates
        print(f"{day}  gemini-4-argon input ${argon['input']:.2f}/M  "
              f"gemini-3.8-flash input ${flash['input']:.2f}/M")
    try:
        table.model("anthropic", "claude-haiku-4-5")
    except KeyError as e:
        print("KeyError:", e)

Run it with uv run python prices.py:

text
price table version: 2026-11-04
2026-11-30  gemini-4-argon input $2.00/M  gemini-3.8-flash input $0.75/M
2026-12-01  gemini-4-argon input $4.00/M  gemini-3.8-flash input $0.75/M
2027-01-01  gemini-4-argon input $4.00/M  gemini-3.8-flash input $1.50/M
KeyError: 'no prices for anthropic/claude-haiku-4-5: add it to the price table'

The Argon price doubles between 30 November and 1 December; the Flash price a month later. A request logged on 30 November and re-priced on 2 December still gets 30 November's price, because the period is chosen by the call's date, not today's.

4.4 Where prices come from, and how to refresh them#

Source What it gives you Watch out for
Official pricing pages (OpenAI, Anthropic, Google) The authority, including footnotes, tiers, thresholds and dates Human-readable only; changes aren't announced through an API
OpenRouter's model list, GET https://openrouter.ai/api/v1/models Public, no key needed. pricing per model: prompt, completion, input_cache_read, input_cache_write (and input_cache_write_1h on Claude models), web_search, internal_reasoning, image, audio, plus overrides for long-context steps (min_prompt_tokens). All strings, in USD per single token These are OpenRouter's prices, which can differ from the provider's: Gemini 3.8 Flash is listed at the price of its US-region endpoint (02.9, 6.13). No effective dates
Pydantic's genai-prices (PyPI, version 0.2.1 in November 2026) A Python package with calc_price, which prices a usage object, and extract_usage, which reads usage from a provider response; its price data ships in the package and can optionally be refreshed from its GitHub repository. Tier and batch rates are covered Its own page warns that "these prices will not be 100% accurate". It has no effective dates for your contract either. Use it as one more tripwire, or as a quick start, and keep your own dated table: you can't review, date or source a price you didn't write down
LiteLLM's model_prices_and_context_window.json (GitHub) A community-maintained file covering thousands of models and many tier variants (..._batches, ..._flex, ..._priority, ..._above_272k_tokens) Maintained by volunteers and LiteLLM's team, not by the providers; it can lag a price change, and it has no effective dates, so a dated price change can't be represented at all

For OpenRouter calls, none of this matters for accounting: use usage.cost (3.5). For direct provider calls, use the official pages as the source of truth and the feeds as tripwires: a daily job that compares your table with them and reports every difference to a human. This one fetches both feeds live (both are public) and checks today's prices and 1 January 2027's. Save as s4_price_drift.py:

python
"""Check your price table against two public price feeds and flag every difference.
Run it daily in CI: a human decides what to change; nothing is updated automatically."""
import datetime as dt

import httpx

from prices import PriceTable

table = PriceTable.load()
today = dt.date.today()
OPENROUTER = {("openai", "gpt-6-luna"): "openai/gpt-6-luna",          # their IDs differ from ours
              ("openai", "gpt-6.1-terra"): "openai/gpt-6.1-terra",
              ("openai", "gpt-6.1-sol"): "openai/gpt-6.1-sol",
              ("openai", "gpt-6-astra"): "openai/gpt-6-astra",
              ("anthropic", "claude-haiku-5-5"): "anthropic/claude-haiku-5.5",
              ("anthropic", "claude-sonnet-5-5"): "anthropic/claude-sonnet-5.5",
              ("anthropic", "claude-fable-5-2"): "anthropic/claude-fable-5.2",
              ("anthropic", "claude-fable-5-1"): "anthropic/claude-fable-5.1",
              ("gemini", "gemini-3.8-flash"): "google/gemini-3.8-flash",
              ("gemini", "gemini-3.5-flash-lite"): "google/gemini-3.5-flash-lite",
              ("gemini", "gemini-4-argon"): "google/gemini-4-argon"}
LITELLM = {("gemini", "gemini-3.8-flash"): "gemini/gemini-3.8-flash",
           ("gemini", "gemini-4-argon"): "gemini/gemini-4-argon"}
LITELLM_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"

with httpx.Client(timeout=30, follow_redirects=True) as http:
    # Public, no key needed. Prices are strings, in USD per single token.
    orouter = {m["id"]: m for m in http.get("https://openrouter.ai/api/v1/models").json()["data"]}
    litellm = http.get(LITELLM_URL).json()          # community-maintained: convenient, can lag


def per_m(value: str | float | None) -> float | None:
    return None if value is None else round(float(value) * 1_000_000, 6)


print(f"prices.yaml version {table.version}, checked on {today}")
for (provider, model), or_id in OPENROUTER.items():
    ours = table.period(provider, model, today).rates
    theirs = orouter.get(or_id, {}).get("pricing", {})
    for line, key in [("input", "prompt"), ("cached_input", "input_cache_read"), ("output", "completion")]:
        a, b = ours.get(line), per_m(theirs.get(key))
        if a != b:
            print(f"  DIFF openrouter {or_id:28s} {line:12s} ours={a} theirs={b}")
for (provider, model), ll_id in LITELLM.items():
    entry = litellm.get(ll_id, {})
    b = per_m(entry.get("input_cost_per_token"))
    for day in [today, dt.date(2027, 1, 1)]:
        a = table.period(provider, model, day).rates["input"]
        if a != b:
            print(f"  DIFF litellm    {ll_id:28s} input on {day}: ours={a} theirs={b} (no end dates in feed)")
Output · fetched on 4 November 2026; the feeds change, so yours will differ6 lines
prices.yaml version 2026-11-04, checked on 2026-11-04
  DIFF openrouter google/gemini-3.8-flash      input        ours=0.75 theirs=0.825
  DIFF openrouter google/gemini-3.8-flash      cached_input ours=0.075 theirs=0.0825
  DIFF openrouter google/gemini-3.8-flash      output       ours=3.75 theirs=4.125
  DIFF litellm    gemini/gemini-3.8-flash      input on 2027-01-01: ours=1.5 theirs=0.75 (no end dates in feed)
  DIFF litellm    gemini/gemini-4-argon        input on 2027-01-01: ours=4.0 theirs=2.0 (no end dates in feed)

Every reported difference has an explanation, and none of them means the table is wrong:

  • OpenRouter's Gemini 3.8 Flash is 10% higher than Google's list price because the catalogue lists the US-region endpoint's price. The table is right for direct Gemini calls; OpenRouter calls are priced by usage.cost anyway.
  • The four models added in this version of the table (Fable 5.1, Terra, Astra, 3.5 Flash-Lite) had no difference on 4 November: OpenRouter's catalogue agrees with the official pages on input, cached input and output. claude-fable-5-2 was added to the table after the run above (released 9 November): OpenRouter lists anthropic/claude-fable-5.2 at $8 input, $0.20 cached input and $40 output, the same as Anthropic's pricing page (both read on 11 November 2026), so the extra mapping line reports no difference.
  • LiteLLM's Gemini prices are correct today, but the file has no end dates, so on 1 January 2027 (and for Argon, on 1 December 2026) anything priced from it will be wrong by half until someone updates it.

What this means for you: automate the check, never the update. A human reads the pricing page, adds a new period with its source, and the change goes through review like code.


Part 5: A cost tracker wired into real calls#

5.1 What to record, and why each field is there#

A cost tracker sits around every model call and writes one record per call. The record is small, but every field answers a question someone will ask:

Field Answers
feature "Which product feature costs the most?" Set it at the call site ("support-bot", "contract-qa"), never infer it later
customer "Which customer costs the most? Are we losing money on the free plan?" A keyed hash of the customer or user ID, never the raw ID or email
env "Is that spend production, staging, or a developer's laptop?"
kind call for a model call, cache_storage for the hours a Gemini explicit cache was kept (8.3)
provider, model, served_model What you asked for, and what the response says served it. They differ when a provider answers with a dated snapshot (gpt-6-luna-2026-09-22), a router picks another model, or a fallback fires (4.3); price lookups and cache analysis want both
api responses, chat, messages, generate_content or interactions: which parser read the response, and which API's quirks apply when a number looks wrong
request_id, trace_id The provider's response ID (the join key to its records, support tickets and OpenRouter's generation endpoint) and your own correlation ID (lesson 03.10), if you have one
prefix A fingerprint of the cacheable prefix (10.4): "did the prefix change when the hit rate dropped?"
tier, batch, regional The tier that served the request, plus two facts only your code knows: that it was a batch result, and that it used a regional endpoint (5.8)
uncached_input_tokens, cached_input_tokens, cache_write_tokens, total_input_tokens, output_tokens, reasoning_tokens The normalized usage from Part 3. The first is uncached input and the fourth the sum of the first three (the convention from 3.1); output_tokens already includes reasoning
finish_reason, status The provider's own stop signal, and ok, truncated, blocked or error:<Name> (an exception name, or failed for a response object that ended in that state). A truncated answer is "a failed request you paid for" (12.1): without this you can't measure what truncation costs, or pick a cap from the p99
attempts How many requests your retry code made for this call (empty if you don't know). A retry after a timeout or a dropped stream may have been billed too (lesson 03.8, 6.6)
cost_usd, cost_source The price, and whether you computed it, the provider reported it (OpenRouter), or it's unknown
price_version Which price table priced it, so you can re-price later and know what changed
latency_ms Cost per success vs cost of failures; failed calls can still be billed
storage_token_hours On cache_storage records only: tokens held times hours kept

The token columns follow the convention from 3.1, and so differ on purpose from lesson 03.2's conversation store, whose input_tokens is the total. total_input_tokens is there so that either reading is one column away.

5.2 The tracker: cost_tracker.py#

Save as cost_tracker.py, next to cost_calc.py and prices.py. normalize() reads every response type the lesson has met: OpenAI Responses and Chat Completions, Anthropic's Message and the BetaMessage that client.beta.messages returns, Gemini's GenerateContentResponse and Interaction, and OpenRouter's Chat Completions and Responses-compatible objects:

python
"""cost_tracker.py: record the cost of every LLM call with who and what it was for."""
from __future__ import annotations

import datetime as dt
import hashlib
import hmac
import json
import logging
import os
import secrets
import threading
import time
import uuid
from contextlib import contextmanager
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Iterator, NamedTuple

from anthropic.types import Message
from anthropic.types.beta import BetaMessage
from google.genai import types as gtypes
from google.genai.interactions import Interaction
from openai.types.chat import ChatCompletion
from openai.types.responses import Response

from cost_calc import (Usage, from_anthropic, from_gemini, from_gemini_interaction, from_openai_chat,
                       from_openai_response, from_openrouter, from_openrouter_response, price,
                       storage_cost)
from prices import PriceTable

log = logging.getLogger("cost")

# finish reasons that mean "you paid for an answer you can't use": extend from lesson 03.8's tables
TRUNCATED = {"max_output_tokens", "length", "max_tokens", "MAX_TOKENS", "model_context_window_exceeded"}
BLOCKED = {"content_filter", "refusal", "SAFETY", "PROHIBITED_CONTENT", "BLOCKLIST", "SPII", "RECITATION"}
FAILED = {"failed", "cancelled"}   # end states of Responses and Interactions objects that carry no usable answer


@dataclass
class CallRecord:
    ts: str
    call_id: str
    env: str
    feature: str
    customer: str | None          # keyed hash, never the raw user ID or email
    kind: str                     # call | cache_storage
    provider: str
    model: str                    # the model you asked for
    served_model: str | None      # the model the response names: can differ (snapshot, router, fallback)
    api: str | None               # responses | chat | messages | generate_content | interactions | ...
    request_id: str | None        # provider's response ID: the join key for reconciliation
    trace_id: str | None          # your own correlation ID (lesson 03.10), if you have one
    prefix: str | None            # fingerprint of the cacheable prefix (see the request builder)
    tier: str | None              # the tier that SERVED the request (or batch, from your context)
    batch: bool                   # a batch result: the response body doesn't say so
    regional: bool                # a data-residency endpoint: the response doesn't say so either
    # Token columns follow the module's convention: `uncached` = billed at the plain input rate.
    uncached_input_tokens: int | None
    cached_input_tokens: int | None
    cache_write_tokens: int | None
    total_input_tokens: int | None   # uncached + cached + written: what lesson 03.2's store calls input_tokens
    output_tokens: int | None     # includes reasoning
    reasoning_tokens: int | None
    finish_reason: str | None     # raw, per provider: lets you measure what truncation costs
    attempts: int | None          # requests your retry wrapper made (None = unknown)
    storage_token_hours: float | None   # cache_storage records only: tokens held x hours kept
    cost_usd: float | None        # None = unknown, never 0
    cost_source: str              # computed | provider | unknown
    price_version: str
    latency_ms: int | None
    status: str                   # ok | truncated | blocked | error:<ExceptionName or failed>


class Parsed(NamedTuple):
    usage: Usage
    request_id: str | None
    served_model: str | None
    api: str
    finish_reason: str | None


class CostTracker:
    # env labels where a missing hash key is tolerated. Anything else (prod, staging, a typo) must bring a key.
    DEV_ENVS = frozenset({"dev", "dev-local", "demo", "mock", "test"})

    def __init__(self, table: PriceTable, sink: str | Path, env: str, hash_key: bytes | None = None) -> None:
        self.table, self.sink, self.env = table, Path(sink), env
        # The secret for the keyed customer hash. NO default: pass it, or set USER_ID_PEPPER (from your secret store; the same
        # variable as lesson 03.2, 10.3, which also explains the purpose string used below).
        key = hash_key or os.environ.get("USER_ID_PEPPER", "").encode()
        if not key:
            if env not in self.DEV_ENVS:   # fail closed: a missing key must stop the service, not weaken the hash
                raise ValueError(f"env={env!r} needs a secret hash key: pass hash_key= or set USER_ID_PEPPER")
            key = secrets.token_bytes(32)  # dev: random per process. Hashes won't match across restarts; nothing is guessable
        self._hash_key = key
        self._lock = threading.Lock()

    def customer_hash(self, customer_id: str | None) -> str | None:
        if customer_id is None:
            return None
        # Keyed hash: stable per customer, but can't be reversed by hashing a list of emails. The message is
        # f"{purpose}:{id}" as in lesson 03.2, 10.3; "logs-v1" is the purpose for IDs in your own records (the ID you send
        # to a provider uses "llm-abuse-v1" instead). 16 hex characters are enough to group one customer's calls.
        return hmac.new(self._hash_key, f"logs-v1:{customer_id}".encode(), hashlib.sha256).hexdigest()[:16]

    @staticmethod
    def normalize(provider: str, response: Any, model: str) -> Parsed:
        """Read usage, IDs and the finish reason from any supported response object."""
        if provider == "openrouter" and isinstance(response, Response):           # Responses API
            return Parsed(from_openrouter_response(response), response.id, response.model, "responses",
                          _openai_status(response))
        if provider == "openai" and isinstance(response, Response):
            return Parsed(from_openai_response(response), response.id, response.model, "responses",
                          _openai_status(response))
        if provider in ("openai", "openrouter") and isinstance(response, ChatCompletion):
            usage = from_openai_chat(response) if provider == "openai" else from_openrouter(response)
            reason = response.choices[0].finish_reason if response.choices else None
            return Parsed(usage, response.id, response.model, "chat", reason)
        if provider == "anthropic" and isinstance(response, (Message, BetaMessage)):
            return Parsed(from_anthropic(response), response.id, response.model, "messages",
                          response.stop_reason)
        if provider == "gemini" and isinstance(response, gtypes.GenerateContentResponse):
            headers = response.sdk_http_response.headers if response.sdk_http_response else None
            tier = (headers or {}).get("x-gemini-service-tier")     # the Developer API's tier signal
            reason = response.candidates[0].finish_reason if response.candidates else None
            return Parsed(from_gemini(response, model, service_tier=tier), response.response_id,
                          response.model_version, "generate_content", reason.name if reason else None)
        if provider == "gemini" and isinstance(response, Interaction):
            return Parsed(from_gemini_interaction(response, model), response.id, response.model,
                          "interactions", response.status)
        raise TypeError(f"don't know how to read usage from {provider} {type(response).__name__}")

    def record(self, *, provider: str, model: str, response: Any, feature: str,
               customer_id: str | None = None, latency_ms: int | None = None,
               prefix: str | None = None, batch: bool = False, regional: bool = False,
               tier: str | None = None, attempts: int | None = None,
               trace_id: str | None = None) -> CallRecord:
        """`batch`, `regional` and `tier` are facts only YOUR code knows (the response body doesn't
        say it came from a batch job or a regional endpoint); they override what the response says."""
        parsed: Parsed | None = None
        cost, source = None, "unknown"
        try:
            parsed = self.normalize(provider, response, model)
            usage = parsed.usage
            if usage.total_input + usage.output == 0 and usage.reported_cost is None:
                # No real call has zero tokens; zeros mean the usage was never filled in (some proxies
                # and some stream chunks). Unknown, not "free".
                raise ValueError("usage is all zeros: the provider (or proxy) didn't fill it in")
            if tier:
                usage.tier = tier
            if batch:
                usage.tier = "batch"                  # wins over fast mode: fast isn't offered in batches
            if regional:
                usage.regional = True
            c = price(usage, self.table)
            cost, source = round(c.usd, 10), ("provider" if usage.reported_cost is not None else "computed")
        except (KeyError, ValueError, TypeError) as e:
            # Never fail the user's request because accounting failed: log loudly, record unknown
            log.warning("cost unknown for %s/%s: %s", provider, model, e)
        usage = parsed.usage if parsed else None
        # If the usage could not be read (a failed Responses object may carry none), the object's own
        # `status` still says whether the call failed: don't record such a call as "ok".
        finish = parsed.finish_reason if parsed else getattr(response, "status", None)
        rec = self._record(
            provider=provider, model=model, feature=feature, customer_id=customer_id,
            served_model=parsed.served_model if parsed else None, api=parsed.api if parsed else None,
            request_id=parsed.request_id if parsed else None, trace_id=trace_id, prefix=prefix,
            tier=usage.tier if usage else None, batch=batch, regional=regional,
            uncached_input_tokens=usage.input if usage else None,
            cached_input_tokens=usage.cached_input if usage else None,
            cache_write_tokens=sum(usage.cache_writes.values()) if usage else None,
            total_input_tokens=usage.total_input if usage else None,
            output_tokens=usage.output if usage else None,
            reasoning_tokens=usage.reasoning if usage else None,
            finish_reason=finish, attempts=attempts, cost_usd=cost, cost_source=source,
            latency_ms=latency_ms,
            status="truncated" if finish in TRUNCATED else "blocked" if finish in BLOCKED
            else f"error:{finish}" if finish in FAILED else "ok")
        return rec

    def record_error(self, *, provider: str, model: str, feature: str, customer_id: str | None,
                     latency_ms: int, error: Exception, attempts: int | None = None,
                     trace_id: str | None = None) -> None:
        """A failed call may still have been billed (input read, partial stream): cost unknown."""
        self._record(provider=provider, model=model, feature=feature, customer_id=customer_id,
                     latency_ms=latency_ms, attempts=attempts, trace_id=trace_id,
                     status=f"error:{type(error).__name__}")

    def record_cache_storage(self, *, provider: str, model: str, cache_name: str, tokens: int,
                             created: dt.datetime, deleted: dt.datetime, feature: str) -> CallRecord:
        """A Gemini explicit cache costs tokens x hours to keep, and no response says so (lesson 03.7, 8.3).
        Call this when you delete the cache (or when it expires): `created` and `deleted` are UTC."""
        cost, source = None, "unknown"
        try:
            cost, source = storage_cost(provider, model, tokens, created, deleted, self.table), "computed"
        except KeyError as e:
            log.warning("storage cost unknown for %s: %s", cache_name, e)
        return self._record(provider=provider, model=model, feature=feature, kind="cache_storage",
                            request_id=cache_name, ts=deleted.isoformat(timespec="seconds"),
                            storage_token_hours=tokens * (deleted - created).total_seconds() / 3600,
                            cost_usd=cost, cost_source=source,
                            latency_ms=round((deleted - created).total_seconds() * 1000))

    @contextmanager
    def track(self, *, provider: str, model: str, feature: str, customer_id: str | None = None,
              prefix: str | None = None, batch: bool = False, regional: bool = False,
              tier: str | None = None, attempts: int | None = None,
              trace_id: str | None = None) -> Iterator[dict]:
        """with tracker.track(...) as call: call["response"] = client.create(...)"""
        call: dict = {}
        start = time.perf_counter()
        try:
            yield call
        except Exception as e:
            self.record_error(provider=provider, model=model, feature=feature, customer_id=customer_id,
                              latency_ms=round((time.perf_counter() - start) * 1000), error=e,
                              attempts=attempts, trace_id=trace_id)
            raise
        if "response" not in call:       # e.g. a stream that ended without its terminal event
            err = RuntimeError("no response was stored in the tracked block")
            self.record_error(provider=provider, model=model, feature=feature, customer_id=customer_id,
                              latency_ms=round((time.perf_counter() - start) * 1000), error=err,
                              attempts=attempts, trace_id=trace_id)
            raise err
        self.record(provider=provider, model=model, response=call["response"], feature=feature,
                    customer_id=customer_id, latency_ms=round((time.perf_counter() - start) * 1000),
                    prefix=prefix, batch=batch, regional=regional, tier=tier, attempts=attempts,
                    trace_id=trace_id)

    def _record(self, *, provider: str, model: str, feature: str, kind: str = "call",
                customer_id: str | None = None, ts: str | None = None, status: str = "ok",
                cost_usd: float | None = None, cost_source: str = "unknown", batch: bool = False,
                regional: bool = False, **fields: Any) -> CallRecord:
        cols = {k: None for k in ("served_model", "api", "request_id", "trace_id", "prefix", "tier",
                                  "uncached_input_tokens", "cached_input_tokens", "cache_write_tokens",
                                  "total_input_tokens", "output_tokens", "reasoning_tokens",
                                  "finish_reason", "attempts", "storage_token_hours", "latency_ms")}
        cols.update(fields)
        rec = CallRecord(
            ts=ts or dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
            call_id=uuid.uuid4().hex, env=self.env, feature=feature,
            customer=self.customer_hash(customer_id), kind=kind, provider=provider, model=model,
            batch=batch, regional=regional, cost_usd=cost_usd, cost_source=cost_source,
            price_version=self.table.version, status=status, **cols)
        with self._lock, self.sink.open("a") as f:     # JSON Lines: one record per line
            f.write(json.dumps(asdict(rec)) + "\n")
        return rec


def _openai_status(resp: Response) -> str | None:
    """Responses: `incomplete` carries the reason (max_output_tokens, content_filter); else the status."""
    if resp.status == "incomplete" and resp.incomplete_details:
        return resp.incomplete_details.reason
    return resp.status

The design decisions that matter in production:

  • Accounting never breaks the request. If pricing fails (a new model, a missing field, a tier with no price, an object it can't read), the tracker logs a warning and records cost_usd: null with cost_source: "unknown". Usage that is all zeros counts as unknown too: no real call has zero tokens, so zeros mean a proxy or a stream chunk never filled it in. The user still gets their answer; your alert on "unknown cost" tells you to fix the table.
  • Unknown is null, never 0. A zero says "free" and makes dashboards and budgets undercount exactly the calls you most need to see (lesson 03.3, 7.6).
  • Facts the response can't state are arguments. record() and track() take batch, regional and tier (plus attempts and trace_id), because a batch result, a data-residency endpoint and a tier you know from context don't appear in the response body (5.8).
  • A truncated, blocked or failed answer isn't "ok". The finish reason is read per provider (incomplete_details.reason, finish_reason, stop_reason, or the status of a Responses or Interactions object) and mapped to truncated, blocked or error:failed; extend the three small sets at the top with lesson 03.8's tables. A failed Responses object may carry no usage at all: then the cost is unknown, but record() still reads the object's own status, so the call is recorded as error:failed, not ok.
  • Failed calls are recorded too. A timeout after the provider started generating, or a broken stream, may still be billed. record_error writes a record with unknown cost, so failure rates and their cost show up. So does a track() block that finishes without storing a response, which is what a stream that ended without its terminal event looks like.
  • JSON Lines to a file here; a log pipeline in production. One JSON object per line is easy to ship to whatever you use for logs or analytics. Lesson 03.10 covers structured logging and redaction; tracing platforms are Module 11A's subject.
  • track() is a context manager, so the call site stays one with block, and timing and error handling can't be forgotten.

5.3 Try it free against the local stand-in#

This sample points every client at the local stand-in explicitly (lesson 03.1, 12.2) and prices the calls with a fake price table, prices_fake_local.yaml, with round numbers that are clearly not real prices:

Save as prices_fake_local.yaml:

yaml
# FAKE PRICES for practising against the local stand-in. NOT real prices.
# Round numbers so the arithmetic is easy to check by hand.
version: fake-local-1
openai:
  gpt-6-luna:
    source: none (practice)
    periods: [{from: 2026-01-01, rates: {input: 1.0, cached_input: 0.1, cache_write_30m: 1.25, cache_write_12h: 2.5, output: 5.0}}]
anthropic:
  claude-haiku-5-5:
    source: none (practice)
    periods: [{from: 2026-01-01, rates: {input: 1.0, cached_input: 0.1, cache_write_5m: 1.25, cache_write_1h: 2.0, output: 5.0}}]
gemini:
  gemini-3.8-flash:
    source: none (practice)
    periods: [{from: 2026-01-01, rates: {input: 1.0, cached_input: 0.1, output: 5.0}}]
openrouter:
  "*":
    source: none (practice)
    use_reported_cost: true

Save as s5_tracker_local.py:

python
"""Try the cost tracker free, against the local stand-in, with a FAKE price table."""
import json
from pathlib import Path

import anthropic
from openai import OpenAI

from cost_tracker import CostTracker
from prices import PriceTable

LOG = Path("calls_local.jsonl")
LOG.unlink(missing_ok=True)
tracker = CostTracker(PriceTable.load("prices_fake_local.yaml"), LOG, env="dev-local")
Q = "In one sentence, what is a token?"

oai = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")          # Ollama
with tracker.track(provider="openai", model="gpt-6-luna", feature="faq", customer_id="cust_42") as call:
    call["response"] = oai.responses.create(model="gpt-6-luna", input=Q, max_output_tokens=60)

claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")
with tracker.track(provider="anthropic", model="claude-haiku-5-5", feature="faq", customer_id="cust_42") as call:
    call["response"] = claude.messages.create(model="claude-haiku-5-5", max_tokens=60,
                                              messages=[{"role": "user", "content": Q}])

router = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")       # OpenRouter-shaped code
with tracker.track(provider="openrouter", model="anthropic/claude-haiku-5.5", feature="faq") as call:
    call["response"] = router.chat.completions.create(
        model="anthropic/claude-haiku-5.5", max_tokens=60, messages=[{"role": "user", "content": Q}])

try:                                                    # a failed call is recorded too
    with tracker.track(provider="openai", model="no-such-model", feature="faq") as call:
        call["response"] = oai.responses.create(model="no-such-model", input=Q, max_output_tokens=10)
except Exception as e:
    print("call failed:", type(e).__name__)

for line in LOG.read_text().splitlines():
    r = json.loads(line)
    print(f"{r['provider']:10s} {r['model']:26s} in={r['uncached_input_tokens']} out={r['output_tokens']} "
          f"cost={r['cost_usd']} ({r['cost_source']}) customer={r['customer']} status={r['status']}")

The Gemini path of the tracker has no local stand-in: 5.5 shows it with a key.

Output · local model qwen2.5:0.5b via Ollama, priced with FAKE prices6 lines
cost unknown for openrouter/anthropic/claude-haiku-5.5: OpenRouter response without usage.cost: fetch /api/v1/generation
call failed: NotFoundError
openai     gpt-6-luna                 in=38 out=18 cost=0.000128 (computed) customer=bbb7247190217d1b status=ok
anthropic  claude-haiku-5-5           in=38 out=17 cost=0.000123 (computed) customer=bbb7247190217d1b status=ok
openrouter anthropic/claude-haiku-5.5 in=38 out=21 cost=None (unknown) customer=None status=ok
openai     no-such-model              in=None out=None cost=None (unknown) customer=None status=error:NotFoundError

And the first record from calls_local.jsonl, with every field of the schema in 5.1:

json
{
  "ts": "2026-11-04T15:37:20+00:00",
  "call_id": "8a503335145f47e2bc24b2dbcd029135",
  "env": "dev-local",
  "feature": "faq",
  "customer": "bbb7247190217d1b",
  "kind": "call",
  "provider": "openai",
  "model": "gpt-6-luna",
  "served_model": "gpt-6-luna",
  "api": "responses",
  "request_id": "resp_33142",
  "trace_id": null,
  "prefix": null,
  "tier": "standard",
  "batch": false,
  "regional": false,
  "uncached_input_tokens": 38,
  "cached_input_tokens": 0,
  "cache_write_tokens": 0,
  "total_input_tokens": 38,
  "output_tokens": 18,
  "reasoning_tokens": 0,
  "finish_reason": "completed",
  "attempts": null,
  "storage_token_hours": null,
  "cost_usd": 0.000128,
  "cost_source": "computed",
  "price_version": "fake-local-1",
  "latency_ms": 248,
  "status": "ok"
}

What the run shows:

  • The same code path priced three providers through their own SDK types: 38 input tokens × $1/M + 18 output tokens × $5/M = $0.000128 for the OpenAI-shaped call, as the fake table says. The model is a different one on every run, so your output counts will differ.
  • The OpenRouter-shaped call came back unknown: Ollama doesn't return usage.cost, and the tracker refused to invent one. Against real OpenRouter, cost_source would be provider.
  • The failed call was recorded with status: error:NotFoundError and unknown cost.
  • Customer IDs are hashed: cust_42 appears as the same bbb7247190217d1b on both of its calls, and nowhere in clear text. The sample runs with env="dev-local" and no USER_ID_PEPPER, so the tracker made a random key for this process: your hash will differ, and it will differ again on the next run. That is deliberate. The tracker has no default key, because a default that is written in the source is a key everyone knows, and anyone could then rebuild the hash of a known email. In a real environment set USER_ID_PEPPER (from your secret store, like an API key) or pass hash_key=; with any env outside the development labels (dev, dev-local, demo, mock, test) the constructor raises ValueError if there is no key, the same fail-closed rule as LogConfig in lesson 03.10, 4.2.
  • The token counts are the stand-in's, approximate and different from any hosted model's. The mechanics are what's real here.

5.4 Streaming calls#

With streaming, usage arrives at the end of the stream (lesson 03.3 covers where, per provider). Record the cost from the stream's terminal object, once the stream has finished; if the stream breaks, the with block raises and the tracker records the failure. Here are three streams on the local stand-in. Save as s5_stream_local.py:

python
"""Streaming calls: record cost from the stream's terminal object, once the stream has finished
(local model, FAKE prices). Three streams: OpenAI Responses, OpenAI Chat Completions, Anthropic."""
import json
from pathlib import Path

import anthropic
import openai
from openai import OpenAI
from openai.types.responses import ResponseCompletedEvent, ResponseFailedEvent, ResponseIncompleteEvent

from cost_tracker import CostTracker
from prices import PriceTable

TERMINAL = (ResponseCompletedEvent, ResponseIncompleteEvent, ResponseFailedEvent)   # all three carry usage
LOG = Path("calls_stream.jsonl")
LOG.unlink(missing_ok=True)
tracker = CostTracker(PriceTable.load("prices_fake_local.yaml"), LOG, env="dev-local")
ASK = "Name three colours."

oai = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")

# 1. Responses API. Don't use stream.get_final_response() here: it raises unless the stream ended with
#    response.completed, and a call that hits max_output_tokens ends with response.incomplete (on
#    hosted OpenAI; Ollama hides it). Keep the terminal event's response yourself: it carries usage.
with tracker.track(provider="openai", model="gpt-6-luna", feature="chat") as call:
    with oai.responses.stream(model="gpt-6-luna", input=ASK, max_output_tokens=40) as s:
        for event in s:
            # forward text deltas to the user here
            if isinstance(event, TERMINAL):
                call["response"] = event.response

# 2. Chat Completions. Usage arrives in an extra last chunk ONLY with include_usage. The .stream()
#    helper raises LengthFinishReasonError when the reply was cut off; the error carries the completion.
with tracker.track(provider="openai", model="gpt-6-luna", feature="chat-completions") as call:
    with oai.chat.completions.stream(model="gpt-6-luna", max_tokens=40,   # max_completion_tokens on OpenAI
                                     messages=[{"role": "user", "content": ASK}],
                                     stream_options={"include_usage": True}) as s:
        try:
            for event in s:
                pass                                       # forward text deltas to the user here
            call["response"] = s.get_final_completion()
        except openai.LengthFinishReasonError as e:        # the cap was hit: still billed, still recorded
            call["response"] = e.completion

# 3. Anthropic: the helper accumulates usage from message_start and message_delta.
claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")
with tracker.track(provider="anthropic", model="claude-haiku-5-5", feature="chat") as call:
    with claude.messages.stream(model="claude-haiku-5-5", max_tokens=40,
                                messages=[{"role": "user", "content": ASK}]) as s:
        for text in s.text_stream:
            pass
        call["response"] = s.get_final_message()

for line in LOG.read_text().splitlines():
    r = json.loads(line)
    print(f"{r['provider']:10s} {r['api']:9s} in={r['uncached_input_tokens']} out={r['output_tokens']} "
          f"cost=${r['cost_usd']:.6f} finish={r['finish_reason']} status={r['status']}")

Output (local model qwen2.5:0.5b via Ollama, priced with FAKE prices; the model's replies, and so the token counts and which calls hit the 40-token cap, differ on every run):

text
openai     responses in=33 out=40 cost=$0.000233 finish=completed status=ok
openai     chat      in=33 out=27 cost=$0.000168 finish=stop status=ok
anthropic  messages  in=33 out=40 cost=$0.000233 finish=max_tokens status=truncated

Three details in that code decide whether the record is right:

  • Don't use get_final_response() for the Responses API. It raises RuntimeError unless the stream ended with response.completed (lesson 03.3, 4.2). On hosted OpenAI, a call that reaches max_output_tokens ends with response.incomplete, so the track() block would catch the exception and write status: error:RuntimeError with an unknown cost, for a call that was billed. The sample keeps the terminal event's response instead: completed, incomplete and failed all carry usage, and from_openai_response prices an incomplete response like any other. The local run can't show this: Ollama ends a capped Responses stream with response.completed (the first line of the output says finish=completed), so the sample passes locally either way. That is why the next sample uses a mock.
  • Chat Completions only reports usage if you ask. The extra last chunk (choices: [], with usage) exists only when the request sets stream_options={"include_usage": True} (lesson 03.3, 3). Without it the tracker has nothing to price. The .stream() helper also refuses a reply that was cut off, with LengthFinishReasonError, and that error carries the completion, usage included, so the sample records it: a capped call is billed and must be recorded. This one does show locally.
  • The cap works as a cost ceiling (12.1), but only if the cost of a capped call still reaches the log, and status: truncated is how you find them afterwards.

Because Ollama hides response.incomplete, here is the same code against a mock server: the real openai SDK with an httpx2.MockTransport that answers with the event sequence OpenAI documents for a capped call (lesson 03.10 covers mock transports). It runs the naive version, the fix and the Chat Completions version, and prices them with the real price table. Save as s5_stream_incomplete.py:

python
"""A capped OpenAI stream, MOCKED: hosted OpenAI ends a call that hit max_output_tokens with
response.incomplete, which the local stand-in never sends. The SDK is real; the server is a mock."""
import json
from pathlib import Path

import httpx2
import openai
from openai import OpenAI
from openai.types.responses import ResponseCompletedEvent, ResponseFailedEvent, ResponseIncompleteEvent

from cost_tracker import CostTracker
from prices import PriceTable


def sse(*events: tuple[str | None, dict | str]) -> httpx2.Client:
    """An httpx2 client whose every request is answered with these server-sent events."""
    body = "".join((f"event: {name}\n" if name else "") + f"data: {data if isinstance(data, str) else json.dumps(data)}\n\n"
                   for name, data in events).encode()
    return httpx2.Client(transport=httpx2.MockTransport(lambda request: httpx2.Response(
        200, headers={"content-type": "text/event-stream"}, content=body)))


USAGE = {"input_tokens": 33, "output_tokens": 40, "total_tokens": 73,
         "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0},
         "output_tokens_details": {"reasoning_tokens": 0}}
RESP = {"id": "resp_1", "object": "response", "created_at": 1, "model": "gpt-6-luna", "output": [],
        "parallel_tool_calls": True, "tool_choice": "auto", "tools": []}
RESPONSES_STREAM = sse(
    ("response.created", {"type": "response.created", "sequence_number": 0,
                          "response": {**RESP, "status": "in_progress"}}),
    ("response.incomplete", {"type": "response.incomplete", "sequence_number": 1,
                             "response": {**RESP, "status": "incomplete", "usage": USAGE,
                                          "incomplete_details": {"reason": "max_output_tokens"}}}))

CHUNK = {"id": "chatcmpl-1", "object": "chat.completion.chunk", "created": 1, "model": "gpt-6-luna"}
CHAT_STREAM = sse(
    (None, {**CHUNK, "choices": [{"index": 0, "delta": {"role": "assistant", "content": "Red, blue"},
                                  "finish_reason": None}]}),
    (None, {**CHUNK, "choices": [{"index": 0, "delta": {}, "finish_reason": "length"}]}),
    (None, {**CHUNK, "choices": [], "usage": {"prompt_tokens": 33, "completion_tokens": 40, "total_tokens": 73}}),
    (None, "[DONE]"))

TERMINAL = (ResponseCompletedEvent, ResponseIncompleteEvent, ResponseFailedEvent)
LOG = Path("calls_incomplete.jsonl")
LOG.unlink(missing_ok=True)
tracker = CostTracker(PriceTable.load(), LOG, env="mock")

# 1. The naive version, as 5.4 first wrote it: get_final_response() raises, so the tracker records an
#    ERROR with unknown cost for a call that was billed
client = OpenAI(api_key="sk-test", http_client=RESPONSES_STREAM)
try:
    with tracker.track(provider="openai", model="gpt-6-luna", feature="naive") as call:
        with client.responses.stream(model="gpt-6-luna", input="Write an essay.", max_output_tokens=40) as s:
            for event in s:
                pass
            call["response"] = s.get_final_response()
except RuntimeError as e:
    print("naive version raised:", e)

# 2. The fix: keep the terminal event's response. Its usage is what OpenAI billed.
client = OpenAI(api_key="sk-test", http_client=RESPONSES_STREAM)
with tracker.track(provider="openai", model="gpt-6-luna", feature="responses") as call:
    with client.responses.stream(model="gpt-6-luna", input="Write an essay.", max_output_tokens=40) as s:
        for event in s:
            if isinstance(event, TERMINAL):
                call["response"] = event.response

# 3. Chat Completions: the usage chunk (choices: []) exists only because the request set include_usage
client = OpenAI(api_key="sk-test", http_client=CHAT_STREAM)
with tracker.track(provider="openai", model="gpt-6-luna", feature="chat-completions") as call:
    with client.chat.completions.stream(model="gpt-6-luna", messages=[{"role": "user", "content": "Write an essay."}],
                                        max_completion_tokens=40, stream_options={"include_usage": True}) as s:
        try:
            for event in s:
                pass
            call["response"] = s.get_final_completion()
        except openai.LengthFinishReasonError as e:       # the helper refuses a cut-off reply
            call["response"] = e.completion

for line in LOG.read_text().splitlines():
    r = json.loads(line)
    print(f"{r['feature']:16s} status={r['status']:20s} finish={r['finish_reason']} "
          f"out={r['output_tokens']} cost_usd={r['cost_usd']}")

Output (the server is a mock; the cost is real arithmetic on the real price table: 33 × $0.10/M + 40 × $0.50/M):

text
naive version raised: Didn't receive a `response.completed` event.
naive            status=error:RuntimeError   finish=None out=None cost_usd=None
responses        status=truncated            finish=max_output_tokens out=40 cost_usd=2.33e-05
chat-completions status=truncated            finish=length out=40 cost_usd=2.33e-05

The naive version raises exactly the error 03.3 warned about and records a billed call as an error with no cost. The fixed version records status: truncated, finish_reason: max_output_tokens and the real cost.

Gemini. Keep the latest chunk that carries usage_metadata: Google doesn't say which chunk has it, and the SDK treats each chunk's value as a running total within a request (03.3, 3.4). On a very long generation, the SDK sums usage across continuation hops for you, so use the merged value (03.3, 4.5b). Save as s5_stream_gemini.py:

python
"""Gemini streaming and cost: keep the LATEST chunk that carries usage_metadata (needs GEMINI_API_KEY)."""
import os

from dotenv import load_dotenv
from google import genai
from google.genai import types

from cost_tracker import CostTracker
from prices import PriceTable

load_dotenv()
tracker = CostTracker(PriceTable.load(), "calls.jsonl", env=os.getenv("APP_ENV", "dev"))
client = genai.Client()

with tracker.track(provider="gemini", model="gemini-3.8-flash", feature="faq") as call:
    for chunk in client.models.generate_content_stream(
            model="gemini-3.8-flash", contents="Name three colours.",
            config=types.GenerateContentConfig(max_output_tokens=300)):
        print(chunk.text or "", end="")                   # forward text to the user here
        # Google doesn't say which chunk carries usage_metadata, and each chunk's value is a running
        # total for the request: so keep the newest one that has it, not "the last chunk"
        if chunk.usage_metadata is not None:
            call["response"] = chunk
print()
print(open("calls.jsonl").read().splitlines()[-1])
Example output · illustrative2 lines
Red, blue and yellow are the three primary colours.
{"ts": "2026-11-04T09:20:11+00:00", "call_id": "b1c2d3e4f5a64b7c8d9e0f1a2b3c4d5e", "env": "dev", "feature": "faq", "customer": null, "kind": "call", "provider": "gemini", "model": "gemini-3.8-flash", "served_model": "gemini-3.8-flash", "api": "generate_content", "request_id": "pQ2sT7vXyZaBcD4eFgH1jA", "trace_id": null, "prefix": null, "tier": "standard", "batch": false, "regional": false, "uncached_input_tokens": 9, "cached_input_tokens": 0, "cache_write_tokens": 0, "total_input_tokens": 9, "output_tokens": 171, "reasoning_tokens": 160, "finish_reason": "STOP", "attempts": null, "storage_token_hours": null, "cost_usd": 0.000648, "cost_source": "computed", "price_version": "2026-11-04", "latency_ms": 1432, "status": "ok"}

This sample is hosted-only, because Gemini has no local stand-in. If a stream ever reported its usage as 0 and 0, the tracker would record an unknown cost instead of a free call: that is the all-zero guard from 5.2 doing its job. For Interactions, pass the interaction carried by the interaction.completed event to the tracker (5.8 shows an Interaction). For OpenRouter, the usage chunk (with cost) arrives last, just before [DONE], and the openai stream helpers hand it back in the final completion (lesson 03.3).

5.5 The same tracker on hosted providers#

On real providers, the code is the same with default clients and the real price table. Save as s5_tracker_hosted.py:

python
"""The cost tracker on real calls to all four providers (needs keys in .env)."""
import os

import anthropic
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import OpenAI

from cost_tracker import CostTracker
from prices import PriceTable

load_dotenv()
tracker = CostTracker(PriceTable.load(), "calls.jsonl", env=os.getenv("APP_ENV", "dev"))
Q = "In one sentence, what is a token?"

oai = OpenAI()
with tracker.track(provider="openai", model="gpt-6-luna", feature="faq", customer_id="cust_42") as call:
    call["response"] = oai.responses.create(model="gpt-6-luna", input=Q, max_output_tokens=300,
                                            reasoning={"effort": "none"})

claude = anthropic.Anthropic()
with tracker.track(provider="anthropic", model="claude-haiku-5-5", feature="faq", customer_id="cust_42") as call:
    call["response"] = claude.messages.create(model="claude-haiku-5-5", max_tokens=300,
                                              messages=[{"role": "user", "content": Q}])

gem = genai.Client()
with tracker.track(provider="gemini", model="gemini-3.8-flash", feature="faq", customer_id="cust_7") as call:
    call["response"] = gem.models.generate_content(
        model="gemini-3.8-flash", contents=Q, config=types.GenerateContentConfig(max_output_tokens=300))

router = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"],
                default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "Cost demo"})
with tracker.track(provider="openrouter", model="anthropic/claude-haiku-5.5", feature="faq") as call:
    call["response"] = router.chat.completions.create(
        model="anthropic/claude-haiku-5.5", max_tokens=300, messages=[{"role": "user", "content": Q}])

print(open("calls.jsonl").read())
Example output · illustrative4 lines
{"ts": "2026-11-04T09:12:31+00:00", "call_id": "5d0c1f6e9b2a4c33a0e1f2d3c4b5a697", "env": "dev", "feature": "faq", "customer": "4cef7bf5228005e6", "kind": "call", "provider": "openai", "model": "gpt-6-luna", "served_model": "gpt-6-luna-2026-09-22", "api": "responses", "request_id": "resp_0a4f2c9e7b1d3e5f", "trace_id": null, "prefix": null, "tier": "standard", "batch": false, "regional": false, "uncached_input_tokens": 15, "cached_input_tokens": 0, "cache_write_tokens": 0, "total_input_tokens": 15, "output_tokens": 24, "reasoning_tokens": 0, "finish_reason": "completed", "attempts": null, "storage_token_hours": null, "cost_usd": 1.35e-05, "cost_source": "computed", "price_version": "2026-11-04", "latency_ms": 612, "status": "ok"}
{"ts": "2026-11-04T09:12:32+00:00", "call_id": "8e2b7a1c0d4f4e6a9b3c5d7e9f1a2b3c", "env": "dev", "feature": "faq", "customer": "4cef7bf5228005e6", "kind": "call", "provider": "anthropic", "model": "claude-haiku-5-5", "served_model": "claude-haiku-5-5", "api": "messages", "request_id": "msg_01H8xVqK3tYp2LmN4rS6wZ9a", "trace_id": null, "prefix": null, "tier": "standard", "batch": false, "regional": false, "uncached_input_tokens": 16, "cached_input_tokens": 0, "cache_write_tokens": 0, "total_input_tokens": 16, "output_tokens": 31, "reasoning_tokens": 0, "finish_reason": "end_turn", "attempts": null, "storage_token_hours": null, "cost_usd": 1.71e-05, "cost_source": "computed", "price_version": "2026-11-04", "latency_ms": 734, "status": "ok"}
{"ts": "2026-11-04T09:12:33+00:00", "call_id": "1f3e5d7c9b0a4c2e8d6f4a2b0c9e7d5f", "env": "dev", "feature": "faq", "customer": "b073f3ee5adefa74", "kind": "call", "provider": "gemini", "model": "gemini-3.8-flash", "served_model": "gemini-3.8-flash", "api": "generate_content", "request_id": "kXQpZ6fNLuWv0sYPq9yA2Q", "trace_id": null, "prefix": null, "tier": "standard", "batch": false, "regional": false, "uncached_input_tokens": 10, "cached_input_tokens": 0, "cache_write_tokens": 0, "total_input_tokens": 10, "output_tokens": 233, "reasoning_tokens": 205, "finish_reason": "STOP", "attempts": null, "storage_token_hours": null, "cost_usd": 0.000881, "cost_source": "computed", "price_version": "2026-11-04", "latency_ms": 1820, "status": "ok"}
{"ts": "2026-11-04T09:12:34+00:00", "call_id": "6a8c0e2f4b6d4a8c9e1f3a5b7c9d1e3f", "env": "dev", "feature": "faq", "customer": null, "kind": "call", "provider": "openrouter", "model": "anthropic/claude-haiku-5.5", "served_model": "anthropic/claude-haiku-5.5", "api": "chat", "request_id": "gen-1793787154-Qm3vR8tYx2LpN6sK", "trace_id": null, "prefix": null, "tier": "standard", "batch": false, "regional": false, "uncached_input_tokens": 16, "cached_input_tokens": 0, "cache_write_tokens": 0, "total_input_tokens": 16, "output_tokens": 29, "reasoning_tokens": 0, "finish_reason": "stop", "attempts": null, "storage_token_hours": null, "cost_usd": 1.61e-05, "cost_source": "provider", "price_version": "2026-11-04", "latency_ms": 905, "status": "ok"}

Against the stand-in, the OpenAI, Anthropic and OpenRouter-shaped calls run end to end (the OpenRouter-shaped call records an unknown cost there, because Ollama returns no cost); the Gemini call is hosted-only, because Gemini has no local stand-in. In the illustration, notice the Gemini line: 28 visible output tokens and 205 thinking tokens, all billed as output. Notice the OpenAI line too: its served_model is a dated snapshot of the alias you asked for. A dashboard that summed candidates_token_count would show an eighth of that call's output cost.

5.6 Attribution beyond your own logs#

Your tracker is one half of attribution; the providers can carry the other half, which helps when you reconcile (Part 13) and when you need their support:

  • Separate projects, workspaces and keys per environment and per major feature. The providers' usage and cost APIs group by project (OpenAI), workspace and API key (Anthropic) and key (OpenRouter), so this split is free attribution at the provider's end (lesson 03.1).
  • Request metadata: OpenAI's safety_identifier and metadata, Anthropic's metadata.user_id, Gemini's labels (in GenerateContentConfig; lesson 03.2 covers what each is for). Do not reuse the hash you log: derive the provider-facing ID with the same keyed hash but the purpose "llm-abuse-v1" (end_user_id() in 03.2, 10.3). Then a provider's abuse report can't be matched to your cost records by anyone who has both.
  • OpenRouter's session_id groups a conversation's requests in its logs and doubles as the sticky-routing key (9.2).
  • OpenAI's prompt_cache_key keeps cache accounting separate per tenant on GPT-5.6 and later (7.2).

5.7 Answering the questions: spend by feature, customer and day#

Recording is only half of the promise at the top of this lesson. The questions people actually ask are "which feature, which customer, which day?", "how much of this is guesswork?" and "what does a bad request cost?". Each is a few lines over the tracker's JSON Lines, so you don't need a warehouse to start. This report uses only the standard library, and runs on the fixture log that 10.2 generates (run make_fixture_log.py first, or point LOG at your own calls.jsonl: the field names are the tracker's). If you'd rather write SQL, the same file loads straight into DuckDB (SELECT feature, sum(cost_usd) FROM 'calls.jsonl' GROUP BY 1) or pandas.read_json(..., lines=True). Save as s5_report.py:

python
"""Answer the cost questions from the tracker's log: spend by feature, customer and day, the share of
unknown costs, and p95 cost per request. Standard library only; run make_fixture_log.py first.
Point LOG at your own calls.jsonl and nothing else changes: the field names are the tracker's."""
import json
import statistics
from collections import defaultdict

LOG = "usage_log.jsonl"
rows = [json.loads(line) for line in open(LOG)]

known = [r for r in rows if r["cost_usd"] is not None]
print(f"{len(rows)} records, {len(rows) - len(known)} with unknown cost "
      f"({(len(rows) - len(known)) / len(rows):.1%}: alert above 1%)")


def spend_by(key) -> dict[str, float]:
    out: dict[str, float] = defaultdict(float)
    for r in known:
        out[key(r)] += r["cost_usd"]
    return dict(sorted(out.items(), key=lambda kv: -kv[1]))


print("\nspend by feature (calls and cache storage together)")
for feature, usd in spend_by(lambda r: r["feature"]).items():
    print(f"  {feature:18s} ${usd:8.2f}")

print("\nwhich customer costs the most? (hashed IDs; top 5)")
for customer, usd in list(spend_by(lambda r: r["customer"] or "(no customer)").items())[:5]:
    print(f"  {customer:18s} ${usd:8.2f}")

print("\nspend by day (UTC)")
for day, usd in sorted(spend_by(lambda r: r["ts"][:10]).items()):
    print(f"  {day}  ${usd:8.2f}")

print("\np95 cost per request, by feature")
per_feature: dict[str, list[float]] = defaultdict(list)
for r in known:
    if r["kind"] == "call":
        per_feature[r["feature"]].append(r["cost_usd"])
for feature, costs in per_feature.items():
    p95 = statistics.quantiles(costs, n=20)[-1]
    print(f"  {feature:18s} p95 ${p95:.5f}   mean ${statistics.mean(costs):.5f}")

Output (on the fixture log; the customer IDs are the hashes the tracker writes, so the report never shows an email):

text
575 records, 5 with unknown cost (0.9%: alert above 1%)

spend by feature (calls and cache storage together)
  contract-qa        $    4.25
  support-bot        $    1.90
  manual-qa          $    1.02
  faq                $    0.54
  nightly-summaries  $    0.08

which customer costs the most? (hashed IDs; top 5)
  07d5a0582d1674a3   $    1.12
  b219050a350ea60b   $    1.11
  (no customer)      $    0.88
  0cff9538db82ba5c   $    0.79
  4850be2f99f2b6d5   $    0.70

spend by day (UTC)
  2026-11-03  $    7.80

p95 cost per request, by feature
  nightly-summaries  p95 $0.00401   mean $0.00401
  support-bot        p95 $0.02528   mean $0.00646
  faq                p95 $0.00298   mean $0.00272
  contract-qa        p95 $0.15966   mean $0.10618
  manual-qa          p95 $0.01611   mean $0.01578

What each block answers:

  • Unknown share. Five of 575 records have no cost (the timed-out calls), 0.9%: just under the 1% alert line in 12.5. The share is the first thing to check, because every other number in the report excludes those records.
  • Spend by feature includes the explicit cache's storage next to its calls, which is why manual-qa costs what it does (8.3).
  • Which customer costs the most is a group-by on the hashed ID. To turn a hash back into a name, hash your customer list with the same key and join; nobody without the key can.
  • By day has one row here because the fixture is one day; on a real log it's the trend line the alerts in 12.5 watch.
  • p95 cost per request shows what the average hides: contract-qa's mean is $0.106 but one request in twenty costs $0.16 or more. Pick the output cap (12.1) and the per-request budget (12.2) from this, not from the mean.

5.8 Batch, regional and the other response types#

Three things a plain record(response=...) can't know, and one thing it can read from objects you may not have met yet. Save as s5_tracker_modes.py; every object is built with the SDK's own types, so it runs offline:

python
"""The tracker on responses that need a hint: batch results, regional calls, BetaMessage, Interactions
and OpenRouter's Responses API. Objects are built with the SDKs' own types: no network, no key."""
import tempfile
from pathlib import Path

from anthropic.types import Message
from anthropic.types.beta import BetaMessage
from google.genai.interactions import Interaction
from openai.types.chat import ChatCompletion
from openai.types.responses import Response

from cost_tracker import CostTracker
from prices import PriceTable

tracker = CostTracker(PriceTable.load(), Path(tempfile.mkdtemp()) / "calls.jsonl", env="demo")


def show(label: str, rec) -> None:
    print(f"{label:34s} api={rec.api:16s} tier={rec.tier:8s} uncached={rec.uncached_input_tokens:>6} "
          f"total_in={rec.total_input_tokens:>6} cost=${rec.cost_usd:.6f} ({rec.cost_source})")


claude_body = {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-sonnet-5-5", "content": [],
               "stop_reason": "end_turn", "usage": {"input_tokens": 1_000, "output_tokens": 500,
                                                    "cache_read_input_tokens": 20_000, "cache_creation_input_tokens": 0}}
# An Anthropic batch result's message says nothing about batching: YOUR code knows, so you say so
msg = Message.model_validate(claude_body)
show("anthropic, interactive", tracker.record(provider="anthropic", model="claude-sonnet-5-5", response=msg, feature="demo"))
show("anthropic, a batch result", tracker.record(provider="anthropic", model="claude-sonnet-5-5", response=msg,
                                                 feature="demo", batch=True))
# client.beta.messages.create returns a BetaMessage, a different class with the same usage fields
beta = BetaMessage.model_validate(claude_body)
show("anthropic, BetaMessage", tracker.record(provider="anthropic", model="claude-sonnet-5-5", response=beta, feature="demo"))

# A data-residency endpoint costs 10% more on OpenAI, and the response doesn't mention it
chat = ChatCompletion.model_validate({
    "id": "chatcmpl-1", "object": "chat.completion", "created": 1, "model": "gpt-6-luna", "choices": [],
    "usage": {"prompt_tokens": 20_000, "completion_tokens": 500, "total_tokens": 20_500}})
show("openai chat, regional endpoint", tracker.record(provider="openai", model="gpt-6-luna", response=chat,
                                                      feature="demo", regional=True))

# Gemini Interactions: the completed interaction goes in as it is (usage, model and tier are read from it)
interaction = Interaction.model_validate({
    "id": "int_1", "status": "completed", "model": "gemini-3.8-flash", "service_tier": "standard",
    "created": "2026-11-04T09:00:00Z", "updated": "2026-11-04T09:00:01Z",
    "usage": {"total_input_tokens": 5_000, "total_cached_tokens": 4_000, "total_output_tokens": 300,
              "total_thought_tokens": 1_200, "total_tokens": 6_500}})
show("gemini, Interactions", tracker.record(provider="gemini", model="gemini-3.8-flash", response=interaction, feature="demo"))

# OpenRouter's Responses API: same Response class as OpenAI's, plus the OpenRouter-only cost
orr = Response.model_validate({
    "id": "gen-1", "object": "response", "created_at": 1, "status": "completed", "model": "anthropic/claude-haiku-5.5",
    "output": [], "parallel_tool_calls": True, "tool_choice": "auto", "tools": [],
    "usage": {"input_tokens": 10_339, "output_tokens": 60, "total_tokens": 10_399,
              "input_tokens_details": {"cached_tokens": 10_318, "cache_write_tokens": 0},
              "output_tokens_details": {"reasoning_tokens": 0}, "cost": 0.00013508}})
show("openrouter, Responses API", tracker.record(provider="openrouter", model="anthropic/claude-haiku-5.5", response=orr, feature="demo"))
Output6 lines
anthropic, interactive             api=messages         tier=standard uncached=  1000 total_in= 21000 cost=$0.009000 (computed)
anthropic, a batch result          api=messages         tier=batch    uncached=  1000 total_in= 21000 cost=$0.004500 (computed)
anthropic, BetaMessage             api=messages         tier=standard uncached=  1000 total_in= 21000 cost=$0.009000 (computed)
openai chat, regional endpoint     api=chat             tier=standard uncached= 20000 total_in= 20000 cost=$0.002475 (computed)
gemini, Interactions               api=interactions     tier=standard uncached=  1000 total_in=  5000 cost=$0.006675 (computed)
openrouter, Responses API          api=responses        tier=standard uncached=    21 total_in= 10339 cost=$0.000135 (provider)
  • A batch result is a normal Message. The body has no marker, so the second line passes batch=True and the tracker halves the price (Anthropic's batch results can carry service_tier: "batch" in usage, but don't count on it for the other providers). Lesson 03.9 says "your cost tracker has to know from context": this is how. batch=True also overrides fast mode, which isn't offered in batches. regional=True adds the 10% data-residency uplift, and tier= overrides the tier for the cases where you know better than the response (a Gemini request you sent with service_tier set, for example).
  • client.beta.messages.create returns a BetaMessage, a different class from Message with the same usage fields. Anthropic's own diagnostics and admin examples use the beta client, so the tracker accepts both.
  • A Gemini Interaction goes in whole: usage, model and service_tier are read from it, and request_id is the interaction's id.
  • OpenRouter's Responses-compatible API returns the same Response class as OpenAI's, so the tracker tells them apart by the provider you say it came from, and reads the OpenRouter-only cost from usage.model_extra.

The tracker has its own tests, one per response type, and they print real output. Save as test_cost_tracker.py and run it with uv run pytest -v --no-header test_cost_tracker.py:

python
"""Record one object of every supported type with CostTracker, offline. Run: pytest -v test_cost_tracker.py"""
import datetime as dt
import json
from pathlib import Path

import pytest
from anthropic.types import Message
from anthropic.types.beta import BetaMessage
from google.genai import types as gtypes
from google.genai.interactions import Interaction
from openai.types.chat import ChatCompletion
from openai.types.responses import Response

from cost_tracker import CostTracker
from prices import PriceTable


@pytest.fixture
def tracker(tmp_path: Path) -> CostTracker:
    return CostTracker(PriceTable.load("prices.yaml"), tmp_path / "calls.jsonl", env="test")


def lines(t: CostTracker) -> list[dict]:
    return [json.loads(x) for x in t.sink.read_text().splitlines()]


def responses_object(model: str, status: str = "completed", **extra_usage) -> Response:
    usage = {"input_tokens": 12_000, "output_tokens": 900, "total_tokens": 12_900,
             "input_tokens_details": {"cached_tokens": 4_000, "cache_write_tokens": 7_000},
             "output_tokens_details": {"reasoning_tokens": 600}, **extra_usage}
    body = {"id": "resp_1", "object": "response", "created_at": 1793750000, "status": status, "model": model,
            "service_tier": "default", "output": [], "parallel_tool_calls": True, "tool_choice": "auto",
            "tools": [], "usage": usage}
    if status == "incomplete":
        body["incomplete_details"] = {"reason": "max_output_tokens"}
    return Response.model_validate(body)


def chat_object(model: str, **extra_usage) -> ChatCompletion:
    return ChatCompletion.model_validate({
        "id": "chatcmpl-1", "object": "chat.completion", "created": 1793750000, "model": model,
        "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "ok"}}],
        "usage": {"prompt_tokens": 10_339, "completion_tokens": 60, "total_tokens": 10_399,
                  "prompt_tokens_details": {"cached_tokens": 10_318, "cache_write_tokens": 0}, **extra_usage}})


def claude_usage() -> dict:
    return {"input_tokens": 10_000, "cache_read_input_tokens": 40_000, "cache_creation_input_tokens": 0,
            "output_tokens": 15_000}


def test_openai_responses(tracker):
    rec = tracker.record(provider="openai", model="gpt-6.1-sol", response=responses_object("gpt-6.1-sol"),
                         feature="t")
    assert (rec.uncached_input_tokens, rec.total_input_tokens, rec.api) == (1_000, 12_000, "responses")
    assert rec.cost_source == "computed" and rec.status == "ok"


def test_openai_incomplete_response_is_billed_and_marked_truncated(tracker):
    rec = tracker.record(provider="openai", model="gpt-6.1-sol", feature="t",
                         response=responses_object("gpt-6.1-sol", status="incomplete"))
    assert rec.cost_usd is not None and rec.finish_reason == "max_output_tokens"
    assert rec.status == "truncated"


def test_openai_chat(tracker):
    rec = tracker.record(provider="openai", model="gpt-6-luna", response=chat_object("gpt-6-luna"), feature="t")
    assert rec.api == "chat" and rec.finish_reason == "stop" and rec.cost_usd is not None


def test_openrouter_chat_uses_the_reported_cost(tracker):
    rec = tracker.record(provider="openrouter", model="anthropic/claude-haiku-5.5", feature="t",
                         response=chat_object("anthropic/claude-haiku-5.5", cost=0.00013508))
    assert (rec.cost_usd, rec.cost_source, rec.api) == (0.00013508, "provider", "chat")


def test_openrouter_responses_api(tracker):
    resp = responses_object("anthropic/claude-haiku-5.5", cost=0.0021, is_byok=False)
    rec = tracker.record(provider="openrouter", model="anthropic/claude-haiku-5.5", response=resp, feature="t")
    assert (rec.cost_usd, rec.cost_source, rec.api) == (0.0021, "provider", "responses")
    assert rec.uncached_input_tokens == 1_000


def test_anthropic_message(tracker):
    msg = Message.model_validate({"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-opus-5-5",
                                  "content": [], "stop_reason": "end_turn", "usage": claude_usage()})
    rec = tracker.record(provider="anthropic", model="claude-opus-5-5", response=msg, feature="t")
    assert rec.cost_usd == pytest.approx(0.348) and rec.total_input_tokens == 50_000


def test_anthropic_beta_message(tracker):
    msg = BetaMessage.model_validate({"id": "msg_2", "type": "message", "role": "assistant",
                                      "model": "claude-opus-5-5", "content": [], "stop_reason": "max_tokens",
                                      "usage": claude_usage()})
    rec = tracker.record(provider="anthropic", model="claude-opus-5-5", response=msg, feature="t")
    assert rec.cost_usd == pytest.approx(0.348) and rec.status == "truncated"


def test_gemini_generate_content(tracker):
    resp = gtypes.GenerateContentResponse(
        response_id="r1", model_version="gemini-3.8-flash",
        candidates=[gtypes.Candidate(finish_reason=gtypes.FinishReason.STOP)],
        usage_metadata=gtypes.GenerateContentResponseUsageMetadata(
            prompt_token_count=5_000, cached_content_token_count=4_000,
            candidates_token_count=300, thoughts_token_count=1_200))
    rec = tracker.record(provider="gemini", model="gemini-3.8-flash", response=resp, feature="t",
                         tier="priority")
    assert (rec.uncached_input_tokens, rec.output_tokens, rec.tier) == (1_000, 1_500, "priority")


def test_gemini_interaction(tracker):
    inter = Interaction.model_validate({
        "id": "int_1", "status": "completed", "model": "gemini-3.8-flash", "service_tier": "standard",
        "created": "2026-11-04T09:00:00Z", "updated": "2026-11-04T09:00:01Z",
        "usage": {"total_input_tokens": 5_000, "total_cached_tokens": 4_000, "total_output_tokens": 300,
                  "total_thought_tokens": 1_200, "total_tokens": 6_500}})
    rec = tracker.record(provider="gemini", model="gemini-3.8-flash", response=inter, feature="t")
    assert (rec.api, rec.uncached_input_tokens, rec.cached_input_tokens, rec.output_tokens) == \
        ("interactions", 1_000, 4_000, 1_500)


def test_batch_and_regional_flags_come_from_your_code(tracker):
    resp = chat_object("gpt-6-luna")
    plain = tracker.record(provider="openai", model="gpt-6-luna", response=resp, feature="t")
    batch = tracker.record(provider="openai", model="gpt-6-luna", response=resp, feature="t", batch=True)
    regional = tracker.record(provider="openai", model="gpt-6-luna", response=resp, feature="t", regional=True)
    assert batch.cost_usd == pytest.approx(plain.cost_usd * 0.5) and batch.tier == "batch" and batch.batch
    assert regional.cost_usd == pytest.approx(plain.cost_usd * 1.1) and regional.regional


def test_unreadable_response_is_recorded_as_unknown_not_zero(tracker):
    rec = tracker.record(provider="openai", model="gpt-6-luna", response={"not": "a response"}, feature="t")
    assert rec.cost_usd is None and rec.cost_source == "unknown"


def test_failed_call_is_recorded(tracker):
    with pytest.raises(RuntimeError):
        with tracker.track(provider="openai", model="gpt-6-luna", feature="t"):
            raise RuntimeError("boom")
    assert lines(tracker)[0]["status"] == "error:RuntimeError" and lines(tracker)[0]["cost_usd"] is None


def test_cache_storage_event(tracker):
    utc = dt.timezone.utc
    rec = tracker.record_cache_storage(provider="gemini", model="gemini-3.8-flash", cache_name="cachedContents/x",
                                       tokens=200_000, created=dt.datetime(2026, 11, 3, 9, tzinfo=utc),
                                       deleted=dt.datetime(2026, 11, 3, 17, tzinfo=utc), feature="manual-qa")
    assert rec.kind == "cache_storage" and rec.cost_usd == pytest.approx(0.2 * 8 * 0.50)


def test_all_zero_usage_is_unknown_not_free(tracker):
    # Some proxies and some stream chunks report 0/0: a successful call never has zero tokens
    resp = gtypes.GenerateContentResponse(usage_metadata=gtypes.GenerateContentResponseUsageMetadata(
        prompt_token_count=0, candidates_token_count=0))
    rec = tracker.record(provider="gemini", model="gemini-3.8-flash", response=resp, feature="t")
    assert rec.cost_usd is None and rec.cost_source == "unknown"


def test_missing_hash_key_fails_closed_outside_dev(tmp_path: Path, monkeypatch):
    monkeypatch.delenv("USER_ID_PEPPER", raising=False)
    with pytest.raises(ValueError, match="USER_ID_PEPPER"):
        CostTracker(PriceTable.load("prices.yaml"), tmp_path / "calls.jsonl", env="prod")
    # a key from the environment, or passed in, is accepted and gives stable hashes
    monkeypatch.setenv("USER_ID_PEPPER", "from-secret-store")
    a = CostTracker(PriceTable.load("prices.yaml"), tmp_path / "a.jsonl", env="prod")
    b = CostTracker(PriceTable.load("prices.yaml"), tmp_path / "b.jsonl", env="prod")
    assert a.customer_hash("cust_42") == b.customer_hash("cust_42")


def test_dev_without_key_gets_a_random_per_process_key(tmp_path: Path, monkeypatch):
    monkeypatch.delenv("USER_ID_PEPPER", raising=False)
    a = CostTracker(PriceTable.load("prices.yaml"), tmp_path / "a.jsonl", env="dev")
    b = CostTracker(PriceTable.load("prices.yaml"), tmp_path / "b.jsonl", env="dev")
    assert a.customer_hash("cust_42") != b.customer_hash("cust_42")      # no shared, guessable fallback
    assert a.customer_hash("cust_42") == a.customer_hash("cust_42")      # stable within one process
    assert a.customer_hash(None) is None
Output · offline; the percentages and ordering are pytest's own21 lines
============================= test session starts ==============================
collecting ... collected 16 items

test_cost_tracker.py::test_openai_responses PASSED                       [  6%]
test_cost_tracker.py::test_openai_incomplete_response_is_billed_and_marked_truncated PASSED [ 12%]
test_cost_tracker.py::test_openai_chat PASSED                            [ 18%]
test_cost_tracker.py::test_openrouter_chat_uses_the_reported_cost PASSED [ 25%]
test_cost_tracker.py::test_openrouter_responses_api PASSED               [ 31%]
test_cost_tracker.py::test_anthropic_message PASSED                      [ 37%]
test_cost_tracker.py::test_anthropic_beta_message PASSED                 [ 43%]
test_cost_tracker.py::test_gemini_generate_content PASSED                [ 50%]
test_cost_tracker.py::test_gemini_interaction PASSED                     [ 56%]
test_cost_tracker.py::test_batch_and_regional_flags_come_from_your_code PASSED [ 62%]
test_cost_tracker.py::test_unreadable_response_is_recorded_as_unknown_not_zero PASSED [ 68%]
test_cost_tracker.py::test_failed_call_is_recorded PASSED                [ 75%]
test_cost_tracker.py::test_cache_storage_event PASSED                    [ 81%]
test_cost_tracker.py::test_all_zero_usage_is_unknown_not_free PASSED     [ 87%]
test_cost_tracker.py::test_missing_hash_key_fails_closed_outside_dev PASSED [ 93%]
test_cost_tracker.py::test_dev_without_key_gets_a_random_per_process_key PASSED [100%]

============================== 16 passed ==============================

Part 6: Anthropic prompt caching in depth#

02.7, 7.2 explained why caching reuses only an identical prefix, 7.3 compared the four providers, and 7.4 gave the design rules. The next four parts are the APIs themselves, every knob, provider by provider. Anthropic comes first because it's the most explicit: nothing is cached unless you ask, and the API tells you exactly what it wrote and read.

6.1 Two ways to turn it on#

Anthropic's caching is opt-in, with a cache_control object, {"type": "ephemeral"} (the only type), optionally with "ttl": "5m" or "1h":

  • Automatic caching: one cache_control at the top level of the request (the SDK's messages.create(..., cache_control=...) parameter). The API puts the breakpoint on the last cacheable block and moves it forward as the conversation grows. Anthropic recommends it as the starting point for multi-turn chats.
  • Explicit breakpoints: cache_control on individual blocks: a tool definition, a system text block, or a content block in messages (text, image, document, tool_use, tool_result). Use these when parts of the prompt change at different rates, or when the last block changes on every request.

You can combine them: up to 4 breakpoints per request, and automatic caching uses one of the four slots. The edge cases, from Anthropic's prompt-caching page:

  • If the last block already has an explicit cache_control with the same TTL, automatic caching does nothing extra; with a different TTL, the API returns 400.
  • With 4 explicit breakpoints already, a top-level cache_control returns 400 ("no slots left for automatic caching").
  • If the last block can't be a breakpoint, the API "silently walks backward to find the nearest eligible block", and skips caching if there's none.
  • Can't be cached directly: thinking blocks (they're cached as part of earlier assistant turns, and count as input when read), sub-content such as citations (cache the document block instead), and empty text blocks.

The simplest correct use, for a growing conversation. Save as s6_auto_chat.py:

python
"""Anthropic automatic caching for a growing chat: one top-level cache_control, nothing else."""
import anthropic
from anthropic.types import MessageParam
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic()
SYSTEM = "You are Acme's onboarding coach.\n" + "\n".join(
    f"Guideline {i}: explain step {i} of the setup with one concrete example." for i in range(120))

history: list[MessageParam] = []
for turn, question in enumerate(["How do I start?", "And after that?", "What if step 3 fails?"], 1):
    history.append({"role": "user", "content": question})
    msg = client.messages.create(
        model="claude-haiku-5-5", max_tokens=400, system=SYSTEM, messages=history,
        cache_control={"type": "ephemeral"},     # breakpoint moves to the last cacheable block itself
    )
    u = msg.usage
    print(f"turn {turn}: read={u.cache_read_input_tokens or 0:>5} written={u.cache_creation_input_tokens or 0:>5} "
          f"uncached={u.input_tokens:>3} out={u.output_tokens}")
    history.append({"role": "assistant", "content": msg.content})   # append-only history
Example output · illustrative3 lines
turn 1: read=    0 written= 2131 uncached=  3 out=212
turn 2: read= 2131 written=  227 uncached=  3 out=188
turn 3: read= 2358 written=  205 uncached=  3 out=240

Each turn reads everything up to the previous turn and writes only the new assistant reply and user message. On the stand-in the sample runs, but every cache field reads 0: Ollama doesn't cache (prompt caching is not supported locally).

6.2 Where breakpoints go: writes, reads and the 20-block lookback#

Anthropic's documentation states three rules that explain almost every surprising miss:

  1. Writes happen only at breakpoints. A breakpoint writes one cache entry: a hash of the whole prefix up to and including that block. Nothing is written for earlier positions.
  2. Reads look backwards for earlier writes. The API computes the prefix hash at your breakpoint; if no entry matches, it walks back one block at a time, looking for a position where an earlier request wrote an entry. It isn't looking for content that happens to be stable.
  3. The lookback is 20 blocks, counting the breakpoint itself. On the Claude API, a run of consecutive tool_use blocks counts as one position, and so does a run of consecutive tool_result blocks.

Two consequences:

  • Never put the breakpoint on a block that changes every request (the user's question, a block with a timestamp). Each request writes a new entry keyed to its own unique block, and none is ever read. Anthropic's "common mistake" example is exactly this. Put it on the last block that's identical across the requests that should share the cache. This is also why automatic caching is wrong for "same document, different question" traffic: its breakpoint lands on the question (02.7, 7.3 shows the fix).
  • Long agent turns can outrun the lookback. If one turn adds 20 or more blocks, the previous turn's entry falls outside the window and the next request misses. Add a second breakpoint earlier in the conversation so an entry already exists within reach.

Here is the lookback as a picture: the previous request wrote entries at blocks 4 and 12, this request adds 22 blocks and puts its breakpoint on block 26, and the window reaches back 20 positions, to block 7.

flowchart LR
    subgraph before ["Written by earlier requests"]
        E1["entry at block 4"]
        E2["entry at block 12<br/>(a second breakpoint)"]
    end
    subgraph req ["This request: 26 blocks, breakpoint on block 26"]
        W["Lookback window:<br/>blocks 7 to 26 (20 positions)"]
    end
    W -. "block 4 is outside the window: not found" .-> E1
    W == "block 12 is inside the window: HIT" ==> E2

The entry at block 4 is out of reach, so without the second breakpoint at block 12 this request would miss entirely and rewrite everything.

Breakpoints themselves cost nothing: you pay for what's written and read, not for the markers.

6.3 Lifetimes: 5 minutes, 1 hour, and mixing them#

"ttl": "5m" (default) "ttl": "1h"
Write price 1.25× base input 2× base input
Read price 0.1× (0.05× Opus/Sonnet 5.5, 0.025× Fable 5.2 and 5.1) the same
Refreshed Free, every time the entry is read the same
Use when Requests reuse the prefix more often than every 5 minutes Gaps of 5 to 60 minutes: a user who reads before replying, a long-running agent step, batches

Two details that matter in code:

  • The lifetime runs from the start of the request, not the end of its response. Anthropic's example: if a response takes 4 minutes to stream, the next request must start within about 1 minute of it finishing to reuse a 5-minute entry. Long generations are a reason to choose 1h.
  • The 1-hour cache also helps throughput, because cache reads don't count toward input-tokens-per-minute limits on most Claude models (02.7, 6.4).

Mixing lifetimes in one request is allowed, with one rule: entries with the longer TTL must come before shorter ones (all 1h breakpoints before any 5m breakpoint). The bill is then computed from three positions in the prompt:

  • A: the token count at the highest cache hit (0 if none);
  • B: the token count at the highest 1h breakpoint after A (or A, if none);
  • C: the token count at the last breakpoint.

You pay cache reads for A tokens, 1h writes for B − A, and 5m writes for C − B. For example, with tools and instructions cached for an hour (ending at token 800) and a document cached for 5 minutes (ending at token 9,600): on a cold request A = 0, B = 800, C = 9,600, so you pay 800 tokens of 1h writes and 8,800 of 5m writes. Ten minutes later the 5-minute entry has expired but the hour-long one hasn't: A = 800, B = 800, C = 9,600, so 800 reads and 8,800 5m writes again. usage.cache_creation reports the split.

flowchart LR
    subgraph cold ["Cold request: A = 0, B = 800, C = 9,600"]
        c1["tokens 1 to 800<br/>(A to B): 1h write"] --> c2["tokens 801 to 9,600<br/>(B to C): 5m write"]
    end
    subgraph later ["Ten minutes later: A = 800, B = 800, C = 9,600"]
        l1["tokens 1 to 800<br/>(0 to A): cache read"] --> l2["tokens 801 to 9,600<br/>(B to C): 5m write again"]
    end
    cold --> later

6.4 The minimum, and the silent no-op#

A prefix shorter than the model's minimum is not cached, and no error is returned. As of November 2026, on the Claude API: 512 tokens for Claude Fable 5.2, Mythos 5.2, Fable 5.1, Mythos 5.1, Opus 5.5, Opus 5, Sonnet 5.5, Fable 5, Mythos 5 and Haiku 5.5; 1,024 for Opus 4.8, Sonnet 5 and Sonnet 4.6; 2,048 for Opus 4.7; 4,096 for Opus 4.6, Opus 4.5 and Haiku 4.5. Bedrock publishes its own minimums, and for Opus 4.7 it lists 4,096 where Anthropic's table says 2,048 (a documented discrepancy, so check the platform you actually call). (The price table carries the minimum per model as min_cacheable_tokens, 4.2, and the analyser in 10.2 reads it from there.)

How to detect it: if both cache_creation_input_tokens and cache_read_input_tokens are 0 on a request that has a breakpoint, the prefix was too short (or the request had no cacheable blocks). Anthropic's advice: if your prompt falls just short of the minimum and is reused often, "expanding the cached content to reach the threshold is often worthwhile", because reads are so much cheaper than uncached input.

6.5 What invalidates what#

The cached prefix is ordered tools → system → messages, and a change at one level invalidates that level and everything after it:

flowchart LR
    T["tools<br/>(breakpoint 1)"] --> S["system<br/>(breakpoints 2-3)"] --> M["messages<br/>(breakpoint 4)"] --> Q["new user turn<br/>(uncached)"]
    X1["Change a tool definition"] -. "invalidates" .-> T
    X2["Toggle web search or citations,<br/>switch speed"] -. "invalidates" .-> S
    X3["Change tool_choice, add or remove<br/>an image, change thinking or effort"] -. "invalidates" .-> M

Anthropic's table, as of November 2026:

What changes Tools cache System cache Messages cache
Tool definitions (names, descriptions, parameters) ✘ ✘ ✘
Web search toggle, citations toggle ✓ ✘ ✘
speed (fast vs standard) ✓ ✘ ✘
tool_choice ✓ ✓ ✘
Adding or removing images anywhere ✓ ✓ ✘
Thinking parameters; output_config.effort model-specific model-specific ✘

Anthropic's full table has two more rows that depend on the model and on thinking: "Non-tool results passed to requests with thinking" and "Dropped thinking blocks" (a Claude 5.1 or later model's thinking block that isn't preserved changes the cached prefix from that block onward). They're covered with thinking in 6.9; the prompt-caching page has the whole table.

What the table means for code:

  • Tool definitions are the most expensive thing to change. Keep them byte-stable: same order, same descriptions, deterministic JSON (10.4). On models that support it, the inline-tools-2026-09-15 beta header (as of November 2026, in beta on the Claude API, Claude Platform on AWS and Claude Models on Google Cloud, Anthropic-managed; see Anthropic's mid-conversation messages page) lets you add or change a tool mid-conversation in a tool_addition block inside a system message, leaving tools (and the cache) untouched.
  • Don't edit the top-level system mid-conversation. On Claude Fable 5.2, Fable 5.1, Opus 5.5, Sonnet 5.5, Haiku 5.5 and some others (not Sonnet 5), you can append a {"role": "system"} message to messages instead, and "the cached prefix stays unchanged".
  • Keep tool_choice, thinking settings and effort constant within a conversation. Setting effort explicitly to the model's default is the same as omitting it, so that doesn't invalidate.

Here's the hierarchy in action, with three breakpoints (tools for an hour, the instructions for an hour, the policy document for 5 minutes) and the API's own cache diagnostics (6.8). Save as s6_anthropic_caching.py:

python
"""Anthropic prompt caching: explicit breakpoints with two lifetimes, then what invalidates what."""
import anthropic
from anthropic.types import Message, MessageParam, TextBlockParam, ToolChoiceParam, ToolParam
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic()
MODEL = "claude-haiku-5-5"

POLICY = "Acme returns policy.\n" + "\n".join(      # about 8,800 tokens of stable reference text
    f"Rule {i}: items in category {i % 9} may be returned within {14 + i % 30} days if unused."
    for i in range(400))


def tools(lookup_description: str) -> list[ToolParam]:
    return [
        {"name": "lookup_order", "description": lookup_description,
         "input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}},
                          "required": ["order_id"]}},
        {"name": "start_return", "description": "Open a return for an order.",
         "input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}},
                          "required": ["order_id"]},
         # Breakpoint 1, on the LAST tool: caches every tool definition. Longest TTL first.
         "cache_control": {"type": "ephemeral", "ttl": "1h"}},
    ]


SYSTEM: list[TextBlockParam] = [
    {"type": "text", "text": "You are Acme's returns assistant. Answer from the policy only.",
     "cache_control": {"type": "ephemeral", "ttl": "1h"}},      # breakpoint 2: rarely changes
    {"type": "text", "text": POLICY,
     "cache_control": {"type": "ephemeral"}},                   # breakpoint 3: 5-minute default
]


def ask(question: str, tool_list: list[ToolParam], choice: ToolChoiceParam,
        previous: Message | None) -> Message:
    messages: list[MessageParam] = [{"role": "user", "content": question}]
    msg = client.messages.create(
        model=MODEL, max_tokens=400, tools=tool_list, tool_choice=choice, system=SYSTEM,
        messages=messages,
        # Ask the API to compare this request with the previous one and explain any miss
        diagnostics={"previous_message_id": previous.id if previous else None},
    )
    u, cc = msg.usage, msg.usage.cache_creation
    reason = msg.diagnostics.cache_miss_reason if msg.diagnostics else None
    # The cache fields are Optional in the SDK types: treat a missing value as 0
    print(f"read={u.cache_read_input_tokens or 0:>6} write_5m={cc.ephemeral_5m_input_tokens if cc else 0:>6} "
          f"write_1h={cc.ephemeral_1h_input_tokens if cc else 0:>5} uncached={u.input_tokens:>3}  "
          f"diagnostics={reason.type if reason else None}")
    return msg


auto: ToolChoiceParam = {"type": "auto"}
base = tools("Look up an order by its ID.")
print("1. cold:              ", end=""); m = ask("Can I return shoes?", base, auto, None)
print("2. same prefix:       ", end=""); m = ask("Can I return a lamp?", base, auto, m)
print("3. tool_choice changed:", end=""); m = ask("Return ORD-7?", base, {"type": "any"}, m)
print("4. tool text changed: ", end=""); m = ask("Can I return a hat?",
                                                 tools("Look up an order by ID."), auto, m)
Example output · illustrative4 lines
1. cold:              read=     0 write_5m=  8846 write_1h=  742 uncached= 14  diagnostics=None
2. same prefix:       read=  9588 write_5m=     0 write_1h=    0 uncached= 14  diagnostics=None
3. tool_choice changed:read=  9588 write_5m=     0 write_1h=    0 uncached= 14  diagnostics=unavailable
4. tool text changed: read=     0 write_5m=  8846 write_1h=  742 uncached= 14  diagnostics=tools_changed

Reading it:

  • Request 1 wrote both lifetimes: 742 tokens (tool definitions, the tool-use system prompt and the instructions) at the 1h price, and 8,846 policy tokens at the 5m price.
  • Request 2 read all 9,588 at the cache-read price. Only the question's 14 tokens were uncached.
  • Request 3 changed tool_choice, which invalidates only message blocks; there's no breakpoint in messages here, so tools and system still hit. Diagnostics report unavailable, which Anthropic documents for exactly this case: model, system and tools match, but "another prompt-affecting request parameter (tool_choice, ...) differs".
  • Request 4 changed one word in a tool description, and everything was written again. Diagnostics name the cause: tools_changed.

On the stand-in, the sample runs end to end but every cache field reads 0 and diagnostics is None (caching and diagnostics are not supported locally).

6.6 Concurrency: warm the cache first#

The strategy for when and how often to warm (on deploy, before bursts) is in 11B.3, 2.4. This section is the API mechanics.

"A cache entry only becomes available after the first response starts. If you need cache hits for parallel requests, wait for the first response before sending subsequent requests." Fire 20 requests at a cold prefix in parallel and you pay for 20 cache writes, each at 1.25× or 2× the input price, and get no reads.

sequenceDiagram
    participant App
    participant API as Anthropic API
    Note over App,API: Cold, in parallel
    App->>API: request 1 (prefix P)
    App->>API: request 2 (prefix P)
    App->>API: request 3 (prefix P)
    API-->>App: 1 starts responding, writes P
    API-->>App: 2 starts responding, writes P again
    API-->>App: 3 starts responding, writes P again
    Note over App,API: Warm first, then parallel
    App->>API: pre-warm (max_tokens 0, prefix P)
    API-->>App: empty content, P written once
    App->>API: requests 1 to 3 (prefix P)
    API-->>App: all three read P at the cache-read price

The fix is a pre-warm request: send the shared prefix with max_tokens: 0. The API "reads your prompt into the model and writes the cache at any cache_control breakpoint, then returns immediately without generating any output": an empty content array, stop_reason: "max_tokens", a full usage block, and "zero output tokens are billed". The rules, from Anthropic's page:

  • Put the breakpoint on the shared prefix (system prompt or tools), not on the placeholder user message; use an explicit breakpoint, because automatic caching would key the entry to the placeholder. The placeholder can be any non-whitespace text.
  • Use the same thinking configuration and effort as the real requests, or you'll warm an entry they never hit.
  • max_tokens: 0 is rejected with stream: true, extended thinking (thinking.type: "enabled"), structured outputs (output_config.format), forced tool_choice, and inside Message Batches.
  • Re-warm before the TTL runs out (every few minutes for 5m), or use 1h. It replaces the older max_tokens: 1 trick.
  • For a batch job, use 1h rather than the 5-minute default. Pre-warming with max_tokens: 0 is rejected inside a batch, and a batch can take longer than 5 minutes, so a 5-minute entry would likely expire before most requests run. Anthropic's batch processing page recommends the 1-hour cache duration for batches with shared context. Hit rates are still best-effort (30 to 98 percent, per Anthropic). The lesson on batches is 03.9, 8.2.

Save as s6_cold_start.py:

python
"""Parallel requests sent before the first response starts all miss the cache. Warm it first."""
import asyncio

import anthropic
from anthropic.types import TextBlockParam, Usage
from dotenv import load_dotenv

load_dotenv()
client = anthropic.AsyncAnthropic()
MODEL = "claude-haiku-5-5"
CLAUSES = "\n".join(f"Clause {i}: delivery within {i % 20 + 1} days." for i in range(600))
QUESTIONS = [f"Summarize clause {i} in one line." for i in range(5)]


def system(version: str) -> list[TextBlockParam]:
    # A different version string = a different prefix, so runs A and B can't share a cache entry
    return [{"type": "text", "text": f"Acme supplier contract {version}.\n{CLAUSES}",
             "cache_control": {"type": "ephemeral"}}]


async def one(sys: list[TextBlockParam], question: str, max_tokens: int = 200) -> Usage:
    msg = await client.messages.create(model=MODEL, max_tokens=max_tokens, system=sys,
                                       messages=[{"role": "user", "content": question}])
    return msg.usage


def report(label: str, usages: list[Usage]) -> None:
    writes = sum(u.cache_creation_input_tokens or 0 for u in usages)
    reads = sum(u.cache_read_input_tokens or 0 for u in usages)
    out = sum(u.output_tokens for u in usages)
    print(f"{label:24s} cache writes={writes:>7,}  cache reads={reads:>7,}  output={out:>5,}")


async def main() -> None:
    # A. Everything at once on a cold cache: no entry exists until a response starts,
    #    so every request writes (and pays for) its own copy of the prefix
    a = system("v1")
    report("A. 5 parallel, cold:", await asyncio.gather(*(one(a, q) for q in QUESTIONS)))

    # B. Warm first. max_tokens=0 writes the cache and returns no output (no output tokens billed).
    #    The breakpoint is on the shared system prompt, not on the placeholder message.
    b = system("v2")
    report("B. pre-warm:", [await one(b, "warmup", max_tokens=0)])
    report("   then 5 parallel:", await asyncio.gather(*(one(b, q) for q in QUESTIONS)))


asyncio.run(main())
Example output · illustrative3 lines
A. 5 parallel, cold:     cache writes= 49,250  cache reads=      0  output=  612
B. pre-warm:             cache writes=  9,850  cache reads=      0  output=    0
   then 5 parallel:      cache writes=      0  cache reads= 49,250  output=  598

Run A paid for five copies of the same 9,850-token write. Run B paid for one, then five reads at a tenth of the input price. On Haiku 5.5 the difference is small in dollars; on Opus 5.5 with a 200,000-token prefix and 50 parallel workers, it's the difference between 50 writes at $5 per million tokens and 1 write plus 50 reads at $0.20.

Run against the stand-in, part A runs (with zero cache fields) and the pre-warm fails with a 400, "max_tokens is required and must be positive", because Ollama doesn't implement Anthropic's max_tokens: 0 (fails only locally).

6.7 Isolation, rate limits and retention#

  • Caches are isolated per workspace on the Claude API, Claude Platform on AWS and Microsoft Foundry (per organization on Bedrock and Google-managed Claude on Google Cloud). Two workspaces sending the same prompt each pay for their own writes. Separate workspaces are good for attribution and isolation; they cost you shared cache hits.
  • Cache reads don't count toward ITPM (input tokens per minute) on most Claude models; cache writes and uncached input do (02.7, 6.4; rate limits are lesson 03.8's subject). A high hit rate is also extra throughput.
  • You can't clear a cache. "Currently, there's no way to manually clear the cache." Entries expire after their lifetime of inactivity. If cached content must not be served again (a document that was withdrawn), change the prefix.
  • Retention: prompt caching is eligible for zero data retention. Only "KV cache representations and cryptographic hashes" are held, in memory, for the cache lifetime.
  • Caching doesn't change the answer. "The response you receive is identical to what you would get if prompt caching were not used."

6.8 Cache diagnostics#

When the hit rate drops, the usage fields say that the cache missed, not why. Cache diagnostics (stable, no beta header needed any more; the old cache-diagnosis-2026-04-07 header is accepted but not required) has the API compare the request with your previous one and report the first divergence:

  • Opt in on every turn with diagnostics={"previous_message_id": None} on the first request and {"previous_message_id": previous.id} after that. The SDK 2.4.0 accepts diagnostics on client.messages.create (Anthropic's own examples use client.beta.messages.create; both work). The API stores a fingerprint (hashes and token-count estimates, never prompt text) only for requests that include the object.
  • Read message.diagnostics: None means no divergence (or nothing to compare); cache_miss_reason None means the comparison was still running ("treat it as inconclusive"); otherwise cache_miss_reason.type is one of model_changed, system_changed, tools_changed, messages_changed (each with cache_missed_input_tokens, an estimate "derived from byte lengths before tokenization", not a billing number), previous_message_not_found or unavailable. With streaming, it arrives on message_start.
  • Combine it with usage: diagnostics None with a low cache_read_input_tokens means the request was the same but the entry had expired (shorten the gaps, or use 1h); a *_changed type with a low read count means fix that cause.
  • Limits: Claude API only (not Bedrock or Google-managed Claude), fingerprints expire after a short time, both requests must be in the same workspace, and it only reports the first divergence.

The sample in 6.5 threads diagnostics through every request. In production, turn it on in your staging environment's tests and on a sample of production traffic, and log cache_miss_reason.type next to the cost record.

6.9 Thinking and caching#

  • Changing the thinking configuration or effort invalidates message caches, and on some models the tool and system caches too, because "the thinking configuration is rendered into the prompt".
  • Thinking blocks are cached as part of earlier assistant turns (you can't put cache_control on them) and "count as input tokens when read from cache".
  • On Opus 4.5+, Sonnet 4.6+ and Haiku 5.5, earlier thinking blocks are kept when you add a new user message, so the cache stays valid; on older models they were stripped and the cache after them was lost. Pass thinking blocks back unchanged (02.8, 8.2).

Part 7: OpenAI prompt caching in depth#

Deep-dive

7.1 Automatic by default#

OpenAI caches automatically on supported models; you don't have to change anything for it to start. As of November 2026, per OpenAI's prompt-caching guide:

  • Minimum 1,024 tokens on GPT-5.6 and later ("varies by request settings for earlier models"). "Tokens in the OpenAI-provided hidden system content do not count toward this minimum."
  • Where the implicit breakpoint goes: on GPT-5.6 and later, in implicit mode (the default), "OpenAI places a breakpoint at the end of the latest eligible message". GPT-5.5 and GPT-5.5 Pro use implicit breakpoints "at regular 2,048-token intervals"; earlier models support only implicit caching, and report cached_tokens rounded down to a multiple of 128.
  • Writes cost money on GPT-5.6 and later, even when caching is automatic: 1.25× the input rate for the default 30-minute lifetime. A long prompt sent once and never again costs 25% more with caching on than off (7.6). Earlier models had no write charge.
  • Reads cost 0.1× the input rate on most current models, 0.05× on GPT-6.1 Sol and GPT-6.1 Terra.

That covers most applications. The rest of this part is the controls for when you need more: who shares a cache, where the prefix ends, how long it lives, and how to find out why it missed.

7.2 prompt_cache_key: routing before GPT-5.6, accounting after#

prompt_cache_key is a string you attach to a request (it "replaces the user field" for this purpose; lesson 03.2 covers user and safety_identifier). What it does depends on the model:

Models before GPT-5.6 GPT-5.6 and later
Purpose Routing: "Keys influence routing; they do not pin requests to a machine or guarantee a cache hit" Accounting and isolation: "OpenAI handles cache routing automatically; the key is not needed to optimize caching"
Guidance Keep each key to "about 15 requests per minute in total across all prefixes", or traffic spills to other machines and misses Use separate keys "to maintain separate cache accounting for customers or users within your application"
Security "separate keys help prevent cache-hit probing across users"

7.3 prompt_cache_options and explicit breakpoints#

On GPT-5.6 and later, two request fields give you Anthropic-style control:

  • prompt_cache_options (top level): mode ("implicit", the default, or "explicit"), ttl (7.4), prewarm (7.5) and comparison_response_id (7.7).
  • prompt_cache_breakpoint on a content block, {"mode": "explicit"} with an optional ttl, marks "the exact end of a reusable prompt prefix".

How they combine, from the SDK 3.42.1 docstrings and OpenAI's guide:

  • implicit mode: OpenAI "creates one implicit breakpoint and writes up to the latest three explicit breakpoints in the request".
  • explicit mode: no implicit breakpoint; OpenAI "writes up to the latest four explicit breakpoints". "If there are no explicit breakpoints, the request does not use prompt caching."
  • Each request can create up to four cache writes.
  • Where breakpoints can go: on "a supported content block inside an input message" (input_text, and the SDK also types it on image and file input blocks). "Top-level instructions cannot contain an explicit breakpoint", so put long stable text in a developer message in input instead. additional_tools items don't accept breakpoints.
  • Two gotchas from the guide: if a message grows from A to A+B, its old end is no longer a message boundary, so append a new message instead of extending the old one. And on some newer models the top-level instructions are appended after input, beyond the breakpoints, so they are billed uncached on every request; put reusable instructions in the first developer message.
  • Chat Completions has the same fields in openai 3.42.1: prompt_cache_options (with mode and ttl only) and prompt_cache_breakpoint on text content parts.
  • Lookback: OpenAI's guide says GPT-5.6 and later check "the first 2 and latest 50 explicit breakpoints", plus up to 20 earlier eligible message endings in implicit mode. The SDK's docstring says something different: "OpenAI considers up to the latest 80 breakpoints in the conversation, without a content-block lookback limit". The guide is the more recent and more specific source; either way, the numbers are far more generous than Anthropic's 20-block window, and you'll rarely hit them.

7.4 Lifetimes: 30m and 12h, and a docs-vs-SDK gap#

On GPT-5.6 and later, a cache entry lives at least 30 minutes (the default, written at 1.25×) or 12 hours (written at 2.5×); OpenAI "may retain entries longer than the requested minimum". You set the lifetime per request with prompt_cache_options.ttl, and override it per breakpoint with prompt_cache_breakpoint.ttl, for example a system prompt for 12 hours and the conversation for 30 minutes. Per OpenAI's guide, 12h is available in the Responses API.

The SDK version the samples were checked against disagrees with the guide in one place:

Field OpenAI guide openai 3.42.1 types
prompt_cache_options.ttl "30m" or "12h" Literal["30m"] only; the docstring says 30m "is currently the only supported value"
prompt_cache_breakpoint.ttl "30m" or "12h" Literal["30m", "12h"]
Chat Completions breakpoint ttl not covered by the guide's 12h statement Literal["30m", "12h"]

So a request-level 12-hour TTL fails type checking. Save as s7_ttl_typecheck.py:

python
"""The docs allow prompt_cache_options.ttl = "12h"; the openai 3.42.1 types allow only "30m"."""
from openai import OpenAI

client = OpenAI()
client.responses.create(model="gpt-6-luna", input="hi",
                        prompt_cache_options={"mode": "implicit", "ttl": "12h"})
Output · pyright against openai 3.42.16 lines
s7_ttl_typecheck.py
  s7_ttl_typecheck.py:6:46 - error: Argument of type "dict[str, str]" cannot be assigned to parameter "prompt_cache_options" of type "PromptCacheOptions | Omit" in function "create"
    Type "dict[str, str]" is not assignable to type "PromptCacheOptions | Omit"
      "dict[str, str]" is not assignable to "PromptCacheOptions"
      "dict[str, str]" is not assignable to "Omit" (reportArgumentType)
1 error, 0 warnings, 0 informations

At run time nothing stops it (TypedDicts aren't checked at run time), so the request would be sent as written. What this lesson teaches: set 12h on the breakpoint, which both the docs and the SDK types support (that's what the 7.8 sample does). If you need a request-level 12h, send it with extra_body={"prompt_cache_options": {...}} and a comment pointing at the guide, and remove the workaround when an SDK release adds the value.

prompt_cache_retention is the older control. The SDK marks it "Deprecated. Use prompt_cache_options.ttl instead"; OpenAI's guide says the new settings "do not change the older-model prompt_cache_retention parameter" and its migration guide says to "Replace prompt_cache_retention with prompt_cache_options.ttl". It takes "in_memory" (typically 5 to 10 minutes of inactivity) or "24h"; for gpt-5.5 and gpt-5.5-pro, only 24h is supported, and for models that support both values the default is 24h unless your organization uses zero data retention (then in_memory). Use it only for models before GPT-5.6.

7.5 Pre-warming#

Set prompt_cache_options={"prewarm": True} on a Responses request "to prepare the prompt cache without generating output". The SDK docstring adds that it "overrides the generate field to false". The written tokens are "billed at the cache-write rate for the selected lifetime". Send the shared prefix as the input, then send real requests with the same prefix and prewarm omitted. It's the same idea as Anthropic's max_tokens: 0 (6.6), and the same rule applies: warm before a burst of parallel requests, not during it.

7.6 Turning caching off for one-off prompts#

Because GPT-5.6 and later charge for writes, a long prompt you'll send exactly once is cheaper uncached. The SDK docstring gives the switch: explicit mode with no breakpoints means "the request does not use prompt caching". So prompt_cache_options={"mode": "explicit"} and no prompt_cache_breakpoint anywhere: no write, no surcharge, cache_write_tokens reads 0. Typical candidates: one-shot document summaries, evaluations over unique inputs, and batch-like jobs where every prompt is different.

7.7 Prompt cache diagnostics#

OpenAI also explains misses. Set prompt_cache_options={"comparison_response_id": earlier.id} on a Responses request (GPT-5.6 and later), and the response's prompt_cache_diagnostics says how this request compares with that one:

type Meaning
cache_hit No miss detected; check usage.input_tokens_details.cached_tokens for actual reuse
cache_miss Something prevented reuse: reason is one of model_changed, prompt_cache_key_changed, service_tier_changed, tools_changed, text_format_changed, reasoning_effort_changed, verbosity_changed, context_compacted, input_changed; plus cache_missed_tokens and, optionally, comparison_reusable_tokens
comparison_response_not_found The comparison record is gone (records "expire after a short period")
unavailable No conclusive result, or the model doesn't support diagnostics

The SDK 3.42.1 types all four (response.prompt_cache_diagnostics). Diagnostics "have no additional cost", "never block or fail requests", report only the first reason found, and are best effort. With streaming, read it from event.response on the response.completed event.

7.8 Reading cache usage, and the full sample#

  • usage.input_tokens_details.cached_tokens: billed reads.
  • usage.input_tokens_details.cache_write_tokens: billed writes, split in cache_write_tokens_details into ttl_30m_tokens and ttl_12h_tokens ("Both fields are returned, including when one is zero"; read them from model_extra in SDK 3.42.1, 3.8).
  • Chat Completions: usage.prompt_tokens_details.cached_tokens and .cache_write_tokens.

Everything together: a per-tenant key, a 12-hour breakpoint on the policy, pre-warming, diagnostics, and caching switched off for a one-off prompt. Save as s7_openai_caching.py:

python
"""OpenAI prompt caching on GPT-5.6+: explicit breakpoints, lifetimes, a cache key, pre-warming
and diagnostics, reading what was read and written from usage."""
from dotenv import load_dotenv
from openai import OpenAI
from openai.types.responses import Response, ResponseInputParam

load_dotenv()
client = OpenAI()
MODEL = "gpt-6-luna"

POLICY = "Acme returns policy.\n" + "\n".join(
    f"Rule {i}: items in category {i % 9} may be returned within {14 + i % 30} days if unused."
    for i in range(400))


def build_input(question: str) -> ResponseInputParam:
    return [
        # Breakpoints can't go in top-level `instructions`, so the stable text is a developer message
        {"role": "developer", "content": [
            {"type": "input_text", "text": POLICY,
             # end of the reusable prefix; this one block gets the 12-hour lifetime (2.5x write)
             "prompt_cache_breakpoint": {"mode": "explicit", "ttl": "12h"}},
        ]},
        {"role": "user", "content": [{"type": "input_text", "text": question}]},
    ]


def show(label: str, r: Response) -> None:
    u = r.usage
    if u is None:
        print(label, "no usage")
        return
    d = u.input_tokens_details
    split = (d.model_extra or {}).get("cache_write_tokens_details")   # not typed in SDK 3.42.1
    diag = r.prompt_cache_diagnostics.type if r.prompt_cache_diagnostics else None
    print(f"{label:22s} input={u.input_tokens:>6} read={d.cached_tokens or 0:>6} "
          f"written={d.cache_write_tokens or 0:>6} split={split} out={u.output_tokens} diagnostics={diag}")


# 1. Pre-warm: write the prefix to the cache without generating output (billed as a cache write)
warm = client.responses.create(model=MODEL, input=build_input("warmup"),
                               prompt_cache_key="tenant-acme",       # per-tenant cache accounting
                               prompt_cache_options={"mode": "explicit", "prewarm": True})
show("1. pre-warm", warm)

# 2. A real question: the prefix should now be a cache read
first = client.responses.create(model=MODEL, input=build_input("Can I return shoes?"),
                                max_output_tokens=300, reasoning={"effort": "none"},
                                prompt_cache_key="tenant-acme",
                                prompt_cache_options={"mode": "explicit"})
show("2. question", first)

# 3. Same prefix, but ask OpenAI to compare with request 2 and explain any miss
second = client.responses.create(model=MODEL, input=build_input("Can I return a lamp?"),
                                 max_output_tokens=300, reasoning={"effort": "none"},
                                 prompt_cache_key="tenant-acme",
                                 prompt_cache_options={"mode": "explicit",
                                                       "comparison_response_id": first.id})
show("3. compared", second)

# 4. A one-off prompt you'll never resend: explicit mode with NO breakpoint = no cache write
once = client.responses.create(model=MODEL, input=POLICY + "\nSummarize in one line.",
                               max_output_tokens=300, reasoning={"effort": "none"},
                               prompt_cache_options={"mode": "explicit"})
show("4. caching off", once)
Example output · illustrative4 lines
1. pre-warm            input=  8021 read=     0 written=  8005 split={'ttl_30m_tokens': 0, 'ttl_12h_tokens': 8005} out=0 diagnostics=None
2. question            input=  8030 read=  8005 written=     0 split={'ttl_30m_tokens': 0, 'ttl_12h_tokens': 0} out=46 diagnostics=None
3. compared            input=  8031 read=  8005 written=     0 split={'ttl_30m_tokens': 0, 'ttl_12h_tokens': 0} out=52 diagnostics=cache_hit
4. caching off         input=  8012 read=     0 written=     0 split={'ttl_30m_tokens': 0, 'ttl_12h_tokens': 0} out=38 diagnostics=None

On gpt-6-luna, request 1 wrote 8,005 tokens at the 12-hour rate ($0.25 per million, so about $0.002), and requests 2 and 3 each read them at $0.01 per million instead of paying $0.10. Request 4 shows the switch-off: the same long text, no write. On the stand-in the sample runs end to end, but every cache field reads 0 or is missing (Ollama doesn't send cache_write_tokens, which is why the sample uses or 0 even on fields the SDK types as int) and prompt_cache_diagnostics is None (prompt caching is not supported locally).

Two more things the guide says, as of November 2026:

  • Cached input still counts toward TPM (tokens per minute). Unlike on Anthropic, a high hit rate saves money and latency on OpenAI but gives no rate-limit headroom (02.7, 6.4).
  • Caches can't be cleared ("Manual cache clearing is not currently available"), aren't shared across organizations, can't be reused across regional processing boundaries, and all caching features are compatible with zero data retention.

Part 8: Gemini caching: implicit and explicit caches#

Deep-dive

Gemini has two separate mechanisms (02.7, 7.3 named them): implicit caching, automatic like OpenAI's, and explicit context caches, objects you create, use by name, extend and delete, and pay storage for by the hour.

8.1 Implicit caching#

As of November 2026, per Google's caching guide:

  • On by default for Gemini 2.5 and newer, on both generate_content and the Interactions API (stateful with previous_interaction_id, or stateless). "We automatically pass on cost savings if your request hits caches."
  • Minimum input: 4,096 tokens on Gemini 4 Argon, 3.8 Flash, 3.6 Flash and 3.1 Pro Preview; 2,048 on 2.5 Flash and 2.5 Pro.
  • No write charge. Hits are billed at the model's "context caching price": $0.075 per million on 3.8 Flash (0.1× its input price) and $0.10 on 4 Argon ("discounts cached input tokens by 95% on cache hits"), through those models' introductory periods.
  • Gemini 4's multi-turn rule: on Gemini 4 Argon and newer, "Gemini caches the full previous request only if the new request adds at least 2,050 tokens. Model output, thought, and function results all count toward this total. For smaller additions, Gemini re-processes the last 2,050 tokens of the previous request at the standard input rate." Short chat turns therefore pay full price for a 2,050-token tail; agent turns, with tool results and thinking, usually clear the bar.
  • Routing change: Google's pricing page says Gemini 2.5 Pro and 2.5 Flash route to newer models from 1 December 2026, so check which model you actually hit before you rely on a minimum or a price.
  • Reading it: usage_metadata.cached_content_token_count on generate_content (remember it's inside prompt_token_count, 3.4), usage.total_cached_tokens on Interactions.
  • Google's two tips are the general rules from 02.7, 7.4: put large, common content at the beginning, and send requests with a similar prefix close together in time. Google gives no lifetime for implicit entries.

There are no knobs. If your prompts are long, stable at the start and frequent, you'll see cached_content_token_count climb; if not, explicit caches are the tool.

8.2 Explicit caches: the full lifecycle#

An explicit cache (CachedContent) is a server-side object holding a prefix: contents, and optionally a system_instruction, tools and tool_config. You create it once, reference it by name in any number of generate_content calls, and it lives until its expiry time or until you delete it.

stateDiagram-v2
    [*] --> Live: caches.create (contents, system_instruction, tools, ttl)
    Live --> Live: generate_content with cached_content = name
    Live --> Live: caches.update (ttl or expire_time only)
    Live --> Expired: expire_time reached
    Live --> Deleted: caches.delete
    Expired --> [*]
    Deleted --> [*]

Availability first, because it rules out many setups: explicit caching works only with generate_content. It's "not supported in the Interactions API, or for Gemini 4 Argon and onward"; Google's migration notes for Argon say to "Remove calls that create or reference cached_content" and rely on implicit caching. On Gemini 3.8 Flash and other supported 3.x and 2.5 models, it works as below. Save as s8_gemini_cache.py:

python
"""Gemini explicit context cache, full lifecycle: create -> use -> update TTL -> list -> delete."""
import datetime as dt

from dotenv import load_dotenv
from google import genai
from google.genai import errors, types

load_dotenv()
client = genai.Client()
MODEL = "gemini-3.8-flash"            # explicit caches: generate_content only, not Gemini 4 Argon+

MANUAL = "Acme X200 service manual.\n" + "\n".join(
    f"Section {i}: torque bolt {i} to {10 + i % 25} Nm and inspect seal {i % 7}." for i in range(1500))

# 1. Create: the cached prefix holds the contents AND the system instruction (and tools, if any)
cache = client.caches.create(
    model=MODEL,
    config=types.CreateCachedContentConfig(
        display_name="x200-manual-v3",                 # your own label: use it to find caches later
        system_instruction="Answer only from the X200 manual. Cite the section number.",
        contents=[types.Content(role="user", parts=[types.Part(text=MANUAL)])],
        ttl="900s",                                    # 15 minutes; storage is billed per hour
    ),
)
name = cache.name or ""                                # e.g. "cachedContents/abc123"
print("created:", name, "| tokens:", cache.usage_metadata.total_token_count if cache.usage_metadata else None,
      "| expires:", cache.expire_time)

try:
    # 2. Use: reference it by name and send only the new contents. The system instruction
    #    (and any tools) are part of the cached prefix, so they aren't repeated here.
    for q in ["What torque for bolt 12?", "Which seal goes with section 30?"]:
        r = client.models.generate_content(
            model=MODEL, contents=q,
            config=types.GenerateContentConfig(cached_content=name, max_output_tokens=300))
        u = r.usage_metadata
        if u:
            print(f"{q!r}: prompt={u.prompt_token_count} cached={u.cached_content_token_count} "
                  f"out={u.candidates_token_count} thoughts={u.thoughts_token_count}")

    # 3. Update: only the expiry can change (ttl or expire_time), never the contents
    cache = client.caches.update(name=name,
                                 config=types.UpdateCachedContentConfig(ttl="3600s"))
    print("extended, now expires:", cache.expire_time)

    # 4. List: find caches you forgot about (each one costs storage every hour it lives)
    now = dt.datetime.now(dt.timezone.utc)
    for c in client.caches.list(config=types.ListCachedContentsConfig(page_size=50)):
        left = (c.expire_time - now) if c.expire_time else None
        print(f"  {c.name}  {c.display_name!r}  model={c.model}  expires in {left}")
finally:
    # 5. Delete as soon as you are done: storage is billed for as long as the cache exists
    try:
        client.caches.delete(name=name)
        print("deleted:", name)
    except errors.APIError as e:
        print("delete failed:", e.code, e.message)
Example output · illustrative7 lines
created: cachedContents/q8z3m1x7k2pv | tokens: 31512 | expires: 2026-11-04 09:57:12.418302+00:00
'What torque for bolt 12?': prompt=31527 cached=31512 out=17 thoughts=84
'Which seal goes with section 30?': prompt=31530 cached=31512 out=21 thoughts=102
extended, now expires: 2026-11-04 10:42:15.203117+00:00
  cachedContents/q8z3m1x7k2pv  'x200-manual-v3'  model=models/gemini-3.8-flash  expires in 0:59:59.512000
  cachedContents/h2n6c0r4w9ts  'x200-manual-v2'  model=models/gemini-3.8-flash  expires in 5:12:40.004000
deleted: cachedContents/q8z3m1x7k2pv

The details, from the SDK 2.34.0 types and Google's caching API reference:

Step Call Notes
Create client.caches.create(model=, config=types.CreateCachedContentConfig(contents=, system_instruction=, tools=, tool_config=, display_name=, ttl= or expire_time=, kms_key_name=)) ttl is a duration string ending in s ("900s"); expire_time an RFC 3339 timestamp. display_name is your own label (up to 128 characters). kms_key_name names a customer-managed encryption key in Google Cloud KMS. Google's caching guide gives a default lifetime of 1 hour when you set neither
Use GenerateContentConfig(cached_content=cache.name) The cache's system instruction and tools are part of the cached prefix; send only the new contents. "Cached content can be only used with model it was created for"
Inspect client.caches.get(name=) usage_metadata.total_token_count is what you pay storage on; expire_time "is always provided on output"
Extend client.caches.update(name=, config=types.UpdateCachedContentConfig(ttl= or expire_time=)) "Only expiration is updatable": you can't change the contents. A new version of a document is a new cache
List client.caches.list(config=types.ListCachedContentsConfig(page_size=)) Returns a pager; at most 1,000 per page
Delete client.caches.delete(name=) Stops storage charges; do it in a finally

The sample's list shows the real-world failure: x200-manual-v2, an older version someone created with a long TTL and never deleted, still has five hours to live, and you're paying for every one of them.

8.3 What an explicit cache costs#

Three charges, as of November 2026, on Gemini 3.8 Flash through 31 December 2026:

  1. Creating it processes the cached tokens once, at the normal input price (02.7, 7.3).
  2. Each request that uses it pays the context-caching price ($0.075 per million) for the cached tokens, plus normal input for the new contents and normal output (thinking included).
  3. Storage: $0.50 per million tokens per hour for as long as the cache exists ($1.00 from 1 January 2027). A 200,000-token cache kept for a day costs $2.40 in storage alone, even if nobody uses it.

Other models differ (Google's pages, read on 20 November 2026): Gemini 3.1 Pro Preview, up to 200k context, is $2.00 input, $0.20 cached read and $4.50 storage per million tokens per hour; Gemini 2.5 Flash is $0.30, $0.03 and $1.00. 11B.4, 5.3 turns those into a reads-per-hour break-even.

None of the storage cost appears in any response's usage, so your tracker has to account for it separately: record each cache's token count, creation time and deletion (or expiry) time, and price the token-hours. storage_cost() in cost_calc.py does the pricing from the price table's cache_storage_per_hour (splitting a cache that lives across a price change), and record_cache_storage() writes the result as its own tracker event, kind: "cache_storage". Call it next to caches.delete (or from the cleanup job in 8.4, for caches that expired). Save as s8_storage_cost.py:

python
"""What an explicit Gemini cache costs to KEEP: no response reports it, so price the token-hours yourself."""
import datetime as dt
import json
import tempfile
from pathlib import Path

from cost_calc import storage_cost
from cost_tracker import CostTracker
from prices import PriceTable

table = PriceTable.load()
utc = dt.timezone.utc
TOKENS = 200_000                                   # CachedContent.usage_metadata.total_token_count

# A day-long cache created at 09:00 and deleted at 09:00 the next day: $0.50 per million tokens per hour
day = storage_cost("gemini", "gemini-3.8-flash", TOKENS, dt.datetime(2026, 11, 3, 9, tzinfo=utc),
                   dt.datetime(2026, 11, 4, 9, tzinfo=utc), table)
print(f"24 h on 3 Nov 2026:               ${day:.2f}   (nobody has to use it)")

# The same cache across New Year: the storage rate doubles at midnight on 1 January 2027
span = storage_cost("gemini", "gemini-3.8-flash", TOKENS, dt.datetime(2026, 12, 31, 12, tzinfo=utc),
                    dt.datetime(2027, 1, 1, 12, tzinfo=utc), table)
print(f"12 h in 2026 + 12 h in 2027:      ${span:.2f}   (two rates, one cache)")

# Record it as its own event when you delete the cache (call this next to caches.delete)
tracker = CostTracker(table, Path(tempfile.mkdtemp()) / "calls.jsonl", env="demo")
rec = tracker.record_cache_storage(provider="gemini", model="gemini-3.8-flash", feature="manual-qa",
                                   cache_name="cachedContents/q8z3m1x7k2pv", tokens=TOKENS,
                                   created=dt.datetime(2026, 11, 3, 9, tzinfo=utc),
                                   deleted=dt.datetime(2026, 11, 3, 17, tzinfo=utc))
print(json.dumps({k: getattr(rec, k) for k in ["kind", "feature", "request_id", "storage_token_hours",
                                               "cost_usd", "cost_source", "status"]}))
Output3 lines
24 h on 3 Nov 2026:               $2.40   (nobody has to use it)
12 h in 2026 + 12 h in 2027:      $3.60   (two rates, one cache)
{"kind": "cache_storage", "feature": "manual-qa", "request_id": "cachedContents/q8z3m1x7k2pv", "storage_token_hours": 1600000.0, "cost_usd": 0.8, "cost_source": "computed", "status": "ok"}

A day-long cache of the 200,000-token manual costs $2.40 whether or not anyone asks it a question, and the same cache across New Year pays two rates. The daily storage line then sits in the reconciliation next to the calls (13.5), and in the per-feature spend (5.7). Part 11 works out when an explicit cache beats implicit caching or no caching at all.

8.4 Housekeeping: orphans, versions and deletion#

  • Short TTLs, extended on demand. Create with the shortest lifetime that covers your burst of traffic and update it while it's in use, instead of creating with a day-long TTL "just in case".
  • Version in display_name (x200-manual-v3), so a cleanup job can find and delete superseded caches. Contents can't be updated, so every document change is a new cache.
  • A scheduled cleanup job that lists caches, and deletes any whose display_name isn't in your list of live versions, or that have outlived their purpose.
  • Deletion requests reach caches too. A cache holding a user's document is a copy of their data. When the user asks for deletion, delete the cache (lesson 03.2 covers the other copies).
  • Caches are per project. Each Google Cloud project (and API key's project) has its own caches.

8.5 If you're on Interactions or Gemini 4 Argon#

You get implicit caching only. To make the most of it: keep the stable part of the prompt first and byte-identical, use previous_interaction_id chaining or resend history unchanged (lesson 03.2), expect short Gemini 4 turns (under 2,050 new tokens) to re-process a 2,050-token tail at the full input price, and measure total_cached_tokens per feature (Part 10).


Part 9: OpenRouter: caching, cost fields and generation stats#

Deep-dive

9.1 Caching passes through to the provider#

OpenRouter doesn't run its own prompt cache; it passes your request to a provider, and that provider's caching rules apply. Per OpenRouter's prompt-caching guide, as of November 2026:

Upstream What you do on OpenRouter
OpenAI, xAI Grok, DeepSeek, Moonshot, Groq, Z.AI, Gemini 2.5+ (implicit) Nothing: caching is automatic. On GPT-5.6 and later you can also send OpenAI's prompt_cache_breakpoint and prompt_cache_options (12-hour TTLs included), on both Chat Completions and the Responses API
Anthropic cache_control is required: top level (automatic caching) or on content blocks (at most 4 breakpoints), with {"type": "ephemeral"} or "ttl": "1h"
Gemini explicit caching cache_control breakpoints in the messages. OpenRouter creates and manages the cache for you; it "will use only the last breakpoint". The first system message becomes Gemini's immutable system instruction, so put dynamic text in a later user message
Alibaba Qwen (some models) cache_control breakpoints, Anthropic syntax, 5-minute writes

One trap in the Gemini row: OpenRouter's guide says explicit-cache writes have a fixed lifetime ("Cache Writes have a 5 minute Time-to-Live (TTL) that does not update"). Unlike Anthropic's 5m, reading the entry doesn't refresh it, so a long-lived conversation pays a new write every five minutes, and the break-even in Part 11 is worse than for the same prefix on Anthropic. Implicit Gemini caching through OpenRouter is described more loosely ("on average 3-5 minutes, but will vary").

Two translation details matter if you write provider-neutral code: a block with Anthropic-style cache_control "gets a prompt_cache_breakpoint when routed to a supporting OpenAI model", and vice versa, but TTLs aren't translated (a cache_control ttl is dropped toward OpenAI, a prompt_cache_breakpoint ttl toward Anthropic or Google). And OpenRouter's Responses API accepts top-level cache_control but not per-block cache_control inside input items; use Chat Completions or OpenRouter's Messages endpoint when you need block-level breakpoints with a TTL.

9.2 Sticky routing keeps the cache warm#

A cache lives at one provider. If OpenRouter sent turn 1 of a conversation to one Anthropic endpoint and turn 2 to another, turn 2 would miss. Provider sticky routing prevents that:

sequenceDiagram
    participant App
    participant OR as OpenRouter
    participant A as Provider A
    participant B as Provider B
    App->>OR: turn 1, session_id S
    OR->>A: route (A chosen)
    A-->>OR: reply, cache written at A
    OR-->>App: reply, usage, cost
    App->>OR: turn 2, session_id S
    Note over OR: sticky: S was served by A in the last 60 minutes
    OR->>A: route to A again
    A-->>OR: reply, cache read at A
    OR-->>App: reply, cached_tokens over 0
    Note over OR,B: If A fails, OpenRouter falls back to B, which has no cache yet

The rules, from the same guide:

  • Automatic after a cached request, for implicit and explicit caching alike, per account, per model and per conversation. By default a conversation is identified by "hashing the first system (or developer) message and the first non-system message".
  • session_id (body field, at most 256 characters, sent through extra_body with the openai SDK; or the x-session-id header) makes the key explicit, which helps agents whose opening messages change. With a session_id, stickiness starts on the first successful request; without one, only after a cache hit is seen. If neither is set, OpenRouter falls back to prompt_cache_key.
  • Sessions expire after 60 minutes of inactivity; each successful request resets the timer.
  • Only when it saves money: sticky routing "only activates when the provider's cache read pricing is cheaper than regular prompt pricing".
  • Manual ordering wins: with provider.order set, sticky routing isn't used.
  • Failover breaks the cache. If the sticky provider is down, the request goes elsewhere and pays a cold write there.

9.3 usage.cost and the generation endpoint#

3.5 gave the cost fields. Here they are on a cached Claude call, followed by the two endpoints you'll use for after-the-fact accounting. Save as s9_openrouter.py:

python
"""OpenRouter: cache_control on a Claude model, usage.cost, then the generation and key endpoints."""
import os
import time
from typing import Any, cast

import httpx
from dotenv import load_dotenv
from openai import OpenAI
from openai.types.chat import ChatCompletionMessageParam

load_dotenv()
KEY = os.environ["OPENROUTER_API_KEY"]
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=KEY,
                default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "Cost demo"})
MODEL = "anthropic/claude-haiku-5.5"
POLICY = "Acme returns policy.\n" + "\n".join(
    f"Rule {i}: items in category {i % 9} may be returned within {14 + i % 30} days." for i in range(400))


def messages(question: str) -> list[ChatCompletionMessageParam]:
    raw: list[dict[str, Any]] = [
        {"role": "system", "content": [
            {"type": "text", "text": POLICY,
             "cache_control": {"type": "ephemeral"}},   # Anthropic-style breakpoint, passed through
        ]},
        {"role": "user", "content": question},
    ]
    # cache_control is an OpenRouter/Anthropic extension the openai SDK's types don't declare
    return cast(list[ChatCompletionMessageParam], raw)


last_id = ""
for q in ["Can I return shoes?", "Can I return a lamp?"]:
    r = client.chat.completions.create(
        model=MODEL, max_tokens=300, messages=messages(q),
        extra_body={"session_id": "support-chat-8841"},   # OpenRouter-only: sticky routing key
    )
    u = r.usage
    if u is None:
        continue
    extra = u.model_extra or {}                            # cost, cost_details, is_byok
    d = u.prompt_tokens_details
    print(f"{q!r}: prompt={u.prompt_tokens} read={d.cached_tokens if d else None} "
          f"written={d.cache_write_tokens if d else None} cost={extra.get('cost')} "
          f"byok={extra.get('is_byok')}")
    last_id = r.id

# After the fact: the full record of the last call (provider, native tokens, cache discount)
headers = {"Authorization": f"Bearer {KEY}"}
with httpx.Client(base_url="https://openrouter.ai/api/v1", headers=headers, timeout=10) as http:
    g = http.get("/generation", params={"id": last_id})
    for attempt in range(2):          # the record can lag a moment behind the response
        if g.status_code != 404:
            break
        time.sleep(1 + attempt)
        g = http.get("/generation", params={"id": last_id})
    g.raise_for_status()
    gen = g.json()["data"]
    print({k: gen.get(k) for k in ["provider_name", "model", "total_cost", "cache_discount",
                                   "native_tokens_prompt", "native_tokens_cached",
                                   "native_tokens_completion", "latency", "service_tier"]})

    key = http.get("/key").json()["data"]        # this key's spend and limit
    print({k: key.get(k) for k in ["label", "usage_daily", "usage_monthly", "limit", "limit_remaining",
                                   "limit_reset"]})
Example output · illustrative4 lines
'Can I return shoes?': prompt=7640 read=0 written=7622 cost=0.000981 byok=False
'Can I return a lamp?': prompt=7643 read=7622 written=0 cost=0.000108 byok=False
{'provider_name': 'Anthropic', 'model': 'anthropic/claude-haiku-5.5', 'total_cost': 0.000108, 'cache_discount': 0.000686, 'native_tokens_prompt': 7643, 'native_tokens_cached': 7622, 'native_tokens_completion': 59, 'latency': 812, 'service_tier': 'standard'}
{'label': 'sk-or-v1-a1b...c3d', 'usage_daily': 0.0011, 'usage_monthly': 3.27, 'limit': 50, 'limit_remaining': 46.73, 'limit_reset': 'monthly'}

Run against the stand-in, both chat calls run (with no cost or cache fields, which Ollama doesn't send); the /generation and /key endpoints don't exist there (not supported locally).

What each part gives you:

  • usage.cost per request: the second request cost about a tenth of the first, because its 7,622 prompt tokens were cache reads (and note that prompt=7643 includes them: 3.1). That's already in the number: don't discount it again.
  • GET /api/v1/generation?id=<generation id> returns the full record of one request: total_cost, cache_discount ("Discount applied due to caching"; OpenRouter notes that Anthropic cache writes show a negative discount), native_tokens_prompt, native_tokens_cached, native_tokens_completion and native_tokens_reasoning (counted by the upstream model's tokenizer), provider_name, latency and generation_time (milliseconds), service_tier ("Service tier the upstream provider reported"), finish_reason and native_finish_reason, is_byok, upstream_inference_cost, session_id, cancelled, streamed and more. Use it when the response's usage was lost (a broken stream), to audit, and to see which provider actually served the request. The generation ID is the response's id, also sent in the X-Generation-Id header (lesson 03.1).
  • GET /api/v1/key describes the key you call it with: usage (all-time), usage_daily, usage_weekly, usage_monthly (all in USD, per UTC day, Monday-to-Sunday week and calendar month), limit, limit_remaining, limit_reset, the BYOK equivalents, is_free_tier, free_model_daily_requests, and budgets with the effective_budget. Its rate_limit field is legacy ("Will always return -1"). It's how a service checks its own remaining budget (12.4).

9.4 Caching controls side by side#

The four providers' caching controls, as of November 2026, in one place. Each cell is a summary: the part named in it owns the detail, and the price table owns the numbers (4.2). 11B.4, 4.6b extends the comparison to the other hosted providers, clouds and self-hosted engines.

OpenAI Anthropic Gemini OpenRouter
How to turn it on Automatic. On GPT-5.6 and later, prompt_cache_options and prompt_cache_breakpoint for explicit control (7.3) Opt in with cache_control: top level (automatic) or on blocks, up to 4 breakpoints (6.1) Implicit caching is automatic (8.1); explicit caches with client.caches.create, on generate_content only (8.2) Pass-through: automatic where the provider is automatic, cache_control for Anthropic and explicit Gemini (9.1)
What is cached The prefix up to each breakpoint; implicit mode adds one at the latest eligible message The prefix tools → system → messages up to each breakpoint (6.5) Implicit: the longest shared prefix. Explicit: the contents, system_instruction and tools you stored Whatever the upstream provider caches
Minimum prefix see 7.1 see 6.4 see 8.1 The upstream provider's
Lifetime 30m or 12h (ttl) 5m or 1h (ttl), refreshed by every read Implicit: not stated. Explicit: yours (ttl or expire_time) The provider's; Gemini explicit through OpenRouter: 5 minutes, not refreshed
Write price 1.25× (30m) or 2.5× (12h) input on GPT-5.6 and later; none before 1.25× (5m) or 2× (1h) input Implicit: none. Explicit: input price to create, plus storage per hour Included in usage.cost
Read price 0.1× input, 0.05× on Terra and Sol (3.2) 0.1× input, 0.05× on Opus and Sonnet 5.5, 0.025× on Fable 5.2 and 5.1 (3.3) The model's cached-input price (3.4) Included in usage.cost
Isolation Per organization; prompt_cache_key separates accounting per tenant (7.2) Per workspace (6.7) Per project (8.4) Per account; session_id pins a conversation to a provider (9.2)
Warm it before a burst prewarm (7.5) max_tokens: 0 (6.6) Create the explicit cache first Send one request, then the rest
Why did it miss? prompt_cache_diagnostics (7.7) diagnostics.cache_miss_reason (6.8) Usage fields only The generation record's cache_discount and native_tokens_cached (9.3)
Usage fields cached_tokens, cache_write_tokens (split in model_extra) cache_read_input_tokens, cache_creation_input_tokens, cache_creation cached_content_token_count (Interactions: total_cached_tokens) prompt_tokens_details.cached_tokens and cache_write_tokens, plus cost
Clear it Can't Can't: change the prefix Explicit: caches.delete. Implicit: can't Can't

Part 10: Measuring caching#

"We turned caching on" is not a result. The result is a number per feature: how much of the input was served from cache, what that saved after paying for writes, and when it stopped working. The cost tracker's records (Part 5) already hold everything you need.

This part is the home for the metrics and the analyser. Running them as a production loop (per-feature dashboards, alerting on prefix churn) is covered in 11B.3, 2.6.

10.1 The metrics#

Metric Formula (per feature, model and time window) Why
Request hit rate requests with cache reads > 0 ÷ requests Easy to explain; misleading on its own (a hit on 5% of the prompt counts as a hit)
Token hit ratio cache-read tokens ÷ all input tokens (uncached + read + written) The one that drives cost. Use the total input, or Anthropic's split makes it look better than it is
Write ratio cache-write tokens ÷ all input tokens High with a low hit ratio means you're paying the write premium for nothing
Net saving cost without caching − actual cost The bottom line, after write premiums. It can be negative
Prefix churn distinct prefix fingerprints ÷ requests Near 1.0 on a feature that should share a prefix means something in the prefix changes every request

The "cost without caching" counterfactual is easy with the calculator: price the same request with every input token as uncached input.

10.2 A hit-rate analyser#

This analyser reads a log of tracker records and prints the metrics per feature, plus the likely cause of each problem it can recognize. Your own log would be the tracker's calls.jsonl; to run the analyser before you have one, generate a fixture log: one simulated day, seeded so everybody gets the same file, with five features that each have a different caching story. The generator writes a subset of the tracker's fields under the tracker's names (so uncached_input_tokens is the plain-input part, 3.1), and prices every row with cost_calc. Save as make_fixture_log.py, in the folder with prices.yaml, and run it first with uv run python make_fixture_log.py:

python
"""make_fixture_log.py: generate usage_log.jsonl, a seeded day of tracker records (FIXTURE data).

Each row has a subset of the CostTracker's fields, with the same names and the same convention:
`uncached_input_tokens` is billed at the plain input rate; the cached and written tokens are extra.
Run it once, in the folder with prices.yaml, before the analysers:  uv run python make_fixture_log.py
"""
import datetime as dt
import hashlib
import json
import random

from cost_calc import Usage, price, storage_cost
from prices import PriceTable

random.seed(7)
TABLE = PriceTable.load()
DAY = dt.date(2026, 11, 3)
T0 = dt.datetime(2026, 11, 3, 9, 0, tzinfo=dt.timezone.utc)
WRITE_TTL = {"anthropic": "5m", "openai": "30m", "gemini": "30m"}    # the log keeps totals, not TTL splits
rows: list[dict] = []


def customer(n: int) -> str:
    """Stand-in for the tracker's keyed hash of a customer ID."""
    return hashlib.sha256(f"fixture-customer-{n}".encode()).hexdigest()[:16]


def add(t: dt.datetime, feature: str, provider: str, model: str, prefix: str, cust: int | None,
        uncached: int, cached: int, written: int, out: int, ok: bool = True) -> None:
    usage = Usage(provider, model, input=uncached, cached_input=cached, output=out,
                  cache_writes={WRITE_TTL[provider]: written} if written else {})
    rows.append({"ts": t.isoformat(timespec="seconds"), "kind": "call", "feature": feature,
                 "customer": customer(cust) if cust else None, "provider": provider, "model": model,
                 "prefix": prefix, "uncached_input_tokens": uncached if ok else None,
                 "cached_input_tokens": cached if ok else None,    # a failed call: usage is unknown
                 "cache_write_tokens": written if ok else None, "output_tokens": out if ok else None,
                 "cost_usd": round(price(usage, TABLE, DAY).usd, 6) if ok else None,
                 "cost_source": "computed" if ok else "unknown",
                 "status": "ok" if ok else "error:APITimeoutError"})


# support-bot: healthy chat traffic on a stable 9,000-token prefix ... until 13:00, when a deploy
# put the current time into the system prompt, so every request writes a new prefix
t = T0
for i in range(300):
    t += dt.timedelta(seconds=random.randint(20, 90))
    broken = t.hour >= 13
    first = i == 0
    cold = first or broken
    add(t, "support-bot", "anthropic", "claude-sonnet-5-5", f"sys-{i}" if broken else "sys-v41",
        random.choice([1, 1, 1, 2, 3, 4, 5, 6, 7, 8]), uncached=random.randint(30, 200),
        cached=0 if cold else 9_000, written=9_000 if cold else random.choice([0, 0, 0, 350]),
        out=random.randint(80, 400), ok=i % 60 != 59)           # a few timed-out calls: cost unknown

# contract-qa: 60,400-token requests (400 uncached + a 60,000-token contract) on gpt-6.1-sol. Each
# first question writes the contract to the cache; about a third are second questions that read it
t = T0
for i in range(40):
    t += dt.timedelta(minutes=random.randint(5, 20))
    second = random.random() < 0.3
    add(t, "contract-qa", "openai", "gpt-6.1-sol", f"contract-{i - 1 if second else i}", random.randint(10, 14),
        uncached=400, cached=60_000 if second else 0, written=0 if second else 60_000,
        out=random.randint(300, 900))

# faq: a 3,000-token prompt on Gemini: below the 4,096-token implicit-caching minimum
t = T0
for i in range(200):
    t += dt.timedelta(seconds=random.randint(30, 120))
    add(t, "faq", "gemini", "gemini-3.8-flash", "faq-v3", random.randint(20, 40), uncached=3_000, cached=0,
        written=0, out=random.randint(50, 200))

# manual-qa: a Gemini EXPLICIT cache of a 200,000-token manual, kept 8 hours for 14 questions.
# Storage is in no response's usage, so it is a separate record (kind: cache_storage)
t = T0
for i in range(14):
    t += dt.timedelta(minutes=random.randint(15, 40))
    add(t, "manual-qa", "gemini", "gemini-3.8-flash", "manual-v3", random.randint(50, 53), uncached=150,
        cached=200_000, written=0, out=random.randint(100, 300))
created, deleted = T0, T0 + dt.timedelta(hours=8)
rows.append({"ts": deleted.isoformat(timespec="seconds"), "kind": "cache_storage", "feature": "manual-qa",
             "customer": None, "provider": "gemini", "model": "gemini-3.8-flash",
             "prefix": "cachedContents/x200-manual-v3", "storage_token_hours": 200_000 * 8,
             "cost_usd": round(storage_cost("gemini", "gemini-3.8-flash", 200_000, created, deleted, TABLE), 6),
             "cost_source": "computed", "status": "ok"})

# nightly-summaries: 20 requests fired at once at a cold 30,000-token prefix
t = T0.replace(hour=2)
for i in range(20):
    add(t + dt.timedelta(milliseconds=50 * i), "nightly-summaries", "anthropic", "claude-haiku-5-5",
        "digest-v2", None, uncached=120, cached=0, written=30_000, out=500)

rows.sort(key=lambda r: r["ts"])
with open("usage_log.jsonl", "w") as f:
    for r in rows:
        f.write(json.dumps(r) + "\n")
print(len(rows), "records written to usage_log.jsonl")
Output1 line
575 records written to usage_log.jsonl

It also writes a cache_storage record for the Gemini explicit cache (8.3) and five failed calls with unknown cost. Now the analyser. It adds the three token fields to get the total, skips records with unknown cost, adds a feature's cache-storage cost to its bill, and reads each model's minimum prefix from the price table. Save as s10_hit_rate.py:

python
"""Cache hit-rate analyser: hit rates, money saved (or lost) and likely causes of misses,
from a log of tracker records. Run make_fixture_log.py first to create usage_log.jsonl."""
import datetime as dt
import json
from collections import defaultdict

from cost_calc import Usage, price
from prices import PriceTable

table = PriceTable.load()
DAY = dt.date(2026, 11, 3)
DEFAULT_WRITE = {"anthropic": "5m", "openai": "30m"}     # the log has totals, not TTL splits

records = [json.loads(line) for line in open("usage_log.jsonl")]
calls = [r for r in records if r["kind"] == "call" and r["cost_usd"] is not None]   # unknown cost: skip
storage = [r for r in records if r["kind"] == "cache_storage"]                      # Gemini explicit caches
by_feature: dict[str, list[dict]] = defaultdict(list)
for r in calls:
    by_feature[r["feature"]].append(r)


def total_input(r: dict) -> int:
    """The module's convention: uncached is only the plain-input part, so the total adds the others."""
    return r["uncached_input_tokens"] + r["cached_input_tokens"] + r["cache_write_tokens"]


def without_caching(r: dict) -> float:
    """Counterfactual: the same request with every input token billed as plain input."""
    return price(Usage(r["provider"], r["model"], input=total_input(r), output=r["output_tokens"]),
                 table, DAY).usd


for feature, rows in by_feature.items():
    provider, model = rows[0]["provider"], rows[0]["model"]
    total_in = sum(total_input(r) for r in rows)
    read = sum(r["cached_input_tokens"] for r in rows)
    written = sum(r["cache_write_tokens"] for r in rows)
    hits = sum(1 for r in rows if r["cached_input_tokens"] > 0)
    stored = sum(s["cost_usd"] for s in storage if s["feature"] == feature)    # in no response's usage
    actual = sum(r["cost_usd"] for r in rows) + stored
    without = sum(without_caching(r) for r in rows)
    print(f"\n{feature} ({provider}/{model}), {len(rows)} requests")
    print(f"  request hit rate {hits / len(rows):5.1%} | token hit ratio {read / total_in:5.1%} "
          f"| written {written / total_in:5.1%} of input")
    print(f"  cost ${actual:.2f}" + (f" (incl. ${stored:.2f} cache storage)" if stored else "")
          + f" vs ${without:.2f} without caching -> {'saved' if without >= actual else 'LOST'} "
          f"${abs(without - actual):.2f}")

    # --- likely causes ---
    minimum = table.model(provider, model).min_cacheable_tokens    # from prices.yaml; None = unpublished
    prefixes = {r["prefix"] for r in rows}
    reads_by_prefix = defaultdict(int)
    for r in rows:
        reads_by_prefix[r["prefix"]] += r["cached_input_tokens"]
    write_only = [p for p in prefixes if reads_by_prefix[p] == 0 and
                  any(r["prefix"] == p and r["cache_write_tokens"] for r in rows)]
    if minimum and all(total_input(r) < minimum for r in rows):
        print(f"  ! prompt below the {minimum:,}-token minimum: never cacheable")
    if len(write_only) > 0.5 * len(prefixes) and len(prefixes) > 3:
        print(f"  ! {len(write_only)} of {len(prefixes)} prefixes were written and never read "
              f"(one-off prompts, or a prefix that changes every request)")
    writes_at = defaultdict(list)
    for r in rows:
        if r["cache_write_tokens"]:
            writes_at[r["prefix"]].append(dt.datetime.fromisoformat(r["ts"]))
    for p, times in writes_at.items():
        burst = [t for t in times if t - times[0] < dt.timedelta(seconds=5)]
        if len(burst) > 1:
            print(f"  ! {len(burst)} writes of prefix {p!r} within 5 s: parallel cold start, warm it first")
    hourly = defaultdict(lambda: [0, 0])
    for r in rows:
        h = r["ts"][11:13]
        hourly[h][0] += r["cached_input_tokens"]
        hourly[h][1] += total_input(r)
    ratios = {h: c / t for h, (c, t) in sorted(hourly.items()) if t}
    drops = [h for h, prev in zip(list(ratios)[1:], list(ratios.values())[:-1])
             if prev > 0.5 and ratios[h] < 0.1]
    if drops:
        print(f"  ! token hit ratio fell from >50% to <10% at {drops[0]}:00 UTC: what was deployed?")
Output · on the fixture log24 lines
nightly-summaries (anthropic/claude-haiku-5-5), 20 requests
  request hit rate  0.0% | token hit ratio  0.0% | written 99.6% of input
  cost $0.08 vs $0.07 without caching -> LOST $0.01
  ! 20 writes of prefix 'digest-v2' within 5 s: parallel cold start, warm it first

support-bot (anthropic/claude-sonnet-5-5), 295 requests
  request hit rate 86.8% | token hit ratio 85.0% | written 13.8% of input
  cost $1.90 vs $6.10 without caching -> saved $4.19
  ! 38 of 39 prefixes were written and never read (one-off prompts, or a prefix that changes every request)
  ! token hit ratio fell from >50% to <10% at 13:00 UTC: what was deployed?

faq (gemini/gemini-3.8-flash), 200 requests
  request hit rate  0.0% | token hit ratio  0.0% | written  0.0% of input
  cost $0.54 vs $0.54 without caching -> saved $0.00
  ! prompt below the 4,096-token minimum: never cacheable

contract-qa (openai/gpt-6.1-sol), 40 requests
  request hit rate 35.0% | token hit ratio 34.8% | written 64.6% of input
  cost $4.25 vs $5.06 without caching -> saved $0.82
  ! 15 of 29 prefixes were written and never read (one-off prompts, or a prefix that changes every request)

manual-qa (gemini/gemini-3.8-flash), 14 requests
  request hit rate 100.0% | token hit ratio 99.9% | written  0.0% of input
  cost $1.02 (incl. $0.80 cache storage) vs $2.11 without caching -> saved $1.09

What it found, and what you'd do:

  • nightly-summaries fired 20 requests at a cold 30,000-token prefix in the same second. Every one wrote the cache and none read it, so caching lost money. Fix: pre-warm, then fan out (6.6).
  • support-bot saved $4.19 (69%) on the day, but the hourly view shows the hit ratio collapsing at 13:00, and 38 one-off prefixes appearing. That's the signature of a deploy that put something variable (here, the current time) into the system prompt. The fingerprint tells you exactly when it changed; the next section stops it happening.
  • faq never caches, because its 3,000-token prompt is below Gemini's implicit-caching minimum (8.1). Nothing to fix unless the prompt grows; don't expect savings.
  • contract-qa writes a 60,000-token contract to the cache on every first question, but only 14 of the 40 requests (35%) were second questions that read it. It still saved $0.82, because those second questions paid for the rest; with fewer of them it would have lost money, so the question to ask is how often a second question arrives (Part 11): if rarely, cache only when one does.
  • manual-qa reads a 200,000-token manual from a Gemini explicit cache on every request (99.9% token hit ratio) and still saves only $1.09 on $2.11, because $0.80 of its $1.02 is storage. Without the storage line in the analyser it would look like a saving of about $1.90. Fourteen questions in eight hours is above the break-even of eight (11.2), so it wins, but not by as much as the hit ratio suggests.

10.3 Diagnosing a miss#

This table is the API-level view: which field or diagnostic names each cause. The full debugging checklist, in the order it usually bites, is in 11B.4, Part 8.

Cause What you see in the logs Fix
The prefix changed (timestamp, user name or request ID in the system prompt; tools in a different order; JSON key order; a re-summarized history) Writes on every request, many distinct fingerprints, diagnostics system_changed / tools_changed / messages_changed (Anthropic) or input_changed / tools_changed (OpenAI) Deterministic request building (10.4); dynamic data after the last breakpoint
Below the minimum (each provider's rule: 6.4, 7.1, 8.1) Read and write both zero, always Accept it, or extend a near-miss prefix if it's reused often
Lifetime expired (gaps longer than 5 minutes on Anthropic's default, 30 minutes on OpenAI's) Reads after quick follow-ups, writes after slow ones; Anthropic diagnostics None with zero reads 1h (Anthropic) or 12h (OpenAI) breakpoints for slow traffic, if the break-even works (Part 11)
Parallel cold start A burst of writes of the same fingerprint within a second or two Pre-warm, then fan out
Different model, tier or provider (a fallback, an A/B test, a router; on OpenRouter, a failover) Writes whenever the model or provider_name changes; diagnostics model_changed or service_tier_changed Keep the model fixed within a cached conversation; use sticky routing on OpenRouter
Prompt-affecting settings changed (tool_choice, images, thinking, effort, verbosity, text.format) Message-level misses with the same system and tools; Anthropic diagnostics unavailable, OpenAI reasoning_effort_changed, verbosity_changed or text_format_changed Keep them constant per conversation
Different workspace, organization, project or region No reads across them, ever Expected: caches are isolated (6.7, 7.8)
Anthropic breakpoint on the varying block, or past the 20-block lookback Writes on every request with an identical system prompt Move the breakpoint to the last stable block; add a second breakpoint for long agent turns (6.2)
Gemini 4 short turns Each short turn pays full price for 2,050 tokens Expected behaviour (8.1)

10.4 A cache-aware request builder#

02.7, 7.4 listed the design rules: stable content first, deterministic tool order, sorted JSON keys, dynamic data at the end. Here they are as code, and proof that they matter: the sample builds the same two requests two ways and captures the exact bytes the real anthropic SDK sends (to a mock server, so nothing leaves your machine). Save as s10_request_builder.py:

python
"""A cache-aware request builder: byte-stable tools and system blocks, dynamic data after the
breakpoint, and a prefix fingerprint to log with every call."""
import datetime as dt
import hashlib
import json
import random
from typing import Any

import anthropic
import httpx2

# --- what the app has: tools registered in whatever order modules happened to import ---
REGISTRY = {
    "start_return": {"description": "Open a return for an order.",
                     "input_schema": {"type": "object", "required": ["order_id"],
                                      "properties": {"order_id": {"type": "string"}}}},
    "lookup_order": {"description": "Look up an order by its ID.",
                     "input_schema": {"properties": {"order_id": {"type": "string"}},
                                      "type": "object", "required": ["order_id"]}},
}
INSTRUCTIONS = "You are Acme's returns assistant. Answer from the policy only."
POLICY = "Acme returns policy. " * 300


def canonical(obj: Any) -> Any:
    """Same content -> same bytes: sort dict keys recursively (lists keep their order)."""
    return json.loads(json.dumps(obj, sort_keys=True))


def build(question: str, user_name: str, now: dt.datetime) -> dict:
    tools = [canonical({"name": n, **REGISTRY[n]}) for n in sorted(REGISTRY)]   # fixed order
    tools[-1]["cache_control"] = {"type": "ephemeral"}            # breakpoint after the tools
    system = [{"type": "text", "text": INSTRUCTIONS},
              {"type": "text", "text": POLICY, "cache_control": {"type": "ephemeral"}}]
    # Per-request facts go AFTER the last breakpoint, in the user turn, never in the system prompt
    user = f"[context] date={now:%Y-%m-%d} customer={user_name}\n\n{question}"
    return {"model": "claude-haiku-5-5", "max_tokens": 400, "tools": tools, "system": system,
            "tool_choice": {"type": "auto"}, "messages": [{"role": "user", "content": user}]}


def prefix_fingerprint(req: dict) -> str:
    """Hash everything the provider renders BEFORE the varying part. Log it with every call:
    when the hit rate drops, a new fingerprint tells you the prefix changed (and when)."""
    keys = ("model", "tools", "system", "tool_choice")              # + thinking/effort if you set them
    return hashlib.sha256(json.dumps({k: req.get(k) for k in keys}, sort_keys=True).encode()).hexdigest()[:12]


def naive(question: str, user_name: str, now: dt.datetime) -> dict:
    """What often happens: tools from an unordered source, the time in the system prompt."""
    names = list(REGISTRY)
    random.shuffle(names)
    return {"model": "claude-haiku-5-5", "max_tokens": 400,
            "tools": [{"name": n, **REGISTRY[n]} for n in names],
            "system": f"Today is {now:%Y-%m-%d %H:%M:%S}. Customer: {user_name}. {INSTRUCTIONS} {POLICY}",
            "messages": [{"role": "user", "content": question}]}


# Capture the exact bytes the real anthropic SDK would send (mock server: nothing leaves the machine)
sent: list[bytes] = []
def handler(request: httpx2.Request) -> httpx2.Response:
    sent.append(request.content)
    return httpx2.Response(200, json={"id": "msg_x", "type": "message", "role": "assistant",
                                      "model": "claude-haiku-5-5", "content": [], "stop_reason": "end_turn",
                                      "usage": {"input_tokens": 1, "output_tokens": 1}})

client = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))
random.seed(3)
t1 = dt.datetime(2026, 11, 4, 9, 0, 0)
t2 = t1 + dt.timedelta(seconds=40)


def prefix_bytes(body: bytes) -> str:
    """Hash the wire body minus the messages: the part the cache can reuse."""
    data = json.loads(body)
    data.pop("messages")
    return hashlib.sha256(json.dumps(data).encode()).hexdigest()[:12]   # key order as sent


for label, make in [("naive  ", naive), ("builder", build)]:
    sent.clear()
    for who, t, q in [("Asha", t1, "Can I return shoes?"), ("Ben", t2, "Can I return a lamp?")]:
        client.messages.create(**make(q, who, t))
    a, b = prefix_bytes(sent[0]), prefix_bytes(sent[1])
    print(f"{label} prefix bytes: {a} vs {b} -> {'SAME: cache can hit' if a == b else 'DIFFERENT: miss'}")

req = build("Can I return shoes?", "Asha", t1)
print("fingerprint to log:", prefix_fingerprint(req))
Output3 lines
naive   prefix bytes: 2b59a4ffd812 vs 95682cd0b0d3 -> DIFFERENT: miss
builder prefix bytes: 784441ad0074 vs 784441ad0074 -> SAME: cache can hit
fingerprint to log: c1fb5a4383f9

The naive version produced a different prefix on every request: the tool registry was iterated in a different order, and the system prompt contained the time and the customer's name. Neither request could ever read the other's cache entry. The builder produced byte-identical prefixes, because:

  • tools are sorted by name and every schema is serialized with sorted keys (the SDKs send dicts in insertion order; Anthropic's troubleshooting list warns that some languages "randomize key order during JSON conversion, breaking caches");
  • the system blocks are constants;
  • per-request facts (date, customer) go in the user turn, after the last breakpoint;
  • a prefix fingerprint is computed from exactly what precedes the varying part (add any settings your provider renders into the prompt, such as thinking or effort), and logged with every call, so a change is visible the minute it's deployed.

Part 11: Cache economics in code#

Deep-dive

11.1 Break-even for token-priced caches#

The formula is derived, with a table of every lifetime and the eight cases where caching loses money, in 11B.4, Part 5. For the economics of response and semantic caches see 11B.3, Part 6. This section is the calculator, read from prices.yaml.

On Anthropic and OpenAI (GPT-5.6 and later), a cached prefix costs a write the first time and a read after that, both as multiples of the normal input price. If n requests share the prefix within one lifetime:

  • without caching you pay n × the prefix at the input price;
  • with caching you pay 1 write + (n − 1) reads.

Caching wins when write + (n − 1) × read < n. With Anthropic's 5-minute write (1.25) and read (0.1): two requests cost 1.25 + 0.1 = 1.35 instead of 2, so it pays from the second request, which is what Anthropic's pricing page says ("caching pays off after one cache read for the 5-minute duration"). One request alone costs 1.25 instead of 1: a 25% surcharge for nothing. The calculator does this for every lifetime, reading each multiplier from prices.yaml instead of repeating it here (so a price change changes the answer, and so does a new model's row). Save as s11_break_even.py:

python
"""Cache economics: how many reuses within one lifetime before caching a prefix pays off?
Every multiplier and price is read from prices.yaml, so a price change changes the answer."""
import datetime as dt
import math

from prices import PriceTable

table = PriceTable.load()
TODAY = dt.date(2026, 11, 4)


def token_cache_break_even(write_mult: float, read_mult: float) -> int:
    """Smallest n (requests sharing the prefix within one lifetime) where
    write + (n - 1) reads < n uncached sends. Multipliers are relative to the input price."""
    # write + (n-1)*read < n  <=>  n > (write - read) / (1 - read)
    return math.floor(round((write_mult - read_mult) / (1 - read_mult), 9)) + 1


def gemini_explicit_cost(prefix: int, n: int, hours: float, input_price: float,
                         cached_price: float, storage_per_hour: float) -> float:
    """Explicit cache: create at the input price, store per hour, read n times at the cached price."""
    m = prefix / 1_000_000
    return m * input_price + m * storage_per_hour * hours + n * m * cached_price


def gemini_break_even(input_price: float, cached_price: float, storage_per_hour: float, hours: float) -> int:
    """create + storage + n*cached < n*input. The prefix size cancels out."""
    return math.floor((input_price + storage_per_hour * hours) / (input_price - cached_price)) + 1


print("Token-priced caches: break-even = requests within ONE lifetime (multipliers from prices.yaml)")
for provider, model, write in [("anthropic", "claude-haiku-5-5", "cache_write_5m"),
                               ("anthropic", "claude-haiku-5-5", "cache_write_1h"),
                               ("anthropic", "claude-opus-5-5", "cache_write_1h"),
                               ("anthropic", "claude-fable-5-1", "cache_write_1h"),
                               ("openai", "gpt-6-luna", "cache_write_30m"),
                               ("openai", "gpt-6-luna", "cache_write_12h"),
                               ("openai", "gpt-6.1-terra", "cache_write_12h")]:
    r = table.period(provider, model, TODAY).rates
    w, rd = r[write] / r["input"], r["cached_input"] / r["input"]
    print(f"  {model:18s} {write[12:]:>3s} write x{w:<5g} read x{rd:<6g} pays off from "
          f"{token_cache_break_even(w, rd)} requests; write-only surcharge +{w - 1:.0%}")

# Gemini explicit cache: a 200K-token manual kept for an 8-hour shift
P, HOURS = 200_000, 8
flash26 = table.period("gemini", "gemini-3.8-flash", dt.date(2026, 11, 4)).rates
flash27 = table.period("gemini", "gemini-3.8-flash", dt.date(2027, 1, 1)).rates
print(f"\nGemini 3.8 Flash explicit cache, {P:,}-token prefix kept {HOURS} h (2026 prices):")
for n in [1, 5, 10, 20, 40, 80]:
    cached = gemini_explicit_cost(P, n, HOURS, flash26["input"], flash26["cached_input"], flash26["cache_storage_per_hour"])
    plain = n * P / 1_000_000 * flash26["input"]
    print(f"  {n:3d} questions: cache ${cached:6.3f} vs no cache ${plain:6.3f}  "
          f"{'cache wins' if cached < plain else 'no cache wins'}")

print("\nBreak-even questions within the lifetime (the prefix size cancels out):")
n26 = gemini_break_even(flash26["input"], flash26["cached_input"], flash26["cache_storage_per_hour"], HOURS)
print(f"  3.8 Flash, 2026 prices:                      {n26} questions in {HOURS} h (about {n26 / HOURS:.1f} per hour)")
n27 = gemini_break_even(flash27["input"], flash27["cached_input"], flash27["cache_storage_per_hour"], HOURS)
print(f"  3.8 Flash, 1 Jan 2027 (every rate doubles):  {n27} questions in {HOURS} h")
only = gemini_break_even(flash26["input"], flash26["cached_input"], flash26["cache_storage_per_hour"] * 2, HOURS)
print(f"  3.8 Flash, ONLY the storage rate doubled:    {only} questions in {HOURS} h")
lite = table.period("gemini", "gemini-3.5-flash-lite", TODAY).rates
nl = gemini_break_even(lite["input"], lite["cached_input"], lite["cache_storage_per_hour"], HOURS)
print(f"  3.5 Flash-Lite (storage dearer vs input):    {nl} questions in {HOURS} h")
Output22 lines
Token-priced caches: break-even = requests within ONE lifetime (multipliers from prices.yaml)
  claude-haiku-5-5    5m write x1.25  read x0.1    pays off from 2 requests; write-only surcharge +25%
  claude-haiku-5-5    1h write x2     read x0.1    pays off from 3 requests; write-only surcharge +100%
  claude-opus-5-5     1h write x2     read x0.05   pays off from 3 requests; write-only surcharge +100%
  claude-fable-5-1    1h write x2     read x0.025  pays off from 3 requests; write-only surcharge +100%
  gpt-6-luna         30m write x1.25  read x0.1    pays off from 2 requests; write-only surcharge +25%
  gpt-6-luna         12h write x2.5   read x0.1    pays off from 3 requests; write-only surcharge +150%
  gpt-6.1-terra      12h write x2.5   read x0.05   pays off from 3 requests; write-only surcharge +150%

Gemini 3.8 Flash explicit cache, 200,000-token prefix kept 8 h (2026 prices):
    1 questions: cache $ 0.965 vs no cache $ 0.150  no cache wins
    5 questions: cache $ 1.025 vs no cache $ 0.750  no cache wins
   10 questions: cache $ 1.100 vs no cache $ 1.500  cache wins
   20 questions: cache $ 1.250 vs no cache $ 3.000  cache wins
   40 questions: cache $ 1.550 vs no cache $ 6.000  cache wins
   80 questions: cache $ 2.150 vs no cache $12.000  cache wins

Break-even questions within the lifetime (the prefix size cancels out):
  3.8 Flash, 2026 prices:                      8 questions in 8 h (about 1.0 per hour)
  3.8 Flash, 1 Jan 2027 (every rate doubles):  8 questions in 8 h
  3.8 Flash, ONLY the storage rate doubled:    13 questions in 8 h
  3.5 Flash-Lite (storage dearer vs input):    31 questions in 8 h

The token-priced caches all pay off from the second or third request within one lifetime (a cheaper read, like the 0.025× on Anthropic's Fable models, doesn't change that: the write premium is what you have to earn back), and the long lifetimes have the biggest downside: a 12-hour OpenAI write that's never read costs 150% more than not caching. Remember that "within one lifetime" is measured per entry: on Anthropic each read refreshes a 5-minute entry for free, so steady traffic keeps one write alive all day; on Gemini's explicit caches, you pay storage whether or not anyone reads.

11.2 Explicit Gemini caches: storage changes the shape#

Gemini's explicit cache has no write premium, but it charges storage per hour. The calculator's second half compares a 200,000-token manual kept for an 8-hour shift on Gemini 3.8 Flash (2026 prices). The break-even is 8 questions in 8 hours, about one an hour, just to cover storage. Below that, no caching is cheaper; well above it, the cache wins by a wide margin. The prefix size cancels out of the formula, so the same 8 holds for a 20,000-token manual.

Two caveats the numbers hide:

  • The real alternative isn't "no caching". Implicit caching is free and automatic on the same model. If your requests arrive close together with the same prefix, implicit hits may give you most of the saving with no storage bill and no lifecycle to manage. Measure the implicit hit ratio first (Part 10); create an explicit cache when implicit hits are unreliable (traffic too sparse for implicit entries to survive, or a prefix you need to guarantee).
  • The 1 January 2027 price change doesn't move the break-even. All of 3.8 Flash's rates double that day (input to $1.50, cached input to $0.15, storage to $1.00 per million tokens per hour), and the break-even is a ratio: (0.75 + 0.50 × 8) ÷ (0.75 − 0.075) and (1.50 + 1.00 × 8) ÷ (1.50 − 0.15) both come to 7.04, so both mean 8 questions in 8 hours. What doubles is the money: the cost of each question and the dollar saving. The break-even would move only if the storage price changed alone (doubling just the storage rate gives 13 questions) or if the cached price stopped being a fixed fraction of input. Models differ more than dates do: on 3.5 Flash-Lite, whose storage is $1.00 against a $0.30 input price, the break-even for the same shift is 31 questions. A dated price table (Part 4) keeps the dollar figures honest, and the calculator above prints all of these.

11.3 When not to cache#

  • Prompts you send once (one-off documents, evaluation runs over unique inputs). On OpenAI GPT-5.6+, turn caching off (7.6); on Anthropic, don't add a breakpoint.
  • Prefixes below the minimum, or traffic slower than the lifetime. Nothing breaks, but don't count on savings: a prefix reused every 20 minutes never hits a 5-minute cache, so either the longer lifetime pays (three or more uses per hour on Anthropic's 1h) or caching doesn't.
  • Prefixes that change faster than they're reused, and parallel fan-outs without a warm-up. Restructure first (10.4) and warm once (6.6); otherwise every request pays a write. 11B.4, 5.2 lists all eight loss cases.
  • When a shared cache is a risk. If cache-hit timing could leak whether another tenant sent something, isolate with OpenAI's per-tenant prompt_cache_key or separate Anthropic workspaces, and accept the lower hit rate (11B.3, 2.8 has the threat model).

Two benefits that don't appear in the dollar calculation, but can tip a borderline case: cache hits cut time to first token on long prompts (02.7, 6.3), and on most Claude models cache reads don't count toward input-tokens-per-minute limits (6.7).


Part 12: Controlling spend#

Deep-dive

Measuring cost tells you what happened. Controlling it means deciding before the call. This part covers the per-call and per-user controls in your own code, then the limits the providers enforce. Cost strategy (which model for which task, cascades, response caching, routing) is Module 11B's; these are the guard rails that every LLM feature needs from day one.

12.1 max_output_tokens is your ceiling#

Input you can count; output you can only cap. The cap is the one hard limit on what a single call can cost:

Provider Parameter
OpenAI max_output_tokens (Responses); max_completion_tokens (Chat Completions)
Anthropic max_tokens (required on every request)
Gemini GenerateContentConfig(max_output_tokens=...); Interactions generation_config.max_output_tokens
OpenRouter max_tokens / max_completion_tokens (Chat Completions); max_output_tokens (Responses)

So the worst case of a call is: input tokens × input price + cap × output price. Three things to remember:

  • Reasoning tokens count against the cap on every provider (02.2, 10.3). A cap that's comfortable for the visible answer can be used up by thinking, and the call is still billed for every token it generated. Lowering reasoning effort is often a better cost lever than lowering the cap.
  • A cap that's too low costs more than it saves: a truncated answer is a failed request you paid for, and the retry pays again (02.5, 4.6). Set the cap from the output lengths you actually see (the p99 from your tracker, 5.7), plus headroom, and watch the share of status: truncated records (5.2): it's the price of a cap that is too low, measured.
  • On Anthropic, max_tokens doesn't count toward your output-tokens-per-minute limit; only tokens actually generated do (lesson 03.8).

12.2 A per-request cost guard#

A cost guard runs before the call: it estimates the worst case (counted or estimated input, plus the output cap at the output price) and, if that's over a per-request cap, tries a cheaper option before refusing. Combined with per-user budgets (12.3), it looks like this. Save as s12_cost_guard.py:

python
"""A per-request cost guard plus per-user budgets: estimate the worst case before sending,
downgrade or refuse when it's over budget, then settle with the real cost."""
import datetime as dt
import threading
from dataclasses import dataclass

from cost_calc import Usage, price
from prices import PriceTable

table = PriceTable.load()
DAY = dt.date(2026, 11, 4)

# Cheapest acceptable model last. Each rung must pass YOUR evals for this feature (Module 10A).
LADDER = [("anthropic", "claude-sonnet-5-5"), ("anthropic", "claude-haiku-5-5")]


def worst_case_usd(provider: str, model: str, input_tokens: int, max_output_tokens: int) -> float:
    """Upper bound: every input token uncached, and the model uses its whole output allowance
    (reasoning tokens count against it too)."""
    return price(Usage(provider, model, input=input_tokens, output=max_output_tokens), table, DAY).usd


@dataclass
class Decision:
    action: str          # send | downgrade | refuse
    provider: str = ""
    model: str = ""
    max_output_tokens: int = 0
    reserved_usd: float = 0.0
    reason: str = ""


class Budgets:
    """Per-user daily budgets with reserve-then-settle. Use Redis or your DB in production
    (atomic increments), so concurrent requests can't all pass the same check."""
    def __init__(self, daily_usd: float) -> None:
        self.daily, self.spent, self.reserved = daily_usd, {}, {}
        self.lock = threading.Lock()

    def try_reserve(self, user: str, usd: float) -> bool:
        with self.lock:
            used = self.spent.get(user, 0.0) + self.reserved.get(user, 0.0)
            if used + usd > self.daily:
                return False
            self.reserved[user] = self.reserved.get(user, 0.0) + usd
            return True

    def settle(self, user: str, reserved: float, actual: float | None) -> None:
        with self.lock:
            self.reserved[user] -= reserved
            # Unknown cost (failed call, broken stream): charge the reservation, to be safe
            self.spent[user] = self.spent.get(user, 0.0) + (reserved if actual is None else actual)


def guard(user: str, input_tokens: int, max_output_tokens: int, per_request_cap: float,
          budgets: Budgets) -> Decision:
    over_budget = False
    for i, (provider, model) in enumerate(LADDER):
        for out in (max_output_tokens, max_output_tokens // 2):      # then try a smaller ceiling
            worst = worst_case_usd(provider, model, input_tokens, out)
            if worst > per_request_cap:
                continue
            if not budgets.try_reserve(user, worst):                  # a cheaper rung may still fit
                over_budget = True
                continue
            action = "send" if (i == 0 and out == max_output_tokens) else "downgrade"
            return Decision(action, provider, model, out, worst, f"worst case ${worst:.4f}")
    why = f"daily budget ${budgets.daily:.2f} used up" if over_budget else \
        f"over the ${per_request_cap} per-request cap on every rung"
    return Decision("refuse", reason=why)


budgets = Budgets(daily_usd=0.20)
cases = [("asha", 8_000, 2_000), ("asha", 60_000, 4_000), ("asha", 400_000, 8_000),
         ("ben", 20_000, 2_000), ("ben", 20_000, 2_000), ("ben", 20_000, 2_000),
         ("ben", 20_000, 2_000), ("ben", 20_000, 2_000), ("ben", 20_000, 2_000)]
for user, inp, out in cases:
    d = guard(user, inp, out, per_request_cap=0.10, budgets=budgets)
    print(f"{user:4s} in={inp:>7,} max_out={out:>5,} -> {d.action:9s} {d.model:17s} "
          f"max_out={d.max_output_tokens:>5,} {d.reason}")
    if d.action != "refuse":       # pretend the call ran and used 30% of its output allowance
        actual = price(Usage(d.provider, d.model, input=inp, output=int(d.max_output_tokens * 0.3)),
                       table, DAY).usd
        budgets.settle(user, d.reserved_usd, actual)
print({u: round(v, 4) for u, v in budgets.spent.items()})
Output10 lines
asha in=  8,000 max_out=2,000 -> send      claude-sonnet-5-5 max_out=2,000 worst case $0.0360
asha in= 60,000 max_out=4,000 -> downgrade claude-haiku-5-5  max_out=4,000 worst case $0.0080
asha in=400,000 max_out=8,000 -> refuse                      max_out=    0 over the $0.1 per-request cap on every rung
ben  in= 20,000 max_out=2,000 -> send      claude-sonnet-5-5 max_out=2,000 worst case $0.0600
ben  in= 20,000 max_out=2,000 -> send      claude-sonnet-5-5 max_out=2,000 worst case $0.0600
ben  in= 20,000 max_out=2,000 -> send      claude-sonnet-5-5 max_out=2,000 worst case $0.0600
ben  in= 20,000 max_out=2,000 -> send      claude-sonnet-5-5 max_out=2,000 worst case $0.0600
ben  in= 20,000 max_out=2,000 -> downgrade claude-haiku-5-5  max_out=2,000 worst case $0.0030
ben  in= 20,000 max_out=2,000 -> downgrade claude-haiku-5-5  max_out=2,000 worst case $0.0030
{'asha': 0.0286, 'ben': 0.1886}

Reading the decisions:

  • Asha's first request fits on Sonnet 5.5 within the $0.10 per-request cap ($0.036 worst case).
  • Her 60,000-token request would cost up to $0.16 on Sonnet, so the guard tried a smaller output cap (still too much) and then downgraded to Haiku 5.5 ($0.008).
  • Her 400,000-token request is refused on every rung: on Haiku 5.5 it crosses the 100,000-token step, so even the cheapest rung could cost over $0.20. Refusing before sending is the point: a 400,000-token request you didn't mean to send is exactly the bug a guard exists for.
  • Ben sends the same request six times. Four fit his $0.20 daily budget on Sonnet; then the remaining budget can't cover Sonnet's $0.06 worst case, and the guard downgrades to Haiku instead of refusing.

Design rules worth keeping:

  • Every rung of the ladder must pass your evaluations for that feature (Module 10A). A downgrade that produces wrong answers is not a saving.
  • Refusals need a user-facing message and a log line, so support can tell a budget refusal from an outage.
  • Use the counting endpoints (Part 2) for the input side when the decision is close; use the local estimate when it isn't.
  • The guard is not your only line of defence. Provider-side limits (12.4) catch what your code doesn't, for example a leaked key used from outside your app.

12.3 Per-user and per-feature budgets#

A budget ("$5 per user per day", "$200 per day for the nightly summarizer") has the classic concurrency problem: ten requests check the same balance at the same moment, all see room, and all spend. The fix is reserve, then settle:

sequenceDiagram
    participant H as Request handler
    participant B as Budget store
    participant P as Provider
    participant T as Cost tracker
    H->>B: reserve worst-case cost for user U
    alt over budget
        B-->>H: no
        H-->>H: downgrade, or refuse
    else within budget
        B-->>H: reserved
        H->>P: call with max_output_tokens cap
        P-->>H: response and usage
        H->>T: price the real usage
        T-->>H: actual cost
        H->>B: settle: release reservation, add actual cost
    end
  • Reserve the worst case atomically before the call (a Redis INCRBYFLOAT with a check, a database row lock or a compare-and-set). Budgets in 12.2 shows the logic with a thread lock; in production the store must be shared by every process.
  • Settle with the actual cost when the call finishes, releasing the difference.
  • If the cost is unknown (a broken stream, an error after the provider started), keep the reservation as spent. Over-charging a budget by a few cents is better than letting failures spend for free.
  • Budgets need a window (per UTC day, per calendar month) that matches how you'll explain them to users and finance.
  • Per-feature budgets protect you from one runaway job (an agent loop, a re-run batch) eating the month's spend. Give batch and background features their own budgets and their own provider projects or keys.

12.4 Limits on the provider's side#

Your code's guards protect your budget from your code. Provider-side limits protect it from everything else: a bug that bypasses the guard, a leaked key, a runaway batch. Lesson 03.1, 3.3 lists the console settings and what happens when each limit trips; here's what you can do in code, as of November 2026:

Provider Programmatic control Notes
OpenAI Admin API: organization spend alerts (client.admin.organization.spend_alerts.create(currency="USD", interval="month", threshold_amount=..., notification_channel=...)) and the hard spend limit (client.admin.organization.spend_limit.update(currency="USD", interval="month", threshold_amount=...)), with project-level equivalents Amounts are in cents; monthly only. Needs an admin key (OPENAI_ADMIN_KEY). A tripped hard limit returns 429 (lesson 03.8)
Anthropic Admin API: client.beta.organization.spend_limits.set(amount=..., scope=..., period=...), plus list, retrieve, delete Amounts are integer strings in cents ("50000" is $500.00). For Claude Console organizations, setting organization and workspace limits "is in an early access preview" (SDK 2.4.0 docstring); otherwise set them in the Console. Two different limits fail differently (rate limits page): the monthly spend cap of your tier returns 429 rate_limit_error with error.details.error_code: "enforced_spend_limit_reached" and no retry-after, so the SDK's automatic retries just burn time until access resumes; a spend limit you set yourself returns 400 invalid_request_error ("You have reached your specified API usage limits", or "...workspace API usage limits"). A wrapper that treats every 429 as "slow down" retries the first one forever, and one that treats every 400 as "your request is malformed" mislabels the second. Lesson 03.8, 4.2 owns the handling
Google Gemini Project spend caps in AI Studio (Spend page), plus the billing account's tier cap; no API Experimental; Google warns of overages during "around a 10 minute latency period", especially from batch jobs and agents. With Prepay billing, requests fail with 402 when the credit balance reaches $0
OpenRouter Per-key credit limit with limit_reset (daily, weekly, monthly), workspace budgets and guardrail budgets; read the state with GET /api/v1/key (9.3) A key or budget limit returns 403 with error.metadata.limit_source (openrouter_key_limit, openrouter_workspace_budget, openrouter_guardrail_budget), limit_usd, spend_usd and resets_at; running out of credits is 402. Handling them is lesson 03.8's subject

12.5 Alerts that catch cost problems early#

The tracker's records make good alerts possible. The ones that catch real incidents:

Alert Catches
Spend per feature per hour above N× its trailing average Runaway loops, retry storms, a traffic spike, a leaked key
p95 cost per request up by more than X% day over day A prompt that grew (more history, more retrieved chunks), a model switch, reasoning effort raised
Token hit ratio for a cached feature drops below its baseline A deploy that broke the prefix (10.2)
Share of cost_source: unknown records above 1% A new model missing from the price table, a provider field change, broken streams
Requests crossing a long-context threshold (272K on OpenAI, 100K on Haiku 5.5) Prompts that just tipped into the higher rates for the whole request
Reasoning share of output above a set level Effort settings or prompts that make the model think far more than expected
Share of status: truncated records above its baseline An output cap that is too low (or a prompt that now asks for more): paid-for answers you can't use
Daily total vs the provider's reported cost differs by more than a few percent Missing records, wrong prices (13.5)

Plus the provider-side spend alerts from 12.4. Dashboards and alerting platforms are Module 11A's subject; what matters here is that the records exist, with the fields from 5.1.


Part 13: Organization usage and cost APIs, and reconciliation#

Reference

Your tracker records what your code saw. The providers record what they billed. The two should agree, and the providers' admin APIs let you check automatically. These APIs need elevated credentials (an OpenAI admin key, an Anthropic Admin API key, an OpenRouter management key) that can read your whole organization's data, and some can change limits and keys. Give them only to a reporting job, store them in your secret manager, and never load them into the application that serves users.

13.1 OpenAI: Usage and Costs APIs#

Both live under the admin client in openai 3.42.1: OpenAI(admin_api_key=...) (or the OPENAI_ADMIN_KEY environment variable), then client.admin.organization.usage.*:

  • usage.completions(start_time=, end_time=, bucket_width=, group_by=, ...) (GET /v1/organization/usage/completions): token usage in time buckets (1m, 1h or 1d; per page up to 1,440, 168 and 31 buckets respectively), optionally grouped by project_id, user_id, api_key_id, model, batch, service_tier or api_source, and filterable by the same. Each result has num_model_requests, input_tokens, input_uncached_tokens, input_cached_tokens, input_cache_write_tokens (with input_cache_write_30m_tokens and input_cache_write_12h_tokens), output_tokens, per-modality counts, and the grouping fields. There are sibling endpoints for embeddings, images, audio, moderations, web search calls, file search, code interpreter sessions and vector stores.
  • usage.costs(start_time=, end_time=, group_by=, ...) (GET /v1/organization/costs): money, in daily buckets only (bucket_width="1d"), grouped by project_id, user_id, line_item, api_key_id or api_source, up to 180 buckets per page. Each result has amount.value and amount.currency (lowercase ISO 4217, such as "usd"), and, when grouped by line_item, quantity and quantity_unit.

Times are Unix seconds (start_time inclusive, end_time exclusive), and results are paginated with page / next_page. Grouping by project_id is why separate projects per environment and feature pay off (5.6).

13.2 Anthropic: Usage and Cost Analytics API#

Anthropic has two generations of this API, as of November 2026:

  • The Usage and Cost Analytics API (recommended for new integrations; beta): GET /v1/organizations/analytics/usage and GET /v1/organizations/analytics/cost, with the anthropic-beta: analytics-usage-cost-2026-08-24 header, which the SDK sends for you. In anthropic 2.4.0: client.beta.organization.analytics.usage.list(...) and .cost.list(...), which page automatically.
    • Rows, not buckets: each row has starting_at, ending_at, a group (every dimension, null unless you grouped by it) and usage or cost. group_by takes up to five dimensions, including model, workspace_id, api_key_id, service_tier, speed, inference_geo, context_window and actor (the user or service account behind a request); the cost endpoint adds cost_type and token_type. time_bucket_width (1m, 1h or 1d) is optional; without it you get totals for the range.
    • Usage rows have uncached_input_tokens, cache_creation.ephemeral_5m_input_tokens / ephemeral_1h_input_tokens, cache_read_input_tokens, output_tokens, server_tool_use.web_search_requests and requests.
    • Cost rows have amount ("the cost after discounts and before any credits are applied"), list_amount, currency (always "USD") and requests. Amounts are decimal strings in cents: "41280.000000" is $412.80. Token types are uncached_input_tokens, cache_read_input_tokens, cache_creation.ephemeral_5m_input_tokens, cache_creation.ephemeral_1h_input_tokens and output_tokens.
    • Freshness: every response has data_refreshed_at; data "typically refreshes within 4 hours" and "can take up to 24 hours", and values can be revised until about 7 days after the month ends. Ranges start on or after 1 January 2026, within the last 365 days, and span at most 31 days.
    • Priority Tier requests appear with service_tier: "priority" but "contribute zero token cost", because the commitment fee is billed separately.
  • The Usage and Cost API (legacy, still supported): GET /v1/organizations/usage_report/messages and GET /v1/organizations/cost_report, no beta header, data "typically appears within 5 minutes", costs in cents, daily cost buckets, and "Priority Tier costs ... are not included in the cost endpoint". anthropic 2.4.0 has no methods for these two paths, so call them over HTTP if you need their 5-minute freshness.

Both need an Admin API key (sk-ant-admin01-...), an OAuth token with the org:admin scope, or a key that isn't scoped to a workspace; workspace keys don't work, and individual accounts don't have the Admin API.

13.3 Google: billing reports, not a Gemini usage API#

As of November 2026, Google's Gemini API documentation describes no Gemini-specific usage or cost API. What it offers:

  • AI Studio's dashboard: usage under Dashboard > Usage, spend and project spend caps on the Spend page, billing on the Billing page.
  • Cloud Billing reports: in the Google Cloud console, the billing account's Reports page, with "Gemini API" in the Service column; group by SKU for per-model, per-line-item costs. Google notes that billing data can lag, "up to around 10 minutes" in AI Studio and longer in the Cloud Billing console.
  • Cloud Billing export to BigQuery (a general Google Cloud feature, Google's guide) is the programmatic route: a daily-updated table of every charge, by project, service and SKU, that you query with SQL and join to your tracker.

So for Gemini, reconciliation is by project and SKU, daily. Separate Google Cloud projects (each with its own key) per environment and feature are the main attribution tool.

13.4 OpenRouter: key, credits and generations#

As with any gateway, check where your prompts are routed and the data policies, retention and ZDR options involved before sending enterprise data (Part 9).

  • GET /api/v1/key: the calling key's spend (usage, usage_daily, usage_weekly, usage_monthly, in USD), limit and budgets (9.3). Any key can read its own.
  • GET /api/v1/credits: "total credits purchased and used for the authenticated user" (total_credits, total_usage). Requires a management key.
  • GET /api/v1/generation?id=...: one request's full record, for audits and for filling in costs your tracker missed.

The sample below reads yesterday's spend from all three sources that have APIs. Save as s13_admin_usage.py:

python
"""Yesterday's spend from the providers' own records: OpenAI, Anthropic and OpenRouter.
Needs ADMIN-level keys, which must never be used for normal model calls."""
import datetime as dt
import os

import anthropic
import httpx
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
today = dt.datetime.now(dt.timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
yesterday = today - dt.timedelta(days=1)

# --- OpenAI: Costs API (admin key, read from OPENAI_ADMIN_KEY) ---
oai = OpenAI(admin_api_key=os.environ["OPENAI_ADMIN_KEY"])
costs = oai.admin.organization.usage.costs(
    start_time=int(yesterday.timestamp()), end_time=int(today.timestamp()),
    bucket_width="1d", group_by=["project_id", "line_item"], limit=1)
for bucket in costs.data:
    for row in bucket.results:
        if row.object == "organization.costs.result" and row.amount:
            print(f"openai    {row.project_id}  {row.line_item:40s} {row.amount.value:>10.4f} {row.amount.currency}")
usage = oai.admin.organization.usage.completions(
    start_time=int(yesterday.timestamp()), end_time=int(today.timestamp()),
    bucket_width="1d", group_by=["model", "service_tier"])
for bucket in usage.data:
    for row in bucket.results:
        if row.object == "organization.usage.completions.result":
            print(f"openai    {row.model} tier={row.service_tier} requests={row.num_model_requests} "
                  f"uncached={row.input_uncached_tokens} cached={row.input_cached_tokens} "
                  f"write30m={row.input_cache_write_30m_tokens} write12h={row.input_cache_write_12h_tokens} "
                  f"out={row.output_tokens}")

# --- Anthropic: Usage and Cost Analytics API (beta; the SDK sends the beta header) ---
admin = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_ADMIN_KEY"])
rows = admin.beta.organization.analytics.cost.list(
    starting_at=yesterday, ending_at=today, group_by=["model", "token_type"])
for item in rows:
    # amounts are decimal strings in CENTS with six decimal places
    print(f"anthropic {item.group.model}  {item.group.token_type}  "
          f"${float(item.cost.amount) / 100:.4f} (list ${float(item.cost.list_amount) / 100:.4f})")

# --- OpenRouter: this key's spend, and account credits (management key) ---
with httpx.Client(base_url="https://openrouter.ai/api/v1", timeout=10) as http:
    key = http.get("/key", headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"})
    data = key.raise_for_status().json()["data"]
    print(f"openrouter key {data['label']}: today ${data['usage_daily']:.4f}, "
          f"month ${data['usage_monthly']:.4f}, limit {data['limit']} ({data['limit_reset']})")
    credits = http.get("/credits",
                       headers={"Authorization": f"Bearer {os.environ['OPENROUTER_MANAGEMENT_KEY']}"})
    c = credits.raise_for_status().json()["data"]
    print(f"openrouter credits: bought {c['total_credits']:.2f}, used {c['total_usage']:.2f}")
Example output · illustrative9 lines
openai    proj_8Fq2Zt7LmN3pXv1R  gpt-6-luna, input_tokens                     2.1873 usd
openai    proj_8Fq2Zt7LmN3pXv1R  gpt-6-luna, output_tokens                    4.0512 usd
openai    gpt-6-luna tier=default requests=48211 uncached=17310442 cached=4419001 write30m=880214 write12h=0 out=8102466
anthropic claude-sonnet-5-5  uncached_input_tokens  $0.4120 (list $0.4120)
anthropic claude-sonnet-5-5  cache_read_input_tokens  $0.1290 (list $0.1290)
anthropic claude-sonnet-5-5  cache_creation.ephemeral_5m_input_tokens  $0.4410 (list $0.4410)
anthropic claude-sonnet-5-5  output_tokens  $1.0680 (list $1.0680)
openrouter key Production backend: today $0.0014, month $3.2700, limit 50 (monthly)
openrouter credits: bought 100.00, used 41.27

Not supported locally: none of these admin endpoints exist on the stand-in (the first call returns 404).

13.5 Reconciling your tracker with the invoice#

A daily job compares your tracker's totals with the providers' numbers for the same UTC day, per provider and model (or project, workspace, key), and flags any difference above a tolerance. This one runs on the fixture log that make_fixture_log.py writes (10.2: generate it first) and fixture provider totals, which are made-up numbers, not real data. It sums the tracker's cost_usd per provider and model, shows the Gemini cache-storage line separately, and compares. Save as s13_reconcile.py:

python
"""Reconcile your own tracker against the provider's cost data, per provider and model.
Needs usage_log.jsonl from make_fixture_log.py (the same fixture log as the hit-rate analyser)."""
import json
from collections import defaultdict

TOLERANCE = 0.03          # 3%: rounding, late-arriving records, retries you didn't log

calls: dict[tuple[str, str], float] = defaultdict(float)
storage: dict[tuple[str, str], float] = defaultdict(float)      # Gemini explicit-cache storage
for line in open("usage_log.jsonl"):
    r = json.loads(line)
    if r["cost_usd"] is None:                                   # unknown cost: not in OUR total
        continue
    (storage if r["kind"] == "cache_storage" else calls)[(r["provider"], r["model"])] += r["cost_usd"]

# What the providers' cost APIs reported for the same UTC day (FIXTURE values; amounts in USD)
theirs = {("anthropic", "claude-sonnet-5-5"): 2.05, ("anthropic", "claude-haiku-5-5"): 0.08,
          ("openai", "gpt-6.1-sol"): 4.25, ("gemini", "gemini-3.8-flash"): 1.56,
          ("openai", "gpt-6-luna"): 3.12}

print(f"{'provider/model':32s} {'ours':>8s} {'theirs':>8s}  diff")
for key in sorted(set(calls) | set(storage) | set(theirs)):
    a, b = calls.get(key, 0.0) + storage.get(key, 0.0), theirs.get(key, 0.0)
    gap = (b - a) / b if b else float("inf")
    flag = "ok" if abs(gap) <= TOLERANCE else "INVESTIGATE"
    print(f"{'/'.join(key):32s} {a:8.2f} {b:8.2f}  {gap:+6.1%} {flag}")
    if storage.get(key):                                        # show the line that is in no usage object
        print(f"{'':32s} of which cache storage: {storage[key]:.2f}")
Output7 lines
provider/model                       ours   theirs  diff
anthropic/claude-haiku-5-5           0.08     0.08   -0.3% ok
anthropic/claude-sonnet-5-5          1.90     2.05   +7.1% INVESTIGATE
gemini/gemini-3.8-flash              1.56     1.56   -0.3% ok
                                 of which cache storage: 0.80
openai/gpt-6-luna                    0.00     3.12  +100.0% INVESTIGATE
openai/gpt-6.1-sol                   4.25     4.25   +0.1% ok

Two lines need a human:

  • Sonnet is 7.1% higher at the provider. Typical causes, in rough order of likelihood: calls your tracker didn't record (an error path that skipped record_error, a script that bypassed the wrapper), calls recorded with an unknown cost (the five timed-out support-bot calls in this log are in the file but have no cost_usd, so they're missing from the sum: 5.7 counts them), streams cut off after the provider had generated tokens, retries after a timeout or a dropped stream (the abandoned attempt may still have been billed, lesson 03.8, 6.6), cache writes priced at the wrong lifetime, or a price-table error.
  • gpt-6-luna appears only at the provider. Somebody is using a key or project your application doesn't know about: a developer's notebook, a forgotten cron job, or a leaked key. This is the most valuable line a reconciliation job ever prints.

Differences you should expect, and tolerate:

  • Freshness. Anthropic's analytics data can take up to 24 hours and be revised for a week after month end; compare only days older than the provider's freshness window.
  • Day boundaries. Use UTC on both sides.
  • Discounts and credits. List-price trackers won't match negotiated prices; compare with Anthropic's list_amount, or keep your contract rates in the price table.
  • Rounding, and tokens you never see (tool-use system prompts and similar, 3.3), which your tracker does capture as long as it reads usage rather than estimating.
  • Storage and per-call fees (Gemini explicit cache storage, web searches, code execution hours), which appear on the invoice but not in token usage. The tracker accounts for two of them: web searches in Usage and Gemini storage as its own event (8.3), which is why the Gemini row above has an "of which cache storage" line. File search, code-interpreter sessions and other per-call fees aren't modelled (3.2), so they show up here as a gap.

Common misconceptions#

Misconception Reality
"input_tokens is how much input we sent." On Anthropic it's only the tokens after the last cache breakpoint; total input is input_tokens + cache_creation_input_tokens + cache_read_input_tokens. On OpenAI, Gemini and OpenRouter it's all input, including cached and written tokens, which are billed at other rates. This lesson's input always means uncached; total_input = input + cached + written (3.1)
"Output tokens are the visible answer." Reasoning tokens are billed as output. OpenAI and Anthropic include them in the output count; Gemini reports thoughts_token_count separately, and forgetting it under-bills (3.4)
"The tier we requested is the tier we paid for." OpenAI Fast mode can fall back to default; Gemini Priority downgrades to Standard under load. Read service_tier (OpenAI), usage.speed / service_tier (Anthropic) and x-gemini-service-tier (Gemini) from the response
"A pre-flight count is what we'll be billed." Counts ignore caching, Anthropic's is an estimate, the Gemini SDK counts only contents on the Developer API, and output is unknown until the end (2.8)
"Turning caching on always saves money." A write that's never read is a surcharge (1.25×, 2× or 2.5×), Gemini explicit caches cost storage every hour, and parallel cold starts write the same prefix many times (Part 11)
"Our prompt is cached; we set cache_control." Below the provider's minimum prefix nothing is cached and no error is raised. Check the usage fields (6.4 for Anthropic, 7.1, 8.1)
"The breakpoint goes at the end of the prompt." On Anthropic it goes on the last block that's identical across requests. On the varying question, every request writes and none reads (6.2)
"Sending requests in parallel makes caching faster." An Anthropic cache entry exists only once the first response starts, so a cold parallel burst all misses. Warm first (6.6)
"OpenRouter's cost is before caching, so subtract the cache discount." usage.cost already includes every discount and premium. Record it as is (3.5)
"We can hard-code prices; they rarely change." Gemini 4 Argon's price doubles on 1 December 2026 and 3.8 Flash's on 1 January 2027. Prices belong in a dated table (Part 4)
"LiteLLM's price file is the source of truth." It's a convenient community file with no effective dates, and it can lag. Use it as a drift check against the official pages (4.4)
"If we can't price a call, log it as $0." Zero says "free". Log unknown as null and alert on it (5.2)
"Gemini's LocalTokenizer counts our model's tokens offline." In google-genai 2.34.0 it doesn't support gemini-3.8-flash or gemini-4-argon at all, counts text only, and needs one online download first (2.5)
"Cached tokens don't count toward rate limits." True for cache reads on most Claude models; false on OpenAI, where cached input still counts toward TPM (6.7, 7.8)
"A stream that hit the output cap is a failed call, so we don't log it." It was billed. On hosted OpenAI it ends with response.incomplete, which get_final_response() rejects; read the terminal event instead and record it as truncated (5.4)
"Our tracker matches the provider, so it's complete." A matching total can hide offsetting errors, and the provider's data can lag by up to a day. Reconcile per model and per project, and look for usage that only the provider sees (13.5)

Key takeaways#

  • Count to decide, usage to account. Use a local estimate of the whole payload by default; call the counting endpoints near limits and for expensive requests, cache the counts of stable prefixes, and give the counting call a timeout, a fallback and its own rate budget.
  • The counting endpoints have gaps: OpenAI's is Responses-shaped; Anthropic's is a free estimate with its own RPM limit that rejects server tools and URL or file media; google-genai 2.34.0 counts only contents on the Developer API; LocalTokenizer works offline after one download but not for current models; OpenRouter has none.
  • One convention, written down: in this lesson input is uncached input, and total_input = input + cached + written. OpenAI, Gemini and OpenRouter include cached and written tokens in their raw input field; Anthropic doesn't (3.1). cost_calc.from_* is the canonical normalizer: call it, don't copy it (3.6).
  • Normalize usage into one bucket per token, then price line items. Subtract overlaps (OpenAI's cached and written tokens from input_tokens; Gemini's cached tokens from prompt_token_count) and add what's separate (Gemini's thoughts and tool-use tokens).
  • Apply every modifier from the response: cache-write lifetimes (Anthropic 5m/1h, OpenAI 30m/12h), the served tier, long-context steps that move the whole request (OpenAI above 272K input tokens, Haiku 5.5 above 100K including cache tokens), Anthropic's fast-mode prices and inference_geo 1.1×, OpenAI's 10% regional uplift, batch at 50%, and per-call tool fees.
  • OpenRouter's usage.cost is the answer. It's always returned, in USD-denominated credits, with discounts applied. Use the generation endpoint for anything you missed.
  • Keep prices in a dated, validated table with sources; check it daily against OpenRouter's catalogue and LiteLLM's file; update it by hand, through review.
  • Record every call with feature, hashed customer, environment, requested and served model, request ID, prefix fingerprint, tier, token buckets, finish reason, cost and cost source. Unknown is null (including all-zero usage), failures and truncated answers are recorded, accounting never breaks the request, and the facts a response can't state (batch, regional endpoint) are arguments you pass (5.8).
  • Record streams from their terminal object, not from get_final_response(): a capped OpenAI Responses stream ends in response.incomplete and was still billed (5.4). Answer "which feature, customer, day?" from the same log (5.7).
  • Anthropic caching: automatic (top level) or explicit breakpoints, 4 slots, writes only at breakpoints, a 20-block lookback, longer TTLs before shorter ones, its minimum prefix (6.4), the tools → system → messages invalidation hierarchy, pre-warm with max_tokens: 0, per-workspace isolation, and diagnostics.cache_miss_reason to explain misses.
  • OpenAI caching: automatic (7.1); prompt_cache_key for accounting and isolation on GPT-5.6+; prompt_cache_options (mode, ttl, prewarm, comparison_response_id) and up to four prompt_cache_breakpoints; 12h on breakpoints (the SDK types don't allow it at request level yet); explicit mode with no breakpoints to avoid write charges; cached tokens still count toward TPM.
  • Gemini caching: implicit caching on current models (Gemini 4 re-caches only when a turn adds 2,050+ tokens); explicit caches on generate_content only, not Interactions or Gemini 4 Argon+, with a create → use → update → list → delete lifecycle and storage billed per hour, which you price and record yourself. The break-even doesn't change when all prices double (11.2). Compare all four providers' controls in one table: 9.4.
  • Measure caching by token hit ratio and net saving, not by "it's on". Log a prefix fingerprint, build requests deterministically, and use the providers' diagnostics to explain misses.
  • Anthropic's two spend limits fail differently: your tier's cap is a 429 with no retry-after (enforced_spend_limit_reached), a limit you set yourself is a 400 (12.4).
  • Control spend before the call: output caps as ceilings, a cost guard that downgrades or refuses, reserve-then-settle budgets per user and feature, provider-side limits as circuit breakers, and alerts on spend, cost per request, hit ratio and unknown costs.
  • Reconcile daily with OpenAI's Usage and Costs APIs, Anthropic's Usage and Cost Analytics API, Google's billing reports or BigQuery export, and OpenRouter's key, credits and generation endpoints.

Terms introduced in this lesson#

Term One-line definition
Pre-flight token count Counting a request's input tokens with the provider's endpoint before sending it
Counting endpoint A provider API that runs only the tokenizer on a request and returns the input token count
Token convention The module's one meaning for token usage fields: input is uncached input (billed at the plain input rate), cached reads and cache writes are separate fields, total_input is every prompt token, and output includes reasoning tokens. Providers' raw fields differ: OpenAI, Gemini and OpenRouter include cached tokens in their input count, and Anthropic does not
Uncached input Input billed at the plain input rate: the raw input field minus (OpenAI, Gemini, OpenRouter) or without (Anthropic) the cached and written tokens. This lesson's meaning of input
Total input input + cached + written: every prompt token, however billed
Cache-storage event A tracker record for the hours a Gemini explicit cache was kept, which no response reports
Normalized usage One provider-neutral record of a call's tokens, with each token in exactly one billing bucket
Line item One billed quantity at one rate (for example, 4,000 cache-read tokens at $0.10 per million)
Price table Configuration holding each model's rates with effective dates and sources
Effective date The first (and optionally last) day a price applies
Price drift A difference between your price table and an external price source
Cost tracker Code that records every call's usage, cost and attribution
Attribution Tagging a cost with what it was for: feature, customer, environment
Cost source Whether a recorded cost was computed by you, reported by the provider, or unknown
Served tier The service tier that actually processed a request, which may differ from the one requested
Cache breakpoint A marker (cache_control, prompt_cache_breakpoint) ending a cacheable prefix
Automatic caching (Anthropic) A top-level cache_control that places the breakpoint on the last cacheable block
Lookback window How far back (20 blocks on Anthropic) the API searches for an earlier cache write
Cache lifetime (TTL) How long a cache entry lives without being used: 5m/1h on Anthropic, 30m/12h on OpenAI
Invalidation hierarchy Anthropic's rule that a change to tools, system or messages invalidates that level and everything after it
Cache pre-warming Writing a prefix to the cache before real traffic (max_tokens: 0 on Anthropic, prewarm: true on OpenAI)
Parallel cold start A burst of requests at an uncached prefix, each paying for its own cache write
Cache diagnostics Provider features that compare a request with an earlier one and report why the cache missed
prompt_cache_key OpenAI's per-request cache key: a routing hint before GPT-5.6, cache accounting and isolation after
Cache-hit probing Inferring another user's prompts from cache-hit timing in a shared cache
Explicit context cache A Gemini CachedContent object you create, use by name, extend and delete, paying storage per hour
Sticky routing OpenRouter sending a conversation's requests to the same provider so its cache can hit
Token hit ratio Cache-read tokens divided by all input tokens
Net saving Cost without caching minus actual cost, after write premiums and storage
Prefix fingerprint A hash of everything before the varying part of a request, logged to detect prefix changes
Break-even (cache) The number of reuses within one lifetime at which caching becomes cheaper than not caching
Cost guard A pre-call check that estimates the worst-case cost and downgrades or refuses over a cap
Reserve-then-settle Reserving a call's worst-case cost against a budget, then replacing it with the actual cost
Admin key / management key A credential for organization-level APIs (usage, costs, limits), never used for model calls
Cost reconciliation Comparing your own cost records with the provider's and explaining every difference

All terms are also collected in the glossary.


Exercises#

  1. Counting (2.7): change CONFIRM_ABOVE to 0.0 and run s2_token_budgeter.py again. How many remote calls happen now, and what would that cost in latency at 150 ms each for 10,000 requests a day? Then add a second stable prefix and check that its count is cached separately.
  2. Counting (2.4): write a function that approximates the full Gemini input count on the Developer API: count contents with count_tokens, count the system instruction and the tools' JSON as text (once, cached by fingerprint), and add them. Compare it with prompt_token_count on a few real calls.
  3. Pricing (3.6): gpt-6.1-terra is in prices.yaml with a 0.05× cache read. Write a test that a 12-hour write followed by two reads beats three uncached sends on Terra, then work out how many reads a 12-hour write needs on Luna (0.1×) instead.
  4. Pricing (3.4): cost_calc.py prices a non-text modality at an input_<modality> rate when the table has one. Build a GenerateContentResponseUsageMetadata with a mixed text and audio prompt (and a cache hit on part of it), add an input_audio rate to a copy of prices.yaml, and check the line items. What does Cost.notes say when you remove the rate again?
  5. Price table (4.3): add a period to gemini-3.8-flash that ends on 2026-12-31 and another that starts on 2026-12-31. Which error do you get, and why is that the behaviour you want?
  6. Tracker (5.3): CallRecord has both model and served_model. Make the tracker log a warning when they differ by more than a date suffix, and run it against the stand-in (whose model names carry a :latest suffix: what does your rule do with it?).
  7. Tracker (5.4): make s5_stream_local.py break mid-stream (raise inside the loop after the first event). Check that a record with status: error:... and cost_usd: null is written. Then change the mock in s5_stream_incomplete.py to end with response.failed and see which of the three versions still records a cost.
  8. Anthropic caching (6.3): for a request with a 1h breakpoint at token 2,000, a 5m breakpoint at token 30,000, and a cache hit only up to token 2,000, work out A, B and C and the tokens billed at each rate. Then do it for a request with no hit at all.
  9. Hit rates (10.2): add a sixth feature to make_fixture_log.py whose traffic arrives every 7 minutes on Anthropic's default 5-minute cache. What does the analyser report? Add a check that detects "writes after gaps longer than the lifetime".
  10. Request builder (10.4): write the unit test from the warning at the end of 10.4: build a request twice with different customers and times and assert the fingerprints are equal. Then break build() by putting the date in the system prompt and watch the test fail.
  11. Break-even (11.2): s11_break_even.py already prints 3.8 Flash at 2026 and 2027 prices, and both give 8 questions in 8 hours. Explain why in two sentences. Then find the break-even for a 2027 storage price with the input price held at its 2026 level, and for a 16-hour shift. At what question rate per hour does implicit caching (free, if it hits) stop being the obvious choice?
  12. Cost guard (12.2): change Budgets so it can be shared by several processes using SQLite with a transaction (BEGIN IMMEDIATE). Run two processes against the same budget and check the total never exceeds it.
  13. Spend questions (5.7): extend s5_report.py to print the five most expensive requests (not customers), and the share of spend that went to status: truncated records. Which cap in 12.1 would you change first?
Hints and checks for the exercises with a number to verify
  • 1. With CONFIRM_ABOVE = 0.0 no estimate is "far from the limit", so every request takes the prefix path and estimated_only drops to 0. The remote count stays at 5, because the token bucket (rpm=5) caps it, and the rate-limited fallbacks rise from 2 to 3; the fingerprint cache is what keeps the other counts local. Without the prefix cache, 10,000 requests × 150 ms is 1,500 seconds (25 minutes) of added waiting a day, spread over the users. A second stable prefix gets its own fingerprint, so it costs one more remote call and then hits.
  • 3. Terra: a 12-hour write plus two reads is 2.5 + 0.05 + 0.05 = 2.6 input-prices, against 3 for three uncached sends. Luna: 2.5 + 0.1 + 0.1 = 2.7, still under 3, so the same two reads (three requests) are enough; token_cache_break_even(2.5, 0.1) in 11.1 returns 3.
  • 5. Both periods claim 31 December, and the validator in prices.py rejects an end date on or after the next period's start with overlapping price periods starting ... and ... (Pydantic wraps it in a ValidationError, a ValueError subclass). That is what you want: a day with two prices is a bug to catch when the table loads, not a silent choice at billing time.
  • 7. With response.failed, the naive version still raises, and the fixed version records status: error:failed. It keeps a cost only if the failed response carries usage (add the USAGE dict to the mock's response to mirror a failure after generation began, and leave it out to mirror one before).
  • 8. Request with a hit: A = 2,000 (the highest hit), B = A = 2,000 (no 1h breakpoint after A), C = 30,000. Billed: 2,000 cache-read tokens, 0 at the 1h write rate and 28,000 at the 5m write rate. With no hit at all: A = 0, B = 2,000, C = 30,000, so 2,000 1h writes and 28,000 5m writes.
  • 11. For a 16-hour shift the formula gives (0.75 + 0.50 × 16) ÷ (0.75 − 0.075) = 12.96, so 13 questions in 16 hours (0.8 an hour), fewer per hour than the 8-hour shift's 1.0, because the storage bill grows with the hours and the saving per question does not.
  • 12. Reserve inside one BEGIN IMMEDIATE transaction that reads spent + reserved, checks the limit and writes the new reservation before committing; two processes then can't both pass the same check, and the sum of spent never exceeds the daily budget.

Check yourself#

  1. When is a pre-flight token count worth a network call, and when is a local estimate enough?
  2. Which parts of a request can't be counted by Anthropic's count_tokens, and by models.count_tokens on the Gemini Developer API with google-genai 2.34.0, and what do you do for them?
  3. An OpenAI response has input_tokens=10,000, cached_tokens=6,000 and cache_write_tokens=3,000. How many tokens are billed at the normal input rate?
  4. An Anthropic response has input_tokens=50, cache_read_input_tokens=100,000 and cache_creation_input_tokens=0. How many input tokens did the request have, and why does a dashboard built on input_tokens mislead?
  5. Why do you have to add thoughts_token_count on Gemini, but not reasoning_tokens on OpenAI?
  6. Your code requested OpenAI's Fast mode. Where do you look to know whether you were charged for it?
  7. A Claude Haiku 5.5 request has 5,000 new tokens and 98,000 cache-read tokens. Which price list applies, and to which tokens?
  8. Why should OpenRouter calls be recorded with usage.cost instead of being priced with your own table?
  9. Why must a price table have effective dates? Give a concrete example from November 2026.
  10. Why does the tracker record an unknown cost as null rather than 0?
  11. On Anthropic, why is putting the breakpoint on the user's question a mistake, and where should it go?
  12. You send 30 requests in parallel with the same 50,000-token Anthropic prefix, and none read the cache. Why, and what's the fix?
  13. On GPT-5.6 and later, what does prompt_cache_key do, and how do you turn caching off for one one-off request?
  14. Which Gemini setups can't use explicit caches, and what does an explicit cache cost besides the tokens you read?
  15. What does OpenRouter's sticky routing do, and how does session_id change it?
  16. Your support bot's token hit ratio fell from 85% to 3% at 13:00. Name two likely causes and how you'd confirm which it is.
  17. With Anthropic's 1-hour lifetime and a 0.1× read, how many requests within the hour does a cached prefix need to pay off?
  18. Your tracker's total for a model is 7% below the provider's cost report. List three possible causes.
  19. A 03.2 conversation record says input_tokens: 10,000 for an Anthropic call that read 9,000 tokens from the cache. How many tokens does 03.7's cost_calc.Usage hold in input, and why does the tracker also write total_input_tokens?

Further resources#


← 03.6 — Images, PDFs and Files | Module 03 overview | 03.8 — Errors, Rate Limits, Timeouts and Retries →

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