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.
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.
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). 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.
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.
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).
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 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).
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)
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.
Longer lifetimes cost more to write. They pay only when calls are spread out enough that a short cache would expire between them.
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".
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.
"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.
Pick one answer for each question. The explanation appears after you choose.
1What single question decides whether prompt caching pays for a workload?
Answer: A. 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.
2Calder's morning agent saves more from caching than its triage agent with the same prefix. Why?
Answer: A. 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.
3Since GPT-5.6, what changed in OpenAI's caching prices?
Answer: C. 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.
4A vendor proposes Gemini explicit caching for an agent that runs a few times a day. What should worry you?
Answer: B. 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.
5The team's AI feature writes "Today is 20 November, user 00100265" at the top of its instructions. What is the cost effect?
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.
6Calder calls models through SAP's generative AI hub. What must you confirm before counting on a caching saving?
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.
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:
Price shape: write multiplier w, read multiplier r, storage s (all relative to input).
Arrival shape: the gaps between calls that carry the same prefix, compared with the lease length.
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.
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:
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.
The formula needs n, and n comes from your traffic, not your volume. Two workloads with the same monthly count behave differently:
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.
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).
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.
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).
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.
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.
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]
In VS Code, right-click the unit10 folder, choose New File, name it cache_economics.py, paste the code below and save.
"""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()
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.
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.
Now write the run's start time into the instructions, as a well-meant "Today is ..." line would.
Run:
python unit10/cache_economics.py simulate --layout bad --workload triage
You should see:
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.
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.
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.
Write a fresh log for Sonnet 5.5 with the 5-minute lease, then measure it:
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.
Delete the scratch file: del sim.txt (Windows) or rm sim.txt (macOS/Linux).
The input and output prices in that file (2.00 and 10.00) already match Sonnet 5.5's list price.
Run it with the hit rate you measured:
python unit10/token_costs.py --hit-rate 0.56
The table near the end should show:
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.
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
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):
# 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).
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.
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). 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.
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.
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.
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.
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.
What share of last month's input tokens was cached, written and plain, per agent?
What in the prefix can change per user, day or document, and which test catches it?
Why this lifetime for this agent, and what was the comparison?
How are cached tokens priced under our SAP contract?
How long does the provider keep cached prompt data, and who approved that?
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.
In unit10/cache_economics.py, add a workload to WORKLOADS: "close": {"agent": "month-end close helper", "runs": 120, "start": 7 * 3600, "window": 11 * 3600}.
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).
For each model, note which lifetime gives the lowest monthly cost, and whether any option costs more than no cache.
Run the same with --layout bad and note the option that suffers most.
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.
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.
Pick one answer for each question. The explanation appears after you choose.
1Using 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?
Answer: A. 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.
2In the simulation, why does the 1-hour Anthropic lease help the triage agent far more than the morning agent?
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.
3With --layout bad, the Gemini explicit cache costs more than no cache. What is the mechanism?
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.
4A 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?
Answer: A. 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.
5Your 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?
Answer: D. 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.
6The triage agent's written share in the cost report doubles overnight with no change in volume. What would you check first?
Answer: A. 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.
7Calder'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?
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.
Pricing (Claude Platform documentation, Anthropic)— 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)— 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)— 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)— 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)— 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)— 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)— 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)— 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)— 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)— 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