valueproof 0.5.0__tar.gz → 0.6.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 (25) hide show
  1. {valueproof-0.5.0/src/valueproof.egg-info → valueproof-0.6.0}/PKG-INFO +66 -30
  2. {valueproof-0.5.0 → valueproof-0.6.0}/README.md +65 -29
  3. {valueproof-0.5.0 → valueproof-0.6.0}/pyproject.toml +1 -1
  4. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof/__init__.py +6 -3
  5. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof/cli.py +33 -3
  6. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof/lever_runner.py +158 -0
  7. {valueproof-0.5.0 → valueproof-0.6.0/src/valueproof.egg-info}/PKG-INFO +66 -30
  8. valueproof-0.6.0/tests/test_runner_cli.py +158 -0
  9. valueproof-0.5.0/tests/test_runner_cli.py +0 -90
  10. {valueproof-0.5.0 → valueproof-0.6.0}/LICENSE-CODE +0 -0
  11. {valueproof-0.5.0 → valueproof-0.6.0}/setup.cfg +0 -0
  12. {valueproof-0.5.0 → valueproof-0.6.0}/src/mixed_model_cost/__init__.py +0 -0
  13. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof/claude.py +0 -0
  14. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof/gemini.py +0 -0
  15. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof/openai.py +0 -0
  16. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof/pipeline.py +0 -0
  17. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof/scout_rescue.py +0 -0
  18. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof/starter.py +0 -0
  19. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof.egg-info/SOURCES.txt +0 -0
  20. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof.egg-info/dependency_links.txt +0 -0
  21. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof.egg-info/entry_points.txt +0 -0
  22. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof.egg-info/requires.txt +0 -0
  23. {valueproof-0.5.0 → valueproof-0.6.0}/src/valueproof.egg-info/top_level.txt +0 -0
  24. {valueproof-0.5.0 → valueproof-0.6.0}/tests/test_adapters.py +0 -0
  25. {valueproof-0.5.0 → valueproof-0.6.0}/tests/test_core.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: valueproof
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: Prove an AI cost cut on your own traffic before you ship it: cheap and strong models working together (Scout & Rescue), measured by cost per outcome with a blind quality review.
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/AndyJakob78/valueproof
@@ -34,8 +34,35 @@ Dynamic: license-file
34
34
 
35
35
  **In 30 seconds:**
36
36
  - **What it is:** a method and a small Python tool that cuts what AI features cost on live user traffic, and proves output quality before you ship the change. A cheap model does the work first; a strong model steps in only when a check in code rejects the result (*Scout & Rescue*). Every change is tested side by side against your current setup on your own requests, with a blind quality review.
37
- - **What we measured:** on a live app's web-search step, cost per article fell from 9.7 ¢ to 4.6–7.7 ¢, and quality held in a blind review. On 40 support tickets, a usable, correct reply cost 0.12 ¢ instead of 1.05 ¢ with Claude Opus 5.5 alone — 89% less per outcome.
38
- - **The trade-off:** on the support tickets, quality was 2–6% lower, and one wrong refund rule slipped past the checks. Your checks decide how much quality you keep.
37
+ - **What we measured:** on a live app's web-search step, cost per article fell from 9.7 ¢ to 4.6–7.7 ¢, and quality held in a blind review. On 40 support tickets, a usable reply cost 82–92% less than with Claude Opus 5.5 alone, over three runs.
38
+ - **The trade-off:** on the support tickets, quality was 2–6% lower, and one wrong refund rule slipped past the checks. The test also showed that the cheap model alone was nearly as good there: the rescuer pays off only where failures are common and a check can catch them.
39
+
40
+ ## Quick start
41
+
42
+ ```bash
43
+ pip install "valueproof[claude]" # or [openai], [gemini], [all]
44
+ ```
45
+
46
+ ```python
47
+ from valueproof import scout_and_rescue
48
+ from valueproof.claude import claude
49
+
50
+ ticket = "Where is my order 48213?"
51
+ out = scout_and_rescue(
52
+ "Reply to this support ticket: " + ticket,
53
+ scout=claude("claude-haiku-5-5"), # the cheap model tries first
54
+ rescue=claude("claude-opus-5-5"), # the frontier model runs only if the check fails
55
+ check=lambda text: None if "48213" in text else "order number missing",
56
+ )
57
+ print(out.path, out.cost_usd) # "scout" or "rescue", and what it cost
58
+ ```
59
+
60
+ Then compare setups on your own requests — offline first, with fake models:
61
+
62
+ ```bash
63
+ valueproof init my_test.py
64
+ valueproof compare my_test.py
65
+ ```
39
66
 
40
67
  ## When it fits
41
68
 
@@ -70,7 +97,7 @@ Most cost tools stop at the first row. This method measures the second before yo
70
97
  | **AI Engineer** | A small Python package: Scout & Rescue, multi-model pipelines, and a test runner (`valueproof compare`) |
71
98
  | **Prompt & Context Engineer** | A test routine that shows whether a prompt change really saves tokens — or quietly costs more |
72
99
  | **AI Builder** | A way to test cheaper setups for an AI app on a small budget, and keep only those that hold quality |
73
- | **AI Evaluation** | A blind A/B review setup and a fixed scoring sheet |
100
+ | **AI Evaluation** | A blind review (LLM-as-judge or a person) on a fixed rubric, plus a measure of how good your eval checks are |
74
101
  | **LLMOps** | Code checks and logging that track how often the expensive model runs |
75
102
  | **FinOps** | A clear before-and-after cost per request, and the yearly saving at your scale |
76
103
 
