budgetrouter 0.2.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 (32) hide show
  1. budgetrouter-0.2.0/LICENSE +21 -0
  2. budgetrouter-0.2.0/MANIFEST.in +3 -0
  3. budgetrouter-0.2.0/PKG-INFO +375 -0
  4. budgetrouter-0.2.0/README.md +349 -0
  5. budgetrouter-0.2.0/examples/agent_workload_demo.py +171 -0
  6. budgetrouter-0.2.0/examples/full_workflow_demo.py +167 -0
  7. budgetrouter-0.2.0/examples/langgraph_example.py +84 -0
  8. budgetrouter-0.2.0/examples/langgraph_integration.py +140 -0
  9. budgetrouter-0.2.0/examples/live_smoke_test.py +73 -0
  10. budgetrouter-0.2.0/examples/quickstart.py +32 -0
  11. budgetrouter-0.2.0/pyproject.toml +50 -0
  12. budgetrouter-0.2.0/setup.cfg +4 -0
  13. budgetrouter-0.2.0/src/budgetrouter/__init__.py +80 -0
  14. budgetrouter-0.2.0/src/budgetrouter/adapters.py +414 -0
  15. budgetrouter-0.2.0/src/budgetrouter/budget.py +332 -0
  16. budgetrouter-0.2.0/src/budgetrouter/eval.py +420 -0
  17. budgetrouter-0.2.0/src/budgetrouter/policy.py +71 -0
  18. budgetrouter-0.2.0/src/budgetrouter/provider.py +256 -0
  19. budgetrouter-0.2.0/src/budgetrouter/router.py +499 -0
  20. budgetrouter-0.2.0/src/budgetrouter/usage.py +256 -0
  21. budgetrouter-0.2.0/src/budgetrouter.egg-info/PKG-INFO +375 -0
  22. budgetrouter-0.2.0/src/budgetrouter.egg-info/SOURCES.txt +30 -0
  23. budgetrouter-0.2.0/src/budgetrouter.egg-info/dependency_links.txt +1 -0
  24. budgetrouter-0.2.0/src/budgetrouter.egg-info/requires.txt +3 -0
  25. budgetrouter-0.2.0/src/budgetrouter.egg-info/top_level.txt +1 -0
  26. budgetrouter-0.2.0/tests/test_adapters.py +396 -0
  27. budgetrouter-0.2.0/tests/test_async.py +215 -0
  28. budgetrouter-0.2.0/tests/test_async_router.py +458 -0
  29. budgetrouter-0.2.0/tests/test_budget.py +281 -0
  30. budgetrouter-0.2.0/tests/test_eval.py +203 -0
  31. budgetrouter-0.2.0/tests/test_router.py +261 -0
  32. budgetrouter-0.2.0/tests/test_usage.py +162 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sen Yang
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,3 @@
1
+ include LICENSE README.md
2
+ recursive-include examples *.py
3
+ recursive-include tests *.py
@@ -0,0 +1,375 @@
1
+ Metadata-Version: 2.4
2
+ Name: budgetrouter
3
+ Version: 0.2.0
4
+ Summary: Lightweight multi-model routing for LLM and agent applications: pick the right model for each request, fall back when a provider fails, and stop the run when the budget runs out.
5
+ Author: Sen Yang
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/samyang777/budgetrouter
8
+ Project-URL: Repository, https://github.com/samyang777/budgetrouter
9
+ Project-URL: Issues, https://github.com/samyang777/budgetrouter/issues
10
+ Keywords: llm,agents,routing,cost,budget,openai,anthropic,ai-agents,langgraph
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # budgetrouter
28
+
29
+ Lightweight multi-model routing for LLM and agent applications: pick the
30
+ right model for each request, fall back when a provider fails, and stop the
31
+ run when the budget runs out — in a few hundred lines, with no dependencies.
32
+
33
+ ## Why
34
+
35
+ Agent workloads make a lot of model calls, and two failure modes dominate:
36
+
37
+ - **Cost surprises.** A looping or retrying agent can burn through an
38
+ expensive frontier model on work a small model would have done fine.
39
+ - **Brittle calls.** A single provider error kills the whole run.
40
+
41
+ budgetrouter addresses both with three small composable pieces: routing
42
+ rules that send each request to a suitable model, a fallback chain for when
43
+ a provider errors, and a budget gate that tracks cumulative estimated cost
44
+ and refuses calls past a cap. It drops into an existing app (LangGraph or
45
+ otherwise) as a library — it is not a framework and does not run your agent.
46
+
47
+ ## Quickstart
48
+
49
+ No API keys needed: the quickstart runs against a built-in `FakeProvider`.
50
+
51
+ ```python
52
+ from budgetrouter import BudgetGate, FakeProvider, Route, RouteRule, Router
53
+
54
+ providers = {
55
+ "fake": FakeProvider(
56
+ {"fake-small": "4", "fake-large": "4 (with a full proof sketch)"},
57
+ ),
58
+ }
59
+ router = Router(
60
+ providers=providers,
61
+ rules=[RouteRule(provider="fake", model="fake-large", tag="hard")],
62
+ default=Route(provider="fake", model="fake-small"),
63
+ fallbacks=[Route(provider="fake", model="fake-small")],
64
+ budget=BudgetGate(budget_usd=1.00, per_request_cap_usd=0.05),
65
+ )
66
+
67
+ easy = router.complete([{"role": "user", "content": "What is 2 + 2?"}])
68
+ print(easy.text) # -> "4", served by fake/fake-small
69
+
70
+ hard = router.complete(
71
+ [{"role": "user", "content": "What is 2 + 2? Show your work."}], tag="hard"
72
+ )
73
+ print(hard.text) # -> routed to fake-large by the "hard" tag rule
74
+ ```
75
+
76
+ The same example lives in [`examples/quickstart.py`](examples/quickstart.py)
77
+ and runs as-is after `pip install -e .`.
78
+
79
+ ## Concepts
80
+
81
+ - **Provider** — anything with a `name` and a
82
+ `complete(messages, model) -> Completion` method (a `typing.Protocol`).
83
+ `Completion` carries the text plus input/output token usage. Bundled
84
+ adapters cover the OpenAI and Anthropic API shapes (see below);
85
+ `FakeProvider` is the in-memory implementation for tests and demos, with
86
+ canned responses, fixed token counts, and simulated failures.
87
+ - **Router & FallbackPolicy** — holds providers, an ordered list of
88
+ `RouteRule`s, a default route, a fallback chain, and a configurable
89
+ `FallbackPolicy`. Rules match on a caller-supplied tag (e.g. `"hard"`,
90
+ `"summarize"`) and/or estimated input size. Provider failures are
91
+ classified on `ProviderError.kind` (`timeout`, `rate_limit`, `server_error`,
92
+ `auth`, `invalid_request`, `transport`, `bad_response`, `unknown`) with
93
+ optional `status_code`. By default, `auth` failures abort immediately
94
+ (no pointless fallback on a bad key) while other failures move down the
95
+ fallback chain; retries (`retry_then_fallback`) and cross-provider auth
96
+ failover are opt-in policy settings. Every attempt is recorded as an
97
+ `AttemptRecord` on `Completion.attempts` (or `ProviderError.attempts` /
98
+ `BudgetExceeded.attempts` on failure) — concurrency-safe and visible,
99
+ never silent.
100
+ - **BudgetGate & BudgetManager** — `BudgetGate` tracks cumulative spend for
101
+ one run using an editable per-model price table (USD per 1K tokens), with
102
+ optional per-request caps and a one-shot warning threshold (default `0.8`,
103
+ via `on_warning(bucket, spent, budget)` + `gate.warned`). `BudgetManager`
104
+ adds independent per-bucket caps (keyed by an explicit `bucket="..."`
105
+ argument on `complete()` / `acomplete()`, separate from `tag`), so
106
+ exhausting one tenant or task never blocks another. Exceeding any cap
107
+ raises `BudgetExceeded`, which the router deliberately does *not* treat as
108
+ a provider failure: being out of budget is terminal, not a reason to spend
109
+ elsewhere.
110
+ - **UsageLedger** — every router owns (or accepts) an in-memory `UsageLedger`
111
+ that records all attempts (successes, provider errors, budget rejections,
112
+ and downgrades). Call `router.usage_summary()` (default grouped by
113
+ `("bucket", "model")`, or `"model"` / `"bucket"`) for structured metrics
114
+ or `.format_table()` for a one-screen summary table.
115
+ - **Eval runner & regression gate** — a JSONL harness (`{"input", "target"}`
116
+ per line) with `exact` / `includes` scoring, error-rate tracking,
117
+ `run_router_eval()` (putting quality, route, cost, and downgrade status on
118
+ the same `CaseResult` record), and `check_gate(report, min_pass_rate=0.90,
119
+ max_error_rate=0.05)`:
120
+
121
+ ```console
122
+ $ python -m budgetrouter.eval --demo --gate
123
+ [PASS] input='What is the capital of France?' target='Paris' output='Paris'
124
+ [PASS] input='What is 2 + 2?' target='4' output='4'
125
+ [PASS] input='What color is the sky on a clear day?' target='blue' output='The sky is blue.'
126
+ 3/3 passed (100%)
127
+ [GATE PASS] pass_rate=100% (min 90%), error_rate=0% (max 5%)
128
+ ```
129
+
130
+ To gate against your own router or callable with a real dataset, pass
131
+ `--data <path.jsonl> --target my_module:answer_fn --gate`. A clearly
132
+ labelled placeholder dataset lives at
133
+ [`eval/placeholder_golden.jsonl`](eval/placeholder_golden.jsonl).
134
+
135
+ ## Real providers
136
+
137
+ Two adapters are bundled. Both are implemented with the standard library
138
+ only (`urllib.request`) — no vendor SDKs — and both raise `ProviderError`
139
+ on HTTP errors or network failures, so the fallback chain works with real
140
+ providers exactly as it does with `FakeProvider`.
141
+
142
+ ### OpenAI-compatible
143
+
144
+ `OpenAICompatibleProvider` talks to `POST {base_url}/chat/completions`, so
145
+ it works with OpenAI and with any compatible server (gateways, local model
146
+ servers). Keys come from the environment unless passed explicitly:
147
+
148
+ ```console
149
+ $ export OPENAI_API_KEY=sk-...
150
+ ```
151
+
152
+ ```python
153
+ from budgetrouter import OpenAICompatibleProvider, Route, Router
154
+
155
+ providers = {
156
+ "openai": OpenAICompatibleProvider(
157
+ "https://api.openai.com/v1", model="gpt-4o-mini"
158
+ ),
159
+ }
160
+ router = Router(providers=providers, default=Route("openai", "gpt-4o-mini"))
161
+ ```
162
+
163
+ To read the key from a differently named variable, pass
164
+ `api_key_env="MY_KEY_VAR"`; to point at a compatible server, change
165
+ `base_url`. A `timeout` (seconds) can be set per provider.
166
+
167
+ ### Anthropic
168
+
169
+ `AnthropicProvider` talks to `POST /v1/messages` (base URL defaults to
170
+ `https://api.anthropic.com`). System messages are split out of the message
171
+ list into Anthropic's top-level `system` field automatically, and text
172
+ content blocks plus `usage.input_tokens` / `usage.output_tokens` are parsed
173
+ into the usual `Completion`.
174
+
175
+ ```console
176
+ $ export ANTHROPIC_API_KEY=sk-ant-...
177
+ ```
178
+
179
+ ```python
180
+ from budgetrouter import AnthropicProvider, Route, Router
181
+
182
+ providers = {
183
+ "anthropic": AnthropicProvider(model="claude-sonnet-4-5"),
184
+ }
185
+ router = Router(
186
+ providers=providers, default=Route("anthropic", "claude-sonnet-4-5")
187
+ )
188
+ ```
189
+
190
+ Mixing providers in one router — e.g. OpenAI as the default route and
191
+ Anthropic as the fallback — is the normal case; the router and budget gate
192
+ do not care which API shape served a call. Before relying on the budget
193
+ gate with real models, check the price table in
194
+ `budgetrouter.DEFAULT_PRICES`: the shipped vendor entries are illustrative
195
+ defaults, so verify them against the vendor's current pricing page.
196
+
197
+ ### Verifying against a real API
198
+
199
+ Both adapters are covered by integration tests against a local stub
200
+ server that speaks the real API shapes (see `tests/test_adapters.py`).
201
+ To verify against a real endpoint, use
202
+ [`examples/live_smoke_test.py`](examples/live_smoke_test.py): point it
203
+ at any OpenAI-compatible endpoint with a real key (it defaults to
204
+ GitHub Models' free tier) and it exercises the adapter plus a
205
+ router + budget round-trip. The Anthropic adapter has *not* yet been
206
+ verified against Anthropic's live API (there is no free tier for the
207
+ native API); it follows the documented request/response format and the
208
+ stub tests.
209
+
210
+ ## Async
211
+
212
+ Agent code is async by default, so budgetrouter ships a full async API:
213
+ `AsyncRouter`, `AsyncFakeProvider`, and async twins of both real
214
+ adapters (`AsyncOpenAICompatibleProvider`, `AsyncAnthropicProvider`).
215
+ `AsyncRouter.complete` mirrors the sync router's semantics exactly —
216
+ same routing rules, same fallback chain, same budget behavior
217
+ (`BudgetExceeded` still propagates immediately and is never treated as
218
+ a provider failure). One deliberate addition: when a budget gate is
219
+ attached, each attempt's check → call → record cycle runs under a lock,
220
+ so concurrent calls can never race past the cap and recorded spend is a
221
+ hard ceiling. Without a budget, calls run fully concurrently.
222
+
223
+ ```python
224
+ import asyncio
225
+
226
+ from budgetrouter import (
227
+ AsyncFakeProvider,
228
+ AsyncRouter,
229
+ BudgetGate,
230
+ Route,
231
+ RouteRule,
232
+ )
233
+
234
+ async def main() -> None:
235
+ providers = {
236
+ "fake": AsyncFakeProvider(
237
+ {"fake-small": "4", "fake-large": "4 (with a full proof sketch)"},
238
+ ),
239
+ }
240
+ router = AsyncRouter(
241
+ providers=providers,
242
+ rules=[RouteRule(provider="fake", model="fake-large", tag="hard")],
243
+ default=Route(provider="fake", model="fake-small"),
244
+ fallbacks=[Route(provider="fake", model="fake-small")],
245
+ budget=BudgetGate(budget_usd=1.00, per_request_cap_usd=0.05),
246
+ )
247
+ easy = await router.complete([{"role": "user", "content": "What is 2 + 2?"}])
248
+ hard = await router.complete(
249
+ [{"role": "user", "content": "What is 2 + 2? Show your work."}],
250
+ tag="hard",
251
+ )
252
+ print(easy.text, "|", hard.text)
253
+
254
+ asyncio.run(main())
255
+ ```
256
+
257
+ Two honesty notes. First, the async adapters are async at the event-loop
258
+ level, not at the socket level: the package has zero dependencies, so
259
+ there is no async HTTP client — the blocking `urllib` call runs via
260
+ `asyncio.to_thread`. Concurrent calls genuinely overlap and the loop
261
+ never blocks, at the cost of one worker thread per in-flight request.
262
+ Second, the sync `Router` also has an `acomplete` method with the same
263
+ semantics, which runs a provider's native `acomplete` when it defines
264
+ one and bridges a sync-only provider through a worker thread — existing
265
+ providers keep working in async apps unchanged.
266
+
267
+ [`examples/langgraph_integration.py`](examples/langgraph_integration.py)
268
+ puts `AsyncRouter` inside a LangGraph `StateGraph` — a classify node on
269
+ the cheap model, an answer node on the strong one, one budget gate per
270
+ run — and runs key-free against `AsyncFakeProvider` (langgraph itself is
271
+ an example-only dependency; budgetrouter does not depend on it).
272
+ [`examples/langgraph_example.py`](examples/langgraph_example.py) shows
273
+ the same idea using `Router.acomplete` in a single node.
274
+
275
+ ## Demo: an agent workload
276
+
277
+ [`examples/agent_workload_demo.py`](examples/agent_workload_demo.py) runs
278
+ the full stack — real adapters, routing, fallback, budget gate — against
279
+ local stub servers, so it works offline with no API keys. It simulates ten
280
+ mixed tasks tagged `cheap`/`strong`; partway through, the strong provider
281
+ starts returning HTTP 500 and the fallback visibly takes over, while spend
282
+ climbs toward the budget cap:
283
+
284
+ ```console
285
+ $ python examples/agent_workload_demo.py
286
+ ...
287
+ --- summary ---
288
+ tasks completed : 10 (2 served by fallback)
289
+ total spend : $0.015234 of $0.017 cap (90% used, $0.001766 left)
290
+ per-model breakdown:
291
+ gpt-4o 4 calls, 3000 tokens, $0.015000
292
+ gpt-4o-mini 6 calls, 840 tokens, $0.000234
293
+ ```
294
+
295
+ [`examples/full_workflow_demo.py`](examples/full_workflow_demo.py) exercises
296
+ failure-aware fallback (`FallbackPolicy`), bucketed budgets (`BudgetManager`
297
+ with warning callbacks), usage attribution (`router.usage_summary().format_table()`),
298
+ and the eval regression gate (`run_router_eval` + `check_gate`) end to end
299
+ with `FakeProvider` — no API keys or network required.
300
+
301
+ ## How this differs from LiteLLM / hosted gateways
302
+
303
+ - **In-process library, not a proxy or a mega-SDK.** Hosted gateways
304
+ (Portkey, LiteLLM Proxy, OpenRouter-style services) put a network hop
305
+ and a running service between your code and the model. LiteLLM the SDK
306
+ is in-process, but its center of gravity is breadth: 100+ provider
307
+ adapters behind one interface. budgetrouter is a few hundred lines you
308
+ import; the routing, fallback, and budget logic runs in your process,
309
+ under your tests, with no extra service to deploy or keep up.
310
+ - **Budget enforcement is a first-class API, not a dashboard setting.**
311
+ The gate is consulted before every call and updated after it, in code:
312
+ per-run and per-request caps raise `BudgetExceeded` in the call path,
313
+ so an agent loop stops instead of overspending. In gateway products,
314
+ budgets typically live in admin configuration and alerting, outside
315
+ the program's control flow.
316
+ - **Two API shapes, deliberately.** The bundled adapters cover the
317
+ OpenAI chat-completions shape (which many providers and local servers
318
+ speak) and Anthropic's messages shape. Anything else can implement
319
+ the small `Provider` / `AsyncProvider` protocol directly — the router
320
+ does not care how a provider talks.
321
+ - **Zero dependencies.** Standard library only, including the async
322
+ adapters (see the Async section for exactly what that means).
323
+ - **What it does not do:** it is not an agent framework, not a hosted
324
+ control plane (no dashboards, key management, or observability
325
+ pipeline), and not a billing system. If you need those, use a gateway
326
+ product — possibly with budgetrouter inside the agent process as well.
327
+
328
+ ## Features
329
+
330
+ - Ordered routing rules by tag and estimated input size, with a default route
331
+ - Failure-classified fallback (`ProviderError.kind` + `FallbackPolicy`) and
332
+ per-attempt logs on `Completion.attempts` / raised exceptions
333
+ - Single-run (`BudgetGate`) and per-bucket (`BudgetManager`) spend caps with
334
+ per-request caps, one-shot warning hooks, and an editable price table
335
+ - In-memory usage attribution (`UsageLedger`) with grouped summaries and
336
+ ASCII table rendering
337
+ - Bundled OpenAI-compatible and Anthropic adapters (stdlib only, env-var keys)
338
+ - Full async API (`AsyncRouter`, `AsyncFakeProvider`, async adapters) with
339
+ lock-guarded budget gates per bucket
340
+ - Provider protocol + `FakeProvider` for tests, demos, and CI
341
+ - Eval runner & regression gate (`check_gate`, `run_router_eval`, CLI `--gate`
342
+ and `--target`) with cost and quality on the same record
343
+ - Zero runtime dependencies (standard library only), typed, Python ≥ 3.10
344
+
345
+ ## Non-goals
346
+
347
+ - **Not an agent framework.** No agents, tools, memory, planning, or
348
+ orchestration — budgetrouter only decides *which model serves a call* and
349
+ *whether the budget allows it*. Use it inside LangGraph, a hand-rolled
350
+ loop, or a plain script.
351
+ - No provider SDK dependencies. The bundled adapters speak plain HTTPS via
352
+ the standard library; provider-specific extras (streaming, tool use,
353
+ batch APIs) are out of scope, and anything unusual can still implement
354
+ the `Provider` protocol directly.
355
+ - No precise tokenization. Input size and pre-call costs are estimates
356
+ (chars / 4); accounting uses the provider's reported usage.
357
+ - Not a billing system. The budget gate is a safety stop, not invoicing.
358
+
359
+ ## Roadmap
360
+
361
+ - Streaming completions
362
+ - Precise tokenizers for pre-call estimates (per-provider, opt-in)
363
+ - Weighted and latency-aware routing strategies
364
+
365
+ ## Development
366
+
367
+ ```console
368
+ $ python -m venv .venv && source .venv/bin/activate
369
+ $ pip install -e ".[dev]"
370
+ $ pytest
371
+ ```
372
+
373
+ ## License
374
+
375
+ MIT — see [LICENSE](LICENSE).