Last active
September 17, 2026 20:44
-
-
Save elementalvoid/3ae69b010a4a71e0094bc4877efff88f to your computer and use it in GitHub Desktop.
A small tool to analyze and recommend LLM inference cache TTL for Pi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """Compare each pi session's actual prompt-cache TTL against the other TTL. | |
| Usage: cache_ttl_cost.py [-n N | --all] [--ttl auto|5m|1h] [--sessions-dir DIR] | |
| pi does not log the TTL (it comes from cacheRetention/PI_CACHE_RETENTION), so it | |
| is inferred: on a turn whose gap since the previous turn is 5m-1h, a 5m session | |
| re-writes the prefix (cacheWrite >> cacheRead) while a 1h session reads it | |
| (cacheRead > cacheWrite). Majority vote over those turns per session. | |
| Sessions are grouped by the TTL they ran with and each group gets its own table: | |
| TTL is a set-it-and-forget-it setting, so the question is "was this group's choice | |
| right", not a blended delta. | |
| Repricing flips exactly those in-window turns, in whichever direction the session | |
| wasn't run: | |
| 5m -> 1h: the miss becomes a read (cacheWrite priced at the read rate), every | |
| other write repriced at the 1h write rate. | |
| 1h -> 5m: the hit becomes a miss (cacheRead+cacheWrite priced as a 5m write), | |
| every other write repriced at the 5m write rate. | |
| Public Anthropic pricing, USD per MTok. | |
| The TTL must be chosen once per session: switching TTL on a live prefix is a full | |
| cache miss (Anthropic binds the cache and signed thinking blocks to the exact | |
| prefix incl. cache_control.ttl), so a mid-session "hybrid" is never worth it. | |
| """ | |
| import argparse | |
| import json | |
| from datetime import datetime | |
| from pathlib import Path | |
| # (base input, 5m write, 1h write, cache read, output) $/MTok | |
| # https://platform.claude.com/docs/en/about-claude/pricing | |
| PRICES = { | |
| "fable-5.1": (10, 12.5, 20, 0.25, 50), | |
| "mythos-5.1": (10, 12.5, 20, 0.25, 50), | |
| "fable-5": (10, 12.5, 20, 1, 50), | |
| "mythos-5": (10, 12.5, 20, 1, 50), | |
| "opus-5": (5, 6.25, 10, 0.5, 25), | |
| "opus-4-8": (5, 6.25, 10, 0.5, 25), | |
| "opus-4-7": (5, 6.25, 10, 0.5, 25), | |
| "opus-4-6": (5, 6.25, 10, 0.5, 25), | |
| "opus-4-5": (5, 6.25, 10, 0.5, 25), | |
| "opus-4-1": (15, 18.75, 30, 1.5, 75), | |
| "opus-4": (15, 18.75, 30, 1.5, 75), | |
| "sonnet-5": (2, 2.5, 4, 0.2, 10), | |
| "sonnet-4-6": (3, 3.75, 6, 0.3, 15), | |
| "sonnet-4-5": (3, 3.75, 6, 0.3, 15), | |
| "sonnet-4": (3, 3.75, 6, 0.3, 15), | |
| "haiku-4-5": (1, 1.25, 2, 0.1, 5), | |
| "haiku-3-5": (0.8, 1, 1.6, 0.08, 4), | |
| } | |
| FIVE_MIN, ONE_HOUR = 300, 3600 | |
| RED, GREEN, BOLD, RESET = "\033[31m", "\033[32m", "\033[1m", "\033[0m" | |
| def color(x, width=9, prec=4): | |
| c = GREEN if x < 0 else RED if x > 0 else "" | |
| return f"{c}{x:>+{width}.{prec}f}{RESET if c else ''}" | |
| def price(model): | |
| m = model.lower().replace(".", "-") | |
| for key in sorted(PRICES, key=len, reverse=True): # longest match first: opus-4-5 before opus-4 | |
| if key.replace(".", "-") in m: | |
| return PRICES[key] | |
| raise KeyError(f"no price for model {model!r}") | |
| def turns(path): | |
| for line in path.open(): | |
| try: | |
| rec = json.loads(line) | |
| except json.JSONDecodeError: | |
| continue | |
| msg = rec.get("message") or {} | |
| if rec.get("type") == "message" and msg.get("role") == "assistant" and msg.get("usage"): | |
| ts = datetime.fromisoformat(rec["timestamp"].replace("Z", "+00:00")).timestamp() | |
| yield ts, msg["model"], msg["usage"] | |
| def session_turns(path): | |
| """[(gap_or_None, model, input, output, cacheRead, cacheWrite)] in order.""" | |
| out = [] | |
| prev = None | |
| for ts, model, u in turns(path): | |
| out.append(( | |
| ts - prev if prev is not None else None, model, | |
| u.get("input", 0), u.get("output", 0), u.get("cacheRead", 0), u.get("cacheWrite", 0), | |
| )) | |
| prev = ts | |
| return out | |
| def infer_ttl(rows): | |
| """'1h' / '5m' / '?' from how in-window (5m-1h) gap turns actually billed.""" | |
| hits = sum(1 for g, _, _, _, cr, cw in rows if g and FIVE_MIN < g < ONE_HOUR and cr > cw) | |
| misses = sum(1 for g, _, _, _, cr, cw in rows if g and FIVE_MIN < g < ONE_HOUR and cr <= cw) | |
| if not hits and not misses: | |
| return "?" | |
| return "1h" if hits > misses else "5m" | |
| def session_cost(path, ttl_override=None): | |
| """(turns, models, as-run ttl, {'5m': $, '1h': $}, miss5, miss1, parts).""" | |
| rows = session_turns(path) | |
| if not rows: | |
| return None | |
| ttl = ttl_override or infer_ttl(rows) | |
| was_1h = ttl == "1h" # '?' is priced as 5m | |
| costs = {"5m": 0.0, "1h": 0.0} | |
| miss5 = miss1 = 0 | |
| parts = {"input": 0.0, "output": 0.0, "cacheRead": 0.0, "cacheWrite": 0.0} | |
| models = set() | |
| for gap, model, i, o, cr, cw in rows: | |
| models.add(model) | |
| base, w5, w1, rd, out = price(model) | |
| w_actual = w1 if was_1h else w5 | |
| fixed = (i * base + o * out) / 1e6 | |
| actual = fixed + (cr * rd + cw * w_actual) / 1e6 | |
| parts["input"] += i * base / 1e6 | |
| parts["output"] += o * out / 1e6 | |
| parts["cacheRead"] += cr * rd / 1e6 | |
| parts["cacheWrite"] += cw * w_actual / 1e6 | |
| if gap is not None and gap > FIVE_MIN: | |
| miss5 += 1 | |
| if gap is not None and gap > ONE_HOUR: | |
| miss1 += 1 | |
| in_window = gap is not None and FIVE_MIN < gap < ONE_HOUR | |
| if was_1h: # reprice at 5m: in-window hits become full re-writes | |
| alt = fixed + ((cr + cw) * w5 if in_window else cr * rd + cw * w5) / 1e6 | |
| else: # reprice at 1h: in-window misses become reads | |
| alt = fixed + (cr * rd + cw * (rd if in_window else w1)) / 1e6 | |
| costs["1h" if was_1h else "5m"] += actual | |
| costs["5m" if was_1h else "1h"] += alt | |
| return len(rows), models, ttl, costs, miss5, miss1, parts | |
| def parse_args(): | |
| ap = argparse.ArgumentParser( | |
| description="Compare 5m vs 1h prompt-cache TTL cost across pi sessions.", | |
| epilog=__doc__.split("Usage:")[0].strip(), | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| ) | |
| g = ap.add_mutually_exclusive_group() | |
| g.add_argument("-n", "--sessions", type=int, default=25, metavar="N", help="N most recent sessions by mtime (default 25)") | |
| g.add_argument("--all", action="store_true", help="every session on disk") | |
| ap.add_argument("--sessions-dir", type=Path, default=Path.home() / ".pi/agent/sessions", metavar="DIR", | |
| help="pi sessions root (default ~/.pi/agent/sessions)") | |
| ap.add_argument("--ttl", choices=("auto", "5m", "1h"), default="auto", | |
| help="TTL each session actually ran with (default auto: infer per session)") | |
| return ap.parse_args() | |
| def group_table(ttl, rows, label): | |
| """One table per as-run TTL: actual vs the counterfactual for that group.""" | |
| other = "5m" if ttl == "1h" else "1h" | |
| print(f"{BOLD}Cache TTL Used: {ttl}{RESET} ({len(rows)} sessions) - {label}") | |
| hdr = (f"{'session':<20} {'model':<22} {'turns':>5} {'miss5m':>6} {'miss1h':>6} " | |
| f"{'as-run':>10} {'if ' + other:>10} {'delta':>9}") | |
| print(hdr) | |
| print("-" * len(hdr)) | |
| ta = tb = 0.0 # as-run, counterfactual | |
| tm5 = tm1 = 0 | |
| for sid, model, n, m5, m1, costs in rows: | |
| a, b = costs[ttl if ttl != "?" else "5m"], costs[other] | |
| ta, tb, tm5, tm1 = ta + a, tb + b, tm5 + m5, tm1 + m1 | |
| print(f"{sid:<20} {model:<22} {n:>5} {m5:>6} {m1:>6} {a:>10.4f} {b:>10.4f} {color(b - a)}") | |
| print("-" * len(hdr)) | |
| d = tb - ta | |
| sign = GREEN + "-" if d < 0 else RED + "+" | |
| pct = f"({color(100 * d / ta, 0, 1)}%)" if ta else "(n/a)" | |
| print(f"{BOLD}{'SUBTOTAL':<20}{RESET} {'':<22} {'':>5} {tm5:>6} {tm1:>6} " | |
| f"{ta:>10.4f} {tb:>10.4f} {color(d)}") | |
| print(f" switching this group to {other}: {sign}${abs(d):.4f}{RESET} {pct}") | |
| print() | |
| return ta, tb | |
| LABELS = { | |
| "5m": "what 1h would have cost", | |
| "1h": "what 5m would have cost", | |
| "?": "no 5m-1h gaps, priced as 5m; delta is just the 2x write premium", | |
| } | |
| def main(): | |
| args = parse_args() | |
| files = sorted(args.sessions_dir.glob("*/*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True) | |
| if not args.all: | |
| files = files[: args.sessions] | |
| tot_a = tot_5m = tot_1h = 0.0 | |
| tot_n = tot_m5 = tot_m1 = 0 | |
| tot_parts = {"input": 0.0, "output": 0.0, "cacheRead": 0.0, "cacheWrite": 0.0} | |
| groups = {} | |
| for f in files: | |
| res = session_cost(f, None if args.ttl == "auto" else args.ttl) | |
| if not res: | |
| continue | |
| n, models, ttl, costs, m5, m1, parts = res | |
| tot_a += costs["1h" if ttl == "1h" else "5m"] | |
| tot_5m += costs["5m"] | |
| tot_1h += costs["1h"] | |
| tot_n += n | |
| tot_m5 += m5 | |
| tot_m1 += m1 | |
| for k in tot_parts: | |
| tot_parts[k] += parts[k] | |
| groups.setdefault(ttl, []).append((f.stem[:20], ",".join(sorted(models))[:22], n, m5, m1, costs)) | |
| nses = sum(len(v) for v in groups.values()) | |
| scope = "all sessions" if args.all else f"{nses} most recent sessions" | |
| print(f"{BOLD}pi prompt-cache TTL: as-run vs counterfactual{RESET} [{scope}]") | |
| print() | |
| contrib = {} # per group: (all-1h) - (all-5m), same sign as the verdict | |
| for ttl in ("5m", "1h", "?"): | |
| if ttl in groups: | |
| ta, tb = group_table(ttl, groups[ttl], LABELS[ttl]) | |
| contrib[ttl] = ta - tb if ttl == "1h" else tb - ta | |
| print(f"{BOLD}Where the money went{RESET} (as-run, summed)") | |
| for k, v in tot_parts.items(): | |
| print(f" {k:<10} ${v:>10.4f} {100 * v / tot_a if tot_a else 0:>5.1f}%") | |
| print(f" {'total':<10} ${tot_a:>10.4f}") | |
| print() | |
| print(f"{BOLD}Legend{RESET}") | |
| print(" input uncached input only (tokens after the last cache breakpoint, ~2-4/turn); cached input is in cacheRead/cacheWrite") | |
| print(" miss5m/miss1h turns whose gap since the previous turn exceeded the TTL (cache expired, full re-write)") | |
| print(" Cache TTL Used TTL the session actually used, inferred from in-window billing ('?' = no 5m-1h gaps to judge by)") | |
| print() | |
| if tot_a: | |
| print(f"{BOLD}Verdict{RESET} (TTL is set-and-forget, so compare the two all-in totals)") | |
| best = "1h" if tot_1h < tot_5m else "5m" | |
| worst, bestv = max(tot_5m, tot_1h), min(tot_5m, tot_1h) | |
| d = bestv - worst | |
| sign = GREEN + "-" if d < 0 else RED + "+" | |
| print(f" {'every session on 5m':<21} ${tot_5m:>10.4f}") | |
| print(f" {'every session on 1h':<21} ${tot_1h:>10.4f}") | |
| print(f" {f'always-{best} wins by':<21} {sign}${abs(d):>10.4f}{RESET} " | |
| f"({color(100 * d / worst, 0, 1)}%)") | |
| flip = 1 if best == "1h" else -1 | |
| terms = " ".join(f"{color(flip * contrib[t], 0)} ({t} group)" for t in ("5m", "1h", "?") if t in contrib) | |
| print(f" {'':<21} = {terms}") | |
| print() | |
| print(f"{BOLD}Evidence{RESET} behind that verdict") | |
| mix = ", ".join(f"{len(groups[t])} ran {t}" for t in ("5m", "1h", "?") if t in groups) | |
| print(f" {nses} sessions ({mix}), {tot_n} assistant turns, ${tot_a:.4f} as-run spend") | |
| print(f" {tot_m5} turns with a >5m gap, {tot_m1} with a >1h gap " | |
| f"({tot_m5 - tot_m1} in the 5m-1h window the TTL choice actually decides)") | |
| if nses < 10 or tot_m5 - tot_m1 < 10: | |
| print(" thin sample: few in-window turns, treat the verdict as directional only") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment