ai-mixed-model-cost-optimization 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AI Mixed Model Cost Optimization contributors
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,198 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai-mixed-model-cost-optimization
3
+ Version: 0.1.0
4
+ Summary: Let cheap and strong AI models work together (Scout & Rescue), and test each cost change against your current setup with a blind quality review.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/AndyJakob78/ai-mixed-model-cost-optimization
7
+ Keywords: llm,cost,model cascade,evaluation,finops,llmops
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE-CODE
14
+ Provides-Extra: claude
15
+ Requires-Dist: anthropic>=2.14; extra == "claude"
16
+ Dynamic: license-file
17
+
18
+ # AI Mixed Model Cost Optimization
19
+
20
+ **Cut the running cost of AI features by letting cheap and strong models work together — and measure what each change does to quality before it ships.**
21
+
22
+ **In 30 seconds:**
23
+ - **What it is:** a method and sample code. 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, with a blind quality review.
24
+ - **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, replies cost 81–88% less than Claude Opus 5.5 alone.
25
+ - **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.
26
+
27
+ ## When it fits
28
+
29
+ It fits when your product sends a lot of requests to a frontier model — such as Claude Opus 5.5 or Fable 5.2, GPT-6.2 Astra, or Gemini 4 Carbon — to read, analyze, review or summarize data. For example:
30
+ - support chatbots
31
+ - code-review bots
32
+ - data extraction
33
+ - search and research assistants
34
+ - document summarizers
35
+
36
+ And most of those requests are routine, and a bad result can be detected in code: an empty result, a missing field, an outdated date, or an invalid format.
37
+
38
+ ## Target audience
39
+
40
+ | Role | What you get |
41
+ |---|---|
42
+ | **Product Manager** | A way to cut AI cost per user with evidence, and to defend every keep-or-drop decision |
43
+ | **System Designer** | A pattern for splitting one AI job into steps, each with the right model |
44
+ | **AI Engineer** | A small Python package: Scout & Rescue, multi-model pipelines, and a test runner (`mmco compare`) |
45
+ | **Prompt & Context Engineer** | A test routine that shows whether a prompt change really saves tokens — or quietly costs more |
46
+ | **AI Builder** | A way to test cheaper setups for an AI app on a small budget, and keep only those that hold quality |
47
+ | **AI Evaluation** | A blind A/B review setup and a fixed scoring sheet |
48
+ | **LLMOps** | Code checks and logging that track how often the expensive model runs |
49
+ | **FinOps** | A clear before-and-after cost per request, and the yearly saving at your scale |
50
+
51
+ ## The problem
52
+
53
+ Some AI features cannot afford a weak answer. **Compliance, regulation or safety** may demand it — a wrong fact in a financial, medical or legal answer is a real risk. Or the **user experience** depends on it — one confidently wrong answer and users stop trusting the product.
54
+
55
+ So teams do the safe thing: **one strong model does the whole job, end to end, for every request.** Quality is high. But:
56
+ - **You pay top price for easy work.** Most requests are routine and don't need the strongest model. They are still billed at its rate.
57
+ - **The cost grows with every user.** At scale, a request can cost more than it earns.
58
+ - **The usual fixes put quality at risk.** "Switch to a smaller model" or "shorten the prompt" may save money, or may quietly lower quality, or may even raise cost. Without a test, you can't tell.
59
+
60
+ **What this method can and cannot do:** it saves money on the requests where a cheap model's mistakes can be caught by a check in code — an empty result, a missing field, an old date, an invalid format. It does **not** catch an answer that looks right but is wrong, such as a plausible but false refund rule. Where such errors carry legal or safety risk, either build a check that really catches them, or keep that step on the strong model.
61
+
62
+ ### Real-world signals (2026)
63
+
64
+ **AI cost is squeezing companies:**
65
+ - **Harvey** (legal AI): in March it updated its AI agents, and customers began using them far more — token use grew about 20× during the year. Harvey mostly charges customers a fixed price per seat but pays the model providers per token, so its gross margin reportedly fell from about **+50% to −50%** by June: serving customers cost about $1.50 for every $1 of revenue. In August it moved its flagship to its own model built on an open-weight model, and margins reportedly turned positive again. [Bloomberg](https://www.bloomberg.com/news/articles/2026-09-21/startups-like-harvey-embrace-open-models-to-cut-reliance-on-anthropic-openai) · [Artificial Lawyer](https://artificiallawyer.com/2026/07/08/harvey-increases-token-use-14x-in-just-6-months)
66
+ - **Industry survey** (Mavvrik, a cost-management vendor, with Benchmarkit; 396 companies, April–May 2026):
67
+ - **62%** say an unexpected AI cost changed a business decision in the past year. Of those, 40% had to escalate it to the board, 33% froze spending, and 25% delayed or cancelled an AI project.
68
+ - **49%** had to raise prices of their AI products because costs rose more than expected.
69
+ - Only **11%** can forecast their AI spend within ±10% (down from 15% in 2025).
70
+ - **43%** name token costs as a top source of surprise spend. Agents are a growing blind spot: almost all companies run them, but only about a third include them in cost reports.
71
+ - [Channel Insider](https://www.channelinsider.com/ai/mavvrik-state-of-ai-cost-governance/) · [CFO Dive](https://cfodive.com/news/1-in-4-companies-delay-cancel-ai-projects-over-cost/827524) · [Diginomica](https://diginomica.com/tokenomics-ai-bill-shock-goes-mainstream-key-cost-driver-becomes-task-complexity)
72
+
73
+ **And when an AI answer is wrong, courts hold the company liable:**
74
+ - **Hamm, Germany (May 2026):** a clinic's website chatbot invented specialist titles for its doctors. The Higher Regional Court held the clinic responsible — even though the bot had been trained on correct data and was run by an IT provider. Switching the bot off was not enough; the clinic also had to sign a cease-and-desist declaration. Not yet final: an appeal to the Federal Court of Justice is allowed. [Court press release (German)](https://www.justiz.nrw/presse/2026-05-12) · [DLA Piper](https://www.dlapiper.com/en/insights/publications/2026/06/german-court-addresses-liability)
75
+ - **Munich, Germany (May 2026):** Google's AI Overviews made false claims about two publishers that did not appear in the linked sources. The Regional Court of Munich treated the AI summary as Google's own statement and barred Google from repeating it, with fines of up to €250,000 per violation. Not yet final. [Court press release (German)](https://www.justiz.bayern.de/gerichte-und-behoerden/landgericht/muenchen-1/presse/2026/13.php) · [The Decoder](https://the-decoder.com/landmark-german-ruling-declares-googles-ai-overviews-are-googles-own-words-and-makes-it-liable-for-false-answers/)
76
+
77
+ The lesson: cut cost **and** prove quality, one change at a time — with tests on real requests, not just offline benchmarks.
78
+
79
+ ### What this looked like for us
80
+
81
+ **The project:** a live language-learning app that turns current local news into reading lessons. Every lesson starts with an AI step that searches the web for one fresh, **true** story. A wrong or outdated fact would be taught to the learner as true, so we ran this step on a strong model for every lesson: **Claude Sonnet 5.5 with full web search**. It cost **9.7 cents per article**. A lesson uses AI twice: once to find the story and once to write the lesson. Finding the story was about half of the lesson's total AI cost, and every lesson a free user read was paid for out of pocket.
82
+
83
+ **Before and after, per article:**
84
+
85
+ | | Before | After | What it means |
86
+ |---|---|---|---|
87
+ | Setup | Claude Sonnet 5.5 + full web search, for every article | **Scout:** Claude Haiku 5.5 + simple web search. **Rescue:** Sonnet 5.5 + full web search | The rescuer runs only when a code check finds no usable story or only an old one — 2 to 5 of every 18 articles. |
88
+ | Cost per article (average) | 9.7 ¢ | **4.6 – 7.7 ¢ (−53% to −21%)** | Depends on how often the rescuer runs (2 to 5 of every 18 articles across our runs); rescued articles pay for both attempts. The final combined test against production gave 4.6 ¢. |
89
+ | Cost per article (typical) | 9.2 ¢ | **2.6 ¢ (−71%)** | Median from the final combined test: most articles finish on the scout. |
90
+ | Quality, blind review (18 articles, max 540) | 434 | **472** | Quality held or improved. This is one blind review of 18 articles, scored by an AI model on a fixed rubric; we did not measure how much this score varies between runs, and in another paired run Scout & Rescue scored level with its competitor (437 vs 429). Likely reasons for the gain: the freshness check sends old stories to the rescuer, and new fact rules keep contact details, guessed descriptions and facts that sources disagree on out of the lesson. We did not measure each reason separately. |
91
+ | Time per search (average) | 34 s | 34 s | Same average, wide spread: in a second comparison run, a typical article took about 14 s on the scout; a rescued article takes the scout's time plus the rescuer's, which pulls the average up. The same setup run twice varies by about ±10%. |
92
+ | Lessons without an article | 0 | 0 | Every one of the 18 test requests ended with a usable story — a test result, not a guarantee. Two cheaper ideas failed here: the scout alone left 1 of 18 learners without a story, and a "lazier" rescuer was 22% cheaper but let old stories through (quality 440 vs 470). |
93
+
94
+ **Over a year:** 1,000 users reading one article a day is 365,000 articles.
95
+
96
+ | | Best run (4.6 ¢) | Most rescues (7.7 ¢) |
97
+ |---|---|---|
98
+ | Before (9.7 ¢ per article) | $35,405 | $35,405 |
99
+ | After | $16,790 | $28,105 |
100
+ | **Saved** | **$18,615** | **$7,300** |
101
+
102
+ Costs cover the search step only, at the API prices of our test, extrapolated from 18 test requests. Your own rescue rate decides where you land.
103
+
104
+ ### A second example: a service chatbot (estimate)
105
+
106
+ An online shop's chatbot sends every turn to Claude Opus 5.5: **2.6 cents per turn, about $156,000 a year** at 500,000 turns a month. Split into steps — Haiku 5.5 to understand the message, Scout & Rescue (Haiku first, Opus only when a check rejects the draft) to answer, and Sonnet 5.5 for one daily summary:
107
+
108
+ | How often Opus is still needed | Cost per year | Saved |
109
+ |---|---|---|
110
+ | 1 in 5 turns | $36,200 | **$119,800 (−77%)** |
111
+ | 2 in 5 turns | $67,400 | **$88,600 (−57%)** |
112
+
113
+ These numbers come from assumptions, not a measurement, and are an upper estimate: they leave out prompt caching, which would make the "before" setup cheaper and the saving smaller. → [Full chatbot example, with the checks and how to prove it](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/example-service-chatbot.md)
114
+
115
+ ### Measured: support replies
116
+
117
+ We then ran the support-reply step of this idea for real: 40 made-up tickets (20 of them hard), Claude Haiku 5.5 as the scout, Opus 5.5 as the rescuer, against Opus 5.5 alone, with a blind review.
118
+
119
+ | | Scout & Rescue | Opus 5.5 alone |
120
+ |---|---|---|
121
+ | Cost per reply | **81–88% less** | — |
122
+ | Quality (blind review, two runs) | **2–6% lower** | — |
123
+ | Hard failures (run 2, 40 tickets) | 3 | 2 |
124
+
125
+ **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/ai-mixed-model-cost-optimization/blob/main/docs/support-test.md)
126
+
127
+ ## The solution
128
+
129
+ **1. Break the job into steps, and give each step the right model.** A recommended starting point — our case study tested this on one step (the search), not a full pipeline.
130
+
131
+ | Step | Recommended starting point |
132
+ |---|---|
133
+ | Read / extract | small, cheap model |
134
+ | Analyze / draft | **Scout & Rescue** (see below) |
135
+ | Review | a check in code where possible |
136
+ | Aggregate | mid-size model, once per batch |
137
+
138
+ **2. Scout & Rescue for the steps that are usually easy but sometimes hard.** A cheap model (the scout) tries first. A strong model (the rescuer) runs only when a check in code says the scout's result is unusable. When most requests pass the check, most finish at the cheap price; the rest get the same strong model you use today.
139
+
140
+ **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.
141
+
142
+ ```python
143
+ from mixed_model_cost import scout_and_rescue
144
+ from mixed_model_cost.claude import claude
145
+
146
+ outcome = scout_and_rescue(
147
+ prompt, # your request
148
+ scout=claude("claude-haiku-5-5"),
149
+ rescue=claude("claude-opus-5-5"),
150
+ check=lambda text: None if order_id in text else "does not mention the order id", # order_id from your data
151
+ )
152
+ print(outcome.path, outcome.cost_usd) # "scout" or "rescue" - how often each runs depends on your checks
153
+ ```
154
+
155
+ **Install** (early version 0.1, Python 3.10+):
156
+
157
+ ```bash
158
+ pip install "ai-mixed-model-cost-optimization[claude] @ git+https://github.com/AndyJakob78/ai-mixed-model-cost-optimization"
159
+ ```
160
+
161
+ The core has no dependencies and works with any provider: a model is just a function `prompt -> ModelResult`. The `[claude]` extra adds the Claude adapter; for OpenAI, Gemini or a local model, write a function with the same shape.
162
+
163
+ **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:
164
+
165
+ ```bash
166
+ mmco compare my_test.py --live
167
+ ```
168
+
169
+ → How to write `my_test.py`, plus a support-ticket demo that works without an API key: [examples/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/examples/). The live Claude mode was run in the [support test](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/support-test.md).
170
+
171
+ **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.
172
+
173
+ **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.
174
+
175
+ → The step-by-step method: [docs/method.md](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/method.md) · Templates: [templates/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/templates/)
176
+
177
+ ## The full story
178
+
179
+ We tested 12 cost-saving ideas one at a time, and **7 raised cost or lowered quality**. For example, a shorter prompt made the model search *more*.
180
+
181
+ → [Case study](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/case-study.md) · [Support test](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/support-test.md) · [Scout & Rescue in detail](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/scout-and-rescue.md) · [Lessons](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/lessons.md)
182
+
183
+ ## Terms used on this page
184
+
185
+ - **Token:** the unit AI providers bill by — roughly a short word of text the model reads or writes.
186
+ - **Lever:** one change that should lower cost, such as a smaller model or a shorter prompt. Each lever is tested on its own.
187
+ - **Scout:** the cheap, fast model that tries first.
188
+ - **Rescuer:** the strong model that runs only when a check in code rejects the scout's result.
189
+ - **Full web search:** a search tool that filters the results with code before the model reads them. Fewer pages to read, but more steps.
190
+ - **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.
191
+ - **Blind review:** a reviewer scores two results labelled only A and B, without knowing which setup made which.
192
+ - **Typical (median):** the middle value — half the requests cost less, half more. Unlike the average, a few expensive outliers don't move it.
193
+
194
+ ## About
195
+
196
+ Built from a real cost-reduction project on a live language-learning app. Engineering, testing and blind reviews were done with an AI coding assistant (Claude); a product owner made every keep-or-drop decision from the results.
197
+
198
+ Text: [CC BY 4.0](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/LICENSE). Code in [src/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/src/) and [examples/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/examples/): [MIT](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/LICENSE-CODE). Use it, adapt it, credit it.
@@ -0,0 +1,181 @@
1
+ # AI Mixed Model Cost Optimization
2
+
3
+ **Cut the running cost of AI features by letting cheap and strong models work together — and measure what each change does to quality before it ships.**
4
+
5
+ **In 30 seconds:**
6
+ - **What it is:** a method and sample code. 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, with a blind quality review.
7
+ - **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, replies cost 81–88% less than Claude Opus 5.5 alone.
8
+ - **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
+
10
+ ## When it fits
11
+
12
+ It fits when your product sends a lot of requests to a frontier model — such as Claude Opus 5.5 or Fable 5.2, GPT-6.2 Astra, or Gemini 4 Carbon — to read, analyze, review or summarize data. For example:
13
+ - support chatbots
14
+ - code-review bots
15
+ - data extraction
16
+ - search and research assistants
17
+ - document summarizers
18
+
19
+ And most of those requests are routine, and a bad result can be detected in code: an empty result, a missing field, an outdated date, or an invalid format.
20
+
21
+ ## Target audience
22
+
23
+ | Role | What you get |
24
+ |---|---|
25
+ | **Product Manager** | A way to cut AI cost per user with evidence, and to defend every keep-or-drop decision |
26
+ | **System Designer** | A pattern for splitting one AI job into steps, each with the right model |
27
+ | **AI Engineer** | A small Python package: Scout & Rescue, multi-model pipelines, and a test runner (`mmco compare`) |
28
+ | **Prompt & Context Engineer** | A test routine that shows whether a prompt change really saves tokens — or quietly costs more |
29
+ | **AI Builder** | A way to test cheaper setups for an AI app on a small budget, and keep only those that hold quality |
30
+ | **AI Evaluation** | A blind A/B review setup and a fixed scoring sheet |
31
+ | **LLMOps** | Code checks and logging that track how often the expensive model runs |
32
+ | **FinOps** | A clear before-and-after cost per request, and the yearly saving at your scale |
33
+
34
+ ## The problem
35
+
36
+ Some AI features cannot afford a weak answer. **Compliance, regulation or safety** may demand it — a wrong fact in a financial, medical or legal answer is a real risk. Or the **user experience** depends on it — one confidently wrong answer and users stop trusting the product.
37
+
38
+ So teams do the safe thing: **one strong model does the whole job, end to end, for every request.** Quality is high. But:
39
+ - **You pay top price for easy work.** Most requests are routine and don't need the strongest model. They are still billed at its rate.
40
+ - **The cost grows with every user.** At scale, a request can cost more than it earns.
41
+ - **The usual fixes put quality at risk.** "Switch to a smaller model" or "shorten the prompt" may save money, or may quietly lower quality, or may even raise cost. Without a test, you can't tell.
42
+
43
+ **What this method can and cannot do:** it saves money on the requests where a cheap model's mistakes can be caught by a check in code — an empty result, a missing field, an old date, an invalid format. It does **not** catch an answer that looks right but is wrong, such as a plausible but false refund rule. Where such errors carry legal or safety risk, either build a check that really catches them, or keep that step on the strong model.
44
+
45
+ ### Real-world signals (2026)
46
+
47
+ **AI cost is squeezing companies:**
48
+ - **Harvey** (legal AI): in March it updated its AI agents, and customers began using them far more — token use grew about 20× during the year. Harvey mostly charges customers a fixed price per seat but pays the model providers per token, so its gross margin reportedly fell from about **+50% to −50%** by June: serving customers cost about $1.50 for every $1 of revenue. In August it moved its flagship to its own model built on an open-weight model, and margins reportedly turned positive again. [Bloomberg](https://www.bloomberg.com/news/articles/2026-09-21/startups-like-harvey-embrace-open-models-to-cut-reliance-on-anthropic-openai) · [Artificial Lawyer](https://artificiallawyer.com/2026/07/08/harvey-increases-token-use-14x-in-just-6-months)
49
+ - **Industry survey** (Mavvrik, a cost-management vendor, with Benchmarkit; 396 companies, April–May 2026):
50
+ - **62%** say an unexpected AI cost changed a business decision in the past year. Of those, 40% had to escalate it to the board, 33% froze spending, and 25% delayed or cancelled an AI project.
51
+ - **49%** had to raise prices of their AI products because costs rose more than expected.
52
+ - Only **11%** can forecast their AI spend within ±10% (down from 15% in 2025).
53
+ - **43%** name token costs as a top source of surprise spend. Agents are a growing blind spot: almost all companies run them, but only about a third include them in cost reports.
54
+ - [Channel Insider](https://www.channelinsider.com/ai/mavvrik-state-of-ai-cost-governance/) · [CFO Dive](https://cfodive.com/news/1-in-4-companies-delay-cancel-ai-projects-over-cost/827524) · [Diginomica](https://diginomica.com/tokenomics-ai-bill-shock-goes-mainstream-key-cost-driver-becomes-task-complexity)
55
+
56
+ **And when an AI answer is wrong, courts hold the company liable:**
57
+ - **Hamm, Germany (May 2026):** a clinic's website chatbot invented specialist titles for its doctors. The Higher Regional Court held the clinic responsible — even though the bot had been trained on correct data and was run by an IT provider. Switching the bot off was not enough; the clinic also had to sign a cease-and-desist declaration. Not yet final: an appeal to the Federal Court of Justice is allowed. [Court press release (German)](https://www.justiz.nrw/presse/2026-05-12) · [DLA Piper](https://www.dlapiper.com/en/insights/publications/2026/06/german-court-addresses-liability)
58
+ - **Munich, Germany (May 2026):** Google's AI Overviews made false claims about two publishers that did not appear in the linked sources. The Regional Court of Munich treated the AI summary as Google's own statement and barred Google from repeating it, with fines of up to €250,000 per violation. Not yet final. [Court press release (German)](https://www.justiz.bayern.de/gerichte-und-behoerden/landgericht/muenchen-1/presse/2026/13.php) · [The Decoder](https://the-decoder.com/landmark-german-ruling-declares-googles-ai-overviews-are-googles-own-words-and-makes-it-liable-for-false-answers/)
59
+
60
+ The lesson: cut cost **and** prove quality, one change at a time — with tests on real requests, not just offline benchmarks.
61
+
62
+ ### What this looked like for us
63
+
64
+ **The project:** a live language-learning app that turns current local news into reading lessons. Every lesson starts with an AI step that searches the web for one fresh, **true** story. A wrong or outdated fact would be taught to the learner as true, so we ran this step on a strong model for every lesson: **Claude Sonnet 5.5 with full web search**. It cost **9.7 cents per article**. A lesson uses AI twice: once to find the story and once to write the lesson. Finding the story was about half of the lesson's total AI cost, and every lesson a free user read was paid for out of pocket.
65
+
66
+ **Before and after, per article:**
67
+
68
+ | | Before | After | What it means |
69
+ |---|---|---|---|
70
+ | Setup | Claude Sonnet 5.5 + full web search, for every article | **Scout:** Claude Haiku 5.5 + simple web search. **Rescue:** Sonnet 5.5 + full web search | The rescuer runs only when a code check finds no usable story or only an old one — 2 to 5 of every 18 articles. |
71
+ | Cost per article (average) | 9.7 ¢ | **4.6 – 7.7 ¢ (−53% to −21%)** | Depends on how often the rescuer runs (2 to 5 of every 18 articles across our runs); rescued articles pay for both attempts. The final combined test against production gave 4.6 ¢. |
72
+ | Cost per article (typical) | 9.2 ¢ | **2.6 ¢ (−71%)** | Median from the final combined test: most articles finish on the scout. |
73
+ | Quality, blind review (18 articles, max 540) | 434 | **472** | Quality held or improved. This is one blind review of 18 articles, scored by an AI model on a fixed rubric; we did not measure how much this score varies between runs, and in another paired run Scout & Rescue scored level with its competitor (437 vs 429). Likely reasons for the gain: the freshness check sends old stories to the rescuer, and new fact rules keep contact details, guessed descriptions and facts that sources disagree on out of the lesson. We did not measure each reason separately. |
74
+ | Time per search (average) | 34 s | 34 s | Same average, wide spread: in a second comparison run, a typical article took about 14 s on the scout; a rescued article takes the scout's time plus the rescuer's, which pulls the average up. The same setup run twice varies by about ±10%. |
75
+ | Lessons without an article | 0 | 0 | Every one of the 18 test requests ended with a usable story — a test result, not a guarantee. Two cheaper ideas failed here: the scout alone left 1 of 18 learners without a story, and a "lazier" rescuer was 22% cheaper but let old stories through (quality 440 vs 470). |
76
+
77
+ **Over a year:** 1,000 users reading one article a day is 365,000 articles.
78
+
79
+ | | Best run (4.6 ¢) | Most rescues (7.7 ¢) |
80
+ |---|---|---|
81
+ | Before (9.7 ¢ per article) | $35,405 | $35,405 |
82
+ | After | $16,790 | $28,105 |
83
+ | **Saved** | **$18,615** | **$7,300** |
84
+
85
+ Costs cover the search step only, at the API prices of our test, extrapolated from 18 test requests. Your own rescue rate decides where you land.
86
+
87
+ ### A second example: a service chatbot (estimate)
88
+
89
+ An online shop's chatbot sends every turn to Claude Opus 5.5: **2.6 cents per turn, about $156,000 a year** at 500,000 turns a month. Split into steps — Haiku 5.5 to understand the message, Scout & Rescue (Haiku first, Opus only when a check rejects the draft) to answer, and Sonnet 5.5 for one daily summary:
90
+
91
+ | How often Opus is still needed | Cost per year | Saved |
92
+ |---|---|---|
93
+ | 1 in 5 turns | $36,200 | **$119,800 (−77%)** |
94
+ | 2 in 5 turns | $67,400 | **$88,600 (−57%)** |
95
+
96
+ These numbers come from assumptions, not a measurement, and are an upper estimate: they leave out prompt caching, which would make the "before" setup cheaper and the saving smaller. → [Full chatbot example, with the checks and how to prove it](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/example-service-chatbot.md)
97
+
98
+ ### Measured: support replies
99
+
100
+ We then ran the support-reply step of this idea for real: 40 made-up tickets (20 of them hard), Claude Haiku 5.5 as the scout, Opus 5.5 as the rescuer, against Opus 5.5 alone, with a blind review.
101
+
102
+ | | Scout & Rescue | Opus 5.5 alone |
103
+ |---|---|---|
104
+ | Cost per reply | **81–88% less** | — |
105
+ | Quality (blind review, two runs) | **2–6% lower** | — |
106
+ | Hard failures (run 2, 40 tickets) | 3 | 2 |
107
+
108
+ **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/ai-mixed-model-cost-optimization/blob/main/docs/support-test.md)
109
+
110
+ ## The solution
111
+
112
+ **1. Break the job into steps, and give each step the right model.** A recommended starting point — our case study tested this on one step (the search), not a full pipeline.
113
+
114
+ | Step | Recommended starting point |
115
+ |---|---|
116
+ | Read / extract | small, cheap model |
117
+ | Analyze / draft | **Scout & Rescue** (see below) |
118
+ | Review | a check in code where possible |
119
+ | Aggregate | mid-size model, once per batch |
120
+
121
+ **2. Scout & Rescue for the steps that are usually easy but sometimes hard.** A cheap model (the scout) tries first. A strong model (the rescuer) runs only when a check in code says the scout's result is unusable. When most requests pass the check, most finish at the cheap price; the rest get the same strong model you use today.
122
+
123
+ **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.
124
+
125
+ ```python
126
+ from mixed_model_cost import scout_and_rescue
127
+ from mixed_model_cost.claude import claude
128
+
129
+ outcome = scout_and_rescue(
130
+ prompt, # your request
131
+ scout=claude("claude-haiku-5-5"),
132
+ rescue=claude("claude-opus-5-5"),
133
+ check=lambda text: None if order_id in text else "does not mention the order id", # order_id from your data
134
+ )
135
+ print(outcome.path, outcome.cost_usd) # "scout" or "rescue" - how often each runs depends on your checks
136
+ ```
137
+
138
+ **Install** (early version 0.1, Python 3.10+):
139
+
140
+ ```bash
141
+ pip install "ai-mixed-model-cost-optimization[claude] @ git+https://github.com/AndyJakob78/ai-mixed-model-cost-optimization"
142
+ ```
143
+
144
+ The core has no dependencies and works with any provider: a model is just a function `prompt -> ModelResult`. The `[claude]` extra adds the Claude adapter; for OpenAI, Gemini or a local model, write a function with the same shape.
145
+
146
+ **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:
147
+
148
+ ```bash
149
+ mmco compare my_test.py --live
150
+ ```
151
+
152
+ → How to write `my_test.py`, plus a support-ticket demo that works without an API key: [examples/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/examples/). The live Claude mode was run in the [support test](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/support-test.md).
153
+
154
+ **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.
155
+
156
+ **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.
157
+
158
+ → The step-by-step method: [docs/method.md](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/method.md) · Templates: [templates/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/templates/)
159
+
160
+ ## The full story
161
+
162
+ We tested 12 cost-saving ideas one at a time, and **7 raised cost or lowered quality**. For example, a shorter prompt made the model search *more*.
163
+
164
+ → [Case study](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/case-study.md) · [Support test](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/support-test.md) · [Scout & Rescue in detail](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/scout-and-rescue.md) · [Lessons](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/lessons.md)
165
+
166
+ ## Terms used on this page
167
+
168
+ - **Token:** the unit AI providers bill by — roughly a short word of text the model reads or writes.
169
+ - **Lever:** one change that should lower cost, such as a smaller model or a shorter prompt. Each lever is tested on its own.
170
+ - **Scout:** the cheap, fast model that tries first.
171
+ - **Rescuer:** the strong model that runs only when a check in code rejects the scout's result.
172
+ - **Full web search:** a search tool that filters the results with code before the model reads them. Fewer pages to read, but more steps.
173
+ - **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.
174
+ - **Blind review:** a reviewer scores two results labelled only A and B, without knowing which setup made which.
175
+ - **Typical (median):** the middle value — half the requests cost less, half more. Unlike the average, a few expensive outliers don't move it.
176
+
177
+ ## About
178
+
179
+ Built from a real cost-reduction project on a live language-learning app. Engineering, testing and blind reviews were done with an AI coding assistant (Claude); a product owner made every keep-or-drop decision from the results.
180
+
181
+ Text: [CC BY 4.0](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/LICENSE). Code in [src/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/src/) and [examples/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/examples/): [MIT](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/LICENSE-CODE). Use it, adapt it, credit it.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ai-mixed-model-cost-optimization"
7
+ version = "0.1.0"
8
+ description = "Let cheap and strong AI models work together (Scout & Rescue), and test each cost change against your current setup with a blind quality review."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE-CODE"]
13
+ keywords = ["llm", "cost", "model cascade", "evaluation", "finops", "llmops"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
18
+ ]
19
+ dependencies = [] # the core has none; any provider works
20
+
21
+ [project.optional-dependencies]
22
+ claude = ["anthropic>=2.14"]
23
+
24
+ [project.scripts]
25
+ mmco = "mixed_model_cost.cli:main"
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/AndyJakob78/ai-mixed-model-cost-optimization"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai-mixed-model-cost-optimization
3
+ Version: 0.1.0
4
+ Summary: Let cheap and strong AI models work together (Scout & Rescue), and test each cost change against your current setup with a blind quality review.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/AndyJakob78/ai-mixed-model-cost-optimization
7
+ Keywords: llm,cost,model cascade,evaluation,finops,llmops
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE-CODE
14
+ Provides-Extra: claude
15
+ Requires-Dist: anthropic>=2.14; extra == "claude"
16
+ Dynamic: license-file
17
+
18
+ # AI Mixed Model Cost Optimization
19
+
20
+ **Cut the running cost of AI features by letting cheap and strong models work together — and measure what each change does to quality before it ships.**
21
+
22
+ **In 30 seconds:**
23
+ - **What it is:** a method and sample code. 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, with a blind quality review.
24
+ - **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, replies cost 81–88% less than Claude Opus 5.5 alone.
25
+ - **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.
26
+
27
+ ## When it fits
28
+
29
+ It fits when your product sends a lot of requests to a frontier model — such as Claude Opus 5.5 or Fable 5.2, GPT-6.2 Astra, or Gemini 4 Carbon — to read, analyze, review or summarize data. For example:
30
+ - support chatbots
31
+ - code-review bots
32
+ - data extraction
33
+ - search and research assistants
34
+ - document summarizers
35
+
36
+ And most of those requests are routine, and a bad result can be detected in code: an empty result, a missing field, an outdated date, or an invalid format.
37
+
38
+ ## Target audience
39
+
40
+ | Role | What you get |
41
+ |---|---|
42
+ | **Product Manager** | A way to cut AI cost per user with evidence, and to defend every keep-or-drop decision |
43
+ | **System Designer** | A pattern for splitting one AI job into steps, each with the right model |
44
+ | **AI Engineer** | A small Python package: Scout & Rescue, multi-model pipelines, and a test runner (`mmco compare`) |
45
+ | **Prompt & Context Engineer** | A test routine that shows whether a prompt change really saves tokens — or quietly costs more |
46
+ | **AI Builder** | A way to test cheaper setups for an AI app on a small budget, and keep only those that hold quality |
47
+ | **AI Evaluation** | A blind A/B review setup and a fixed scoring sheet |
48
+ | **LLMOps** | Code checks and logging that track how often the expensive model runs |
49
+ | **FinOps** | A clear before-and-after cost per request, and the yearly saving at your scale |
50
+
51
+ ## The problem
52
+
53
+ Some AI features cannot afford a weak answer. **Compliance, regulation or safety** may demand it — a wrong fact in a financial, medical or legal answer is a real risk. Or the **user experience** depends on it — one confidently wrong answer and users stop trusting the product.
54
+
55
+ So teams do the safe thing: **one strong model does the whole job, end to end, for every request.** Quality is high. But:
56
+ - **You pay top price for easy work.** Most requests are routine and don't need the strongest model. They are still billed at its rate.
57
+ - **The cost grows with every user.** At scale, a request can cost more than it earns.
58
+ - **The usual fixes put quality at risk.** "Switch to a smaller model" or "shorten the prompt" may save money, or may quietly lower quality, or may even raise cost. Without a test, you can't tell.
59
+
60
+ **What this method can and cannot do:** it saves money on the requests where a cheap model's mistakes can be caught by a check in code — an empty result, a missing field, an old date, an invalid format. It does **not** catch an answer that looks right but is wrong, such as a plausible but false refund rule. Where such errors carry legal or safety risk, either build a check that really catches them, or keep that step on the strong model.
61
+
62
+ ### Real-world signals (2026)
63
+
64
+ **AI cost is squeezing companies:**
65
+ - **Harvey** (legal AI): in March it updated its AI agents, and customers began using them far more — token use grew about 20× during the year. Harvey mostly charges customers a fixed price per seat but pays the model providers per token, so its gross margin reportedly fell from about **+50% to −50%** by June: serving customers cost about $1.50 for every $1 of revenue. In August it moved its flagship to its own model built on an open-weight model, and margins reportedly turned positive again. [Bloomberg](https://www.bloomberg.com/news/articles/2026-09-21/startups-like-harvey-embrace-open-models-to-cut-reliance-on-anthropic-openai) · [Artificial Lawyer](https://artificiallawyer.com/2026/07/08/harvey-increases-token-use-14x-in-just-6-months)
66
+ - **Industry survey** (Mavvrik, a cost-management vendor, with Benchmarkit; 396 companies, April–May 2026):
67
+ - **62%** say an unexpected AI cost changed a business decision in the past year. Of those, 40% had to escalate it to the board, 33% froze spending, and 25% delayed or cancelled an AI project.
68
+ - **49%** had to raise prices of their AI products because costs rose more than expected.
69
+ - Only **11%** can forecast their AI spend within ±10% (down from 15% in 2025).
70
+ - **43%** name token costs as a top source of surprise spend. Agents are a growing blind spot: almost all companies run them, but only about a third include them in cost reports.
71
+ - [Channel Insider](https://www.channelinsider.com/ai/mavvrik-state-of-ai-cost-governance/) · [CFO Dive](https://cfodive.com/news/1-in-4-companies-delay-cancel-ai-projects-over-cost/827524) · [Diginomica](https://diginomica.com/tokenomics-ai-bill-shock-goes-mainstream-key-cost-driver-becomes-task-complexity)
72
+
73
+ **And when an AI answer is wrong, courts hold the company liable:**
74
+ - **Hamm, Germany (May 2026):** a clinic's website chatbot invented specialist titles for its doctors. The Higher Regional Court held the clinic responsible — even though the bot had been trained on correct data and was run by an IT provider. Switching the bot off was not enough; the clinic also had to sign a cease-and-desist declaration. Not yet final: an appeal to the Federal Court of Justice is allowed. [Court press release (German)](https://www.justiz.nrw/presse/2026-05-12) · [DLA Piper](https://www.dlapiper.com/en/insights/publications/2026/06/german-court-addresses-liability)
75
+ - **Munich, Germany (May 2026):** Google's AI Overviews made false claims about two publishers that did not appear in the linked sources. The Regional Court of Munich treated the AI summary as Google's own statement and barred Google from repeating it, with fines of up to €250,000 per violation. Not yet final. [Court press release (German)](https://www.justiz.bayern.de/gerichte-und-behoerden/landgericht/muenchen-1/presse/2026/13.php) · [The Decoder](https://the-decoder.com/landmark-german-ruling-declares-googles-ai-overviews-are-googles-own-words-and-makes-it-liable-for-false-answers/)
76
+
77
+ The lesson: cut cost **and** prove quality, one change at a time — with tests on real requests, not just offline benchmarks.
78
+
79
+ ### What this looked like for us
80
+
81
+ **The project:** a live language-learning app that turns current local news into reading lessons. Every lesson starts with an AI step that searches the web for one fresh, **true** story. A wrong or outdated fact would be taught to the learner as true, so we ran this step on a strong model for every lesson: **Claude Sonnet 5.5 with full web search**. It cost **9.7 cents per article**. A lesson uses AI twice: once to find the story and once to write the lesson. Finding the story was about half of the lesson's total AI cost, and every lesson a free user read was paid for out of pocket.
82
+
83
+ **Before and after, per article:**
84
+
85
+ | | Before | After | What it means |
86
+ |---|---|---|---|
87
+ | Setup | Claude Sonnet 5.5 + full web search, for every article | **Scout:** Claude Haiku 5.5 + simple web search. **Rescue:** Sonnet 5.5 + full web search | The rescuer runs only when a code check finds no usable story or only an old one — 2 to 5 of every 18 articles. |
88
+ | Cost per article (average) | 9.7 ¢ | **4.6 – 7.7 ¢ (−53% to −21%)** | Depends on how often the rescuer runs (2 to 5 of every 18 articles across our runs); rescued articles pay for both attempts. The final combined test against production gave 4.6 ¢. |
89
+ | Cost per article (typical) | 9.2 ¢ | **2.6 ¢ (−71%)** | Median from the final combined test: most articles finish on the scout. |
90
+ | Quality, blind review (18 articles, max 540) | 434 | **472** | Quality held or improved. This is one blind review of 18 articles, scored by an AI model on a fixed rubric; we did not measure how much this score varies between runs, and in another paired run Scout & Rescue scored level with its competitor (437 vs 429). Likely reasons for the gain: the freshness check sends old stories to the rescuer, and new fact rules keep contact details, guessed descriptions and facts that sources disagree on out of the lesson. We did not measure each reason separately. |
91
+ | Time per search (average) | 34 s | 34 s | Same average, wide spread: in a second comparison run, a typical article took about 14 s on the scout; a rescued article takes the scout's time plus the rescuer's, which pulls the average up. The same setup run twice varies by about ±10%. |
92
+ | Lessons without an article | 0 | 0 | Every one of the 18 test requests ended with a usable story — a test result, not a guarantee. Two cheaper ideas failed here: the scout alone left 1 of 18 learners without a story, and a "lazier" rescuer was 22% cheaper but let old stories through (quality 440 vs 470). |
93
+
94
+ **Over a year:** 1,000 users reading one article a day is 365,000 articles.
95
+
96
+ | | Best run (4.6 ¢) | Most rescues (7.7 ¢) |
97
+ |---|---|---|
98
+ | Before (9.7 ¢ per article) | $35,405 | $35,405 |
99
+ | After | $16,790 | $28,105 |
100
+ | **Saved** | **$18,615** | **$7,300** |
101
+
102
+ Costs cover the search step only, at the API prices of our test, extrapolated from 18 test requests. Your own rescue rate decides where you land.
103
+
104
+ ### A second example: a service chatbot (estimate)
105
+
106
+ An online shop's chatbot sends every turn to Claude Opus 5.5: **2.6 cents per turn, about $156,000 a year** at 500,000 turns a month. Split into steps — Haiku 5.5 to understand the message, Scout & Rescue (Haiku first, Opus only when a check rejects the draft) to answer, and Sonnet 5.5 for one daily summary:
107
+
108
+ | How often Opus is still needed | Cost per year | Saved |
109
+ |---|---|---|
110
+ | 1 in 5 turns | $36,200 | **$119,800 (−77%)** |
111
+ | 2 in 5 turns | $67,400 | **$88,600 (−57%)** |
112
+
113
+ These numbers come from assumptions, not a measurement, and are an upper estimate: they leave out prompt caching, which would make the "before" setup cheaper and the saving smaller. → [Full chatbot example, with the checks and how to prove it](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/example-service-chatbot.md)
114
+
115
+ ### Measured: support replies
116
+
117
+ We then ran the support-reply step of this idea for real: 40 made-up tickets (20 of them hard), Claude Haiku 5.5 as the scout, Opus 5.5 as the rescuer, against Opus 5.5 alone, with a blind review.
118
+
119
+ | | Scout & Rescue | Opus 5.5 alone |
120
+ |---|---|---|
121
+ | Cost per reply | **81–88% less** | — |
122
+ | Quality (blind review, two runs) | **2–6% lower** | — |
123
+ | Hard failures (run 2, 40 tickets) | 3 | 2 |
124
+
125
+ **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/ai-mixed-model-cost-optimization/blob/main/docs/support-test.md)
126
+
127
+ ## The solution
128
+
129
+ **1. Break the job into steps, and give each step the right model.** A recommended starting point — our case study tested this on one step (the search), not a full pipeline.
130
+
131
+ | Step | Recommended starting point |
132
+ |---|---|
133
+ | Read / extract | small, cheap model |
134
+ | Analyze / draft | **Scout & Rescue** (see below) |
135
+ | Review | a check in code where possible |
136
+ | Aggregate | mid-size model, once per batch |
137
+
138
+ **2. Scout & Rescue for the steps that are usually easy but sometimes hard.** A cheap model (the scout) tries first. A strong model (the rescuer) runs only when a check in code says the scout's result is unusable. When most requests pass the check, most finish at the cheap price; the rest get the same strong model you use today.
139
+
140
+ **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.
141
+
142
+ ```python
143
+ from mixed_model_cost import scout_and_rescue
144
+ from mixed_model_cost.claude import claude
145
+
146
+ outcome = scout_and_rescue(
147
+ prompt, # your request
148
+ scout=claude("claude-haiku-5-5"),
149
+ rescue=claude("claude-opus-5-5"),
150
+ check=lambda text: None if order_id in text else "does not mention the order id", # order_id from your data
151
+ )
152
+ print(outcome.path, outcome.cost_usd) # "scout" or "rescue" - how often each runs depends on your checks
153
+ ```
154
+
155
+ **Install** (early version 0.1, Python 3.10+):
156
+
157
+ ```bash
158
+ pip install "ai-mixed-model-cost-optimization[claude] @ git+https://github.com/AndyJakob78/ai-mixed-model-cost-optimization"
159
+ ```
160
+
161
+ The core has no dependencies and works with any provider: a model is just a function `prompt -> ModelResult`. The `[claude]` extra adds the Claude adapter; for OpenAI, Gemini or a local model, write a function with the same shape.
162
+
163
+ **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:
164
+
165
+ ```bash
166
+ mmco compare my_test.py --live
167
+ ```
168
+
169
+ → How to write `my_test.py`, plus a support-ticket demo that works without an API key: [examples/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/examples/). The live Claude mode was run in the [support test](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/support-test.md).
170
+
171
+ **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.
172
+
173
+ **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.
174
+
175
+ → The step-by-step method: [docs/method.md](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/method.md) · Templates: [templates/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/templates/)
176
+
177
+ ## The full story
178
+
179
+ We tested 12 cost-saving ideas one at a time, and **7 raised cost or lowered quality**. For example, a shorter prompt made the model search *more*.
180
+
181
+ → [Case study](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/case-study.md) · [Support test](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/support-test.md) · [Scout & Rescue in detail](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/scout-and-rescue.md) · [Lessons](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/docs/lessons.md)
182
+
183
+ ## Terms used on this page
184
+
185
+ - **Token:** the unit AI providers bill by — roughly a short word of text the model reads or writes.
186
+ - **Lever:** one change that should lower cost, such as a smaller model or a shorter prompt. Each lever is tested on its own.
187
+ - **Scout:** the cheap, fast model that tries first.
188
+ - **Rescuer:** the strong model that runs only when a check in code rejects the scout's result.
189
+ - **Full web search:** a search tool that filters the results with code before the model reads them. Fewer pages to read, but more steps.
190
+ - **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.
191
+ - **Blind review:** a reviewer scores two results labelled only A and B, without knowing which setup made which.
192
+ - **Typical (median):** the middle value — half the requests cost less, half more. Unlike the average, a few expensive outliers don't move it.
193
+
194
+ ## About
195
+
196
+ Built from a real cost-reduction project on a live language-learning app. Engineering, testing and blind reviews were done with an AI coding assistant (Claude); a product owner made every keep-or-drop decision from the results.
197
+
198
+ Text: [CC BY 4.0](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/LICENSE). Code in [src/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/src/) and [examples/](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/examples/): [MIT](https://github.com/AndyJakob78/ai-mixed-model-cost-optimization/blob/main/LICENSE-CODE). Use it, adapt it, credit it.
@@ -0,0 +1,15 @@
1
+ LICENSE-CODE
2
+ README.md
3
+ pyproject.toml
4
+ src/ai_mixed_model_cost_optimization.egg-info/PKG-INFO
5
+ src/ai_mixed_model_cost_optimization.egg-info/SOURCES.txt
6
+ src/ai_mixed_model_cost_optimization.egg-info/dependency_links.txt
7
+ src/ai_mixed_model_cost_optimization.egg-info/entry_points.txt
8
+ src/ai_mixed_model_cost_optimization.egg-info/requires.txt
9
+ src/ai_mixed_model_cost_optimization.egg-info/top_level.txt
10
+ src/mixed_model_cost/__init__.py
11
+ src/mixed_model_cost/claude.py
12
+ src/mixed_model_cost/cli.py
13
+ src/mixed_model_cost/lever_runner.py
14
+ src/mixed_model_cost/pipeline.py
15
+ src/mixed_model_cost/scout_rescue.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mmco = mixed_model_cost.cli:main
@@ -0,0 +1,20 @@
1
+ """AI Mixed Model Cost Optimization: let cheap and strong models work together,
2
+ and measure what each change does to cost and quality before it ships.
3
+
4
+ from mixed_model_cost import scout_and_rescue, ModelResult
5
+ from mixed_model_cost.claude import claude # needs the [claude] extra
6
+
7
+ Any provider works: a model is just a function `prompt -> ModelResult`.
8
+ """
9
+
10
+ from .lever_runner import Report, Run, Score, print_table, run_levers, save
11
+ from .pipeline import RunResult, Step, StepLog, run_pipeline
12
+ from .scout_rescue import Check, Model, ModelResult, Outcome, handoff_prompt, scout_and_rescue
13
+
14
+ __version__ = "0.1.0"
15
+
16
+ __all__ = [
17
+ "Check", "Model", "ModelResult", "Outcome", "handoff_prompt", "scout_and_rescue",
18
+ "RunResult", "Step", "StepLog", "run_pipeline",
19
+ "Report", "Run", "Score", "print_table", "run_levers", "save",
20
+ ]
@@ -0,0 +1,69 @@
1
+ """Claude adapter: turns a Claude model into a `Model` function for
2
+ scout_rescue and pipeline. Other providers need only a function with the
3
+ same shape (prompt in, ModelResult out).
4
+
5
+ Requires: pip install "ai-mixed-model-cost-optimization[claude]" (or anthropic), and credentials (ANTHROPIC_API_KEY or `ant auth login`).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .scout_rescue import Model, ModelResult
11
+
12
+ # USD per million tokens: (input, output). Prices change - check the current
13
+ # price list before you trust any cost number. Haiku 5.5 price is for prompts
14
+ # up to 100K tokens. Cache discounts are ignored here for simplicity.
15
+ PRICES = {
16
+ "claude-haiku-5-5": (0.10, 0.50),
17
+ "claude-sonnet-5-5": (2.00, 10.00),
18
+ "claude-opus-5-5": (4.00, 20.00),
19
+ }
20
+
21
+ # These models support server-side refusal fallbacks; we turn them on so a
22
+ # rare policy decline is retried on a suitable model instead of returning nothing.
23
+ _FALLBACK_MODELS = {"claude-opus-5-5", "claude-sonnet-5-5"}
24
+
25
+ _client = None
26
+
27
+
28
+ def _get_client():
29
+ global _client
30
+ if _client is None:
31
+ import anthropic
32
+
33
+ _client = anthropic.Anthropic()
34
+ return _client
35
+
36
+
37
+ def claude(model: str, effort: str = "low", system: str | None = None, max_tokens: int = 16000) -> Model:
38
+ """Return a Model function for one Claude model at one effort level."""
39
+ price_in, price_out = PRICES[model]
40
+
41
+ def call(prompt: str) -> ModelResult:
42
+ kwargs = dict(
43
+ model=model,
44
+ max_tokens=max_tokens,
45
+ output_config={"effort": effort},
46
+ messages=[{"role": "user", "content": prompt}],
47
+ )
48
+ if system:
49
+ kwargs["system"] = system
50
+
51
+ client = _get_client()
52
+ if model in _FALLBACK_MODELS:
53
+ response = client.beta.messages.create(
54
+ betas=["server-side-fallback-2026-07-01"], fallbacks="default", **kwargs
55
+ )
56
+ else:
57
+ response = client.messages.create(**kwargs)
58
+
59
+ # A refusal returns no usable text; the check will treat "" as a failure.
60
+ if response.stop_reason == "refusal":
61
+ text = ""
62
+ else:
63
+ text = "".join(block.text for block in response.content if block.type == "text")
64
+
65
+ usage = response.usage
66
+ cost = (usage.input_tokens * price_in + usage.output_tokens * price_out) / 1_000_000
67
+ return ModelResult(text=text, cost_usd=cost, model=model)
68
+
69
+ return call
@@ -0,0 +1,74 @@
1
+ """The `mmco` command.
2
+
3
+ mmco compare my_test.py # run every setup on every case, print the table
4
+ mmco compare my_test.py --live # your file decides what "live" means (real API calls)
5
+ mmco compare my_test.py --out dir # where results and the blind review sheet go
6
+
7
+ Your test file is plain Python and defines one function:
8
+
9
+ def build(live: bool, args: list[str]) -> dict:
10
+ return {
11
+ "cases": [...], # your test requests
12
+ "setups": {"baseline": run, ...}, # name -> run(case) -> Run; first is the baseline
13
+ "judge": judge, # optional: judge(case, text) -> Score
14
+ "describe": lambda case: str(case), # optional: how a case shows on the review sheet
15
+ }
16
+
17
+ Checks stay in code, inside your setups - that is what makes them reliable.
18
+ Any extra arguments after the file are passed to build() as `args`.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import importlib.util
25
+ import sys
26
+ from datetime import datetime
27
+ from pathlib import Path
28
+
29
+ from . import __version__
30
+ from .lever_runner import print_table, run_levers, save
31
+
32
+
33
+ def _load(path: Path):
34
+ sys.path.insert(0, str(path.parent)) # let the test file import its neighbours
35
+ spec = importlib.util.spec_from_file_location(path.stem, path)
36
+ if spec is None or spec.loader is None:
37
+ raise SystemExit(f"Cannot load {path}")
38
+ module = importlib.util.module_from_spec(spec)
39
+ sys.modules[spec.name] = module # dataclasses in the test file need this
40
+ spec.loader.exec_module(module)
41
+ if not hasattr(module, "build"):
42
+ raise SystemExit(f"{path} must define build(live, args) -> dict. See: mmco compare --help")
43
+ return module
44
+
45
+
46
+ def compare(file: str, live: bool = False, out: str | None = None, extra: list[str] | None = None) -> None:
47
+ path = Path(file).resolve()
48
+ spec = _load(path).build(live, extra or [])
49
+ cases, setups = spec["cases"], spec["setups"]
50
+ print(f"{'LIVE' if live else 'OFFLINE'}: {len(cases)} cases x {len(setups)} setups")
51
+ report = run_levers(cases, setups, judge=spec.get("judge"))
52
+ print()
53
+ print_table(report, list(setups))
54
+ out_dir = Path(out) if out else path.parent / "results" / datetime.now().strftime("%Y%m%d-%H%M%S")
55
+ save(report, cases, out_dir, describe=spec.get("describe", str))
56
+ print(f"\nSaved to {out_dir}")
57
+
58
+
59
+ def main(argv: list[str] | None = None) -> None:
60
+ parser = argparse.ArgumentParser(prog="mmco", description="Test cheaper AI setups against your current one.")
61
+ parser.add_argument("--version", action="version", version=f"mmco {__version__}")
62
+ sub = parser.add_subparsers(dest="command", required=True)
63
+ cmp_ = sub.add_parser("compare", help="run setups side by side and print a keep-or-drop table",
64
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
65
+ cmp_.add_argument("file", help="your test file, defining build(live, args)")
66
+ cmp_.add_argument("--live", action="store_true", help="tell build() to use real models")
67
+ cmp_.add_argument("--out", help="folder for results (default: results/<time> next to the file)")
68
+ args, extra = parser.parse_known_args(argv)
69
+ if args.command == "compare":
70
+ compare(args.file, args.live, args.out, extra)
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()
@@ -0,0 +1,128 @@
1
+ """Lever runner: test one change (a "lever") against your current setup on the
2
+ same requests, at the same time, and print a keep-or-drop table.
3
+
4
+ You give it:
5
+ cases - a list of test requests (any objects)
6
+ setups - {name: run(case) -> Run}; the first one is the baseline
7
+ judge - optional: judge(case, text) -> Score, for a blind quality review
8
+
9
+ Every case runs through every setup before the next case starts (in a shuffled
10
+ order), so all setups see the same moment - same web, same API load.
11
+ The judge sees one reply at a time and never the setup's name.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import csv
17
+ import json
18
+ import random
19
+ import statistics
20
+ from dataclasses import asdict, dataclass, field
21
+ from pathlib import Path
22
+ from typing import Any, Callable, Optional
23
+
24
+
25
+ @dataclass
26
+ class Run:
27
+ text: str
28
+ cost_usd: float
29
+ seconds: float
30
+ path: str = "single" # "scout", "rescue" or "single"
31
+ final_check: Optional[str] = None # None if the final text passes your check
32
+
33
+
34
+ @dataclass
35
+ class Score:
36
+ points: int # on your fixed rubric
37
+ max_points: int
38
+ hard_failure: bool = False # wrong policy, invented promise, no answer ...
39
+ note: str = ""
40
+
41
+
42
+ @dataclass
43
+ class Row:
44
+ case: int
45
+ setup: str
46
+ run: Run
47
+ score: Optional[Score] = None
48
+
49
+
50
+ @dataclass
51
+ class Report:
52
+ rows: list[Row] = field(default_factory=list)
53
+
54
+ def for_setup(self, name: str) -> list[Row]:
55
+ return [r for r in self.rows if r.setup == name]
56
+
57
+
58
+ def run_levers(
59
+ cases: list[Any],
60
+ setups: dict[str, Callable[[Any], Run]],
61
+ judge: Optional[Callable[[Any, str], Score]] = None,
62
+ seed: int = 1,
63
+ ) -> Report:
64
+ rng = random.Random(seed)
65
+ report = Report()
66
+ for i, case in enumerate(cases):
67
+ names = list(setups)
68
+ rng.shuffle(names) # no setup always goes first
69
+ for name in names:
70
+ report.rows.append(Row(i, name, setups[name](case)))
71
+ print(f" case {i + 1}/{len(cases)} done", flush=True)
72
+
73
+ if judge:
74
+ # Score each distinct reply once, in random order, without the setup name.
75
+ unique = {(r.case, r.run.text) for r in report.rows}
76
+ order = sorted(unique)
77
+ rng.shuffle(order)
78
+ scores = {}
79
+ for n, (i, text) in enumerate(order, 1):
80
+ scores[(i, text)] = judge(cases[i], text)
81
+ print(f" reviewed {n}/{len(order)}", flush=True)
82
+ for r in report.rows:
83
+ r.score = scores[(r.case, r.run.text)]
84
+ return report
85
+
86
+
87
+ def print_table(report: Report, setups: list[str]) -> None:
88
+ base = setups[0]
89
+ base_cost = statistics.mean(r.run.cost_usd for r in report.for_setup(base))
90
+ head = f"{'setup':<28}{'avg cost':>10}{'median':>9}{'vs base':>9}{'rescued':>9}{'avg s':>7}{'check fail':>11}"
91
+ has_scores = any(r.score for r in report.rows)
92
+ if has_scores:
93
+ head += f"{'quality':>12}{'hard fail':>10}"
94
+ print(head)
95
+ for name in setups:
96
+ rows = report.for_setup(name)
97
+ costs = [r.run.cost_usd for r in rows]
98
+ avg = statistics.mean(costs)
99
+ rescued = sum(r.run.path == "rescue" for r in rows)
100
+ line = (
101
+ f"{name:<28}{avg * 100:>8.3f}c{statistics.median(costs) * 100:>8.3f}c"
102
+ f"{(avg / base_cost - 1) * 100:>+8.0f}%{rescued:>5}/{len(rows):<3}"
103
+ f"{statistics.mean(r.run.seconds for r in rows):>7.1f}"
104
+ f"{sum(r.run.final_check is not None for r in rows):>11}"
105
+ )
106
+ if has_scores:
107
+ pts = sum(r.score.points for r in rows)
108
+ mx = sum(r.score.max_points for r in rows)
109
+ line += f"{pts:>7}/{mx:<4}{sum(r.score.hard_failure for r in rows):>10}"
110
+ print(line)
111
+
112
+
113
+ def save(report: Report, cases: list[Any], out_dir: Path, describe: Callable[[Any], str]) -> None:
114
+ """Write all results, plus a blind review sheet a person can score by hand."""
115
+ out_dir.mkdir(parents=True, exist_ok=True)
116
+ (out_dir / "results.json").write_text(
117
+ json.dumps([asdict(r) for r in report.rows], indent=2, ensure_ascii=False)
118
+ )
119
+ rng = random.Random(7)
120
+ rows = report.rows[:]
121
+ rng.shuffle(rows)
122
+ with open(out_dir / "blind_review.csv", "w", newline="") as f, open(out_dir / "blind_key.csv", "w", newline="") as k:
123
+ sheet, key = csv.writer(f), csv.writer(k)
124
+ sheet.writerow(["id", "request", "reply", "your score", "hard failure?"])
125
+ key.writerow(["id", "case", "setup"])
126
+ for n, r in enumerate(rows, 1):
127
+ sheet.writerow([n, describe(cases[r.case]), r.run.text, "", ""])
128
+ key.writerow([n, r.case, r.setup])
@@ -0,0 +1,70 @@
1
+ """Split one AI job into steps and give each step the cheapest model that
2
+ does it well. A step either uses one model, or Scout & Rescue.
3
+
4
+ Typical split:
5
+ read / extract -> small, cheap model
6
+ analyze / draft -> Scout & Rescue (cheap first, strong only when needed)
7
+ review -> code checks where possible, a model only where needed
8
+ aggregate -> mid-size model, once per batch instead of once per item
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass, field
14
+ from typing import Callable, Optional
15
+
16
+ from .scout_rescue import Model, Outcome, scout_and_rescue
17
+
18
+
19
+ @dataclass
20
+ class Step:
21
+ name: str
22
+ build_prompt: Callable[[dict], str] # turns the data so far into a prompt
23
+ model: Optional[Model] = None # single model, or ...
24
+ scout: Optional[Model] = None # ... Scout & Rescue
25
+ rescue: Optional[Model] = None
26
+ # check(text, data) -> None if usable, else a reason. Gets the data so far,
27
+ # so it can compare against earlier steps (e.g. "mentions the order id?").
28
+ check: Optional[Callable[[str, dict], Optional[str]]] = None
29
+
30
+
31
+ @dataclass
32
+ class StepLog:
33
+ step: str
34
+ path: str
35
+ model: str
36
+ cost_usd: float
37
+ note: str = ""
38
+
39
+
40
+ @dataclass
41
+ class RunResult:
42
+ data: dict
43
+ log: list[StepLog] = field(default_factory=list)
44
+
45
+ @property
46
+ def cost_usd(self) -> float:
47
+ return sum(entry.cost_usd for entry in self.log)
48
+
49
+
50
+ def run_step(step: Step, data: dict) -> Outcome:
51
+ prompt = step.build_prompt(data)
52
+ if step.model is not None:
53
+ result = step.model(prompt)
54
+ return Outcome(result.text, "single", result.cost_usd, result.model)
55
+ if step.scout and step.rescue and step.check:
56
+ return scout_and_rescue(prompt, step.scout, step.rescue, lambda text: step.check(text, data))
57
+ raise ValueError(f"Step {step.name!r} needs either `model` or `scout` + `rescue` + `check`.")
58
+
59
+
60
+ def run_pipeline(steps: list[Step], data: dict) -> RunResult:
61
+ """Run the steps in order. Each step's output is stored under its name."""
62
+ run = RunResult(data=dict(data))
63
+ for step in steps:
64
+ outcome = run_step(step, run.data)
65
+ run.data[step.name] = outcome.text
66
+ run.log.append(
67
+ StepLog(step.name, outcome.path, outcome.model, outcome.cost_usd,
68
+ f"scout rejected: {outcome.rejected_because}" if outcome.rejected_because else "")
69
+ )
70
+ return run
@@ -0,0 +1,69 @@
1
+ """Scout & Rescue: a cheap model tries first; a strong model runs only when
2
+ a check in code says the cheap result is not usable.
3
+
4
+ This file has no provider code. A "model" is any function that takes a prompt
5
+ and returns a ModelResult, so you can plug in Claude, OpenAI, Gemini, a local
6
+ model, or a stub for tests.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from typing import Callable, Optional
13
+
14
+
15
+ @dataclass
16
+ class ModelResult:
17
+ text: str
18
+ cost_usd: float
19
+ model: str
20
+
21
+
22
+ # A model: prompt in, result out.
23
+ Model = Callable[[str], ModelResult]
24
+
25
+ # A check: returns None if the text is usable, or a short reason why it is not.
26
+ # Keep checks in plain code - free, instant, and predictable.
27
+ Check = Callable[[str], Optional[str]]
28
+
29
+
30
+ @dataclass
31
+ class Outcome:
32
+ text: str
33
+ path: str # "scout" or "rescue"
34
+ cost_usd: float
35
+ model: str
36
+ rejected_because: Optional[str] = None # why the scout's result failed the check
37
+
38
+
39
+ def handoff_prompt(prompt: str, draft: str, problem: str) -> str:
40
+ """The rescuer's prompt when it is told what the scout tried and why it failed."""
41
+ return (
42
+ f"{prompt}\n\n---\nA first draft of this answer was rejected by an automatic check.\n"
43
+ f"Reason: {problem}\nRejected draft:\n{draft}\n---\n"
44
+ "Write the answer again, fixing that problem. Do not copy mistakes from the draft."
45
+ )
46
+
47
+
48
+ def scout_and_rescue(
49
+ prompt: str, scout: Model, rescue: Model, check: Check, handoff: bool = False
50
+ ) -> Outcome:
51
+ """Run the cheap scout first; call the strong rescuer only if the check fails.
52
+
53
+ handoff=True also gives the rescuer the scout's draft and the reason it was
54
+ rejected. It may help the rescuer, or make it copy the scout's mistakes and
55
+ read more tokens - treat it as a lever and test it before you turn it on.
56
+ """
57
+ first = scout(prompt)
58
+ problem = check(first.text)
59
+ if problem is None:
60
+ return Outcome(first.text, "scout", first.cost_usd, first.model)
61
+
62
+ second = rescue(handoff_prompt(prompt, first.text, problem) if handoff else prompt)
63
+ return Outcome(
64
+ text=second.text,
65
+ path="rescue",
66
+ cost_usd=first.cost_usd + second.cost_usd, # you pay for both attempts
67
+ model=second.model,
68
+ rejected_because=problem,
69
+ )