budgetrouter 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,80 @@
1
+ """budgetrouter: multi-model routing with budget gates, fallback policies, and usage attribution."""
2
+
3
+ from .adapters import (
4
+ AnthropicProvider,
5
+ AsyncAnthropicProvider,
6
+ AsyncOpenAICompatibleProvider,
7
+ OpenAICompatibleProvider,
8
+ )
9
+ from .budget import (
10
+ DEFAULT_PRICES,
11
+ BudgetExceeded,
12
+ BudgetGate,
13
+ BudgetManager,
14
+ estimate_cost,
15
+ )
16
+ from .eval import (
17
+ CaseResult,
18
+ EvalReport,
19
+ GateResult,
20
+ check_gate,
21
+ load_cases,
22
+ run_eval,
23
+ run_router_eval,
24
+ )
25
+ from .policy import DEFAULT_FALLBACK_ACTIONS, FallbackPolicy
26
+ from .provider import (
27
+ AsyncFakeProvider,
28
+ AsyncProvider,
29
+ AttemptOutcome,
30
+ AttemptRecord,
31
+ Completion,
32
+ FailureKind,
33
+ FakeProvider,
34
+ Provider,
35
+ ProviderError,
36
+ Usage,
37
+ )
38
+ from .router import AsyncRouter, Route, RouteRule, Router, estimate_tokens
39
+ from .usage import GroupSummary, UsageLedger, UsageSummary
40
+
41
+ __version__ = "0.2.0"
42
+
43
+ __all__ = [
44
+ "AnthropicProvider",
45
+ "AsyncAnthropicProvider",
46
+ "AsyncFakeProvider",
47
+ "AsyncOpenAICompatibleProvider",
48
+ "AsyncProvider",
49
+ "AsyncRouter",
50
+ "AttemptOutcome",
51
+ "AttemptRecord",
52
+ "BudgetExceeded",
53
+ "BudgetGate",
54
+ "BudgetManager",
55
+ "CaseResult",
56
+ "Completion",
57
+ "DEFAULT_FALLBACK_ACTIONS",
58
+ "DEFAULT_PRICES",
59
+ "EvalReport",
60
+ "FailureKind",
61
+ "FakeProvider",
62
+ "FallbackPolicy",
63
+ "GateResult",
64
+ "GroupSummary",
65
+ "OpenAICompatibleProvider",
66
+ "Provider",
67
+ "ProviderError",
68
+ "Route",
69
+ "RouteRule",
70
+ "Router",
71
+ "Usage",
72
+ "UsageLedger",
73
+ "UsageSummary",
74
+ "check_gate",
75
+ "estimate_cost",
76
+ "estimate_tokens",
77
+ "load_cases",
78
+ "run_eval",
79
+ "run_router_eval",
80
+ ]
@@ -0,0 +1,414 @@
1
+ """Real provider adapters, built on the standard library only.
2
+
3
+ These adapters speak plain HTTPS via :mod:`urllib.request`, so the package
4
+ keeps its zero-runtime-dependency promise — no vendor SDKs are required.
5
+ Both implement the :class:`~budgetrouter.provider.Provider` protocol and can
6
+ be pointed at any base URL, which is also how the test-suite runs them
7
+ against a local stub server.
8
+
9
+ API keys are never hard-coded: pass ``api_key`` explicitly or name an
10
+ environment variable with ``api_key_env`` (defaults to the vendor's usual
11
+ variable) and the key is read from the environment at construction time.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import json
18
+ import math
19
+ import os
20
+ import urllib.error
21
+ import urllib.request
22
+
23
+ from .provider import Completion, FailureKind, Message, ProviderError, Usage
24
+
25
+ ANTHROPIC_VERSION = "2023-06-01"
26
+ """Value sent in the ``anthropic-version`` header."""
27
+
28
+ USER_AGENT = "budgetrouter/0.2.0"
29
+ """Value sent in the ``User-Agent`` header of every adapter request.
30
+
31
+ urllib's default ``Python-urllib/x.y`` agent is rejected outright by
32
+ some API gateways (Cloudflare-fronted endpoints answer HTTP 403, error
33
+ 1010), so the adapters identify themselves explicitly instead.
34
+ """
35
+
36
+
37
+ def _classify_http_status(status_code: int) -> FailureKind:
38
+ """Map an HTTP status code to a :class:`FailureKind`."""
39
+ if status_code == 429:
40
+ return "rate_limit"
41
+ if status_code in (401, 403):
42
+ return "auth"
43
+ if 500 <= status_code <= 599:
44
+ return "server_error"
45
+ if 400 <= status_code <= 499:
46
+ return "invalid_request"
47
+ return "unknown"
48
+
49
+
50
+ def _resolve_api_key(
51
+ api_key: str | None, api_key_env: str, provider_name: str
52
+ ) -> str:
53
+ if api_key:
54
+ return api_key
55
+ value = os.environ.get(api_key_env)
56
+ if not value:
57
+ raise ProviderError(
58
+ f"{provider_name}: no API key given and environment variable "
59
+ f"{api_key_env} is not set",
60
+ kind="auth",
61
+ )
62
+ return value
63
+
64
+
65
+ def _post_json(
66
+ url: str,
67
+ payload: dict,
68
+ headers: dict[str, str],
69
+ timeout: float,
70
+ provider_name: str,
71
+ ) -> dict:
72
+ """POST ``payload`` as JSON and return the decoded response body.
73
+
74
+ Any transport failure, non-2xx status, or undecodable body becomes a
75
+ classified :class:`ProviderError`, so the router's fallback policy can
76
+ react appropriately.
77
+ """
78
+ body = json.dumps(payload).encode("utf-8")
79
+ request = urllib.request.Request(
80
+ url,
81
+ data=body,
82
+ headers={
83
+ "Content-Type": "application/json",
84
+ "User-Agent": USER_AGENT,
85
+ **headers,
86
+ },
87
+ method="POST",
88
+ )
89
+ try:
90
+ with urllib.request.urlopen(request, timeout=timeout) as response:
91
+ raw_bytes = response.read()
92
+ except urllib.error.HTTPError as exc:
93
+ detail = exc.read().decode("utf-8", "replace")[:200]
94
+ raise ProviderError(
95
+ f"{provider_name}: HTTP {exc.code} from {url}: {detail}",
96
+ kind=_classify_http_status(exc.code),
97
+ status_code=exc.code,
98
+ ) from exc
99
+ except urllib.error.URLError as exc:
100
+ if isinstance(exc.reason, TimeoutError):
101
+ raise ProviderError(
102
+ f"{provider_name}: request to {url} timed out",
103
+ kind="timeout",
104
+ ) from exc
105
+ raise ProviderError(
106
+ f"{provider_name}: request to {url} failed: {exc.reason}",
107
+ kind="transport",
108
+ ) from exc
109
+ except TimeoutError as exc:
110
+ raise ProviderError(
111
+ f"{provider_name}: request to {url} timed out",
112
+ kind="timeout",
113
+ ) from exc
114
+ try:
115
+ raw = raw_bytes.decode("utf-8")
116
+ except UnicodeDecodeError as exc:
117
+ raise ProviderError(
118
+ f"{provider_name}: undecodable response from {url}: {exc}",
119
+ kind="bad_response",
120
+ ) from exc
121
+ try:
122
+ decoded = json.loads(raw)
123
+ except json.JSONDecodeError as exc:
124
+ raise ProviderError(
125
+ f"{provider_name}: undecodable response from {url}: {exc}",
126
+ kind="bad_response",
127
+ ) from exc
128
+ if not isinstance(decoded, dict):
129
+ raise ProviderError(
130
+ f"{provider_name}: unexpected response shape from {url}",
131
+ kind="bad_response",
132
+ )
133
+ return decoded
134
+
135
+
136
+ def _estimate_tokens(text: str) -> int:
137
+ """Rough token estimate for a text: ~4 characters per token."""
138
+ return math.ceil(len(text) / 4) if text else 0
139
+
140
+
141
+ def _parse_usage(
142
+ usage_data: object,
143
+ *,
144
+ input_key: str,
145
+ output_key: str,
146
+ input_fallback: int,
147
+ output_fallback: int,
148
+ provider_name: str,
149
+ ) -> Usage:
150
+ """Build a :class:`Usage` from a provider's usage block.
151
+
152
+ A provider that omits usage — or just one of its fields — must not
153
+ make the call free: the missing counts are estimated from the
154
+ request and response text (the ``input_fallback`` / ``output_fallback``
155
+ arguments), using the heuristic above. Values that are present but
156
+ negative or non-numeric are malformed and raise :class:`ProviderError`;
157
+ a negative count would otherwise *reduce* recorded spend in the
158
+ budget gate.
159
+ """
160
+ if usage_data is None:
161
+ return Usage(input_tokens=input_fallback, output_tokens=output_fallback)
162
+ if not isinstance(usage_data, dict):
163
+ raise ProviderError(
164
+ f"{provider_name}: malformed usage block: {usage_data!r}",
165
+ kind="bad_response",
166
+ )
167
+ parsed: dict[str, int] = {}
168
+ for key, fallback in (
169
+ (input_key, input_fallback),
170
+ (output_key, output_fallback),
171
+ ):
172
+ raw_value = usage_data.get(key)
173
+ if raw_value is None:
174
+ parsed[key] = fallback
175
+ continue
176
+ try:
177
+ value = int(raw_value)
178
+ except (TypeError, ValueError) as exc:
179
+ raise ProviderError(
180
+ f"{provider_name}: malformed usage value {key}={raw_value!r}",
181
+ kind="bad_response",
182
+ ) from exc
183
+ if value < 0:
184
+ raise ProviderError(
185
+ f"{provider_name}: negative usage value {key}={value}",
186
+ kind="bad_response",
187
+ )
188
+ parsed[key] = value
189
+ return Usage(
190
+ input_tokens=parsed[input_key], output_tokens=parsed[output_key]
191
+ )
192
+
193
+
194
+ class OpenAICompatibleProvider:
195
+ """Provider for OpenAI's chat-completions API and compatible servers.
196
+
197
+ Works with OpenAI itself and with any server exposing the same
198
+ ``POST {base_url}/chat/completions`` shape (many gateways and local
199
+ model servers do). ``model`` is the default model, used when a call
200
+ does not name one; the router passes the routed model on each call.
201
+ """
202
+
203
+ def __init__(
204
+ self,
205
+ base_url: str,
206
+ model: str,
207
+ *,
208
+ api_key: str | None = None,
209
+ api_key_env: str = "OPENAI_API_KEY",
210
+ timeout: float = 30.0,
211
+ name: str = "openai",
212
+ ) -> None:
213
+ self.name = name
214
+ self.base_url = base_url.rstrip("/")
215
+ self.model = model
216
+ self.timeout = timeout
217
+ self._api_key = _resolve_api_key(api_key, api_key_env, name)
218
+
219
+ def complete(self, messages: list[Message], model: str) -> Completion:
220
+ use_model = model or self.model
221
+ data = _post_json(
222
+ f"{self.base_url}/chat/completions",
223
+ {"model": use_model, "messages": messages},
224
+ {"Authorization": f"Bearer {self._api_key}"},
225
+ self.timeout,
226
+ self.name,
227
+ )
228
+ try:
229
+ text = data["choices"][0]["message"]["content"] or ""
230
+ except (KeyError, IndexError, TypeError) as exc:
231
+ raise ProviderError(
232
+ f"{self.name}: malformed chat-completions response: {exc}",
233
+ kind="bad_response",
234
+ ) from exc
235
+ usage = _parse_usage(
236
+ data.get("usage"),
237
+ input_key="prompt_tokens",
238
+ output_key="completion_tokens",
239
+ input_fallback=_estimate_tokens(
240
+ "".join(m.get("content", "") for m in messages)
241
+ ),
242
+ output_fallback=_estimate_tokens(text),
243
+ provider_name=self.name,
244
+ )
245
+ return Completion(
246
+ text=text, model=use_model, provider=self.name, usage=usage
247
+ )
248
+
249
+ async def acomplete(self, messages: list[Message], model: str) -> Completion:
250
+ """Async twin of :meth:`complete`.
251
+
252
+ The HTTP call itself is the blocking urllib request, run in a
253
+ worker thread so the event loop stays free; request/response
254
+ handling is shared with the sync path, byte for byte.
255
+ """
256
+ return await asyncio.to_thread(self.complete, messages, model)
257
+
258
+
259
+ class AnthropicProvider:
260
+ """Provider for Anthropic's messages API (``POST /v1/messages``).
261
+
262
+ Anthropic takes the system prompt outside the message list, so any
263
+ ``role == "system"`` messages are split out and sent as the top-level
264
+ ``system`` field. ``max_tokens`` is required by the API and defaults to
265
+ 1024.
266
+ """
267
+
268
+ def __init__(
269
+ self,
270
+ model: str,
271
+ *,
272
+ api_key: str | None = None,
273
+ api_key_env: str = "ANTHROPIC_API_KEY",
274
+ timeout: float = 30.0,
275
+ base_url: str = "https://api.anthropic.com",
276
+ max_tokens: int = 1024,
277
+ name: str = "anthropic",
278
+ ) -> None:
279
+ self.name = name
280
+ self.base_url = base_url.rstrip("/")
281
+ self.model = model
282
+ self.timeout = timeout
283
+ self.max_tokens = max_tokens
284
+ self._api_key = _resolve_api_key(api_key, api_key_env, name)
285
+
286
+ def complete(self, messages: list[Message], model: str) -> Completion:
287
+ use_model = model or self.model
288
+ system = "\n\n".join(
289
+ m.get("content", "") for m in messages if m.get("role") == "system"
290
+ )
291
+ conversation = [m for m in messages if m.get("role") != "system"]
292
+ payload: dict = {
293
+ "model": use_model,
294
+ "messages": conversation,
295
+ "max_tokens": self.max_tokens,
296
+ }
297
+ if system:
298
+ payload["system"] = system
299
+ data = _post_json(
300
+ f"{self.base_url}/v1/messages",
301
+ payload,
302
+ {
303
+ "x-api-key": self._api_key,
304
+ "anthropic-version": ANTHROPIC_VERSION,
305
+ },
306
+ self.timeout,
307
+ self.name,
308
+ )
309
+ try:
310
+ text = "".join(
311
+ block.get("text", "")
312
+ for block in data["content"]
313
+ if block.get("type") == "text"
314
+ )
315
+ except (KeyError, TypeError, AttributeError) as exc:
316
+ raise ProviderError(
317
+ f"{self.name}: malformed messages response: {exc}",
318
+ kind="bad_response",
319
+ ) from exc
320
+ usage = _parse_usage(
321
+ data.get("usage"),
322
+ input_key="input_tokens",
323
+ output_key="output_tokens",
324
+ input_fallback=_estimate_tokens(
325
+ "".join(m.get("content", "") for m in messages)
326
+ ),
327
+ output_fallback=_estimate_tokens(text),
328
+ provider_name=self.name,
329
+ )
330
+ return Completion(
331
+ text=text, model=use_model, provider=self.name, usage=usage
332
+ )
333
+
334
+ async def acomplete(self, messages: list[Message], model: str) -> Completion:
335
+ """Async twin of :meth:`complete`; see the OpenAI adapter's note."""
336
+ return await asyncio.to_thread(self.complete, messages, model)
337
+
338
+
339
+ class AsyncOpenAICompatibleProvider:
340
+ """Async counterpart of :class:`OpenAICompatibleProvider`.
341
+
342
+ Same constructor, same wire format, same parsing — the request is
343
+ built and answered by the sync implementation. Because the package
344
+ promises zero runtime dependencies, there is no async HTTP client
345
+ underneath: :mod:`urllib` is blocking, so the call runs via
346
+ :func:`asyncio.to_thread`. That is honestly scoped — the event loop
347
+ is never blocked and concurrent calls genuinely overlap, at the cost
348
+ of one worker thread per in-flight request.
349
+ """
350
+
351
+ def __init__(
352
+ self,
353
+ base_url: str,
354
+ model: str,
355
+ *,
356
+ api_key: str | None = None,
357
+ api_key_env: str = "OPENAI_API_KEY",
358
+ timeout: float = 30.0,
359
+ name: str = "openai",
360
+ ) -> None:
361
+ self._sync = OpenAICompatibleProvider(
362
+ base_url,
363
+ model,
364
+ api_key=api_key,
365
+ api_key_env=api_key_env,
366
+ timeout=timeout,
367
+ name=name,
368
+ )
369
+ self.name = self._sync.name
370
+ self.base_url = self._sync.base_url
371
+ self.model = self._sync.model
372
+ self.timeout = self._sync.timeout
373
+
374
+ async def complete(self, messages: list[Message], model: str) -> Completion:
375
+ return await asyncio.to_thread(self._sync.complete, messages, model)
376
+
377
+
378
+ class AsyncAnthropicProvider:
379
+ """Async counterpart of :class:`AnthropicProvider`.
380
+
381
+ Same constructor and behavior as the sync adapter (including the
382
+ system-message split), with the blocking urllib call offloaded via
383
+ :func:`asyncio.to_thread` — see :class:`AsyncOpenAICompatibleProvider`
384
+ for why, and what that does and does not promise.
385
+ """
386
+
387
+ def __init__(
388
+ self,
389
+ model: str,
390
+ *,
391
+ api_key: str | None = None,
392
+ api_key_env: str = "ANTHROPIC_API_KEY",
393
+ timeout: float = 30.0,
394
+ base_url: str = "https://api.anthropic.com",
395
+ max_tokens: int = 1024,
396
+ name: str = "anthropic",
397
+ ) -> None:
398
+ self._sync = AnthropicProvider(
399
+ model,
400
+ api_key=api_key,
401
+ api_key_env=api_key_env,
402
+ timeout=timeout,
403
+ base_url=base_url,
404
+ max_tokens=max_tokens,
405
+ name=name,
406
+ )
407
+ self.name = self._sync.name
408
+ self.base_url = self._sync.base_url
409
+ self.model = self._sync.model
410
+ self.timeout = self._sync.timeout
411
+ self.max_tokens = self._sync.max_tokens
412
+
413
+ async def complete(self, messages: list[Message], model: str) -> Completion:
414
+ return await asyncio.to_thread(self._sync.complete, messages, model)