compache 0.14.0__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.
- compache/__init__.py +54 -0
- compache/__main__.py +3 -0
- compache/_tls.py +47 -0
- compache/api.py +761 -0
- compache/cli.py +665 -0
- compache/defaults.py +113 -0
- compache/demo/labels.jsonl +71 -0
- compache/demo/threads.jsonl.gz +0 -0
- compache/errors.py +5 -0
- compache/hermes.py +284 -0
- compache/labels.py +336 -0
- compache/langchain.py +65 -0
- compache/langfuse.py +738 -0
- compache/litellm.py +306 -0
- compache/live.py +1443 -0
- compache/mlflow.py +439 -0
- compache/models.json +156 -0
- compache/models.py +156 -0
- compache/notes.py +365 -0
- compache/optimizer/__init__.py +51 -0
- compache/optimizer/cache_breaks.py +755 -0
- compache/optimizer/contracts.py +196 -0
- compache/optimizer/distribution.py +1384 -0
- compache/optimizer/edit_accounting.py +324 -0
- compache/optimizer/header_traffic.py +225 -0
- compache/optimizer/host_ledger.py +318 -0
- compache/optimizer/parts.py +435 -0
- compache/optimizer/recovery.py +250 -0
- compache/optimizer/replay.py +638 -0
- compache/optimizer/retention.py +996 -0
- compache/optimizer/session.py +1269 -0
- compache/optimizer/shared_prefix.py +465 -0
- compache/optimizer/solve.py +382 -0
- compache/optimizer/usage.py +49 -0
- compache/otel.py +390 -0
- compache/profile.py +643 -0
- compache/proxy.py +352 -0
- compache/py.typed +0 -0
- compache/record.py +238 -0
- compache/threads.py +892 -0
- compache/wire.py +1548 -0
- compache/wrap.py +417 -0
- compache-0.14.0.dist-info/METADATA +174 -0
- compache-0.14.0.dist-info/RECORD +47 -0
- compache-0.14.0.dist-info/WHEEL +4 -0
- compache-0.14.0.dist-info/entry_points.txt +6 -0
- compache-0.14.0.dist-info/licenses/LICENCE.md +202 -0
compache/api.py
ADDED
|
@@ -0,0 +1,761 @@
|
|
|
1
|
+
"""Fit a policy on recorded threads, price it on others, and apply it to live ones."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
import weakref
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime, timedelta, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from .errors import ContractError
|
|
14
|
+
from .models import cache_lifetimes, model_spec, pricing
|
|
15
|
+
from .optimizer.cache_breaks import CacheBreakChecker, CacheScope
|
|
16
|
+
from .optimizer.contracts import ModelSpec, seconds
|
|
17
|
+
from .optimizer.parts import Request, Source
|
|
18
|
+
from .optimizer.recovery import reopen as _reopen
|
|
19
|
+
from .optimizer.replay import arm_costs, replay_workload
|
|
20
|
+
from .optimizer.retention import RetentionRecipe
|
|
21
|
+
from .optimizer.session import WorkloadPolicy, WorkloadSession
|
|
22
|
+
from .optimizer.solve import solve_workload
|
|
23
|
+
from .profile import header_size, measure, workload
|
|
24
|
+
from .record import SIZES_ONLY, is_record
|
|
25
|
+
from .record import load as load_record
|
|
26
|
+
from .threads import (
|
|
27
|
+
cache_read_reported,
|
|
28
|
+
canonical_usage,
|
|
29
|
+
load_threads,
|
|
30
|
+
read_jsonl,
|
|
31
|
+
recorded,
|
|
32
|
+
)
|
|
33
|
+
from .wire import TTLS, cache_mark
|
|
34
|
+
|
|
35
|
+
__all__ = ["Policy", "Session", "Turn", "fit", "replay"]
|
|
36
|
+
|
|
37
|
+
_HORIZON_SECONDS = 86400
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _rows(source) -> list:
|
|
41
|
+
if source is None:
|
|
42
|
+
return []
|
|
43
|
+
if isinstance(source, (str, Path)):
|
|
44
|
+
return list(read_jsonl(source))
|
|
45
|
+
return list(source)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _labels(labels, threads) -> list:
|
|
49
|
+
"""Label rows as given, or those a record folder of threads carries itself."""
|
|
50
|
+
if labels is None and is_record(threads):
|
|
51
|
+
return load_record(threads)[1]
|
|
52
|
+
return _rows(labels)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _threads(source, model=None):
|
|
56
|
+
"""Threads priced as one model, its spec, and what the rows record about themselves.
|
|
57
|
+
|
|
58
|
+
Without `model` the threads are priced as the model most of them record.
|
|
59
|
+
"""
|
|
60
|
+
rows = _rows(source)
|
|
61
|
+
found = recorded(rows)
|
|
62
|
+
if model is None:
|
|
63
|
+
model = found["model"]
|
|
64
|
+
if model is None:
|
|
65
|
+
raise ContractError(
|
|
66
|
+
"the threads do not record which model answered: name it with --model or model="
|
|
67
|
+
)
|
|
68
|
+
spec = model_spec(model)
|
|
69
|
+
return load_threads(rows, model=spec.model_id), spec, found, model
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _calls(threads):
|
|
73
|
+
"""Model calls per turn where the record has them and any turn made more than one."""
|
|
74
|
+
counts = {run.run_id: run.calls for t in threads for run in t.runs if run.calls}
|
|
75
|
+
return counts if any(n > 1 for n in counts.values()) else None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _observed_until(threads, given):
|
|
79
|
+
"""When the record ends. Unless told otherwise, every thread is taken to be over."""
|
|
80
|
+
if given is not None:
|
|
81
|
+
return given
|
|
82
|
+
last = max(seconds(t.runs[-1].ended_at) for t in threads)
|
|
83
|
+
end = datetime.fromtimestamp(last, timezone.utc) + timedelta(
|
|
84
|
+
seconds=_HORIZON_SECONDS
|
|
85
|
+
)
|
|
86
|
+
return end.isoformat().replace("+00:00", "Z")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def fit(
|
|
90
|
+
threads,
|
|
91
|
+
labels=None,
|
|
92
|
+
*,
|
|
93
|
+
model=None,
|
|
94
|
+
system_prompt=None,
|
|
95
|
+
tools=None,
|
|
96
|
+
observed_until=None,
|
|
97
|
+
**options,
|
|
98
|
+
) -> Policy:
|
|
99
|
+
"""Fit what to keep in view, how many keep-warm pings to send and how long the cache is to live.
|
|
100
|
+
|
|
101
|
+
`threads` and `labels` are paths to JSONL files (or folders of them), or
|
|
102
|
+
lists of dicts. `model` names a known model or gives a model spec. Left
|
|
103
|
+
out, it is the model the threads record, as are the system prompt, the
|
|
104
|
+
tools and when the record was read. Without labels only the caching is
|
|
105
|
+
fitted and the whole history stays in view. Where the threads record
|
|
106
|
+
several model calls in a turn, those are priced.
|
|
107
|
+
|
|
108
|
+
Every candidate is replayed against the provider's cache rules at the
|
|
109
|
+
threads' own timestamps, each thread priced by a model of returns fitted on
|
|
110
|
+
the others, and the cheapest wins after paying for what it would fetch back.
|
|
111
|
+
Where a known model can be asked for another cache lifetime, as Claude can
|
|
112
|
+
for an hour, every candidate is priced under that too.
|
|
113
|
+
`observed_until` is when the record was cut, for a record that ends while
|
|
114
|
+
conversations were still going. `options` go to the solver.
|
|
115
|
+
"""
|
|
116
|
+
labels = _labels(labels, threads)
|
|
117
|
+
threads, spec, found, model = _threads(threads, model)
|
|
118
|
+
lifetimes = options.pop("lifetimes", None)
|
|
119
|
+
if lifetimes is None:
|
|
120
|
+
lifetimes = cache_lifetimes(model)
|
|
121
|
+
for other in lifetimes:
|
|
122
|
+
if other.cache_ttl_seconds not in TTLS:
|
|
123
|
+
raise ContractError(
|
|
124
|
+
f"no request can ask for cache entries of {other.cache_ttl_seconds:g} seconds"
|
|
125
|
+
)
|
|
126
|
+
if system_prompt is None:
|
|
127
|
+
system_prompt = found["system_prompt"] or ""
|
|
128
|
+
tools = list(found["tools"] or ()) if tools is None else list(tools)
|
|
129
|
+
if all(t.to_dict().get("provenance") == SIZES_ONLY for t in threads):
|
|
130
|
+
# No words to match a question against: see `solve_workload`.
|
|
131
|
+
options.setdefault("match_questions", False)
|
|
132
|
+
artifact = solve_workload(
|
|
133
|
+
threads,
|
|
134
|
+
labels,
|
|
135
|
+
spec,
|
|
136
|
+
observation_end=_observed_until(
|
|
137
|
+
threads, observed_until or found["observed_until"]
|
|
138
|
+
),
|
|
139
|
+
system_prompt=system_prompt,
|
|
140
|
+
default_tools=tools,
|
|
141
|
+
lifetimes=lifetimes,
|
|
142
|
+
**{"calls_per_run": _calls(threads), **options},
|
|
143
|
+
)
|
|
144
|
+
scored = artifact["recipes"]
|
|
145
|
+
artifact["fitted"] = {
|
|
146
|
+
"threads": len(threads),
|
|
147
|
+
"turns": artifact["solve"]["turns"],
|
|
148
|
+
"labelled_turns": scored[0]["turns"] - scored[0]["unlabeled_runs"]
|
|
149
|
+
if scored
|
|
150
|
+
else 0,
|
|
151
|
+
"unknown_requirements": scored[0]["unknown_requirements"] if scored else 0,
|
|
152
|
+
"assessed_requirements": scored[0]["direct_required"]
|
|
153
|
+
+ scored[0]["historical_required"]
|
|
154
|
+
if scored
|
|
155
|
+
else 0,
|
|
156
|
+
"unknown_turns": scored[0]["unknown_runs"] if scored else 0,
|
|
157
|
+
"historical_requirements": scored[0]["historical_required"] if scored else 0,
|
|
158
|
+
"candidate_cuts": len(scored),
|
|
159
|
+
}
|
|
160
|
+
# The policy file keeps the cut that won. The priced candidates stay under `solve`.
|
|
161
|
+
artifact["recipes"] = [row for row in scored if row["eligible"]]
|
|
162
|
+
artifact["header"] = {
|
|
163
|
+
"system_prompt": system_prompt,
|
|
164
|
+
"default_tools": tools,
|
|
165
|
+
"share_headers": options.get("share_headers", True),
|
|
166
|
+
}
|
|
167
|
+
artifact["pricing"] = pricing(model)
|
|
168
|
+
# The measured workload, so that the calculator can show the policy at work on it.
|
|
169
|
+
preset, scenario = workload(
|
|
170
|
+
measure(threads, spec, labels),
|
|
171
|
+
spec,
|
|
172
|
+
model,
|
|
173
|
+
header_size(spec, system_prompt, tools),
|
|
174
|
+
)
|
|
175
|
+
artifact["workload"] = {
|
|
176
|
+
"model": preset,
|
|
177
|
+
"scenario": scenario,
|
|
178
|
+
"source": f"{len(threads):,} threads, {artifact['fitted']['turns']:,} turns",
|
|
179
|
+
}
|
|
180
|
+
return Policy(artifact)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def replay(policy, threads, labels=None, *, observed_until=None, **options) -> dict:
|
|
184
|
+
"""Price a fitted policy on threads it has not seen, against keeping everything.
|
|
185
|
+
|
|
186
|
+
With labels the report also says how much of what those threads needed
|
|
187
|
+
stays in view, and adds the cost of fetching the rest back.
|
|
188
|
+
"""
|
|
189
|
+
if not isinstance(policy, Policy):
|
|
190
|
+
policy = Policy(policy)
|
|
191
|
+
labels = _labels(labels, threads)
|
|
192
|
+
threads, _, found, _ = _threads(threads, policy.spec)
|
|
193
|
+
header = policy.artifact.get("header") or {}
|
|
194
|
+
# Threads share a cached system prompt in the replay if they did in the fit.
|
|
195
|
+
options.setdefault("share_headers", header.get("share_headers", True))
|
|
196
|
+
options.setdefault("calls_per_run", _calls(threads))
|
|
197
|
+
detail = replay_workload(
|
|
198
|
+
threads,
|
|
199
|
+
labels,
|
|
200
|
+
policy.artifact,
|
|
201
|
+
observation_end=_observed_until(
|
|
202
|
+
threads, observed_until or found["observed_until"]
|
|
203
|
+
),
|
|
204
|
+
system_prompt=header.get("system_prompt", ""),
|
|
205
|
+
default_tools=header.get("default_tools", []),
|
|
206
|
+
**options,
|
|
207
|
+
)
|
|
208
|
+
candidate, baseline = detail["candidate"], detail["baseline"]
|
|
209
|
+
turns, replayed, recovery = arm_costs(candidate["ledger"])
|
|
210
|
+
cost = replayed + recovery
|
|
211
|
+
baseline_turns, keep, _ = arm_costs(baseline["ledger"])
|
|
212
|
+
complete = candidate["complete"] and baseline["complete"]
|
|
213
|
+
answers = [r for r in candidate["ledger"] if r["role"] == "answer"]
|
|
214
|
+
per_thread = {}
|
|
215
|
+
for row in answers:
|
|
216
|
+
counts = per_thread.setdefault(row["thread_id"], [0, 0])
|
|
217
|
+
counts[0] += row["historical_retained"]
|
|
218
|
+
counts[1] += row["historical_required"]
|
|
219
|
+
full_tokens = sum(r["canonical_part_tokens"] for r in answers)
|
|
220
|
+
common_runs = {r["run_id"] for r in answers} & {
|
|
221
|
+
r["run_id"] for r in baseline["ledger"] if r["role"] == "answer"
|
|
222
|
+
}
|
|
223
|
+
paired = {}
|
|
224
|
+
for name, arm in (("policy", candidate), ("keep_everything", baseline)):
|
|
225
|
+
_, charges, extra = arm_costs(
|
|
226
|
+
[r for r in arm["ledger"] if r["run_id"] in common_runs]
|
|
227
|
+
)
|
|
228
|
+
paired[name] = charges + extra
|
|
229
|
+
return {
|
|
230
|
+
"threads": len(threads),
|
|
231
|
+
"turns": turns,
|
|
232
|
+
"planned_turns": candidate["planned_answers"],
|
|
233
|
+
"policy_turns": turns,
|
|
234
|
+
"baseline_turns": baseline_turns,
|
|
235
|
+
"complete": complete,
|
|
236
|
+
"policy_cost": cost,
|
|
237
|
+
"replayed_cost": replayed,
|
|
238
|
+
"recovery_cost": recovery,
|
|
239
|
+
"keep_everything_cost": keep,
|
|
240
|
+
"saving": 1 - cost / keep if complete and keep else None,
|
|
241
|
+
"common_prefix": {
|
|
242
|
+
"turns": len(common_runs),
|
|
243
|
+
"cost_per_1000_turns": policy._per_1000_turns(paired, len(common_runs)),
|
|
244
|
+
"saving": 1 - paired["policy"] / paired["keep_everything"]
|
|
245
|
+
if paired["keep_everything"]
|
|
246
|
+
else None,
|
|
247
|
+
},
|
|
248
|
+
"pings": candidate["pings"],
|
|
249
|
+
"needs_history": candidate["historical_required"] if labels else None,
|
|
250
|
+
"coverage": candidate["coverage"],
|
|
251
|
+
"coverage_by_thread": {
|
|
252
|
+
tid: {"retained": n, "required": d, "coverage": n / d if d else None}
|
|
253
|
+
for tid, (n, d) in per_thread.items()
|
|
254
|
+
},
|
|
255
|
+
"unassessable_turns": candidate["unassessable_runs"],
|
|
256
|
+
"unknown_requirements": sum(r["unknown_requirements"] for r in answers),
|
|
257
|
+
"assessed_requirements": sum(r["assessed_requirements"] for r in answers),
|
|
258
|
+
"tokens_kept": sum(r["sent_part_tokens"] for r in answers) / full_tokens
|
|
259
|
+
if full_tokens
|
|
260
|
+
else None,
|
|
261
|
+
"cost_per_1000_turns": {
|
|
262
|
+
**policy._per_1000_turns({"policy": cost}, turns),
|
|
263
|
+
**policy._per_1000_turns({"keep_everything": keep}, baseline_turns),
|
|
264
|
+
},
|
|
265
|
+
"detail": detail,
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _duration(seconds):
|
|
270
|
+
"""A cache lifetime as a word before a noun: one-hour, 12-hour."""
|
|
271
|
+
hours = seconds / 3600
|
|
272
|
+
return "one-hour" if hours == 1 else f"{hours:g}-hour"
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _window(count, noun):
|
|
276
|
+
if count is None:
|
|
277
|
+
return f"all {noun}"
|
|
278
|
+
if count == 0:
|
|
279
|
+
return f"no earlier {noun}"
|
|
280
|
+
return f"{noun} from the last {'turn' if count == 1 else f'{count} turns'}"
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
class Policy:
|
|
284
|
+
"""A fitted policy: what stays in view, and how many pings keep the cache warm."""
|
|
285
|
+
|
|
286
|
+
def __init__(self, artifact: dict):
|
|
287
|
+
if (
|
|
288
|
+
not isinstance(artifact, dict)
|
|
289
|
+
or artifact.get("schema_version") != "compache-workload-planner-v1"
|
|
290
|
+
):
|
|
291
|
+
raise ContractError("expected a fitted policy")
|
|
292
|
+
self.artifact = artifact
|
|
293
|
+
self._compiled = None
|
|
294
|
+
self._checker = None
|
|
295
|
+
self._lock = threading.Lock()
|
|
296
|
+
|
|
297
|
+
@classmethod
|
|
298
|
+
def load(cls, path) -> Policy:
|
|
299
|
+
return cls(json.loads(Path(path).read_text("utf-8")))
|
|
300
|
+
|
|
301
|
+
def save(self, path) -> None:
|
|
302
|
+
path = Path(path)
|
|
303
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
304
|
+
path.write_text(
|
|
305
|
+
json.dumps(self.artifact, ensure_ascii=False, indent=2) + "\n", "utf-8"
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
@property
|
|
309
|
+
def spec(self) -> ModelSpec:
|
|
310
|
+
return ModelSpec.from_dict(self.artifact["model_spec"])
|
|
311
|
+
|
|
312
|
+
@property
|
|
313
|
+
def cache_lifetime(self) -> float | None:
|
|
314
|
+
"""How long the provider is asked to keep what it caches, in seconds. None for its default."""
|
|
315
|
+
standard = self.artifact.get("standard_spec")
|
|
316
|
+
if standard is None or standard["cache_ttl_seconds"] == (
|
|
317
|
+
self.spec.cache_ttl_seconds
|
|
318
|
+
):
|
|
319
|
+
return None
|
|
320
|
+
return self.spec.cache_ttl_seconds
|
|
321
|
+
|
|
322
|
+
@property
|
|
323
|
+
def cache_control(self) -> dict:
|
|
324
|
+
"""The cache mark for a Claude request you assemble yourself."""
|
|
325
|
+
return cache_mark(self.cache_lifetime)
|
|
326
|
+
|
|
327
|
+
def at_default_lifetime(self) -> Policy:
|
|
328
|
+
"""The same cut and pings, planned under the provider's default cache lifetime."""
|
|
329
|
+
if self.cache_lifetime is None:
|
|
330
|
+
return self
|
|
331
|
+
artifact = {k: v for k, v in self.artifact.items() if k != "standard_spec"}
|
|
332
|
+
return Policy({**artifact, "model_spec": self.artifact["standard_spec"]})
|
|
333
|
+
|
|
334
|
+
@property
|
|
335
|
+
def recipe(self) -> RetentionRecipe | None:
|
|
336
|
+
"""The cut the policy applies, or None when it keeps the whole history."""
|
|
337
|
+
for row in self.artifact["recipes"]:
|
|
338
|
+
if row["eligible"]:
|
|
339
|
+
return RetentionRecipe(**row["recipe"])
|
|
340
|
+
return None
|
|
341
|
+
|
|
342
|
+
@property
|
|
343
|
+
def max_pings(self) -> int:
|
|
344
|
+
return (self.artifact.get("planner_options") or {}).get("max_pings", 1)
|
|
345
|
+
|
|
346
|
+
def _per_1000_turns(self, costs, turns):
|
|
347
|
+
"""Costs per 1,000 turns: in dollars for a known model, else in input tokens."""
|
|
348
|
+
price = (self.artifact.get("pricing") or {}).get("input_price_per_million")
|
|
349
|
+
scale = 1000 / turns if turns else None
|
|
350
|
+
if price is None:
|
|
351
|
+
return {
|
|
352
|
+
"unit": "input-token equivalents",
|
|
353
|
+
**{
|
|
354
|
+
k: v * scale if scale is not None else None
|
|
355
|
+
for k, v in costs.items()
|
|
356
|
+
},
|
|
357
|
+
}
|
|
358
|
+
return {
|
|
359
|
+
"unit": "USD",
|
|
360
|
+
**{
|
|
361
|
+
k: v * scale * price / 1e6 if scale is not None else None
|
|
362
|
+
for k, v in costs.items()
|
|
363
|
+
},
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
@property
|
|
367
|
+
def summary(self) -> dict:
|
|
368
|
+
"""The decision and what it costs on the fitted threads, as plain numbers."""
|
|
369
|
+
solved = self.artifact.get("solve") or {}
|
|
370
|
+
chosen = solved.get("chosen") or {}
|
|
371
|
+
recipe = self.recipe
|
|
372
|
+
keep = solved.get("keep_everything_cost")
|
|
373
|
+
costs = {
|
|
374
|
+
"policy": chosen.get("expected_cost"),
|
|
375
|
+
"keep_everything": keep,
|
|
376
|
+
}
|
|
377
|
+
alone = (solved.get("caching_alone") or {}).get("expected_cost")
|
|
378
|
+
if alone is not None:
|
|
379
|
+
# Everything kept, at the cheapest pings and lifetime: what caching can do by itself.
|
|
380
|
+
costs["caching_alone"] = alone
|
|
381
|
+
fitted = self.artifact.get("fitted") or {}
|
|
382
|
+
return {
|
|
383
|
+
"model": self.spec.model_id,
|
|
384
|
+
"threads": len(self.artifact["training_threads"]),
|
|
385
|
+
"turns": solved.get("turns"),
|
|
386
|
+
"labelled_turns": fitted.get("labelled_turns", 0),
|
|
387
|
+
"unknown_requirements": fitted.get("unknown_requirements"),
|
|
388
|
+
"assessed_requirements": fitted.get("assessed_requirements"),
|
|
389
|
+
"unknown_turns": fitted.get("unknown_turns"),
|
|
390
|
+
"historical_requirements": fitted.get("historical_requirements"),
|
|
391
|
+
"keep": None
|
|
392
|
+
if recipe is None
|
|
393
|
+
else {
|
|
394
|
+
"questions": recipe.input_runs,
|
|
395
|
+
"answers": recipe.output_runs,
|
|
396
|
+
"retrieved": recipe.retrieval_runs,
|
|
397
|
+
"matching_retrieved": recipe.protect_query_matches,
|
|
398
|
+
"always_under_tokens": recipe.keep_under_tokens,
|
|
399
|
+
**(
|
|
400
|
+
{"cited_answer_runs": recipe.cited_answer_runs}
|
|
401
|
+
if recipe.cited_answer_runs != 0
|
|
402
|
+
else {}
|
|
403
|
+
),
|
|
404
|
+
},
|
|
405
|
+
"max_pings": self.max_pings,
|
|
406
|
+
"cache_lifetime_seconds": self.cache_lifetime,
|
|
407
|
+
"coverage": chosen.get("coverage"),
|
|
408
|
+
"saving": solved.get("saving_fraction"),
|
|
409
|
+
"cost_per_1000_turns": None
|
|
410
|
+
if None in costs.values()
|
|
411
|
+
else self._per_1000_turns(costs, solved.get("turns")),
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
def describe(self) -> str:
|
|
415
|
+
"""The decision in sentences."""
|
|
416
|
+
summary, recipe = self.summary, self.recipe
|
|
417
|
+
lines = []
|
|
418
|
+
if recipe is None:
|
|
419
|
+
lines.append(
|
|
420
|
+
"Keep the whole history in view."
|
|
421
|
+
if summary["labelled_turns"]
|
|
422
|
+
else "Keep the whole history in view: without labels only the caching is fitted."
|
|
423
|
+
)
|
|
424
|
+
else:
|
|
425
|
+
lines.append(
|
|
426
|
+
f"Keep {_window(recipe.input_runs, 'questions')}, "
|
|
427
|
+
f"{_window(recipe.output_runs, 'answers')} and "
|
|
428
|
+
f"{_window(recipe.retrieval_runs, 'retrieved text')}."
|
|
429
|
+
)
|
|
430
|
+
if recipe.protect_query_matches and recipe.retrieval_runs is not None:
|
|
431
|
+
lines.append(
|
|
432
|
+
"Earlier retrieved text that matches the new question stays too."
|
|
433
|
+
)
|
|
434
|
+
if recipe.cited_answer_runs != 0:
|
|
435
|
+
lines.append(
|
|
436
|
+
f"Keep visible sources cited by {_window(recipe.cited_answer_runs, 'answers')}."
|
|
437
|
+
)
|
|
438
|
+
if recipe.keep_under_tokens:
|
|
439
|
+
lines.append(
|
|
440
|
+
f"Parts of at most {recipe.keep_under_tokens} tokens always stay."
|
|
441
|
+
)
|
|
442
|
+
if summary["cache_lifetime_seconds"]:
|
|
443
|
+
lines.append(
|
|
444
|
+
f"Ask for {_duration(summary['cache_lifetime_seconds'])} cache entries."
|
|
445
|
+
)
|
|
446
|
+
pings = summary["max_pings"]
|
|
447
|
+
lines.append(
|
|
448
|
+
f"Send up to {pings} keep-warm ping{'' if pings == 1 else 's'} while a user is away."
|
|
449
|
+
if pings
|
|
450
|
+
else "Send no keep-warm pings."
|
|
451
|
+
)
|
|
452
|
+
if recipe is not None and summary["coverage"] is not None:
|
|
453
|
+
kept = f"{summary['coverage']:.0%} of what the labelled turns need from earlier turns stays in view."
|
|
454
|
+
if summary["coverage"] < 0.995:
|
|
455
|
+
kept += " The rest is fetched back, and that call is in the cost."
|
|
456
|
+
lines.append(kept)
|
|
457
|
+
costs, saving = summary["cost_per_1000_turns"], summary["saving"]
|
|
458
|
+
if costs and saving is not None:
|
|
459
|
+
if costs["unit"] == "USD":
|
|
460
|
+
lines.append(
|
|
461
|
+
f"${costs['policy']:,.2f} per 1,000 turns against "
|
|
462
|
+
f"${costs['keep_everything']:,.2f} keeping everything: {saving:.0%} less."
|
|
463
|
+
)
|
|
464
|
+
alone = costs.get("caching_alone")
|
|
465
|
+
if recipe is not None and alone and alone < costs["keep_everything"]:
|
|
466
|
+
lines.append(
|
|
467
|
+
f"Caching alone, at its best, would cost ${alone:,.2f}."
|
|
468
|
+
)
|
|
469
|
+
else:
|
|
470
|
+
lines.append(f"{saving:.0%} cheaper than keeping everything.")
|
|
471
|
+
return "\n".join(lines)
|
|
472
|
+
|
|
473
|
+
def session(self, thread_id: str, *, system_prompt=None, tools=None) -> Session:
|
|
474
|
+
"""The session of one conversation. Keep it for as long as the conversation lives."""
|
|
475
|
+
with self._lock:
|
|
476
|
+
# Conversations open at the same moment on a server: set up once, and in full.
|
|
477
|
+
if self._compiled is None:
|
|
478
|
+
checker = CacheBreakChecker()
|
|
479
|
+
weakref.finalize(self, checker.close)
|
|
480
|
+
self._checker = checker
|
|
481
|
+
self._compiled = WorkloadPolicy(self.artifact)
|
|
482
|
+
header = self.artifact.get("header") or {}
|
|
483
|
+
return Session(
|
|
484
|
+
self,
|
|
485
|
+
thread_id,
|
|
486
|
+
header.get("system_prompt", "") if system_prompt is None else system_prompt,
|
|
487
|
+
header.get("default_tools", []) if tools is None else tools,
|
|
488
|
+
)
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
@dataclass(frozen=True)
|
|
492
|
+
class Turn:
|
|
493
|
+
"""One request to send: its parts in order, with archived ones reduced to a notice."""
|
|
494
|
+
|
|
495
|
+
parts: tuple[Source, ...]
|
|
496
|
+
archived_ids: frozenset
|
|
497
|
+
tokens: int
|
|
498
|
+
action: str
|
|
499
|
+
plan: object = None
|
|
500
|
+
|
|
501
|
+
@property
|
|
502
|
+
def messages(self) -> list[dict]:
|
|
503
|
+
"""One chat message per part: answers from the assistant, everything else from the user."""
|
|
504
|
+
return [
|
|
505
|
+
{"role": "assistant" if p.kind == "output" else "user", "content": p.text}
|
|
506
|
+
for p in self.parts
|
|
507
|
+
]
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _counters(usage) -> dict:
|
|
511
|
+
"""Provider usage as the counters the session takes. Unknown shapes count as no usage."""
|
|
512
|
+
counted = canonical_usage(usage)
|
|
513
|
+
if counted is None:
|
|
514
|
+
return {}
|
|
515
|
+
return {
|
|
516
|
+
"input_tokens": counted["input"],
|
|
517
|
+
"cached_input_tokens": counted["cache_read"]
|
|
518
|
+
if cache_read_reported(usage)
|
|
519
|
+
else None,
|
|
520
|
+
"cache_write_input_tokens": counted["cache_write"],
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
class Session:
|
|
525
|
+
"""One conversation under a policy.
|
|
526
|
+
|
|
527
|
+
`prepare` returns the request for a new user message. `complete` records the
|
|
528
|
+
answer. `next_ping_at` says when a keep-warm ping is due. The session keeps
|
|
529
|
+
the full history itself, so an archived part can always be reopened.
|
|
530
|
+
"""
|
|
531
|
+
|
|
532
|
+
def __init__(self, policy: Policy, thread_id: str, system_prompt, tools):
|
|
533
|
+
self.policy, self.thread_id = policy, thread_id
|
|
534
|
+
self.system_prompt, self.tools = system_prompt, tools
|
|
535
|
+
self._model = policy.spec.model_id
|
|
536
|
+
self._engine = WorkloadSession(
|
|
537
|
+
policy._compiled,
|
|
538
|
+
CacheScope("compache", "declared", self._model, thread_id),
|
|
539
|
+
policy._checker,
|
|
540
|
+
)
|
|
541
|
+
self._history: list[Source] = []
|
|
542
|
+
self._run = 0
|
|
543
|
+
self._pending = None
|
|
544
|
+
|
|
545
|
+
def _request(self, run, parts):
|
|
546
|
+
return Request(
|
|
547
|
+
self.thread_id,
|
|
548
|
+
f"{self.thread_id}:{run}",
|
|
549
|
+
run,
|
|
550
|
+
self._model,
|
|
551
|
+
tuple(self._history) + tuple(parts),
|
|
552
|
+
)
|
|
553
|
+
|
|
554
|
+
def _retrieved(self, run, items, first) -> list[Source]:
|
|
555
|
+
"""Retrieved items of one run as parts, numbered from `first`."""
|
|
556
|
+
prefix, parts = f"{self.thread_id}:{run}", []
|
|
557
|
+
for k, item in enumerate(items, first):
|
|
558
|
+
fields = {"text": item} if isinstance(item, str) else dict(item)
|
|
559
|
+
part_id = fields.get("part_id", f"{prefix}:retrieval:{k}")
|
|
560
|
+
if (
|
|
561
|
+
not isinstance(part_id, str)
|
|
562
|
+
or not part_id.strip()
|
|
563
|
+
or part_id.strip() != part_id
|
|
564
|
+
):
|
|
565
|
+
raise ContractError(
|
|
566
|
+
"a retrieval part_id must be a nonempty trimmed string"
|
|
567
|
+
)
|
|
568
|
+
if part_id == f"{prefix}:output":
|
|
569
|
+
raise ContractError(
|
|
570
|
+
"a retrieval part_id collides with the current answer"
|
|
571
|
+
)
|
|
572
|
+
if not isinstance(fields.get("text"), str):
|
|
573
|
+
raise ContractError("a question and every retrieved item need text")
|
|
574
|
+
parts.append(
|
|
575
|
+
Source(
|
|
576
|
+
part_id,
|
|
577
|
+
"retrieval",
|
|
578
|
+
run,
|
|
579
|
+
fields["text"],
|
|
580
|
+
fields.get("document_id", part_id),
|
|
581
|
+
fields.get("version", "1"),
|
|
582
|
+
fields.get("chunk_id", part_id),
|
|
583
|
+
)
|
|
584
|
+
)
|
|
585
|
+
return parts
|
|
586
|
+
|
|
587
|
+
def prepare(
|
|
588
|
+
self, question: str, retrieved=(), *, at=None, system_prompt=None, tools=None
|
|
589
|
+
) -> Turn:
|
|
590
|
+
"""The request to send for a new user message and the text retrieved for it.
|
|
591
|
+
|
|
592
|
+
Each retrieved item is text, or a dict with `text` and optionally
|
|
593
|
+
`part_id`, `document_id`, `version` and `chunk_id`. An explicit part ID
|
|
594
|
+
identifies this occurrence and must be unique in the thread. Call again with the same
|
|
595
|
+
arguments to retry a request that was never answered.
|
|
596
|
+
"""
|
|
597
|
+
run = self._run + 1
|
|
598
|
+
parts = [Source(f"{self.thread_id}:{run}:input", "input", run, question)]
|
|
599
|
+
parts += self._retrieved(run, retrieved, 1)
|
|
600
|
+
if not isinstance(question, str):
|
|
601
|
+
raise ContractError("a question and every retrieved item need text")
|
|
602
|
+
request = self._request(run, parts)
|
|
603
|
+
plan = self._engine.prepare(
|
|
604
|
+
request,
|
|
605
|
+
started_at=time.time() if at is None else at,
|
|
606
|
+
system_prompt=self.system_prompt
|
|
607
|
+
if system_prompt is None
|
|
608
|
+
else system_prompt,
|
|
609
|
+
tools=self.tools if tools is None else tools,
|
|
610
|
+
)
|
|
611
|
+
self._pending = (request, tuple(parts))
|
|
612
|
+
view = plan.view
|
|
613
|
+
return Turn(
|
|
614
|
+
view.parts,
|
|
615
|
+
view.archived_ids,
|
|
616
|
+
view.tokens,
|
|
617
|
+
"keep" if plan.decision["action"] == "keep" else "cut",
|
|
618
|
+
plan,
|
|
619
|
+
)
|
|
620
|
+
|
|
621
|
+
def extend(self, turn: Turn, retrieved) -> Turn:
|
|
622
|
+
"""Add text retrieved while `turn` is being answered, such as the results of a tool loop.
|
|
623
|
+
|
|
624
|
+
The history stays as `prepare` sent it and the new items follow it, so
|
|
625
|
+
the cached prefix is untouched. Returns the turn to pass to `complete`.
|
|
626
|
+
"""
|
|
627
|
+
if self._pending is None or self._pending[0] is not turn.plan.request:
|
|
628
|
+
raise ContractError("no prepared turn to extend")
|
|
629
|
+
request, parts = self._pending
|
|
630
|
+
found = sum(p.kind == "retrieval" for p in parts)
|
|
631
|
+
added = self._retrieved(request.run_index, retrieved, found + 1)
|
|
632
|
+
plan = self._engine.extend(turn.plan, added)
|
|
633
|
+
self._pending = (plan.request, parts + tuple(added))
|
|
634
|
+
view = plan.view
|
|
635
|
+
return Turn(view.parts, view.archived_ids, view.tokens, turn.action, plan)
|
|
636
|
+
|
|
637
|
+
def complete(
|
|
638
|
+
self,
|
|
639
|
+
turn: Turn,
|
|
640
|
+
answer: str,
|
|
641
|
+
*,
|
|
642
|
+
at=None,
|
|
643
|
+
usage=None,
|
|
644
|
+
last_usage=None,
|
|
645
|
+
cited_part_ids=(),
|
|
646
|
+
):
|
|
647
|
+
"""Record the answer to `turn`. Returns when the next ping is due, if one is.
|
|
648
|
+
|
|
649
|
+
`usage` is the provider's usage for the answer call, as a dict in
|
|
650
|
+
Anthropic's or OpenAI's shape. With it the session tracks real input
|
|
651
|
+
sizes and notices a cache that stopped hitting. Without it the request
|
|
652
|
+
is taken to be cached the way the model's rules say. When the turn made
|
|
653
|
+
several calls, `usage` is that of the first and `last_usage` that of
|
|
654
|
+
the last: the first shows what the turn found cached, the last what it
|
|
655
|
+
leaves there. If the host records which visible retrievals the answer
|
|
656
|
+
cited, pass their part IDs.
|
|
657
|
+
"""
|
|
658
|
+
if self._pending is None or self._pending[0] is not turn.plan.request:
|
|
659
|
+
raise ContractError("no prepared turn to complete")
|
|
660
|
+
request, parts = self._pending
|
|
661
|
+
source = Source(
|
|
662
|
+
f"{request.run_id}:output",
|
|
663
|
+
"output",
|
|
664
|
+
request.run_index,
|
|
665
|
+
answer,
|
|
666
|
+
cited_part_ids=cited_part_ids,
|
|
667
|
+
)
|
|
668
|
+
if source.cited_part_ids:
|
|
669
|
+
visible = {
|
|
670
|
+
p.part_id
|
|
671
|
+
for p in turn.parts
|
|
672
|
+
if p.kind == "retrieval" and p.part_id not in turn.archived_ids
|
|
673
|
+
}
|
|
674
|
+
if not set(source.cited_part_ids) <= visible:
|
|
675
|
+
raise ContractError(
|
|
676
|
+
"cited_part_ids must name visible retrievals in the answered request"
|
|
677
|
+
)
|
|
678
|
+
counters = _counters(usage)
|
|
679
|
+
final = _counters(last_usage)
|
|
680
|
+
spec = self.policy.spec
|
|
681
|
+
if counters and final:
|
|
682
|
+
# The first call says what the turn found cached, the last what it leaves.
|
|
683
|
+
left = final["input_tokens"]
|
|
684
|
+
if final["cache_write_input_tokens"]:
|
|
685
|
+
left = min(
|
|
686
|
+
left,
|
|
687
|
+
(final["cached_input_tokens"] or 0)
|
|
688
|
+
+ final["cache_write_input_tokens"],
|
|
689
|
+
)
|
|
690
|
+
left = left // spec.cache_block_tokens * spec.cache_block_tokens
|
|
691
|
+
cacheable = spec.cache_ttl_seconds > 0 and left >= spec.cache_min_tokens
|
|
692
|
+
counters = {
|
|
693
|
+
"input_tokens": final["input_tokens"],
|
|
694
|
+
"cached_input_tokens": counters["cached_input_tokens"],
|
|
695
|
+
"reusable_input_tokens": left if cacheable else 0,
|
|
696
|
+
}
|
|
697
|
+
elif not counters:
|
|
698
|
+
cached = turn.tokens // spec.cache_block_tokens * spec.cache_block_tokens
|
|
699
|
+
cacheable = spec.cache_ttl_seconds > 0 and cached >= spec.cache_min_tokens
|
|
700
|
+
counters = {"reusable_input_tokens": cached if cacheable else 0}
|
|
701
|
+
self._engine.complete(
|
|
702
|
+
turn.plan,
|
|
703
|
+
source,
|
|
704
|
+
ended_at=time.time() if at is None else at,
|
|
705
|
+
**counters,
|
|
706
|
+
)
|
|
707
|
+
self._history.extend((*parts, source))
|
|
708
|
+
self._run, self._pending = request.run_index, None
|
|
709
|
+
return self.next_ping_at
|
|
710
|
+
|
|
711
|
+
@property
|
|
712
|
+
def next_ping_at(self):
|
|
713
|
+
"""Epoch seconds at which the next keep-warm ping is due, or None."""
|
|
714
|
+
return self._engine.next_ping_at
|
|
715
|
+
|
|
716
|
+
def ping(self, *, at=None) -> Turn | None:
|
|
717
|
+
"""The request to send as a keep-warm ping, or None when it is no longer worth sending.
|
|
718
|
+
|
|
719
|
+
Send it with the smallest output the provider allows, then call `ping_sent`.
|
|
720
|
+
"""
|
|
721
|
+
if not self._run:
|
|
722
|
+
return None
|
|
723
|
+
view = self._engine.ping_view(
|
|
724
|
+
run_id=f"{self.thread_id}:{self._run}",
|
|
725
|
+
at=time.time() if at is None else at,
|
|
726
|
+
)
|
|
727
|
+
if view is None:
|
|
728
|
+
return None
|
|
729
|
+
return Turn(view.parts, view.archived_ids, view.tokens, "ping")
|
|
730
|
+
|
|
731
|
+
def ping_sent(self, *, at, usage=None, completed_at=None) -> bool:
|
|
732
|
+
"""Record a ping sent at `at`. True when it refreshed the cache.
|
|
733
|
+
|
|
734
|
+
Pass the ping's own usage. Without it the refresh cannot be confirmed
|
|
735
|
+
and no further ping is planned for this wait.
|
|
736
|
+
"""
|
|
737
|
+
counted = canonical_usage(usage) or {}
|
|
738
|
+
return self._engine.acknowledge_ping(
|
|
739
|
+
run_id=f"{self.thread_id}:{self._run}",
|
|
740
|
+
at=at,
|
|
741
|
+
completed_at=completed_at,
|
|
742
|
+
output_tokens=counted.get("output"),
|
|
743
|
+
**_counters(usage),
|
|
744
|
+
)
|
|
745
|
+
|
|
746
|
+
def reopen(self, reference: str, offset: int = 0, *, search=("retrieval",)) -> dict:
|
|
747
|
+
"""Resolve the model's `reopen` tool call against this conversation's archive.
|
|
748
|
+
|
|
749
|
+
Words that are not a reference are looked for in retrieved text. `search`
|
|
750
|
+
adds `"input"` and `"output"`, for a conversation whose questions hold its sources.
|
|
751
|
+
"""
|
|
752
|
+
if self._pending is not None:
|
|
753
|
+
request = self._pending[0]
|
|
754
|
+
elif self._run:
|
|
755
|
+
request = self._request(self._run + 1, ())
|
|
756
|
+
else:
|
|
757
|
+
raise ContractError("nothing to reopen before the first turn")
|
|
758
|
+
arguments = {"reference": reference}
|
|
759
|
+
if offset:
|
|
760
|
+
arguments["offset"] = offset
|
|
761
|
+
return _reopen(request, arguments, search=tuple(search))
|