boldrouter 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.
- boldrouter-0.1.0/.gitignore +24 -0
- boldrouter-0.1.0/CHANGELOG.md +5 -0
- boldrouter-0.1.0/LICENSE +21 -0
- boldrouter-0.1.0/PKG-INFO +125 -0
- boldrouter-0.1.0/README.md +95 -0
- boldrouter-0.1.0/boldrouter/__init__.py +36 -0
- boldrouter-0.1.0/boldrouter/_client.py +230 -0
- boldrouter-0.1.0/boldrouter/_options.py +112 -0
- boldrouter-0.1.0/pyproject.toml +48 -0
- boldrouter-0.1.0/tests/test_sdk.py +151 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
node_modules/
|
|
2
|
+
dist/
|
|
3
|
+
coverage/
|
|
4
|
+
*.tsbuildinfo
|
|
5
|
+
.env
|
|
6
|
+
.env.*
|
|
7
|
+
!.env.example
|
|
8
|
+
|
|
9
|
+
# Python
|
|
10
|
+
__pycache__/
|
|
11
|
+
*.pyc
|
|
12
|
+
*.egg-info/
|
|
13
|
+
build/
|
|
14
|
+
.venv/
|
|
15
|
+
.pytest_cache/
|
|
16
|
+
.ruff_cache/
|
|
17
|
+
|
|
18
|
+
# live AI SDK provider recordings; review before committing as evidence
|
|
19
|
+
packages/ai-sdk-provider/test/fixtures/live/
|
|
20
|
+
|
|
21
|
+
# PHP (a library ships without composer.lock)
|
|
22
|
+
packages/sdk-php/vendor/
|
|
23
|
+
packages/sdk-php/composer.lock
|
|
24
|
+
packages/sdk-php/.phpunit.cache/
|
boldrouter-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cybrient Technologies SA
|
|
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,125 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: boldrouter
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official BoldRouter SDK for Python. The OpenAI SDK, preconfigured for BoldRouter, plus typed routing, failover, reasoning, anonymization and caching options and model comparison helpers.
|
|
5
|
+
Project-URL: Homepage, https://boldrouter.com
|
|
6
|
+
Project-URL: Documentation, https://boldrouter.com/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/boldrouter/boldrouter
|
|
8
|
+
Project-URL: Issues, https://github.com/boldrouter/boldrouter/issues
|
|
9
|
+
Author-email: "GentleBulldozer (GentleDozer on X)" <support@boldrouter.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai,boldrouter,gateway,llm,openai-compatible,router,sdk
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Requires-Dist: openai<4,>=1.60
|
|
24
|
+
Requires-Dist: typing-extensions>=4.7
|
|
25
|
+
Provides-Extra: test
|
|
26
|
+
Requires-Dist: httpx>=0.27; extra == 'test'
|
|
27
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
|
|
28
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# boldrouter
|
|
32
|
+
|
|
33
|
+
Official [BoldRouter](https://boldrouter.com) SDK for Python. It is the OpenAI SDK, preconfigured for BoldRouter, plus typed BoldRouter options and a few helpers. One API key, 170+ models across 30+ providers, automatic routing and failover, prompt caching and PII anonymization.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install boldrouter
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Python 3.10+.
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from boldrouter import BoldRouter
|
|
47
|
+
|
|
48
|
+
client = BoldRouter(api_key="sk-bold-...") # or omit and set BOLDROUTER_API_KEY
|
|
49
|
+
|
|
50
|
+
# Everything from the OpenAI SDK works unchanged:
|
|
51
|
+
res = client.chat.completions.create(
|
|
52
|
+
model="bold/auto",
|
|
53
|
+
messages=[{"role": "user", "content": "What is an API gateway?"}],
|
|
54
|
+
)
|
|
55
|
+
print(res.choices[0].message.content)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Streaming, tools, structured outputs and embeddings are the same calls you already know. Image generation goes through chat completions: pass `modalities=["image", "text"]` with an image-capable model such as `bold/image` and read `choices[0].message.images`. `AsyncBoldRouter` is the async variant.
|
|
59
|
+
|
|
60
|
+
## BoldRouter options
|
|
61
|
+
|
|
62
|
+
`client.bold.chat` takes the same parameters as `chat.completions.create` plus typed BoldRouter options, and returns the reply together with which provider served it:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
r = client.bold.chat(
|
|
66
|
+
model="anthropic/claude-sonnet-4.6",
|
|
67
|
+
messages=[{"role": "user", "content": "Summarize this..."}],
|
|
68
|
+
routing="price", # x-bold-routing header
|
|
69
|
+
provider={"order": ["anthropic", "openai"], "allow_fallbacks": True},
|
|
70
|
+
models=["openai/gpt-5.5", "google/gemini-2.5-pro"], # cross-model fallback chain
|
|
71
|
+
reasoning={"enabled": True, "effort": "high"},
|
|
72
|
+
anonymize=True,
|
|
73
|
+
cache=False,
|
|
74
|
+
)
|
|
75
|
+
print(r.text, r.provider, r.bold["model"], r.completion.usage)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Defaults for every `client.bold` call: `BoldRouter(defaults={"routing": "latency"})`.
|
|
79
|
+
|
|
80
|
+
To use the options with the plain OpenAI methods, or with streaming:
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from boldrouter import bold_options
|
|
84
|
+
|
|
85
|
+
stream = client.chat.completions.create(
|
|
86
|
+
model="bold/auto", messages=msgs, stream=True,
|
|
87
|
+
**bold_options(model="bold/auto", routing="latency", models=["openai/gpt-5.5"]),
|
|
88
|
+
)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
| Option | Sent as | Docs |
|
|
92
|
+
|---|---|---|
|
|
93
|
+
| `routing` | `x-bold-routing` header: `balanced` (default), `price`, `latency`, `uptime` | [Routing](https://boldrouter.com/docs/routing) |
|
|
94
|
+
| `provider` | `provider` body field: `order`, `only`, `ignore`, `allow_fallbacks`, `sort` | [Routing](https://boldrouter.com/docs/routing) |
|
|
95
|
+
| `models` | `models` body field. The primary model is prepended automatically. | [Routing](https://boldrouter.com/docs/routing) |
|
|
96
|
+
| `reasoning` | `reasoning` body field: `enabled`, `effort` | [Chat completions](https://boldrouter.com/docs/chat-completions) |
|
|
97
|
+
| `anonymize` | `anonymize` body field, `True` or `{"enabled", "reverse", "entities"}` | [Anonymization](https://boldrouter.com/docs/anonymization) |
|
|
98
|
+
| `cache` | `cache` body field. On by default; `False` disables. | [Prompt caching](https://boldrouter.com/docs/prompt-caching) |
|
|
99
|
+
|
|
100
|
+
## Helpers
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
client.bold.models(kind="chat") # bold/* first, then alphabetical
|
|
104
|
+
client.bold.compare(["openai/gpt-5.5", "anthropic/claude-sonnet-4.6"], messages=msgs)
|
|
105
|
+
# [CompareResult(model=..., ok=True, text=..., bold={"provider": ...}, usage=..., latency_ms=...), ...]
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`read_bold_headers(raw.headers)` extracts the `x-bold-*` headers from any `with_raw_response` result.
|
|
109
|
+
|
|
110
|
+
## Configuration
|
|
111
|
+
|
|
112
|
+
| Option | Default | Description |
|
|
113
|
+
|---|---|---|
|
|
114
|
+
| `api_key` | `BOLDROUTER_API_KEY` | Keys start with `sk-bold-`. Create one at [boldrouter.com/dashboard/keys](https://boldrouter.com/dashboard/keys). |
|
|
115
|
+
| `base_url` | `https://boldrouter.com/v1` or `BOLDROUTER_BASE_URL` | Override for proxies or testing. |
|
|
116
|
+
| `defaults` | `{}` | BoldRouter options applied to every `client.bold` call. |
|
|
117
|
+
| anything else | | Passed to the OpenAI client: `timeout`, `max_retries`, `http_client`, `default_headers`, ... |
|
|
118
|
+
|
|
119
|
+
## Errors
|
|
120
|
+
|
|
121
|
+
BoldRouter returns OpenAI-shaped errors, so the OpenAI SDK's exceptions apply: `AuthenticationError` (401), `RateLimitError` (429), `NotFoundError` (404 unknown model), `APIStatusError` with status 402 for insufficient credit and 502 when all providers failed. The SDK retries 429 and 5xx with backoff by default.
|
|
122
|
+
|
|
123
|
+
## License
|
|
124
|
+
|
|
125
|
+
MIT. Project: [BoldRouter](https://boldrouter.com). Author: GentleBulldozer ([GentleDozer on X](https://x.com/GentleDozer)). Owner: Cybrient Technologies SA.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# boldrouter
|
|
2
|
+
|
|
3
|
+
Official [BoldRouter](https://boldrouter.com) SDK for Python. It is the OpenAI SDK, preconfigured for BoldRouter, plus typed BoldRouter options and a few helpers. One API key, 170+ models across 30+ providers, automatic routing and failover, prompt caching and PII anonymization.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install boldrouter
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Python 3.10+.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from boldrouter import BoldRouter
|
|
17
|
+
|
|
18
|
+
client = BoldRouter(api_key="sk-bold-...") # or omit and set BOLDROUTER_API_KEY
|
|
19
|
+
|
|
20
|
+
# Everything from the OpenAI SDK works unchanged:
|
|
21
|
+
res = client.chat.completions.create(
|
|
22
|
+
model="bold/auto",
|
|
23
|
+
messages=[{"role": "user", "content": "What is an API gateway?"}],
|
|
24
|
+
)
|
|
25
|
+
print(res.choices[0].message.content)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Streaming, tools, structured outputs and embeddings are the same calls you already know. Image generation goes through chat completions: pass `modalities=["image", "text"]` with an image-capable model such as `bold/image` and read `choices[0].message.images`. `AsyncBoldRouter` is the async variant.
|
|
29
|
+
|
|
30
|
+
## BoldRouter options
|
|
31
|
+
|
|
32
|
+
`client.bold.chat` takes the same parameters as `chat.completions.create` plus typed BoldRouter options, and returns the reply together with which provider served it:
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
r = client.bold.chat(
|
|
36
|
+
model="anthropic/claude-sonnet-4.6",
|
|
37
|
+
messages=[{"role": "user", "content": "Summarize this..."}],
|
|
38
|
+
routing="price", # x-bold-routing header
|
|
39
|
+
provider={"order": ["anthropic", "openai"], "allow_fallbacks": True},
|
|
40
|
+
models=["openai/gpt-5.5", "google/gemini-2.5-pro"], # cross-model fallback chain
|
|
41
|
+
reasoning={"enabled": True, "effort": "high"},
|
|
42
|
+
anonymize=True,
|
|
43
|
+
cache=False,
|
|
44
|
+
)
|
|
45
|
+
print(r.text, r.provider, r.bold["model"], r.completion.usage)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Defaults for every `client.bold` call: `BoldRouter(defaults={"routing": "latency"})`.
|
|
49
|
+
|
|
50
|
+
To use the options with the plain OpenAI methods, or with streaming:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from boldrouter import bold_options
|
|
54
|
+
|
|
55
|
+
stream = client.chat.completions.create(
|
|
56
|
+
model="bold/auto", messages=msgs, stream=True,
|
|
57
|
+
**bold_options(model="bold/auto", routing="latency", models=["openai/gpt-5.5"]),
|
|
58
|
+
)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
| Option | Sent as | Docs |
|
|
62
|
+
|---|---|---|
|
|
63
|
+
| `routing` | `x-bold-routing` header: `balanced` (default), `price`, `latency`, `uptime` | [Routing](https://boldrouter.com/docs/routing) |
|
|
64
|
+
| `provider` | `provider` body field: `order`, `only`, `ignore`, `allow_fallbacks`, `sort` | [Routing](https://boldrouter.com/docs/routing) |
|
|
65
|
+
| `models` | `models` body field. The primary model is prepended automatically. | [Routing](https://boldrouter.com/docs/routing) |
|
|
66
|
+
| `reasoning` | `reasoning` body field: `enabled`, `effort` | [Chat completions](https://boldrouter.com/docs/chat-completions) |
|
|
67
|
+
| `anonymize` | `anonymize` body field, `True` or `{"enabled", "reverse", "entities"}` | [Anonymization](https://boldrouter.com/docs/anonymization) |
|
|
68
|
+
| `cache` | `cache` body field. On by default; `False` disables. | [Prompt caching](https://boldrouter.com/docs/prompt-caching) |
|
|
69
|
+
|
|
70
|
+
## Helpers
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
client.bold.models(kind="chat") # bold/* first, then alphabetical
|
|
74
|
+
client.bold.compare(["openai/gpt-5.5", "anthropic/claude-sonnet-4.6"], messages=msgs)
|
|
75
|
+
# [CompareResult(model=..., ok=True, text=..., bold={"provider": ...}, usage=..., latency_ms=...), ...]
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`read_bold_headers(raw.headers)` extracts the `x-bold-*` headers from any `with_raw_response` result.
|
|
79
|
+
|
|
80
|
+
## Configuration
|
|
81
|
+
|
|
82
|
+
| Option | Default | Description |
|
|
83
|
+
|---|---|---|
|
|
84
|
+
| `api_key` | `BOLDROUTER_API_KEY` | Keys start with `sk-bold-`. Create one at [boldrouter.com/dashboard/keys](https://boldrouter.com/dashboard/keys). |
|
|
85
|
+
| `base_url` | `https://boldrouter.com/v1` or `BOLDROUTER_BASE_URL` | Override for proxies or testing. |
|
|
86
|
+
| `defaults` | `{}` | BoldRouter options applied to every `client.bold` call. |
|
|
87
|
+
| anything else | | Passed to the OpenAI client: `timeout`, `max_retries`, `http_client`, `default_headers`, ... |
|
|
88
|
+
|
|
89
|
+
## Errors
|
|
90
|
+
|
|
91
|
+
BoldRouter returns OpenAI-shaped errors, so the OpenAI SDK's exceptions apply: `AuthenticationError` (401), `RateLimitError` (429), `NotFoundError` (404 unknown model), `APIStatusError` with status 402 for insufficient credit and 502 when all providers failed. The SDK retries 429 and 5xx with backoff by default.
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT. Project: [BoldRouter](https://boldrouter.com). Author: GentleBulldozer ([GentleDozer on X](https://x.com/GentleDozer)). Owner: Cybrient Technologies SA.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Official BoldRouter SDK for Python."""
|
|
2
|
+
|
|
3
|
+
from ._client import AsyncBold, AsyncBoldRouter, Bold, BoldChatResult, BoldRouter, CompareResult
|
|
4
|
+
from ._options import (
|
|
5
|
+
API_KEY_ENV,
|
|
6
|
+
BASE_URL_ENV,
|
|
7
|
+
DEFAULT_BASE_URL,
|
|
8
|
+
Anonymize,
|
|
9
|
+
BoldOptions,
|
|
10
|
+
ProviderPreferences,
|
|
11
|
+
Reasoning,
|
|
12
|
+
RoutingStrategy,
|
|
13
|
+
bold_options,
|
|
14
|
+
read_bold_headers,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"API_KEY_ENV",
|
|
21
|
+
"BASE_URL_ENV",
|
|
22
|
+
"DEFAULT_BASE_URL",
|
|
23
|
+
"Anonymize",
|
|
24
|
+
"AsyncBold",
|
|
25
|
+
"AsyncBoldRouter",
|
|
26
|
+
"Bold",
|
|
27
|
+
"BoldChatResult",
|
|
28
|
+
"BoldOptions",
|
|
29
|
+
"BoldRouter",
|
|
30
|
+
"CompareResult",
|
|
31
|
+
"ProviderPreferences",
|
|
32
|
+
"Reasoning",
|
|
33
|
+
"RoutingStrategy",
|
|
34
|
+
"bold_options",
|
|
35
|
+
"read_bold_headers",
|
|
36
|
+
]
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""BoldRouter clients: the OpenAI SDK, preconfigured, plus ``client.bold`` helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any, Dict, Iterable, List, Optional, Union
|
|
10
|
+
|
|
11
|
+
from openai import AsyncOpenAI, OpenAI
|
|
12
|
+
from openai.types.chat import ChatCompletion
|
|
13
|
+
|
|
14
|
+
from ._options import (
|
|
15
|
+
API_KEY_ENV,
|
|
16
|
+
BASE_URL_ENV,
|
|
17
|
+
DEFAULT_BASE_URL,
|
|
18
|
+
Anonymize,
|
|
19
|
+
ProviderPreferences,
|
|
20
|
+
Reasoning,
|
|
21
|
+
RoutingStrategy,
|
|
22
|
+
bold_options,
|
|
23
|
+
read_bold_headers,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _resolve(api_key: Optional[str], base_url: Optional[str]) -> tuple[str, str]:
|
|
28
|
+
key = api_key or os.environ.get(API_KEY_ENV)
|
|
29
|
+
if not key:
|
|
30
|
+
raise ValueError(
|
|
31
|
+
"BoldRouter API key is missing. Pass `api_key=` or set the "
|
|
32
|
+
f"{API_KEY_ENV} environment variable. Create a key at "
|
|
33
|
+
"https://boldrouter.com/dashboard/keys"
|
|
34
|
+
)
|
|
35
|
+
return key, (base_url or os.environ.get(BASE_URL_ENV) or DEFAULT_BASE_URL).rstrip("/")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _text(completion: ChatCompletion) -> str:
|
|
39
|
+
try:
|
|
40
|
+
content = completion.choices[0].message.content
|
|
41
|
+
except (IndexError, AttributeError):
|
|
42
|
+
return ""
|
|
43
|
+
return content if isinstance(content, str) else ""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class BoldChatResult:
|
|
48
|
+
"""A non-streaming completion plus BoldRouter's response metadata."""
|
|
49
|
+
|
|
50
|
+
text: str
|
|
51
|
+
completion: ChatCompletion
|
|
52
|
+
bold: Dict[str, str] = field(default_factory=dict)
|
|
53
|
+
latency_ms: int = 0
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def provider(self) -> Optional[str]:
|
|
57
|
+
return self.bold.get("provider")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class CompareResult:
|
|
62
|
+
model: str
|
|
63
|
+
ok: bool
|
|
64
|
+
text: Optional[str] = None
|
|
65
|
+
bold: Dict[str, str] = field(default_factory=dict)
|
|
66
|
+
usage: Optional[Any] = None
|
|
67
|
+
latency_ms: Optional[int] = None
|
|
68
|
+
error: Optional[str] = None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _sort_models(models: Iterable[Any], kind: Optional[str], search: Optional[str]) -> List[Any]:
|
|
72
|
+
out = list(models)
|
|
73
|
+
if kind:
|
|
74
|
+
out = [m for m in out if getattr(m, "kind", None) in (None, kind)]
|
|
75
|
+
if search:
|
|
76
|
+
needle = search.lower()
|
|
77
|
+
out = [m for m in out if needle in m.id.lower()]
|
|
78
|
+
return sorted(out, key=lambda m: (0 if m.id.startswith("bold/") else 1, m.id))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _BoldBase:
|
|
82
|
+
def __init__(self, defaults: Optional[Dict[str, Any]]):
|
|
83
|
+
self._defaults: Dict[str, Any] = dict(defaults or {})
|
|
84
|
+
|
|
85
|
+
def _merge(self, **overrides: Any) -> Dict[str, Any]:
|
|
86
|
+
merged = dict(self._defaults)
|
|
87
|
+
merged.update({k: v for k, v in overrides.items() if v is not None})
|
|
88
|
+
return merged
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class Bold(_BoldBase):
|
|
92
|
+
"""BoldRouter-specific helpers, available as ``client.bold``."""
|
|
93
|
+
|
|
94
|
+
def __init__(self, client: "BoldRouter", defaults: Optional[Dict[str, Any]] = None):
|
|
95
|
+
super().__init__(defaults)
|
|
96
|
+
self._client = client
|
|
97
|
+
|
|
98
|
+
def chat(
|
|
99
|
+
self,
|
|
100
|
+
*,
|
|
101
|
+
model: str = "bold/auto",
|
|
102
|
+
messages: Any,
|
|
103
|
+
routing: Optional[RoutingStrategy] = None,
|
|
104
|
+
provider: Optional[ProviderPreferences] = None,
|
|
105
|
+
models: Optional[List[str]] = None,
|
|
106
|
+
reasoning: Optional[Reasoning] = None,
|
|
107
|
+
anonymize: Optional[Union[bool, Anonymize]] = None,
|
|
108
|
+
cache: Optional[bool] = None,
|
|
109
|
+
**params: Any,
|
|
110
|
+
) -> BoldChatResult:
|
|
111
|
+
"""One non-streaming chat completion with typed BoldRouter options."""
|
|
112
|
+
opts = self._merge(routing=routing, provider=provider, models=models, reasoning=reasoning, anonymize=anonymize, cache=cache)
|
|
113
|
+
extras = bold_options(model=model, **opts)
|
|
114
|
+
started = time.monotonic()
|
|
115
|
+
raw = self._client.chat.completions.with_raw_response.create(model=model, messages=messages, stream=False, **params, **extras)
|
|
116
|
+
completion = raw.parse()
|
|
117
|
+
return BoldChatResult(
|
|
118
|
+
text=_text(completion),
|
|
119
|
+
completion=completion,
|
|
120
|
+
bold=read_bold_headers(raw.headers),
|
|
121
|
+
latency_ms=int((time.monotonic() - started) * 1000),
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
def models(self, *, kind: Optional[str] = None, search: Optional[str] = None) -> List[Any]:
|
|
125
|
+
"""The model catalog, auto-router IDs (``bold/*``) first, then alphabetical."""
|
|
126
|
+
return _sort_models(self._client.models.list().data, kind, search)
|
|
127
|
+
|
|
128
|
+
def compare(self, models: List[str], **params: Any) -> List[CompareResult]:
|
|
129
|
+
"""Run the same request against several models. Failures are returned, not raised."""
|
|
130
|
+
results: List[CompareResult] = []
|
|
131
|
+
for model in models:
|
|
132
|
+
try:
|
|
133
|
+
r = self.chat(model=model, **params)
|
|
134
|
+
results.append(CompareResult(model=model, ok=True, text=r.text, bold=r.bold, usage=r.completion.usage, latency_ms=r.latency_ms))
|
|
135
|
+
except Exception as error: # noqa: BLE001 - surfaced to the caller
|
|
136
|
+
results.append(CompareResult(model=model, ok=False, error=str(error)))
|
|
137
|
+
return results
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class AsyncBold(_BoldBase):
|
|
141
|
+
"""Async variant of :class:`Bold`, available as ``client.bold`` on :class:`AsyncBoldRouter`."""
|
|
142
|
+
|
|
143
|
+
def __init__(self, client: "AsyncBoldRouter", defaults: Optional[Dict[str, Any]] = None):
|
|
144
|
+
super().__init__(defaults)
|
|
145
|
+
self._client = client
|
|
146
|
+
|
|
147
|
+
async def chat(
|
|
148
|
+
self,
|
|
149
|
+
*,
|
|
150
|
+
model: str = "bold/auto",
|
|
151
|
+
messages: Any,
|
|
152
|
+
routing: Optional[RoutingStrategy] = None,
|
|
153
|
+
provider: Optional[ProviderPreferences] = None,
|
|
154
|
+
models: Optional[List[str]] = None,
|
|
155
|
+
reasoning: Optional[Reasoning] = None,
|
|
156
|
+
anonymize: Optional[Union[bool, Anonymize]] = None,
|
|
157
|
+
cache: Optional[bool] = None,
|
|
158
|
+
**params: Any,
|
|
159
|
+
) -> BoldChatResult:
|
|
160
|
+
opts = self._merge(routing=routing, provider=provider, models=models, reasoning=reasoning, anonymize=anonymize, cache=cache)
|
|
161
|
+
extras = bold_options(model=model, **opts)
|
|
162
|
+
started = time.monotonic()
|
|
163
|
+
raw = await self._client.chat.completions.with_raw_response.create(model=model, messages=messages, stream=False, **params, **extras)
|
|
164
|
+
completion = raw.parse()
|
|
165
|
+
return BoldChatResult(
|
|
166
|
+
text=_text(completion),
|
|
167
|
+
completion=completion,
|
|
168
|
+
bold=read_bold_headers(raw.headers),
|
|
169
|
+
latency_ms=int((time.monotonic() - started) * 1000),
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
async def models(self, *, kind: Optional[str] = None, search: Optional[str] = None) -> List[Any]:
|
|
173
|
+
page = await self._client.models.list()
|
|
174
|
+
return _sort_models(page.data, kind, search)
|
|
175
|
+
|
|
176
|
+
async def compare(self, models: List[str], **params: Any) -> List[CompareResult]:
|
|
177
|
+
async def one(model: str) -> CompareResult:
|
|
178
|
+
try:
|
|
179
|
+
r = await self.chat(model=model, **params)
|
|
180
|
+
return CompareResult(model=model, ok=True, text=r.text, bold=r.bold, usage=r.completion.usage, latency_ms=r.latency_ms)
|
|
181
|
+
except Exception as error: # noqa: BLE001
|
|
182
|
+
return CompareResult(model=model, ok=False, error=str(error))
|
|
183
|
+
|
|
184
|
+
return list(await asyncio.gather(*(one(m) for m in models)))
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class BoldRouter(OpenAI):
|
|
188
|
+
"""The OpenAI client, preconfigured for BoldRouter.
|
|
189
|
+
|
|
190
|
+
Everything on ``openai.OpenAI`` works unchanged. ``client.bold`` adds
|
|
191
|
+
BoldRouter-specific helpers::
|
|
192
|
+
|
|
193
|
+
from boldrouter import BoldRouter
|
|
194
|
+
|
|
195
|
+
client = BoldRouter() # reads BOLDROUTER_API_KEY
|
|
196
|
+
r = client.bold.chat(model="bold/auto", messages=[{"role": "user", "content": "Hi"}], routing="price")
|
|
197
|
+
print(r.text, r.provider)
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
bold: Bold
|
|
201
|
+
|
|
202
|
+
def __init__(
|
|
203
|
+
self,
|
|
204
|
+
*,
|
|
205
|
+
api_key: Optional[str] = None,
|
|
206
|
+
base_url: Optional[str] = None,
|
|
207
|
+
defaults: Optional[Dict[str, Any]] = None,
|
|
208
|
+
**kwargs: Any,
|
|
209
|
+
) -> None:
|
|
210
|
+
key, base = _resolve(api_key, base_url)
|
|
211
|
+
super().__init__(api_key=key, base_url=base, **kwargs)
|
|
212
|
+
self.bold = Bold(self, defaults)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class AsyncBoldRouter(AsyncOpenAI):
|
|
216
|
+
"""Async variant of :class:`BoldRouter`."""
|
|
217
|
+
|
|
218
|
+
bold: AsyncBold
|
|
219
|
+
|
|
220
|
+
def __init__(
|
|
221
|
+
self,
|
|
222
|
+
*,
|
|
223
|
+
api_key: Optional[str] = None,
|
|
224
|
+
base_url: Optional[str] = None,
|
|
225
|
+
defaults: Optional[Dict[str, Any]] = None,
|
|
226
|
+
**kwargs: Any,
|
|
227
|
+
) -> None:
|
|
228
|
+
key, base = _resolve(api_key, base_url)
|
|
229
|
+
super().__init__(api_key=key, base_url=base, **kwargs)
|
|
230
|
+
self.bold = AsyncBold(self, defaults)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Typed BoldRouter request options and their mapping to headers and body fields.
|
|
2
|
+
|
|
3
|
+
See https://boldrouter.com/docs/chat-completions and https://boldrouter.com/docs/routing
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Any, Dict, List, Literal, Mapping, Optional, Union
|
|
9
|
+
|
|
10
|
+
from typing_extensions import TypedDict
|
|
11
|
+
|
|
12
|
+
DEFAULT_BASE_URL = "https://boldrouter.com/v1"
|
|
13
|
+
API_KEY_ENV = "BOLDROUTER_API_KEY"
|
|
14
|
+
BASE_URL_ENV = "BOLDROUTER_BASE_URL"
|
|
15
|
+
|
|
16
|
+
RoutingStrategy = Literal["balanced", "price", "latency", "uptime"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ProviderPreferences(TypedDict, total=False):
|
|
20
|
+
"""The ``provider`` body field."""
|
|
21
|
+
|
|
22
|
+
order: List[str]
|
|
23
|
+
only: List[str]
|
|
24
|
+
ignore: List[str]
|
|
25
|
+
allow_fallbacks: bool
|
|
26
|
+
sort: Literal["price", "latency", "throughput", "uptime"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Reasoning(TypedDict, total=False):
|
|
30
|
+
"""The ``reasoning`` body field."""
|
|
31
|
+
|
|
32
|
+
enabled: bool
|
|
33
|
+
effort: Literal["low", "medium", "high"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Anonymize(TypedDict, total=False):
|
|
37
|
+
"""The ``anonymize`` body field."""
|
|
38
|
+
|
|
39
|
+
enabled: bool
|
|
40
|
+
reverse: bool
|
|
41
|
+
entities: List[str]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class BoldOptions(TypedDict, total=False):
|
|
45
|
+
routing: RoutingStrategy
|
|
46
|
+
provider: ProviderPreferences
|
|
47
|
+
models: List[str]
|
|
48
|
+
reasoning: Reasoning
|
|
49
|
+
anonymize: Union[bool, Anonymize]
|
|
50
|
+
cache: bool
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def bold_options(
|
|
54
|
+
*,
|
|
55
|
+
model: Optional[str] = None,
|
|
56
|
+
routing: Optional[RoutingStrategy] = None,
|
|
57
|
+
provider: Optional[ProviderPreferences] = None,
|
|
58
|
+
models: Optional[List[str]] = None,
|
|
59
|
+
reasoning: Optional[Reasoning] = None,
|
|
60
|
+
anonymize: Optional[Union[bool, Anonymize]] = None,
|
|
61
|
+
cache: Optional[bool] = None,
|
|
62
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
63
|
+
extra_body: Optional[Mapping[str, Any]] = None,
|
|
64
|
+
) -> Dict[str, Any]:
|
|
65
|
+
"""Build ``{"extra_headers": ..., "extra_body": ...}`` for the OpenAI SDK.
|
|
66
|
+
|
|
67
|
+
Splat the result into any ``create`` call::
|
|
68
|
+
|
|
69
|
+
client.chat.completions.create(model="bold/auto", messages=msgs, **bold_options(routing="price"))
|
|
70
|
+
|
|
71
|
+
If ``models`` (the cross-model fallback chain) is given and does not already
|
|
72
|
+
include the primary ``model``, the primary model is prepended.
|
|
73
|
+
"""
|
|
74
|
+
headers: Dict[str, str] = dict(extra_headers or {})
|
|
75
|
+
if routing and routing != "balanced":
|
|
76
|
+
headers["x-bold-routing"] = routing
|
|
77
|
+
|
|
78
|
+
body: Dict[str, Any] = dict(extra_body or {})
|
|
79
|
+
if provider is not None:
|
|
80
|
+
body["provider"] = dict(provider)
|
|
81
|
+
if models is not None:
|
|
82
|
+
chain = list(models)
|
|
83
|
+
if model and model not in chain:
|
|
84
|
+
chain = [model, *chain]
|
|
85
|
+
body["models"] = chain
|
|
86
|
+
if reasoning is not None:
|
|
87
|
+
body["reasoning"] = dict(reasoning)
|
|
88
|
+
if anonymize is not None:
|
|
89
|
+
body["anonymize"] = dict(anonymize) if isinstance(anonymize, Mapping) else anonymize
|
|
90
|
+
if cache is not None:
|
|
91
|
+
body["cache"] = cache
|
|
92
|
+
|
|
93
|
+
out: Dict[str, Any] = {}
|
|
94
|
+
if headers:
|
|
95
|
+
out["extra_headers"] = headers
|
|
96
|
+
if body:
|
|
97
|
+
out["extra_body"] = body
|
|
98
|
+
return out
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def read_bold_headers(headers: Optional[Mapping[str, str]]) -> Dict[str, str]:
|
|
102
|
+
"""Extract ``x-bold-*`` response headers as ``{"provider": ..., "model": ..., "x-bold-provider": ...}``."""
|
|
103
|
+
out: Dict[str, str] = {}
|
|
104
|
+
if not headers:
|
|
105
|
+
return out
|
|
106
|
+
for key, value in headers.items():
|
|
107
|
+
k = key.lower()
|
|
108
|
+
if not k.startswith("x-bold-"):
|
|
109
|
+
continue
|
|
110
|
+
out[k] = value
|
|
111
|
+
out[k[len("x-bold-") :].replace("-", "_")] = value
|
|
112
|
+
return out
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "boldrouter"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official BoldRouter SDK for Python. The OpenAI SDK, preconfigured for BoldRouter, plus typed routing, failover, reasoning, anonymization and caching options and model comparison helpers."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
authors = [{ name = "GentleBulldozer (GentleDozer on X)", email = "support@boldrouter.com" }]
|
|
14
|
+
keywords = ["boldrouter", "sdk", "llm", "ai", "openai-compatible", "router", "gateway"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
dependencies = [
|
|
27
|
+
"openai>=1.60,<4",
|
|
28
|
+
"typing-extensions>=4.7",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
test = ["pytest>=8", "pytest-asyncio>=0.24", "httpx>=0.27"]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://boldrouter.com"
|
|
36
|
+
Documentation = "https://boldrouter.com/docs"
|
|
37
|
+
Repository = "https://github.com/boldrouter/boldrouter"
|
|
38
|
+
Issues = "https://github.com/boldrouter/boldrouter/issues"
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.wheel]
|
|
41
|
+
packages = ["boldrouter"]
|
|
42
|
+
|
|
43
|
+
[tool.hatch.build.targets.sdist]
|
|
44
|
+
include = ["boldrouter", "tests", "README.md", "CHANGELOG.md", "LICENSE", "pyproject.toml"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
testpaths = ["tests"]
|
|
48
|
+
asyncio_mode = "auto"
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from boldrouter import AsyncBoldRouter, BoldRouter, bold_options, read_bold_headers
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def completion(text="hello", model="openai/gpt-5.5"):
|
|
10
|
+
return {
|
|
11
|
+
"id": "chatcmpl-1",
|
|
12
|
+
"object": "chat.completion",
|
|
13
|
+
"created": 1,
|
|
14
|
+
"model": model,
|
|
15
|
+
"choices": [{"index": 0, "message": {"role": "assistant", "content": text}, "finish_reason": "stop"}],
|
|
16
|
+
"usage": {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5},
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Capture:
|
|
21
|
+
def __init__(self, route):
|
|
22
|
+
self.calls = []
|
|
23
|
+
self._route = route
|
|
24
|
+
|
|
25
|
+
def handler(self, request: httpx.Request) -> httpx.Response:
|
|
26
|
+
call = {
|
|
27
|
+
"url": str(request.url),
|
|
28
|
+
"method": request.method,
|
|
29
|
+
"headers": {k.lower(): v for k, v in request.headers.items()},
|
|
30
|
+
"body": json.loads(request.content) if request.content else None,
|
|
31
|
+
}
|
|
32
|
+
self.calls.append(call)
|
|
33
|
+
r = self._route(call)
|
|
34
|
+
return httpx.Response(r.get("status", 200), json=r["body"], headers=r.get("headers", {}))
|
|
35
|
+
|
|
36
|
+
def client(self):
|
|
37
|
+
return httpx.Client(transport=httpx.MockTransport(self.handler))
|
|
38
|
+
|
|
39
|
+
def async_client(self):
|
|
40
|
+
return httpx.AsyncClient(transport=httpx.MockTransport(self.handler))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_bold_options_and_headers():
|
|
44
|
+
assert bold_options(model="bold/auto") == {}
|
|
45
|
+
assert bold_options(routing="balanced") == {}
|
|
46
|
+
assert bold_options(model="c/d", routing="price", models=["a/b"], cache=False, anonymize=True, reasoning={"effort": "low"}, provider={"only": ["x"]}) == {
|
|
47
|
+
"extra_headers": {"x-bold-routing": "price"},
|
|
48
|
+
"extra_body": {"provider": {"only": ["x"]}, "models": ["c/d", "a/b"], "reasoning": {"effort": "low"}, "anonymize": True, "cache": False},
|
|
49
|
+
}
|
|
50
|
+
assert bold_options(extra_headers={"x-a": "1"}, extra_body={"z": 1}, cache=True) == {"extra_headers": {"x-a": "1"}, "extra_body": {"z": 1, "cache": True}}
|
|
51
|
+
assert read_bold_headers({"X-Bold-Provider": "anthropic", "x-bold-model": "a/b", "content-type": "x"}) == {
|
|
52
|
+
"x-bold-provider": "anthropic",
|
|
53
|
+
"provider": "anthropic",
|
|
54
|
+
"x-bold-model": "a/b",
|
|
55
|
+
"model": "a/b",
|
|
56
|
+
}
|
|
57
|
+
assert read_bold_headers(None) == {}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_plain_openai_call_goes_to_boldrouter(monkeypatch):
|
|
61
|
+
monkeypatch.delenv("BOLDROUTER_API_KEY", raising=False)
|
|
62
|
+
cap = Capture(lambda call: {"body": completion("pong")})
|
|
63
|
+
client = BoldRouter(api_key="sk-bold-test", http_client=cap.client())
|
|
64
|
+
|
|
65
|
+
res = client.chat.completions.create(model="bold/auto", messages=[{"role": "user", "content": "ping"}])
|
|
66
|
+
|
|
67
|
+
assert res.choices[0].message.content == "pong"
|
|
68
|
+
call = cap.calls[0]
|
|
69
|
+
assert call["url"] == "https://boldrouter.com/v1/chat/completions"
|
|
70
|
+
assert call["headers"]["authorization"] == "Bearer sk-bold-test"
|
|
71
|
+
assert call["body"]["model"] == "bold/auto"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_bold_chat_maps_options_defaults_and_metadata():
|
|
75
|
+
cap = Capture(lambda call: {"body": completion("pong", "anthropic/claude-sonnet-4.6"), "headers": {"x-bold-provider": "anthropic", "x-bold-cache": "on"}})
|
|
76
|
+
client = BoldRouter(api_key="k", http_client=cap.client(), defaults={"cache": False, "routing": "latency"})
|
|
77
|
+
|
|
78
|
+
r = client.bold.chat(
|
|
79
|
+
model="anthropic/claude-sonnet-4.6",
|
|
80
|
+
messages=[{"role": "user", "content": "hi"}],
|
|
81
|
+
temperature=0.2,
|
|
82
|
+
routing="price",
|
|
83
|
+
provider={"order": ["anthropic"], "allow_fallbacks": False},
|
|
84
|
+
models=["openai/gpt-5.5"],
|
|
85
|
+
reasoning={"enabled": True, "effort": "high"},
|
|
86
|
+
anonymize=True,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
assert r.text == "pong"
|
|
90
|
+
assert r.provider == "anthropic"
|
|
91
|
+
assert r.bold["cache"] == "on"
|
|
92
|
+
assert r.completion.usage.total_tokens == 5
|
|
93
|
+
assert r.latency_ms >= 0
|
|
94
|
+
call = cap.calls[0]
|
|
95
|
+
assert call["headers"]["x-bold-routing"] == "price"
|
|
96
|
+
body = call["body"]
|
|
97
|
+
assert body["model"] == "anthropic/claude-sonnet-4.6"
|
|
98
|
+
assert body["temperature"] == 0.2
|
|
99
|
+
assert body["stream"] is False
|
|
100
|
+
assert body["provider"] == {"order": ["anthropic"], "allow_fallbacks": False}
|
|
101
|
+
assert body["models"] == ["anthropic/claude-sonnet-4.6", "openai/gpt-5.5"]
|
|
102
|
+
assert body["reasoning"] == {"enabled": True, "effort": "high"}
|
|
103
|
+
assert body["anonymize"] is True
|
|
104
|
+
assert body["cache"] is False
|
|
105
|
+
assert "routing" not in body
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_models_and_compare():
|
|
109
|
+
def route(call):
|
|
110
|
+
if call["url"].endswith("/models"):
|
|
111
|
+
return {"body": {"object": "list", "data": [
|
|
112
|
+
{"id": "openai/gpt-5.5", "object": "model", "created": 1, "owned_by": "x", "kind": "chat"},
|
|
113
|
+
{"id": "bold/fast", "object": "model", "created": 1, "owned_by": "x", "kind": "chat"},
|
|
114
|
+
{"id": "openai/text-embedding-3-small", "object": "model", "created": 1, "owned_by": "x", "kind": "embedding"},
|
|
115
|
+
{"id": "bold/auto", "object": "model", "created": 1, "owned_by": "x", "kind": "chat"},
|
|
116
|
+
]}}
|
|
117
|
+
if call["body"]["model"] == "bad/model":
|
|
118
|
+
return {"status": 404, "body": {"error": {"message": "Unknown model", "type": "model_not_found"}}}
|
|
119
|
+
return {"body": completion(f"from {call['body']['model']}", call["body"]["model"]), "headers": {"x-bold-provider": call["body"]["model"].split("/")[0]}}
|
|
120
|
+
|
|
121
|
+
cap = Capture(route)
|
|
122
|
+
client = BoldRouter(api_key="k", http_client=cap.client(), max_retries=0)
|
|
123
|
+
|
|
124
|
+
assert [m.id for m in client.bold.models(kind="chat")] == ["bold/auto", "bold/fast", "openai/gpt-5.5"]
|
|
125
|
+
assert [m.id for m in client.bold.models(search="embedding")] == ["openai/text-embedding-3-small"]
|
|
126
|
+
|
|
127
|
+
results = client.bold.compare(["openai/gpt-5.5", "bad/model"], messages=[{"role": "user", "content": "hi"}])
|
|
128
|
+
assert results[0].ok and results[0].text == "from openai/gpt-5.5" and results[0].bold["provider"] == "openai"
|
|
129
|
+
assert not results[1].ok and "Unknown model" in results[1].error
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def test_env_key_base_url_and_missing_key(monkeypatch):
|
|
133
|
+
monkeypatch.delenv("BOLDROUTER_API_KEY", raising=False)
|
|
134
|
+
with pytest.raises(ValueError, match="BOLDROUTER_API_KEY"):
|
|
135
|
+
BoldRouter()
|
|
136
|
+
monkeypatch.setenv("BOLDROUTER_API_KEY", "sk-bold-env")
|
|
137
|
+
cap = Capture(lambda call: {"body": {"object": "list", "data": []}})
|
|
138
|
+
BoldRouter(base_url="https://eu.example.test/v1/", http_client=cap.client()).models.list()
|
|
139
|
+
assert cap.calls[0]["url"] == "https://eu.example.test/v1/models"
|
|
140
|
+
assert cap.calls[0]["headers"]["authorization"] == "Bearer sk-bold-env"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
async def test_async_client():
|
|
144
|
+
cap = Capture(lambda call: {"body": completion("pong"), "headers": {"x-bold-provider": "openai"}})
|
|
145
|
+
client = AsyncBoldRouter(api_key="k", http_client=cap.async_client())
|
|
146
|
+
r = await client.bold.chat(messages=[{"role": "user", "content": "hi"}], routing="uptime")
|
|
147
|
+
assert r.text == "pong" and r.provider == "openai"
|
|
148
|
+
assert cap.calls[0]["headers"]["x-bold-routing"] == "uptime"
|
|
149
|
+
assert cap.calls[0]["body"]["model"] == "bold/auto"
|
|
150
|
+
results = await client.bold.compare(["a/b", "c/d"], messages=[{"role": "user", "content": "hi"}])
|
|
151
|
+
assert [x.ok for x in results] == [True, True]
|