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/cli.py
ADDED
|
@@ -0,0 +1,665 @@
|
|
|
1
|
+
"""compache: fit a context and cache policy to recorded threads."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import gzip
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from importlib import resources
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .api import Policy, fit, replay
|
|
15
|
+
from .defaults import default_policy
|
|
16
|
+
from .errors import ContractError
|
|
17
|
+
from .labels import build_packet, label_index
|
|
18
|
+
from .models import _sheet, known_models
|
|
19
|
+
from .optimizer.contracts import ModelSpec
|
|
20
|
+
from .profile import history_resent, measure, profile
|
|
21
|
+
from .record import is_record
|
|
22
|
+
from .record import load as load_record
|
|
23
|
+
from .threads import load_threads, read_jsonl
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _parser() -> argparse.ArgumentParser:
|
|
27
|
+
parser = argparse.ArgumentParser(prog="compache", description=__doc__)
|
|
28
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
29
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
30
|
+
|
|
31
|
+
def command(name, text, *, model=False, labels=True):
|
|
32
|
+
sub = commands.add_parser(name, help=text, description=text)
|
|
33
|
+
sub.add_argument(
|
|
34
|
+
"threads",
|
|
35
|
+
type=Path,
|
|
36
|
+
help="Threads as JSONL, gzipped JSONL or a folder of either",
|
|
37
|
+
)
|
|
38
|
+
if labels:
|
|
39
|
+
sub.add_argument(
|
|
40
|
+
"--labels", type=Path, help="Dependency labels for these threads"
|
|
41
|
+
)
|
|
42
|
+
if model:
|
|
43
|
+
sub.add_argument(
|
|
44
|
+
"--model",
|
|
45
|
+
help=f"A known model ({', '.join(known_models())}) or a JSON file of model spec fields. "
|
|
46
|
+
"Left out, the model the threads record",
|
|
47
|
+
)
|
|
48
|
+
sub.add_argument(
|
|
49
|
+
"--system-prompt", type=Path, help="Text file with the system prompt"
|
|
50
|
+
)
|
|
51
|
+
sub.add_argument(
|
|
52
|
+
"--tools",
|
|
53
|
+
type=Path,
|
|
54
|
+
help="JSON file with the tool definitions sent on every request",
|
|
55
|
+
)
|
|
56
|
+
sub.add_argument("--json", action="store_true", help="Print JSON")
|
|
57
|
+
return sub
|
|
58
|
+
|
|
59
|
+
sub = command(
|
|
60
|
+
"fit", "Fit a policy and say what it saves on these threads", model=True
|
|
61
|
+
)
|
|
62
|
+
sub.add_argument(
|
|
63
|
+
"--observed-until",
|
|
64
|
+
help="When the record was cut, if conversations were still going",
|
|
65
|
+
)
|
|
66
|
+
sub.add_argument("-o", "--output", type=Path, default=Path("policy.json"))
|
|
67
|
+
|
|
68
|
+
text = "Fit a policy on four sample conversations that come with compache"
|
|
69
|
+
sub = commands.add_parser("demo", help=text, description=text)
|
|
70
|
+
sub.add_argument(
|
|
71
|
+
"--model",
|
|
72
|
+
default="claude-sonnet-5-5",
|
|
73
|
+
help="The model to fit for, by name or a JSON file of model spec fields",
|
|
74
|
+
)
|
|
75
|
+
sub.add_argument(
|
|
76
|
+
"-o",
|
|
77
|
+
"--output",
|
|
78
|
+
type=Path,
|
|
79
|
+
help="Keep the policy here. Left out, it is only shown",
|
|
80
|
+
)
|
|
81
|
+
sub.add_argument("--json", action="store_true", help="Print JSON")
|
|
82
|
+
|
|
83
|
+
sub = command("replay", "Price a fitted policy on threads it has not seen")
|
|
84
|
+
sub.add_argument("--policy", type=Path, required=True)
|
|
85
|
+
sub.add_argument(
|
|
86
|
+
"--observed-until",
|
|
87
|
+
help="When the record was cut, if conversations were still going",
|
|
88
|
+
)
|
|
89
|
+
sub.add_argument("-o", "--output", type=Path, help="Write the full report here")
|
|
90
|
+
|
|
91
|
+
sub = command(
|
|
92
|
+
"profile",
|
|
93
|
+
"Measure the workload and open the cost calculator with it",
|
|
94
|
+
model=True,
|
|
95
|
+
)
|
|
96
|
+
sub.add_argument(
|
|
97
|
+
"-o",
|
|
98
|
+
"--output",
|
|
99
|
+
type=Path,
|
|
100
|
+
help="Write the profile here, for the calculator's Import",
|
|
101
|
+
)
|
|
102
|
+
sub.add_argument(
|
|
103
|
+
"--policy",
|
|
104
|
+
type=Path,
|
|
105
|
+
help="A fitted policy for the calculator to show and price on this workload",
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
command("check", "Validate threads and labels and summarize them")
|
|
109
|
+
|
|
110
|
+
sub = command(
|
|
111
|
+
"packets", "Write what a labeller may see for a sample of runs", labels=False
|
|
112
|
+
)
|
|
113
|
+
sub.add_argument("-o", "--output", type=Path, default=Path("packets.jsonl"))
|
|
114
|
+
sub.add_argument("--sample", type=int, default=200, help="How many runs to label")
|
|
115
|
+
sub.add_argument("--seed", default="0")
|
|
116
|
+
|
|
117
|
+
text = "Read the conversations kept in Langfuse, MLflow or an OpenTelemetry export into a threads file"
|
|
118
|
+
sub = commands.add_parser("pull", help=text, description=text)
|
|
119
|
+
sub.add_argument("source", choices=["langfuse", "mlflow", "otel"])
|
|
120
|
+
sub.add_argument(
|
|
121
|
+
"export",
|
|
122
|
+
nargs="?",
|
|
123
|
+
type=Path,
|
|
124
|
+
help="A file already exported, read instead of the API. Needed for otel",
|
|
125
|
+
)
|
|
126
|
+
sub.add_argument("-o", "--output", type=Path, default=Path("threads.jsonl.gz"))
|
|
127
|
+
sub.add_argument("--days", type=float, default=30, help="How far back to read")
|
|
128
|
+
sub.add_argument("--since", help="Read from this time instead")
|
|
129
|
+
sub.add_argument("--until", help="Read up to this time")
|
|
130
|
+
sub.add_argument("--environment", help="Only this Langfuse environment")
|
|
131
|
+
sub.add_argument(
|
|
132
|
+
"--tag",
|
|
133
|
+
action="append",
|
|
134
|
+
default=[],
|
|
135
|
+
help="Only traces with this tag. Repeat for any of several",
|
|
136
|
+
)
|
|
137
|
+
sub.add_argument(
|
|
138
|
+
"--filter",
|
|
139
|
+
help="More conditions: a Langfuse filter in JSON, or an MLflow filter string",
|
|
140
|
+
)
|
|
141
|
+
sub.add_argument(
|
|
142
|
+
"--tracking-uri", help="The MLflow server. Left out, MLFLOW_TRACKING_URI"
|
|
143
|
+
)
|
|
144
|
+
sub.add_argument(
|
|
145
|
+
"--experiment",
|
|
146
|
+
action="append",
|
|
147
|
+
default=[],
|
|
148
|
+
help="An MLflow experiment ID. Repeat for several. Left out, experiment 0",
|
|
149
|
+
)
|
|
150
|
+
sub.add_argument(
|
|
151
|
+
"--rows",
|
|
152
|
+
type=Path,
|
|
153
|
+
help="The same as the export file: observations or traces as JSON or JSONL",
|
|
154
|
+
)
|
|
155
|
+
sub.add_argument("--json", action="store_true", help="Print JSON")
|
|
156
|
+
|
|
157
|
+
text = "Write the policy for the default workload, to start from before there is a record"
|
|
158
|
+
sub = commands.add_parser("default", help=text, description=text)
|
|
159
|
+
sub.add_argument(
|
|
160
|
+
"--model",
|
|
161
|
+
required=True,
|
|
162
|
+
help=f"A known model ({', '.join(known_models())}) or a JSON file of model spec fields",
|
|
163
|
+
)
|
|
164
|
+
sub.add_argument("-o", "--output", type=Path, default=Path("policy.json"))
|
|
165
|
+
sub.add_argument("--json", action="store_true", help="Print JSON")
|
|
166
|
+
|
|
167
|
+
text = "Run compache behind a base URL: apply a policy, keep a record, or both"
|
|
168
|
+
sub = commands.add_parser("proxy", help=text, description=text)
|
|
169
|
+
sub.add_argument("--policy", type=Path, help="A fitted policy to apply")
|
|
170
|
+
sub.add_argument(
|
|
171
|
+
"--record",
|
|
172
|
+
type=Path,
|
|
173
|
+
help="A folder to record conversations in, without their text",
|
|
174
|
+
)
|
|
175
|
+
sub.add_argument(
|
|
176
|
+
"--sample",
|
|
177
|
+
type=float,
|
|
178
|
+
default=0.0,
|
|
179
|
+
help="Share of turns whose reply is asked what it needed. Needs --record",
|
|
180
|
+
)
|
|
181
|
+
sub.add_argument(
|
|
182
|
+
"--notes",
|
|
183
|
+
choices=["apart", "inline"],
|
|
184
|
+
default="apart",
|
|
185
|
+
help="Ask in a short request of its own after the reply, or in the reply itself",
|
|
186
|
+
)
|
|
187
|
+
sub.add_argument("--host", default="127.0.0.1")
|
|
188
|
+
sub.add_argument("--port", type=int, default=8787)
|
|
189
|
+
sub.add_argument(
|
|
190
|
+
"--upstream", help="One base URL to forward everything to, such as a gateway's"
|
|
191
|
+
)
|
|
192
|
+
sub.add_argument(
|
|
193
|
+
"--openai-url", help="Where OpenAI's API goes instead of api.openai.com"
|
|
194
|
+
)
|
|
195
|
+
sub.add_argument(
|
|
196
|
+
"--anthropic-url",
|
|
197
|
+
help="Where Anthropic's API goes instead of api.anthropic.com",
|
|
198
|
+
)
|
|
199
|
+
sub.add_argument("--gemini-url", help="Where Gemini's API goes instead of Google's")
|
|
200
|
+
|
|
201
|
+
listing = commands.add_parser(
|
|
202
|
+
"models", help="List the models with a built-in price sheet"
|
|
203
|
+
)
|
|
204
|
+
listing.add_argument("--json", action="store_true", help="Print JSON")
|
|
205
|
+
return parser
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _header(args) -> dict:
|
|
209
|
+
options = {}
|
|
210
|
+
if args.system_prompt:
|
|
211
|
+
options["system_prompt"] = args.system_prompt.read_text("utf-8")
|
|
212
|
+
if args.tools:
|
|
213
|
+
options["tools"] = json.loads(args.tools.read_text("utf-8"))
|
|
214
|
+
return options
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _write(path: Path, value) -> None:
|
|
218
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
219
|
+
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", "utf-8")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _money(costs, key) -> str:
|
|
223
|
+
return (
|
|
224
|
+
f"${costs[key]:,.2f}"
|
|
225
|
+
if costs["unit"] == "USD"
|
|
226
|
+
else f"{costs[key]:,.0f} input tokens"
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _fit(args):
|
|
231
|
+
policy = fit(
|
|
232
|
+
args.threads,
|
|
233
|
+
args.labels,
|
|
234
|
+
model=args.model,
|
|
235
|
+
observed_until=args.observed_until,
|
|
236
|
+
**_header(args),
|
|
237
|
+
)
|
|
238
|
+
policy.save(args.output)
|
|
239
|
+
summary = policy.summary
|
|
240
|
+
labelled = (
|
|
241
|
+
f" ({summary['labelled_turns']:,} labelled)"
|
|
242
|
+
if summary["labelled_turns"]
|
|
243
|
+
else ""
|
|
244
|
+
)
|
|
245
|
+
resent = history_resent(load_threads(args.threads), policy.spec)
|
|
246
|
+
text = "\n".join(
|
|
247
|
+
[
|
|
248
|
+
f"Fitted on {summary['threads']:,} threads, {summary['turns']:,} turns{labelled} "
|
|
249
|
+
f"for {summary['model']}.",
|
|
250
|
+
"",
|
|
251
|
+
policy.describe(),
|
|
252
|
+
*_trimmed(resent),
|
|
253
|
+
"",
|
|
254
|
+
f"Wrote {args.output}",
|
|
255
|
+
]
|
|
256
|
+
)
|
|
257
|
+
return {"output": str(args.output), **summary}, text
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _demo(args):
|
|
261
|
+
with resources.as_file(resources.files(__package__).joinpath("demo")) as sample:
|
|
262
|
+
policy = fit(
|
|
263
|
+
sample / "threads.jsonl.gz", sample / "labels.jsonl", model=args.model
|
|
264
|
+
)
|
|
265
|
+
if args.output is not None:
|
|
266
|
+
policy.save(args.output)
|
|
267
|
+
summary = policy.summary
|
|
268
|
+
text = "\n".join(
|
|
269
|
+
[
|
|
270
|
+
f"Fitted on {summary['threads']:,} sample threads, {summary['turns']:,} turns "
|
|
271
|
+
f"({summary['labelled_turns']:,} labelled) for {summary['model']}.",
|
|
272
|
+
"",
|
|
273
|
+
policy.describe(),
|
|
274
|
+
"",
|
|
275
|
+
f"Wrote {args.output}"
|
|
276
|
+
if args.output is not None
|
|
277
|
+
else "Not kept. Give -o to keep it.",
|
|
278
|
+
"Your own: compache fit threads.jsonl --labels labels.jsonl",
|
|
279
|
+
]
|
|
280
|
+
)
|
|
281
|
+
return summary, text
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _replay(args):
|
|
285
|
+
report = replay(
|
|
286
|
+
Policy.load(args.policy),
|
|
287
|
+
args.threads,
|
|
288
|
+
args.labels,
|
|
289
|
+
observed_until=args.observed_until,
|
|
290
|
+
)
|
|
291
|
+
detail = report.pop("detail")
|
|
292
|
+
if args.output:
|
|
293
|
+
_write(args.output, {**report, "detail": detail})
|
|
294
|
+
lines = [f"{report['threads']:,} threads, {report['planned_turns']:,} turns."]
|
|
295
|
+
costs = report["cost_per_1000_turns"]
|
|
296
|
+
if report["saving"] is None:
|
|
297
|
+
lines.append(
|
|
298
|
+
"Some requests did not fit the model: the policy answers "
|
|
299
|
+
f"{report['policy_turns']:,} turns and keeping everything {report['baseline_turns']:,}."
|
|
300
|
+
)
|
|
301
|
+
common = report["common_prefix"]
|
|
302
|
+
if common["turns"]:
|
|
303
|
+
paired = common["cost_per_1000_turns"]
|
|
304
|
+
lines.append(
|
|
305
|
+
f"On the {common['turns']:,} turns both answer: {_money(paired, 'policy')} per 1,000 turns "
|
|
306
|
+
f"with the policy against {_money(paired, 'keep_everything')} keeping everything."
|
|
307
|
+
)
|
|
308
|
+
else:
|
|
309
|
+
lines.append(
|
|
310
|
+
f"{_money(costs, 'policy')} per 1,000 turns with the policy against "
|
|
311
|
+
f"{_money(costs, 'keep_everything')} keeping everything: {report['saving']:.0%} less."
|
|
312
|
+
)
|
|
313
|
+
if report["coverage"] is not None:
|
|
314
|
+
lines.append(
|
|
315
|
+
f"{report['coverage']:.0%} of the {report['needs_history']:,} labelled needs for earlier "
|
|
316
|
+
f"context are in view. {report['tokens_kept']:.0%} of the history tokens are kept."
|
|
317
|
+
)
|
|
318
|
+
lines.append(f"{report['pings']:,} keep-warm pings sent.")
|
|
319
|
+
return report, "\n".join(lines)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _trimmed(resent) -> list[str]:
|
|
323
|
+
"""A warning for an app that already leaves earlier text out of its requests."""
|
|
324
|
+
if resent is None or resent >= 0.8:
|
|
325
|
+
return []
|
|
326
|
+
return [
|
|
327
|
+
f"Its requests carried {resent:.0%} of the conversation so far: the app already leaves "
|
|
328
|
+
"earlier text out, so keeping everything costs more than it pays today."
|
|
329
|
+
]
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _describe(measured) -> list[str]:
|
|
333
|
+
tokens, lengths = measured["tokens_per_turn"], measured["turns_per_thread"]
|
|
334
|
+
lines = [
|
|
335
|
+
f"{measured['threads']:,} threads, {measured['turns']:,} turns.",
|
|
336
|
+
"Tokens per turn, median (95th percentile): "
|
|
337
|
+
+ ", ".join(
|
|
338
|
+
f"{name} {tokens[kind]['median']:,} ({tokens[kind]['p95']:,})"
|
|
339
|
+
for kind, name in (
|
|
340
|
+
("input", "question"),
|
|
341
|
+
("retrieval", "retrieved"),
|
|
342
|
+
("output", "answer"),
|
|
343
|
+
)
|
|
344
|
+
)
|
|
345
|
+
+ ".",
|
|
346
|
+
f"Turns per thread: {lengths['median']} ({lengths['p95']}).",
|
|
347
|
+
]
|
|
348
|
+
if 0 < measured["turns_that_retrieve"] < 1:
|
|
349
|
+
lines.append(
|
|
350
|
+
f"Turns that retrieve anything: {measured['turns_that_retrieve']:.0%}."
|
|
351
|
+
)
|
|
352
|
+
if lengths["law"] == "continuation":
|
|
353
|
+
another = lengths["another_turn"]
|
|
354
|
+
lines.append(
|
|
355
|
+
f"Chance of another turn: {another['after_first']:.0%} after turn 1, "
|
|
356
|
+
f"{another['in_long_threads']:.0%} in long threads, halfway by turn {1 + another['half_turn']:g}. "
|
|
357
|
+
f"{lengths['one_turn_share']:.0%} of threads are one turn."
|
|
358
|
+
)
|
|
359
|
+
if measured["idle_minutes"]:
|
|
360
|
+
idle = measured["idle_minutes"]
|
|
361
|
+
where = " in long threads" if idle["half_turn"] else ""
|
|
362
|
+
lines.append(
|
|
363
|
+
f"Minutes away between turns{where}: {idle['median']:.1f} ({idle['p95']:.1f})."
|
|
364
|
+
)
|
|
365
|
+
if idle["half_turn"]:
|
|
366
|
+
lines.append(
|
|
367
|
+
f" after turn 1 the wait is {idle['first_factor']:.1f} times that, "
|
|
368
|
+
f"halfway by turn {1 + idle['half_turn']:g}."
|
|
369
|
+
)
|
|
370
|
+
if idle["break_share"]:
|
|
371
|
+
lines.append(
|
|
372
|
+
f" {idle['break_share']:.0%} of returns follow a long break, "
|
|
373
|
+
f"median {idle['break_median'] / 60:.1f} hours."
|
|
374
|
+
)
|
|
375
|
+
extras = []
|
|
376
|
+
if measured["answer_seconds"]:
|
|
377
|
+
extras.append(f"an answer takes {measured['answer_seconds']:.0f} s")
|
|
378
|
+
if measured["calls_per_turn"] and measured["calls_per_turn"] > 1:
|
|
379
|
+
extras.append(f"{measured['calls_per_turn']:.1f} model calls a turn")
|
|
380
|
+
if measured["reasoning_tokens"]:
|
|
381
|
+
extras.append(
|
|
382
|
+
f"{measured['reasoning_tokens']:,} output tokens an answer are billed beyond its text"
|
|
383
|
+
)
|
|
384
|
+
if measured["cache_read_when_live"] is not None:
|
|
385
|
+
extras.append(
|
|
386
|
+
f"a request still in the cache was read to {measured['cache_read_when_live']:.0%} by the next turn"
|
|
387
|
+
)
|
|
388
|
+
if measured["prompt_warmed_by_others"]:
|
|
389
|
+
extras.append(
|
|
390
|
+
f"another thread was active within the cache lifetime at "
|
|
391
|
+
f"{measured['prompt_warmed_by_others']:.0%} of cold starts"
|
|
392
|
+
)
|
|
393
|
+
if extras:
|
|
394
|
+
lines.append("Also: " + ", ".join(extras) + ".")
|
|
395
|
+
lines += _trimmed(measured["history_resent"])
|
|
396
|
+
if measured["needs"]:
|
|
397
|
+
share = measured["turns_needing_history"] / measured["assessed_turns"]
|
|
398
|
+
lines.append(
|
|
399
|
+
f"Labels: {measured['labelled_turns']:,} turns. Of the {measured['assessed_turns']:,} "
|
|
400
|
+
f"assessed after a thread's first turn, {share:.0%} need earlier context."
|
|
401
|
+
)
|
|
402
|
+
for kind, name in (
|
|
403
|
+
("input", "questions"),
|
|
404
|
+
("retrieval", "retrieved text"),
|
|
405
|
+
("output", "answers"),
|
|
406
|
+
):
|
|
407
|
+
found = measured["needs"][kind]
|
|
408
|
+
if found["turns_back"]:
|
|
409
|
+
back = found["turns_back"]
|
|
410
|
+
lines.append(
|
|
411
|
+
f" earlier {name}: {found['share_of_turns']:.0%} of turns, "
|
|
412
|
+
f"median {back['median']} back (95th percentile {back['p95']})."
|
|
413
|
+
)
|
|
414
|
+
elif measured["labelled_turns"]:
|
|
415
|
+
lines.append(f"Labels: {measured['labelled_turns']:,} turns, none assessed.")
|
|
416
|
+
return lines
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _profile(args):
|
|
420
|
+
result = profile(
|
|
421
|
+
args.threads,
|
|
422
|
+
args.labels,
|
|
423
|
+
model=args.model,
|
|
424
|
+
policy=args.policy,
|
|
425
|
+
**_header(args),
|
|
426
|
+
)
|
|
427
|
+
if args.output:
|
|
428
|
+
_write(args.output, result)
|
|
429
|
+
lines = _describe(result["measured"]) + result["notes"]
|
|
430
|
+
lines += ["", "Open the calculator with this workload:", result["link"]]
|
|
431
|
+
if args.output:
|
|
432
|
+
lines.append(f"Wrote {args.output}")
|
|
433
|
+
return result, "\n".join(lines)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _check(args):
|
|
437
|
+
threads = load_threads(args.threads)
|
|
438
|
+
if args.labels:
|
|
439
|
+
labels = list(read_jsonl(args.labels))
|
|
440
|
+
else:
|
|
441
|
+
# A record folder carries its own labels.
|
|
442
|
+
labels = load_record(args.threads)[1] if is_record(args.threads) else []
|
|
443
|
+
# Building the index validates every label against what its run could see.
|
|
444
|
+
label_index(threads, labels)
|
|
445
|
+
measured = measure(threads, ModelSpec(threads[0].runs[0].generation.model), labels)
|
|
446
|
+
return {"valid": True, **measured}, "\n".join(["Valid."] + _describe(measured))
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _packets(args):
|
|
450
|
+
threads = load_threads(args.threads)
|
|
451
|
+
candidates = [(t, r) for t in threads for r in t.runs if r.run_index > 1]
|
|
452
|
+
|
|
453
|
+
def rank(pair):
|
|
454
|
+
thread, run = pair
|
|
455
|
+
return hashlib.sha256(
|
|
456
|
+
f"{args.seed}:{thread.thread_id}:{run.run_id}".encode()
|
|
457
|
+
).hexdigest()
|
|
458
|
+
|
|
459
|
+
chosen = sorted(
|
|
460
|
+
sorted(candidates, key=rank)[: max(0, args.sample)],
|
|
461
|
+
key=lambda p: (p[0].thread_id, p[1].run_index),
|
|
462
|
+
)
|
|
463
|
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
464
|
+
with args.output.open("w", encoding="utf-8") as stream:
|
|
465
|
+
for thread, run in chosen:
|
|
466
|
+
stream.write(
|
|
467
|
+
json.dumps(build_packet(thread, run.run_id), ensure_ascii=False) + "\n"
|
|
468
|
+
)
|
|
469
|
+
result = {
|
|
470
|
+
"output": str(args.output),
|
|
471
|
+
"packets": len(chosen),
|
|
472
|
+
"runs": len(candidates),
|
|
473
|
+
}
|
|
474
|
+
return result, f"Wrote {len(chosen):,} of {len(candidates):,} runs to {args.output}"
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _exported(path: Path) -> list:
|
|
478
|
+
"""Observation rows from an export: a JSON list, an API response, or JSONL."""
|
|
479
|
+
opener = gzip.open if path.name.endswith(".gz") else open
|
|
480
|
+
with opener(path, "rt", encoding="utf-8") as stream:
|
|
481
|
+
text = stream.read()
|
|
482
|
+
try:
|
|
483
|
+
data = json.loads(text)
|
|
484
|
+
except json.JSONDecodeError:
|
|
485
|
+
return [json.loads(line) for line in text.splitlines() if line.strip()]
|
|
486
|
+
if isinstance(data, dict):
|
|
487
|
+
# An API response: Langfuse keeps its rows under `data`, MLflow its traces under `traces`.
|
|
488
|
+
return data.get("data") or data.get("traces") or [data]
|
|
489
|
+
return data
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
_LEFT_OUT = (
|
|
493
|
+
(
|
|
494
|
+
"calls_recorded_twice",
|
|
495
|
+
"{:,} model calls were recorded twice and are counted once.",
|
|
496
|
+
),
|
|
497
|
+
(
|
|
498
|
+
"helper_calls",
|
|
499
|
+
"{:,} model calls outside the conversation, such as a query rewriter, are left out.",
|
|
500
|
+
),
|
|
501
|
+
(
|
|
502
|
+
"turns_with_pasted_retrieval",
|
|
503
|
+
"In {:,} turns the retrieved text was pasted into the prompt. It is read as retrieved text.",
|
|
504
|
+
),
|
|
505
|
+
(
|
|
506
|
+
"threads_read_trace_by_trace",
|
|
507
|
+
"{:,} threads were read trace by trace, as their model calls do not carry the conversation.",
|
|
508
|
+
),
|
|
509
|
+
(
|
|
510
|
+
"threads_with_trimmed_history",
|
|
511
|
+
"In {:,} threads the app did not resend the whole history, so keeping everything is not what it does today.",
|
|
512
|
+
),
|
|
513
|
+
(
|
|
514
|
+
"overlapping_turns",
|
|
515
|
+
"{:,} turns began before the answer to the one before. They are read one after the other.",
|
|
516
|
+
),
|
|
517
|
+
(
|
|
518
|
+
"sessions_begun_earlier",
|
|
519
|
+
"{:,} sessions began before the first row read. Read further back to include them.",
|
|
520
|
+
),
|
|
521
|
+
(
|
|
522
|
+
"sessions_without_text",
|
|
523
|
+
"{:,} sessions have model calls without their text. Record prompts and answers to use them.",
|
|
524
|
+
),
|
|
525
|
+
("sessions_unreadable", "{:,} sessions could not be rebuilt into turns."),
|
|
526
|
+
(
|
|
527
|
+
"traces_without_session",
|
|
528
|
+
"{:,} traces have no session ID, and a thread needs one.",
|
|
529
|
+
),
|
|
530
|
+
)
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _pull(args):
|
|
534
|
+
export = args.rows or args.export
|
|
535
|
+
window = dict(since=args.since, until=args.until, days=args.days)
|
|
536
|
+
if args.source == "otel":
|
|
537
|
+
from .otel import pull
|
|
538
|
+
|
|
539
|
+
if export is None:
|
|
540
|
+
raise ContractError(
|
|
541
|
+
"pull otel reads an export file: compache pull otel spans.jsonl"
|
|
542
|
+
)
|
|
543
|
+
threads, report = pull(export, until=args.until)
|
|
544
|
+
elif args.source == "mlflow":
|
|
545
|
+
from .mlflow import pull
|
|
546
|
+
|
|
547
|
+
if export is not None:
|
|
548
|
+
threads, report = pull(traces=_exported(export), until=args.until)
|
|
549
|
+
else:
|
|
550
|
+
threads, report = pull(
|
|
551
|
+
tracking_uri=args.tracking_uri,
|
|
552
|
+
experiment_ids=args.experiment or ["0"],
|
|
553
|
+
filter=args.filter,
|
|
554
|
+
**window,
|
|
555
|
+
)
|
|
556
|
+
else:
|
|
557
|
+
from .langfuse import pull
|
|
558
|
+
|
|
559
|
+
if export is not None:
|
|
560
|
+
threads, report = pull(rows=_exported(export), **window)
|
|
561
|
+
else:
|
|
562
|
+
conditions = json.loads(args.filter) if args.filter else []
|
|
563
|
+
threads, report = pull(
|
|
564
|
+
environment=args.environment,
|
|
565
|
+
tags=args.tag,
|
|
566
|
+
filters=conditions if isinstance(conditions, list) else [conditions],
|
|
567
|
+
**window,
|
|
568
|
+
)
|
|
569
|
+
rows = "observations" if args.source == "langfuse" else "spans"
|
|
570
|
+
lines = [
|
|
571
|
+
f"Read {report.get('observations', 0):,} {rows}: {report.get('model_calls', 0):,} "
|
|
572
|
+
f"model calls in {report.get('sessions', 0):,} sessions."
|
|
573
|
+
]
|
|
574
|
+
notes = [text.format(report[key]) for key, text in _LEFT_OUT if report.get(key)]
|
|
575
|
+
if not threads:
|
|
576
|
+
raise ContractError(" ".join(lines + notes + ["No thread could be read."]))
|
|
577
|
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
578
|
+
opener = gzip.open if args.output.name.endswith(".gz") else open
|
|
579
|
+
with opener(args.output, "wt", encoding="utf-8") as stream:
|
|
580
|
+
for thread in threads:
|
|
581
|
+
stream.write(json.dumps(thread, ensure_ascii=False) + "\n")
|
|
582
|
+
lines.append(
|
|
583
|
+
f"Wrote {report['threads']:,} threads, {report['turns']:,} turns to {args.output}."
|
|
584
|
+
)
|
|
585
|
+
lines += notes
|
|
586
|
+
if report["models"]:
|
|
587
|
+
lines.append(
|
|
588
|
+
"Answered by "
|
|
589
|
+
+ ", ".join(
|
|
590
|
+
f"{name} ({count:,} calls)" for name, count in report["models"].items()
|
|
591
|
+
)
|
|
592
|
+
+ "."
|
|
593
|
+
)
|
|
594
|
+
if len(report["models"]) > 1:
|
|
595
|
+
lines.append(
|
|
596
|
+
"A fit prices every thread as one model: the most common, unless --model names another. "
|
|
597
|
+
"To fit one app of several, narrow the read with --tag or --environment."
|
|
598
|
+
)
|
|
599
|
+
lines += ["", f"Next: compache fit {args.output}"]
|
|
600
|
+
return {"output": str(args.output), **report}, "\n".join(lines)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def _default(args):
|
|
604
|
+
policy = default_policy(args.model)
|
|
605
|
+
policy.save(args.output)
|
|
606
|
+
summary = policy.summary
|
|
607
|
+
lines = [
|
|
608
|
+
f"Fitted to the default workload, not to yours, for {summary['model']}.",
|
|
609
|
+
"",
|
|
610
|
+
policy.describe(),
|
|
611
|
+
"",
|
|
612
|
+
f"Wrote {args.output}",
|
|
613
|
+
"Next: apply it and record your own traffic, then fit on the record.",
|
|
614
|
+
]
|
|
615
|
+
return summary, "\n".join(lines)
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def _models(args):
|
|
619
|
+
models = _sheet()["models"]
|
|
620
|
+
lines = [f"Prices per million tokens, checked {_sheet()['checked']}."]
|
|
621
|
+
for model_id, entry in models.items():
|
|
622
|
+
seconds = [entry["cache_ttl_seconds"]] + [
|
|
623
|
+
other["seconds"] for other in entry.get("cache_lifetimes", ())
|
|
624
|
+
]
|
|
625
|
+
lasting = [f"{s // 60} min" if s < 3600 else f"{s / 3600:g} h" for s in seconds]
|
|
626
|
+
lines.append(
|
|
627
|
+
f"{model_id:<20} input ${entry['input_price']:g}, cache read ${entry['cache_read_price']:g}, "
|
|
628
|
+
f"output ${entry['output_price']:g}, cache {' or '.join(lasting)}"
|
|
629
|
+
)
|
|
630
|
+
return models, "\n".join(lines)
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
_COMMANDS = {
|
|
634
|
+
"fit": _fit,
|
|
635
|
+
"demo": _demo,
|
|
636
|
+
"replay": _replay,
|
|
637
|
+
"profile": _profile,
|
|
638
|
+
"check": _check,
|
|
639
|
+
"packets": _packets,
|
|
640
|
+
"pull": _pull,
|
|
641
|
+
"default": _default,
|
|
642
|
+
"models": _models,
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def main(argv: list[str] | None = None) -> int:
|
|
647
|
+
args = _parser().parse_args(argv)
|
|
648
|
+
if args.command == "proxy":
|
|
649
|
+
# Runs until interrupted, so it is imported and started apart from the commands that report.
|
|
650
|
+
from .proxy import main as run_proxy
|
|
651
|
+
|
|
652
|
+
try:
|
|
653
|
+
return run_proxy(args)
|
|
654
|
+
except (ContractError, OSError, ValueError) as exc:
|
|
655
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
656
|
+
return 1
|
|
657
|
+
try:
|
|
658
|
+
result, text = _COMMANDS[args.command](args)
|
|
659
|
+
except (ContractError, OSError, json.JSONDecodeError) as exc:
|
|
660
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
661
|
+
return 1
|
|
662
|
+
print(
|
|
663
|
+
json.dumps(result, ensure_ascii=False) if getattr(args, "json", False) else text
|
|
664
|
+
)
|
|
665
|
+
return 0
|