downshift-llm 0.4.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.
downshift/cli.py ADDED
@@ -0,0 +1,556 @@
1
+ """downshift: every model change, proven on your own traffic."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import sys
6
+ from datetime import date
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+ import typer
11
+
12
+ from . import pricing
13
+ from .cluster import cluster_records
14
+ from .engine import estimate_replay_cost, sample_clusters
15
+ from .engine import run as run_engine
16
+ from .gate import calibrate as calibrate_judge
17
+ from .gate import run_gate
18
+ from .ingest import load_logs, save_records
19
+ from .judge import get_judge
20
+ from .report import write_report
21
+ from .router import Router, export_routes
22
+
23
+ app = typer.Typer(add_completion=False, help=__doc__, no_args_is_help=True)
24
+
25
+
26
+ def _say(msg: str) -> None:
27
+ typer.echo(msg, err=True)
28
+
29
+
30
+ def _analyse(records, logs: Path, candidates: list[str], out: Path, *, sample=50, threshold=0.9, k=None,
31
+ group_by="auto", judge_model=None, prices=None, days=30.0, monthly_requests=None, yes=False,
32
+ require_cheaper=True, mode="optimize", quiet=False, max_cost=None, use_cache=True):
33
+ from .cache import ReplayCache
34
+ from .providers import set_cache
35
+
36
+ out.mkdir(parents=True, exist_ok=True)
37
+ cache = ReplayCache() if use_cache else None
38
+ set_cache(cache)
39
+ overrides = pricing.load_overrides(prices)
40
+ cluster_ids, cmodel = cluster_records(records, k=k, group_by=group_by)
41
+ _say(f"Found {len(cmodel.names)} task types: {', '.join(cmodel.names.values())}")
42
+
43
+ missing = pricing.check_known(list(candidates) + [r.model for r in records], overrides)
44
+ if missing:
45
+ _say("No price known for: " + ", ".join(missing) + "\nAdd them to a prices file (USD or your currency "
46
+ "per 1M tokens) and pass --prices prices.json. Example entry:\n"
47
+ f' "{missing[0]}": {{"input": 1.0, "output": 2.0}}')
48
+ raise typer.Exit(2)
49
+ samples = sample_clusters(records, cluster_ids, sample)
50
+ est = estimate_replay_cost(samples, candidates, overrides)
51
+ n = sum(len(v) for v in samples.values()) * len(candidates)
52
+ _say(f"Replaying {n} calls on {len(candidates)} candidate(s); estimated cost ${est:.2f} (+ judge calls)"
53
+ + ("; cached answers are reused for free" if cache else ""))
54
+ if max_cost is not None and est > max_cost:
55
+ _say(f"Stopped: estimated cost ${est:.2f} is above --max-cost ${max_cost:.2f}. "
56
+ "Lower --sample or test fewer candidates.")
57
+ raise typer.Exit(2)
58
+ if not yes and not all(c.startswith("mock/") for c in candidates):
59
+ typer.confirm("Continue?", abort=True)
60
+
61
+ answers: list[dict] = []
62
+ result, samples = run_engine(records, cluster_ids, cmodel.names, candidates, get_judge(judge_model), overrides,
63
+ per_cluster=sample, threshold=threshold, assume_days=days,
64
+ monthly_requests=monthly_requests, require_cheaper=require_cheaper, mode=mode,
65
+ progress=None if quiet else (lambda m: _say(f" · {m}")), answers=answers)
66
+ result.logs_path = str(logs.resolve())
67
+ if cache and (cache.hits or cache.misses):
68
+ _say(f"Replay cache: {cache.hits} reused, {cache.misses} new calls")
69
+
70
+ evalset = []
71
+ for cid, recs in samples.items():
72
+ for r in recs:
73
+ r.meta["downshift_cluster"] = cid
74
+ evalset.append(r)
75
+ save_records(evalset, out / "evalset.jsonl")
76
+ with open(out / "answers.jsonl", "w", encoding="utf-8") as fh:
77
+ for a in answers:
78
+ fh.write(json.dumps(a) + "\n")
79
+ (out / "assignments.json").write_text(json.dumps({r.id: c for r, c in zip(records, cluster_ids)}), encoding="utf-8")
80
+ (out / "results.json").write_text(json.dumps(result.to_dict(), indent=2), encoding="utf-8")
81
+ export_routes(result, cmodel, out)
82
+ write_report(result, out / "report.html")
83
+ from .audit import write_change_record
84
+
85
+ write_change_record(out, result, logs_path=result.logs_path, candidates=candidates,
86
+ judge=get_judge(judge_model).name)
87
+ return result
88
+
89
+
90
+ def _print_summary(result, out: Path) -> None:
91
+ from rich.console import Console
92
+ from rich.table import Table
93
+
94
+ console = Console(highlight=False)
95
+ pct = 100 * result.monthly_savings / result.baseline_monthly_cost if result.baseline_monthly_cost else 0
96
+ console.print(f"\n[bold]Projected savings:[/bold] [bold green]${result.monthly_savings:,.0f}/month[/bold green] "
97
+ f"({pct:.0f}% of ${result.baseline_monthly_cost:,.0f})")
98
+ table = Table(show_header=True, header_style="bold", box=None, pad_edge=False)
99
+ for col, kw in (("Verdict", {}), ("Task type", {}), ("Today", {}), ("Route", {}), ("Saves/mo", {"justify": "right"})):
100
+ table.add_column(col, **kw)
101
+ colors = {"SAFE": "green", "RISKY": "yellow", "KEEP": "dim"}
102
+ for c in sorted(result.clusters, key=lambda c: -c.monthly_savings):
103
+ route = c.recommended_model if c.recommended_model != c.baseline_model else "stay"
104
+ table.add_row(f"[{colors[c.recommended_verdict]}]{c.recommended_verdict}[/]", c.name, c.baseline_model,
105
+ route, f"${c.monthly_savings:,.0f}")
106
+ console.print(table)
107
+ if result.tasks:
108
+ t = result.tasks
109
+ console.print(f"[bold]Agent cost per completed task:[/bold] ${t.baseline_cost_per_task:.4f} -> "
110
+ f"${t.projected_cost_per_task:.4f} incl. retries (naive: ${t.naive_cost_per_task:.4f})")
111
+ console.print(f"Report: {out / 'report.html'}")
112
+
113
+
114
+ @app.command()
115
+ def run(
116
+ logs: Path = typer.Argument(..., exists=True, help="JSONL log file"),
117
+ candidates: str = typer.Option(..., "--candidates", "-c", help="Comma-separated models to test"),
118
+ out: Path = typer.Option(Path("downshift-out"), "--out", "-o"),
119
+ sample: int = typer.Option(50, help="Requests sampled per task type"),
120
+ threshold: float = typer.Option(0.9, help="Min 95%-lower-bound 'no worse' rate for SAFE"),
121
+ k: Optional[int] = typer.Option(None, help="Number of task clusters (default: auto)"),
122
+ group_by: str = typer.Option("auto", help="auto (cluster prompts) | task (meta.task) | step (agent steps)"),
123
+ judge_model: Optional[str] = typer.Option(None, "--judge", help="Model for pairwise judging of free text"),
124
+ prices: Optional[Path] = typer.Option(None, help="JSON file of prices per 1M tokens"),
125
+ days: float = typer.Option(30.0, help="Days the logs cover, if they have no timestamps"),
126
+ monthly_requests: Optional[float] = typer.Option(None, help="Override monthly request volume"),
127
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip the cost confirmation"),
128
+ max_cost: Optional[float] = typer.Option(None, help="Stop before replaying if the estimate exceeds this, in USD"),
129
+ no_cache: bool = typer.Option(False, "--no-cache", help="Call every model fresh instead of reusing answers"),
130
+ ):
131
+ """Prove which task types (and agent steps) can move to cheaper models."""
132
+ records = load_logs(logs)
133
+ _say(f"Loaded {len(records)} requests from {logs}")
134
+ result = _analyse(records, logs, [c.strip() for c in candidates.split(",") if c.strip()], out, sample=sample,
135
+ threshold=threshold, k=k, group_by=group_by, judge_model=judge_model, prices=prices,
136
+ days=days, monthly_requests=monthly_requests, yes=yes, max_cost=max_cost,
137
+ use_cache=not no_cache)
138
+ _print_summary(result, out)
139
+ typer.echo(f"LiteLLM config: {out / 'litellm_config.yaml'}\nCI gate: downshift gate {out}")
140
+
141
+
142
+ @app.command()
143
+ def watch(
144
+ logs: Path = typer.Argument(..., exists=True),
145
+ feed: str = typer.Option(..., help="Retirement feed: JSON file path or URL"),
146
+ ):
147
+ """List which models in your logs are being retired, and how soon."""
148
+ from .migrate import load_feed, watch as do_watch
149
+
150
+ rows = do_watch(load_logs(logs), load_feed(feed))
151
+ for r in rows:
152
+ if r["status"] == "no notice":
153
+ typer.echo(f" ok {r['model']:32} {r['share']:>6.1%} of traffic")
154
+ else:
155
+ typer.echo(f" {r['status']:8} {r['model']:32} {r['share']:>6.1%} of traffic shuts down {r['shutdown']}"
156
+ f" ({r['days_left']} days) replacement: {r.get('replacement') or 'see provider'}")
157
+ urgent = [r for r in rows if r["status"] in ("URGENT", "RETIRED", "PLAN")]
158
+ for r in urgent:
159
+ if r.get("replacement"):
160
+ typer.echo(f"\nNext: downshift migrate {logs} --from {r['model']} --to {r['replacement']} "
161
+ f"--deadline {r['shutdown']}")
162
+
163
+
164
+ @app.command()
165
+ def migrate(
166
+ logs: Path = typer.Argument(..., exists=True),
167
+ from_model: str = typer.Option(..., "--from"),
168
+ to_model: str = typer.Option(..., "--to"),
169
+ deadline: Optional[str] = typer.Option(None, help="Shutdown date, YYYY-MM-DD"),
170
+ out: Path = typer.Option(Path("downshift-migration"), "--out", "-o"),
171
+ sample: int = typer.Option(60),
172
+ threshold: float = typer.Option(0.9),
173
+ group_by: str = typer.Option("auto"),
174
+ judge_model: Optional[str] = typer.Option(None, "--judge"),
175
+ prices: Optional[Path] = typer.Option(None),
176
+ yes: bool = typer.Option(False, "--yes", "-y"),
177
+ max_cost: Optional[float] = typer.Option(None, help="Stop before replaying if the estimate exceeds this, in USD"),
178
+ no_cache: bool = typer.Option(False, "--no-cache"),
179
+ ):
180
+ """Prove a forced model replacement before the deadline. Exits 1 if not ready."""
181
+ from .migrate import migration_summary
182
+
183
+ records = [r for r in load_logs(logs) if r.model == from_model]
184
+ if not records:
185
+ raise typer.BadParameter(f"no requests in the logs use {from_model}")
186
+ _say(f"{len(records)} requests use {from_model}")
187
+ result = _analyse(records, logs, [to_model], out, sample=sample, threshold=threshold, group_by=group_by,
188
+ judge_model=judge_model, prices=prices, yes=yes, require_cheaper=False, mode="migrate",
189
+ max_cost=max_cost, use_cache=not no_cache)
190
+ result.migration = {"from": from_model, "to": to_model, "deadline": deadline}
191
+ (out / "results.json").write_text(json.dumps(result.to_dict(), indent=2), encoding="utf-8")
192
+ write_report(result, out / "report.html")
193
+ from .audit import write_change_record
194
+
195
+ write_change_record(out, result, logs_path=result.logs_path, candidates=[to_model],
196
+ judge=get_judge(judge_model).name)
197
+ text, ready = migration_summary(result, from_model, to_model, deadline)
198
+ (out / "migration.md").write_text(text, encoding="utf-8")
199
+ typer.echo(text)
200
+ typer.echo(f"Report: {out / 'report.html'}")
201
+ raise typer.Exit(0 if ready else 1)
202
+
203
+
204
+ @app.command()
205
+ def distill(
206
+ out: Path = typer.Argument(Path("downshift-out"), exists=True),
207
+ logs: Optional[Path] = typer.Option(None, help="Log file (default: the one used by `run`)"),
208
+ min_examples: int = typer.Option(50),
209
+ ):
210
+ """Export fine-tuning datasets for task types no cheap model passed (eval set held out)."""
211
+ from .distill import export
212
+
213
+ for s in export(out, logs, min_examples=min_examples):
214
+ typer.echo(f" {s['task']:28} {s['available']:>6} examples {s['status']}")
215
+ typer.echo(f"\nNext steps: {out / 'distill' / 'README.md'}")
216
+
217
+
218
+ @app.command()
219
+ def gate(
220
+ out: Path = typer.Argument(Path("downshift-out"), exists=True, help="Output folder of a previous run"),
221
+ judge_model: Optional[str] = typer.Option(None, "--judge"),
222
+ prices: Optional[Path] = typer.Option(None),
223
+ threshold: Optional[float] = typer.Option(None),
224
+ require_approval: bool = typer.Option(False, help="Also fail unless the change record is approved and verifies"),
225
+ ):
226
+ """Re-check every switched route; exit 1 if quality regressed (use in CI)."""
227
+ ok, summary = run_gate(out, get_judge(judge_model), pricing.load_overrides(prices), threshold)
228
+ if require_approval:
229
+ from .audit import is_approved
230
+
231
+ approved = is_approved(out)
232
+ ok = ok and approved
233
+ summary += ("\nChange record: approved and verified.\n" if approved else
234
+ "\nChange record: NOT approved or files changed. Run `downshift approve` after review.\n")
235
+ typer.echo(summary)
236
+ raise typer.Exit(0 if ok else 1)
237
+
238
+
239
+ @app.command()
240
+ def ledger(path: Path = typer.Argument(..., exists=True), fee: float = typer.Option(0.15)):
241
+ """Summarise verified savings, shadow checks and automatic reverts from a GuardedRouter ledger."""
242
+ from .guard import summarize_ledger
243
+
244
+ typer.echo(summarize_ledger(path, fee))
245
+
246
+
247
+ @app.command()
248
+ def share(out: Path = typer.Argument(Path("downshift-out"), exists=True),
249
+ domain: Optional[str] = typer.Option(None, help="Optional industry label, e.g. fintech")):
250
+ """Write an anonymised, opt-in Downshift Index contribution (no prompts, no outputs, no names)."""
251
+ from .index import build
252
+
253
+ payload = build(out, domain)
254
+ typer.echo(f"Wrote {len(payload['entries'])} aggregate entries to {out / 'index_contribution.json'}. "
255
+ "Review it before sharing.")
256
+
257
+
258
+ @app.command()
259
+ def labelset(
260
+ out: Path = typer.Argument(Path("downshift-out"), exists=True, help="Output folder of a previous run"),
261
+ n: int = typer.Option(60, help="How many pairs to label (50-100 is a good calibration set)"),
262
+ dest: Path = typer.Option(Path("labels_todo.jsonl"), help="Where to write the pairs"),
263
+ ):
264
+ """Export free-text answer pairs for you to label by hand, then run `calibrate` on them."""
265
+ import random
266
+
267
+ rows = [json.loads(l) for l in (out / "answers.jsonl").read_text(encoding="utf-8").splitlines() if l]
268
+ rows = [r for r in rows if r["kind"] == "text" and r["candidate"].strip() != r["baseline"].strip()]
269
+ if not rows:
270
+ raise typer.BadParameter("no free-text pairs with different answers in this run")
271
+ rng = random.Random(0)
272
+ rng.shuffle(rows)
273
+ with open(dest, "w", encoding="utf-8") as fh:
274
+ for r in rows[:n]:
275
+ a, b = (r["baseline"], r["candidate"]) if rng.random() < 0.5 else (r["candidate"], r["baseline"])
276
+ fh.write(json.dumps({"prompt": r["prompt"], "a": a, "b": b, "human": ""}, ensure_ascii=False) + "\n")
277
+ typer.echo(f"Wrote {min(n, len(rows))} pairs to {dest}.\n"
278
+ "For each line, set \"human\" to \"A\", \"B\" or \"TIE\" (which answer is better), then run:\n"
279
+ f" downshift calibrate {dest} --judge <your judge model>")
280
+
281
+
282
+ @app.command()
283
+ def calibrate(labels: Path = typer.Argument(..., exists=True),
284
+ judge_model: Optional[str] = typer.Option(None, "--judge"),
285
+ record: Optional[Path] = typer.Option(None, help="Run folder whose change record should store this result")):
286
+ """Measure how often the judge agrees with human labels."""
287
+ res = calibrate_judge(labels, get_judge(judge_model))
288
+ if res["n"] == 0:
289
+ typer.echo('No labelled rows yet: set "human" to A, B or TIE on each line first.')
290
+ return
291
+ if record:
292
+ from .audit import _canonical, load, render_md
293
+
294
+ rec = load(record)
295
+ rec["method"]["judge_calibration"] = {"labels": res["n"], "agreement": round(res["agreement"], 4),
296
+ "judge": get_judge(judge_model).name}
297
+ rec["approvals"] = []
298
+ rec["content_sha256"] = _canonical(rec)
299
+ (record / "change_record.json").write_text(json.dumps(rec, indent=2, ensure_ascii=False), encoding="utf-8")
300
+ (record / "change_record.md").write_text(render_md(rec), encoding="utf-8")
301
+ typer.echo(f"Saved to {record / 'change_record.json'} (any earlier approvals were cleared).")
302
+ typer.echo(f"Judge agreement with humans: {res['agreement']:.1%} on {res['n']} labels")
303
+ typer.echo(json.dumps(res["confusion"], indent=2))
304
+ if res["agreement"] < 0.8:
305
+ typer.echo("Warning: below 80% agreement. Don't trust free-text verdicts from this judge yet.")
306
+
307
+
308
+ @app.command()
309
+ def route(out: Path = typer.Argument(..., exists=True), text: str = typer.Argument(...)):
310
+ """Show which model a request would be routed to."""
311
+ typer.echo(Router.load(out).model_for(text))
312
+
313
+
314
+ @app.command(name="import")
315
+ def import_traces(
316
+ src: Path = typer.Argument(..., exists=True, help="Trace export (JSON or JSONL)"),
317
+ fmt: str = typer.Option(..., "--from", help="otel (OpenTelemetry GenAI / OpenInference) | langfuse"),
318
+ dest: Path = typer.Option(Path("imported_logs.jsonl"), "--out", "-o"),
319
+ ):
320
+ """Convert traces you already collect (OpenTelemetry GenAI, OpenInference, Langfuse) into Downshift logs."""
321
+ from .importers import convert
322
+
323
+ n = convert(src, fmt, dest)
324
+ if n == 0:
325
+ typer.echo("No LLM calls with both a prompt and an answer were found. Make sure your tracer records "
326
+ "message content (often off by default).")
327
+ raise typer.Exit(1)
328
+ typer.echo(f"Imported {n} LLM calls -> {dest}\nNext: downshift run {dest} -c <cheaper models>")
329
+
330
+
331
+ @app.command()
332
+ def serve(
333
+ log: Path = typer.Option(Path("traffic.jsonl"), help="Where every proxied call is logged"),
334
+ routes: Optional[Path] = typer.Option(None, help="Run folder to route with (omit for record-only mode)"),
335
+ host: str = typer.Option("127.0.0.1"),
336
+ port: int = typer.Option(8787),
337
+ key: Optional[str] = typer.Option(None, envvar="DOWNSHIFT_PROXY_KEY", help="Require this bearer key from clients"),
338
+ max_cost_per_hour: Optional[float] = typer.Option(None, help="Block calls once this USD/hour is spent"),
339
+ shadow_rate: float = typer.Option(0.05),
340
+ judge_model: Optional[str] = typer.Option(None, "--judge"),
341
+ prices: Optional[Path] = typer.Option(None),
342
+ ):
343
+ """Run an OpenAI-compatible proxy: record traffic now, route it safely later. No code changes in your app."""
344
+ from .serve import serve as start
345
+
346
+ if host not in ("127.0.0.1", "localhost") and not key:
347
+ raise typer.BadParameter("binding to a public address needs --key (or DOWNSHIFT_PROXY_KEY)")
348
+ if routes:
349
+ routes_data = json.loads((routes / "routes.json").read_text(encoding="utf-8"))["routes"].values()
350
+ models = [r["model"] for r in routes_data] + [r["baseline_model"] for r in routes_data]
351
+ missing = pricing.check_known(models, pricing.load_overrides(prices))
352
+ if missing:
353
+ typer.echo("Route mode needs a price for every routed model, to record savings. Missing: "
354
+ + ", ".join(missing) + "\nStart it again with --prices prices.json")
355
+ raise typer.Exit(2)
356
+ httpd, guard = start(log, routes, host, port, key, max_cost_per_hour, shadow_rate, judge_model,
357
+ prices=pricing.load_overrides(prices))
358
+ mode = f"ROUTE using {routes}" if routes else "RECORD only"
359
+ typer.echo(f"Downshift proxy on http://{host}:{port}/v1 ({mode}); logging to {log}. Ctrl+C to stop.")
360
+ typer.echo(f' Point your app at it: OpenAI(base_url="http://{host}:{port}/v1", api_key="{"<your --key>" if key else "any"}")')
361
+ try:
362
+ httpd.serve_forever()
363
+ except KeyboardInterrupt:
364
+ pass
365
+ finally:
366
+ httpd.server_close()
367
+ if guard:
368
+ guard.close()
369
+
370
+
371
+ @app.command()
372
+ def approve(out: Path = typer.Argument(Path("downshift-out"), exists=True),
373
+ by: Optional[str] = typer.Option(None, help="Approver name (default: your login)"),
374
+ note: Optional[str] = typer.Option(None)):
375
+ """Sign off a run's change record after review (bound to its content hash)."""
376
+ from .audit import approve as do_approve
377
+
378
+ rec = do_approve(out, by, note)
379
+ typer.echo(f"Approved record {rec['id'][:12]} as {rec['approvals'][-1]['by']}. See {out / 'change_record.md'}")
380
+
381
+
382
+ @app.command()
383
+ def verify(out: Path = typer.Argument(Path("downshift-out"), exists=True)):
384
+ """Check a run's change record: files unchanged, approvals valid. Exit 1 on any problem."""
385
+ from .audit import verify as do_verify
386
+
387
+ ok, problems = do_verify(out)
388
+ if ok:
389
+ typer.echo("Change record verified: inputs, outputs and approvals match.")
390
+ return
391
+ for p in problems:
392
+ typer.echo(f" PROBLEM: {p}")
393
+ raise typer.Exit(1)
394
+
395
+
396
+ @app.command()
397
+ def scout(logs: Path = typer.Argument(..., exists=True),
398
+ top: int = typer.Option(5),
399
+ providers: Optional[str] = typer.Option(None, help="Only these providers, comma-separated (e.g. openai,gemini)"),
400
+ table: Optional[Path] = typer.Option(None, help="Your own price table JSON instead of LiteLLM's")):
401
+ """Suggest cheaper models worth proving, priced on your real token mix."""
402
+ from .scout import default_table, scout as do_scout
403
+
404
+ tbl = json.loads(table.read_text(encoding="utf-8")) if table else default_table()
405
+ rows = do_scout(load_logs(logs), tbl, top, set(providers.split(",")) if providers else None)
406
+ for r in rows:
407
+ if "note" in r:
408
+ typer.echo(f"{r['model']} ({r['requests']} requests): {r['note']}")
409
+ continue
410
+ typer.echo(f"{r['model']} ({r['requests']} requests, ${r['cost_per_request']:.5f}/request). Candidates:")
411
+ for c in r["candidates"]:
412
+ typer.echo(f" {c['cost_ratio']:>6.0%} of the cost {c['model']}")
413
+ if r["candidates"]:
414
+ typer.echo(f" Prove them: downshift run {logs} -c {','.join(c['model'] for c in r['candidates'][:3])}")
415
+
416
+
417
+ @app.command()
418
+ def mcp():
419
+ """Run Downshift as an MCP server (stdio) so AI agents can check verdicts and routes before switching models."""
420
+ from .mcp_server import main as run_mcp
421
+
422
+ run_mcp()
423
+
424
+
425
+ @app.command()
426
+ def doctor():
427
+ """Check your setup: Python, optional extras, API keys (never printed) and a local Ollama server."""
428
+ import importlib.util
429
+ import os
430
+ import platform
431
+ import urllib.request
432
+
433
+ from . import __version__
434
+
435
+ ok = True
436
+
437
+ def line(status: str, label: str, detail: str = "") -> None:
438
+ typer.echo(f" [{status:^4}] {label}{(' - ' + detail) if detail else ''}")
439
+
440
+ typer.echo(f"Downshift {__version__} on Python {platform.python_version()} ({platform.system()})")
441
+ if sys.version_info < (3, 10):
442
+ ok = False
443
+ line("FAIL", "Python 3.10+ required")
444
+ else:
445
+ line(" OK ", "Python version")
446
+ for mod, extra, why in (("litellm", "llm", "call real models"), ("datasets", "data", "make_real_logs.py"),
447
+ ("mcp", "mcp", "run `downshift mcp`")):
448
+ if importlib.util.find_spec(mod):
449
+ line(" OK ", f"{mod} installed")
450
+ else:
451
+ line("WARN", f"{mod} missing", f'pip install -e ".[{extra}]" to {why}')
452
+ keys = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "GROQ_API_KEY", "MISTRAL_API_KEY",
453
+ "TOGETHERAI_API_KEY", "OPENROUTER_API_KEY"]
454
+ found = [k for k in keys if os.environ.get(k)]
455
+ line(" OK " if found else "WARN", "API keys", ", ".join(found) if found else "none (fine if you only use Ollama)")
456
+ try:
457
+ with urllib.request.urlopen("http://localhost:11434/api/tags", timeout=2) as resp:
458
+ models = [m["name"] for m in json.loads(resp.read().decode()).get("models", [])]
459
+ line(" OK ", "Ollama running", ", ".join(f"ollama/{m}" for m in models[:8]) or "no models pulled yet")
460
+ except Exception:
461
+ line("INFO", "Ollama not running", "only needed for free local models")
462
+ for f in ("prices.json", "retirements.json"):
463
+ line(" OK " if Path(f).exists() else "INFO", f, "found" if Path(f).exists() else "run `downshift init` to create")
464
+ typer.echo("\nAll required checks passed." if ok else "\nFix the FAIL items above first.")
465
+ raise typer.Exit(0 if ok else 1)
466
+
467
+
468
+ @app.command()
469
+ def init(force: bool = typer.Option(False, help="Overwrite files that already exist")):
470
+ """Create starter files in this folder: prices.json, retirements.json and .gitignore entries."""
471
+ files = {
472
+ "prices.json": json.dumps({
473
+ "_note": "USD per 1M tokens. Replace the placeholders with your providers' current prices.",
474
+ "your-current-model": {"input": 2.0, "output": 8.0},
475
+ "your-cheaper-model": {"input": 0.15, "output": 0.6},
476
+ "ollama/qwen3:4b": {"input": 0.0, "output": 0.0},
477
+ }, indent=2) + "\n",
478
+ "retirements.json": json.dumps([{
479
+ "model": "o3", "provider": "openai", "shutdown": "2026-12-11", "replacement": None,
480
+ "source": "https://developers.openai.com/api/docs/deprecations",
481
+ "note": "Example entry. Add the models you use and check each provider's deprecations page.",
482
+ }], indent=2) + "\n",
483
+ }
484
+ for name, content in files.items():
485
+ p = Path(name)
486
+ if p.exists() and not force:
487
+ typer.echo(f" skip {name} (exists)")
488
+ continue
489
+ p.write_text(content, encoding="utf-8")
490
+ typer.echo(f" wrote {name}")
491
+ gi = Path(".gitignore")
492
+ # raw logs and caches stay out of git; run folders (with change records) can be committed for the CI gate
493
+ wanted = [".downshift-cache/", "downshift-demo/", "real_logs.jsonl", "traffic.jsonl", "ledger.jsonl",
494
+ "labels_todo.jsonl", "imported_logs.jsonl"]
495
+ have = gi.read_text(encoding="utf-8").splitlines() if gi.exists() else []
496
+ add = [w for w in wanted if w not in have]
497
+ if add:
498
+ with open(gi, "a", encoding="utf-8") as fh:
499
+ fh.write(("\n" if have and have[-1] else "") + "# Downshift\n" + "\n".join(add) + "\n")
500
+ typer.echo(f" update .gitignore (+{len(add)}: logs and outputs stay out of git)")
501
+ typer.echo("\nNext: edit prices.json, then `downshift doctor`, then `downshift run <logs> -c <models>`.")
502
+
503
+
504
+ @app.command()
505
+ def demo(out: Path = typer.Option(Path("downshift-demo"), "--out", "-o")):
506
+ """The whole loop offline (no API keys): prove, make, route, watch, revert, migrate."""
507
+ from .demo import demo_feed, generate, simulate_live
508
+ from .distill import export
509
+ from .guard import summarize_ledger
510
+ from .migrate import migration_summary, watch as do_watch
511
+
512
+ out.mkdir(parents=True, exist_ok=True)
513
+ logs = out / "demo_logs.jsonl"
514
+ generate(str(logs))
515
+ records = load_logs(logs)
516
+ common = dict(sample=60, threshold=0.9, monthly_requests=1_500_000, yes=True, quiet=True)
517
+
518
+ typer.echo("\n[1/5] PROVE off-the-shelf cheaper models on 7 task types (4 request types + 3 agent steps)")
519
+ first = _analyse(records, logs, ["mock/mid", "mock/small"], out / "stage1-prove", **common)
520
+ _print_summary(first, out / "stage1-prove")
521
+
522
+ typer.echo("\n[2/5] MAKE distillation datasets for the task types that stayed on the frontier model")
523
+ for s in export(out / "stage1-prove", min_examples=50):
524
+ typer.echo(f" {s['task']:28} {s['available']:>4} examples {s['status']}")
525
+ typer.echo(" (simulating a small model fine-tuned on that export: mock/small-ft)")
526
+
527
+ typer.echo("\n[3/5] PROVE again, now including the fine-tuned model")
528
+ final = _analyse(records, logs, ["mock/mid", "mock/small", "mock/small-ft"], out, **common)
529
+ _print_summary(final, out)
530
+
531
+ typer.echo("\n[4/5] ROUTE + WATCH live traffic; halfway through, the provider silently degrades mock/small")
532
+ ledger_path = out / "ledger.jsonl"
533
+ ledger_path.unlink(missing_ok=True)
534
+ simulate_live(out, records, ledger_path)
535
+ typer.echo(" (4,000 simulated calls; dollar figures are for this sample, not a month)")
536
+ typer.echo(summarize_ledger(ledger_path))
537
+
538
+ typer.echo("[5/5] MIGRATE pretend notice: mock/frontier retires in 14 days -> prove mock/mid")
539
+ for r in do_watch(records, demo_feed(date.today())):
540
+ typer.echo(f" {r['status']}: {r['model']} ({r['share']:.0%} of traffic) shuts down {r.get('shutdown')}")
541
+ mig = _analyse(records, logs, ["mock/mid"], out / "stage5-migrate", require_cheaper=False, mode="migrate",
542
+ **common)
543
+ text, _ = migration_summary(mig, "mock/frontier", "mock/mid", demo_feed(date.today())[0]["shutdown"])
544
+ (out / "stage5-migrate" / "migration.md").write_text(text, encoding="utf-8")
545
+ typer.echo(text)
546
+ typer.echo(f"Open {out / 'report.html'} for the final report.")
547
+
548
+
549
+ def main() -> None: # pragma: no cover
550
+ # Windows consoles default to a legacy code page; make output UTF-8 so symbols never crash the CLI.
551
+ for stream in (sys.stdout, sys.stderr):
552
+ try:
553
+ stream.reconfigure(encoding="utf-8", errors="replace")
554
+ except (AttributeError, ValueError):
555
+ pass
556
+ sys.exit(app())
downshift/cluster.py ADDED
@@ -0,0 +1,88 @@
1
+ """Group requests into task clusters so each task type gets its own verdict."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from dataclasses import dataclass
6
+
7
+ import numpy as np
8
+ from sklearn.cluster import KMeans
9
+ from sklearn.feature_extraction.text import TfidfVectorizer
10
+ from sklearn.metrics import silhouette_score
11
+
12
+ from .ingest import Record
13
+
14
+
15
+ @dataclass
16
+ class ClusterModel:
17
+ vectorizer: TfidfVectorizer | None
18
+ kmeans: KMeans | None
19
+ names: dict[int, str]
20
+ labels_mode: bool = False
21
+ label_to_id: dict[str, int] | None = None
22
+
23
+ def predict(self, texts: list[str]) -> list[int]:
24
+ if self.kmeans is None or self.vectorizer is None:
25
+ return [0] * len(texts)
26
+ return self.kmeans.predict(self.vectorizer.transform(texts)).tolist()
27
+
28
+
29
+ def _slug(text: str) -> str:
30
+ return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:40] or "cluster"
31
+
32
+
33
+ def _label(r: Record, group_by: str) -> str | None:
34
+ if group_by == "step":
35
+ return f"step-{r.step}" if r.step else r.meta.get("task")
36
+ return r.meta.get("task")
37
+
38
+
39
+ def cluster_records(
40
+ records: list[Record], k: int | None = None, group_by: str = "auto", max_k: int = 8
41
+ ) -> tuple[list[int], ClusterModel]:
42
+ """Return a cluster id per record plus the fitted model (used later for routing).
43
+
44
+ group_by: "auto" clusters prompt text; "task" uses meta.task labels; "step" uses agent step names.
45
+ """
46
+ if group_by not in ("auto", "task", "step"):
47
+ raise ValueError("group_by must be auto, task or step")
48
+ if group_by != "auto" and not all(_label(r, group_by) for r in records):
49
+ raise ValueError(f"--group-by {group_by} needs a label on every record")
50
+ if group_by != "auto":
51
+ names_sorted = sorted({_label(r, group_by) for r in records})
52
+ label_to_id = {n: i for i, n in enumerate(names_sorted)}
53
+ ids = [label_to_id[_label(r, group_by)] for r in records]
54
+ # still fit a text model so the runtime router can classify new prompts
55
+ vec = TfidfVectorizer(max_features=5000, stop_words="english", ngram_range=(1, 2))
56
+ X = vec.fit_transform([r.prompt_text for r in records])
57
+ centers = np.vstack([np.asarray(X[np.array(ids) == i].mean(axis=0)) for i in range(len(names_sorted))])
58
+ km = KMeans(n_clusters=len(names_sorted), init=centers, n_init=1, max_iter=1).fit(X)
59
+ names = {i: _slug(n) for n, i in label_to_id.items()}
60
+ return ids, ClusterModel(vec, km, names, labels_mode=True, label_to_id=label_to_id)
61
+
62
+ texts = [r.prompt_text for r in records]
63
+ if len(records) < 4:
64
+ return [0] * len(records), ClusterModel(None, None, {0: "all-requests"})
65
+
66
+ vec = TfidfVectorizer(max_features=5000, stop_words="english", ngram_range=(1, 2))
67
+ X = vec.fit_transform(texts)
68
+
69
+ if k is None:
70
+ best_k, best_score = 2, -1.0
71
+ for cand in range(2, min(max_k, len(records) - 1) + 1):
72
+ km = KMeans(n_clusters=cand, n_init=10, random_state=0).fit(X)
73
+ score = silhouette_score(X, km.labels_, sample_size=min(2000, len(records)), random_state=0)
74
+ if score > best_score:
75
+ best_k, best_score = cand, score
76
+ k = best_k
77
+
78
+ km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
79
+ terms = np.array(vec.get_feature_names_out())
80
+ overall = km.cluster_centers_.mean(axis=0)
81
+ names: dict[int, str] = {}
82
+ for i, center in enumerate(km.cluster_centers_):
83
+ # name a cluster by the words that set it apart from the others, not just its most common words
84
+ distinct = center - overall
85
+ top = [t for t in terms[np.argsort(distinct)[::-1]] if " " not in t and not t.isdigit()][:2]
86
+ name = _slug("-".join(top)) or f"cluster-{i}"
87
+ names[i] = name if name not in names.values() else f"{name}-{i}"
88
+ return km.labels_.tolist(), ClusterModel(vec, km, names)