cacheplan 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cacheplan/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """cacheplan: diagnose LLM prompt caching, forecast what each setting would cost,
2
+ and plan the fix. See https://github.com/shamiksaharcciit-oss/cacheplan"""
3
+ __version__ = "0.1.0a1"
cacheplan/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
cacheplan/cli.py ADDED
@@ -0,0 +1,213 @@
1
+ """cacheplan command line."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import statistics
7
+ import sys
8
+
9
+ from . import __version__
10
+ from .diagnose import find_breaks, summarise
11
+ from .findings import RULES, findings
12
+ from .forecast import OPTIONS, Knowledge, examine, learn_from, simulate
13
+ from .logs import by_app, load
14
+ from .messages import est_tokens, prefix_blocks
15
+ from .render import as_dict, text
16
+
17
+
18
+ def _load(args) -> tuple[list[dict], Knowledge | None]:
19
+ """Rows to analyse, and knowledge learned from another log when --learn-from is given."""
20
+ learn_path = getattr(args, "learn_from", None)
21
+ log = load([learn_path, *args.logs] if learn_path else args.logs)
22
+ for why, n in log.skipped.items():
23
+ print(f"skipped {n} line(s): {why}", file=sys.stderr)
24
+ if not log.rows:
25
+ raise SystemExit("No Anthropic Messages requests found in the log.")
26
+ if learn_path:
27
+ train = [r for r in log.rows if r["_src"] == 0]
28
+ rows = [r for r in log.rows if r["_src"] > 0]
29
+ return rows, learn_from(train)
30
+ return log.rows, None
31
+
32
+
33
+ def cmd_report(a) -> int:
34
+ rows, k = _load(a)
35
+ verdicts = examine(rows, k, a.min_tokens)
36
+ k = k or learn_from(rows)
37
+ apps = by_app(rows)
38
+ results = [(v, findings(v, apps[v.app], k, a.min_tokens, not a.no_content)) for v in verdicts]
39
+ if a.json:
40
+ print(json.dumps({"cacheplan": __version__, "applications": [as_dict(v, f) for v, f in results]}, indent=1))
41
+ else:
42
+ print(f"cacheplan {__version__}: {len(rows)} requests, {len(results)} application(s). "
43
+ "Forecasts come from a local model of Anthropic caching; confirm with `cacheplan verify`.\n")
44
+ shown = [(v, f) for v, f in results if v.requests >= 3 or len(results) == 1]
45
+ print("\n\n".join(text(v, f) for v, f in shown))
46
+ if len(shown) < len(results):
47
+ print(f"\n{len(results) - len(shown)} application(s) with fewer than 3 requests not shown (use --json for all).")
48
+ fail = set(filter(None, (a.fail_on or "").split(",")))
49
+ hit = sorted({f.rule for _, fs in results for f in fs} & fail)
50
+ if hit:
51
+ print("\nfailing on: " + ", ".join(hit), file=sys.stderr)
52
+ return 1
53
+ return 0
54
+
55
+
56
+ def cmd_diagnose(a) -> int:
57
+ rows, _ = _load(a)
58
+ for app, rs in by_app(rows).items():
59
+ breaks = find_breaks(app, rs)
60
+ print(f"{app}: {len(rs)} requests, {len(breaks)} prefix break(s)")
61
+ for g in summarise(breaks):
62
+ cause = f" ({g['cause']})" if g["cause"] else ""
63
+ print(f" {g['count']:>3}x {g['kind']}{cause} at {g['where']}: ~{g['lost_tokens']:,} tokens re-sent")
64
+ if a.verbose:
65
+ for b in breaks:
66
+ print(f" request {b.request}: {b.kind} at {b.path}" + (f" +{b.offset}" if b.kind == "changed" else "")
67
+ + f", ~{b.lost_tokens:,} tokens behind it")
68
+ if b.was and not a.no_content:
69
+ print(f" was: {b.was}\n now: {b.now}")
70
+ print()
71
+ return 0
72
+
73
+
74
+ def cmd_check(a) -> int:
75
+ """For pipelines: fail when the reusable share of a log falls below a threshold."""
76
+ rows, k = _load(a)
77
+ bad = 0
78
+ for v in examine(rows, k, a.min_tokens):
79
+ ok = v.reusable >= a.min_reusable
80
+ bad += not ok
81
+ print(f"{'ok ' if ok else 'FAIL'} {v.app}: {v.reusable:.0%} of input tokens reusable "
82
+ f"(threshold {a.min_reusable:.0%})")
83
+ return 1 if bad else 0
84
+
85
+
86
+ def cmd_gaps(a) -> int:
87
+ rows, k = _load(a)
88
+ k = k or learn_from(rows)
89
+ opts = ["off", "auto_5m", "auto_1h", "plan_5m", "plan_1h"]
90
+ t0 = rows[0]["ts"]
91
+ print("Forecast cost vs no caching as the time between requests grows (local model)\n")
92
+ print("| Pauses scaled by | Median pause | " + " | ".join(OPTIONS[o][0] for o in opts[1:]) + " |")
93
+ print("| --- | --- |" + " --- |" * (len(opts) - 1))
94
+ for scale in [float(x) for x in a.scales.split(",")]:
95
+ scaled = [dict(r, ts=t0 + (r["ts"] - t0) * scale) for r in rows]
96
+ res = simulate(scaled, k, opts, a.min_tokens)
97
+ tot = {o: sum(per[o].cost_units() for per in res.values()) for o in opts}
98
+ base = sum(per["off"].total for per in res.values())
99
+ d = [y["ts"] - x["ts"] for x, y in zip(scaled, scaled[1:])] or [0]
100
+ print(f"| {scale:g}x | {statistics.median(d):.0f} s | " + " | ".join(f"{tot[o] / base:.0%}" for o in opts[1:]) + " |")
101
+ return 0
102
+
103
+
104
+ def cmd_verify(a) -> int:
105
+ from . import live
106
+ rows, k = _load(a)
107
+ if a.limit:
108
+ rows = rows[:a.limit]
109
+ verdicts = examine(rows, k, a.min_tokens)
110
+ k = k or learn_from(rows)
111
+ wanted = ["auto_5m"] + sorted({v.recommended for v in verdicts} | {v.fix_option for v in verdicts if v.fix_option})
112
+ if a.options:
113
+ wanted = a.options.split(",")
114
+ options = [o for o in dict.fromkeys(wanted) if o in OPTIONS and o != "off"]
115
+ est = sum(est_tokens(t) for r in rows for t, _ in prefix_blocks(r["request"]))
116
+ print(f"Live run: {len(rows)} requests x {len(options)} option(s) ({', '.join(options)}), "
117
+ f"about {est * len(options):,} input tokens in total (estimate), max_tokens=1.")
118
+ if not a.yes:
119
+ print("Add --yes to send them.")
120
+ return 2
121
+ measured = live.run(rows, k, options, a.model)
122
+ forecast = simulate(rows, k, ["off"] + options, a.min_tokens)
123
+ print(f"\n{'Application':<34} {'Option':<36} {'Forecast':>9} {'Measured':>9} {'Read':>6}")
124
+ for app, per in measured.items():
125
+ base = per["off"].total
126
+ fbase = max(1, forecast[app]["off"].total)
127
+ for o in options:
128
+ u = per[o]
129
+ print(f"{app[:34]:<34} {OPTIONS[o][0]:<36} {forecast[app][o].cost_units() / fbase:>9.0%} "
130
+ f"{u.cost_units() / base:>9.0%} {u.cache_read_input_tokens / max(1, u.total):>6.0%}")
131
+ if a.out:
132
+ with open(a.out, "w", encoding="utf-8") as f:
133
+ json.dump({app: {o: vars(u) for o, u in per.items()} for app, per in measured.items()}, f, indent=1)
134
+ return 0
135
+
136
+
137
+ def cmd_capture(a) -> int:
138
+ from .proxy import serve
139
+ print(f"Capturing on http://127.0.0.1:{a.port} -> {a.upstream}; writing {a.out}.\n"
140
+ f"In the shell that runs your application set ANTHROPIC_BASE_URL=http://127.0.0.1:{a.port}\n"
141
+ "Ctrl+C to stop.")
142
+ try:
143
+ serve(a.port, a.upstream, a.out, a.app).serve_forever()
144
+ except KeyboardInterrupt:
145
+ print("\nstopped")
146
+ return 0
147
+
148
+
149
+ def cmd_rules(_) -> int:
150
+ for rule, what in RULES.items():
151
+ print(f"{rule} {what}")
152
+ return 0
153
+
154
+
155
+ def main(argv: list[str] | None = None) -> int:
156
+ ap = argparse.ArgumentParser(prog="cacheplan", description=__doc__)
157
+ ap.add_argument("--version", action="version", version=__version__)
158
+ sub = ap.add_subparsers(dest="cmd", required=True)
159
+
160
+ def common(p, learn=True):
161
+ p.add_argument("logs", nargs="+", help="JSONL request log(s)")
162
+ p.add_argument("--min-tokens", type=int, default=1024,
163
+ help="minimum cacheable prompt length for your model (default 1024)")
164
+ if learn:
165
+ p.add_argument("--learn-from", metavar="LOG",
166
+ help="learn the plan from this other log (out-of-sample forecast)")
167
+
168
+ p = sub.add_parser("report", help="diagnosis, forecast and recommendation per application")
169
+ common(p)
170
+ p.add_argument("--json", action="store_true")
171
+ p.add_argument("--no-content", action="store_true", help="never print prompt text")
172
+ p.add_argument("--fail-on", metavar="RULES", help="comma-separated rule ids that make the exit status 1")
173
+ p.set_defaults(fn=cmd_report)
174
+
175
+ p = sub.add_parser("diagnose", help="where and why the reusable prefix breaks")
176
+ common(p, learn=False)
177
+ p.add_argument("-v", "--verbose", action="store_true", help="list every break")
178
+ p.add_argument("--no-content", action="store_true")
179
+ p.set_defaults(fn=cmd_diagnose)
180
+
181
+ p = sub.add_parser("verify", help="replay under the recommended options against the live API")
182
+ common(p)
183
+ p.add_argument("--model", required=True)
184
+ p.add_argument("--options", help="comma-separated option keys: " + ",".join(o for o in OPTIONS if o != "off"))
185
+ p.add_argument("--limit", type=int)
186
+ p.add_argument("--yes", action="store_true", help="actually send the requests")
187
+ p.add_argument("--out", help="write measured usage to this JSON file")
188
+ p.set_defaults(fn=cmd_verify)
189
+
190
+ p = sub.add_parser("gaps", help="how the forecast changes with longer pauses between requests")
191
+ common(p)
192
+ p.add_argument("--scales", default="1,2,5,10,20,50")
193
+ p.set_defaults(fn=cmd_gaps)
194
+
195
+ p = sub.add_parser("check", help="for pipelines: fail when too little of the prompt is reusable")
196
+ common(p)
197
+ p.add_argument("--min-reusable", type=float, default=0.5)
198
+ p.set_defaults(fn=cmd_check)
199
+
200
+ p = sub.add_parser("capture", help="logging proxy: record the requests your application sends")
201
+ p.add_argument("--out", required=True)
202
+ p.add_argument("--app", default="app", help="label for the application being captured")
203
+ p.add_argument("--port", type=int, default=8787)
204
+ p.add_argument("--upstream", default="https://api.anthropic.com")
205
+ p.set_defaults(fn=cmd_capture)
206
+
207
+ sub.add_parser("rules", help="list rule ids").set_defaults(fn=cmd_rules)
208
+ a = ap.parse_args(argv)
209
+ return a.fn(a)
210
+
211
+
212
+ if __name__ == "__main__":
213
+ raise SystemExit(main())
cacheplan/diagnose.py ADDED
@@ -0,0 +1,114 @@
1
+ """Where and why the reusable prefix breaks between requests.
2
+
3
+ Each request is compared with the earlier request of the same application that shares
4
+ the longest prefix with it. If that earlier request had content beyond the shared
5
+ prefix, the prefix broke there, and everything behind the break has to be paid for again.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections import defaultdict
11
+ from dataclasses import dataclass
12
+
13
+ from .messages import est_tokens, located_blocks, strip_cache_control
14
+
15
+ WINDOW = 20
16
+ _CAUSES = [
17
+ ("timestamp", re.compile(r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}")),
18
+ ("uuid", re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")),
19
+ ("date", re.compile(r"\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{2,4}")),
20
+ ("time of day", re.compile(r"\b\d{1,2}:\d{2}(:\d{2})?\b")),
21
+ ("random id", re.compile(r"\b[0-9a-f]{12,}\b|\b[A-Za-z0-9_-]{20,}\b")),
22
+ ("number", re.compile(r"\d+")),
23
+ ]
24
+
25
+
26
+ @dataclass
27
+ class Break:
28
+ app: str
29
+ request: int # position of the request within its application
30
+ path: str # e.g. system[0] or messages[8].content[0]
31
+ kind: str # changed | inserted | removed | tool order
32
+ lost_tokens: int # previously sent tokens behind the break
33
+ cause: str | None = None # for "changed": what the differing text looks like
34
+ offset: int = 0
35
+ was: str = ""
36
+ now: str = ""
37
+
38
+ @property
39
+ def where(self) -> str:
40
+ return re.sub(r"tools\[\d+\]", "tools", re.sub(r"messages\[\d+\]\.content\[\d+\]", "messages", self.path))
41
+
42
+
43
+ def _token_at(text: str, i: int) -> str:
44
+ a = i
45
+ while a > 0 and not text[a - 1].isspace() and text[a - 1] not in '"\\':
46
+ a -= 1
47
+ b = i
48
+ while b < len(text) and not text[b].isspace() and text[b] not in '"\\':
49
+ b += 1
50
+ return text[a:b]
51
+
52
+
53
+ def _classify(was: str, now: str, i: int) -> str | None:
54
+ a, b = _token_at(was, min(i, len(was) - 1)), _token_at(now, min(i, len(now) - 1))
55
+ for name, pat in _CAUSES:
56
+ if pat.search(a) and pat.search(b):
57
+ return name
58
+ return None
59
+
60
+
61
+ def _snip(text: str, i: int, width: int = 28) -> str:
62
+ return ("…" if i > width else "") + text[max(0, i - width):i + width // 2].replace("\n", " ")
63
+
64
+
65
+ def find_breaks(app: str, rows: list[dict]) -> list[Break]:
66
+ out, seen = [], []
67
+ for n, row in enumerate(rows):
68
+ cur = located_blocks(strip_cache_control(row["request"]))
69
+ texts = [t for _, t, _ in cur]
70
+ best, prev = -1, None
71
+ for cand in seen[-WINDOW:]:
72
+ k = 0
73
+ while k < min(len(cand), len(texts)) and cand[k] == texts[k]:
74
+ k += 1
75
+ if k >= best: # ties: the most recent one
76
+ best, prev = k, cand
77
+ seen.append(texts)
78
+ if prev is None or best >= len(prev): # first request, or a pure continuation
79
+ continue
80
+ lost = sum(est_tokens(t) for t in prev[best:])
81
+ if best >= len(texts):
82
+ out.append(Break(app, n, cur[-1][0] if cur else "request", "removed", lost))
83
+ continue
84
+ path, now_t = cur[best][0], texts[best]
85
+ was_t = prev[best]
86
+ if path == "messages[0].content[0]": # a different conversation, not a break
87
+ continue
88
+ if path.startswith("tools") and sorted(t for t in prev if t.startswith("tool:")) == \
89
+ sorted(t for t in texts if t.startswith("tool:")):
90
+ out.append(Break(app, n, path, "tool order", lost))
91
+ elif path.startswith("messages") and any(t in texts[best + off + 1:best + off + 14] # moved further down
92
+ for off, t in enumerate(prev[best:best + 4])):
93
+ out.append(Break(app, n, path, "inserted", lost))
94
+ elif now_t in prev[best + 1:best + 12]:
95
+ out.append(Break(app, n, path, "removed", lost))
96
+ else:
97
+ i = 0
98
+ while i < min(len(was_t), len(now_t)) and was_t[i] == now_t[i]:
99
+ i += 1
100
+ out.append(Break(app, n, path, "changed", lost, _classify(was_t, now_t, i), i,
101
+ _snip(was_t, i), _snip(now_t, i)))
102
+ return out
103
+
104
+
105
+ def summarise(breaks: list[Break]) -> list[dict]:
106
+ """Group breaks by where and why, most costly first."""
107
+ groups: dict[tuple, list[Break]] = defaultdict(list)
108
+ for b in breaks:
109
+ groups[(b.where, b.kind, b.cause)].append(b)
110
+ out = []
111
+ for (where, kind, cause), bs in groups.items():
112
+ out.append({"where": where, "kind": kind, "cause": cause, "count": len(bs),
113
+ "lost_tokens": sum(b.lost_tokens for b in bs), "example": bs[0]})
114
+ return sorted(out, key=lambda g: -g["lost_tokens"])
cacheplan/findings.py ADDED
@@ -0,0 +1,97 @@
1
+ """Findings with stable rule ids, each with a suggested fix."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+
6
+ from .diagnose import summarise
7
+ from .forecast import Knowledge, Verdict
8
+ from .messages import est_tokens, prefix_blocks, strip_cache_control
9
+
10
+ RULES = {
11
+ "CP001": "a value in the system prompt or tools changes between requests",
12
+ "CP002": "tool definitions are sent in a different order",
13
+ "CP003": "caching is not switched on",
14
+ "CP004": "prompts are shorter than the minimum cacheable length",
15
+ "CP005": "a per-tenant or per-user value sits before static content",
16
+ "CP006": "new content is inserted before content that was already sent",
17
+ "CP007": "previously sent message content changes between requests",
18
+ "CP008": "many pauses are longer than the 5-minute cache lifetime",
19
+ "CP009": "cache writes are rarely read back with the current settings",
20
+ }
21
+
22
+
23
+ @dataclass
24
+ class Finding:
25
+ rule: str
26
+ message: str
27
+ fix: str
28
+ tokens: int = 0 # estimated tokens re-sent because of it, over the log
29
+
30
+ def __str__(self) -> str:
31
+ cost = f" (~{self.tokens:,} tokens re-sent in this log)" if self.tokens else ""
32
+ return f"{self.rule} {self.message}{cost}\n fix: {self.fix}"
33
+
34
+
35
+ def findings(v: Verdict, rows: list[dict], k: Knowledge, min_tokens: int = 1024,
36
+ show_content: bool = True) -> list[Finding]:
37
+ out: list[Finding] = []
38
+ groups = summarise(v.breaks)
39
+ tpl = k.templates.get(v.app)
40
+ head_lost = sum(g["lost_tokens"] for g in groups if g["where"].startswith(("system", "tools")))
41
+ slots = tpl.slots() if tpl else []
42
+ for s in slots:
43
+ ex = f' (e.g. "{s.example.replace(chr(10), " ")[:40]}")' if show_content else ""
44
+ if s.kind == "volatile":
45
+ out.append(Finding("CP001", f"system value <<{s.name}>> changes between requests{ex}; "
46
+ "everything after it, including the conversation history, cannot be reused",
47
+ "move it to the latest user message, or make it change rarely "
48
+ "(a date instead of a timestamp)", head_lost))
49
+ head_lost = 0 # count the loss once
50
+ elif s.distinct > 1:
51
+ out.append(Finding("CP005", f"system value <<{s.name}>> has {s.distinct} values{ex} and sits "
52
+ "before static content", "move it behind the static instructions"))
53
+ for g in groups:
54
+ if g["lost_tokens"] < 0.01 * v.tokens: # too small to matter
55
+ continue
56
+ b = g["example"]
57
+ detail = f': "{b.was}" became "{b.now}"' if show_content and b.was else ""
58
+ if g["kind"] == "tool order":
59
+ out.append(Finding("CP002", f"tool order differs in {g['count']} requests",
60
+ "build the tool list in a fixed order, for example sorted by name",
61
+ g["lost_tokens"]))
62
+ elif g["kind"] == "changed" and g["where"].startswith(("system", "tools")) and not slots:
63
+ what = f"a {g['cause']}" if g["cause"] else "text"
64
+ out.append(Finding("CP001", f"{what} in {g['where']} changes between requests "
65
+ f"({g['count']} times){detail}",
66
+ "move the changing value to the latest user message, or make it change rarely",
67
+ g["lost_tokens"]))
68
+ elif g["kind"] == "inserted":
69
+ out.append(Finding("CP006", f"new content is inserted before previously sent content "
70
+ f"({g['count']} times, first at {b.path})",
71
+ "use the planned breakpoints above, which sit just before the insertion "
72
+ "point, or append new turns at the end", g["lost_tokens"]))
73
+ elif g["kind"] == "changed" and g["where"] == "messages":
74
+ what = f"a {g['cause']}" if g["cause"] else "content"
75
+ out.append(Finding("CP007", f"{what} in an earlier message changes between requests "
76
+ f"({g['count']} times, first at {b.path}){detail}",
77
+ "keep earlier messages byte-identical; send changing material "
78
+ "(file contents, retrieved documents) as late as possible", g["lost_tokens"]))
79
+ if (v.recommended != "off" or v.fix_option) and \
80
+ not any(any(ttl for _, ttl in prefix_blocks(r["request"])) for r in rows):
81
+ out.append(Finding("CP003", "no request sets cache_control, so nothing is cached",
82
+ "see the recommendation above before switching it on"))
83
+ sizes = sorted(sum(est_tokens(t) for t, _ in prefix_blocks(strip_cache_control(r["request"]))) for r in rows)
84
+ if sizes[len(sizes) // 2] < min_tokens:
85
+ out.append(Finding("CP004", f"the typical prompt is ~{sizes[len(sizes) // 2]:,} tokens; the minimum "
86
+ f"cacheable length is set to {min_tokens:,}",
87
+ "nothing to do: prompts this short are not cached"))
88
+ if v.gaps_over_5m >= 0.2:
89
+ out.append(Finding("CP008", f"{v.gaps_over_5m:.0%} of pauses between requests exceed 5 minutes",
90
+ "compare the 1-hour rows in the forecast"))
91
+ if "logged" in v.usage:
92
+ u = v.usage["logged"]
93
+ if u.cache_creation_input_tokens and u.cache_read_input_tokens < 0.5 * u.cache_creation_input_tokens:
94
+ out.append(Finding("CP009", f"current settings write ~{u.cache_creation_input_tokens:,} tokens "
95
+ f"to the cache and read back ~{u.cache_read_input_tokens:,}",
96
+ "follow the recommendation above"))
97
+ return out
cacheplan/forecast.py ADDED
@@ -0,0 +1,175 @@
1
+ """Forecast what each caching option would cost on a logged workload, and recommend one."""
2
+ from __future__ import annotations
3
+
4
+ import statistics
5
+ from collections import defaultdict
6
+ from dataclasses import dataclass, field
7
+
8
+ from .diagnose import Break, find_breaks, summarise
9
+ from .logs import by_app, conversation_key
10
+ from .messages import (FIVE_MIN, ONE_HOUR, BreakPlan, Template, canonicalize_request, cc,
11
+ est_tokens, learn, learn_breakpoints, place_breakpoints, prefix_blocks,
12
+ strip_cache_control, system_text)
13
+ from .sim import CacheSim, Usage
14
+
15
+ OPTIONS = { # key -> (label, changes the prompt text)
16
+ "off": ("Caching off", False),
17
+ "auto_5m": ("Automatic caching, 5-minute", False),
18
+ "auto_1h": ("Automatic caching, 1-hour", False),
19
+ "plan_5m": ("Planned breakpoints, 5-minute", False),
20
+ "plan_1h": ("Planned breakpoints, 1-hour", False),
21
+ "fix_5m": ("Prompt fix + breakpoints, 5-minute", True),
22
+ "fix_1h": ("Prompt fix + breakpoints, 1-hour", True),
23
+ "logged": ("As logged (current settings)", False),
24
+ }
25
+ SIMPLICITY = ["off", "auto_5m", "auto_1h", "plan_5m", "plan_1h"]
26
+
27
+
28
+ @dataclass
29
+ class Knowledge:
30
+ """What was learned from a log: one prompt template and one breakpoint plan per application."""
31
+ templates: dict[str, Template | None] = field(default_factory=dict)
32
+ plans: dict[str, BreakPlan] = field(default_factory=dict)
33
+
34
+
35
+ def learn_from(rows: list[dict]) -> Knowledge:
36
+ k = Knowledge()
37
+ for app, rs in by_app(rows).items():
38
+ k.templates[app] = learn([system_text(r["request"]) for r in rs], [conversation_key(r) for r in rs])
39
+ k.plans[app] = learn_breakpoints([r["request"] for r in rs])
40
+ return k
41
+
42
+
43
+ def build(option: str, row: dict, k: Knowledge) -> dict:
44
+ """The request as it would be sent under one option."""
45
+ req, app = row["request"], row["app"]
46
+ ttl = ONE_HOUR if option.endswith("_1h") else FIVE_MIN
47
+ if option == "logged":
48
+ return {f: req[f] for f in ("tools", "system", "messages", "cache_control") if req.get(f)}
49
+ if option == "off":
50
+ return strip_cache_control(req)
51
+ if option.startswith("auto"):
52
+ return dict(strip_cache_control(req), cache_control=cc(ttl))
53
+ plan = k.plans.get(app) or BreakPlan(head=False, offsets=())
54
+ if option.startswith("plan"):
55
+ return place_breakpoints(req, plan=plan, ttl=ttl)
56
+ return canonicalize_request(req, k.templates.get(app), plan, ttl=ttl)
57
+
58
+
59
+ def has_fix(rows: list[dict], k: Knowledge) -> bool:
60
+ tpl = k.templates.get(rows[0]["app"])
61
+ return bool(tpl and any(s.kind == "volatile" or s.distinct > 1 for s in tpl.slots()))
62
+
63
+
64
+ def simulate(rows: list[dict], k: Knowledge, options: list[str], min_tokens: int = 1024) -> dict:
65
+ """{app: {option: Usage}} from the local cache model."""
66
+ out: dict[str, dict[str, Usage]] = defaultdict(dict)
67
+ for opt in options:
68
+ sim = CacheSim(min_tokens)
69
+ for row in rows:
70
+ out[row["app"]].setdefault(opt, Usage()).add(sim.request(build(opt, row, k), row["ts"]))
71
+ return dict(out)
72
+
73
+
74
+ def reusable_share(rows: list[dict], ttl: float = FIVE_MIN) -> float:
75
+ """Share of input tokens that repeat an earlier request's prefix within the lifetime:
76
+ the most that caching could read from these prompts exactly as written."""
77
+ seen, reuse, total = [], 0, 0
78
+ for r in rows:
79
+ blocks = [t for t, _ in prefix_blocks(strip_cache_control(r["request"]))]
80
+ best = 0
81
+ for ts, prev in seen[-40:]:
82
+ if r["ts"] - ts > ttl:
83
+ continue
84
+ n = 0
85
+ while n < min(len(prev), len(blocks)) and prev[n] == blocks[n]:
86
+ n += 1
87
+ best = max(best, sum(est_tokens(b) for b in blocks[:n]))
88
+ reuse += best
89
+ total += sum(est_tokens(b) for b in blocks)
90
+ seen.append((r["ts"], blocks))
91
+ return reuse / total if total else 0.0
92
+
93
+
94
+ @dataclass
95
+ class Verdict:
96
+ app: str
97
+ requests: int
98
+ tokens: int
99
+ layout: str
100
+ reusable: float
101
+ median_gap: float
102
+ gaps_over_5m: float
103
+ usage: dict[str, Usage]
104
+ recommended: str
105
+ reason: str
106
+ fix_option: str | None # best option that changes the prompt, if clearly better
107
+ plan: BreakPlan
108
+ breaks: list[Break]
109
+ in_sample: bool = True
110
+
111
+ def cost(self, opt: str) -> float:
112
+ return self.usage[opt].cost_units() / max(1, self.usage["off"].total)
113
+
114
+ def read(self, opt: str) -> float:
115
+ u = self.usage[opt]
116
+ return u.cache_read_input_tokens / max(1, u.total)
117
+
118
+
119
+ def _recommend(cost: dict[str, float]) -> tuple[str, str]:
120
+ plain = [o for o in SIMPLICITY if o in cost]
121
+ best = min(plain, key=lambda o: cost[o])
122
+ if "logged" in cost and cost["logged"] < 0.97 and cost["logged"] <= cost[best] + 0.02:
123
+ return "logged", "your current settings are within 2 points of the best option"
124
+ if cost[best] >= 0.97:
125
+ return "off", "no option saves at least 3%, and cache writes cost extra"
126
+ pick = next(o for o in plain if cost[o] <= cost[best] + 0.02) # simplest within 2 points
127
+ if pick == best:
128
+ return pick, "lowest forecast cost"
129
+ return pick, f"within 2 points of the best option and simpler to set up"
130
+
131
+
132
+ def _layout(reusable: float, cost: dict[str, float], breaks: list[Break], fixable: bool) -> str:
133
+ head = [b for b in breaks if b.path.startswith(("system", "tools"))]
134
+ if breaks and len(head) * 2 >= len(breaks) and (fixable or reusable < 0.15):
135
+ return "changing content at the top of the prompt"
136
+ if reusable < 0.15:
137
+ return "little repeats between requests"
138
+ if cost["auto_5m"] <= cost["plan_5m"] + 0.03 and cost["auto_5m"] < 0.97:
139
+ return "append-only conversation"
140
+ if any(b.kind == "inserted" for b in breaks) or cost["plan_5m"] < cost["auto_5m"] - 0.03:
141
+ return "content inserted or changed mid-prompt"
142
+ return "mixed"
143
+
144
+
145
+ def examine(rows: list[dict], k: Knowledge | None = None, min_tokens: int = 1024) -> list[Verdict]:
146
+ """One verdict per application. If k is None the plan is learned from the same rows."""
147
+ in_sample = k is None
148
+ k = k or learn_from(rows)
149
+ apps = by_app(rows)
150
+ options = [o for o in OPTIONS if o != "logged"]
151
+ if any(any(ttl for _, ttl in prefix_blocks(r["request"])) for r in rows):
152
+ options.append("logged")
153
+ usage = simulate(rows, k, options, min_tokens)
154
+ out = []
155
+ for app, rs in apps.items():
156
+ u = dict(usage[app])
157
+ fixable = has_fix(rs, k)
158
+ if not fixable:
159
+ u.pop("fix_5m", None), u.pop("fix_1h", None)
160
+ base = max(1, u["off"].total)
161
+ cost = {o: x.cost_units() / base for o, x in u.items()}
162
+ pick, reason = _recommend(cost)
163
+ fix = None
164
+ if fixable:
165
+ best_fix = min(("fix_5m", "fix_1h"), key=lambda o: cost[o])
166
+ if cost[best_fix] < cost[pick] - 0.05:
167
+ fix = best_fix
168
+ gaps = [b["ts"] - a["ts"] for a, b in zip(rs, rs[1:])]
169
+ breaks = find_breaks(app, rs)
170
+ out.append(Verdict(app, len(rs), u["off"].total, _layout(reusable_share(rs), cost, breaks, fixable),
171
+ reusable_share(rs), statistics.median(gaps) if gaps else 0.0,
172
+ sum(g > FIVE_MIN for g in gaps) / len(gaps) if gaps else 0.0,
173
+ u, pick, reason, fix, k.plans.get(app) or BreakPlan(head=False, offsets=()),
174
+ breaks, in_sample))
175
+ return sorted(out, key=lambda v: -v.tokens)