switchboard-router 0.1.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.
- switchboard_router/__init__.py +12 -0
- switchboard_router/backends.py +222 -0
- switchboard_router/cli.py +58 -0
- switchboard_router/decision.py +37 -0
- switchboard_router/py.typed +0 -0
- switchboard_router/router.py +79 -0
- switchboard_router-0.1.0.dist-info/METADATA +115 -0
- switchboard_router-0.1.0.dist-info/RECORD +11 -0
- switchboard_router-0.1.0.dist-info/WHEEL +4 -0
- switchboard_router-0.1.0.dist-info/entry_points.txt +2 -0
- switchboard_router-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Switchboard: pick the cheapest LLM that can handle each prompt."""
|
|
2
|
+
from .backends import BackendError, OllamaBackend, OpenAIBackend, TransformersBackend
|
|
3
|
+
from .decision import DOMAINS, TIERS, Decision, parse_decision
|
|
4
|
+
from .router import DEFAULT_MODELS, MAX_PROMPT_CHARS, Router
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Router", "Decision", "parse_decision", "BackendError",
|
|
10
|
+
"OllamaBackend", "OpenAIBackend", "TransformersBackend",
|
|
11
|
+
"DEFAULT_MODELS", "TIERS", "DOMAINS", "MAX_PROMPT_CHARS", "__version__",
|
|
12
|
+
]
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Ways to run the Switchboard model: Ollama, any OpenAI-compatible server, or Transformers in-process."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import http.client
|
|
5
|
+
import importlib.util
|
|
6
|
+
import json
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from typing import Protocol
|
|
11
|
+
|
|
12
|
+
OLLAMA_HOST = "http://localhost:11434"
|
|
13
|
+
OLLAMA_MODEL = "hf.co/switchboardllm/switchboard-router-0.5b-GGUF"
|
|
14
|
+
HF_REPO = "switchboardllm/switchboard-router-0.5b"
|
|
15
|
+
MAX_NEW_TOKENS = 24
|
|
16
|
+
MAX_PROMPT_TOKENS = 512 # the router was trained on prompts cut to 512 tokens
|
|
17
|
+
DEFAULT_TIMEOUT = 15.0 # routing sits in front of every request, so don't hang for long
|
|
18
|
+
PULL_TIMEOUT = 1800.0 # pulling the 994 MB GGUF on first use can take a while
|
|
19
|
+
_TRANSPORT_ERRORS = (OSError, http.client.HTTPException, UnicodeDecodeError, ValueError)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BackendError(RuntimeError):
|
|
23
|
+
"""The backend could not produce an answer (network, server or model error)."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Backend(Protocol):
|
|
27
|
+
def generate(self, prompt: str) -> str: ...
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
31
|
+
"""Don't follow redirects: urllib would forward the Authorization header to the new host."""
|
|
32
|
+
|
|
33
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_OPENER = urllib.request.build_opener(_NoRedirect)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _open(req: urllib.request.Request, timeout: float):
|
|
41
|
+
return _OPENER.open(req, timeout=timeout)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _check_http_url(url: str, what: str) -> str:
|
|
45
|
+
parts = urllib.parse.urlsplit(url)
|
|
46
|
+
if parts.scheme not in ("http", "https") or not parts.netloc:
|
|
47
|
+
raise ValueError(f"{what} must be an http(s) URL, got {url!r}")
|
|
48
|
+
return url.rstrip("/")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _safe_url(url: str) -> str:
|
|
52
|
+
"""The URL without credentials or query, for error messages."""
|
|
53
|
+
parts = urllib.parse.urlsplit(url)
|
|
54
|
+
host = parts.hostname or ""
|
|
55
|
+
if parts.port:
|
|
56
|
+
host = f"{host}:{parts.port}"
|
|
57
|
+
return urllib.parse.urlunsplit((parts.scheme, host, parts.path, "", ""))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _redact(text: str, secret: str | None) -> str:
|
|
61
|
+
return text.replace(secret, "***") if secret else text
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _post_json(url: str, body: dict, headers: dict | None = None, timeout: float = DEFAULT_TIMEOUT,
|
|
65
|
+
secret: str | None = None) -> dict:
|
|
66
|
+
req = urllib.request.Request(
|
|
67
|
+
url,
|
|
68
|
+
data=json.dumps(body).encode("utf-8"),
|
|
69
|
+
headers={"Content-Type": "application/json", **(headers or {})},
|
|
70
|
+
method="POST",
|
|
71
|
+
)
|
|
72
|
+
where = _safe_url(url)
|
|
73
|
+
try:
|
|
74
|
+
with _open(req, timeout) as resp:
|
|
75
|
+
raw = resp.read()
|
|
76
|
+
except urllib.error.HTTPError as exc:
|
|
77
|
+
try:
|
|
78
|
+
detail = exc.read().decode("utf-8", "replace")[:200]
|
|
79
|
+
except _TRANSPORT_ERRORS:
|
|
80
|
+
detail = ""
|
|
81
|
+
raise BackendError(_redact(f"HTTP {exc.code} from {where}: {detail}", secret)) from exc
|
|
82
|
+
except _TRANSPORT_ERRORS as exc:
|
|
83
|
+
reason = getattr(exc, "reason", exc)
|
|
84
|
+
raise BackendError(_redact(f"could not reach {where}: {reason}", secret)) from exc
|
|
85
|
+
try:
|
|
86
|
+
return json.loads(raw.decode("utf-8"))
|
|
87
|
+
except (UnicodeDecodeError, ValueError) as exc:
|
|
88
|
+
raise BackendError(f"{where} did not return JSON") from exc
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class OllamaBackend:
|
|
92
|
+
"""Calls a local Ollama server. Pulls the GGUF from Hugging Face the first time it's missing."""
|
|
93
|
+
|
|
94
|
+
def __init__(self, model: str = OLLAMA_MODEL, host: str = OLLAMA_HOST, timeout: float = DEFAULT_TIMEOUT,
|
|
95
|
+
auto_pull: bool = True):
|
|
96
|
+
self.model = model
|
|
97
|
+
self.host = _check_http_url(host, "host")
|
|
98
|
+
self.timeout = timeout
|
|
99
|
+
self.auto_pull = auto_pull
|
|
100
|
+
|
|
101
|
+
def _chat(self, prompt: str) -> dict:
|
|
102
|
+
body = {
|
|
103
|
+
"model": self.model,
|
|
104
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
105
|
+
"stream": False,
|
|
106
|
+
"options": {"temperature": 0, "num_predict": MAX_NEW_TOKENS},
|
|
107
|
+
}
|
|
108
|
+
return _post_json(f"{self.host}/api/chat", body, timeout=self.timeout)
|
|
109
|
+
|
|
110
|
+
def pull(self) -> None:
|
|
111
|
+
_post_json(f"{self.host}/api/pull", {"model": self.model, "stream": False}, timeout=PULL_TIMEOUT)
|
|
112
|
+
|
|
113
|
+
def generate(self, prompt: str) -> str:
|
|
114
|
+
try:
|
|
115
|
+
data = self._chat(prompt)
|
|
116
|
+
except BackendError as exc:
|
|
117
|
+
if "HTTP 404" not in str(exc):
|
|
118
|
+
raise
|
|
119
|
+
if not self.auto_pull:
|
|
120
|
+
raise BackendError(f"model not pulled yet; run: ollama pull {self.model}") from exc
|
|
121
|
+
self.pull()
|
|
122
|
+
data = self._chat(prompt)
|
|
123
|
+
try:
|
|
124
|
+
return data["message"]["content"]
|
|
125
|
+
except (KeyError, TypeError) as exc:
|
|
126
|
+
raise BackendError(f"unexpected Ollama response: {str(data)[:200]}") from exc
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class OpenAIBackend:
|
|
130
|
+
"""Calls any OpenAI-compatible chat endpoint: llama-server, vLLM, or the Surplus API."""
|
|
131
|
+
|
|
132
|
+
def __init__(self, base_url: str, model: str, api_key: str | None = None, timeout: float = DEFAULT_TIMEOUT):
|
|
133
|
+
self.base_url = _check_http_url(base_url, "base_url")
|
|
134
|
+
self.model = model
|
|
135
|
+
self.api_key = api_key
|
|
136
|
+
self.timeout = timeout
|
|
137
|
+
|
|
138
|
+
def generate(self, prompt: str) -> str:
|
|
139
|
+
body = {
|
|
140
|
+
"model": self.model,
|
|
141
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
142
|
+
"temperature": 0,
|
|
143
|
+
"max_tokens": MAX_NEW_TOKENS,
|
|
144
|
+
}
|
|
145
|
+
headers = {"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}
|
|
146
|
+
data = _post_json(f"{self.base_url}/chat/completions", body, headers, self.timeout, secret=self.api_key)
|
|
147
|
+
try:
|
|
148
|
+
return data["choices"][0]["message"]["content"]
|
|
149
|
+
except (KeyError, IndexError, TypeError) as exc:
|
|
150
|
+
raise BackendError(_redact(f"unexpected response: {str(data)[:200]}", self.api_key)) from exc
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class TransformersBackend:
|
|
154
|
+
"""Runs the model in this process. Needs `pip install switchboard-router[local]`."""
|
|
155
|
+
|
|
156
|
+
def __init__(self, repo: str = HF_REPO, device: str | None = None, revision: str | None = None):
|
|
157
|
+
if not transformers_available():
|
|
158
|
+
raise RuntimeError("the transformers backend needs: pip install 'switchboard-router[local]'")
|
|
159
|
+
import torch
|
|
160
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
161
|
+
|
|
162
|
+
self._torch = torch
|
|
163
|
+
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
|
164
|
+
self.tokenizer = AutoTokenizer.from_pretrained(repo, revision=revision)
|
|
165
|
+
self.model = AutoModelForCausalLM.from_pretrained(repo, revision=revision).to(self.device).eval()
|
|
166
|
+
|
|
167
|
+
def generate(self, prompt: str) -> str:
|
|
168
|
+
tok = self.tokenizer
|
|
169
|
+
ids = tok(prompt, add_special_tokens=False)["input_ids"]
|
|
170
|
+
if len(ids) > MAX_PROMPT_TOKENS:
|
|
171
|
+
prompt = tok.decode(ids[:MAX_PROMPT_TOKENS])
|
|
172
|
+
# render to text first: apply_chat_template's return type changed across transformers versions
|
|
173
|
+
text = tok.apply_chat_template([{"role": "user", "content": prompt}], add_generation_prompt=True, tokenize=False)
|
|
174
|
+
enc = tok(text, return_tensors="pt", add_special_tokens=False).to(self.device)
|
|
175
|
+
with self._torch.inference_mode():
|
|
176
|
+
out = self.model.generate(**enc, max_new_tokens=MAX_NEW_TOKENS, do_sample=False,
|
|
177
|
+
pad_token_id=tok.eos_token_id)
|
|
178
|
+
return tok.decode(out[0, enc["input_ids"].shape[1]:], skip_special_tokens=True)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def ollama_is_running(host: str = OLLAMA_HOST, timeout: float = 1.0) -> bool:
|
|
182
|
+
try:
|
|
183
|
+
with _open(urllib.request.Request(f"{host.rstrip('/')}/api/version"), timeout):
|
|
184
|
+
return True
|
|
185
|
+
except _TRANSPORT_ERRORS:
|
|
186
|
+
return False
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def transformers_available() -> bool:
|
|
190
|
+
return all(importlib.util.find_spec(m) is not None for m in ("transformers", "torch"))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def build_backend(
|
|
194
|
+
name: str = "auto",
|
|
195
|
+
*,
|
|
196
|
+
base_url: str | None = None,
|
|
197
|
+
backend_model: str | None = None,
|
|
198
|
+
api_key: str | None = None,
|
|
199
|
+
host: str = OLLAMA_HOST,
|
|
200
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
201
|
+
) -> Backend:
|
|
202
|
+
if name == "auto":
|
|
203
|
+
if base_url:
|
|
204
|
+
name = "openai"
|
|
205
|
+
elif ollama_is_running(host):
|
|
206
|
+
name = "ollama"
|
|
207
|
+
elif transformers_available():
|
|
208
|
+
name = "transformers"
|
|
209
|
+
else:
|
|
210
|
+
raise RuntimeError(
|
|
211
|
+
"No backend found. Start Ollama (https://ollama.com), or install the local backend with "
|
|
212
|
+
"pip install 'switchboard-router[local]', or pass backend='openai' with a base_url."
|
|
213
|
+
)
|
|
214
|
+
if name == "ollama":
|
|
215
|
+
return OllamaBackend(model=backend_model or OLLAMA_MODEL, host=host, timeout=timeout)
|
|
216
|
+
if name == "openai":
|
|
217
|
+
if not base_url:
|
|
218
|
+
raise ValueError("backend='openai' needs base_url, e.g. http://localhost:8080/v1")
|
|
219
|
+
return OpenAIBackend(base_url=base_url, model=backend_model or "switchboard", api_key=api_key, timeout=timeout)
|
|
220
|
+
if name == "transformers":
|
|
221
|
+
return TransformersBackend(repo=backend_model or HF_REPO)
|
|
222
|
+
raise ValueError(f"unknown backend {name!r}: use auto, ollama, openai or transformers")
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""`switchboard "your prompt"` prints the tier, domain and model as JSON. Use `-` to read the prompt from stdin."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from .router import Router
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def build_router(**kwargs) -> Router:
|
|
13
|
+
return Router(**kwargs)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main(argv: list[str] | None = None) -> int:
|
|
17
|
+
ap = argparse.ArgumentParser(prog="switchboard", description="Pick the cheapest model tier for a prompt.")
|
|
18
|
+
ap.add_argument("prompt", help="the prompt to route, or - to read it from stdin")
|
|
19
|
+
ap.add_argument("--backend", default="auto", choices=["auto", "ollama", "openai", "transformers"])
|
|
20
|
+
ap.add_argument("--base-url", default=None, help="OpenAI-compatible base URL, e.g. http://localhost:8080/v1")
|
|
21
|
+
ap.add_argument("--backend-model", default=None, help="model name on the backend")
|
|
22
|
+
ap.add_argument("--api-key-env", default=None, help="name of the env var holding the API key")
|
|
23
|
+
ap.add_argument("--timeout", type=float, default=None, help="seconds to wait for the backend")
|
|
24
|
+
args = ap.parse_args(argv)
|
|
25
|
+
|
|
26
|
+
prompt = sys.stdin.read() if args.prompt == "-" else args.prompt
|
|
27
|
+
if not prompt.strip():
|
|
28
|
+
print("switchboard: prompt is empty", file=sys.stderr)
|
|
29
|
+
return 2
|
|
30
|
+
options: dict = {"backend": args.backend}
|
|
31
|
+
if args.base_url:
|
|
32
|
+
options["base_url"] = args.base_url
|
|
33
|
+
if args.backend_model:
|
|
34
|
+
options["backend_model"] = args.backend_model
|
|
35
|
+
if args.timeout:
|
|
36
|
+
options["timeout"] = args.timeout
|
|
37
|
+
if args.api_key_env:
|
|
38
|
+
key = os.environ.get(args.api_key_env)
|
|
39
|
+
if not key:
|
|
40
|
+
print(f"switchboard: environment variable {args.api_key_env} is not set", file=sys.stderr)
|
|
41
|
+
return 1
|
|
42
|
+
options["api_key"] = key
|
|
43
|
+
try:
|
|
44
|
+
router = build_router(**options)
|
|
45
|
+
decision = router.route(prompt)
|
|
46
|
+
except Exception as exc: # report setup problems as a message, not a traceback
|
|
47
|
+
print(f"switchboard: {exc}", file=sys.stderr)
|
|
48
|
+
return 1
|
|
49
|
+
result = {**decision.to_dict(), "model": router.models[decision.tier]}
|
|
50
|
+
if decision.error:
|
|
51
|
+
result["error"] = decision.error
|
|
52
|
+
print(f"switchboard: routing failed, using frontier: {decision.error}", file=sys.stderr)
|
|
53
|
+
print(json.dumps(result))
|
|
54
|
+
return 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
if __name__ == "__main__":
|
|
58
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""The router's answer, parsed from one line of JSON, failing safe to the frontier tier."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
TIERS = ("small", "mid", "frontier")
|
|
8
|
+
DOMAINS = ("code", "math", "writing", "general")
|
|
9
|
+
SAFE_TIER = "frontier"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Decision:
|
|
14
|
+
tier: str
|
|
15
|
+
domain: str = "general"
|
|
16
|
+
raw: str = ""
|
|
17
|
+
valid: bool = True
|
|
18
|
+
error: str = ""
|
|
19
|
+
|
|
20
|
+
def to_dict(self) -> dict:
|
|
21
|
+
return {"tier": self.tier, "domain": self.domain, "valid": self.valid}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def parse_decision(text: str) -> Decision:
|
|
25
|
+
"""Read the model's output. Anything unreadable becomes frontier, so a bad call costs money, not quality."""
|
|
26
|
+
try:
|
|
27
|
+
data = json.loads(text.strip())
|
|
28
|
+
except (ValueError, RecursionError, AttributeError, TypeError):
|
|
29
|
+
return Decision(tier=SAFE_TIER, raw=text, valid=False)
|
|
30
|
+
if not isinstance(data, dict) or data.get("tier") not in TIERS:
|
|
31
|
+
return Decision(tier=SAFE_TIER, raw=text, valid=False)
|
|
32
|
+
domain = data.get("domain") if data.get("domain") in DOMAINS else "general"
|
|
33
|
+
return Decision(tier=data["tier"], domain=domain, raw=text, valid=True)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def failed(error: str) -> Decision:
|
|
37
|
+
return Decision(tier=SAFE_TIER, valid=False, error=error)
|
|
File without changes
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Route a prompt to the cheapest tier that can handle it, then map the tier to a model id."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import warnings
|
|
5
|
+
from types import MappingProxyType
|
|
6
|
+
from typing import Mapping, Union
|
|
7
|
+
|
|
8
|
+
from . import backends
|
|
9
|
+
from .backends import Backend, BackendError
|
|
10
|
+
from .decision import TIERS, Decision, failed, parse_decision
|
|
11
|
+
|
|
12
|
+
MAX_PROMPT_CHARS = 2000
|
|
13
|
+
|
|
14
|
+
# Default tier models on Surplus (list output price per 1M tokens: $0.50, $10, $20).
|
|
15
|
+
DEFAULT_MODELS: Mapping[str, str] = MappingProxyType({
|
|
16
|
+
"small": "anthropic/claude-haiku-5.5",
|
|
17
|
+
"mid": "anthropic/claude-sonnet-5.5",
|
|
18
|
+
"frontier": "anthropic/claude-opus-5.5",
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _check_models(models: Mapping[str, str] | None) -> Mapping[str, str]:
|
|
23
|
+
models = dict(models or {})
|
|
24
|
+
unknown = set(models) - set(TIERS)
|
|
25
|
+
if unknown:
|
|
26
|
+
raise ValueError(f"unknown tier(s) in models: {sorted(unknown)}; use {list(TIERS)}")
|
|
27
|
+
if any(not isinstance(v, str) or not v.strip() for v in models.values()):
|
|
28
|
+
raise ValueError("model ids must be non-empty strings")
|
|
29
|
+
missing = [t for t in TIERS if t not in models]
|
|
30
|
+
if models and missing:
|
|
31
|
+
warnings.warn(f"models has no entry for {missing}; those tiers use the defaults", UserWarning, stacklevel=3)
|
|
32
|
+
return MappingProxyType({**DEFAULT_MODELS, **models})
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Router:
|
|
36
|
+
"""
|
|
37
|
+
>>> router = Router() # uses Ollama if it's running
|
|
38
|
+
>>> router.route("Write a haiku about rain").tier
|
|
39
|
+
'small'
|
|
40
|
+
>>> router.pick_model("Unscramble the following words: eglar, ngareo, kobo")
|
|
41
|
+
'anthropic/claude-opus-5.5'
|
|
42
|
+
|
|
43
|
+
Unreadable output and backend failures route to frontier (valid=False) unless fail_safe=False,
|
|
44
|
+
in which case they raise. Empty or non-string prompts always raise.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
backend: Union[str, Backend] = "auto",
|
|
50
|
+
models: Mapping[str, str] | None = None,
|
|
51
|
+
fail_safe: bool = True,
|
|
52
|
+
**backend_options,
|
|
53
|
+
):
|
|
54
|
+
self.models = _check_models(models)
|
|
55
|
+
self.fail_safe = fail_safe
|
|
56
|
+
if isinstance(backend, str):
|
|
57
|
+
backend = backends.build_backend(backend, **backend_options)
|
|
58
|
+
if not callable(getattr(backend, "generate", None)):
|
|
59
|
+
raise TypeError("backend must be a name or an object with a generate(prompt) method")
|
|
60
|
+
self.backend: Backend = backend
|
|
61
|
+
|
|
62
|
+
def route(self, prompt: str) -> Decision:
|
|
63
|
+
if not isinstance(prompt, str):
|
|
64
|
+
raise TypeError(f"prompt must be a string, got {type(prompt).__name__}")
|
|
65
|
+
if not prompt.strip():
|
|
66
|
+
raise ValueError("prompt is empty")
|
|
67
|
+
try:
|
|
68
|
+
text = self.backend.generate(prompt[:MAX_PROMPT_CHARS])
|
|
69
|
+
except Exception as exc: # any failure must still produce a safe decision
|
|
70
|
+
if not self.fail_safe:
|
|
71
|
+
raise
|
|
72
|
+
return failed(f"{type(exc).__name__}: {exc}")
|
|
73
|
+
decision = parse_decision(text)
|
|
74
|
+
if not decision.valid and not self.fail_safe:
|
|
75
|
+
raise BackendError(f"unreadable router output: {str(text)[:100]!r}")
|
|
76
|
+
return decision
|
|
77
|
+
|
|
78
|
+
def pick_model(self, prompt: str) -> str:
|
|
79
|
+
return self.models[self.route(prompt).tier]
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: switchboard-router
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Pick the cheapest LLM that can handle each prompt, with the open Switchboard router.
|
|
5
|
+
Project-URL: Homepage, https://huggingface.co/spaces/switchboardllm/switchboard
|
|
6
|
+
Project-URL: Model, https://huggingface.co/switchboardllm/switchboard-router-0.5b
|
|
7
|
+
Author: Switchboard
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: cost,llm,llm-routing,ollama,openai,router
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
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: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Provides-Extra: local
|
|
22
|
+
Requires-Dist: torch>=2.1; extra == 'local'
|
|
23
|
+
Requires-Dist: transformers>=4.45; extra == 'local'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# switchboard-router
|
|
27
|
+
|
|
28
|
+
Pick the cheapest LLM that can handle each prompt.
|
|
29
|
+
|
|
30
|
+
`switchboard-router` asks [Switchboard](https://huggingface.co/switchboardllm/switchboard-router-0.5b), a 0.5B open router model, which tier a prompt needs: `small`, `mid` or `frontier`. Easy prompts go to a cheap model, and you pay frontier prices only when the prompt needs it.
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
pip install switchboard-router
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Quickstart
|
|
37
|
+
|
|
38
|
+
You need one way to run the model. The easiest is [Ollama](https://ollama.com): install it and leave it running. If the model isn't in Ollama yet, the first call pulls it (994 MB) from Hugging Face, which takes a minute or two. To do that ahead of time:
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
ollama pull hf.co/switchboardllm/switchboard-router-0.5b-GGUF
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from switchboard_router import Router
|
|
46
|
+
|
|
47
|
+
router = Router() # uses Ollama when it's running
|
|
48
|
+
|
|
49
|
+
router.route("Write a haiku about rain").tier
|
|
50
|
+
# 'small'
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
router.pick_model("Unscramble the following words: eglar, ngareo, kobo")
|
|
54
|
+
# 'anthropic/claude-opus-5.5'
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
From the terminal:
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
switchboard "Design a rate limiter for 10M requests per second across 5 regions"
|
|
61
|
+
{"tier": "mid", "domain": "general", "valid": true, "model": "anthropic/claude-sonnet-5.5"}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Route, then call the model
|
|
65
|
+
|
|
66
|
+
`pick_model` returns a model id for the tier. By default these are Claude models on [Surplus](https://surplusllm.com), which serves every model behind one OpenAI-compatible key:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from openai import OpenAI
|
|
70
|
+
from switchboard_router import Router
|
|
71
|
+
|
|
72
|
+
router = Router()
|
|
73
|
+
llm = OpenAI(base_url="https://api.surplusllm.com/api/v1", api_key="sk-surplus-...")
|
|
74
|
+
|
|
75
|
+
prompt = "Write a Python function that reverses a string"
|
|
76
|
+
reply = llm.chat.completions.create(
|
|
77
|
+
model=router.pick_model(prompt),
|
|
78
|
+
messages=[{"role": "user", "content": prompt}],
|
|
79
|
+
)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Use your own models per tier (give all three, or the rest fall back to the defaults with a warning):
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
router = Router(models={"small": "my/small-model", "mid": "my/mid-model", "frontier": "my/frontier-model"})
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Backends
|
|
89
|
+
|
|
90
|
+
| Backend | Use it when | How |
|
|
91
|
+
|---|---|---|
|
|
92
|
+
| `ollama` | You run models locally | `Router(backend="ollama")` |
|
|
93
|
+
| `openai` | You serve the model with llama-server or vLLM, or call it on the Surplus API | `Router(backend="openai", base_url="http://localhost:8080/v1", backend_model="switchboard")` |
|
|
94
|
+
| `transformers` | You want it in-process | `pip install 'switchboard-router[local]'`, then `Router(backend="transformers")` |
|
|
95
|
+
|
|
96
|
+
`Router()` with no backend uses Ollama if it's running, then Transformers if it's installed, and otherwise tells you what to install.
|
|
97
|
+
|
|
98
|
+
## Failing safe
|
|
99
|
+
|
|
100
|
+
If the backend can't be reached, errors out, or the model's output isn't valid JSON, the decision is `frontier` with `valid=False` and the reason in `decision.error`. A failed routing call costs you money, never quality. With `fail_safe=False`, those cases raise instead. Empty or non-string prompts always raise `ValueError` or `TypeError`.
|
|
101
|
+
|
|
102
|
+
Requests time out after 15 seconds by default (`Router(timeout=5)` to change it), and redirects are not followed, so an API key is never sent to another host.
|
|
103
|
+
|
|
104
|
+
## Limits
|
|
105
|
+
|
|
106
|
+
- The router reads the first 2,000 characters of a prompt. A question at the very end of a long prompt may be missed.
|
|
107
|
+
- It reads the prompt it's given, so a prompt can try to talk it into a cheaper tier. Don't use it as a security boundary.
|
|
108
|
+
|
|
109
|
+
## How good is the routing?
|
|
110
|
+
|
|
111
|
+
Switchboard v0.1 on 10,000 held-out prompts: 64.5% cheaper than sending every prompt to Claude Opus 5.5, and 5.5% of prompts were sent to a cheaper tier than they needed. Method, limits and the full results are in the [model card](https://huggingface.co/switchboardllm/switchboard-router-0.5b). Try it in your browser: [Switchboard demo](https://huggingface.co/spaces/switchboardllm/switchboard).
|
|
112
|
+
|
|
113
|
+
## License
|
|
114
|
+
|
|
115
|
+
Apache-2.0.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
switchboard_router/__init__.py,sha256=d1LWJ9ERBYdNz38cZGqdz9KMqTgg7kcqwTBGJZyg5I4,516
|
|
2
|
+
switchboard_router/backends.py,sha256=6lI3CgkZQwvpYrnNudsmdA40dTuxB1jiJqTENgGsSos,8964
|
|
3
|
+
switchboard_router/cli.py,sha256=sfd7x2yMImjleF0hP2RcSy4gLTWtjMm2BwVxgZtf5d8,2341
|
|
4
|
+
switchboard_router/decision.py,sha256=9lfhEt6kZCXSoa53w6GJX8i-Xq7YBAJyB2YaX2lxlrA,1302
|
|
5
|
+
switchboard_router/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
switchboard_router/router.py,sha256=q6__NNI7hB_7juElaLyuff0yGOJvsQep7psP5FHetlA,3168
|
|
7
|
+
switchboard_router-0.1.0.dist-info/METADATA,sha256=ACmp0NIMQrw4xJcAtT1NNCjvO5hXGEMvJP-yN_K9wTk,4883
|
|
8
|
+
switchboard_router-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
9
|
+
switchboard_router-0.1.0.dist-info/entry_points.txt,sha256=RoQCRaAkT-1shO7vs-348Vtt6l9UhiaHeN6O_IK-brE,60
|
|
10
|
+
switchboard_router-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
11
|
+
switchboard_router-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|