@@ -144,10 +171,16 @@ We then ran the support-reply step of this idea for real: 40 made-up tickets (20
144
171
 
145
172
  | | Scout & Rescue | Opus 5.5 alone |
146
173
  |---|---|---|
147
- | Cost per reply | **81–88% less** | — |
148
- | Quality (blind review, two runs) | **2–6% lower** | — |
174
+ | Cost per reply (three runs) | **81–92% less** | — |
175
+ | Quality (blind review, three runs) | **2–6% lower** | — |
149
176
  | Hard failures (run 2, 40 tickets) | 3 | 2 |
150
- | **Cost per outcome** (run 2) | **0.12 ¢** (36 of 40) | 1.05 ¢ (35 of 40) |
177
+ | **Cost per outcome** (three runs) | **82–92% less** | — |
178
+
179
+ **Is the rescuer worth it? Here, barely.** In a third run we added the cheap model alone: it cost 0.025 ¢ per outcome against 0.069 ¢ for Scout & Rescue and 0.92 ¢ for Opus, with nearly the same quality as Scout & Rescue. The rescuer ran on 2 of 40 tickets. On this task the saving comes from the cheap model; the rescuer is cheap insurance.
180
+
181
+ **Code checks catch form; a check by a model catches substance.** Our code checks missed every hard failure. A fourth run added a policy check by the cheap model: it caught the one hard failure, and the gap to Opus shrank from 4.7% to 3.5% — for twice the cost per reply and twice the false alarms, still 73% cheaper per outcome than Opus alone. One case is thin evidence; it shows the direction.
182
+
183
+ **Then make it cheaper again, one lever at a time.** A fifth run tested five levers on that setup, each with an estimate written down first. Sonnet as the rescuer instead of Opus: −58% cost, same quality. Lower effort, dropping an over-strict rule, and checking only the topics the product owner marks high-risk: −29% to −45% each. All three stacked: −75%, but the quality gain was gone. `valueproof compare` prints this keep-or-drop ledger itself.
151
184
 
152
185
  **Good for cost, with a quality trade-off.** Most cheap replies were good, but some were weaker in ways no check saw, and one stated a wrong refund rule. Use it where a few percent of quality is acceptable, or where your checks catch the mistakes that matter; keep refund, money and legal answers on the strong model until they do. → [Full results, caveats and how to rerun it](https://github.com/AndyJakob78/valueproof/blob/main/docs/support-test.md)
153
186
 
@@ -177,22 +210,11 @@ flowchart LR
177
210
 
178
211
  The checks decide the quality: a mistake no check catches goes straight to the user at the cheap price.
179
212
 
180
- **Expect a small quality cost.** Requests that pass the check are only as good as the cheap model's answer. In our support test, Scout & Rescue cost 81–88% less than the strong model alone and scored 2–6% lower in a blind review — a much stronger cost lever than tuning the strong model, with a quality trade-off you should measure for your own task. How much quality you keep depends mostly on your checks.
213
+ **Expect a small quality cost.** Requests that pass the check are only as good as the cheap model's answer. In our support test, Scout & Rescue cost 81–92% less than the strong model alone and scored 2–6% lower in a blind review — a much stronger cost lever than tuning the strong model, with a quality trade-off you should measure for your own task. How much quality you keep depends mostly on your checks.
181
214
 
182
- ```python
183
- from valueproof import scout_and_rescue
184
- from valueproof.claude import claude
215
+ The code for this is in the [quick start](#quick-start) at the top.
185
216
 
186
- outcome = scout_and_rescue(
187
- prompt, # your request
188
- scout=claude("claude-haiku-5-5"),
189
- rescue=claude("claude-opus-5-5"),
190
- check=lambda text: None if order_id in text else "does not mention the order id", # order_id from your data
191
- )
192
- print(outcome.path, outcome.cost_usd) # "scout" or "rescue" - how often each runs depends on your checks
193
- ```
194
-
195
- **Install** (version 0.5, early: the API may still change; Python 3.10+, Gemini adapter 3.11+):
217
+ **Install** (version 0.6, early: the API may still change; Python 3.10+, Gemini adapter 3.11+):
196
218
 
197
219
  ```bash
198
220
  pip install "valueproof[claude]"
@@ -200,11 +222,6 @@ pip install "valueproof[claude]"
200
222
 
201
223
  One name for everything: `pip install valueproof`, `import valueproof`, `valueproof compare`. (Until version 0.3 the package was called `ai-mixed-model-cost-optimization`; the old name still installs and pulls in `valueproof`.)
202
224
 
203
- ```python
204
- from valueproof import scout_and_rescue
205
- from valueproof.claude import claude # or .openai / .gemini
206
- ```
207
-
208
225
  The core has no dependencies and works with any provider: a model is just a function `prompt -> ModelResult`. Adapters come as extras: `[claude]`, `[openai]`, `[gemini]` or `[all]`. For a local model, write a function with the same shape.
209
226
 
210
227
  **Test a change on your own requests** with one command — it runs every setup on every request, side by side, and prints cost (average and median), rescue rate, time, check failures and blind-review quality:
@@ -215,13 +232,13 @@ valueproof compare my_test.py --live --estimate # runs 2 requests for real,
215
232
  valueproof compare my_test.py --live --max-spend 5 # the full test, stops starting new requests at $5
216
233
  ```
217
234
 
218
- After the table it lists **which check rule fired most often**, so you see whether rescues come from formatting, missing fields or stale data.
235
+ If your test file names its levers, it prints the **lever ledger**: each lever against the setup it changes, your estimate from before the test, and a keep-or-drop verdict. After the table it lists **which check rule fired most often**, and **how good your eval checks are**: how many of the judge's hard failures they caught, how many they missed, and how many false alarms they raised. In our own support test the answer was sobering: the code checks caught 0 of 7 hard failures. You can also **rate candidate eval checks** before you build on one: with a policy check done by a cheap model, the one hard failure in that run was caught and fixed, for about twice the cost per reply. → [Support test](https://github.com/AndyJakob78/valueproof/blob/main/docs/support-test.md)
219
236
 
220
237
  → How to write `my_test.py`, plus a support-ticket demo that works without an API key: [examples/](https://github.com/AndyJakob78/valueproof/blob/main/examples/). The live Claude mode was run in the [support test](https://github.com/AndyJakob78/valueproof/blob/main/docs/support-test.md).
221
238
 
222
239
  **A second, smaller lever: lower effort on the strong model.** In the same test, running the rescuer at effort low instead of medium cost 24–25% less in two runs, with no measurable quality loss on the rescued tickets. Measured on short support replies only.
223
240
 
224
- **3. Prove every change before you ship it.** Change one thing at a time. Run the old and new versions side by side on the same requests. Review quality blind, as A vs. B. Keep only what saves money *and* holds quality.
241
+ **3. Prove every change before you ship it.** Change one thing at a time. Run the old and new versions side by side on the same requests. Review quality blind: the reviewer never knows which setup wrote a result. Keep only what saves money *and* holds quality.
225
242
 
226
243
  The test setup is an **eval**: a fixed set of real requests, checks in code and a blind review, built once and reused for every change. Without it you can't tell a saving from a quality loss.
227
244
 
@@ -235,6 +252,23 @@ flowchart LR
235
252
  L -- "no levers left" --> S["4. Test all kept levers together,<br/>ship, keep measuring"]
236
253
  ```
237
254
 
255
+ **How the blind review works.** `valueproof compare` supports two reviewers, and you can use both:
256
+
257
+ - **LLM-as-judge:** you pass a `judge(case, text) -> Score` function. It gets one result at a time, in random order, and never the setup's name. Give it the reference that defines "right" (the policy, the fact sheet, the help article); without it a judge can only tell whether an answer looks usable, not whether it is correct.
258
+ - **A person:** every run also writes `blind_review.csv` (the results, shuffled, no setup names) and `blind_key.csv` (which setup wrote which). Score the sheet, then map it back with the key.
259
+
260
+ The rubric from our support test, as an example — four criteria, 0–10 each, plus one flag:
261
+
262
+ | Criterion | The question |
263
+ |---|---|
264
+ | Policy correct | Does the reply follow the policy exactly, with no wrong rule? |
265
+ | Solves | Does it answer every issue in the ticket and name the next step? |
266
+ | Tone | Friendly, calm, fitting the customer's mood? |
267
+ | Clarity | Short and clear? |
268
+ | **Hard failure** (yes/no) | A wrong policy rule, a promise the policy doesn't allow, an invented order number, or no answer |
269
+
270
+ Hard failures are counted separately, so no average can hide them. For scoring two results side by side as A and B by hand, see the [rubric template](https://github.com/AndyJakob78/valueproof/blob/main/templates/blind-review-rubric.md).
271
+
238
272
  The full flow, with the cost breakdown and the ledger: [method.md](https://github.com/AndyJakob78/valueproof/blob/main/docs/method.md#the-flow)
239
273
 
240
274
  → The step-by-step method: [docs/method.md](https://github.com/AndyJakob78/valueproof/blob/main/docs/method.md) · Templates: [templates/](https://github.com/AndyJakob78/valueproof/blob/main/templates/)
@@ -263,10 +297,12 @@ We tested 12 cost-saving ideas one at a time, and **7 raised cost or lowered qua
263
297
  - **Token:** the unit AI providers bill by — roughly a short word of text the model reads or writes.
264
298
  - **Lever:** one change that should lower cost, such as a smaller model or a shorter prompt. Each lever is tested on its own.
265
299
  - **Scout:** the cheap, fast model that tries first.
266
- - **Rescuer:** the strong model that runs only when a check in code rejects the scout's result.
300
+ - **Rescuer:** the strong model that runs only when an eval check rejects the scout's result.
301
+ - **Eval check:** a rule in code that judges one answer at runtime (a code-based eval): is it empty, is a field missing, is the date too old? It decides whether the cheap answer is used or the rescuer runs. The pages here also call it a "check in code" or just "check".
302
+ - **Check quality:** how well the eval checks agree with the blind review: caught, missed, false alarms.
267
303
  - **Full web search:** a search tool that filters the results with code before the model reads them. Fewer pages to read, but more steps.
268
304
  - **Simple web search:** a search tool that hands the raw results straight to the model. Fewer steps; the model reads everything it gets, which is cheap on a small model but expensive on a large one.
269
- - **Blind review:** a reviewer scores two results labelled only A and B, without knowing which setup made which.
305
+ - **Blind review:** a reviewer scores results on a fixed rubric without knowing which setup wrote them. The reviewer can be a model (LLM-as-judge) or a person.
270
306
  - **Eval:** the fixed test that decides whether a change is kept — real requests, checks in code and a blind review, run the same way every time.
271
307
  - **Outcome:** a request whose final result passed your checks and, if reviewed, had no hard failure — a result a user could rely on.
272
308
  - **Cost per outcome:** everything a setup spent, including failed and rescued attempts, divided by its outcomes. The number to compare.
@@ -6,8 +6,35 @@
6
6
 
7
7
  **In 30 seconds:**
8
8
  - **What it is:** a method and a small Python tool that cuts what AI features cost on live user traffic, and proves output quality before you ship the change. A cheap model does the work first; a strong model steps in only when a check in code rejects the result (*Scout & Rescue*). Every change is tested side by side against your current setup on your own requests, with a blind quality review.
9
- - **What we measured:** on a live app's web-search step, cost per article fell from 9.7 ¢ to 4.6–7.7 ¢, and quality held in a blind review. On 40 support tickets, a usable, correct reply cost 0.12 ¢ instead of 1.05 ¢ with Claude Opus 5.5 alone — 89% less per outcome.
10
- - **The trade-off:** on the support tickets, quality was 2–6% lower, and one wrong refund rule slipped past the checks. Your checks decide how much quality you keep.
9
+ - **What we measured:** on a live app's web-search step, cost per article fell from 9.7 ¢ to 4.6–7.7 ¢, and quality held in a blind review. On 40 support tickets, a usable reply cost 82–92% less than with Claude Opus 5.5 alone, over three runs.
10
+ - **The trade-off:** on the support tickets, quality was 2–6% lower, and one wrong refund rule slipped past the checks. The test also showed that the cheap model alone was nearly as good there: the rescuer pays off only where failures are common and a check can catch them.
11
+
12
+ ## Quick start
13
+
14
+ ```bash
15
+ pip install "valueproof[claude]" # or [openai], [gemini], [all]
16
+ ```
17
+
18
+ ```python
19
+ from valueproof import scout_and_rescue
20
+ from valueproof.claude import claude
21
+
22
+ ticket = "Where is my order 48213?"
23
+ out = scout_and_rescue(
24
+ "Reply to this support ticket: " + ticket,
25
+ scout=claude("claude-haiku-5-5"), # the cheap model tries first
26
+ rescue=claude("claude-opus-5-5"), # the frontier model runs only if the check fails
27
+ check=lambda text: None if "48213" in text else "order number missing",
28
+ )
29
+ print(out.path, out.cost_usd) # "scout" or "rescue", and what it cost
30
+ ```
31
+
32
+ Then compare setups on your own requests — offline first, with fake models:
33
+
34
+ ```bash
35
+ valueproof init my_test.py
36
+ valueproof compare my_test.py
37
+ ```
11
38
 
12
39
  ## When it fits
13
40
 
@@ -42,7 +69,7 @@ Most cost tools stop at the first row. This method measures the second before yo
42
69
  | **AI Engineer** | A small Python package: Scout & Rescue, multi-model pipelines, and a test runner (`valueproof compare`) |
43
70
  | **Prompt & Context Engineer** | A test routine that shows whether a prompt change really saves tokens — or quietly costs more |
44
71
  | **AI Builder** | A way to test cheaper setups for an AI app on a small budget, and keep only those that hold quality |
45
- | **AI Evaluation** | A blind A/B review setup and a fixed scoring sheet |
72
+ | **AI Evaluation** | A blind review (LLM-as-judge or a person) on a fixed rubric, plus a measure of how good your eval checks are |
46
73
  | **LLMOps** | Code checks and logging that track how often the expensive model runs |
47
74
  | **FinOps** | A clear before-and-after cost per request, and the yearly saving at your scale |
48
75
 
@@ -116,10 +143,16 @@ We then ran the support-reply step of this idea for real: 40 made-up tickets (20
116
143
 
117
144
  | | Scout & Rescue | Opus 5.5 alone |
118
145
  |---|---|---|
119
- | Cost per reply | **81–88% less** | — |
120
- | Quality (blind review, two runs) | **2–6% lower** | — |
146
+ | Cost per reply (three runs) | **81–92% less** | — |
147
+ | Quality (blind review, three runs) | **2–6% lower** | — |
121
148
  | Hard failures (run 2, 40 tickets) | 3 | 2 |
122
- | **Cost per outcome** (run 2) | **0.12 ¢** (36 of 40) | 1.05 ¢ (35 of 40) |
149
+ | **Cost per outcome** (three runs) | **82–92% less** | — |
150
+
151
+ **Is the rescuer worth it? Here, barely.** In a third run we added the cheap model alone: it cost 0.025 ¢ per outcome against 0.069 ¢ for Scout & Rescue and 0.92 ¢ for Opus, with nearly the same quality as Scout & Rescue. The rescuer ran on 2 of 40 tickets. On this task the saving comes from the cheap model; the rescuer is cheap insurance.
152
+
153
+ **Code checks catch form; a check by a model catches substance.** Our code checks missed every hard failure. A fourth run added a policy check by the cheap model: it caught the one hard failure, and the gap to Opus shrank from 4.7% to 3.5% — for twice the cost per reply and twice the false alarms, still 73% cheaper per outcome than Opus alone. One case is thin evidence; it shows the direction.
154
+
155
+ **Then make it cheaper again, one lever at a time.** A fifth run tested five levers on that setup, each with an estimate written down first. Sonnet as the rescuer instead of Opus: −58% cost, same quality. Lower effort, dropping an over-strict rule, and checking only the topics the product owner marks high-risk: −29% to −45% each. All three stacked: −75%, but the quality gain was gone. `valueproof compare` prints this keep-or-drop ledger itself.
123
156
 
124
157
  **Good for cost, with a quality trade-off.** Most cheap replies were good, but some were weaker in ways no check saw, and one stated a wrong refund rule. Use it where a few percent of quality is acceptable, or where your checks catch the mistakes that matter; keep refund, money and legal answers on the strong model until they do. → [Full results, caveats and how to rerun it](https://github.com/AndyJakob78/valueproof/blob/main/docs/support-test.md)
125
158
 
@@ -149,22 +182,11 @@ flowchart LR
149
182
 
150
183
  The checks decide the quality: a mistake no check catches goes straight to the user at the cheap price.
151
184
 
152
- **Expect a small quality cost.** Requests that pass the check are only as good as the cheap model's answer. In our support test, Scout & Rescue cost 81–88% less than the strong model alone and scored 2–6% lower in a blind review — a much stronger cost lever than tuning the strong model, with a quality trade-off you should measure for your own task. How much quality you keep depends mostly on your checks.
185
+ **Expect a small quality cost.** Requests that pass the check are only as good as the cheap model's answer. In our support test, Scout & Rescue cost 81–92% less than the strong model alone and scored 2–6% lower in a blind review — a much stronger cost lever than tuning the strong model, with a quality trade-off you should measure for your own task. How much quality you keep depends mostly on your checks.
153
186
 
154
- ```python
155
- from valueproof import scout_and_rescue
156
- from valueproof.claude import claude
187
+ The code for this is in the [quick start](#quick-start) at the top.
157
188
 
158
- outcome = scout_and_rescue(
159
- prompt, # your request
160
- scout=claude("claude-haiku-5-5"),
161
- rescue=claude("claude-opus-5-5"),
162
- check=lambda text: None if order_id in text else "does not mention the order id", # order_id from your data
163
- )
164
- print(outcome.path, outcome.cost_usd) # "scout" or "rescue" - how often each runs depends on your checks
165
- ```
166
-
167
- **Install** (version 0.5, early: the API may still change; Python 3.10+, Gemini adapter 3.11+):
189
+ **Install** (version 0.6, early: the API may still change; Python 3.10+, Gemini adapter 3.11+):
168
190
 
169
191
  ```bash
170
192
  pip install "valueproof[claude]"
@@ -172,11 +194,6 @@ pip install "valueproof[claude]"
172
194
 
173
195
  One name for everything: `pip install valueproof`, `import valueproof`, `valueproof compare`. (Until version 0.3 the package was called `ai-mixed-model-cost-optimization`; the old name still installs and pulls in `valueproof`.)
174
196
 
175
- ```python
176
- from valueproof import scout_and_rescue
177
- from valueproof.claude import claude # or .openai / .gemini
178
- ```
179
-
180
197
  The core has no dependencies and works with any provider: a model is just a function `prompt -> ModelResult`. Adapters come as extras: `[claude]`, `[openai]`, `[gemini]` or `[all]`. For a local model, write a function with the same shape.
181
198
 
182
199
  **Test a change on your own requests** with one command — it runs every setup on every request, side by side, and prints cost (average and median), rescue rate, time, check failures and blind-review quality:
@@ -187,13 +204,13 @@ valueproof compare my_test.py --live --estimate # runs 2 requests for real,
187
204
  valueproof compare my_test.py --live --max-spend 5 # the full test, stops starting new requests at $5
188
205
  ```
189
206
 
190
- After the table it lists **which check rule fired most often**, so you see whether rescues come from formatting, missing fields or stale data.
207
+ If your test file names its levers, it prints the **lever ledger**: each lever against the setup it changes, your estimate from before the test, and a keep-or-drop verdict. After the table it lists **which check rule fired most often**, and **how good your eval checks are**: how many of the judge's hard failures they caught, how many they missed, and how many false alarms they raised. In our own support test the answer was sobering: the code checks caught 0 of 7 hard failures. You can also **rate candidate eval checks** before you build on one: with a policy check done by a cheap model, the one hard failure in that run was caught and fixed, for about twice the cost per reply. → [Support test](https://github.com/AndyJakob78/valueproof/blob/main/docs/support-test.md)
191
208
 
192
209
  → How to write `my_test.py`, plus a support-ticket demo that works without an API key: [examples/](https://github.com/AndyJakob78/valueproof/blob/main/examples/). The live Claude mode was run in the [support test](https://github.com/AndyJakob78/valueproof/blob/main/docs/support-test.md).
193
210
 
194
211
  **A second, smaller lever: lower effort on the strong model.** In the same test, running the rescuer at effort low instead of medium cost 24–25% less in two runs, with no measurable quality loss on the rescued tickets. Measured on short support replies only.
195
212
 
196
- **3. Prove every change before you ship it.** Change one thing at a time. Run the old and new versions side by side on the same requests. Review quality blind, as A vs. B. Keep only what saves money *and* holds quality.
213
+ **3. Prove every change before you ship it.** Change one thing at a time. Run the old and new versions side by side on the same requests. Review quality blind: the reviewer never knows which setup wrote a result. Keep only what saves money *and* holds quality.
197
214
 
198
215
  The test setup is an **eval**: a fixed set of real requests, checks in code and a blind review, built once and reused for every change. Without it you can't tell a saving from a quality loss.
199
216
 
@@ -207,6 +224,23 @@ flowchart LR
207
224
  L -- "no levers left" --> S["4. Test all kept levers together,<br/>ship, keep measuring"]
208
225
  ```
209
226
 
227
+ **How the blind review works.** `valueproof compare` supports two reviewers, and you can use both:
228
+
229
+ - **LLM-as-judge:** you pass a `judge(case, text) -> Score` function. It gets one result at a time, in random order, and never the setup's name. Give it the reference that defines "right" (the policy, the fact sheet, the help article); without it a judge can only tell whether an answer looks usable, not whether it is correct.
230
+ - **A person:** every run also writes `blind_review.csv` (the results, shuffled, no setup names) and `blind_key.csv` (which setup wrote which). Score the sheet, then map it back with the key.
231
+
232
+ The rubric from our support test, as an example — four criteria, 0–10 each, plus one flag:
233
+
234
+ | Criterion | The question |
235
+ |---|---|
236
+ | Policy correct | Does the reply follow the policy exactly, with no wrong rule? |
237
+ | Solves | Does it answer every issue in the ticket and name the next step? |
238
+ | Tone | Friendly, calm, fitting the customer's mood? |
239
+ | Clarity | Short and clear? |
240
+ | **Hard failure** (yes/no) | A wrong policy rule, a promise the policy doesn't allow, an invented order number, or no answer |
241
+
242
+ Hard failures are counted separately, so no average can hide them. For scoring two results side by side as A and B by hand, see the [rubric template](https://github.com/AndyJakob78/valueproof/blob/main/templates/blind-review-rubric.md).
243
+
210
244
  The full flow, with the cost breakdown and the ledger: [method.md](https://github.com/AndyJakob78/valueproof/blob/main/docs/method.md#the-flow)
211
245
 
212
246
  → The step-by-step method: [docs/method.md](https://github.com/AndyJakob78/valueproof/blob/main/docs/method.md) · Templates: [templates/](https://github.com/AndyJakob78/valueproof/blob/main/templates/)
@@ -235,10 +269,12 @@ We tested 12 cost-saving ideas one at a time, and **7 raised cost or lowered qua
235
269
  - **Token:** the unit AI providers bill by — roughly a short word of text the model reads or writes.
236
270
  - **Lever:** one change that should lower cost, such as a smaller model or a shorter prompt. Each lever is tested on its own.
237
271
  - **Scout:** the cheap, fast model that tries first.
238
- - **Rescuer:** the strong model that runs only when a check in code rejects the scout's result.
272
+ - **Rescuer:** the strong model that runs only when an eval check rejects the scout's result.
273
+ - **Eval check:** a rule in code that judges one answer at runtime (a code-based eval): is it empty, is a field missing, is the date too old? It decides whether the cheap answer is used or the rescuer runs. The pages here also call it a "check in code" or just "check".
274
+ - **Check quality:** how well the eval checks agree with the blind review: caught, missed, false alarms.
239
275
  - **Full web search:** a search tool that filters the results with code before the model reads them. Fewer pages to read, but more steps.
240
276
  - **Simple web search:** a search tool that hands the raw results straight to the model. Fewer steps; the model reads everything it gets, which is cheap on a small model but expensive on a large one.
241
- - **Blind review:** a reviewer scores two results labelled only A and B, without knowing which setup made which.
277
+ - **Blind review:** a reviewer scores results on a fixed rubric without knowing which setup wrote them. The reviewer can be a model (LLM-as-judge) or a person.
242
278
  - **Eval:** the fixed test that decides whether a change is kept — real requests, checks in code and a blind review, run the same way every time.
243
279
  - **Outcome:** a request whose final result passed your checks and, if reviewed, had no hard failure — a result a user could rely on.
244
280
  - **Cost per outcome:** everything a setup spent, including failed and rescued attempts, divided by its outcomes. The number to compare.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "valueproof"
7
- version = "0.5.0"
7
+ version = "0.6.0"
8
8
  description = "Prove an AI cost cut on your own traffic before you ship it: cheap and strong models working together (Scout & Rescue), measured by cost per outcome with a blind quality review."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -9,14 +9,17 @@ and measure what each change does to cost and quality before it ships.
9
9
  Any provider works: a model is just a function `prompt -> ModelResult`.
10
10
  """
11
11
 
12
- from .lever_runner import Report, Run, Score, estimate, is_outcome, print_table, run_levers, save, summarize
12
+ from .lever_runner import (Report, Run, Score, check_quality, estimate, is_outcome, ledger_markdown, lever_ledger,
13
+ load_report, print_check_ratings, print_ledger,
14
+ print_table, rate_checks, run_levers, save, summarize)
13
15
  from .pipeline import RunResult, Step, StepLog, run_pipeline
14
16
  from .scout_rescue import Check, Model, ModelResult, Outcome, handoff_prompt, scout_and_rescue
15
17
 
16
- __version__ = "0.5.0"
18
+ __version__ = "0.6.0"
17
19
 
18
20
  __all__ = [
19
21
  "Check", "Model", "ModelResult", "Outcome", "handoff_prompt", "scout_and_rescue",
20
22
  "RunResult", "Step", "StepLog", "run_pipeline",
21
- "Report", "Run", "Score", "estimate", "is_outcome", "print_table", "run_levers", "save", "summarize",
23
+ "Report", "Run", "Score", "check_quality", "estimate", "is_outcome", "ledger_markdown", "lever_ledger", "load_report", "print_check_ratings", "print_ledger", "print_table",
24
+ "rate_checks", "run_levers", "save", "summarize",
22
25
  ]
@@ -14,6 +14,8 @@ Your test file is plain Python and defines one function:
14
14
  "cases": [...], # your test requests
15
15
  "setups": {"baseline": run, ...}, # name -> run(case) -> Run; first is the baseline
16
16
  "judge": judge, # optional: judge(case, text) -> Score
17
+ "checks": {"my new check": fn}, # optional: candidate eval checks to rate, fn(case, text)
18
+ "levers": {"new": {"baseline": "baseline", "estimate": "-30% cost"}}, # optional: keep-or-drop ledger
17
19
  "describe": lambda case: str(case), # optional: how a case shows on the review sheet
18
20
  }
19
21
 
@@ -25,12 +27,13 @@ from __future__ import annotations
25
27
 
26
28
  import argparse
27
29
  import importlib.util
30
+ import json
28
31
  import sys
29
32
  from datetime import datetime
30
33
  from pathlib import Path
31
34
 
32
35
  from . import __version__
33
- from .lever_runner import estimate, print_table, run_levers, save
36
+ from .lever_runner import estimate, ledger_markdown, lever_ledger, load_report, print_check_ratings, print_ledger, print_table, rate_checks, run_levers, save
34
37
  from .starter import STARTER
35
38
 
36
39
 
@@ -48,7 +51,8 @@ def _load(path: Path):
48
51
 
49
52
 
50
53
  def compare(file: str, live: bool = False, out: str | None = None, extra: list[str] | None = None,
51
- max_spend: float | None = None, estimate_only: bool = False, sample: int = 2) -> None:
54
+ max_spend: float | None = None, estimate_only: bool = False, sample: int = 2,
55
+ from_results: str | None = None) -> None:
52
56
  path = Path(file).resolve()
53
57
  spec = _load(path).build(live, extra or [])
54
58
  cases, setups, judge = spec["cases"], spec["setups"], spec.get("judge")
@@ -60,6 +64,21 @@ def compare(file: str, live: bool = False, out: str | None = None, extra: list[s
60
64
  print(f"Projected full run: ${e['projected_total']:.2f} for {e['cases']} cases, including the review")
61
65
  print("A rough guide: hard cases and rescues cost more. Set a ceiling with --max-spend.")
62
66
  return
67
+ if from_results: # no model runs: rate the candidate checks on saved replies
68
+ report = load_report(Path(from_results))
69
+ present = list(dict.fromkeys(r.setup for r in report.rows))
70
+ names = [n for n in setups if n in present] + [n for n in present if n not in setups] # first = baseline
71
+ print(f"{mode}: {len(report.rows)} saved results from {from_results} (no model runs)\n")
72
+ print_table(report, names)
73
+ ledger = lever_ledger(report, spec.get("levers") or {})
74
+ print_ledger(ledger)
75
+ if spec.get("checks"):
76
+ print_check_ratings(rate_checks(report, cases, names, spec["checks"]))
77
+ print(f"Spent on the checks: ${report.spent_usd:.4f}")
78
+ if out and ledger:
79
+ Path(out).mkdir(parents=True, exist_ok=True)
80
+ (Path(out) / "ledger.md").write_text(ledger_markdown(ledger) + "\n")
81
+ return
63
82
  limit = f", stops at ${max_spend:.2f}" if max_spend is not None else ""
64
83
  print(f"{mode}: {len(cases)} cases x {len(setups)} setups{limit}")
65
84
  report = run_levers(cases, setups, judge=judge, max_spend=max_spend)
@@ -68,8 +87,17 @@ def compare(file: str, live: bool = False, out: str | None = None, extra: list[s
68
87
  return
69
88
  print()
70
89
  print_table(report, list(setups))
90
+ ledger = lever_ledger(report, spec.get("levers") or {})
91
+ print_ledger(ledger)
92
+ ratings = rate_checks(report, cases, list(setups), spec["checks"]) if spec.get("checks") and judge else {}
93
+ print_check_ratings(ratings)
71
94
  out_dir = Path(out) if out else path.parent / "results" / datetime.now().strftime("%Y%m%d-%H%M%S")
72
95
  save(report, cases, out_dir, describe=spec.get("describe", str))
96
+ if ledger:
97
+ (out_dir / "ledger.md").write_text(ledger_markdown(ledger) + "\n")
98
+ if ratings:
99
+ (out_dir / "check_ratings.json").write_text(json.dumps(ratings, indent=2))
100
+ print(f"Spent including the check ratings: ${report.spent_usd:.4f}")
73
101
  print(f"\nSaved to {out_dir}")
74
102
 
75
103
 
@@ -95,11 +123,13 @@ def main(argv: list[str] | None = None) -> None:
95
123
  cmp_.add_argument("--estimate", action="store_true",
96
124
  help="run only a small sample for real and print the projected cost of the full run")
97
125
  cmp_.add_argument("--sample", type=int, default=2, help="cases to run for --estimate (default: 2)")
126
+ cmp_.add_argument("--from-results", metavar="FILE",
127
+ help="skip the runs: rate the test file's candidate checks on a saved results.json")
98
128
  ini = sub.add_parser("init", help="write a starter test file that runs offline straight away")
99
129
  ini.add_argument("file", nargs="?", default="valueproof_test.py", help="file to create (default: valueproof_test.py)")
100
130
  args, extra = parser.parse_known_args(argv)
101
131
  if args.command == "compare":
102
- compare(args.file, args.live, args.out, extra, args.max_spend, args.estimate, args.sample)
132
+ compare(args.file, args.live, args.out, extra, args.max_spend, args.estimate, args.sample, args.from_results)
103
133
  elif args.command == "init":
104
134
  init(args.file)
105
135
 
@@ -110,6 +110,16 @@ def run_levers(
110
110
  return report
111
111
 
112
112
 
113
+ def load_report(path: Path) -> Report:
114
+ """Read a results.json written by save(). Lets you rate new eval checks on replies you already paid for."""
115
+ report = Report()
116
+ for r in json.loads(Path(path).read_text()):
117
+ run = Run(**{k: v for k, v in r["run"].items() if k in Run.__dataclass_fields__})
118
+ score = Score(**{k: v for k, v in r["score"].items() if k in Score.__dataclass_fields__}) if r.get("score") else None
119
+ report.rows.append(Row(r["case"], r["setup"], run, score))
120
+ return report
121
+
122
+
113
123
  def estimate(
114
124
  cases: list[Any],
115
125
  setups: dict[str, Callable[[Any], Run]],
@@ -171,6 +181,146 @@ def summarize(report: Report, setups: list[str]) -> list[dict]:
171
181
  return out
172
182
 
173
183
 
184
+ def check_quality(report: Report, setups: list[str], weaker_by: float = 0.125,
185
+ flagged_by: Optional[Callable[[Row], bool]] = None) -> Optional[dict]:
186
+ """How good are your eval checks? Compares each check verdict with the judge's verdict.
187
+
188
+ Counted over every distinct reply in the run (the same reply from two setups counts once):
189
+ caught the check failed a reply the judge called a hard failure
190
+ missed the check passed a reply the judge called a hard failure <- the costly case
191
+ false_alarms the check failed a reply the judge found acceptable <- pays for a rescue for nothing
192
+ Also: replies clearly weaker than the baseline's reply to the same request (by `weaker_by` of the
193
+ scale or more), and how many of those a check flagged. Returns None if no judge ran.
194
+ """
195
+ scored = [r for r in report.rows if r.score]
196
+ if not scored:
197
+ return None
198
+ base = {r.case: r.score.points for r in scored if r.setup == setups[0]}
199
+ seen, q = set(), dict(replies=0, hard_failures=0, caught=0, missed=0, false_alarms=0, weaker=0, weaker_flagged=0)
200
+ for r in scored:
201
+ key = (r.case, r.run.text)
202
+ if key in seen:
203
+ continue
204
+ seen.add(key)
205
+ flagged = flagged_by(r) if flagged_by else r.run.final_check is not None
206
+ bad = r.score.hard_failure
207
+ q["replies"] += 1
208
+ q["hard_failures"] += bad
209
+ q["caught"] += flagged and bad
210
+ q["missed"] += (not flagged) and bad
211
+ q["false_alarms"] += flagged and not bad
212
+ if r.case in base and base[r.case] - r.score.points >= weaker_by * r.score.max_points:
213
+ q["weaker"] += 1
214
+ q["weaker_flagged"] += flagged
215
+ return q
216
+
217
+
218
+ def rate_checks(report: Report, cases: list[Any], setups: list[str],
219
+ checks: dict[str, Callable[[Any, str], Any]], weaker_by: float = 0.125) -> dict[str, dict]:
220
+ """Try candidate eval checks on every distinct reply of a finished run and rate each against the judge.
221
+
222
+ checks: {name: fn(case, text)}; fn returns None if the reply is usable, else a reason -
223
+ or a tuple (that, cost_usd) when the check itself costs money (a model call).
224
+ Lets you compare checks before you build a setup around one.
225
+ """
226
+ ratings = {}
227
+ for name, fn in checks.items():
228
+ verdicts: dict = {}
229
+ cost = 0.0
230
+
231
+ def flagged(r: Row) -> bool:
232
+ nonlocal cost
233
+ key = (r.case, r.run.text)
234
+ if key not in verdicts:
235
+ v = fn(cases[r.case], r.run.text)
236
+ if isinstance(v, tuple):
237
+ v, c = v
238
+ cost += c
239
+ verdicts[key] = v is not None
240
+ if len(verdicts) % 20 == 0:
241
+ print(f" {name}: {len(verdicts)} replies checked", flush=True)
242
+ return verdicts[key]
243
+
244
+ q = check_quality(report, setups, weaker_by, flagged)
245
+ if q is None:
246
+ return {}
247
+ q["flagged"], q["cost_usd"] = sum(verdicts.values()), cost
248
+ report.spent_usd += cost
249
+ ratings[name] = q
250
+ print(f" rated check: {name}", flush=True)
251
+ return ratings
252
+
253
+
254
+ def print_check_ratings(ratings: dict[str, dict]) -> None:
255
+ if not ratings:
256
+ return
257
+ first = next(iter(ratings.values()))
258
+ print(f"\nCandidate eval checks, rated against the judge ({first['replies']} distinct replies, "
259
+ f"{first['hard_failures']} hard failures, {first['weaker']} clearly weaker):")
260
+ print(f"{'check':<34}{'caught':>8}{'missed':>8}{'false alarms':>14}{'weaker flagged':>16}{'cost per check':>16}")
261
+ for name, q in ratings.items():
262
+ per = q["cost_usd"] / q["replies"] * 100 if q["replies"] else 0
263
+ print(f"{name:<34}{q['caught']:>8}{q['missed']:>8}{q['false_alarms']:>14}"
264
+ f"{str(q['weaker_flagged']) + '/' + str(q['weaker']):>16}{per:>14.3f}c")
265
+
266
+
267
+ def lever_ledger(report: Report, levers: dict[str, dict], tolerance: float = 0.01) -> list[dict]:
268
+ """The keep-or-drop ledger: each lever against the setup it changes.
269
+
270
+ levers: {setup_name: {"baseline": other_setup_name, "estimate": "what you expected, written before the test"}}
271
+ A lever is kept when it costs less per request, quality did not fall by more than `tolerance` of the
272
+ maximum score (default 1%, about the noise between runs), and it has no more hard failures.
273
+ A lever that costs more but improves quality or removes hard failures is flagged as the owner's call.
274
+ Without a judge the verdict rests on cost alone and says so.
275
+ """
276
+ names = {r.setup for r in report.rows}
277
+ rows = []
278
+ for name, info in levers.items():
279
+ base = info.get("baseline")
280
+ if name not in names or base not in names:
281
+ continue
282
+ s = {x["setup"]: x for x in summarize(report, [base, name])}
283
+ b, l = s[base], s[name]
284
+ cost = l["avg_cost"] / b["avg_cost"] - 1 if b["avg_cost"] else 0.0
285
+ row = {"lever": name, "baseline": base, "estimate": info.get("estimate", ""),
286
+ "cost_change": cost, "seconds_change": l["avg_seconds"] - b["avg_seconds"],
287
+ "rescued": f"{b['rescued']} -> {l['rescued']}", "quality_change": None, "hard_fail_change": None}
288
+ if l["quality"] is not None and b["quality"] is not None:
289
+ row["quality_change"] = l["quality"] - b["quality"]
290
+ row["hard_fail_change"] = l["hard_fail"] - b["hard_fail"]
291
+ held = row["quality_change"] >= -tolerance * l["quality_max"] and row["hard_fail_change"] <= 0
292
+ better = row["quality_change"] > tolerance * l["quality_max"] or row["hard_fail_change"] < 0
293
+ row["verdict"] = ("keep" if cost < 0 and held else "drop: quality fell" if cost < 0
294
+ else "costs more, buys quality: your call" if better else "drop: not cheaper")
295
+ else:
296
+ row["verdict"] = "cheaper (quality not reviewed)" if cost < 0 else "drop: not cheaper"
297
+ rows.append(row)
298
+ return rows
299
+
300
+
301
+ def ledger_markdown(rows: list[dict]) -> str:
302
+ out = ["| Lever | Against | Estimate before the test | Cost | Time | Rescues | Quality | Hard failures | Verdict |",
303
+ "|---|---|---|---|---|---|---|---|---|"]
304
+ for r in rows:
305
+ q = "not reviewed" if r["quality_change"] is None else f"{r['quality_change']:+d} points"
306
+ h = "" if r["hard_fail_change"] is None else f"{r['hard_fail_change']:+d}"
307
+ out.append(f"| {r['lever']} | {r['baseline']} | {r['estimate']} | {r['cost_change'] * 100:+.0f}% | "
308
+ f"{r['seconds_change']:+.1f} s | {r['rescued']} | {q} | {h} | **{r['verdict']}** |")
309
+ return "\n".join(out)
310
+
311
+
312
+ def print_ledger(rows: list[dict]) -> None:
313
+ if not rows:
314
+ return
315
+ print("\nLever ledger (each lever against the setup it changes):")
316
+ print(f"{'lever':<28}{'cost':>7}{'time':>8}{'rescues':>10}{'quality':>9}{'hard':>6} verdict | estimate before the test")
317
+ for r in rows:
318
+ q = "n/a" if r["quality_change"] is None else f"{r['quality_change']:+d}"
319
+ h = "" if r["hard_fail_change"] is None else f"{r['hard_fail_change']:+d}"
320
+ print(f"{r['lever']:<28}{r['cost_change'] * 100:>+6.0f}%{r['seconds_change']:>+7.1f}s{r['rescued']:>10}{q:>9}{h:>6}"
321
+ f" {r['verdict']} | {r['estimate']}")
322
+
323
+
174
324
  def print_table(report: Report, setups: list[str]) -> None:
175
325
  rows = summarize(report, setups)
176
326
  base = rows[0]["cost_per_outcome"]
@@ -202,6 +352,14 @@ def print_table(report: Report, setups: list[str]) -> None:
202
352
  if counts:
203
353
  top = ", ".join(f"{why} ({n})" for why, n in counts.most_common(5))
204
354
  print(f" {label}: {top}")
355
+ q = check_quality(report, setups)
356
+ if q:
357
+ print(f"\nHow good are the eval checks? (check verdict vs. the judge, over {q['replies']} distinct replies)")
358
+ print(f" hard failures: {q['hard_failures']} -> caught {q['caught']}, missed {q['missed']}")
359
+ print(f" false alarms (check failed a reply the judge accepted): {q['false_alarms']}")
360
+ print(f" replies clearly weaker than '{setups[0]}': {q['weaker']} -> flagged by a check: {q['weaker_flagged']}")
361
+ if q["missed"] or q["weaker"] > q["weaker_flagged"]:
362
+ print(" Missed and unflagged replies reach users as they are: write checks for those mistakes.")
205
363
  if report.stopped:
206
364
  print(f"\nNote: {report.stopped}.")
207
365
  print(f"Spent on this run: ${report.spent_usd:.4f}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: valueproof
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: Prove an AI cost cut on your own traffic before you ship it: cheap and strong models working together (Scout & Rescue), measured by cost per outcome with a blind quality review.
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/AndyJakob78/valueproof
@@ -34,8 +34,35 @@ Dynamic: license-file
34
34
 
35
35
  **In 30 seconds:**
36
36
  - **What it is:** a method and a small Python tool that cuts what AI features cost on live user traffic, and proves output quality before you ship the change. A cheap model does the work first; a strong model steps in only when a check in code rejects the result (*Scout & Rescue*). Every change is tested side by side against your current setup on your own requests, with a blind quality review.
37
- - **What we measured:** on a live app's web-search step, cost per article fell from 9.7 ¢ to 4.6–7.7 ¢, and quality held in a blind review. On 40 support tickets, a usable, correct reply cost 0.12 ¢ instead of 1.05 ¢ with Claude Opus 5.5 alone — 89% less per outcome.
38
- - **The trade-off:** on the support tickets, quality was 2–6% lower, and one wrong refund rule slipped past the checks. Your checks decide how much quality you keep.
37
+ - **What we measured:** on a live app's web-search step, cost per article fell from 9.7 ¢ to 4.6–7.7 ¢, and quality held in a blind review. On 40 support tickets, a usable reply cost 82–92% less than with Claude Opus 5.5 alone, over three runs.
38
+ - **The trade-off:** on the support tickets, quality was 2–6% lower, and one wrong refund rule slipped past the checks. The test also showed that the cheap model alone was nearly as good there: the rescuer pays off only where failures are common and a check can catch them.
39
+
40
+ ## Quick start
41
+
42
+ ```bash
43
+ pip install "valueproof[claude]" # or [openai], [gemini], [all]
44
+ ```
45
+
46
+ ```python
47
+ from valueproof import scout_and_rescue
48
+ from valueproof.claude import claude
49
+
50
+ ticket = "Where is my order 48213?"
51
+ out = scout_and_rescue(
52
+ "Reply to this support ticket: " + ticket,
53
+ scout=claude("claude-haiku-5-5"), # the cheap model tries first
54
+ rescue=claude("claude-opus-5-5"), # the frontier model runs only if the check fails
55
+ check=lambda text: None if "48213" in text else "order number missing",
56
+ )
57
+ print(out.path, out.cost_usd) # "scout" or "rescue", and what it cost
58
+ ```
59
+
60
+ Then compare setups on your own requests — offline first, with fake models:
61
+
62
+ ```bash
63
+ valueproof init my_test.py
64
+ valueproof compare my_test.py
65
+ ```
39
66
 
40
67
  ## When it fits
41
68
 
@@ -70,7 +97,7 @@ Most cost tools stop at the first row. This method measures the second before yo
70
97
  | **AI Engineer** | A small Python package: Scout & Rescue, multi-model pipelines, and a test runner (`valueproof compare`) |
71
98
  | **Prompt & Context Engineer** | A test routine that shows whether a prompt change really saves tokens — or quietly costs more |
72
99
  | **AI Builder** | A way to test cheaper setups for an AI app on a small budget, and keep only those that hold quality |
73
- | **AI Evaluation** | A blind A/B review setup and a fixed scoring sheet |
100
+ | **AI Evaluation** | A blind review (LLM-as-judge or a person) on a fixed rubric, plus a measure of how good your eval checks are |
74
101
  | **LLMOps** | Code checks and logging that track how often the expensive model runs |
75
102
  | **FinOps** | A clear before-and-after cost per request, and the yearly saving at your scale |
76
103
 
@@ -144,10 +171,16 @@ We then ran the support-reply step of this idea for real: 40 made-up tickets (20
144
171
 
145
172
  | | Scout & Rescue | Opus 5.5 alone |
146
173
  |---|---|---|
147
- | Cost per reply | **81–88% less** | — |
148
- | Quality (blind review, two runs) | **2–6% lower** | — |
174
+ | Cost per reply (three runs) | **81–92% less** | — |
175
+ | Quality (blind review, three runs) | **2–6% lower** | — |
149
176
  | Hard failures (run 2, 40 tickets) | 3 | 2 |
150
- | **Cost per outcome** (run 2) | **0.12 ¢** (36 of 40) | 1.05 ¢ (35 of 40) |
177
+ | **Cost per outcome** (three runs) | **82–92% less** | — |
178
+
179
+ **Is the rescuer worth it? Here, barely.** In a third run we added the cheap model alone: it cost 0.025 ¢ per outcome against 0.069 ¢ for Scout & Rescue and 0.92 ¢ for Opus, with nearly the same quality as Scout & Rescue. The rescuer ran on 2 of 40 tickets. On this task the saving comes from the cheap model; the rescuer is cheap insurance.
180
+
181
+ **Code checks catch form; a check by a model catches substance.** Our code checks missed every hard failure. A fourth run added a policy check by the cheap model: it caught the one hard failure, and the gap to Opus shrank from 4.7% to 3.5% — for twice the cost per reply and twice the false alarms, still 73% cheaper per outcome than Opus alone. One case is thin evidence; it shows the direction.
182
+
183
+ **Then make it cheaper again, one lever at a time.** A fifth run tested five levers on that setup, each with an estimate written down first. Sonnet as the rescuer instead of Opus: −58% cost, same quality. Lower effort, dropping an over-strict rule, and checking only the topics the product owner marks high-risk: −29% to −45% each. All three stacked: −75%, but the quality gain was gone. `valueproof compare` prints this keep-or-drop ledger itself.
151
184
 
152
185
  **Good for cost, with a quality trade-off.** Most cheap replies were good, but some were weaker in ways no check saw, and one stated a wrong refund rule. Use it where a few percent of quality is acceptable, or where your checks catch the mistakes that matter; keep refund, money and legal answers on the strong model until they do. → [Full results, caveats and how to rerun it](https://github.com/AndyJakob78/valueproof/blob/main/docs/support-test.md)
153
186
 
@@ -177,22 +210,11 @@ flowchart LR
177
210
 
178
211
  The checks decide the quality: a mistake no check catches goes straight to the user at the cheap price.
179
212
 
180
- **Expect a small quality cost.** Requests that pass the check are only as good as the cheap model's answer. In our support test, Scout & Rescue cost 81–88% less than the strong model alone and scored 2–6% lower in a blind review — a much stronger cost lever than tuning the strong model, with a quality trade-off you should measure for your own task. How much quality you keep depends mostly on your checks.
213
+ **Expect a small quality cost.** Requests that pass the check are only as good as the cheap model's answer. In our support test, Scout & Rescue cost 81–92% less than the strong model alone and scored 2–6% lower in a blind review — a much stronger cost lever than tuning the strong model, with a quality trade-off you should measure for your own task. How much quality you keep depends mostly on your checks.
181
214
 
182
- ```python
183
- from valueproof import scout_and_rescue
184
- from valueproof.claude import claude
215
+ The code for this is in the [quick start](#quick-start) at the top.
185
216
 
186
- outcome = scout_and_rescue(
187
- prompt, # your request
188
- scout=claude("claude-haiku-5-5"),
189
- rescue=claude("claude-opus-5-5"),
190
- check=lambda text: None if order_id in text else "does not mention the order id", # order_id from your data
191
- )
192
- print(outcome.path, outcome.cost_usd) # "scout" or "rescue" - how often each runs depends on your checks
193
- ```
194
-
195
- **Install** (version 0.5, early: the API may still change; Python 3.10+, Gemini adapter 3.11+):
217
+ **Install** (version 0.6, early: the API may still change; Python 3.10+, Gemini adapter 3.11+):
196
218
 
197
219
  ```bash
198
220
  pip install "valueproof[claude]"
@@ -200,11 +222,6 @@ pip install "valueproof[claude]"
200
222
 
201
223
  One name for everything: `pip install valueproof`, `import valueproof`, `valueproof compare`. (Until version 0.3 the package was called `ai-mixed-model-cost-optimization`; the old name still installs and pulls in `valueproof`.)
202
224
 
203
- ```python
204
- from valueproof import scout_and_rescue
205
- from valueproof.claude import claude # or .openai / .gemini
206
- ```
207
-
208
225
  The core has no dependencies and works with any provider: a model is just a function `prompt -> ModelResult`. Adapters come as extras: `[claude]`, `[openai]`, `[gemini]` or `[all]`. For a local model, write a function with the same shape.
209
226
 
210
227
  **Test a change on your own requests** with one command — it runs every setup on every request, side by side, and prints cost (average and median), rescue rate, time, check failures and blind-review quality:
@@ -215,13 +232,13 @@ valueproof compare my_test.py --live --estimate # runs 2 requests for real,
215
232
  valueproof compare my_test.py --live --max-spend 5 # the full test, stops starting new requests at $5
216
233
  ```
217
234
 
218
- After the table it lists **which check rule fired most often**, so you see whether rescues come from formatting, missing fields or stale data.
235
+ If your test file names its levers, it prints the **lever ledger**: each lever against the setup it changes, your estimate from before the test, and a keep-or-drop verdict. After the table it lists **which check rule fired most often**, and **how good your eval checks are**: how many of the judge's hard failures they caught, how many they missed, and how many false alarms they raised. In our own support test the answer was sobering: the code checks caught 0 of 7 hard failures. You can also **rate candidate eval checks** before you build on one: with a policy check done by a cheap model, the one hard failure in that run was caught and fixed, for about twice the cost per reply. → [Support test](https://github.com/AndyJakob78/valueproof/blob/main/docs/support-test.md)
219
236
 
220
237
  → How to write `my_test.py`, plus a support-ticket demo that works without an API key: [examples/](https://github.com/AndyJakob78/valueproof/blob/main/examples/). The live Claude mode was run in the [support test](https://github.com/AndyJakob78/valueproof/blob/main/docs/support-test.md).
221
238
 
222
239
  **A second, smaller lever: lower effort on the strong model.** In the same test, running the rescuer at effort low instead of medium cost 24–25% less in two runs, with no measurable quality loss on the rescued tickets. Measured on short support replies only.
223
240
 
224
- **3. Prove every change before you ship it.** Change one thing at a time. Run the old and new versions side by side on the same requests. Review quality blind, as A vs. B. Keep only what saves money *and* holds quality.
241
+ **3. Prove every change before you ship it.** Change one thing at a time. Run the old and new versions side by side on the same requests. Review quality blind: the reviewer never knows which setup wrote a result. Keep only what saves money *and* holds quality.
225
242
 
226
243
  The test setup is an **eval**: a fixed set of real requests, checks in code and a blind review, built once and reused for every change. Without it you can't tell a saving from a quality loss.
227
244
 
@@ -235,6 +252,23 @@ flowchart LR
235
252
  L -- "no levers left" --> S["4. Test all kept levers together,<br/>ship, keep measuring"]
236
253
  ```
237
254
 
255
+ **How the blind review works.** `valueproof compare` supports two reviewers, and you can use both:
256
+
257
+ - **LLM-as-judge:** you pass a `judge(case, text) -> Score` function. It gets one result at a time, in random order, and never the setup's name. Give it the reference that defines "right" (the policy, the fact sheet, the help article); without it a judge can only tell whether an answer looks usable, not whether it is correct.
258
+ - **A person:** every run also writes `blind_review.csv` (the results, shuffled, no setup names) and `blind_key.csv` (which setup wrote which). Score the sheet, then map it back with the key.
259
+
260
+ The rubric from our support test, as an example — four criteria, 0–10 each, plus one flag:
261
+
262
+ | Criterion | The question |
263
+ |---|---|
264
+ | Policy correct | Does the reply follow the policy exactly, with no wrong rule? |
265
+ | Solves | Does it answer every issue in the ticket and name the next step? |
266
+ | Tone | Friendly, calm, fitting the customer's mood? |
267
+ | Clarity | Short and clear? |
268
+ | **Hard failure** (yes/no) | A wrong policy rule, a promise the policy doesn't allow, an invented order number, or no answer |
269
+
270
+ Hard failures are counted separately, so no average can hide them. For scoring two results side by side as A and B by hand, see the [rubric template](https://github.com/AndyJakob78/valueproof/blob/main/templates/blind-review-rubric.md).
271
+
238
272
  The full flow, with the cost breakdown and the ledger: [method.md](https://github.com/AndyJakob78/valueproof/blob/main/docs/method.md#the-flow)
239
273
 
240
274
  → The step-by-step method: [docs/method.md](https://github.com/AndyJakob78/valueproof/blob/main/docs/method.md) · Templates: [templates/](https://github.com/AndyJakob78/valueproof/blob/main/templates/)
@@ -263,10 +297,12 @@ We tested 12 cost-saving ideas one at a time, and **7 raised cost or lowered qua
263
297
  - **Token:** the unit AI providers bill by — roughly a short word of text the model reads or writes.
264
298
  - **Lever:** one change that should lower cost, such as a smaller model or a shorter prompt. Each lever is tested on its own.
265
299
  - **Scout:** the cheap, fast model that tries first.
266
- - **Rescuer:** the strong model that runs only when a check in code rejects the scout's result.
300
+ - **Rescuer:** the strong model that runs only when an eval check rejects the scout's result.
301
+ - **Eval check:** a rule in code that judges one answer at runtime (a code-based eval): is it empty, is a field missing, is the date too old? It decides whether the cheap answer is used or the rescuer runs. The pages here also call it a "check in code" or just "check".
302
+ - **Check quality:** how well the eval checks agree with the blind review: caught, missed, false alarms.
267
303
  - **Full web search:** a search tool that filters the results with code before the model reads them. Fewer pages to read, but more steps.
268
304
  - **Simple web search:** a search tool that hands the raw results straight to the model. Fewer steps; the model reads everything it gets, which is cheap on a small model but expensive on a large one.
269
- - **Blind review:** a reviewer scores two results labelled only A and B, without knowing which setup made which.
305
+ - **Blind review:** a reviewer scores results on a fixed rubric without knowing which setup wrote them. The reviewer can be a model (LLM-as-judge) or a person.
270
306
  - **Eval:** the fixed test that decides whether a change is kept — real requests, checks in code and a blind review, run the same way every time.
271
307
  - **Outcome:** a request whose final result passed your checks and, if reviewed, had no hard failure — a result a user could rely on.
272
308
  - **Cost per outcome:** everything a setup spent, including failed and rescued attempts, divided by its outcomes. The number to compare.
@@ -0,0 +1,158 @@
1
+ import json
2
+ import shutil
3
+ import subprocess
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from valueproof import Run, Score, check_quality, estimate, ledger_markdown, lever_ledger, load_report, rate_checks, print_table, run_levers, save, summarize
8
+ from valueproof.cli import main
9
+
10
+ ROOT = Path(__file__).resolve().parent.parent
11
+
12
+
13
+ def test_run_levers_table_and_files(tmp_path, capsys):
14
+ cases = ["a", "b"]
15
+ setups = {
16
+ "base": lambda c: Run("x" + c, 0.01, 1.0, "single"),
17
+ "new": lambda c: Run("y" + c, 0.002, 0.5, "rescue" if c == "b" else "scout"),
18
+ }
19
+ report = run_levers(cases, setups, judge=lambda c, t: Score(30, 40))
20
+ assert len(report.rows) == 4 and all(r.score.points == 30 for r in report.rows)
21
+ print_table(report, list(setups))
22
+ out = capsys.readouterr().out
23
+ assert "-80%" in out and "1/2" in out and "cost/outcome" in out
24
+ save(report, cases, tmp_path, describe=str)
25
+ assert len(json.loads((tmp_path / "results.json").read_text())) == 4
26
+ assert (tmp_path / "blind_review.csv").exists() and (tmp_path / "blind_key.csv").exists()
27
+
28
+
29
+ def test_cost_per_outcome_counts_failures_as_spent_but_not_delivered():
30
+ setups = {
31
+ "base": lambda c: Run("ok", 0.01, 1.0),
32
+ "cheap": lambda c: Run("bad" if c == "b" else "ok", 0.002, 1.0, final_check="too short" if c == "b" else None),
33
+ }
34
+ judge = lambda c, t: Score(30, 40, hard_failure=(c == "c"))
35
+ s = {x["setup"]: x for x in summarize(run_levers(["a", "b", "c", "d"], setups, judge=judge), list(setups))}
36
+ # base: 4 x 0.01 spent, request "c" has a hard failure -> 3 outcomes
37
+ assert s["base"]["outcomes"] == 3 and abs(s["base"]["cost_per_outcome"] - 0.04 / 3) < 1e-12
38
+ # cheap: "b" fails the check, "c" has a hard failure -> 2 outcomes for 0.008
39
+ assert s["cheap"]["outcomes"] == 2 and abs(s["cheap"]["cost_per_outcome"] - 0.004) < 1e-12
40
+
41
+
42
+ def test_init_then_compare(tmp_path, capsys, monkeypatch):
43
+ monkeypatch.chdir(tmp_path)
44
+ main(["init", "my_test.py"])
45
+ main(["compare", "my_test.py", "--out", str(tmp_path / "out")])
46
+ out = capsys.readouterr().out
47
+ assert "Scout & Rescue" in out and "1/3" in out # the fake cheap model fails one request
48
+ assert (tmp_path / "out" / "results.json").exists()
49
+
50
+
51
+ def test_bundled_examples_run_offline(tmp_path):
52
+ results = ROOT / "examples" / "results"
53
+ before = set(results.iterdir()) if results.exists() else set()
54
+ for args in (["examples/demo_support.py"], ["examples/test_levers_support.py", "--hard"]):
55
+ r = subprocess.run([sys.executable, *args], cwd=ROOT, capture_output=True, text=True)
56
+ assert r.returncode == 0, r.stderr
57
+ for new in set(results.iterdir()) - before: # remove only what this test wrote
58
+ shutil.rmtree(new)
59
+
60
+
61
+ def test_max_spend_stops_between_cases_and_keeps_pairs():
62
+ setups = {"a": lambda c: Run("x", 0.01, 0.1), "b": lambda c: Run("y", 0.02, 0.1)}
63
+ report = run_levers(list(range(10)), setups, max_spend=0.05)
64
+ # each case costs 0.03; after 2 cases (0.06) no new case starts
65
+ assert len({r.case for r in report.rows}) == 2 and len(report.rows) == 4
66
+ assert report.stopped and abs(report.spent_usd - 0.06) < 1e-12
67
+
68
+
69
+ def test_review_skipped_when_it_would_pass_the_limit():
70
+ setups = {"a": lambda c: Run("x" + str(c), 0.01, 0.1)}
71
+ report = run_levers([1, 2], setups, judge=lambda c, t: Score(30, 40, cost_usd=0.05), max_spend=0.04)
72
+ assert all(r.score is None for r in report.rows) and "review" in report.stopped
73
+
74
+
75
+ def test_estimate_projects_from_a_sample():
76
+ setups = {"a": lambda c: Run("x", 0.01, 0.1), "b": lambda c: Run("y", 0.03, 0.1)}
77
+ e = estimate(list(range(50)), setups, judge=lambda c, t: Score(30, 40, cost_usd=0.005), sample=2)
78
+ # per case: 0.04 runs + 2 reviews x 0.005 = 0.05 -> 50 cases = 2.50
79
+ assert e["sample_cases"] == 2 and abs(e["projected_total"] - 2.5) < 1e-9
80
+
81
+
82
+ def test_rejection_reasons_are_grouped(capsys):
83
+ reasons = ["does not cite §1", "does not cite §5, §6", None, "too short"]
84
+ setups = {"s&r": lambda c: Run("t", 0.01, 0.1, "rescue" if reasons[c] else "scout",
85
+ rejected_because=reasons[c])}
86
+ report = run_levers(list(range(4)), setups)
87
+ s = summarize(report, ["s&r"])[0]
88
+ assert s["first_try_rejections"]["does not cite #"] == 2 and s["first_try_pass"] == 1
89
+ print_table(report, ["s&r"])
90
+ assert "does not cite # (2)" in capsys.readouterr().out
91
+
92
+
93
+ def test_check_quality_counts_caught_missed_and_false_alarms(capsys):
94
+ # request: (text, check verdict, judge points, judge hard failure) for the cheap setup
95
+ cheap = {0: ("a", None, 36, False), # fine, passed
96
+ 1: ("b", "too short", 20, True), # bad, caught
97
+ 2: ("c", None, 22, True), # bad, missed
98
+ 3: ("d", "no id", 35, False), # fine, false alarm
99
+ 4: ("e", None, 30, False)} # passed, but clearly weaker than the baseline
100
+ setups = {"base": lambda c: Run("base" + str(c), 0.01, 0.1),
101
+ "cheap": lambda c: Run(cheap[c][0], 0.001, 0.1, final_check=cheap[c][1])}
102
+ def judge(c, text):
103
+ if text.startswith("base"):
104
+ return Score(36, 40)
105
+ _, _, pts, hard = cheap[c]
106
+ return Score(pts, 40, hard)
107
+ report = run_levers(list(range(5)), setups, judge=judge)
108
+ q = check_quality(report, list(setups))
109
+ assert (q["hard_failures"], q["caught"], q["missed"], q["false_alarms"]) == (2, 1, 1, 1)
110
+ assert (q["weaker"], q["weaker_flagged"]) == (3, 1) # b, c and e are 5+ points below; only b was flagged
111
+ print_table(report, list(setups))
112
+ assert "caught 1, missed 1" in capsys.readouterr().out
113
+ assert check_quality(run_levers([0], setups), list(setups)) is None # no judge, no verdict
114
+
115
+
116
+ def test_rate_checks_compares_candidates_and_counts_their_cost():
117
+ setups = {"base": lambda c: Run("good", 0.01, 0.1), "cheap": lambda c: Run("bad" if c == 1 else "fine", 0.001, 0.1)}
118
+ judge = lambda c, text: Score(10 if text == "bad" else 36, 40, hard_failure=(text == "bad"))
119
+ report = run_levers([0, 1], setups, judge=judge)
120
+ before = report.spent_usd
121
+ ratings = rate_checks(report, [0, 1], list(setups), {
122
+ "blind check": lambda case, text: None,
123
+ "sharp check": lambda case, text: ("is bad", 0.002) if text == "bad" else (None, 0.002),
124
+ })
125
+ assert (ratings["blind check"]["caught"], ratings["blind check"]["missed"]) == (0, 1)
126
+ assert (ratings["sharp check"]["caught"], ratings["sharp check"]["missed"], ratings["sharp check"]["false_alarms"]) == (1, 0, 0)
127
+ assert abs(report.spent_usd - before - 0.008) < 1e-12 # 4 distinct replies x 0.002
128
+
129
+
130
+ def test_saved_results_can_be_rated_again(tmp_path):
131
+ setups = {"base": lambda c: Run("good", 0.01, 0.1), "cheap": lambda c: Run("bad", 0.001, 0.1)}
132
+ report = run_levers([0], setups, judge=lambda c, t: Score(10 if t == "bad" else 36, 40, hard_failure=(t == "bad")))
133
+ save(report, [0], tmp_path, describe=str)
134
+ again = load_report(tmp_path / "results.json")
135
+ assert len(again.rows) == 2 and again.rows[0].score.max_points == 40
136
+ r = rate_checks(again, [0], ["base", "cheap"], {"sharp": lambda case, text: "bad" if text == "bad" else None})
137
+ assert (r["sharp"]["caught"], r["sharp"]["missed"]) == (1, 0)
138
+
139
+
140
+ def test_lever_ledger_keeps_cheaper_levers_that_hold_quality():
141
+ setups = {"today": lambda c: Run("t", 0.010, 2.0),
142
+ "cheap ok": lambda c: Run("a", 0.004, 1.5),
143
+ "cheap worse": lambda c: Run("b", 0.003, 1.5),
144
+ "dearer": lambda c: Run("d", 0.020, 2.5),
145
+ "dearer but better": lambda c: Run("e", 0.020, 2.5)}
146
+ points = {"t": 36, "a": 36, "b": 30, "d": 36, "e": 40}
147
+ report = run_levers([0, 1], setups, judge=lambda c, text: Score(points[text], 40))
148
+ levers = {n: {"baseline": "today", "estimate": "guess"}
149
+ for n in ("cheap ok", "cheap worse", "dearer", "dearer but better", "not run")}
150
+ rows = {r["lever"]: r for r in lever_ledger(report, levers)}
151
+ assert set(rows) == {"cheap ok", "cheap worse", "dearer", "dearer but better"} # one that did not run is left out
152
+ assert rows["dearer but better"]["verdict"] == "costs more, buys quality: your call"
153
+ assert rows["cheap ok"]["verdict"] == "keep" and round(rows["cheap ok"]["cost_change"], 2) == -0.6
154
+ assert rows["cheap worse"]["verdict"] == "drop: quality fell" and rows["cheap worse"]["quality_change"] == -12
155
+ assert rows["dearer"]["verdict"] == "drop: not cheaper"
156
+ assert "**keep**" in ledger_markdown(list(rows.values()))
157
+ no_judge = lever_ledger(run_levers([0], setups), levers)
158
+ assert no_judge[0]["verdict"] == "cheaper (quality not reviewed)"
@@ -1,90 +0,0 @@
1
- import json
2
- import shutil
3
- import subprocess
4
- import sys
5
- from pathlib import Path
6
-
7
- from valueproof import Run, Score, estimate, print_table, run_levers, save, summarize
8
- from valueproof.cli import main
9
-
10
- ROOT = Path(__file__).resolve().parent.parent
11
-
12
-
13
- def test_run_levers_table_and_files(tmp_path, capsys):
14
- cases = ["a", "b"]
15
- setups = {
16
- "base": lambda c: Run("x" + c, 0.01, 1.0, "single"),
17
- "new": lambda c: Run("y" + c, 0.002, 0.5, "rescue" if c == "b" else "scout"),
18
- }
19
- report = run_levers(cases, setups, judge=lambda c, t: Score(30, 40))
20
- assert len(report.rows) == 4 and all(r.score.points == 30 for r in report.rows)
21
- print_table(report, list(setups))
22
- out = capsys.readouterr().out
23
- assert "-80%" in out and "1/2" in out and "cost/outcome" in out
24
- save(report, cases, tmp_path, describe=str)
25
- assert len(json.loads((tmp_path / "results.json").read_text())) == 4
26
- assert (tmp_path / "blind_review.csv").exists() and (tmp_path / "blind_key.csv").exists()
27
-
28
-
29
- def test_cost_per_outcome_counts_failures_as_spent_but_not_delivered():
30
- setups = {
31
- "base": lambda c: Run("ok", 0.01, 1.0),
32
- "cheap": lambda c: Run("bad" if c == "b" else "ok", 0.002, 1.0, final_check="too short" if c == "b" else None),
33
- }
34
- judge = lambda c, t: Score(30, 40, hard_failure=(c == "c"))
35
- s = {x["setup"]: x for x in summarize(run_levers(["a", "b", "c", "d"], setups, judge=judge), list(setups))}
36
- # base: 4 x 0.01 spent, request "c" has a hard failure -> 3 outcomes
37
- assert s["base"]["outcomes"] == 3 and abs(s["base"]["cost_per_outcome"] - 0.04 / 3) < 1e-12
38
- # cheap: "b" fails the check, "c" has a hard failure -> 2 outcomes for 0.008
39
- assert s["cheap"]["outcomes"] == 2 and abs(s["cheap"]["cost_per_outcome"] - 0.004) < 1e-12
40
-
41
-
42
- def test_init_then_compare(tmp_path, capsys, monkeypatch):
43
- monkeypatch.chdir(tmp_path)
44
- main(["init", "my_test.py"])
45
- main(["compare", "my_test.py", "--out", str(tmp_path / "out")])
46
- out = capsys.readouterr().out
47
- assert "Scout & Rescue" in out and "1/3" in out # the fake cheap model fails one request
48
- assert (tmp_path / "out" / "results.json").exists()
49
-
50
-
51
- def test_bundled_examples_run_offline(tmp_path):
52
- results = ROOT / "examples" / "results"
53
- before = set(results.iterdir()) if results.exists() else set()
54
- for args in (["examples/demo_support.py"], ["examples/test_levers_support.py", "--hard"]):
55
- r = subprocess.run([sys.executable, *args], cwd=ROOT, capture_output=True, text=True)
56
- assert r.returncode == 0, r.stderr
57
- for new in set(results.iterdir()) - before: # remove only what this test wrote
58
- shutil.rmtree(new)
59
-
60
-
61
- def test_max_spend_stops_between_cases_and_keeps_pairs():
62
- setups = {"a": lambda c: Run("x", 0.01, 0.1), "b": lambda c: Run("y", 0.02, 0.1)}
63
- report = run_levers(list(range(10)), setups, max_spend=0.05)
64
- # each case costs 0.03; after 2 cases (0.06) no new case starts
65
- assert len({r.case for r in report.rows}) == 2 and len(report.rows) == 4
66
- assert report.stopped and abs(report.spent_usd - 0.06) < 1e-12
67
-
68
-
69
- def test_review_skipped_when_it_would_pass_the_limit():
70
- setups = {"a": lambda c: Run("x" + str(c), 0.01, 0.1)}
71
- report = run_levers([1, 2], setups, judge=lambda c, t: Score(30, 40, cost_usd=0.05), max_spend=0.04)
72
- assert all(r.score is None for r in report.rows) and "review" in report.stopped
73
-
74
-
75
- def test_estimate_projects_from_a_sample():
76
- setups = {"a": lambda c: Run("x", 0.01, 0.1), "b": lambda c: Run("y", 0.03, 0.1)}
77
- e = estimate(list(range(50)), setups, judge=lambda c, t: Score(30, 40, cost_usd=0.005), sample=2)
78
- # per case: 0.04 runs + 2 reviews x 0.005 = 0.05 -> 50 cases = 2.50
79
- assert e["sample_cases"] == 2 and abs(e["projected_total"] - 2.5) < 1e-9
80
-
81
-
82
- def test_rejection_reasons_are_grouped(capsys):
83
- reasons = ["does not cite §1", "does not cite §5, §6", None, "too short"]
84
- setups = {"s&r": lambda c: Run("t", 0.01, 0.1, "rescue" if reasons[c] else "scout",
85
- rejected_because=reasons[c])}
86
- report = run_levers(list(range(4)), setups)
87
- s = summarize(report, ["s&r"])[0]
88
- assert s["first_try_rejections"]["does not cite #"] == 2 and s["first_try_pass"] == 1
89
- print_table(report, ["s&r"])
90
- assert "does not cite # (2)" in capsys.readouterr().out
File without changes
File without changes