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/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Downshift: prove which LLM calls can safely move to cheaper models."""
2
+ from .guard import GuardedRouter
3
+ from .router import Router
4
+
5
+ __version__ = "0.4.0"
6
+ __all__ = ["GuardedRouter", "Router", "__version__"]
downshift/audit.py ADDED
@@ -0,0 +1,136 @@
1
+ """Audit-ready model change records.
2
+
3
+ Every `run` / `migrate` writes `change_record.json` (+ a readable `change_record.md`): what was evaluated, on which
4
+ data (SHA-256 of every input and output file), by which judge and threshold, what was decided per task, and who
5
+ approved it. `verify` re-hashes the files so tampering is visible; `approve` adds a sign-off bound to the record's
6
+ content hash. These records support the record-keeping, monitoring and change-management evidence that audits and
7
+ AI regulation ask for. They are evidence, not legal advice or a compliance certificate.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import getpass
12
+ import hashlib
13
+ import json
14
+ import uuid
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+
18
+ from . import __version__
19
+
20
+ TRACKED = ["results.json", "routes.json", "evalset.jsonl", "answers.jsonl", "litellm_config.yaml", "report.html"]
21
+
22
+
23
+ def _sha256(path: Path) -> str | None:
24
+ if not path.exists():
25
+ return None
26
+ h = hashlib.sha256()
27
+ with open(path, "rb") as fh:
28
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
29
+ h.update(chunk)
30
+ return h.hexdigest()
31
+
32
+
33
+ def _canonical(record: dict) -> str:
34
+ body = {k: v for k, v in record.items() if k not in ("approvals", "content_sha256")}
35
+ return hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()
36
+
37
+
38
+ def write_change_record(out: str | Path, result, *, logs_path: str | None, candidates: list[str], judge: str,
39
+ calibration: dict | None = None) -> dict:
40
+ out = Path(out)
41
+ decisions = []
42
+ for c in result.clusters:
43
+ best = next((m for m in c.candidates if m.model == c.recommended_model), None)
44
+ decisions.append({
45
+ "task": c.name, "traffic_share": round(c.share, 4), "from": c.baseline_model,
46
+ "to": c.recommended_model, "verdict": c.recommended_verdict,
47
+ "evidence": None if best is None else {
48
+ "n": best.n, "no_worse_rate": round(best.no_worse_rate, 4),
49
+ "ci95": [round(best.ci_low, 4), round(best.ci_high, 4)],
50
+ "cost_per_request": best.cost_per_request},
51
+ })
52
+ record = {
53
+ "schema": "downshift-change-record/v1",
54
+ "id": uuid.uuid4().hex,
55
+ "created_at": datetime.now(timezone.utc).isoformat(),
56
+ "tool": f"downshift {__version__}",
57
+ "mode": result.mode,
58
+ "migration": result.migration,
59
+ "inputs": {"logs": logs_path, "logs_sha256": _sha256(Path(logs_path)) if logs_path else None,
60
+ "requests": result.total_requests},
61
+ "method": {"candidates": candidates, "judge": judge, "threshold": result.threshold,
62
+ "rule": "SAFE when the 95% Wilson lower bound of the no-worse rate >= threshold",
63
+ "judge_calibration": calibration},
64
+ "decisions": decisions,
65
+ "projected": {"baseline_monthly_cost": result.baseline_monthly_cost,
66
+ "projected_monthly_cost": result.projected_monthly_cost,
67
+ "monthly_savings": result.monthly_savings},
68
+ "artifacts": {name: _sha256(out / name) for name in TRACKED},
69
+ "approvals": [],
70
+ }
71
+ record["content_sha256"] = _canonical(record)
72
+ (out / "change_record.json").write_text(json.dumps(record, indent=2, ensure_ascii=False), encoding="utf-8")
73
+ (out / "change_record.md").write_text(render_md(record), encoding="utf-8")
74
+ return record
75
+
76
+
77
+ def render_md(r: dict) -> str:
78
+ lines = [f"# Model change record `{r['id'][:12]}`", "",
79
+ f"- Created: {r['created_at']} by {r['tool']} ({r['mode']})",
80
+ f"- Input: {r['inputs']['logs']} ({r['inputs']['requests']} requests), "
81
+ f"sha256 `{(r['inputs']['logs_sha256'] or '')[:16]}…`",
82
+ f"- Method: candidates {', '.join(r['method']['candidates'])}; judge {r['method']['judge']}; "
83
+ f"threshold {r['method']['threshold']:.0%}",
84
+ f"- Judge calibration: {r['method']['judge_calibration'] or 'not recorded'}",
85
+ f"- Content hash: `{r['content_sha256']}`", "",
86
+ "| Task | Traffic | From | To | Verdict | No-worse (95% CI) |", "| --- | --- | --- | --- | --- | --- |"]
87
+ for d in r["decisions"]:
88
+ ev = d["evidence"]
89
+ ci = f"{ev['no_worse_rate']:.1%} ({ev['ci95'][0]:.1%}-{ev['ci95'][1]:.1%})" if ev else "-"
90
+ lines.append(f"| {d['task']} | {d['traffic_share']:.0%} | {d['from']} | {d['to']} | {d['verdict']} | {ci} |")
91
+ lines += ["", "## Approvals", ""]
92
+ lines += [f"- {a['by']} at {a['at']}: {a.get('note') or ''}" for a in r["approvals"]] or ["- none yet"]
93
+ return "\n".join(lines) + "\n"
94
+
95
+
96
+ def load(out: str | Path) -> dict:
97
+ return json.loads((Path(out) / "change_record.json").read_text(encoding="utf-8"))
98
+
99
+
100
+ def approve(out: str | Path, by: str | None = None, note: str | None = None) -> dict:
101
+ out = Path(out)
102
+ r = load(out)
103
+ if _canonical(r) != r["content_sha256"]:
104
+ raise ValueError("change record was modified after it was written; re-run the analysis")
105
+ r["approvals"].append({"by": by or getpass.getuser(), "at": datetime.now(timezone.utc).isoformat(),
106
+ "note": note, "content_sha256": r["content_sha256"]})
107
+ (out / "change_record.json").write_text(json.dumps(r, indent=2, ensure_ascii=False), encoding="utf-8")
108
+ (out / "change_record.md").write_text(render_md(r), encoding="utf-8")
109
+ return r
110
+
111
+
112
+ def verify(out: str | Path) -> tuple[bool, list[str]]:
113
+ out = Path(out)
114
+ r = load(out)
115
+ problems = []
116
+ if _canonical(r) != r["content_sha256"]:
117
+ problems.append("record content changed after it was written")
118
+ for name, expected in r["artifacts"].items():
119
+ if expected and _sha256(out / name) != expected:
120
+ problems.append(f"{name} changed since the record was written")
121
+ logs = r["inputs"].get("logs")
122
+ if logs and r["inputs"].get("logs_sha256") and Path(logs).exists() and _sha256(Path(logs)) != r["inputs"]["logs_sha256"]:
123
+ problems.append("the input log file changed since the analysis")
124
+ for a in r["approvals"]:
125
+ if a.get("content_sha256") != r["content_sha256"]:
126
+ problems.append(f"approval by {a['by']} was for a different record")
127
+ return not problems, problems
128
+
129
+
130
+ def is_approved(out: str | Path) -> bool:
131
+ try:
132
+ r = load(out)
133
+ except FileNotFoundError:
134
+ return False
135
+ ok, _ = verify(out)
136
+ return ok and any(a.get("content_sha256") == r["content_sha256"] for a in r["approvals"])
downshift/cache.py ADDED
@@ -0,0 +1,41 @@
1
+ """On-disk cache of replayed model answers, so re-running an analysis doesn't pay for the same calls twice.
2
+
3
+ Keyed by model + exact messages. Stored as one small JSON file per call under `.downshift-cache/`.
4
+ Delete the folder (or pass --no-cache) to force fresh calls, e.g. after a provider updates a model.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json
10
+ from pathlib import Path
11
+
12
+
13
+ class ReplayCache:
14
+ def __init__(self, root: str | Path = ".downshift-cache"):
15
+ self.root = Path(root)
16
+ self.hits = 0
17
+ self.misses = 0
18
+
19
+ def _path(self, model: str, messages: list[dict]) -> Path:
20
+ key = hashlib.sha256(json.dumps([model, messages], sort_keys=True, ensure_ascii=False).encode("utf-8"))
21
+ h = key.hexdigest()
22
+ return self.root / h[:2] / f"{h}.json"
23
+
24
+ def get(self, model: str, messages: list[dict]) -> dict | None:
25
+ p = self._path(model, messages)
26
+ if p.exists():
27
+ try:
28
+ data = json.loads(p.read_text(encoding="utf-8"))
29
+ self.hits += 1
30
+ return data
31
+ except (OSError, ValueError):
32
+ pass
33
+ self.misses += 1
34
+ return None
35
+
36
+ def put(self, model: str, messages: list[dict], data: dict) -> None:
37
+ p = self._path(model, messages)
38
+ p.parent.mkdir(parents=True, exist_ok=True)
39
+ tmp = p.with_suffix(".tmp")
40
+ tmp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
41
+ tmp.replace(p)
downshift/capture.py ADDED
@@ -0,0 +1,75 @@
1
+ """Record LLM calls in Downshift's log format, from any app.
2
+
3
+ Option 1: let Downshift make the call (uses LiteLLM, so any provider works):
4
+
5
+ from downshift.capture import Recorder
6
+ rec = Recorder("logs.jsonl")
7
+ text = rec.completion("gpt-4.1", messages, task="ticket_triage")
8
+
9
+ Option 2: you already have the answer from your own client; just log it:
10
+
11
+ from downshift.capture import record
12
+ record("logs.jsonl", model="gpt-4.1", messages=messages, response=text, task="ticket_triage")
13
+
14
+ For agents, pass the same trace_id for every step of one run and a step name for each call.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import threading
20
+ import uuid
21
+ from datetime import datetime, timezone
22
+ from pathlib import Path
23
+ from typing import Callable
24
+
25
+ _lock = threading.Lock()
26
+
27
+
28
+ def record(path: str | Path, *, model: str, messages: list[dict], response: str,
29
+ prompt_tokens: int | None = None, completion_tokens: int | None = None,
30
+ task: str | None = None, trace_id: str | None = None, step: str | None = None,
31
+ id: str | None = None) -> dict:
32
+ row = {
33
+ "id": id or uuid.uuid4().hex[:12],
34
+ "timestamp": datetime.now(timezone.utc).isoformat(),
35
+ "model": model,
36
+ "messages": messages,
37
+ "response": response,
38
+ }
39
+ if prompt_tokens is not None:
40
+ row["prompt_tokens"] = prompt_tokens
41
+ if completion_tokens is not None:
42
+ row["completion_tokens"] = completion_tokens
43
+ if trace_id:
44
+ row["trace_id"] = trace_id
45
+ if step:
46
+ row["step"] = step
47
+ if task:
48
+ row["meta"] = {"task": task}
49
+ with _lock, open(path, "a", encoding="utf-8") as fh:
50
+ fh.write(json.dumps(row, ensure_ascii=False) + "\n")
51
+ return row
52
+
53
+
54
+ class Recorder:
55
+ """Calls a model through LiteLLM and logs the call. Errors are raised, not logged."""
56
+
57
+ def __init__(self, path: str | Path, completion_fn: Callable | None = None, **defaults):
58
+ self.path = Path(path)
59
+ self.defaults = defaults # e.g. temperature=0
60
+ if completion_fn is None:
61
+ import litellm
62
+
63
+ completion_fn = litellm.completion
64
+ self._completion = completion_fn
65
+
66
+ def completion(self, model: str, messages: list[dict], *, task: str | None = None,
67
+ trace_id: str | None = None, step: str | None = None, **kwargs) -> str:
68
+ resp = self._completion(model=model, messages=messages, **{**self.defaults, **kwargs})
69
+ text = resp.choices[0].message.content or ""
70
+ usage = getattr(resp, "usage", None)
71
+ record(self.path, model=model, messages=messages, response=text,
72
+ prompt_tokens=getattr(usage, "prompt_tokens", None),
73
+ completion_tokens=getattr(usage, "completion_tokens", None),
74
+ task=task, trace_id=trace_id, step=step)
75
+ return text