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/live.py ADDED
@@ -0,0 +1,73 @@
1
+ """Verify a forecast against the real API: replay the logged requests under each option
2
+ with max_tokens=1 and read the provider's own cache counters."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import time
8
+ import urllib.error
9
+ import urllib.request
10
+ import uuid
11
+ from collections import defaultdict
12
+
13
+ from .forecast import Knowledge, build
14
+ from .sim import Usage
15
+
16
+ API_URL = "https://api.anthropic.com/v1/messages"
17
+
18
+
19
+ def isolate(req: dict, nonce: str) -> dict:
20
+ """Make this run's prefixes unique so options cannot read each other's cache."""
21
+ tag = f"[run {nonce}]"
22
+ for t in req.get("tools") or []:
23
+ t["description"] = (t.get("description", "") + " " + tag).strip()
24
+ s = req.get("system")
25
+ if isinstance(s, str):
26
+ req["system"] = tag + "\n" + s
27
+ elif s:
28
+ s[0] = dict(s[0], text=tag + "\n" + s[0].get("text", ""))
29
+ else:
30
+ req["system"] = tag
31
+ return req
32
+
33
+
34
+ def _post(body: dict, key: str, url: str) -> dict:
35
+ data = json.dumps(body).encode()
36
+ for attempt in range(6):
37
+ rq = urllib.request.Request(url, data=data, headers={
38
+ "x-api-key": key, "anthropic-version": "2023-06-01", "content-type": "application/json"})
39
+ try:
40
+ with urllib.request.urlopen(rq, timeout=120) as resp:
41
+ return json.loads(resp.read())
42
+ except urllib.error.HTTPError as e:
43
+ if e.code in (429, 500, 529) and attempt < 5:
44
+ time.sleep(2 ** attempt)
45
+ continue
46
+ raise SystemExit(f"API error {e.code}: {e.read().decode()[:400]}")
47
+ raise SystemExit("gave up after retries")
48
+
49
+
50
+ def run(rows: list[dict], k: Knowledge, options: list[str], model: str, progress=print,
51
+ url: str = API_URL) -> dict:
52
+ """{app: {option: Usage}} measured live. 'off' is computed from the first option's totals."""
53
+ key = os.environ.get("ANTHROPIC_API_KEY")
54
+ if not key:
55
+ raise SystemExit("ANTHROPIC_API_KEY is not set in this shell.")
56
+ out: dict[str, dict[str, Usage]] = defaultdict(dict)
57
+ for opt in [o for o in options if o != "off"]:
58
+ nonce = uuid.uuid4().hex[:10]
59
+ for i, row in enumerate(rows, 1):
60
+ body = isolate(json.loads(json.dumps(build(opt, row, k))), nonce)
61
+ body.update(model=model, max_tokens=1)
62
+ u = _post(body, key, url).get("usage", {})
63
+ creation = u.get("cache_creation_input_tokens") or 0
64
+ one_hour = (u.get("cache_creation") or {}).get("ephemeral_1h_input_tokens")
65
+ if one_hour is None:
66
+ one_hour = creation if opt.endswith("_1h") else 0
67
+ out[row["app"]].setdefault(opt, Usage()).add(
68
+ Usage(u.get("input_tokens", 0), creation, u.get("cache_read_input_tokens") or 0, one_hour))
69
+ if i % 25 == 0:
70
+ progress(f" {opt}: {i}/{len(rows)}")
71
+ for app, per in out.items():
72
+ per["off"] = Usage(input_tokens=next(iter(per.values())).total)
73
+ return dict(out)
cacheplan/logs.py ADDED
@@ -0,0 +1,100 @@
1
+ """Read request logs.
2
+
3
+ Accepted line formats (JSONL, one request per line, formats may be mixed):
4
+ cacheplan capture {"ts": ..., "app": ..., "request": {tools, system, messages}}
5
+ raw request body {"model": ..., "system": ..., "messages": [...]}
6
+ promptcachelint trace {"provider": "anthropic", "body": {...}, "at": ..., "usage": {...}}
7
+
8
+ Only Anthropic Messages API requests are analysed in this release; other lines are
9
+ counted and skipped.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from collections import defaultdict
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+
18
+ from .messages import system_text
19
+
20
+
21
+ @dataclass
22
+ class Log:
23
+ rows: list[dict] = field(default_factory=list)
24
+ skipped: dict[str, int] = field(default_factory=dict)
25
+
26
+
27
+ def _row(d: dict, default_app: str, n: int) -> dict | str:
28
+ if not isinstance(d, dict):
29
+ return "not a JSON object"
30
+ usage = None
31
+ if isinstance(d.get("request"), dict):
32
+ req, ts, app, session = d["request"], d.get("ts"), d.get("app"), d.get("session")
33
+ elif isinstance(d.get("body"), dict): # promptcachelint trace
34
+ if d.get("provider") not in (None, "anthropic"):
35
+ return f"provider {d.get('provider')} not supported yet"
36
+ req, ts, app, session, usage = d["body"], d.get("at"), None, d.get("session_id"), d.get("usage")
37
+ elif "messages" in d:
38
+ req, ts, app, session = d, None, None, None
39
+ else:
40
+ return "no request found"
41
+ if not isinstance(req.get("messages"), list) or "input" in req:
42
+ return "not an Anthropic Messages request"
43
+ return {"ts": float(ts) if ts else float(n), "app": app or default_app, "session": session,
44
+ "request": req, "usage": usage}
45
+
46
+
47
+ def _lines(text: str) -> set[str]:
48
+ return {l for l in text.split("\n") if len(l.strip()) >= 12}
49
+
50
+
51
+ def load(paths) -> Log:
52
+ """Load one or more logs. Requests under one app label are split further when their
53
+ system prompts are different prompts altogether (an agent's main prompt and its
54
+ commit-message prompt, say), so that each group is one prompt template."""
55
+ log, skipped = Log(), defaultdict(int)
56
+ for src, path in enumerate([paths] if isinstance(paths, (str, Path)) else list(paths)):
57
+ p = Path(path)
58
+ for n, line in enumerate(p.read_text(encoding="utf-8").splitlines()):
59
+ if not line.strip():
60
+ continue
61
+ try:
62
+ row = _row(json.loads(line), p.stem, n)
63
+ except json.JSONDecodeError:
64
+ row = "invalid JSON"
65
+ if isinstance(row, str):
66
+ skipped[row] += 1
67
+ continue
68
+ row["_src"] = src
69
+ log.rows.append(row)
70
+ log.rows.sort(key=lambda r: (r["_src"], r["ts"]))
71
+ clusters: dict[str, list[set]] = defaultdict(list)
72
+ for r in log.rows:
73
+ ls = _lines(system_text(r["request"]))
74
+ reps = clusters[r["app"]]
75
+ for k, rep in enumerate(reps):
76
+ if (not ls and not rep) or len(ls & rep) >= 0.5 * max(len(ls), len(rep), 1):
77
+ break
78
+ else:
79
+ reps.append(ls)
80
+ k = len(reps) - 1
81
+ r["_cluster"] = k
82
+ for r in log.rows:
83
+ k = r.pop("_cluster")
84
+ if len(clusters[r["app"]]) > 1:
85
+ first = system_text(r["request"]).strip().split("\n")[0][:40]
86
+ r["app"] = f'{r["app"]}#{k + 1} "{first}"'
87
+ log.skipped = dict(skipped)
88
+ return log
89
+
90
+
91
+ def by_app(rows: list[dict]) -> dict[str, list[dict]]:
92
+ out: dict[str, list[dict]] = defaultdict(list)
93
+ for r in rows:
94
+ out[r["app"]].append(r)
95
+ return dict(out)
96
+
97
+
98
+ def conversation_key(row: dict) -> str:
99
+ msgs = row["request"].get("messages") or [{}]
100
+ return row.get("session") or json.dumps(msgs[0], sort_keys=True)
cacheplan/messages.py ADDED
@@ -0,0 +1,428 @@
1
+ """Core operations on Anthropic Messages API requests ({tools, system, messages}).
2
+
3
+ learn() infer, from a sample of requests produced by one app, which
4
+ parts of the system prompt are static, shared by a few
5
+ callers (tenant-like) or volatile. No annotations needed.
6
+ canonicalize_request() rewrite a request so stable content forms the prefix,
7
+ inside the order the API fixes (tools -> system -> messages),
8
+ and place up to four cache breakpoints.
9
+ prefix_blocks() the request as the ordered list of cacheable blocks.
10
+
11
+ Nothing is dropped: every value removed from the system prompt reappears either in
12
+ a trailing system block (shared values) or in a <request_context> block at the end
13
+ of the latest user message (volatile values).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import copy
18
+ import json
19
+ import re
20
+ from dataclasses import dataclass, field
21
+ from difflib import SequenceMatcher
22
+
23
+ EPHEMERAL = {"type": "ephemeral"}
24
+ FIVE_MIN, ONE_HOUR = 300, 3600
25
+ CHARS_PER_TOKEN = 3.0 # rough; three live runs measured 2.6 to 3.2 characters per token
26
+
27
+
28
+ def cc(ttl: int = FIVE_MIN) -> dict:
29
+ """A cache_control marker for the 5-minute or the 1-hour lifetime."""
30
+ return {"type": "ephemeral", "ttl": "1h"} if ttl >= ONE_HOUR else {"type": "ephemeral"}
31
+
32
+
33
+ def _ttl(holder: dict) -> int:
34
+ c = holder.get("cache_control")
35
+ if not c:
36
+ return 0
37
+ return ONE_HOUR if isinstance(c, dict) and c.get("ttl") == "1h" else FIVE_MIN
38
+ SLOT_NOTE = ("Values written as <<name>> are given under [name], either in the next "
39
+ "system block or in <request_context> in the latest user message.")
40
+
41
+
42
+ def est_tokens(s: str) -> int:
43
+ """Rough token estimate. Live verification uses the provider's real counts."""
44
+ return max(1, int(len(s) / CHARS_PER_TOKEN))
45
+
46
+
47
+ def system_text(req: dict) -> str:
48
+ s = req.get("system") or ""
49
+ if isinstance(s, str):
50
+ return s
51
+ return "\n".join(b.get("text", "") for b in s if b.get("type") == "text")
52
+
53
+
54
+ def _blocks(content) -> list[dict]:
55
+ return [{"type": "text", "text": content}] if isinstance(content, str) else list(content)
56
+
57
+
58
+ def _strip(o):
59
+ if isinstance(o, dict):
60
+ return {k: _strip(v) for k, v in o.items() if k != "cache_control"}
61
+ if isinstance(o, list):
62
+ return [_strip(v) for v in o]
63
+ return o
64
+
65
+
66
+ def strip_cache_control(req: dict) -> dict:
67
+ return _strip({k: req[k] for k in ("tools", "system", "messages") if req.get(k)})
68
+
69
+
70
+ def prefix_blocks(req: dict) -> list[tuple[str, int]]:
71
+ """(serialised block, lifetime of its breakpoint in seconds or 0) in hashing order."""
72
+ return [(text, ttl) for _, text, ttl in located_blocks(req)]
73
+
74
+
75
+ def located_blocks(req: dict) -> list[tuple[str, str, int]]:
76
+ """(path, serialised block, breakpoint lifetime) in the order the API hashes them:
77
+ tools, then system, then messages."""
78
+ out: list[tuple[str, str, int]] = []
79
+ for i, t in enumerate(req.get("tools") or []):
80
+ out.append((f"tools[{i}]", "tool:" + json.dumps(_strip(t), sort_keys=True), _ttl(t)))
81
+ s = req.get("system")
82
+ for i, b in enumerate(_blocks(s) if s else []):
83
+ out.append((f"system[{i}]", "system:" + json.dumps(_strip(b), sort_keys=True), _ttl(b)))
84
+ for i, m in enumerate(req.get("messages") or []):
85
+ for j, b in enumerate(_blocks(m["content"])):
86
+ out.append((f"messages[{i}].content[{j}]",
87
+ m["role"] + ":" + json.dumps(_strip(b), sort_keys=True), _ttl(b)))
88
+ if req.get("cache_control") and out: # top-level field = automatic caching
89
+ p, t, _ = out[-1]
90
+ out[-1] = (p, t, _ttl(req))
91
+ return out
92
+
93
+
94
+ # --------------------------------------------------------------------------- learning
95
+ @dataclass
96
+ class Slot:
97
+ name: str
98
+ kind: str # "shared" (few distinct values) or "volatile"
99
+ distinct: int = 0
100
+ example: str = ""
101
+
102
+
103
+ @dataclass
104
+ class Line:
105
+ const: str | None = None # identical in every sample
106
+ pattern: re.Pattern | None = None # a line with varying words
107
+ fmt: str = "" # that line with <<name>> placeholders
108
+ subslots: list[Slot] = field(default_factory=list)
109
+
110
+
111
+ @dataclass
112
+ class Gap:
113
+ const: list[str] | None = None # identical in every sample
114
+ slot: Slot | None = None # the whole gap varies (different line counts)
115
+ lines: list[Line] | None = None # same number of lines everywhere: line by line
116
+
117
+ def slots(self) -> list[Slot]:
118
+ if self.slot:
119
+ return [self.slot]
120
+ return [s for l in (self.lines or []) for s in l.subslots]
121
+
122
+
123
+ @dataclass
124
+ class Template:
125
+ anchors: list[str]
126
+ gaps: list[Gap]
127
+ samples: int
128
+
129
+ def slots(self) -> list[Slot]:
130
+ return [s for g in self.gaps for s in g.slots()]
131
+
132
+
133
+ def _split(text: str, anchors: list[str]) -> list[list[str]] | None:
134
+ lines, gaps, pos = text.split("\n"), [], 0
135
+ for a in anchors:
136
+ try:
137
+ i = lines.index(a, pos)
138
+ except ValueError:
139
+ return None
140
+ gaps.append(lines[pos:i])
141
+ pos = i + 1
142
+ gaps.append(lines[pos:])
143
+ return gaps
144
+
145
+
146
+ def _slug(words: str, used: set[str]) -> str:
147
+ base = "_".join(re.findall(r"[a-z0-9]+", words.lower())[-3:]) or "value"
148
+ name, n = base, 2
149
+ while name in used:
150
+ name, n = f"{base}_{n}", n + 1
151
+ used.add(name)
152
+ return name
153
+
154
+
155
+ def _kind(values: list[str]) -> tuple[str, int]:
156
+ d = len(set(values))
157
+ return ("shared" if d <= max(1, len(values) // 4) else "volatile"), d
158
+
159
+
160
+ def _line(lines: list[str], used: set[str]) -> Line | None:
161
+ """All samples have exactly one line here: find the words that vary."""
162
+ ref = lines[0].split(" ")
163
+ stable = set(range(len(ref)))
164
+ for other in lines[1:]:
165
+ sm = SequenceMatcher(None, ref, other.split(" "), autojunk=False)
166
+ stable &= {i for b in sm.get_matching_blocks() for i in range(b.a, b.a + b.size)}
167
+ parts: list[tuple[str, str]] = [] # ("lit", text) | ("slot", "")
168
+ for i, w in enumerate(ref):
169
+ k = "lit" if i in stable else "slot"
170
+ if parts and parts[-1][0] == k:
171
+ if k == "lit":
172
+ parts[-1] = ("lit", parts[-1][1] + " " + w)
173
+ else:
174
+ parts.append((k, w if k == "lit" else ""))
175
+ if not any(k == "slot" for k, _ in parts) or len(stable) * 2 < len(ref):
176
+ return None # nothing varies, or too little is fixed to call it a form
177
+ pat = re.compile(" ".join(re.escape(t) if k == "lit" else "(.+?)" for k, t in parts), re.S)
178
+ found = [pat.fullmatch(l) for l in lines]
179
+ if not all(found):
180
+ return None
181
+ subs, fmt, prev, gi = [], [], "", 0
182
+ for k, t in parts:
183
+ if k == "lit":
184
+ fmt.append(t)
185
+ prev = t
186
+ else:
187
+ vals = [m.group(gi + 1) for m in found]
188
+ kind, d = _kind(vals)
189
+ s = Slot(_slug(prev, used), kind, d, vals[0])
190
+ subs.append(s)
191
+ fmt.append(f"<<{s.name}>>")
192
+ gi += 1
193
+ return Line(pattern=pat, fmt=" ".join(fmt), subslots=subs)
194
+
195
+
196
+ def _block_name(first_lines: list[str], anchor: str) -> str:
197
+ words = [l.split(" ") for l in first_lines]
198
+ n = 0
199
+ while all(len(w) > n and w[n] == words[0][n] for w in words):
200
+ n += 1
201
+ if n >= 2:
202
+ return " ".join(words[0][:n])
203
+ return anchor if anchor.rstrip().endswith(":") else "block"
204
+
205
+
206
+ def learn(texts: list[str], keys: list | None = None, max_samples: int = 40) -> Template | None:
207
+ """Infer the template behind a set of system prompts from one application.
208
+
209
+ keys, if given, identify the conversation each text belongs to. A value is
210
+ treated as shared (cacheable per tenant or user) only if it has few distinct
211
+ values and never changes inside one conversation; otherwise it is volatile.
212
+ """
213
+ all_texts = texts
214
+ texts = [t for t in texts if t]
215
+ if len(texts) < 4:
216
+ return None
217
+ step = max(1, len(texts) // max_samples)
218
+ samples = texts[::step][:max_samples]
219
+ ref = samples[0].split("\n")
220
+ cand = {i for i, l in enumerate(ref) if len(l.strip()) >= 12}
221
+ for s in samples[1:]:
222
+ sm = SequenceMatcher(None, ref, s.split("\n"), autojunk=False)
223
+ cand &= {i for b in sm.get_matching_blocks() for i in range(b.a, b.a + b.size)}
224
+ anchors = [ref[i] for i in sorted(cand)]
225
+ splits = [g for g in (_split(s, anchors) for s in samples) if g is not None]
226
+ if len(splits) < 4:
227
+ return None
228
+ used: set[str] = set()
229
+ gaps: list[Gap] = []
230
+ for k in range(len(anchors) + 1):
231
+ vals = [sp[k] for sp in splits]
232
+ if all(v == vals[0] for v in vals):
233
+ gaps.append(Gap(const=vals[0]))
234
+ continue
235
+ g = None
236
+ varying = sum(1 for j in range(len(vals[0])) if any(len(v) > j and v[j] != vals[0][j] for v in vals))
237
+ if all(len(v) == len(vals[0]) for v in vals) and varying <= 2: # form-like lines
238
+ ls = []
239
+ for j in range(len(vals[0])):
240
+ col = [v[j] for v in vals]
241
+ ls.append(Line(const=col[0]) if all(x == col[0] for x in col) else _line(col, used))
242
+ if all(ls):
243
+ g = Gap(lines=ls)
244
+ if g is None:
245
+ joined = ["\n".join(v).strip("\n") for v in vals]
246
+ kind, d = _kind(joined)
247
+ name = _block_name([j.split("\n")[0] for j in joined], anchors[k - 1] if k else "block")
248
+ g = Gap(slot=Slot(_slug(name, used), kind, d, joined[0]))
249
+ gaps.append(g)
250
+ tpl = Template(anchors, gaps, len(splits))
251
+ if keys: # demote values that change inside a conversation
252
+ seen: dict = {}
253
+ by_name = {sl.name: sl for sl in tpl.slots()}
254
+ for text, key in zip(all_texts, keys):
255
+ got = apply_template(tpl, text) if text else None
256
+ for name, value in (got[1] if got else []):
257
+ if seen.setdefault((key, name), value) != value:
258
+ by_name[name].kind = "volatile"
259
+ return tpl
260
+
261
+
262
+ def apply_template(tpl: Template, text: str):
263
+ """-> (static text with placeholders, shared [(name, value)], volatile [...]) or None."""
264
+ split = _split(text, tpl.anchors)
265
+ if split is None:
266
+ return None
267
+ lines: list[str] = []
268
+ shared, volatile = [], []
269
+
270
+ def put(slot: Slot, value: str):
271
+ if value.strip():
272
+ (shared if slot.kind == "shared" else volatile).append((slot.name, value))
273
+
274
+ for k, g in enumerate(tpl.gaps):
275
+ cur = split[k]
276
+ if g.const is not None:
277
+ if cur != g.const:
278
+ return None
279
+ lines += cur
280
+ elif g.slot:
281
+ put(g.slot, "\n".join(cur).strip("\n"))
282
+ body = [i for i, l in enumerate(cur) if l.strip()]
283
+ lead, trail = (body[0], len(cur) - 1 - body[-1]) if body else (0, 0)
284
+ lines += [""] * lead + [f"<<{g.slot.name}>>"] + [""] * trail
285
+ else:
286
+ if len(cur) != len(g.lines):
287
+ return None
288
+ for spec, line in zip(g.lines, cur):
289
+ if spec.const is not None:
290
+ if line != spec.const:
291
+ return None
292
+ lines.append(line)
293
+ continue
294
+ m = spec.pattern.fullmatch(line)
295
+ if not m:
296
+ return None
297
+ for s, v in zip(spec.subslots, m.groups()):
298
+ put(s, v)
299
+ lines.append(spec.fmt)
300
+ if k < len(tpl.anchors):
301
+ lines.append(tpl.anchors[k])
302
+ return "\n".join(lines), shared, volatile
303
+
304
+
305
+ # --------------------------------------------------------------------------- rewriting
306
+ def _fmt(pairs) -> str:
307
+ return "\n\n".join(f"[{n}]\n{v}" for n, v in pairs)
308
+
309
+
310
+ def _msg_blocks(req: dict) -> list[str]:
311
+ return [m["role"] + ":" + json.dumps(_strip(b), sort_keys=True)
312
+ for m in req.get("messages") or [] for b in _blocks(m["content"])]
313
+
314
+
315
+ @dataclass
316
+ class BreakPlan:
317
+ """Where logged traffic showed a prefix being reused often enough to pay for the write.
318
+ head cache the tools + system blocks
319
+ const_prefix leading message blocks that later requests kept matching (examples etc.)
320
+ offsets distances from the last block where a later request still matched"""
321
+ head: bool = True
322
+ const_prefix: int = 0
323
+ offsets: tuple = (0,)
324
+ reuse: dict = field(default_factory=dict) # position -> share of writes later read
325
+
326
+
327
+ def learn_breakpoints(reqs: list[dict], window: int = 20,
328
+ write_x: float = 1.25, read_x: float = 0.10) -> BreakPlan:
329
+ """Cost-aware breakpoint plan for one application, learned from its log.
330
+
331
+ For every request, find how far a later request (within the next `window`) repeated
332
+ its prefix. A breakpoint is kept only where the share of writes that were later read
333
+ exceeds the break-even point (write premium / read saving: 28% at the default prices),
334
+ because everything up to the last breakpoint is paid for at the write price."""
335
+ from collections import Counter
336
+ need = (write_x - 1) / (1 - read_x)
337
+ seqs, heads = [], []
338
+ for r in reqs:
339
+ bl = [t for t, _ in prefix_blocks(strip_cache_control(r))]
340
+ seqs.append(bl)
341
+ heads.append(sum(1 for t in bl if t.startswith(("tool:", "system:"))))
342
+ future = [] # blocks of request i repeated by a later one
343
+ for i, cur in enumerate(seqs[:-1]):
344
+ best = 0
345
+ for nxt in seqs[i + 1:i + 1 + window]:
346
+ n = 0
347
+ while n < min(len(cur), len(nxt)) and cur[n] == nxt[n]:
348
+ n += 1
349
+ best = max(best, n)
350
+ future.append(best)
351
+ if not future:
352
+ return BreakPlan(head=False, offsets=()) # a single request: nothing to reuse
353
+ k = len(future)
354
+ share = lambda hits: sum(hits) / k
355
+ p_head = share(f >= h > 0 for f, h in zip(future, heads))
356
+ beyond = [f - h for f, h in zip(future, heads) if f > h]
357
+ const = min(beyond) if len(beyond) >= 0.5 * k else 0
358
+ cand = Counter(len(seqs[i]) - f for i, f in enumerate(future) if f > heads[i])
359
+ reuse, keep = {"head": p_head}, []
360
+ for off, _ in cand.most_common(5):
361
+ p = share(f >= len(seqs[i]) - off > heads[i] for i, f in enumerate(future))
362
+ reuse[f"end-{off}"] = p
363
+ if p > need:
364
+ keep.append(off)
365
+ offsets = tuple(sorted({min(keep), keep[0]})) if keep else ()
366
+ return BreakPlan(p_head > need, const, offsets, reuse)
367
+
368
+
369
+ def place_breakpoints(req: dict, sort_tools: bool = False, plan: BreakPlan | None = None,
370
+ ttl: int = FIVE_MIN) -> dict:
371
+ """At most four breakpoints. Without a plan: end of tools, end of system, last message
372
+ block. With a plan: only the positions the plan found worth paying for. Content and
373
+ order are left exactly as written."""
374
+ out = copy.deepcopy(strip_cache_control(req))
375
+ head = plan is None or plan.head
376
+ if out.get("tools"):
377
+ if sort_tools:
378
+ out["tools"].sort(key=lambda t: t.get("name", ""))
379
+ if head and (plan is None or not out.get("system")):
380
+ out["tools"][-1]["cache_control"] = cc(ttl)
381
+ if out.get("system"):
382
+ out["system"] = _blocks(out["system"])
383
+ if head:
384
+ out["system"][-1]["cache_control"] = cc(ttl)
385
+ flat = []
386
+ for m in out.get("messages", []):
387
+ m["content"] = [dict(b) for b in _blocks(m["content"])]
388
+ flat += m["content"]
389
+ if flat:
390
+ last = len(flat) - 1
391
+ idx = {last} if plan is None else {last - o for o in plan.offsets}
392
+ if plan and plan.const_prefix:
393
+ idx.add(plan.const_prefix - 1)
394
+ for i in sorted(i for i in idx if 0 <= i <= last)[-3:]:
395
+ flat[i]["cache_control"] = cc(ttl)
396
+ return out
397
+
398
+
399
+ def canonicalize_request(req: dict, tpl: Template | None, plan: "BreakPlan | None" = None,
400
+ ttl: int = FIVE_MIN) -> dict:
401
+ """Sorted tools; static system text; shared values in a second system block;
402
+ volatile values at the end of the latest user message; four breakpoints."""
403
+ applied = apply_template(tpl, system_text(req)) if tpl else None
404
+ hoisted = sum(len(v) for _, v in (applied[1] + applied[2])) if applied else 0
405
+ if applied is None or not hoisted or hoisted > 0.5 * len(system_text(req)):
406
+ # nothing to hoist, or the "template" is mostly variable: leave the content alone
407
+ return place_breakpoints(req, sort_tools=True, plan=plan, ttl=ttl)
408
+ static, shared, volatile = applied
409
+ out = copy.deepcopy(strip_cache_control(req))
410
+ if out.get("tools"):
411
+ out["tools"].sort(key=lambda t: t.get("name", ""))
412
+ out["tools"][-1]["cache_control"] = cc(ttl)
413
+ out["system"] = [{"type": "text", "text": static + "\n\n" + SLOT_NOTE, "cache_control": cc(ttl)}]
414
+ if shared:
415
+ out["system"].append({"type": "text", "text": _fmt(shared), "cache_control": cc(ttl)})
416
+ msgs = out.get("messages", [])
417
+ for m in msgs:
418
+ m["content"] = _blocks(m["content"])
419
+ if msgs and msgs[-1]["content"]:
420
+ last = msgs[-1]["content"]
421
+ last[-1] = dict(last[-1], cache_control=cc(ttl))
422
+ if volatile:
423
+ ctx = {"type": "text", "text": "<request_context>\n" + _fmt(volatile) + "\n</request_context>"}
424
+ if msgs[-1]["role"] == "user":
425
+ last.append(ctx) # after the breakpoint: never cached
426
+ else:
427
+ out["system"].append(ctx) # assistant prefill: keep it in system
428
+ return out
cacheplan/proxy.py ADDED
@@ -0,0 +1,76 @@
1
+ """Logging proxy for the Anthropic API.
2
+
3
+ Point any Anthropic client at it (ANTHROPIC_BASE_URL=http://127.0.0.1:8787) and every
4
+ /v1/messages request body is appended to a JSONL file exactly as the client assembled
5
+ it. Headers are never written, so the API key stays out of the log. Responses are
6
+ passed through unchanged.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import http.client
12
+ import json
13
+ import threading
14
+ import time
15
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
16
+ from urllib.parse import urlsplit
17
+
18
+ HOP = {"connection", "transfer-encoding", "content-length", "keep-alive", "host"}
19
+
20
+
21
+ def make_handler(upstream: str, out_path: str, app: str):
22
+ up = urlsplit(upstream)
23
+ lock, counter = threading.Lock(), [0]
24
+
25
+ class Handler(BaseHTTPRequestHandler):
26
+ protocol_version = "HTTP/1.1"
27
+
28
+ def log_message(self, *_):
29
+ pass
30
+
31
+ def _forward(self, body: bytes | None):
32
+ Conn = http.client.HTTPSConnection if up.scheme == "https" else http.client.HTTPConnection
33
+ conn = Conn(up.hostname, up.port, timeout=600)
34
+ headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP}
35
+ headers["Host"] = up.netloc
36
+ conn.request(self.command, self.path, body=body, headers=headers)
37
+ resp = conn.getresponse()
38
+ self.send_response(resp.status)
39
+ for k, v in resp.getheaders():
40
+ if k.lower() not in HOP:
41
+ self.send_header(k, v)
42
+ self.send_header("Transfer-Encoding", "chunked")
43
+ self.send_header("Connection", "close") # one request per connection: simplest to get right
44
+ self.end_headers()
45
+ while chunk := resp.read1(65536):
46
+ self.wfile.write(f"{len(chunk):x}\r\n".encode() + chunk + b"\r\n")
47
+ self.wfile.flush()
48
+ self.wfile.write(b"0\r\n\r\n")
49
+ self.wfile.flush()
50
+ conn.close()
51
+ self.close_connection = True
52
+
53
+ def do_GET(self):
54
+ self._forward(None)
55
+
56
+ def do_POST(self):
57
+ body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
58
+ path = self.path.split("?")[0].rstrip("/")
59
+ if path.endswith("/v1/messages"):
60
+ try:
61
+ req = json.loads(body)
62
+ with lock:
63
+ counter[0] += 1
64
+ with open(out_path, "a", encoding="utf-8") as f:
65
+ f.write(json.dumps({"id": f"{app}-{counter[0]}", "ts": time.time(),
66
+ "app": app, "request": req}) + "\n")
67
+ print(f"captured {counter[0]} requests", end="\r", flush=True)
68
+ except ValueError:
69
+ pass
70
+ self._forward(body)
71
+
72
+ return Handler
73
+
74
+
75
+ def serve(port: int, upstream: str, out: str, app: str) -> ThreadingHTTPServer:
76
+ return ThreadingHTTPServer(("127.0.0.1", port), make_handler(upstream, out, app))