# Prompt caching economics

> Price cache writes, reads and storage across vendors, lay out SAP context so the cache hits, and measure the saving on Calder's agents from the usage log.

- Course: Orchestrate, Unit 10 · Production and LLMOps
- Page: https://erpfde.com/topics/prompt-caching-economics/
- Updated: 2026-11-23
- Reading time: Foundational 8 min, Deep 35 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

Most AI calls in an SAP setting start with the same long text: the tool definitions, the instructions, the company's policy. Only the end changes: this order, this invoice, this question. **Prompt caching** lets the model provider keep the processed start of the prompt for a while and charge much less when the next call reuses it.

It is not free money. Three prices decide whether it pays:

- **A write**: the first call stores the prefix. Several vendors now charge more than normal input for it.
- **A read**: later calls reuse it at a small fraction of the input price.
- **Storage**: one vendor model (Google's explicit caching) bills each hour the cache exists.

A cache that is written and never read costs more than no cache. So the economics come down to one question: **how many times is the same prefix read before it expires?** That depends on two things you control: how your traffic arrives, and whether your prompt keeps the stable part stable.

[Caching for LLM applications](https://erpfde.com/topics/caching-for-llm-applications/) explained the mechanics. This topic puts numbers on them.

### Why it matters to the business

Input tokens are usually most of an agent's bill, because every call resends the instructions and every step of an agent loop resends the conversation so far ([Token economics](https://erpfde.com/topics/token-economics/)). A cache read on the vendors' current price lists costs between a tenth and a fortieth of normal input. On a long, stable prefix that is the largest saving available without changing the model or the answers.

Take Calder Pumpworks, the course's fictional pump maker. Two of its agents run every working day, three model calls per run:

- The **order-exceptions agent** works through blocked sales orders for the morning review: 600 runs a month, all between 08:00 and 09:30.
- The **invoice triage agent** (`AGT_INV_TRIAGE`) looks at blocked supplier invoices as they arrive: 300 runs a month, spread over the working day.

Both send the same 4,800-token prefix on every call. In the course's simulation at list prices, caching cuts the month's model bill by about half or more on every vendor tried. The morning agent saves more than the triage agent, because its calls come close together. And one careless prompt layout, the run's start time written into the instructions, throws a large part of the saving away; on one vendor option it makes caching cost more than no cache at all.

> **Note** These figures come from synthetic Calder data at list prices. They show the method, not a result from a real SAP system or contract. Calder's whole bill is tens of dollars a month; the same percentages on a larger prefix or volume are what make the decision worth a design review.

The business decision is small but recurring: which cache lifetime to buy, which prompt layout to require, and how to prove the saving from the usage log rather than from a vendor's headline.

### How SAP does it

When you call models through SAP's generative AI hub, the orchestration service passes caching instructions on to the model provider. As of November 2026, the SAP Cloud SDK for AI for Python (version 7.4.1, read in this run) lets you mark a text block, image or tool definition with a cache control of 5 minutes or 1 hour, and reports cached and newly written tokens in every response's usage. SAP AI Core's documentation limits that explicit marking to orchestration V2 and the Anthropic Claude and Amazon Nova model families: Nova takes no marks on tools and no explicit lifetime, and the 1-hour lifetime works only on selected Claude models. OpenAI and Gemini models get the vendors' implicit caching by default in orchestration ([SAP AI Core: Prompt caching](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/prompt-caching-77118d6.md)).

On SAP AI Core you don't pay the vendor's dollar price list. Tokens convert to capacity units at per-model rates in SAP Note 3437766 ([Token economics](https://erpfde.com/topics/token-economics/) shows the arithmetic). The SAP sources opened for this topic don't say how cached or written tokens convert. Ask your SAP account team before a business case counts on a caching discount through SAP.

SAP-delivered AI, such as Joule or the agents inside S/4HANA, runs on SAP's side: SAP decides what it caches, and you pay through SAP's own commercial model ([Pricing custom agents after the free runtime](https://erpfde.com/topics/pricing-custom-agents-after-the-free-runtime/)).

### The price of a cache, vendor by vendor

As read on the vendors' own pages on 20 November 2026 (US dollars per million tokens, standard tier, global processing). Prices change; check the pages before you budget.

| Model | Input | Cache write | Cache read | Lifetime | Pays back after |
| --- | --- | --- | --- | --- | --- |
| Anthropic Claude Sonnet 5.5 | 2.00 | 2.50 (5 min) or 4.00 (1 hour) | 0.10 | 5 min or 1 hour, restarted by each read | 1 read (5 min), 2 reads (1 hour) |
| Anthropic Claude Haiku 4.5 | 1.00 | 1.25 or 2.00 | 0.10 | same | same; needs a 4,096-token prefix |
| OpenAI gpt-5.6-terra | 2.00 | 2.50 (30 min) or 5.00 (12 hours) | 0.20 | at least 30 min or 12 hours | 1 read (30 min), 2 reads (12 hours) |
| OpenAI gpt-5.4 | 2.50 | no extra charge | 0.25 | about 5 to 10 min, or "24h" (typically about 30 min) | immediately |
| Google Gemini 3.1 Pro Preview, explicit cache | 2.00 | normal input | 0.20 | you set it (default 1 hour) | 2.5 reads every hour the cache exists |

Sources: [Anthropic pricing](https://platform.claude.com/docs/en/about-claude/pricing), [OpenAI pricing](https://developers.openai.com/api/docs/pricing) and [caching guide](https://developers.openai.com/api/docs/guides/prompt-caching), [Gemini pricing](https://aistudio.google.com/docs/pricing) and [caching guide](https://aistudio.google.com/docs/caching.md?generate-content=true).

Four things in this table change decisions:

1. **Writes are no longer free at OpenAI.** From GPT-5.6 on, a write costs 1.25 times input for 30 minutes or 2.5 times for 12 hours. Older OpenAI models still write at no extra charge.
2. **Longer lifetimes cost more to write.** They pay only when calls are spread out enough that a short cache would expire between them.
3. **Google charges rent.** An explicit Gemini cache costs storage for every hour it exists, used or not. Google's implicit caching is free to use but carries "no cost saving guarantee".
4. **Minimum lengths bite.** A prefix below the model's minimum (512 to 4,096 tokens depending on the model) is simply not cached, with no error.

Data residency costs extra on top: Anthropic charges 1.1 times for US-only processing on recent models, and OpenAI adds 10% for regional processing on models released since 5 March 2026. Caching multipliers apply on top of those.

> **Note** **For functional consultants.** Caching changes nothing in configuration or business process. It changes what a test must check: an AI feature's prompt must not carry the user, date or document number in its fixed part. Add that line to the test cases for any AI feature you sign off.

### Questions to ask

- What share of our input tokens is the same on every call, and how long is that part in tokens?
- How close together do our calls arrive? Show me the gaps, not the monthly volume.
- Which cache lifetime are we paying for, and did we compare it with the shorter one on our own traffic?
- What does our usage log say about cached, written and plain input tokens last month?
- Through SAP AI Core, how are cached and written tokens converted to capacity units under our contract?
- Does anything in the fixed part of the prompt change per user, per day or per document?
- How long does the provider keep our cached data, and is that within what our data protection officer approved?

### Common misconceptions

- **"Caching always saves money."** A write that is never read costs up to 2.5 times normal input, and a stored Gemini cache costs rent while idle.
- **"The longest lifetime is the safest choice."** It costs more per write and only pays when calls are far apart.
- **"Our volume is high, so we will hit the cache."** Monthly volume says nothing about the gap between two calls with the same prefix.
- **"Caching changes the answers."** The model gets the same input; only the billing and speed change. The risk is in the layout, not the output.
- **"The vendor's saving applies through SAP too."** Through the generative AI hub you pay in capacity units under SAP's rates; confirm how cached tokens convert.

### Key terms

- **Prompt caching:** the provider keeps the processed start of a prompt and charges less when a later call starts with exactly the same text.
- **Prefix:** the start of the prompt that is identical across calls: tools, instructions, reference text.
- **Cache write:** the call that stores a prefix, priced at or above normal input.
- **Cache read (hit):** a call that reuses a stored prefix, priced at a fraction of input.
- **Time to live (TTL):** how long a cached prefix lives before it expires unless used again.
- **Break-even:** the number of reads after which a write has paid for itself.
- **Storage price:** a charge per million tokens per hour for keeping an explicit cache (Gemini).
- **Hit rate:** the share of calls, or of input tokens, served from the cache.

### Check yourself

1. What single question decides whether prompt caching pays for a workload?
   - A. Whether the model vendor offers a one-hour cache lifetime
   - B. How many times the same prefix is read before it expires
   - C. Whether the monthly call volume is above a vendor threshold
   - D. Whether the agent's answers are long or short on average

   Answer: B. A write costs at or above normal input, and only reads earn the money back. Monthly volume alone doesn't tell you how often the same prefix is reused inside its lifetime.

2. Calder's morning agent saves more from caching than its triage agent with the same prefix. Why?
   - A. The morning agent uses a cheaper model than the triage agent
   - B. The triage agent's prefix is below every vendor's minimum
   - C. Its calls arrive close together, so the cache rarely expires
   - D. The morning agent pays no write charge at any vendor

   Answer: C. The morning runs all fall between 08:00 and 09:30, while triage runs are spread over the day. With short lifetimes, the triage cache often expires between runs and has to be written again.

3. Since GPT-5.6, what changed in OpenAI's caching prices?
   - A. Cache writes cost more than input: 1.25 times for 30 minutes
   - B. Cache reads became free for prompts above 1,024 tokens
   - C. Caching must be bought as a separate monthly add-on
   - D. Cached tokens are now billed at the output token price

   Answer: A. OpenAI's guide prices 30-minute writes at 1.25 times and 12-hour writes at 2.5 times the uncached input rate on GPT-5.6 and later. Earlier models still write at no extra charge.

4. A vendor proposes Gemini explicit caching for an agent that runs a few times a day. What should worry you?
   - A. Explicit caches can't hold more than one prompt at a time
   - B. Gemini refuses requests that don't use the cache
   - C. Cached tokens on Gemini cost more than normal input
   - D. Storage is billed every hour the cache exists, used or not

   Answer: D. Explicit Gemini caches are billed for cached tokens plus storage by the hour. On Gemini 3.1 Pro Preview the cache needs about 2.5 reads an hour just to cover its storage.

5. The team's AI feature writes "Today is 20 November, user 00100265" at the top of its instructions. What is the cost effect?
   - A. None: the provider ignores dates when it compares prompts
   - B. The answers become wrong, but the bill stays the same
   - C. Each user or day gets its own prefix, so the cache is rewritten
   - D. The prompt becomes too short for the vendor's minimum

   Answer: C. A cache hit needs an identical prefix. Anything that changes per user, day or document belongs after the stable part, or each variation pays a new write.

6. Calder calls models through SAP's generative AI hub. What must you confirm before counting on a caching saving?
   - A. That the model vendor publishes a dollar price for cache reads
   - B. How SAP converts cached and written tokens to capacity units
   - C. That S/4HANA has caching switched on in its configuration
   - D. That every model on the hub accepts a one-hour cache lifetime

   Answer: B. On SAP AI Core you pay capacity units at SAP's per-model rates, not the vendor's dollar list. The SAP sources opened for this topic don't state how cached tokens convert, so ask your account team.

## Deep layer

### Mental model

A cached prefix is a **short lease with a deposit**. The write is the deposit: you pay it once, at or above the input price. Each read inside the lease pays you back most of the input price. Some leases also charge rent by the hour. The lease ends when it expires, and on most vendors every read extends it.

So the saving on a workload is a function of three things:

1. **Price shape**: write multiplier `w`, read multiplier `r`, storage `s` (all relative to input).
2. **Arrival shape**: the gaps between calls that carry the same prefix, compared with the lease length.
3. **Prefix stability**: whether calls that should share a prefix really carry byte-identical text.

The vendor controls the first. You control the other two. Everything in this topic is about measuring them and choosing well.

### How it works

#### The break-even formula

Take a prefix of `P` tokens, written once and read `n` times before it expires, at input price `i` per token. Without caching it costs `P × i × (1 + n)`. With caching it costs `P × i × (w + n × r)`. Caching pays when:

```text
n ≥ (w − 1) / (1 − r)
```

| Price shape | `w` | `r` | Reads to break even |
| --- | --- | --- | --- |
| Anthropic 5-minute write | 1.25 | 0.025 to 0.1 | 1 |
| Anthropic 1-hour write | 2.0 | 0.025 to 0.1 | 2 |
| OpenAI GPT-5.6+, 30-minute write | 1.25 | 0.1 | 1 |
| OpenAI GPT-5.6+, 12-hour write | 2.5 | 0.1 | 2 |
| OpenAI earlier models | 1.0 | 0.1 | 0 |

Anthropic states the same result on its pricing page: a 5-minute write pays off after one read, a 1-hour write after two.

For storage-priced caches the question is per hour. A cache of `P` tokens costs `P × s` per hour and saves `P × (i − c)` per read, where `c` is the cached price. It pays when reads per hour exceed `s / (i − c)`. On Gemini 3.1 Pro Preview that is `4.50 / (2.00 − 0.20) = 2.5` reads an hour; on Gemini 3.8 Flash at its prices from 1 January 2027 (input 1.50, cached 0.15, storage 1.00) it is `1.00 / 1.35`, under one.

#### Arrival shape decides `n`

The formula needs `n`, and `n` comes from your traffic, not your volume. Two workloads with the same monthly count behave differently:

```mermaid
flowchart LR
  subgraph Morning["Morning review: 08:00 to 09:30"]
    M1[run] --> M2[run] --> M3[run] --> M4[run]
  end
  subgraph Day["Triage: 08:00 to 17:00"]
    T1[run] -.->|38 min gap| T2[run] -.->|35 min gap| T3[run]
  end
```

With about 29 morning runs in 90 minutes, the gap between runs is about three minutes; a 5-minute lease almost never lapses. With about 14 triage runs over nine hours, the average gap is over half an hour; a 5-minute lease lapses between most runs, and the first call of each run pays a write. Inside one run, the three calls are seconds apart and always hit.

That is why the lifetime choice is workload by workload. A longer lease costs more per write but turns spread-out traffic into hits.

#### What breaks a prefix

A hit needs the prefix to be identical, token for token, up to the cache point. The vendors' guides name the usual breakers:

- **Variable text early in the prompt**: a timestamp, the user ID, a request ID, today's date. OpenAI's guide says to put stable content first and dynamic content last.
- **Changing tools**: on Anthropic, changing tool definitions invalidates the whole cache, because tools come first in the cache order (tools, system, messages). OpenAI's guide says to keep tool definitions stable and restrict use with `tool_choice` or allowed tools instead of removing them.
- **Rewriting history**: summarizing or truncating earlier turns of an agent conversation changes the prefix. Append instead.
- **Changing request settings**: on Anthropic, switching thinking or speed settings can invalidate message or system caches.
- **Unstable serialization**: JSON with keys in a different order, or retrieved notes in a different order, is different text.

Two less obvious ones:

- **Per-user tool lists.** Building the tool list from the user's role (so the planner sees fewer tools than the buyer) splits the cache by role. Keep one tool list and enforce authorization in the tool itself ([Agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/)).
- **Where instructions go.** On GPT-6.2 and later, OpenAI's guide says top-level `instructions` bill at the uncached rate on every request; reusable instructions belong in a leading developer message.

#### Laying out SAP context

For Calder's order-exceptions agent the layout that caches well looks like this, most stable first:

| Layer | What it holds | Changes when | Cache point |
| --- | --- | --- | --- |
| 1. Tools | `get_sales_order`, `get_customer`, `draft_next_step` definitions | A release | |
| 2. Instructions | Role, rules, answer format | A prompt version | |
| 3. Calder reference | Block reason guide, credit rules, the order-to-cash runbook | Monthly | Breakpoint here |
| 4. Run data | The blocked order, retrieved notes, the clerk's question | Every run | |
| 5. Agent turns | Tool calls and results so far | Every call | Moving breakpoint |

Layers 1 to 3 are the 4,800-token prefix in the lab. Who is asking, which order and what date it is go into layer 4. Logging the user belongs in your traces, not the prompt ([Observability for AI systems](https://erpfde.com/topics/observability-for-ai-systems/)).

If a prefix sits just under a model's minimum, adding stable reference text can make it cacheable. OpenAI's guide includes a break-even formula for exactly that trade.

#### Isolation and retention

Caches are an operational store of your prompt, so they come with data questions:

- **Scope.** OpenAI doesn't share caches across organizations or regional processing boundaries. Anthropic isolates by organization, and by workspace on its own API (only by organization on Bedrock and Google-managed Vertex AI).
- **Per-customer keys.** OpenAI's `prompt_cache_key` gives separate accounting per customer or workspace and, on GPT-5.6 and later, helps prevent cache-hit probing across users. Use one key per tenant if your app serves several companies.
- **Retention.** OpenAI's extended "24h" retention keeps cache data up to 24 hours, and organizations without Zero Data Retention default to it on models that offer both. Check that with your data protection officer, not just your budget owner.

### Build it yourself: price Calder's cache for a month

You will build `cache_economics.py`, a simulator that replays one month of Calder's two agents against each vendor's cache rules and prices it with and without caching. It writes a usage log in the shape SAP's orchestration service reports, measures the saving from that log, and hands the measured hit rate to the cost model you built in [Token economics](https://erpfde.com/topics/token-economics/).

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 10](https://erpfde.com/topics/set-up-for-unit-10/). Step 8 uses `unit10/token_costs.py` from [Token economics](https://erpfde.com/topics/token-economics/); the rest needs nothing else.

```mermaid
flowchart LR
  P[prices<br/>vendor tables] --> S[simulate<br/>a month of calls]
  W[Calder workloads<br/>morning + triage] --> S
  S --> R[cost per model<br/>and lifetime]
  S --> L[cache_usage.jsonl<br/>SAP-shaped usage]
  L --> M[measure<br/>saving + hit rate]
  M --> T[token_costs.py<br/>--hit-rate]
```

> **Note** New words. **Simulate** means replaying made-up events with fixed rules to see what would happen. A **seed** is the number that makes "random" choices repeat exactly, so your output matches this page. **JSONL** is a text file with one JSON record per line. A **usage log** is the record of tokens each model call used.

#### What you need

- Your course folder `orchestrate-course` with `.venv` from the setup topics. The script uses only built-in Python modules.
- About 35 minutes.
- Cost: free. No model is called and no account is needed.

> **Note** Everything here is **synthetic**: Calder's volumes, the arrival times (seed 42), the token counts and the three calls per run are course values. The prices are the vendors' list prices as read on 20 November 2026. The output shows the method, not what any real system or contract would pay.

#### Step 1: Open your course folder and turn on the virtual environment

1. Open VS Code, choose **File > Open Folder**, and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. If the prompt doesn't start with `(.venv)`, turn it on:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

#### Step 2: Create the script

1. In VS Code, right-click the `unit10` folder, choose **New File**, name it `cache_economics.py`, paste the code below and save.

```python
"""Unit 10: does prompt caching pay for Calder's two agents, and on which model?

Calder Pumpworks (a fictional company) runs two agents that make three model calls per run:

  morning   the order-exceptions agent, 600 runs a month, all between 08:00 and 09:30
  triage    the invoice triage agent (AGT_INV_TRIAGE), 300 runs a month, spread over 08:00-17:00

Every call starts with the same long prefix (tools, instructions, Calder's policy text). This
script simulates one month of calls (21 working days, seed 42), keeps a cache the way each
vendor describes it, and prices the month with and without caching.

  python unit10/cache_economics.py prices                  list prices and break-even reads
  python unit10/cache_economics.py simulate                both agents, stable prefix
  python unit10/cache_economics.py simulate --layout bad   the run's start time in the prompt
  python unit10/cache_economics.py simulate --prefix-tokens 3000
  python unit10/cache_economics.py measure unit10/cache_usage.jsonl --model claude-sonnet-5.5 --option 5m

No model is called and nothing leaves your computer. The prices were read on the vendors' pages
on 2026-11-20 (USD per million tokens, standard tier, global processing). They change: check them.
"""
import argparse
import json
import random
import sys
from pathlib import Path

# ----------------------------------------------------------------------------------------------
# Prices, USD per 1 million tokens, as read on the vendors' pages on 2026-11-20.
# writes: option -> (price per million for a cache write, lifetime in seconds used here)
# ----------------------------------------------------------------------------------------------
PRICES = {
    "claude-sonnet-5.5": {"vendor": "Anthropic", "input": 2.00, "output": 10.00, "read": 0.10,
                          "writes": {"5m": (2.50, 300), "1h": (4.00, 3600)}, "min_tokens": 512,
                          "kind": "prefix"},
    "claude-haiku-4.5": {"vendor": "Anthropic", "input": 1.00, "output": 5.00, "read": 0.10,
                         "writes": {"5m": (1.25, 300), "1h": (2.00, 3600)}, "min_tokens": 4096,
                         "kind": "prefix"},
    "gpt-5.6-terra": {"vendor": "OpenAI", "input": 2.00, "output": 12.00, "read": 0.20,
                      "writes": {"30m": (2.50, 1800), "12h": (5.00, 43200)}, "min_tokens": 1024,
                      "kind": "prefix"},
    # Earlier OpenAI models: no extra charge for a write (it costs the normal input price).
    # in_memory lasts about 5 to 10 minutes; 24h typically about 30 minutes. We use the low ends.
    "gpt-5.4": {"vendor": "OpenAI", "input": 2.50, "output": 15.00, "read": 0.25,
                "writes": {"in_memory": (2.50, 300), "24h": (2.50, 1800)}, "min_tokens": 1024,
                "kind": "prefix"},
    # Gemini explicit caching: cached tokens at a reduced rate plus storage per hour.
    # The minimum is listed for implicit caching; this lab applies it to explicit caching too.
    "gemini-3.1-pro-preview": {"vendor": "Google", "input": 2.00, "output": 12.00, "read": 0.20,
                               "writes": {"explicit": (2.00, 3600)}, "storage_per_hour": 4.50,
                               "min_tokens": 4096, "kind": "explicit"},
}

# Calder's two agents. Course values, all fictional.
WORKLOADS = {
    "morning": {"agent": "order exceptions", "runs": 600, "start": 8 * 3600, "window": 90 * 60},
    "triage": {"agent": "AGT_INV_TRIAGE", "runs": 300, "start": 8 * 3600, "window": 9 * 3600},
}
WORKING_DAYS = 21
CALL_GAP = 6  # seconds between the three calls of one run
# Tokens per call after the prefix (order or invoice data, question, tool results so far) and out.
REST = [800, 1150, 1500]
OUT = [60, 60, 250]
DEFAULT_PREFIX = 4800  # tools 700 + instructions 900 + Calder's policy and runbook 3,200
LOG = Path("unit10/cache_usage.jsonl")


def per_million(tokens: float, price: float) -> float:
    return tokens * price / 1_000_000


def runs_of_month(name: str, seed: int) -> list:
    """Start times (seconds from the 1st working day 00:00) of every run of one agent."""
    w = WORKLOADS[name]
    rng = random.Random(f"{seed}-{name}")
    base, extra = divmod(w["runs"], WORKING_DAYS)
    starts = []
    for day in range(WORKING_DAYS):
        n = base + (1 if day < extra else 0)
        day_starts = sorted(w["start"] + rng.uniform(0, w["window"]) for _ in range(n))
        starts += [day * 86400 + s for s in day_starts]
    return starts


def calls_of_month(name: str, seed: int, layout: str) -> list:
    """Every model call: time, which prefix it carries, position in its run."""
    calls = []
    for run_no, start in enumerate(runs_of_month(name, seed)):
        # Good layout: one prefix for the whole agent. Bad layout: the run's start time is
        # written into the system prompt, so each run has its own prefix.
        prefix_id = name if layout == "good" else f"{name}-{int(start)}"
        for i in range(3):
            calls.append({"t": start + i * CALL_GAP, "prefix": prefix_id, "call": i + 1,
                          "run": run_no + 1, "rest": REST[i], "out": OUT[i]})
    return sorted(calls, key=lambda c: c["t"])


def simulate(model: str, option: str, calls: list, prefix_tokens: int, log=None) -> dict:
    """Walk through the calls with a cache that behaves as the vendor documents."""
    p = PRICES[model]
    write_price, ttl = p["writes"][option]
    cacheable = prefix_tokens >= p["min_tokens"]
    expiry, created = {}, {}
    r = {"calls": 0, "hits": 0, "writes": 0, "storage_hours": 0.0,
         "cost_none": 0.0, "cost_cache": 0.0, "first_calls": 0, "first_hits": 0}
    for c in calls:
        r["calls"] += 1
        out_cost = per_million(c["out"], p["output"])
        r["cost_none"] += per_million(prefix_tokens + c["rest"], p["input"]) + out_cost
        hit = cacheable and expiry.get(c["prefix"], -1) > c["t"]
        cached = written = 0
        if not cacheable:
            r["cost_cache"] += per_million(prefix_tokens + c["rest"], p["input"]) + out_cost
        elif hit:
            r["hits"] += 1
            cached = prefix_tokens
            r["cost_cache"] += (per_million(prefix_tokens, p["read"])
                                + per_million(c["rest"], p["input"]) + out_cost)
        else:
            r["writes"] += 1
            written = prefix_tokens
            if p["kind"] == "explicit" and c["prefix"] in created:
                # The old cache expired: bill its storage before creating a new one.
                r["storage_hours"] += (expiry[c["prefix"]] - created[c["prefix"]]) / 3600
            created[c["prefix"]] = c["t"]
            r["cost_cache"] += (per_million(prefix_tokens, write_price)
                                + per_million(c["rest"], p["input"]) + out_cost)
        if cacheable:
            if model.startswith("gpt-5.6") and option == "12h" and not hit:
                expiry[c["prefix"]] = c["t"] + ttl          # 12-hour minimum lifetime from the write
            elif model.startswith("gpt-5.6"):
                expiry[c["prefix"]] = max(expiry.get(c["prefix"], 0), c["t"] + 1800)  # reads refresh to 30 min
            else:
                expiry[c["prefix"]] = c["t"] + ttl          # each use restarts the lifetime
        if c["call"] == 1:
            r["first_calls"] += 1
            r["first_hits"] += 1 if hit else 0
        if log is not None:
            log.append({"agent": c["prefix"].split("-")[0], "run": c["run"], "call_in_run": c["call"],
                        "model": model, "cache_option": option,
                        # Field names follow SAP's orchestration v2 usage. In this lab, prompt_tokens
                        # counts every input token, cached or not.
                        "usage": {"prompt_tokens": prefix_tokens + c["rest"],
                                  "completion_tokens": c["out"],
                                  "prompt_tokens_details": {"cached_tokens": cached,
                                                            "cache_creation_tokens": written}}})
    if p["kind"] == "explicit":
        for key, start in created.items():
            r["storage_hours"] += (expiry[key] - start) / 3600
        r["cost_cache"] += per_million(prefix_tokens, p["storage_per_hour"]) * r["storage_hours"]
    return r


def break_even_reads(model: str, option: str) -> str:
    p = PRICES[model]
    write_price = p["writes"][option][0]
    if p["kind"] == "explicit":
        per_hour = p["storage_per_hour"] / (p["input"] - p["read"])
        return f"{per_hour:.1f} hits per hour"
    extra = write_price - p["input"]
    if extra <= 0:
        return "0 (no write premium)"
    reads = extra / (p["input"] - p["read"])
    return f"{int(-(-reads // 1))} read(s)"


def cmd_prices(_args) -> None:
    print("Prompt caching prices, USD per million tokens (vendor pages, read 2026-11-20)\n")
    print(f"{'model':<24}{'option':<11}{'input':>7}{'write':>7}{'read':>7}{'min':>6}  pays back after")
    for model, p in PRICES.items():
        for option, (write_price, _ttl) in p["writes"].items():
            print(f"{model:<24}{option:<11}{p['input']:>7.2f}{write_price:>7.2f}{p['read']:>7.2f}"
                  f"{p['min_tokens']:>6}  {break_even_reads(model, option)}")
    print("\nGemini explicit caching also bills storage: 4.50 per million tokens per hour on this model.")
    print("Regional or data-residency processing adds about 10% at Anthropic and OpenAI (see the topic).")


def cmd_simulate(args) -> None:
    names = ["morning", "triage"] if args.workload == "both" else [args.workload]
    print(f"Calder's agents, one month ({WORKING_DAYS} working days, seed {args.seed}), "
          f"prefix {args.prefix_tokens:,} tokens, layout '{args.layout}'\n")
    log = []
    totals = {}
    for name in names:
        calls = calls_of_month(name, args.seed, args.layout)
        w = WORKLOADS[name]
        print(f"{name}: {w['agent']}, {w['runs']} runs, {len(calls)} calls")
        print(f"  {'model':<24}{'option':<11}{'hit rate':>9}{'writes':>8}{'no cache':>10}{'cached':>10}{'saving':>8}")
        for model, p in PRICES.items():
            for option in p["writes"]:
                want_log = model == args.log_model and option == args.log_option
                r = simulate(model, option, calls, args.prefix_tokens, log if want_log else None)
                saving = 1 - r["cost_cache"] / r["cost_none"]
                hit_rate = r["hits"] / r["calls"]
                t = totals.setdefault((model, option), [0.0, 0.0])
                t[0] += r["cost_none"]
                t[1] += r["cost_cache"]
                note = "" if args.prefix_tokens >= p["min_tokens"] else "  below minimum"
                print(f"  {model:<24}{option:<11}{hit_rate:>8.0%}{r['writes']:>8}"
                      f"{r['cost_none']:>10.2f}{r['cost_cache']:>10.2f}{saving:>8.0%}{note}")
        print()
    if len(names) > 1:
        print("Both agents, USD per month")
        print(f"  {'model':<24}{'option':<11}{'no cache':>10}{'cached':>10}{'saving':>8}")
        for (model, option), (none, cache) in totals.items():
            print(f"  {model:<24}{option:<11}{none:>10.2f}{cache:>10.2f}{1 - cache / none:>8.0%}")
        print()
    LOG.parent.mkdir(parents=True, exist_ok=True)
    LOG.write_text("".join(json.dumps(x) + "\n" for x in log), encoding="utf-8")
    print(f"Wrote {len(log)} usage records for {args.log_model} ({args.log_option}) to {LOG}")
    print("Synthetic: course volumes and timings, vendor list prices. Not a quote for any contract.")


def cmd_measure(args) -> None:
    path = Path(args.file)
    if not path.exists():
        sys.exit(f"No file {path}. Run 'python unit10/cache_economics.py simulate' first.")
    if args.model not in PRICES:
        sys.exit(f"Unknown model {args.model}. Choose one of: {', '.join(PRICES)}")
    p = PRICES[args.model]
    option = args.option or next(iter(p["writes"]))
    if option not in p["writes"]:
        sys.exit(f"--option must be one of {', '.join(p['writes'])}")
    write_price = p["writes"][option][0]
    records = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
    prompt = cached = written = out = first = first_hit = 0
    for rec in records:
        u = rec["usage"]
        d = u.get("prompt_tokens_details") or {}
        prompt += u["prompt_tokens"]
        cached += d.get("cached_tokens") or 0
        written += d.get("cache_creation_tokens") or 0
        out += u["completion_tokens"]
        if rec.get("call_in_run") == 1:
            first += 1
            first_hit += 1 if d.get("cached_tokens") else 0
    plain = prompt - cached - written
    cost_none = per_million(prompt, p["input"]) + per_million(out, p["output"])
    cost = (per_million(plain, p["input"]) + per_million(cached, p["read"])
            + per_million(written, write_price) + per_million(out, p["output"]))
    print(f"{len(records)} calls in {path.name}, priced as {args.model} {option} (write {write_price:.2f})\n")
    print(f"input tokens            {prompt:>12,}")
    print(f"  read from cache       {cached:>12,}  ({cached / prompt:.0%} of input)")
    print(f"  written to cache      {written:>12,}  ({written / prompt:.0%})")
    print(f"  plain input           {plain:>12,}  ({plain / prompt:.0%})")
    print(f"output tokens           {out:>12,}")
    print(f"\ncost without caching    {cost_none:>12.2f} USD")
    print(f"cost with caching       {cost:>12.2f} USD  (saving {1 - cost / cost_none:.0%})")
    if first:
        rate = first_hit / first
        print(f"\nfirst calls of a run that hit the cache: {first_hit} of {first} ({rate:.2f})")
        print(f"In the cost model from the token economics topic, use: --hit-rate {rate:.2f}")


def main() -> None:
    parser = argparse.ArgumentParser(description="Prompt caching economics for Calder's agents.")
    sub = parser.add_subparsers(dest="command", required=True)
    sub.add_parser("prices", help="list prices and break-even reads")
    s = sub.add_parser("simulate", help="simulate one month of calls")
    s.add_argument("--layout", choices=["good", "bad"], default="good")
    s.add_argument("--workload", choices=["morning", "triage", "both"], default="both")
    s.add_argument("--prefix-tokens", type=int, default=DEFAULT_PREFIX)
    s.add_argument("--seed", type=int, default=42)
    s.add_argument("--log-model", default="claude-sonnet-5.5", choices=list(PRICES))
    s.add_argument("--log-option", default="5m")
    m = sub.add_parser("measure", help="price a usage log")
    m.add_argument("file")
    m.add_argument("--model", default="claude-sonnet-5.5")
    m.add_argument("--option", help="cache option whose write price applies, for example 5m or 1h")
    args = parser.parse_args()
    if args.command == "simulate":
        if args.log_option not in PRICES[args.log_model]["writes"]:
            sys.exit(f"--log-option must be one of {', '.join(PRICES[args.log_model]['writes'])}")
        if args.prefix_tokens < 1:
            sys.exit("--prefix-tokens must be a positive number.")
    {"prices": cmd_prices, "simulate": cmd_simulate, "measure": cmd_measure}[args.command](args)


if __name__ == "__main__":
    main()
```

2. Check that the file is in the right place:

   - **Windows (PowerShell):**

     ```powershell
     dir unit10\cache_economics.py
     ```

   - **macOS / Linux:**

     ```bash
     ls unit10/cache_economics.py
     ```

   You should see the file name.

#### Step 3: List the prices and break-even points

1. Run (the same on every system):

   ```bash
   python unit10/cache_economics.py prices
   ```

2. You should see:

```text
Prompt caching prices, USD per million tokens (vendor pages, read 2026-11-20)

model                   option       input  write   read   min  pays back after
claude-sonnet-5.5       5m            2.00   2.50   0.10   512  1 read(s)
claude-sonnet-5.5       1h            2.00   4.00   0.10   512  2 read(s)
claude-haiku-4.5        5m            1.00   1.25   0.10  4096  1 read(s)
claude-haiku-4.5        1h            1.00   2.00   0.10  4096  2 read(s)
gpt-5.6-terra           30m           2.00   2.50   0.20  1024  1 read(s)
gpt-5.6-terra           12h           2.00   5.00   0.20  1024  2 read(s)
gpt-5.4                 in_memory     2.50   2.50   0.25  1024  0 (no write premium)
gpt-5.4                 24h           2.50   2.50   0.25  1024  0 (no write premium)
gemini-3.1-pro-preview  explicit      2.00   2.00   0.20  4096  2.5 hits per hour

Gemini explicit caching also bills storage: 4.50 per million tokens per hour on this model.
Regional or data-residency processing adds about 10% at Anthropic and OpenAI (see the topic).
```

The last column applies the break-even formula. The 1-hour and 12-hour options need two reads, older OpenAI models none, and the Gemini explicit cache needs 2.5 reads every hour it exists.

#### Step 4: Simulate a month with a stable prefix

1. Run:

   ```bash
   python unit10/cache_economics.py simulate
   ```

2. You should see this (your numbers match exactly, because the seed is fixed):

```text
Calder's agents, one month (21 working days, seed 42), prefix 4,800 tokens, layout 'good'

morning: order exceptions, 600 runs, 1800 calls
  model                   option      hit rate  writes  no cache    cached  saving
  claude-sonnet-5.5       5m              93%     131     23.64      8.73     63%
  claude-sonnet-5.5       1h              99%      21     23.64      7.62     68%
  claude-haiku-4.5        5m              93%     131     11.82      4.77     60%
  claude-haiku-4.5        1h              99%      21     11.82      4.24     64%
  gpt-5.6-terra           30m             99%      21     24.08      8.76     64%
  gpt-5.6-terra           12h             99%      21     24.08      9.02     63%
  gpt-5.4                 in_memory       93%     131     30.11     12.08     60%
  gpt-5.4                 24h             99%      21     30.11     10.89     64%
  gemini-3.1-pro-preview  explicit        99%      21     24.08      9.81     59%

triage: AGT_INV_TRIAGE, 300 runs, 900 calls
  model                   option      hit rate  writes  no cache    cached  saving
  claude-sonnet-5.5       5m              71%     263     11.82      6.64     44%
  claude-sonnet-5.5       1h              93%      65     11.82      4.83     59%
  claude-haiku-4.5        5m              71%     263      5.91      3.47     41%
  claude-haiku-4.5        1h              93%      65      5.91      2.61     56%
  gpt-5.6-terra           30m             84%     144     12.04      5.86     51%
  gpt-5.6-terra           12h             98%      21     12.04      4.75     61%
  gpt-5.4                 in_memory       71%     263     15.05      8.17     46%
  gpt-5.4                 24h             84%     144     15.05      6.89     54%
  gemini-3.1-pro-preview  explicit        93%      65     12.04      8.19     32%

Both agents, USD per month
  model                   option       no cache    cached  saving
  claude-sonnet-5.5       5m              35.46     15.37     57%
  claude-sonnet-5.5       1h              35.46     12.45     65%
  claude-haiku-4.5        5m              17.73      8.24     54%
  claude-haiku-4.5        1h              17.73      6.85     61%
  gpt-5.6-terra           30m             36.13     14.62     60%
  gpt-5.6-terra           12h             36.13     13.77     62%
  gpt-5.4                 in_memory       45.16     20.25     55%
  gpt-5.4                 24h             45.16     17.78     61%
  gemini-3.1-pro-preview  explicit        36.13     18.00     50%

Wrote 2700 usage records for claude-sonnet-5.5 (5m) to unit10/cache_usage.jsonl
Synthetic: course volumes and timings, vendor list prices. Not a quote for any contract.
```

> **Note** Synthetic numbers: course volumes, timings and list prices, not a measurement of any real system.

Read it in three passes:

- **Morning**: every option saves 59 to 68%. Calls arrive every few minutes, so even a 5-minute lease hits 93% of the time.
- **Triage**: the 5-minute options hit 71% and save about 44%; the 1-hour, 30-minute and 12-hour options do better because runs are spread out. Gemini's explicit cache saves only 32%: it pays storage all day for a cache read a few times an hour.
- **Both agents**: on Anthropic, the 1-hour lease beats the 5-minute one for both agents: by a little in the morning, by a lot for triage. On OpenAI the 12-hour write wins on triage but not in the morning, so a real design could choose per agent.

#### Step 5: Break the layout

Now write the run's start time into the instructions, as a well-meant "Today is ..." line would.

1. Run:

   ```bash
   python unit10/cache_economics.py simulate --layout bad --workload triage
   ```

2. You should see:

```text
Calder's agents, one month (21 working days, seed 42), prefix 4,800 tokens, layout 'bad'

triage: AGT_INV_TRIAGE, 300 runs, 900 calls
  model                   option      hit rate  writes  no cache    cached  saving
  claude-sonnet-5.5       5m              67%     300     11.82      7.07     40%
  claude-sonnet-5.5       1h              67%     300     11.82      9.23     22%
  claude-haiku-4.5        5m              67%     300      5.91      3.68     38%
  claude-haiku-4.5        1h              67%     300      5.91      4.76     19%
  gpt-5.6-terra           30m             67%     300     12.04      7.58     37%
  gpt-5.6-terra           12h             67%     300     12.04     11.18      7%
  gpt-5.4                 in_memory       67%     300     15.05      8.57     43%
  gpt-5.4                 24h             67%     300     15.05      8.57     43%
  gemini-3.1-pro-preview  explicit        67%     300     12.04     13.36    -11%

Wrote 900 usage records for claude-sonnet-5.5 (5m) to unit10/cache_usage.jsonl
Synthetic: course volumes and timings, vendor list prices. Not a quote for any contract.
```

Every run now has its own prefix, so every run pays a write and only its own second and third calls hit. The long leases hurt most: the 12-hour write saves 7% instead of 61%, and the Gemini cache costs 11% **more** than no cache, because each run creates a cache that is stored for an hour and read twice. The fix costs nothing: move the date after the cache point.

#### Step 6: See the minimum length bite

1. Run with a shorter prefix:

   ```bash
   python unit10/cache_economics.py simulate --prefix-tokens 3000 --workload triage
   ```

2. You should see:

```text
Calder's agents, one month (21 working days, seed 42), prefix 3,000 tokens, layout 'good'

triage: AGT_INV_TRIAGE, 300 runs, 900 calls
  model                   option      hit rate  writes  no cache    cached  saving
  claude-sonnet-5.5       5m              71%     263      8.58      5.34     38%
  claude-sonnet-5.5       1h              93%      65      8.58      4.21     51%
  claude-haiku-4.5        5m               0%       0      4.29      4.29      0%  below minimum
  claude-haiku-4.5        1h               0%       0      4.29      4.29      0%  below minimum
  gpt-5.6-terra           30m             84%     144      8.80      4.94     44%
  gpt-5.6-terra           12h             98%      21      8.80      4.24     52%
  gpt-5.4                 in_memory       71%     263     11.00      6.70     39%
  gpt-5.4                 24h             84%     144     11.00      5.90     46%
  gemini-3.1-pro-preview  explicit         0%       0      8.80      8.80      0%  below minimum

Wrote 900 usage records for claude-sonnet-5.5 (5m) to unit10/cache_usage.jsonl
Synthetic: course volumes and timings, vendor list prices. Not a quote for any contract.
```

Haiku 4.5 and Gemini 3.1 Pro Preview need 4,096 tokens, so a 3,000-token prefix isn't cached at all, with no error. A cheap model with a high minimum can lose its caching saving on a short prompt.

#### Step 7: Measure the saving from the usage log

Every `simulate` run wrote `unit10/cache_usage.jsonl`, one record per call, with the fields SAP's orchestration service returns: `prompt_tokens`, `completion_tokens` and, under `prompt_tokens_details`, `cached_tokens` and `cache_creation_tokens`. In a real system you would log those from each response. Here, measure the log as if it came from production.

1. Write a fresh log for Sonnet 5.5 with the 5-minute lease, then measure it:

   ```bash
   python unit10/cache_economics.py simulate > sim.txt
   python unit10/cache_economics.py measure unit10/cache_usage.jsonl --model claude-sonnet-5.5 --option 5m
   ```

2. You should see:

```text
2700 calls in cache_usage.jsonl, priced as claude-sonnet-5.5 5m (write 2.50)

input tokens              16,065,000
  read from cache         11,068,800  (69% of input)
  written to cache         1,891,200  (12%)
  plain input              3,105,000  (19%)
output tokens                333,000

cost without caching           35.46 USD
cost with caching              15.37 USD  (saving 57%)

first calls of a run that hit the cache: 506 of 900 (0.56)
In the cost model from the token economics topic, use: --hit-rate 0.56
```

Most input is now read from the cache, about a ninth is writes, and a fifth is plain input that changes every call. The last line is the share of **first** calls in a run that found the cache warm; the second and third calls always hit.

3. Delete the scratch file: `del sim.txt` (Windows) or `rm sim.txt` (macOS/Linux).

> **Note** In this lab, `prompt_tokens` counts every input token, cached or not. Check how your model reports it before you add the numbers up: on some APIs the plain input field already excludes cached tokens. SAP's own response example for orchestration shows `prompt_tokens` of 3 beside `cached_tokens` of 4,657, which suggests that through orchestration `prompt_tokens` excludes cached tokens; if your log shows that, compute plain input as `prompt_tokens` alone rather than subtracting.

#### Step 8: Carry the result into your cost model

The cost model from [Token economics](https://erpfde.com/topics/token-economics/) uses Anthropic's general multipliers. Sonnet 5.5 reads at 0.05 times input, and its minimum is 512 tokens.

1. Open `unit10/token_costs.py` and change two lines in `RATES`:

   ```python
   "cache_read_multiplier": 0.05,
   "min_cacheable_tokens": 512,
   ```

   The input and output prices in that file (2.00 and 10.00) already match Sonnet 5.5's list price.

2. Run it with the hit rate you measured:

   ```bash
   python unit10/token_costs.py --hit-rate 0.56
   ```

3. The table near the end should show:

```text
design    cache   calls   input  cached  output   per order   per month
pipeline  off         1    1320       0     220 0.00484 USD   29.04 USD
pipeline  on          1     259    1061     220 0.00394 USD   23.67 USD
agent     off         3    3708       0     300 0.01042 USD   62.50 USD
agent     on          3     525    3183     300 0.00549 USD   32.93 USD
```

The blocked-orders assistant's 1,061-token prefix is now above the minimum, so caching works on it, and the measured hit rate replaces the guessed 0.8 that the cost model used by default.

#### Step 9: Save your work

1. Commit:

   ```bash
   git add unit10/cache_economics.py unit10/token_costs.py
   git commit -m "Unit 10: prompt caching economics"
   ```

   The usage log is generated, so you can leave it out of Git.

#### How the code works

| Part | What it does |
| --- | --- |
| `PRICES` | Each model's input, output, read and write prices, the lifetime used for each option, the minimum length, and storage for Gemini |
| `WORKLOADS`, `runs_of_month` | Calder's two agents: runs per month spread over 21 working days, start times drawn with seed 42 inside each agent's window |
| `calls_of_month` | Three calls per run, 6 seconds apart; with `--layout bad` each run gets its own prefix |
| `simulate` | Walks the calls in time order, keeps an expiry per prefix, prices each call as a hit, a write or plain input, adds Gemini storage, and logs SAP-shaped usage |
| Lifetime rules | Anthropic and older OpenAI: each use restarts the lifetime. GPT-5.6+: reads keep it at least 30 minutes; a 12-hour write lasts 12 hours. Gemini: the app extends the cache to an hour after each use |
| `break_even_reads` | The formula from How it works, per option |
| `measure` | Reads the usage log, splits input into cached, written and plain, prices it and computes the first-call hit rate |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python` is "not recognized" / "command not found" | Python isn't on the path or `.venv` isn't on | Step 1; see [Set up your computer](https://erpfde.com/topics/set-up-your-computer/) |
| `No file unit10/cache_usage.jsonl` | `measure` ran before `simulate` | Run `simulate` first |
| `--option must be one of ...` | The option doesn't exist for that model | Use one listed by `prices`, for example `30m` for `gpt-5.6-terra` |
| `can't open file ... cache_economics.py` | The terminal isn't in `orchestrate-course`, or the file has another name | Open the course folder (Step 1) and check Step 2 |
| Numbers differ from this page | The script was changed or the seed differs | Paste the script again; don't pass `--seed` |
| `token_costs.py` not found in Step 8 | You haven't done the token economics walkthrough | Do it first, or skip Step 8 |
| A proxy or network message | Nothing here uses the network | Check you ran this script, not one with `--llm` |

### The SAP way

#### Caching through the orchestration service

As of the SAP Cloud SDK for AI for Python 7.4.1 (downloaded and read in this run), the version 2 orchestration models carry a `CacheControl` with `type` `"ephemeral"` and an optional `ttl` of `"5m"` (the default) or `"1h"`. It attaches to a `TextPart`, an `ImagePart` or a `ChatCompletionTool`. A system message can hold a list of text parts, so you can mark the end of Calder's reference text as the cache point (a **sketch**: it needs an SAP AI Core account with the extended plan, set up in Unit 3):

```python
# Sketch: needs SAP AI Core credentials (see Set up for Unit 3). Not runnable on its own.
from gen_ai_hub.orchestration_v2 import CacheControl, SystemMessage, TextPart, UserMessage

system = SystemMessage(content=[
    TextPart(text=INSTRUCTIONS),                      # layer 2: role, rules, format
    TextPart(text=CALDER_REFERENCE,                   # layer 3: block reasons, credit rules, runbook
             cache_control=CacheControl(type="ephemeral", ttl="1h")),
])
user = UserMessage(content="Order data: {{?order}}\n\nQuestion: {{?question}}")  # layer 4: per run
```

Responses report `usage.prompt_tokens_details.cached_tokens` for a hit and `cache_creation_tokens` for a write, with a per-TTL breakdown when you set a `ttl`. Log those three numbers with the prompt version on every call; Step 7 is the analysis you then run.

SAP AI Core's documentation adds the limits: explicit caching works only in orchestration V2 and only for Claude (system, messages and tools, up to four breakpoints) and Nova (system and messages, no explicit lifetime); the 1-hour lifetime works only on selected Claude models; OpenAI and Gemini models get implicit caching by default ([SAP AI Core: Prompt caching](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/prompt-caching-77118d6.md)).

The JavaScript SDK (`@sap-ai-sdk/langchain` 2.13.0) adds a `cache_control` call option that puts the breakpoint on the last cacheable text block of the last message, so it moves forward as an agent conversation grows. Its documentation says this applies to the Anthropic Claude and Amazon Nova families through orchestration, and other models ignore it.

> **Note** Amazon Nova caches differently from Claude. AWS documents a 5-minute lifetime and at most 20,000 cached tokens for Nova, and says Nova's own implicit cache reuse is neither reported nor billed as cache reads ([Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html)). How that carries over to Nova on SAP AI Core is something to confirm with SAP.

#### What you pay through SAP

On SAP AI Core, model tokens convert to capacity units at per-model rates in SAP Note 3437766, under your SAP BTP contract ([Token economics](https://erpfde.com/topics/token-economics/)). The SAP sources opened for this topic don't say whether cached or written tokens convert at different rates. Until SAP confirms it for your models, put two lines in the business case: the saving at vendor list prices, and "through SAP: to be confirmed", rather than one number.

#### SAP-delivered AI

Joule, Joule Agents and the AI features inside S/4HANA run on SAP's side. You don't control their prompts or caching, and you pay through SAP's commercial model, not per token.

### Build vs. SAP

| Question | Calling a vendor directly | Through SAP's generative AI hub |
| --- | --- | --- |
| Price you see | Vendor list price per token, with published write and read prices | Capacity units at SAP's per-model rates; cached-token treatment to confirm |
| How you mark the cache | The vendor's own fields (`cache_control`, `prompt_cache_options`, explicit cache objects) | `CacheControl` in the SAP SDK for Claude and Nova; OpenAI and Gemini cache implicitly by default |
| Lifetimes on offer | All the vendor offers (for example 30 minutes and 12 hours at OpenAI) | 5 minutes, or 1 hour on selected Claude models, in the SDK's `CacheControl` |
| Usage reporting | Vendor fields | `cached_tokens`, `cache_creation_tokens` in `prompt_tokens_details` |
| Data approval and filtering | Your own contracts and filters | SAP's contract, plus orchestration's filtering and masking |
| Best when | You need a lifetime or storage model SAP doesn't expose, and the data is approved for that vendor | You already run on SAP AI Core and want one place for models, filters and billing |

### Architecture view

**Where it sits.** Caching is a property of each model call, but the decisions sit in the BTP app that builds the prompt: the layout, the cache point and the lifetime. The usage log feeds your observability stack and the cost report.

```mermaid
flowchart LR
  S4[S/4HANA<br/>blocked orders, invoices] -->|released APIs| APP[BTP agent app<br/>prompt layout + cache point]
  APP -->|/v2/completion| ORCH[Orchestration<br/>SAP AI Core]
  ORCH --> MOD[Model provider<br/>prefix cache]
  APP -->|usage: cached, written, plain| OBS[Traces and cost report]
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Cost per run | Agreed per agent, with cached share tracked | The bill grows with the prefix and no one sees why |
| Cache hit share | Most prefix tokens read, not written, per agent | Writes at 1.25 to 2.5 times input cost more than no cache |
| Prefix stability | No user, date or document in layers 1 to 3 | Every user or day writes its own cache |
| Data retention | Provider cache retention within the approved period | Prompt data kept up to 24 hours without approval |
| Latency | Long prefixes read from cache for interactive use | Slow first answers on every call |

**Integration and identity.** The app reads S/4HANA through released APIs, as the user or a technical user. The user's identity must not enter the cached prefix: put it in the run data and in your traces. If one app serves several companies or tenants, give each its own cache key where the vendor offers one, so accounting and probing protection follow the tenant.

**The decision to record** (short form from [Writing a solution design doc](https://erpfde.com/topics/writing-a-solution-design-doc/)):

- **Context:** Calder's two agents send a 4,800-token prefix on every call; triage runs are spread over the day.
- **Options:** A) no explicit caching; B) 5-minute cache for both agents; C) 1-hour cache for both agents; D) Gemini explicit cache kept through the working day.
- **Decision:** C on the approved Claude model: the cheapest option in the simulation for both agents at list prices, with the layer order enforced by a prompt test.
- **Consequences:** Each write costs 2 times input, so a prompt change that breaks the prefix costs more than under B. The prompt test joins the release gate. The saving through SAP AI Core is confirmed with SAP before it enters the budget.

**What a design review will ask.**

1. What share of last month's input tokens was cached, written and plain, per agent?
2. What in the prefix can change per user, day or document, and which test catches it?
3. Why this lifetime for this agent, and what was the comparison?
4. How are cached tokens priced under our SAP contract?
5. How long does the provider keep cached prompt data, and who approved that?

### Production concerns

- **Security and authorizations.** A cache doesn't widen what the model sees, but a prefix built per role or user splits it, and tenants sharing a key share accounting. Keep one tool list and check authorizations in the tools; give each tenant its own cache key where offered.
- **Data protection.** Cached prompts are stored by the provider for the lease, up to 24 hours on OpenAI's extended retention. Record that in the data flow and get it approved like any other processing.
- **Evaluation.** Caching shouldn't change answers. Run your evaluation set once with and once without cache markers when you introduce them; any difference points at a layout change, not the cache.
- **Cost.** Report cost per agent run from the usage log, split into cached, written and plain input. Watch the written share: a jump means something started changing the prefix.
- **Operations.** A prompt release resets every cache: the first calls after a deployment are writes. Deploy outside the morning peak if the morning agent matters most.
- **Clean core.** All of this sits in the BTP app; S/4HANA is only read through released APIs.

### Pitfalls

- **Dates and users in the system prompt.** The most common way to pay for writes that are never read.
- **Choosing the longest lifetime by default.** On bursty traffic it costs more per write for hits a short lease would have got anyway.
- **Explicit storage caches for occasional traffic.** They cost rent whether used or not.
- **A prefix just under the minimum.** No error, no cache. Check the token count against each model's minimum.
- **Reading the wrong usage field.** Some APIs count cached tokens inside the prompt total, others report plain input separately. Adding them twice doubles the apparent input.
- **Budgeting with vendor list prices through SAP.** Through the generative AI hub you pay SAP's capacity units.
- **Forgetting regional uplifts.** Data residency options add about 10% at Anthropic and OpenAI, and caching multipliers stack on top.

### Exercise

Choose a cache lifetime for a third Calder agent.

1. In `unit10/cache_economics.py`, add a workload to `WORKLOADS`: `"close": {"agent": "month-end close helper", "runs": 120, "start": 7 * 3600, "window": 11 * 3600}`.
2. Run `python unit10/cache_economics.py simulate --workload close` (add `"close"` to the `--workload` choices and to the names list in `cmd_simulate` if you want it in the `both` run).
3. For each model, note which lifetime gives the lowest monthly cost, and whether any option costs more than no cache.
4. Run the same with `--layout bad` and note the option that suffers most.
5. In `unit10/cache_decision.md`, write the decision record from the Architecture view for the three agents, with one lifetime per agent and the reason from your numbers.
6. Commit both files.

**Done when:** `simulate --workload close` prints a table for the new agent, and `cache_decision.md` names a lifetime per agent backed by the simulated monthly costs. The decision record feeds [the security review topic](https://erpfde.com/topics/getting-an-ai-system-through-security-review/).

### Check yourself

1. Using the break-even formula, how many reads does a 12-hour OpenAI write (2.5 times input, reads at 0.1) need before it pays?
   - A. One read, like every cache write at OpenAI
   - B. Two reads, because 1.5 divided by 0.9 is about 1.7
   - C. Three reads, because the write costs 2.5 times input
   - D. None, since OpenAI writes cost no more than input

   Answer: B. Caching pays when n is at least (w − 1) / (1 − r). With w = 2.5 and r = 0.1 that is 1.5 / 0.9, about 1.7, so two reads. The no-charge rule applies only to OpenAI models before GPT-5.6.

2. In the simulation, why does the 1-hour Anthropic lease help the triage agent far more than the morning agent?
   - A. The morning agent's prefix is too short for the 1-hour option
   - B. The 1-hour lease has a cheaper read price than the 5-minute lease
   - C. Triage runs are spread out, so short leases lapse between runs
   - D. The morning agent makes fewer calls per run than triage

   Answer: C. Morning runs arrive every few minutes, so a 5-minute lease rarely expires. Triage runs are about half an hour apart, so the 5-minute cache is rewritten at most runs and the longer lease turns those writes into reads.

3. With `--layout bad`, the Gemini explicit cache costs more than no cache. What is the mechanism?
   - A. Each run creates its own cache, stores it an hour and reads it twice
   - B. Gemini rejects prompts with timestamps and charges a retry
   - C. The bad layout pushes the prefix below Gemini's minimum length
   - D. Gemini bills cached tokens above the normal input price

   Answer: A. The start time makes every run's prefix unique. Each run pays to create a cache plus an hour of storage for only two reads by its own later calls, which is below the 2.5 reads an hour that storage needs.

4. A colleague moves the instructions of a GPT-6.2 agent into the top-level `instructions` field "to keep the messages clean". What does OpenAI's guide say happens?
   - A. The instructions are cached for 12 hours automatically
   - B. The instructions stop counting toward the input token total
   - C. The request is rejected because instructions need a cache key
   - D. They bill at the uncached rate on every request

   Answer: D. OpenAI's caching guide says top-level instructions on GPT-6.2 and later bill uncached on every request and recommends a leading developer message for reusable instructions. Small API choices like this decide whether a prefix can be cached.

5. Your usage log shows `prompt_tokens` 5,355, `cached_tokens` 3,628 and `cache_creation_tokens` 691 for a batch of calls. How much input was plain, assuming the prompt total includes cached tokens?
   - A. 5,355 tokens, since cached tokens are reported separately
   - B. 4,664 tokens, the total minus only the written tokens
   - C. 1,036 tokens, the total minus cached and written tokens
   - D. 3,628 tokens, the same as the cached token count

   Answer: C. When the prompt total includes every input token, plain input is the total minus reads minus writes. Check your API's convention first; on some, the plain field already excludes cached tokens and subtracting again would undercount.

6. The triage agent's written share in the cost report doubles overnight with no change in volume. What would you check first?
   - A. Whether the vendor raised its read price that night
   - B. Whether a release put something variable into the prefix
   - C. Whether the model's output answers got longer
   - D. Whether S/4HANA started returning more blocked invoices

   Answer: B. Writes rise when prefixes stop matching: a date, user or reordered tool list in the fixed part, or a new prompt version. Volume and output length don't change the written share of input.

7. Calder's business case uses Anthropic's list prices for an agent that will run through SAP's generative AI hub. What should the review ask?
   - A. Whether Anthropic offers the 1-hour lease in every region
   - B. Whether the agent can call Anthropic directly to save the hub fee
   - C. Whether SAP charges extra for using cache_control in requests
   - D. How cached and written tokens convert to capacity units under the contract

   Answer: D. Through SAP AI Core, tokens convert to capacity units at SAP's per-model rates. The sources opened for this topic don't state how cached tokens convert, so the saving through SAP must be confirmed rather than copied from the vendor list.

## Sources

- [Pricing (Claude Platform documentation, Anthropic)](https://platform.claude.com/docs/en/about-claude/pricing): read 2026-11-20; per model: base input, 5-minute write, 1-hour write, cache hit, output (Sonnet 5.5 2 / 2.50 / 4 / 0.10 / 10; Haiku 4.5 1 / 1.25 / 2 / 0.10 / 5 USD per million tokens); writes 1.25x (5 minutes) and 2x (1 hour) base input; reads 0.1x on most models, 0.05x on Opus 5.5 and Sonnet 5.5, 0.025x on Fable and Mythos 5.1 and 5.2; a 5-minute write pays off after one read, a 1-hour write after two; multipliers stack with batch, long-context and data residency pricing; inference_geo us 1.1x on Claude 4.6 and later
- [Prompt caching (Claude Platform documentation, Anthropic)](https://platform.claude.com/docs/en/build-with-claude/prompt-caching): read 2026-11-20; minimum cacheable length 512 to 4,096 tokens by model (Haiku 4.5 4,096), shorter prompts processed without caching and without an error; 5-minute default lifetime restarted by each read, 1-hour option; up to 4 breakpoints; automatic caching on the last cacheable block; 20-block lookback; order tools, system, messages; changing tool definitions invalidates the whole cache; caches isolated by organization, and by workspace on the Claude API
- [Pricing (OpenAI API documentation)](https://developers.openai.com/api/docs/pricing): read 2026-11-20; standard tier per million tokens: gpt-5.6-terra input 2.00, cached input 0.20, output 12.00, 30-minute write 2.50, 12-hour write 5.00; gpt-5.4 input 2.50, cached 0.25, output 15.00, no write price; regional processing (data residency) endpoints 10% uplift for models released on or after 5 March 2026
- [Prompt caching (OpenAI API documentation)](https://developers.openai.com/api/docs/guides/prompt-caching): read 2026-11-20 (markdown version); on by default; GPT-5.6 and later: 1,024-token minimum, 30-minute writes at 1.25x and 12-hour writes at 2.5x the uncached input rate, reads 0.1x (0.05x on some GPT-6.x models), prompt_cache_options and prompt_cache_breakpoint; earlier models: no extra write charge, prompt_cache_retention in_memory (about 5 to 10 minutes of inactivity, up to an hour) or 24h (typically about 30 minutes, up to 24 hours); prompt_cache_key for per-customer accounting and against cache-hit probing, about 15 requests per minute per key on earlier models; caches not shared across organizations or regional processing boundaries; organizations without Zero Data Retention default to 24h; stable content first, keep tool definitions stable, append instead of rewriting
- [Gemini Developer API pricing (Google AI for Developers)](https://aistudio.google.com/docs/pricing): read 2026-11-20, re-read 2026-11-23 (the ai.google.dev URL now redirects here); gemini-3.1-pro-preview paid tier: input 2.00, output 12.00, context caching 0.20 (prompts up to 200k tokens) and storage 4.50 per million tokens per hour; Gemini 3.8 Flash: input 1.50, context caching 0.15, storage 1.00 per million tokens per hour from 1 January 2027 (0.75, 0.075 and 0.50 through 31 December 2026)
- [Context caching (Gemini API documentation, Google AI for Developers)](https://aistudio.google.com/docs/caching.md?generate-content=true): read 2026-11-20, re-read 2026-11-23 (the ai.google.dev URL now redirects to aistudio.google.com); implicit caching on by default for Gemini 2.5 and newer with no cost saving guarantee, minimum 4,096 tokens on Gemini 3.1 Pro Preview and later listed models, 2,048 on 2.5; explicit caching in beta with a cost-saving guarantee, on Gemini 3 and 2.5 models only (not Gemini 4), default TTL 1 hour, billed as reduced-rate cached tokens plus storage by TTL duration; put large common content first and send similar-prefix requests close together
- [Prompt caching for faster model inference (Amazon Bedrock User Guide)](https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html): read 2026-11-20; Nova models: 1K minimum, 4 checkpoints, 5-minute TTL, at most 20K tokens cached; implicit cache reuse on Nova is not reported or billed as cache reads; written tokens billed at the model's cache-write rate, which can be higher than input; not supported with batch inference; cache hits not deducted against rate limits
- [Prompt caching (SAP AI Core documentation, generative AI hub)](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/prompt-caching-77118d6.md): read 2026-11-23 from its source in github.com/SAP-docs/sap-artificial-intelligence (prompt-caching-77118d6.md); explicit caching with cache_control in orchestration V2 only, for Anthropic Claude (system, messages, tools; up to four breakpoints) and Amazon Nova (system and messages, no tools, no explicit TTL); 5-minute default, 1 hour on select Claude models; implicit caching for OpenAI and Gemini models on by default in orchestration; usage reports cached_tokens and cache_creation_tokens; the page doesn't say how cached tokens are metered
- [SAP Cloud SDK for AI, generative AI package (sap-ai-sdk-gen 7.4.1 on PyPI)](https://pypi.org/project/sap-ai-sdk-gen/7.4.1/): downloaded and read in this run: orchestration_v2 CacheControl (type ephemeral, ttl 5m default or 1h) attaches to TextPart, ImagePart and ChatCompletionTool; SystemMessage content may be a list of TextPart; usage prompt_tokens_details.cached_tokens (cache hit) and cache_creation_tokens (cache miss), with a per-TTL breakdown when a ttl is set
- [@sap-ai-sdk/langchain 2.13.0, orchestration types (SAP Cloud SDK for AI for JavaScript, on unpkg)](https://app.unpkg.com/@sap-ai-sdk/langchain@2.13.0/files/dist/orchestration/types.d.ts): read 2026-11-20; cache_control call option puts a breakpoint on the last cacheable text block of the last message, moving forward as the conversation grows; applies only to models that support cache_control through orchestration, named as the Anthropic Claude and Amazon Nova families; other models ignore it
