downshift-llm 0.4.0__tar.gz

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.
Files changed (36) hide show
  1. downshift_llm-0.4.0/LICENSE +21 -0
  2. downshift_llm-0.4.0/PKG-INFO +263 -0
  3. downshift_llm-0.4.0/README.md +218 -0
  4. downshift_llm-0.4.0/downshift/__init__.py +6 -0
  5. downshift_llm-0.4.0/downshift/audit.py +136 -0
  6. downshift_llm-0.4.0/downshift/cache.py +41 -0
  7. downshift_llm-0.4.0/downshift/capture.py +75 -0
  8. downshift_llm-0.4.0/downshift/cli.py +556 -0
  9. downshift_llm-0.4.0/downshift/cluster.py +88 -0
  10. downshift_llm-0.4.0/downshift/demo.py +159 -0
  11. downshift_llm-0.4.0/downshift/distill.py +67 -0
  12. downshift_llm-0.4.0/downshift/engine.py +243 -0
  13. downshift_llm-0.4.0/downshift/gate.py +66 -0
  14. downshift_llm-0.4.0/downshift/guard.py +230 -0
  15. downshift_llm-0.4.0/downshift/importers.py +229 -0
  16. downshift_llm-0.4.0/downshift/index.py +38 -0
  17. downshift_llm-0.4.0/downshift/ingest.py +138 -0
  18. downshift_llm-0.4.0/downshift/judge.py +142 -0
  19. downshift_llm-0.4.0/downshift/mcp_server.py +92 -0
  20. downshift_llm-0.4.0/downshift/migrate.py +73 -0
  21. downshift_llm-0.4.0/downshift/pricing.py +62 -0
  22. downshift_llm-0.4.0/downshift/providers.py +117 -0
  23. downshift_llm-0.4.0/downshift/report.py +216 -0
  24. downshift_llm-0.4.0/downshift/router.py +63 -0
  25. downshift_llm-0.4.0/downshift/scout.py +52 -0
  26. downshift_llm-0.4.0/downshift/serve.py +137 -0
  27. downshift_llm-0.4.0/downshift/stats.py +22 -0
  28. downshift_llm-0.4.0/downshift_llm.egg-info/PKG-INFO +263 -0
  29. downshift_llm-0.4.0/downshift_llm.egg-info/SOURCES.txt +34 -0
  30. downshift_llm-0.4.0/downshift_llm.egg-info/dependency_links.txt +1 -0
  31. downshift_llm-0.4.0/downshift_llm.egg-info/entry_points.txt +2 -0
  32. downshift_llm-0.4.0/downshift_llm.egg-info/requires.txt +24 -0
  33. downshift_llm-0.4.0/downshift_llm.egg-info/top_level.txt +1 -0
  34. downshift_llm-0.4.0/pyproject.toml +54 -0
  35. downshift_llm-0.4.0/setup.cfg +4 -0
  36. downshift_llm-0.4.0/tests/test_downshift.py +457 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arathi Sivaraj
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,263 @@
1
+ Metadata-Version: 2.4
2
+ Name: downshift-llm
3
+ Version: 0.4.0
4
+ Summary: Every model change, proven on your own traffic: replay LLM logs on cheaper or replacement models, route safely, auto-revert.
5
+ Author: Arathi Sivaraj
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://arathis1.github.io/downshift/
8
+ Project-URL: Repository, https://github.com/ArathiS1/downshift
9
+ Project-URL: Issues, https://github.com/ArathiS1/downshift/issues
10
+ Project-URL: Changelog, https://github.com/ArathiS1/downshift/blob/main/CHANGELOG.md
11
+ Keywords: llm,llmops,evaluation,cost-optimization,model-routing,litellm,ai-agents,mcp,opentelemetry,model-migration
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Software Development :: Quality Assurance
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: typer>=0.12
26
+ Requires-Dist: jinja2>=3.1
27
+ Requires-Dist: scikit-learn>=1.3
28
+ Requires-Dist: numpy>=1.24
29
+ Requires-Dist: joblib>=1.3
30
+ Requires-Dist: rich>=13
31
+ Provides-Extra: llm
32
+ Requires-Dist: litellm>=1.40; extra == "llm"
33
+ Provides-Extra: data
34
+ Requires-Dist: datasets>=2.18; extra == "data"
35
+ Provides-Extra: mcp
36
+ Requires-Dist: mcp>=1.2; extra == "mcp"
37
+ Provides-Extra: dev
38
+ Requires-Dist: pytest>=8; extra == "dev"
39
+ Provides-Extra: all
40
+ Requires-Dist: litellm>=1.40; extra == "all"
41
+ Requires-Dist: datasets>=2.18; extra == "all"
42
+ Requires-Dist: mcp>=1.2; extra == "all"
43
+ Requires-Dist: pytest>=8; extra == "all"
44
+ Dynamic: license-file
45
+
46
+ <p align="center">
47
+ <img src="https://raw.githubusercontent.com/ArathiS1/downshift/main/docs/assets/social-preview.png" alt="Downshift: every model change, proven on your own traffic" width="820">
48
+ </p>
49
+
50
+ <p align="center">
51
+ <a href="https://github.com/ArathiS1/downshift/actions/workflows/ci.yml"><img src="https://github.com/ArathiS1/downshift/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
52
+ <a href="https://pypi.org/project/downshift-llm/"><img src="https://img.shields.io/pypi/v/downshift-llm" alt="PyPI"></a>
53
+ <img src="https://img.shields.io/badge/python-3.10%2B-blue" alt="Python 3.10+">
54
+ <img src="https://img.shields.io/badge/license-MIT-green" alt="MIT">
55
+ <a href="https://arathis1.github.io/downshift/"><img src="https://img.shields.io/badge/website-live-0E7A4A" alt="Website"></a>
56
+ </p>
57
+
58
+ <p align="center">
59
+ <a href="https://arathis1.github.io/downshift/"><b>Website</b></a> ·
60
+ <a href="#quick-start"><b>Quick start</b></a> ·
61
+ <a href="https://github.com/ArathiS1/downshift/blob/main/docs/case-studies/sarvam-2026-11.md"><b>Real-world case study</b></a> ·
62
+ <a href="https://github.com/ArathiS1/downshift/blob/main/CHANGELOG.md"><b>Changelog</b></a>
63
+ </p>
64
+
65
+ # Downshift
66
+
67
+ **Every model change, proven on your own traffic.**
68
+
69
+ LLM apps change models constantly: to cut cost, because a provider retires a model, or because a new release looks better. Every switch is a gamble, because benchmarks don't tell you how a model behaves on *your* traffic.
70
+
71
+ **Downshift is the open-source, local-first safety layer for model changes.** It proves a change on your real traffic, routes each task to the cheapest proven model, watches live quality, reverts on its own, caps runaway spend, and leaves an audit-ready record of every decision.
72
+
73
+ > **Routers guess. Eval tools measure. Downshift proves, switches, watches, reverts and keeps the receipts.**
74
+
75
+ <p align="center"><img src="https://raw.githubusercontent.com/ArathiS1/downshift/main/docs/assets/demo.svg" alt="downshift demo output" width="820"></p>
76
+
77
+ ## Real result, not just a demo
78
+
79
+ On a real support-ticket workload on Sarvam's API ([full case study](https://github.com/ArathiS1/downshift/blob/main/docs/case-studies/sarvam-2026-11.md)):
80
+
81
+ - **Ticket triage proven SAFE** on a cheaper model: 100% no-worse (95% CI 92.9–100%) at about **half the cost per request**, then routed live with **8/8 shadow checks** passing.
82
+ - The model with the **cheapest token price cost 2.6× more per answer**, because reasoning tokens are billed as output.
83
+ - **2 of 3 task types were correctly held back.** A safety tool that says yes to everything isn't one.
84
+ - Mid-test, a candidate model was **retired by its provider**, the exact problem `downshift migrate` exists for.
85
+
86
+ ## Why it's different
87
+
88
+ | Category | Examples | What they do | What they don't do |
89
+ | --- | --- | --- | --- |
90
+ | Model routers | Martian, Not Diamond | Pick a model per request | No proof on *your* traffic |
91
+ | AI gateways | Portkey, LiteLLM | Route, cache, fail over on errors | Don't decide which model is *safe* |
92
+ | Eval / observability | Langfuse, Braintrust, LangSmith | Tests and traces you set up | You build the tests; they alert but don't switch or revert |
93
+ | Logs → cheaper model | OpenPipe, Predibase | Fine-tuning from logs | No longer independent (acquired in 2025) |
94
+ | **Downshift** | | **Proves, switches, watches, reverts, records** | Neutral, open source, your data stays local |
95
+
96
+ Downshift doesn't replace your gateway or tracing. It **imports** your traces and **exports** routes to them.
97
+
98
+ ## Built for 2027
99
+
100
+ | 2027 reality | What Downshift does |
101
+ | --- | --- |
102
+ | Teams won't rewrite code to try a tool | **Drop-in proxy:** change one base URL. Record traffic first, route it later (`downshift serve`) |
103
+ | Traces are standardising on OpenTelemetry GenAI conventions | **Import** OTel GenAI, OpenInference and Langfuse traces (`downshift import`) |
104
+ | AI regulation and audits want records of changes (EU AI Act high-risk duties from Dec 2027) | **Change records** with SHA-256 evidence, approvals and tamper checks (`approve`, `verify`, `gate --require-approval`) |
105
+ | Agent projects get cancelled over cost and risk | **Cost per completed task**, an **hourly spend cap**, and **cost-spike alerts** in the live router |
106
+ | Agents connect to tools through MCP | **MCP server:** agents check verdicts and routes before switching models (`downshift mcp`) |
107
+ | A new model every few weeks | **Scout** cheaper candidates priced on your token mix, then prove them (`downshift scout`) |
108
+ | Providers retire models on short notice | **Migration readiness** before the deadline (`downshift watch`, `downshift migrate`) |
109
+
110
+ ## Quick start
111
+
112
+ ```bash
113
+ pip install "downshift-llm[all]" # the command is still `downshift`
114
+ downshift doctor
115
+ downshift demo # the whole loop offline, about 10 seconds, no API keys
116
+ ```
117
+
118
+ From source:
119
+
120
+ ```bash
121
+ git clone https://github.com/ArathiS1/downshift.git
122
+ cd downshift
123
+ python -m venv .venv
124
+ # Windows: .venv\Scripts\activate macOS/Linux: source .venv/bin/activate
125
+ pip install -e ".[all]"
126
+ ```
127
+
128
+ Open `downshift-demo/report.html`. Demo numbers come from simulated models; they show how it works, not what you'll save.
129
+
130
+ ## The adoption path, step by step
131
+
132
+ **1. Collect real traffic.** Pick whichever fits:
133
+
134
+ ```bash
135
+ # a) Zero code changes: run the proxy and point your app's base_url at it
136
+ downshift serve --log traffic.jsonl
137
+ # OpenAI(base_url="http://127.0.0.1:8787/v1", api_key="any")
138
+
139
+ # b) You already trace with OpenTelemetry / Phoenix / Langfuse
140
+ downshift import traces.json --from otel -o traffic.jsonl # or --from langfuse
141
+
142
+ # c) Record from code
143
+ # from downshift.capture import Recorder; Recorder("traffic.jsonl").completion(model, messages, task="triage")
144
+
145
+ # d) No app yet: realistic traffic from public datasets, or through the proxy, answered by a real model
146
+ python examples/make_real_logs.py --model gpt-4.1 --n 150 --out traffic.jsonl
147
+ python examples/send_test_traffic.py --model gpt-4.1-mini --n 180 # sends through a running proxy
148
+ ```
149
+
150
+ *(Model names here and below are examples.)*
151
+
152
+ **2. Find and prove cheaper models.**
153
+
154
+ ```bash
155
+ downshift init # prices.json, retirements.json, .gitignore
156
+ downshift scout traffic.jsonl --top 5 # cheaper candidates priced on your token mix
157
+ downshift run traffic.jsonl -c gpt-4.1-mini,ollama/qwen3:4b --judge gpt-4.1 --prices prices.json --max-cost 5
158
+ ```
159
+
160
+ **3. Trust, then sign off.**
161
+
162
+ ```bash
163
+ downshift labelset downshift-out --n 60 # label pairs: set "human" to A, B or TIE
164
+ downshift calibrate labels_todo.jsonl --judge gpt-4.1 --record downshift-out
165
+ downshift approve downshift-out --by "Your Name" --note "Reviewed report"
166
+ downshift verify downshift-out
167
+ ```
168
+
169
+ **4. Route safely in production.**
170
+
171
+ ```bash
172
+ downshift serve --log traffic.jsonl --routes downshift-out --max-cost-per-hour 20
173
+ ```
174
+
175
+ The proxy only reroutes requests for the model the routes were proven against; everything else passes through. It shadow-checks a sample against the old model, reverts a task automatically when there's evidence of harm, blocks calls past the hourly cap (HTTP 429), and logs everything to `downshift-out/ledger.jsonl`.
176
+
177
+ **5. Keep it safe.**
178
+
179
+ ```bash
180
+ downshift gate downshift-out --judge gpt-4.1 --require-approval # in CI on every PR
181
+ downshift ledger downshift-out/ledger.jsonl # verified savings, reverts, cost alerts
182
+ ```
183
+
184
+ ## How verdicts work
185
+
186
+ - **Task types** come from clustering prompts (TF-IDF + k-means), from `meta.task` labels (`--group-by task`), or from agent steps (`--group-by step`).
187
+ - **Judging:**
188
+ - JSON: field by field (order of plain lists ignored).
189
+ - Labels: exact match.
190
+ - Free text: a pairwise LLM judge run twice with the answer order swapped.
191
+ - **SAFE** only when the 95% Wilson lower bound of the "no worse" rate clears the threshold (default 90%). **RISKY** means it looks good but there isn't enough evidence yet. **KEEP** means stay put.
192
+ - **Cost** is per *successful* request. For agents (lines with `trace_id` and `step`) it reports **cost per completed task**, including retries.
193
+ - **Live revert** happens only when even the *upper* bound of a task's live rate falls below the threshold: evidence of harm, not noise.
194
+ - Replayed answers are cached in `.downshift-cache/`, so re-runs don't pay twice. `--max-cost` stops a run before it overspends.
195
+
196
+ ## Use from Python
197
+
198
+ ```python
199
+ from downshift import GuardedRouter
200
+ import litellm
201
+
202
+ def call_llm(model, messages):
203
+ return litellm.completion(model=model, messages=messages).choices[0].message.content
204
+
205
+ guard = GuardedRouter("downshift-out", call_llm, shadow_rate=0.05,
206
+ ledger_path="ledger.jsonl", max_cost_per_hour=20)
207
+ answer = guard.complete(messages)
208
+ ```
209
+
210
+ ## Use from AI agents (MCP)
211
+
212
+ ```json
213
+ {"mcpServers": {"downshift": {"command": "downshift", "args": ["mcp"]}}}
214
+ ```
215
+
216
+ | Tool | What it does |
217
+ | --- | --- |
218
+ | `downshift_verdicts` | Per-task verdicts and savings from a run |
219
+ | `downshift_route` | Which model a prompt would go to |
220
+ | `downshift_change_record` | The audit record, and whether its files still verify |
221
+ | `downshift_ledger` | Live savings, reverts and cost alerts |
222
+ | `downshift_run` | Run an analysis; spends money, so it requires `max_cost` |
223
+
224
+ ## All commands
225
+
226
+ | Command | Purpose |
227
+ | --- | --- |
228
+ | `doctor` / `init` | Check setup / create starter files |
229
+ | `serve` | OpenAI-compatible proxy: record mode, or route mode with spend cap |
230
+ | `import` | OTel GenAI, OpenInference or Langfuse traces → Downshift logs |
231
+ | `scout` | Cheaper candidates worth proving |
232
+ | `run` | Prove candidates; writes report, routes, LiteLLM config, change record |
233
+ | `labelset` / `calibrate` | Human labels → judge agreement (optionally stored in the record) |
234
+ | `approve` / `verify` | Sign off a change record; detect tampering |
235
+ | `gate` | CI regression check (`--require-approval` also needs a valid sign-off) |
236
+ | `distill` | Fine-tuning data for task types no cheap model passed |
237
+ | `watch` / `migrate` | Retirement detection and replacement proof |
238
+ | `ledger` | Verified savings, reverts, cost alerts, outcome fee |
239
+ | `share` | Anonymised, opt-in Downshift Index contribution |
240
+ | `route` | Which model a request would go to |
241
+ | `mcp` | MCP server for agents |
242
+ | `demo` | The whole loop offline |
243
+
244
+ ## Honest limits
245
+
246
+ - The verdict is only as good as the judge. Calibrate it on 50–100 pairs you've labelled yourself.
247
+ - "No worse than the current model" is relative: if the current model is wrong, a candidate that copies it still counts as no worse.
248
+ - The proxy doesn't stream yet; streaming requests get a clear error.
249
+ - OpenTelemetry's GenAI conventions are still evolving, and many tracers don't record message content by default. Turn content capture on for import.
250
+ - Change records are evidence for audits and reviews. They are not legal advice or a compliance certificate.
251
+ - Replay sends prompts to candidate providers. Use local models or redact logs if that's a problem.
252
+
253
+ ## Roadmap
254
+
255
+ - [ ] Streaming support in the proxy
256
+ - [ ] Embedding-based clustering option
257
+ - [ ] Full agent re-runs with tool sandboxes
258
+ - [ ] Hosted Downshift Cloud: scheduled re-proofs, new-model alerts, team ledger and approvals
259
+ - [ ] Public Downshift Index site
260
+
261
+ ## Contributing and license
262
+
263
+ See [CONTRIBUTING.md](https://github.com/ArathiS1/downshift/blob/main/CONTRIBUTING.md) and [CHANGELOG.md](https://github.com/ArathiS1/downshift/blob/main/CHANGELOG.md). MIT licence. Built by [Arathi Sivaraj](https://linkedin.com/in/arathisivaraj).
@@ -0,0 +1,218 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/ArathiS1/downshift/main/docs/assets/social-preview.png" alt="Downshift: every model change, proven on your own traffic" width="820">
3
+ </p>
4
+
5
+ <p align="center">
6
+ <a href="https://github.com/ArathiS1/downshift/actions/workflows/ci.yml"><img src="https://github.com/ArathiS1/downshift/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
7
+ <a href="https://pypi.org/project/downshift-llm/"><img src="https://img.shields.io/pypi/v/downshift-llm" alt="PyPI"></a>
8
+ <img src="https://img.shields.io/badge/python-3.10%2B-blue" alt="Python 3.10+">
9
+ <img src="https://img.shields.io/badge/license-MIT-green" alt="MIT">
10
+ <a href="https://arathis1.github.io/downshift/"><img src="https://img.shields.io/badge/website-live-0E7A4A" alt="Website"></a>
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="https://arathis1.github.io/downshift/"><b>Website</b></a> ·
15
+ <a href="#quick-start"><b>Quick start</b></a> ·
16
+ <a href="https://github.com/ArathiS1/downshift/blob/main/docs/case-studies/sarvam-2026-11.md"><b>Real-world case study</b></a> ·
17
+ <a href="https://github.com/ArathiS1/downshift/blob/main/CHANGELOG.md"><b>Changelog</b></a>
18
+ </p>
19
+
20
+ # Downshift
21
+
22
+ **Every model change, proven on your own traffic.**
23
+
24
+ LLM apps change models constantly: to cut cost, because a provider retires a model, or because a new release looks better. Every switch is a gamble, because benchmarks don't tell you how a model behaves on *your* traffic.
25
+
26
+ **Downshift is the open-source, local-first safety layer for model changes.** It proves a change on your real traffic, routes each task to the cheapest proven model, watches live quality, reverts on its own, caps runaway spend, and leaves an audit-ready record of every decision.
27
+
28
+ > **Routers guess. Eval tools measure. Downshift proves, switches, watches, reverts and keeps the receipts.**
29
+
30
+ <p align="center"><img src="https://raw.githubusercontent.com/ArathiS1/downshift/main/docs/assets/demo.svg" alt="downshift demo output" width="820"></p>
31
+
32
+ ## Real result, not just a demo
33
+
34
+ On a real support-ticket workload on Sarvam's API ([full case study](https://github.com/ArathiS1/downshift/blob/main/docs/case-studies/sarvam-2026-11.md)):
35
+
36
+ - **Ticket triage proven SAFE** on a cheaper model: 100% no-worse (95% CI 92.9–100%) at about **half the cost per request**, then routed live with **8/8 shadow checks** passing.
37
+ - The model with the **cheapest token price cost 2.6× more per answer**, because reasoning tokens are billed as output.
38
+ - **2 of 3 task types were correctly held back.** A safety tool that says yes to everything isn't one.
39
+ - Mid-test, a candidate model was **retired by its provider**, the exact problem `downshift migrate` exists for.
40
+
41
+ ## Why it's different
42
+
43
+ | Category | Examples | What they do | What they don't do |
44
+ | --- | --- | --- | --- |
45
+ | Model routers | Martian, Not Diamond | Pick a model per request | No proof on *your* traffic |
46
+ | AI gateways | Portkey, LiteLLM | Route, cache, fail over on errors | Don't decide which model is *safe* |
47
+ | Eval / observability | Langfuse, Braintrust, LangSmith | Tests and traces you set up | You build the tests; they alert but don't switch or revert |
48
+ | Logs → cheaper model | OpenPipe, Predibase | Fine-tuning from logs | No longer independent (acquired in 2025) |
49
+ | **Downshift** | | **Proves, switches, watches, reverts, records** | Neutral, open source, your data stays local |
50
+
51
+ Downshift doesn't replace your gateway or tracing. It **imports** your traces and **exports** routes to them.
52
+
53
+ ## Built for 2027
54
+
55
+ | 2027 reality | What Downshift does |
56
+ | --- | --- |
57
+ | Teams won't rewrite code to try a tool | **Drop-in proxy:** change one base URL. Record traffic first, route it later (`downshift serve`) |
58
+ | Traces are standardising on OpenTelemetry GenAI conventions | **Import** OTel GenAI, OpenInference and Langfuse traces (`downshift import`) |
59
+ | AI regulation and audits want records of changes (EU AI Act high-risk duties from Dec 2027) | **Change records** with SHA-256 evidence, approvals and tamper checks (`approve`, `verify`, `gate --require-approval`) |
60
+ | Agent projects get cancelled over cost and risk | **Cost per completed task**, an **hourly spend cap**, and **cost-spike alerts** in the live router |
61
+ | Agents connect to tools through MCP | **MCP server:** agents check verdicts and routes before switching models (`downshift mcp`) |
62
+ | A new model every few weeks | **Scout** cheaper candidates priced on your token mix, then prove them (`downshift scout`) |
63
+ | Providers retire models on short notice | **Migration readiness** before the deadline (`downshift watch`, `downshift migrate`) |
64
+
65
+ ## Quick start
66
+
67
+ ```bash
68
+ pip install "downshift-llm[all]" # the command is still `downshift`
69
+ downshift doctor
70
+ downshift demo # the whole loop offline, about 10 seconds, no API keys
71
+ ```
72
+
73
+ From source:
74
+
75
+ ```bash
76
+ git clone https://github.com/ArathiS1/downshift.git
77
+ cd downshift
78
+ python -m venv .venv
79
+ # Windows: .venv\Scripts\activate macOS/Linux: source .venv/bin/activate
80
+ pip install -e ".[all]"
81
+ ```
82
+
83
+ Open `downshift-demo/report.html`. Demo numbers come from simulated models; they show how it works, not what you'll save.
84
+
85
+ ## The adoption path, step by step
86
+
87
+ **1. Collect real traffic.** Pick whichever fits:
88
+
89
+ ```bash
90
+ # a) Zero code changes: run the proxy and point your app's base_url at it
91
+ downshift serve --log traffic.jsonl
92
+ # OpenAI(base_url="http://127.0.0.1:8787/v1", api_key="any")
93
+
94
+ # b) You already trace with OpenTelemetry / Phoenix / Langfuse
95
+ downshift import traces.json --from otel -o traffic.jsonl # or --from langfuse
96
+
97
+ # c) Record from code
98
+ # from downshift.capture import Recorder; Recorder("traffic.jsonl").completion(model, messages, task="triage")
99
+
100
+ # d) No app yet: realistic traffic from public datasets, or through the proxy, answered by a real model
101
+ python examples/make_real_logs.py --model gpt-4.1 --n 150 --out traffic.jsonl
102
+ python examples/send_test_traffic.py --model gpt-4.1-mini --n 180 # sends through a running proxy
103
+ ```
104
+
105
+ *(Model names here and below are examples.)*
106
+
107
+ **2. Find and prove cheaper models.**
108
+
109
+ ```bash
110
+ downshift init # prices.json, retirements.json, .gitignore
111
+ downshift scout traffic.jsonl --top 5 # cheaper candidates priced on your token mix
112
+ downshift run traffic.jsonl -c gpt-4.1-mini,ollama/qwen3:4b --judge gpt-4.1 --prices prices.json --max-cost 5
113
+ ```
114
+
115
+ **3. Trust, then sign off.**
116
+
117
+ ```bash
118
+ downshift labelset downshift-out --n 60 # label pairs: set "human" to A, B or TIE
119
+ downshift calibrate labels_todo.jsonl --judge gpt-4.1 --record downshift-out
120
+ downshift approve downshift-out --by "Your Name" --note "Reviewed report"
121
+ downshift verify downshift-out
122
+ ```
123
+
124
+ **4. Route safely in production.**
125
+
126
+ ```bash
127
+ downshift serve --log traffic.jsonl --routes downshift-out --max-cost-per-hour 20
128
+ ```
129
+
130
+ The proxy only reroutes requests for the model the routes were proven against; everything else passes through. It shadow-checks a sample against the old model, reverts a task automatically when there's evidence of harm, blocks calls past the hourly cap (HTTP 429), and logs everything to `downshift-out/ledger.jsonl`.
131
+
132
+ **5. Keep it safe.**
133
+
134
+ ```bash
135
+ downshift gate downshift-out --judge gpt-4.1 --require-approval # in CI on every PR
136
+ downshift ledger downshift-out/ledger.jsonl # verified savings, reverts, cost alerts
137
+ ```
138
+
139
+ ## How verdicts work
140
+
141
+ - **Task types** come from clustering prompts (TF-IDF + k-means), from `meta.task` labels (`--group-by task`), or from agent steps (`--group-by step`).
142
+ - **Judging:**
143
+ - JSON: field by field (order of plain lists ignored).
144
+ - Labels: exact match.
145
+ - Free text: a pairwise LLM judge run twice with the answer order swapped.
146
+ - **SAFE** only when the 95% Wilson lower bound of the "no worse" rate clears the threshold (default 90%). **RISKY** means it looks good but there isn't enough evidence yet. **KEEP** means stay put.
147
+ - **Cost** is per *successful* request. For agents (lines with `trace_id` and `step`) it reports **cost per completed task**, including retries.
148
+ - **Live revert** happens only when even the *upper* bound of a task's live rate falls below the threshold: evidence of harm, not noise.
149
+ - Replayed answers are cached in `.downshift-cache/`, so re-runs don't pay twice. `--max-cost` stops a run before it overspends.
150
+
151
+ ## Use from Python
152
+
153
+ ```python
154
+ from downshift import GuardedRouter
155
+ import litellm
156
+
157
+ def call_llm(model, messages):
158
+ return litellm.completion(model=model, messages=messages).choices[0].message.content
159
+
160
+ guard = GuardedRouter("downshift-out", call_llm, shadow_rate=0.05,
161
+ ledger_path="ledger.jsonl", max_cost_per_hour=20)
162
+ answer = guard.complete(messages)
163
+ ```
164
+
165
+ ## Use from AI agents (MCP)
166
+
167
+ ```json
168
+ {"mcpServers": {"downshift": {"command": "downshift", "args": ["mcp"]}}}
169
+ ```
170
+
171
+ | Tool | What it does |
172
+ | --- | --- |
173
+ | `downshift_verdicts` | Per-task verdicts and savings from a run |
174
+ | `downshift_route` | Which model a prompt would go to |
175
+ | `downshift_change_record` | The audit record, and whether its files still verify |
176
+ | `downshift_ledger` | Live savings, reverts and cost alerts |
177
+ | `downshift_run` | Run an analysis; spends money, so it requires `max_cost` |
178
+
179
+ ## All commands
180
+
181
+ | Command | Purpose |
182
+ | --- | --- |
183
+ | `doctor` / `init` | Check setup / create starter files |
184
+ | `serve` | OpenAI-compatible proxy: record mode, or route mode with spend cap |
185
+ | `import` | OTel GenAI, OpenInference or Langfuse traces → Downshift logs |
186
+ | `scout` | Cheaper candidates worth proving |
187
+ | `run` | Prove candidates; writes report, routes, LiteLLM config, change record |
188
+ | `labelset` / `calibrate` | Human labels → judge agreement (optionally stored in the record) |
189
+ | `approve` / `verify` | Sign off a change record; detect tampering |
190
+ | `gate` | CI regression check (`--require-approval` also needs a valid sign-off) |
191
+ | `distill` | Fine-tuning data for task types no cheap model passed |
192
+ | `watch` / `migrate` | Retirement detection and replacement proof |
193
+ | `ledger` | Verified savings, reverts, cost alerts, outcome fee |
194
+ | `share` | Anonymised, opt-in Downshift Index contribution |
195
+ | `route` | Which model a request would go to |
196
+ | `mcp` | MCP server for agents |
197
+ | `demo` | The whole loop offline |
198
+
199
+ ## Honest limits
200
+
201
+ - The verdict is only as good as the judge. Calibrate it on 50–100 pairs you've labelled yourself.
202
+ - "No worse than the current model" is relative: if the current model is wrong, a candidate that copies it still counts as no worse.
203
+ - The proxy doesn't stream yet; streaming requests get a clear error.
204
+ - OpenTelemetry's GenAI conventions are still evolving, and many tracers don't record message content by default. Turn content capture on for import.
205
+ - Change records are evidence for audits and reviews. They are not legal advice or a compliance certificate.
206
+ - Replay sends prompts to candidate providers. Use local models or redact logs if that's a problem.
207
+
208
+ ## Roadmap
209
+
210
+ - [ ] Streaming support in the proxy
211
+ - [ ] Embedding-based clustering option
212
+ - [ ] Full agent re-runs with tool sandboxes
213
+ - [ ] Hosted Downshift Cloud: scheduled re-proofs, new-model alerts, team ledger and approvals
214
+ - [ ] Public Downshift Index site
215
+
216
+ ## Contributing and license
217
+
218
+ See [CONTRIBUTING.md](https://github.com/ArathiS1/downshift/blob/main/CONTRIBUTING.md) and [CHANGELOG.md](https://github.com/ArathiS1/downshift/blob/main/CHANGELOG.md). MIT licence. Built by [Arathi Sivaraj](https://linkedin.com/in/arathisivaraj).
@@ -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__"]
@@ -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"])