basal-engine 3.0.3__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.
Files changed (111) hide show
  1. basal/__init__.py +7 -0
  2. basal/adapter.py +420 -0
  3. basal/adapters.py +8 -0
  4. basal/agree.py +393 -0
  5. basal/attach.py +160 -0
  6. basal/attn512.py +132 -0
  7. basal/auth.py +194 -0
  8. basal/bench.py +367 -0
  9. basal/blockquant.py +227 -0
  10. basal/calibrate.py +2198 -0
  11. basal/chat.py +175 -0
  12. basal/cli.py +70 -0
  13. basal/client.py +8 -0
  14. basal/decision_log.py +189 -0
  15. basal/decision_rules.py +569 -0
  16. basal/decisions.py +158 -0
  17. basal/derive.py +98 -0
  18. basal/disconnect.py +85 -0
  19. basal/engine.py +6023 -0
  20. basal/evidence.py +133 -0
  21. basal/examples/choice.jsonl +8 -0
  22. basal/examples/complex.jsonl +5 -0
  23. basal/examples/labelled_tickets.jsonl +500 -0
  24. basal/examples/local_backend.py +34 -0
  25. basal/examples/noul.jsonl +8 -0
  26. basal/examples/questions.jsonl +20 -0
  27. basal/examples/score.jsonl +8 -0
  28. basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
  29. basal/examples/selfcheck_basal-omni-pico.json +1 -0
  30. basal/examples/types_demo.py +74 -0
  31. basal/facts.py +497 -0
  32. basal/feedback.py +234 -0
  33. basal/file_identity.py +39 -0
  34. basal/finetune.py +321 -0
  35. basal/fit_decisions.py +944 -0
  36. basal/fla_configs.json +1822 -0
  37. basal/fold.py +206 -0
  38. basal/fonts/OFL-DMSans.txt +93 -0
  39. basal/fonts/OFL-SpaceGrotesk.txt +93 -0
  40. basal/fonts/dm-sans-latin-ext.woff2 +0 -0
  41. basal/fonts/dm-sans-latin.woff2 +0 -0
  42. basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
  43. basal/fonts/space-grotesk-latin.woff2 +0 -0
  44. basal/fp8block.py +100 -0
  45. basal/gdn_graph.py +1792 -0
  46. basal/gemma4.py +726 -0
  47. basal/gemma4_graph.py +931 -0
  48. basal/gguf_export.py +497 -0
  49. basal/identity.py +217 -0
  50. basal/int8block.py +50 -0
  51. basal/interpolate.py +330 -0
  52. basal/jsonl.py +172 -0
  53. basal/lean.py +204 -0
  54. basal/llama_attn.py +252 -0
  55. basal/llama_attn_kernels.py +266 -0
  56. basal/llama_graph.py +587 -0
  57. basal/llama_kernels.py +593 -0
  58. basal/loadtest.py +189 -0
  59. basal/mcp_server.py +432 -0
  60. basal/media.py +138 -0
  61. basal/metrics.py +16 -0
  62. basal/mlx_attn_kernels.py +1057 -0
  63. basal/mlx_forward.py +326 -0
  64. basal/mlx_kernels.py +543 -0
  65. basal/mlx_metal.py +510 -0
  66. basal/navcut.py +283 -0
  67. basal/navigate.py +646 -0
  68. basal/navtree.py +397 -0
  69. basal/nvfp4.py +245 -0
  70. basal/ordercheck.py +165 -0
  71. basal/pdf.py +183 -0
  72. basal/prepared.py +355 -0
  73. basal/presets.py +8 -0
  74. basal/prompt.py +462 -0
  75. basal/rank.py +373 -0
  76. basal/readout.py +121 -0
  77. basal/request.py +327 -0
  78. basal/response_cache.py +105 -0
  79. basal/router.py +1551 -0
  80. basal/router_ui.html +902 -0
  81. basal/router_ui.py +277 -0
  82. basal/run.py +376 -0
  83. basal/selfcheck.py +215 -0
  84. basal/server.py +5279 -0
  85. basal/sets.py +214 -0
  86. basal/signals.py +28 -0
  87. basal/state_disk.py +942 -0
  88. basal/strix.py +505 -0
  89. basal/synth.py +92 -0
  90. basal/tasks.py +848 -0
  91. basal/textio.py +21 -0
  92. basal/think.py +390 -0
  93. basal/tools.py +171 -0
  94. basal/tpu.py +336 -0
  95. basal/tpu_kernels.py +129 -0
  96. basal/trace.py +125 -0
  97. basal/ui.html +861 -0
  98. basal/ui.py +526 -0
  99. basal/varloop.py +813 -0
  100. basal/varloop_graph.py +1377 -0
  101. basal/varloop_kernels.py +907 -0
  102. basal/viz.html +660 -0
  103. basal/viz.py +375 -0
  104. basal/vllm_unified.py +100 -0
  105. basal_engine-3.0.3.dist-info/METADATA +416 -0
  106. basal_engine-3.0.3.dist-info/RECORD +111 -0
  107. basal_engine-3.0.3.dist-info/WHEEL +5 -0
  108. basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
  109. basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
  110. basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
  111. basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/router.py ADDED
@@ -0,0 +1,1551 @@
1
+ """basal-router (2.5): several basal-serve replicas (one per GPU) behind one HTTP endpoint.
2
+
3
+ A request goes to the replica its state is routed to, so the questions over one document meet the same replica's
4
+ state sharing (SOAM) and state cache: consistent hashing of the state's text over a ring of the ready replicas, with
5
+ bounded load (a replica already holding more than LOAD_FACTOR x the mean in-flight requests passes the request on
6
+ along the ring). Requests without a state go to the less loaded of two random replicas. Replicas are polled at
7
+ /health; one answering 503 (starting) or not answering gets no requests until it is ready again. With --gpus, the
8
+ router exits (status 1) when every replica it started has exited, and the replicas it started end with it: each runs
9
+ in its own process group, which the router ends when it stops (SIGTERM, SIGINT, SIGHUP, an error) and, on Linux, which
10
+ gets SIGTERM when the router is killed. With CUDA_VISIBLE_DEVICES set, --gpus gives indexes of the GPUs it lists (as
11
+ CUDA numbers them), and anything else is refused.
12
+
13
+ Off by default (the replicas' answers then pass through untouched):
14
+ --escalate URL ... --escalate-below P a cascade: questions whose top probability (calibrated, as the first replica
15
+ answers) is under P are asked again of the escalation replicas (a bigger
16
+ model); every answer says "answered_by": "first" or "escalated". Repeated,
17
+ the pairs are ordered levels: the first replica is level 1, the k-th
18
+ --escalate level k + 1, and a question goes on from level k to level k + 1
19
+ only while its top probability at level k is under the k-th
20
+ --escalate-below; every answer then also gives its "level" and "model" (as
21
+ that replica reports it). A level that is down or does not answer 200 leaves
22
+ the previous answers. Multi and task answers never escalate.
23
+ --blend URL ... --blend-weights W0 W1 ...
24
+ a blend: every question is also asked of each --blend pool (one model
25
+ each; repeat the flag), and a plain choice / noul / score answer gets the
26
+ weighted mean of the models' probabilities (W0 for --replicas, then one per
27
+ --blend, in order): choice, noul, score and confidence follow from it, and
28
+ the answer says "blend": {"models": [...], "weights": [...]} and
29
+ "calibrated": false (no model's thresholds hold for it: refit them on the
30
+ blend's output). A model that is down or does not answer 200 is left out
31
+ (the weights of the rest are used). Every question costs a call per model.
32
+ Multi, act, tool, task answers, questions with coverage / max_error /
33
+ evidence keep the first replica's answer. Not with --escalate.
34
+ --fallback URL --fallback-model NAME --fallback-below T
35
+ an LLM after the last level (or the single model): a plain choice question
36
+ whose top probability there is under T goes to an OpenAI-compatible chat
37
+ endpoint (URL: its base, e.g. http://127.0.0.1:8100/v1), with a prompt the
38
+ router builds from the document, the question and the options, and a JSON
39
+ schema that admits only the options' letters. Its answer says "answered_by":
40
+ "fallback", the "model", "calibrated": false, option probabilities from the
41
+ endpoint's logprobs (renormalised over the options; null without them) and
42
+ the basal answer it replaced. Greedy (temperature 0, seed 0), up to
43
+ --fallback-max-tokens (8192) tokens. Down, --fallback-timeout (60 s), an
44
+ answer that does not parse or is not an option: the basal answer stays.
45
+ Multi, task,
46
+ coverage / max_error / evidence questions and requests with media never go.
47
+ --fallback-extra JSON is merged into the chat request (e.g. a thinking
48
+ switch); BASAL_FALLBACK_API_KEY, if set, is sent as a bearer token.
49
+ --route SCRIPT=URL[,URL] requests whose state is mostly in that script (latin, cyrillic, greek,
50
+ arabic, hebrew, cjk) go to those replicas instead
51
+ --max-body-mb MB a request body over MB MiB (256, basal-serve's default) answers 413 before
52
+ the router reads it whole
53
+ --max-requests N decision requests in flight at the router at once (1,024 per replica of
54
+ --replicas / --gpus by default, basal-serve's own cap for each); one beyond
55
+ them answers 503 (code OVERLOADED, Retry-After: 1) before its body is read
56
+ --api-keys PATH the router checks a client's key itself (basal-serve's key file): 401
57
+ before anything else, every route but GET /health needs a key, and the key
58
+ still goes on to the replicas
59
+ --max-requests-per-key N with --api-keys: one key's requests in flight at once (default: no cap of
60
+ its own); one beyond them answers 503 OVERLOADED, so a key cannot take every
61
+ place of --max-requests
62
+ --state-holders on a state's later requests go to the least loaded replica that answered it,
63
+ within --load-factor (a state passed on once along the ring is no longer a
64
+ state-cache miss each time)
65
+ --prefix-affinity on a state that begins with one answered before (a growing agent trace or chat,
66
+ an edited document) goes to the replica that answered it, within
67
+ --load-factor: its state cache holds the beginning. Both options key a list
68
+ or object state by its JSON text, and remember only states answered (200)
69
+ --replica-timeout S a call to a replica that has not answered in S seconds ends: the client
70
+ gets 504 (a cascade level or a blend model that times out leaves the
71
+ previous answers, as one that is down). Off: no deadline, as a long rank
72
+ request may need; connecting to a replica is bounded by CONNECT_S (10 s)
73
+ either way
74
+
75
+ With --escalate, --blend or --fallback, the questions asked again go without their ask_if / depends_on, and ask_if is
76
+ applied to the final answers: a question whose gate a replaced answer fails is null (usage.skipped), and one whose
77
+ gate it now passes is asked of the first replica and goes through the same levels.
78
+
79
+ basal-router --replicas http://127.0.0.1:8001 http://127.0.0.1:8002 --port 8000
80
+ basal-router --gpus 0,1,2,3 --port 8000 -- --model Remek/basal-2.0-mini --mode fast (starts one basal-serve per
81
+ GPU on ports 8001..)
82
+ basal-router --replicas http://127.0.0.1:8001 --escalate http://127.0.0.1:8002 --escalate-below 0.8 \
83
+ --escalate http://127.0.0.1:8003 --escalate-below 0.9 (pico on 8001, mini on 8002, ultra on 8003)
84
+ basal-router --replicas http://127.0.0.1:8003 --blend http://127.0.0.1:8002 --blend http://127.0.0.1:8001 \
85
+ --blend-weights 0.6 0.2 0.2 (ultra first: answers that are not blended are its own)
86
+ GET /health: 200 when a replica of --replicas / --gpus (the pool of ordinary requests) is ready, else 503 (the ready
87
+ replicas of every pool in its "pools"); /metrics: per replica in flight, requests routed by
88
+ state / by load, failures, readiness, answers per cascade level, blended answers, fallback calls by result
89
+ (Prometheus); /v1/models and /v1/capabilities: the first ready replica's of that pool. --ui on: GET /ui, one live page of the router and every replica
90
+ (each replica's own panels when it runs with --ui on); GET /ui/state, its JSON.
91
+
92
+ Request ids: the client's X-Request-Id (or a req_<hex> the router makes when it has none or an invalid one) goes to
93
+ every replica the request reaches and comes back as the response's x-request-id, so the replicas' logs and the client
94
+ name one request alike.
95
+
96
+ API keys: a client's Authorization / X-API-Key header is passed on, as it came, to every replica its request reaches
97
+ (--replicas, --escalate, --blend, --route; never to --fallback), so replicas started with --api-keys (the same key file
98
+ on each) check it as if called directly. Without --api-keys of its own the router checks no key: its /health and
99
+ /metrics stay open. With it, the router answers 401 to a missing or unknown key before it reads the request, as
100
+ basal-serve does (GET /health stays open; GET /v1/keys needs an admin key).
101
+
102
+ POST /v1/decisions (OpenAI's Decisions API) goes to a replica of --replicas / --gpus routed by its input, and its
103
+ response comes back as the replica gave it: the cascade, blend and fallback apply to /v1/systemone and /v1/basal.
104
+ """
105
+ import argparse
106
+ import asyncio
107
+ import atexit
108
+ import bisect
109
+ import collections
110
+ import functools
111
+ import hashlib
112
+ import json
113
+ import math
114
+ import os
115
+ import random
116
+ import re
117
+ import signal
118
+ import subprocess
119
+ import sys
120
+ import time
121
+
122
+ from .metrics import prometheus
123
+ from .request import (MAX_BODY_BYTES, RequestError, error_object, is_multipart, limit_body, named_options, parse_body,
124
+ read_multipart, text_of)
125
+ from .trace import _f as fmt, routed, skipped as skip_trace
126
+
127
+ LOAD_FACTOR = 1.25
128
+ VNODES = 64
129
+ # --prefix-affinity (3.0): a state that begins with one answered before goes to the replica that answered it (its state
130
+ # cache holds that beginning, so a growing agent trace computes only its new tokens there). The routing key is read in
131
+ # BLOCK-character blocks, each hash chained to the ones before, so one block's hash stands for the whole beginning up to
132
+ # it; at most KEY_BLOCKS blocks of a key are hashed (its first MiB: the work per request is bounded) and at most
133
+ # KEY_ENTRIES of them recorded (blocks 1, 2, 4, 8, ... and the last), MAX_BLOCKS entries per pool, the least recently
134
+ # used dropped first
135
+ BLOCK = 256
136
+ KEY_BLOCKS = 4096
137
+ MAX_BLOCKS = 1 << 18
138
+ # --state-holders (3.0): per pool, the replicas that answered a state (HOLDERS states, the least recently used dropped
139
+ # first); its later requests go to the least loaded of them within the load bound
140
+ HOLDERS = 65536
141
+ ROUTED = ("state", "load") # how a request was routed (/metrics, the page); "held" and "prefix" with their options
142
+ POLL_S = 2.0
143
+ CONNECT_S = 10.0 # connecting to a replica (TCP): an unreachable host fails the call (502) instead of waiting forever
144
+ SERVE = [sys.executable, "-m", "basal.server"] # what --gpus starts per GPU (spawn)
145
+ MAX_REQUESTS = 1024 # --max-requests: per replica of the main pool by default (basal-serve's own --max-requests)
146
+ LIMITS = ("max_requests", "per_key") # what an OVERLOADED answer was refused by (/metrics)
147
+ DECIDING = ("/v1/systemone", "/v1/basal") # the routes whose questions may select a decision rule (experimental)
148
+ UNREAD = object() # a replica's decision rules that could not be read (Router.rules_of)
149
+
150
+
151
+ class Overloaded(RuntimeError):
152
+ """A request beyond --max-requests in flight at the router, or beyond --max-requests-per-key for its key: 503
153
+ OVERLOADED with Retry-After, before its body is read (a retry may succeed)."""
154
+
155
+ def __init__(self, message, limit):
156
+ super().__init__(message)
157
+ self.limit = limit
158
+
159
+
160
+ class Admitted:
161
+ """A request's place under the router's --max-requests (and its key's under --max-requests-per-key), from before
162
+ its body is read to its answer; release gives it back once."""
163
+
164
+ def __init__(self, router, key):
165
+ self.router, self.key, self.held = router, key, True
166
+ router.in_flight += 1
167
+ if key is not None:
168
+ router.by_key[key] = router.by_key.get(key, 0) + 1
169
+
170
+ def release(self):
171
+ if not self.held:
172
+ return
173
+ self.held = False
174
+ rt = self.router
175
+ rt.in_flight -= 1
176
+ if self.key is not None:
177
+ rt.by_key[self.key] -= 1
178
+ if not rt.by_key[self.key]:
179
+ del rt.by_key[self.key] # (a key with nothing in flight takes no memory)
180
+
181
+
182
+ def key_blocks(key):
183
+ """The chained hashes of the full BLOCK-character blocks of a routing key, at most KEY_BLOCKS of them: the i-th
184
+ stands for key[: BLOCK * (i + 1)]."""
185
+ out, h = [], b""
186
+ for i in range(BLOCK, min(len(key), BLOCK * KEY_BLOCKS) + 1, BLOCK):
187
+ h = hashlib.blake2b(h + key[i - BLOCK: i].encode("utf-8", "surrogatepass"), digest_size=8).digest()
188
+ out.append(h)
189
+ return out
190
+
191
+
192
+ def recorded(n):
193
+ """The indices of a key's n blocks that --prefix-affinity records: 0, 1, 3, 7, ... (blocks 1, 2, 4, 8, ...) and the
194
+ last, so a state adds at most KEY_ENTRIES entries however long it is, and a later state that begins with it finds
195
+ its last block."""
196
+ out, i = [], 1
197
+ while i <= n:
198
+ out.append(i - 1)
199
+ i *= 2
200
+ return out + ([n - 1] if n and n - 1 not in out else [])
201
+
202
+
203
+ KEY_ENTRIES = len(recorded(KEY_BLOCKS))
204
+
205
+
206
+ def chat_key(req):
207
+ """The routing key of a chat completion request (POST /v1/chat/completions, basal-serve --chat-classify on): its
208
+ last user message's text (the text parts of a list joined by line breaks), what basal/chat.py reads as the state,
209
+ whitespace normalised; None without one. So a chat request goes by its state, as /v1/decisions goes by its input."""
210
+ msgs = req.get("messages") if isinstance(req, dict) else None
211
+ users = [m for m in msgs if isinstance(m, dict) and m.get("role") == "user"] if isinstance(msgs, list) else []
212
+ content = users[-1].get("content") if users else None
213
+ if isinstance(content, list):
214
+ content = "\n".join(p["text"] for p in content if isinstance(p, dict) and p.get("type") == "text"
215
+ and isinstance(p.get("text"), str))
216
+ return (" ".join(content.split()) or None) if isinstance(content, str) else None
217
+
218
+
219
+ def structured_key(req):
220
+ """The routing key of a state given as a list or an object (chat messages, items): its JSON text as the model is
221
+ shown it (text_of), whitespace normalised; None otherwise. Used with --prefix-affinity or --state-holders only
222
+ (without them such a state goes by load, as before)."""
223
+ d = req if isinstance(req, dict) else None
224
+ state = d.get("state", d.get("input")) if d is not None else None
225
+ if not isinstance(state, (list, dict)):
226
+ return None
227
+ return " ".join(text_of(state).split()) or None
228
+
229
+
230
+ def state_key(body):
231
+ """The routing key of a request (its body, or the body as parse_body read it): its state (a /v1/decisions request:
232
+ its input) with whitespace normalised (None without one, or for a body that is not a JSON object)."""
233
+ d = parse_body(body) if isinstance(body, (bytes, str)) else body
234
+ state = d.get("state", d.get("input")) if isinstance(d, dict) else None
235
+ if not isinstance(state, str) or not state.strip():
236
+ return None
237
+ return re.sub(r"\s+", " ", state.strip())
238
+
239
+
240
+ SCRIPTS = ("latin", "cyrillic", "greek", "arabic", "hebrew", "cjk")
241
+
242
+
243
+ def script_of(text):
244
+ """The script most of the letters of text are in (SCRIPTS, or "other"; None without letters). A state that is not a
245
+ string is read as its JSON text, as basal-serve shows it to the model (keys too)."""
246
+ if text is not None and not isinstance(text, str):
247
+ text = text_of(text)
248
+ count = {}
249
+ for ch, n in collections.Counter(text or "").items(): # (each distinct character named once, in text order)
250
+ if ch.isalpha():
251
+ sc = _script(ch)
252
+ count[sc] = count.get(sc, 0) + n
253
+ return max(count, key=count.get) if count else None
254
+
255
+
256
+ @functools.lru_cache(maxsize=65536)
257
+ def _script(ch):
258
+ import unicodedata
259
+ name = unicodedata.name(ch, "")
260
+ sc = next((x for x in SCRIPTS[:5] if name.startswith(x.upper())), None)
261
+ return sc or ("cjk" if name.startswith(("CJK", "HIRAGANA", "KATAKANA", "HANGUL")) else "other")
262
+
263
+
264
+ def top_probability(answer):
265
+ """The top probability of an answer (its option probabilities), None for answers without one (multi, tasks)."""
266
+ p = answer.get("probabilities") if isinstance(answer, dict) else None
267
+ if answer.get("type") == "multi" or not isinstance(p, dict) or not p:
268
+ return None
269
+ return max(p.values())
270
+
271
+
272
+ BLENDS = ("choice", "noul", "score")
273
+ PLAIN = ("coverage", "max_error", "evidence", "multi") # question fields whose answers are not blended
274
+ CERTIFIED = ("abstain", "max_error", "answer_set", "coverage", "coverage_note", "calibration") # one model's calibration
275
+
276
+
277
+ def blendable(question, answer):
278
+ """A plain choice / noul / score answer (its option probabilities only) to a question without limits or evidence."""
279
+ return (isinstance(answer, dict) and answer.get("type") in BLENDS and isinstance(answer.get("probabilities"), dict)
280
+ and bool(answer["probabilities"]) and isinstance(question, dict) and not any(k in question for k in PLAIN))
281
+
282
+
283
+ def blend_answer(answer, members):
284
+ """answer (the first replica's) with the weighted mean of members' probabilities, [(weight, model, answer)] in
285
+ order: p[k] = sum(w * p_m[k]) / sum(w); choice / noul / score / confidence recomputed from p as basal-serve does.
286
+ The blend is not calibrated: "calibrated": false, and no field that rests on one model's calibration (CERTIFIED)."""
287
+ total = sum(w for w, _, _ in members)
288
+ p = {k: sum(w * a["probabilities"][k] for w, _, a in members) / total for k in answer["probabilities"]}
289
+ out = {k: v for k, v in answer.items() if k not in CERTIFIED}
290
+ out.update(probabilities=p, confidence=max(p.values()))
291
+ if answer["type"] == "choice":
292
+ out["choice"] = max(p, key=p.get)
293
+ elif answer["type"] == "noul":
294
+ out["noul"] = p["true"]
295
+ else:
296
+ out["score"] = float(sum(i * v for i, v in enumerate(p.values())))
297
+ out["blend"] = {"models": [m for _, m, _ in members], "weights": [w for w, _, _ in members]}
298
+ out["calibrated"] = False
299
+ return out
300
+
301
+
302
+ GATES = ("ask_if", "depends_on")
303
+
304
+
305
+ def selects_rule(req):
306
+ """Whether a request's questions select a decision rule (a question with "decision_rule")."""
307
+ qs = req.get("questions") if isinstance(req, dict) else None
308
+ return isinstance(qs, dict) and any(isinstance(q, dict) and "decision_rule" in q for q in qs.values())
309
+
310
+
311
+ def request_part(body, content_type):
312
+ """The JSON request of a multipart/form-data body (its "request" part, as parse_body reads it; its media parts are
313
+ not read), None when it has none or is no such body (the replica answers it)."""
314
+ if not is_multipart(content_type):
315
+ return None
316
+ try:
317
+ parts = read_multipart(body, content_type)
318
+ except RequestError:
319
+ return None
320
+ return next((parse_body(data) for name, _, data in parts if name == "request"), None)
321
+
322
+
323
+ def traces_of(resp):
324
+ """The response's "trace" by question name (a request with "trace": true), else None: the router keeps it with the
325
+ answers, so a question whose answer it replaces gets the trace of its new answer."""
326
+ t = resp.get("trace") if isinstance(resp, dict) else None
327
+ return t if isinstance(t, dict) else None
328
+
329
+
330
+ def failed(answer):
331
+ """An answer that is a question's error ({"error", "code"}: basal-serve's "errors": "per_question")."""
332
+ return isinstance(answer, dict) and "error" in answer and "type" not in answer
333
+
334
+
335
+ def ungated(questions, names):
336
+ """The named questions of a request without ask_if / depends_on: what a cascade level or a blend model is asked
337
+ again (the questions a gate names may not be among them; the router applies the gates to the final answers)."""
338
+ return {q: {k: v for k, v in questions[q].items() if k not in GATES} if isinstance(questions[q], dict)
339
+ else questions[q] for q in names}
340
+
341
+
342
+ def gate_order(questions):
343
+ """[(name, ask_if)] of the questions with an ask_if, each after every question its ask_if names; [] without gates
344
+ or when they do not form an order (the replica that answered the request checked them)."""
345
+ gates = {n: q["ask_if"] for n, q in questions.items() if isinstance(q, dict) and isinstance(q.get("ask_if"), dict)
346
+ and q["ask_if"]}
347
+ order, done = [], set()
348
+ while len(order) < len(gates):
349
+ ready = [n for n in gates if n not in done and all(x in done or x not in gates for x in gates[n])]
350
+ if not ready:
351
+ return []
352
+ done.update(ready)
353
+ order += [(n, gates[n]) for n in ready]
354
+ return order
355
+
356
+
357
+ def answer_key(answer):
358
+ """The canonical answer of a choice / noul / score answer, as basal-serve's ask_if reads it: the choice, "true" /
359
+ "false" (true on a tie), the top score level, the decision rule's key of an answer with a "decision"; None for
360
+ another answer or none."""
361
+ if not isinstance(answer, dict):
362
+ return None
363
+ if isinstance(answer.get("decision"), dict) and isinstance(answer["decision"].get("key"), str):
364
+ return answer["decision"]["key"]
365
+ t, p = answer.get("type"), answer.get("probabilities")
366
+ if t == "choice":
367
+ return answer.get("choice")
368
+ if t == "noul":
369
+ if isinstance(p, dict) and "true" in p and "false" in p:
370
+ return "true" if p["true"] >= p["false"] else "false"
371
+ return None if answer.get("noul") is None else "true" if answer["noul"] >= 0.5 else "false"
372
+ if t == "score" and isinstance(p, dict) and p:
373
+ return max(p, key=p.get)
374
+ return None
375
+
376
+
377
+ def gates_pass(answers, ask):
378
+ """Whether every question an ask_if names has an answer among its values (yes / no / booleans of a noul question, a
379
+ score level's key or its text, as basal-serve reads them)."""
380
+ for x, vals in ask.items():
381
+ a = answers.get(x)
382
+ key = answer_key(a)
383
+ if key is None or not isinstance(vals, list):
384
+ return False
385
+ legend = a.get("legend") if isinstance(a.get("legend"), dict) else {}
386
+ text = {t: k for k, t in legend.items() if t not in legend}
387
+ ok = set()
388
+ for v in vals:
389
+ v = ("true" if v else "false") if isinstance(v, bool) else v
390
+ if a.get("type") == "noul":
391
+ v = {"yes": "true", "no": "false"}.get(v, v)
392
+ elif a.get("type") == "score" and v not in legend:
393
+ v = text.get(v, v)
394
+ ok.add(v)
395
+ if key not in ok:
396
+ return False
397
+ return True
398
+
399
+
400
+ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
401
+ FALLBACK_RESULTS = ("answered", "error", "timeout", "unparseable", "not_an_option")
402
+ RETRY_MIN_S = 1.0 # a fallback call is retried (once) only with at least this much of --fallback-timeout left
403
+ FALLBACK_SYSTEM = ("You answer a question about a document. Read the document, then pick the one option that answers "
404
+ 'the question. Reply with JSON only: {"answer": "<the letter of the option>"}.')
405
+
406
+
407
+ def fallback_options(question, answer):
408
+ """[(key, text)] of a plain choice question in the answer's order, the texts as basal-serve shows them to the model
409
+ (option_keys); None when the question does not go to the fallback (another type, limits, evidence, multi, keys
410
+ that do not match the answer's, fewer than 2 or more than 26 options)."""
411
+ if not (isinstance(answer, dict) and answer.get("type") == "choice" and isinstance(answer.get("probabilities"), dict)
412
+ and isinstance(question, dict) and question.get("type", "choice") == "choice"
413
+ and not any(k in question for k in PLAIN)):
414
+ return None
415
+ crit = question.get("criteria") or {}
416
+ if isinstance(crit, list):
417
+ crit = {k: None for k in crit}
418
+ if not isinstance(crit, dict) or [str(k) for k in crit] != list(answer["probabilities"]) or not 2 <= len(crit) <= 26:
419
+ return None
420
+ keys, texts = named_options(crit, "hide" if question.get("option_keys") == "hide" else "show")
421
+ return [(str(k), t) for k, t in zip(keys, texts)]
422
+
423
+
424
+ def fallback_messages(state, question, options):
425
+ """The chat messages for the fallback: the document, the question and the options as lettered lines."""
426
+ q = question.get("instructions")
427
+ lines = "\n".join(f"{LETTERS[i]}. {t}" for i, (_, t) in enumerate(options))
428
+ user = (f"Document:\n{text_of(state)}\n\nQuestion:\n{text_of(q) if q else 'Which option fits the document?'}\n\n"
429
+ f"Options:\n{lines}")
430
+ return [{"role": "system", "content": FALLBACK_SYSTEM}, {"role": "user", "content": user}]
431
+
432
+
433
+ def fallback_request(model, messages, n, extra=None, max_tokens=8192, seed=0):
434
+ """The chat completion request: greedy (temperature 0, a fixed seed), a token budget with room for a model's
435
+ thinking, logprobs, and a JSON schema that admits only the n options' letters; extra merged last."""
436
+ schema = {"type": "object", "properties": {"answer": {"type": "string", "enum": list(LETTERS[:n])}},
437
+ "required": ["answer"], "additionalProperties": False}
438
+ body = {"model": model, "messages": messages, "temperature": 0, "seed": seed, "max_tokens": max_tokens,
439
+ "logprobs": True, "top_logprobs": 20,
440
+ "response_format": {"type": "json_schema", "json_schema": {"name": "answer", "strict": True, "schema": schema}}}
441
+ body.update(extra or {})
442
+ return body
443
+
444
+
445
+ def _letter_probs(entries, letter, n):
446
+ """Probabilities of the n letters at the token that carries the answer's letter (the last '"answer": "' of the
447
+ output), from its top logprobs renormalised over the letters (letters not among them: 0); None if not found."""
448
+ toks = [(e.get("token") or "") if isinstance(e, dict) else "" for e in entries]
449
+ text = "".join(toks)
450
+ hits = list(re.finditer(r'"answer"\s*:\s*"', text))
451
+ if not hits:
452
+ return None
453
+ v, pos = hits[-1].end(), 0
454
+ for i, t in enumerate(toks):
455
+ if pos <= v < pos + len(t):
456
+ break
457
+ pos += len(t)
458
+ else:
459
+ return None
460
+ pre, chosen = text[pos:v], toks[i]
461
+ if chosen[len(pre):len(pre) + 1] != letter or not isinstance(entries[i], dict):
462
+ return None
463
+ rest = chosen[len(pre) + 1:]
464
+ lp = {letter: entries[i].get("logprob")}
465
+ for alt in entries[i].get("top_logprobs") or []:
466
+ t = alt.get("token") or ""
467
+ c = t[len(pre):len(pre) + 1]
468
+ if t.startswith(pre) and c and c in LETTERS[:n] and t[len(pre) + 1:] == rest and alt.get("logprob") is not None:
469
+ lp[c] = max(lp.get(c) if lp.get(c) is not None else -math.inf, alt["logprob"])
470
+ lp = {c: x for c, x in lp.items() if isinstance(x, (int, float)) and math.isfinite(x)} # (a masked letter: -inf)
471
+ if letter not in lp:
472
+ return None
473
+ top = max(lp.values())
474
+ ex = {c: math.exp(x - top) for c, x in lp.items()}
475
+ total = sum(ex.values())
476
+ return [ex.get(c, 0.0) / total for c in LETTERS[:n]]
477
+
478
+
479
+ def fallback_parse(data, n):
480
+ """A chat completion -> (option index or None, probabilities or None, result): strict, the content must be
481
+ exactly {"answer": "<one of the n letters>"}."""
482
+ try:
483
+ choice = data["choices"][0]
484
+ content = choice["message"]["content"]
485
+ ans = json.loads(content)
486
+ except (KeyError, IndexError, TypeError, ValueError):
487
+ return None, None, "unparseable"
488
+ if not isinstance(ans, dict) or set(ans) != {"answer"} or not isinstance(ans["answer"], str):
489
+ return None, None, "unparseable"
490
+ if len(ans["answer"]) != 1 or ans["answer"] not in LETTERS[:n]:
491
+ return None, None, "not_an_option"
492
+ entries = ((choice.get("logprobs") or {}).get("content") or []) if isinstance(choice, dict) else []
493
+ return LETTERS.index(ans["answer"]), _letter_probs(entries, ans["answer"], n) if entries else None, "answered"
494
+
495
+
496
+ KEY_HEADERS = ("authorization", "x-api-key") # a client's API key, as basal-serve --api-keys reads it
497
+
498
+
499
+ def key_headers(raw):
500
+ """The client's API key headers among raw ASGI headers, values as bytes, the last of each name (as basal-serve
501
+ reads them): passed on to the replicas, never to the --fallback LLM. {} without them."""
502
+ return {k: v.strip() for k, v in ((n.decode("latin1").lower(), v) for n, v in raw) if k in KEY_HEADERS}
503
+
504
+
505
+ def _h(text):
506
+ # (surrogatepass: a state with a lone surrogate, "\ud800" in its JSON, still has a key; the replica refuses it)
507
+ return int.from_bytes(hashlib.sha256(text.encode("utf-8", "surrogatepass")).digest()[:8], "big")
508
+
509
+
510
+ class Ring:
511
+ """Consistent hashing with bounded load over replica names (VNODES points per replica)."""
512
+
513
+ def __init__(self, names, vnodes=VNODES):
514
+ self.points = sorted((_h(f"{n}#{v}"), n) for n in names for v in range(vnodes))
515
+ self.keys = [p[0] for p in self.points]
516
+
517
+ def pick(self, key, load, ready, factor=LOAD_FACTOR):
518
+ """The replica for key: the first ready one clockwise from hash(key) whose load stays within factor x the
519
+ mean load (counting this request); None when no replica is ready."""
520
+ names = [n for n in dict.fromkeys(n for _, n in self.points) if n in ready]
521
+ if not names:
522
+ return None
523
+ cap = math.ceil(factor * (sum(load.get(n, 0) for n in names) + 1) / len(names)) # (at least 1)
524
+ i = bisect.bisect(self.keys, _h(key)) % len(self.points)
525
+ seen = set()
526
+ for j in range(len(self.points)):
527
+ n = self.points[(i + j) % len(self.points)][1]
528
+ if n in ready and n not in seen:
529
+ seen.add(n)
530
+ if load.get(n, 0) + 1 <= cap:
531
+ return n
532
+ return min(names, key=lambda n: load.get(n, 0))
533
+
534
+
535
+ class Router:
536
+ def __init__(self, replicas, transport=None, factor=LOAD_FACTOR, seed=0, escalate=(), below=0.0, routes=None,
537
+ levels=None, blend=None, blend_weight=1.0, fallback=None, timeout=None, max_requests=None,
538
+ max_per_key=None, prefix_affinity=False, state_holders=False):
539
+ """escalate, below: one cascade level; levels: [(URLs, threshold), ...] for levels 2, 3, ... instead;
540
+ blend: [(URLs, weight), ...] asked beside the replicas (weight blend_weight); fallback: {url, model, below,
541
+ timeout, extra} of the LLM after the last level; timeout: seconds of a replica call (--replica-timeout,
542
+ None: no deadline); max_requests: decision requests in flight at once (--max-requests; None: MAX_REQUESTS
543
+ per replica of replicas); max_per_key: one API key's (--max-requests-per-key; None: no cap of its own);
544
+ prefix_affinity, state_holders: --prefix-affinity, --state-holders (off: routed as before 3.0)."""
545
+ import httpx
546
+ self.max_requests = MAX_REQUESTS * max(1, len(replicas)) if max_requests is None else max_requests
547
+ self.max_per_key = max_per_key
548
+ self.in_flight, self.by_key = 0, {} # decision requests the router holds, and per API key name
549
+ self.overloaded = dict.fromkeys(LIMITS, 0)
550
+ levels = [(list(u), b) for u, b in (levels if levels is not None else [(escalate, below)]) if u]
551
+ self.levels = [(f"level:{k}", b) for k, (_, b) in enumerate(levels, start=2)] # (level k's pool, k - 1's threshold)
552
+ blend = [(list(u), w) for u, w in (blend or []) if u]
553
+ self.blends = [(f"blend:{k}", w) for k, (_, w) in enumerate(blend, start=2)]
554
+ self.blend_weight = blend_weight
555
+ self.blended = {}
556
+ self.fallback = fallback
557
+ self.fallback_counts = {k: 0 for k in FALLBACK_RESULTS}
558
+ self.pools = {"main": list(replicas), **{f"level:{k}": u for k, (u, _) in enumerate(levels, start=2)},
559
+ **{f"blend:{k}": u for k, (u, _) in enumerate(blend, start=2)},
560
+ **{f"script:{k}": list(v) for k, v in (routes or {}).items()}}
561
+ self.replicas = list(dict.fromkeys(u for urls in self.pools.values() for u in urls))
562
+ self.rings = {name: Ring(urls) for name, urls in self.pools.items() if urls}
563
+ self.ring = self.rings.get("main")
564
+ self.answered = {"first": 0, "escalated": 0}
565
+ self.by_level = {k: 0 for k in range(1, len(self.levels) + 2)}
566
+ self.scripts = {}
567
+ self.ready = set()
568
+ self.load = {r: 0 for r in self.replicas}
569
+ # a replica's GET /v1/models "decision_rules" (None: no file) with the readiness generation it was read in,
570
+ # read when a request that selects a rule first needs it; a replica's generation changes every time it leaves
571
+ # or joins the ready ones (a failed call or poll, a restart that may load another file), which forgets it
572
+ self.rules, self.gen = {}, {r: 0 for r in self.replicas}
573
+ self.prefix, self.holding = bool(prefix_affinity), bool(state_holders)
574
+ self.hows = ROUTED + (("held",) if self.holding else ()) + (("prefix",) if self.prefix else ())
575
+ self.routed = {(r, how): 0 for r in self.replicas for how in self.hows}
576
+ self.blocks = {} # pool -> OrderedDict(block hash -> the replica that last answered a state with that beginning)
577
+ self.holders = collections.OrderedDict() # (pool, hash of a state) -> the replicas that answered it, in order
578
+ self.failed = {r: 0 for r in self.replicas}
579
+ self.factor = factor
580
+ self.rng = random.Random(seed)
581
+ self.dead = False
582
+ self.timeout = timeout
583
+ self.client = httpx.AsyncClient(
584
+ timeout=httpx.Timeout(timeout, connect=CONNECT_S if timeout is None else min(CONNECT_S, timeout)),
585
+ transport=transport, limits=httpx.Limits(max_connections=None, max_keepalive_connections=256))
586
+
587
+ def admit(self, key=None):
588
+ """A decision request's place (Admitted), or Overloaded: --max-requests in flight at the router, or key (the
589
+ name of the API key the router checked; None without --api-keys) at --max-requests-per-key."""
590
+ if self.in_flight >= self.max_requests:
591
+ self.overloaded["max_requests"] += 1
592
+ raise Overloaded(f"this router has {self.in_flight} requests in flight, the most it takes at once "
593
+ f"(--max-requests {self.max_requests}); retry later", "max_requests")
594
+ if key is not None and self.max_per_key is not None and self.by_key.get(key, 0) >= self.max_per_key:
595
+ self.overloaded["per_key"] += 1
596
+ raise Overloaded(f"this API key has {self.by_key[key]} requests in flight at this router, the most one key "
597
+ f"takes at once (--max-requests-per-key {self.max_per_key}); retry later", "per_key")
598
+ return Admitted(self, key)
599
+
600
+ def choose(self, key, pool="main", hs=None, only=None):
601
+ """(replica, how) for a request with routing key key (None: by load), among the replicas of pool (and of
602
+ `only`, when given): with --state-holders the least loaded replica that answered the same state ("held"), with
603
+ --prefix-affinity the one that answered the longest beginning of it ("prefix"), each within the load bound;
604
+ else the ring's ("state"). hs: key_blocks(key), when the caller has them."""
605
+ ready = self.ready if only is None else self.ready & set(only)
606
+ if key is not None:
607
+ if self.holding:
608
+ r = self._held(key, pool)
609
+ if r is not None and r in ready:
610
+ return r, "held"
611
+ if self.prefix:
612
+ r = self._prefix(key_blocks(key) if hs is None else hs, pool, len(key))
613
+ if r is not None and r in ready:
614
+ return r, "prefix"
615
+ r = self.rings[pool].pick(key, self.load, ready, self.factor)
616
+ return r, "state"
617
+ ready = sorted(ready & set(self.pools[pool]))
618
+ if not ready:
619
+ return None, "load"
620
+ a, b = self.rng.choice(ready), self.rng.choice(ready)
621
+ return (a if self.load[a] <= self.load[b] else b), "load"
622
+
623
+ def _cap(self, pool):
624
+ """The load bound: a replica takes a request while it holds at most factor x the mean in flight over the ready
625
+ replicas of pool, counting this request (the ring's bound, Ring.pick)."""
626
+ names = [n for n in self.pools[pool] if n in self.ready]
627
+ return math.ceil(self.factor * (sum(self.load.get(n, 0) for n in names) + 1) / len(names)) if names else 0
628
+
629
+ def _held(self, key, pool):
630
+ """--state-holders: the least loaded ready replica that answered this state, within the load bound (the first
631
+ that answered it on a tie); None without one."""
632
+ held = self.holders.get((pool, _h(key)))
633
+ cap = self._cap(pool) if held else 0
634
+ fit = [r for r in held or () if r in self.ready and self.load.get(r, 0) + 1 <= cap]
635
+ return min(fit, key=lambda r: self.load.get(r, 0)) if fit else None
636
+
637
+ def _prefix(self, hs, pool, n):
638
+ """--prefix-affinity: the replica that last answered the longest recorded beginning of a key of n characters
639
+ (whole blocks; the first MiB of a longer key), when that beginning is at least as long as the rest (a shared
640
+ letterhead does not pin unrelated documents), the replica is ready and within the load bound; else None."""
641
+ idx = self.blocks.get(pool)
642
+ if not idx or not hs:
643
+ return None
644
+ for i in range(len(hs) - 1, -1, -1): # (the deepest recorded block: it stands for the whole beginning)
645
+ r = idx.get(hs[i])
646
+ if r is not None:
647
+ m = (i + 1) * BLOCK
648
+ ok = m >= min(n, BLOCK * KEY_BLOCKS) - m and r in self.ready and self.load.get(r, 0) + 1 <= self._cap(pool)
649
+ return r if ok else None
650
+ return None
651
+
652
+ def _remember(self, key, hs, pool, r):
653
+ """A state replica r answered (200: it read, and may cache, it): --state-holders adds r to its holders,
654
+ --prefix-affinity records its blocks for r. A request refused or failed records nothing."""
655
+ if self.holding:
656
+ k = (pool, _h(key))
657
+ held = self.holders.pop(k, [])
658
+ if r not in held:
659
+ held.append(r)
660
+ self.holders[k] = held # (the most recently used last)
661
+ while len(self.holders) > HOLDERS:
662
+ self.holders.popitem(last=False)
663
+ if self.prefix and hs:
664
+ idx = self.blocks.setdefault(pool, collections.OrderedDict())
665
+ for i in recorded(len(hs)):
666
+ idx[hs[i]] = r
667
+ idx.move_to_end(hs[i])
668
+ while len(idx) > MAX_BLOCKS:
669
+ idx.popitem(last=False)
670
+
671
+ async def poll(self):
672
+ """Readiness of every replica (GET /health: 200 = ready)."""
673
+ async def one(r):
674
+ try:
675
+ ok = (await self.client.get(r + "/health", timeout=5)).status_code == 200
676
+ except Exception: # noqa: BLE001 (down or still binding)
677
+ ok = False
678
+ (self.set_ready if ok else self.set_unready)(r)
679
+ await asyncio.gather(*(one(r) for r in self.replicas))
680
+
681
+ async def forward(self, path, body, headers):
682
+ """-> (status, content, content type): the request to the replica its pool and state give, then (--escalate)
683
+ its low-confidence questions to the escalation replicas."""
684
+ req = parse_body(body) # read once (None: not a request the replicas take; the replica answers it)
685
+ key = state_key(req) # (every call of the request goes by its state: the sub-requests keep it)
686
+ if path == "/v1/chat/completions": # (its state: the last user message, as basal/chat.py reads it)
687
+ key = chat_key(req)
688
+ if key is None and (self.prefix or self.holding): # (a list / object state: by its JSON text then)
689
+ key = structured_key(req)
690
+ if path in ("/v1/decisions", "/v1/chat/completions"): # as it is (OpenAI's shapes: the cascade, blend and
691
+ # fallback read basal answers)
692
+ return await self._send("main", path, body, headers, key)
693
+ only = None # (a request that selects a decision rule: the replicas whose rules were read for it)
694
+ selecting = path in DECIDING and selects_rule(req if req is not None else
695
+ request_part(body, headers.get("content-type")))
696
+ if selecting:
697
+ why, only = await self.rules_refused(headers)
698
+ if why is not None:
699
+ code, message = why
700
+ out = dict(error_object(path, 422, message, "INVALID_REQUEST"), decision_rules_code=code)
701
+ return 422, json.dumps(out).encode(), "application/json"
702
+ if is_multipart(headers.get("content-type")) and (self.levels or self.blends or self.fallback
703
+ or getattr(self, "certificate", None) is not None or any(k.startswith("script:") for k in self.rings)):
704
+ why = "multipart cannot be evaluated under the configured router policy; send JSON with inline media"
705
+ return 422, json.dumps(error_object(path, 422, why, "INVALID_REQUEST")).encode(), "application/json"
706
+ pool = "main"
707
+ if any(name.startswith("script:") for name in self.rings): # --route
708
+ sc = script_of(req.get("state")) if req is not None else None
709
+ if sc is not None:
710
+ self.scripts[sc] = self.scripts.get(sc, 0) + 1
711
+ pool = f"script:{sc}" if f"script:{sc}" in self.rings else pool
712
+ status, content, ctype = await self._send(pool, path, body, headers, key, only)
713
+ if status == 200 and req is not None and (self.levels or self.blends or self.fallback):
714
+ content = await self._stages(path, req, content, headers, key)
715
+ if b'"ask_if"' in body:
716
+ status, content, ctype = await self._gates(pool, path, req, content, headers, key, ctype)
717
+ return status, content, ctype
718
+
719
+ async def _stages(self, path, req, content, headers, key):
720
+ """The first replica's response (content) to the request req (parse_body) through the cascade, the blend and
721
+ the fallback."""
722
+ level = {}
723
+ if self.levels:
724
+ content = await self._cascade(path, req, content, headers, key, level)
725
+ if self.blends:
726
+ content = await self._blend(path, req, content, headers, key)
727
+ if self.fallback:
728
+ content = await self._fallback(req, content, level if self.levels else None)
729
+ return content
730
+
731
+ async def _gates(self, pool, path, req, content, headers, key, ctype="application/json"):
732
+ """ask_if over the final answers: the replica skipped questions by its own answers, which a cascade level, a
733
+ blend or the fallback may have replaced. In the gates' order, a question whose gate now fails is null; the ones
734
+ it now passes that were skipped are asked (without their gates, through the same stages), and the questions
735
+ gated on them are decided after their answers. usage.skipped names the null ones. -> (status, content, content
736
+ type): a call asking them that fails fails the request with its status and error, as basal-serve fails a
737
+ request one of whose engine calls fails (the question was not answered; null would say its condition failed)."""
738
+ try:
739
+ resp = json.loads(content)
740
+ qs, answers = req["questions"], resp["answers"]
741
+ order = gate_order(qs)
742
+ except (ValueError, KeyError, TypeError, AttributeError):
743
+ return 200, content, ctype
744
+ if not order or not isinstance(answers, dict):
745
+ return 200, content, ctype
746
+ tried, traces = set(), traces_of(resp)
747
+ for _ in range(len(order) + 1):
748
+ todo, open_ = [], set() # (open: asked now, or gated on a question that is)
749
+ for name, ask in order:
750
+ if failed(answers.get(name)): # ("errors": "per_question": the replica's error stays the answer)
751
+ continue
752
+ if any(x in open_ for x in ask):
753
+ open_.add(name)
754
+ elif not gates_pass(answers, ask):
755
+ answers[name] = None
756
+ if traces is not None:
757
+ traces[name] = skip_trace(qs[name])
758
+ elif answers.get(name) is None and name not in tried:
759
+ todo.append(name)
760
+ open_.add(name)
761
+ if not todo:
762
+ break
763
+ tried.update(todo)
764
+ sub = dict(req, questions=ungated(qs, todo))
765
+ st, c2, ct2 = await self._send(pool, path, json.dumps(sub).encode(), headers, key)
766
+ if st != 200:
767
+ return st, c2, ct2
768
+ try:
769
+ r2 = json.loads(await self._stages(path, sub, c2, headers, key))
770
+ except ValueError:
771
+ continue
772
+ for q in todo:
773
+ answers[q] = (r2.get("answers") or {}).get(q)
774
+ if traces is not None: # (its own trace: it was asked, through the stages, as the others were)
775
+ t2 = (traces_of(r2) or {}).get(q)
776
+ traces[q] = t2 if isinstance(t2, dict) else skip_trace(qs[q]) if answers[q] is None else routed(
777
+ answers[q], "asked once the router applied its ask_if to the final answers")
778
+ for k in ("cascade", "fallback"): # what the stages did to them
779
+ if isinstance(r2.get(k), dict) and k not in resp:
780
+ resp[k] = r2[k]
781
+ elif isinstance(r2.get(k), dict) and isinstance(resp.get(k), dict):
782
+ for f in ("escalated", "asked", "answered"):
783
+ if isinstance(r2[k].get(f), list) and isinstance(resp[k].get(f), list):
784
+ resp[k][f] += r2[k][f]
785
+ skipped = [name for name, _ in order if answers.get(name) is None]
786
+ usage = resp.setdefault("usage", {})
787
+ if isinstance(usage, dict):
788
+ if skipped:
789
+ usage["skipped"] = skipped
790
+ else:
791
+ usage.pop("skipped", None)
792
+ return 200, json.dumps(resp, ensure_ascii=False).encode(), ctype
793
+
794
+ async def _fallback(self, req, content, level=None):
795
+ """The answers of the last level (level: the cascade's level of each question; None: one model) whose top
796
+ probability is under --fallback-below asked of the LLM, concurrently; its answer replaces the basal one."""
797
+ try:
798
+ resp = json.loads(content)
799
+ answers = resp["answers"]
800
+ qs = req.get("questions") or {}
801
+ if req.get("media") is not None or req.get("images") is not None: # (images: the alias of media)
802
+ return content
803
+ go = []
804
+ for q, a in answers.items():
805
+ opts = fallback_options(qs.get(q), a) if q in qs else None
806
+ if opts and (level is None or level.get(q) == len(self.levels) + 1) \
807
+ and top_probability(a) < self.fallback["below"]:
808
+ go.append((q, a, opts))
809
+ except (ValueError, KeyError, TypeError, AttributeError):
810
+ return content
811
+ if not go:
812
+ return content
813
+ res = await asyncio.gather(*(self._ask_fallback(req.get("state"), qs[q], opts) for q, _, opts in go))
814
+ answered = []
815
+ for (q, a, opts), (i, probs, result, model) in zip(go, res):
816
+ self.fallback_counts[result] += 1
817
+ if i is None:
818
+ continue
819
+ keys = [k for k, _ in opts]
820
+ p = None if probs is None else dict(zip(keys, probs))
821
+ if traces_of(resp) is not None:
822
+ resp["trace"][q] = routed({"choice": keys[i], "probabilities": p}, (
823
+ f"basal's top probability {top_probability(a):.4f} is below --fallback-below "
824
+ f"{self.fallback['below']:g}: the fallback LLM ({model}) answered {keys[i]!r}, not calibrated"), keys)
825
+ answers[q] = {"type": "choice", "choice": keys[i], "probabilities": p,
826
+ "confidence": None if p is None else max(p.values()), "answered_by": "fallback",
827
+ "model": model, "calibrated": False,
828
+ "basal": {"choice": a.get("choice"), "confidence": top_probability(a),
829
+ "model": a.get("model", resp.get("model"))}}
830
+ answered.append(q)
831
+ resp["fallback"] = {"below": self.fallback["below"], "asked": [q for q, _, _ in go], "answered": answered}
832
+ return json.dumps(resp, ensure_ascii=False).encode()
833
+
834
+ async def _ask_fallback(self, state, question, options):
835
+ """-> (option index or None, probabilities or None, result, model) of one fallback call."""
836
+ import httpx
837
+ f = self.fallback
838
+ body = fallback_request(f["model"], fallback_messages(state, question, options), len(options), f.get("extra"),
839
+ f.get("max_tokens", 8192))
840
+ headers = {"content-type": "application/json"}
841
+ if os.environ.get("BASAL_FALLBACK_API_KEY"):
842
+ headers["authorization"] = "Bearer " + os.environ["BASAL_FALLBACK_API_KEY"]
843
+ deadline = time.monotonic() + f.get("timeout", 60.0) # (both attempts together)
844
+ for attempt in (0, 1):
845
+ left = deadline - time.monotonic()
846
+ try:
847
+ r = await asyncio.wait_for(self.client.post(
848
+ f["url"].rstrip("/") + "/chat/completions", content=json.dumps(body).encode(), headers=headers,
849
+ timeout=left), left)
850
+ break
851
+ except (httpx.TimeoutException, asyncio.TimeoutError):
852
+ return None, None, "timeout", None
853
+ except (httpx.ReadError, httpx.WriteError, httpx.RemoteProtocolError):
854
+ # once more, in the time left (at least RETRY_MIN_S): a pooled connection the endpoint closed as it
855
+ # was reused, at its keep-alive
856
+ if attempt or deadline - time.monotonic() < RETRY_MIN_S:
857
+ return None, None, "error", None
858
+ except Exception: # noqa: BLE001 (down, refused)
859
+ return None, None, "error", None
860
+ if r.status_code != 200:
861
+ return None, None, "error", None
862
+ try:
863
+ data = r.json()
864
+ except ValueError:
865
+ return None, None, "unparseable", None
866
+ i, probs, result = fallback_parse(data, len(options))
867
+ return i, probs, result, (data.get("model") if isinstance(data, dict) else None) or f["model"]
868
+
869
+ async def _blend(self, path, req, content, headers, key):
870
+ """The first replica's answers, the blendable ones mixed with the --blend pools' (asked at once, concurrently)."""
871
+ try:
872
+ resp = json.loads(content)
873
+ answers = resp["answers"]
874
+ qs = req.get("questions") or {}
875
+ want = [q for q, a in answers.items() if q in qs and blendable(qs[q], a)]
876
+ except (ValueError, KeyError, TypeError, AttributeError):
877
+ return content
878
+ if not want:
879
+ return content
880
+ sub = json.dumps(dict(req, questions=ungated(qs, want))).encode()
881
+ outs = await asyncio.gather(*(self._send(pool, path, sub, headers, key) for pool, _ in self.blends))
882
+ others = []
883
+ for (_, w), (st, c, _) in zip(self.blends, outs):
884
+ try:
885
+ r = json.loads(c) if st == 200 else None
886
+ if isinstance(r, dict) and isinstance(r.get("answers"), dict):
887
+ others.append((w, r.get("model"), r["answers"]))
888
+ except ValueError:
889
+ continue
890
+ for q in want:
891
+ a = answers[q]
892
+ keys = list(a["probabilities"])
893
+ members = [(self.blend_weight, resp.get("model"), a)] + [
894
+ (w, m, x[q]) for w, m, x in others if isinstance(x.get(q), dict) and x[q].get("type") == a["type"]
895
+ and isinstance(x[q].get("probabilities"), dict) and list(x[q]["probabilities"]) == keys]
896
+ members = [m for m in members if m[0] > 0] # (a weight of 0: the model takes no part, the first one too)
897
+ if len(members) > 1:
898
+ answers[q] = blend_answer(members[0][2], members)
899
+ why = f"the blend of {len(members)} models' probabilities (weights {[w for w, _, _ in members]})"
900
+ elif members: # only one model answered (or has a weight): its answer as it is
901
+ answers[q] = dict(members[0][2], blend={"models": [members[0][1]], "weights": [members[0][0]]})
902
+ why = f"the answer of {members[0][1]}, the only model of the blend that answered"
903
+ traces = traces_of(resp)
904
+ if members and traces is not None:
905
+ if len(members) == 1 and members[0][2] is a and isinstance(traces.get(q), dict):
906
+ # (the first replica's own answer, unchanged: calibrated, its certified fields kept, and so its trace)
907
+ traces[q] = dict(traces[q], reason=f"{traces[q].get('reason')}; the only model of the blend that "
908
+ f"answered")
909
+ else:
910
+ t = routed(answers[q], "")
911
+ conf = answers[q].get("confidence")
912
+ conf = conf if isinstance(conf, (int, float)) and not isinstance(conf, bool) else \
913
+ top_probability(answers[q])
914
+ note = ", not calibrated" if answers[q].get("calibrated") is False else ""
915
+ t["reason"] = f"{why}: {t['chosen']!r} at {fmt(conf)}{note}"
916
+ traces[q] = t
917
+ self.blended[len(members)] = self.blended.get(len(members), 0) + 1
918
+ return json.dumps(resp, ensure_ascii=False).encode()
919
+
920
+ async def _cascade(self, path, req, content, headers, key, level_out=None):
921
+ """The answers of the first replica (level 1), with those under level k's threshold asked again of level k + 1,
922
+ level by level. A level that is down or does not answer 200 leaves the previous answers (and ends the chain).
923
+ With one level the response is as before; with more, every answer also gives its level and model."""
924
+ try:
925
+ resp = json.loads(content)
926
+ answers = resp["answers"]
927
+ except (ValueError, KeyError, TypeError):
928
+ return content
929
+ named = len(self.levels) > 1
930
+ level = {} if level_out is None else level_out
931
+ for q, a in answers.items():
932
+ if isinstance(a, dict) and not failed(a): # (an error answer stays as the replica gave it)
933
+ a["answered_by"] = "first"
934
+ if named:
935
+ a["level"], a["model"] = 1, resp.get("model")
936
+ level[q] = 1
937
+ done = []
938
+ for k, (pool, below) in enumerate(self.levels, start=1):
939
+ low = [q for q, a in answers.items() if q in (req.get("questions") or {}) and level.get(q) == k
940
+ and (top_probability(a) if isinstance(a, dict) else None) is not None and top_probability(a) < below]
941
+ if not low:
942
+ break
943
+ sub = dict(req, questions=ungated(req["questions"], low))
944
+ st, c2, _ = await self._send(pool, path, json.dumps(sub).encode(), headers, key)
945
+ if st != 200:
946
+ break
947
+ try:
948
+ r2 = json.loads(c2)
949
+ except (ValueError, UnicodeError):
950
+ break
951
+ if not isinstance(r2, dict) or not isinstance(r2.get("answers"), dict):
952
+ break
953
+ traces, t2 = traces_of(resp), traces_of(r2) or {}
954
+ for q, a in (r2.get("answers") or {}).items():
955
+ if q in low and isinstance(a, dict):
956
+ if traces is not None: # (the trace of the answer returned: this level's, and why it was asked)
957
+ why = (f"escalated to level {k + 1} ({r2.get('model')}): level {k}'s top probability "
958
+ f"{top_probability(answers[q]):.4f} is below {below:g}")
959
+ traces[q] = (dict(t2[q], reason=f"{t2[q].get('reason')}; {why}") if isinstance(t2.get(q), dict)
960
+ else routed(a, why))
961
+ a["answered_by"] = "escalated"
962
+ if named:
963
+ a["level"], a["model"] = k + 1, r2.get("model")
964
+ answers[q] = a
965
+ level[q] = k + 1
966
+ if k == 1:
967
+ done.append(q)
968
+ self.answered["escalated"] += len(done)
969
+ self.answered["first"] += sum(1 for a in answers.values() if isinstance(a, dict) and not failed(a)) - len(done)
970
+ for k in level.values():
971
+ self.by_level[k] += 1
972
+ below = [b for _, b in self.levels] if named else self.levels[0][1]
973
+ resp["cascade"] = {"below": below, "escalated": done}
974
+ return json.dumps(resp, ensure_ascii=False).encode()
975
+
976
+ def set_ready(self, r):
977
+ """Replica r answers /health: ready (a replica that was not starts a new readiness generation)."""
978
+ if r not in self.ready:
979
+ self.gen[r] = self.gen.get(r, 0) + 1
980
+ self.rules.pop(r, None)
981
+ self.ready.add(r)
982
+
983
+ def set_unready(self, r):
984
+ """Replica r failed a poll or a call: not ready, and what it reported is forgotten (a new generation)."""
985
+ self.forget(r)
986
+ self.ready.discard(r)
987
+
988
+ def forget(self, r):
989
+ """What replica r reported (its decision rules) is forgotten: a new readiness generation, read again when a
990
+ request that selects a rule needs it. Its place in rotation is unchanged."""
991
+ self.gen[r] = self.gen.get(r, 0) + 1
992
+ self.rules.pop(r, None)
993
+
994
+ async def rules_of(self, r, headers):
995
+ """Replica r's decision rules: its GET /v1/models entry's "decision_rules" (None: none loaded), read once per
996
+ readiness generation; UNREAD when the entry has no such field (a basal-serve before 3.0) or cannot be read."""
997
+ gen = self.gen.get(r, 0)
998
+ cached = self.rules.get(r)
999
+ if cached is not None and cached[0] == gen:
1000
+ return cached[1]
1001
+ try:
1002
+ resp = await self.client.get(r + "/v1/models", timeout=10, headers=headers)
1003
+ entry = resp.json()["models"][0] if resp.status_code == 200 else {}
1004
+ except Exception: # noqa: BLE001 (down, not JSON, another shape: asked again next time)
1005
+ return UNREAD
1006
+ if not isinstance(entry, dict) or "decision_rules" not in entry:
1007
+ return UNREAD
1008
+ if self.gen.get(r, 0) == gen: # (kept only for the generation it was read in)
1009
+ self.rules[r] = (gen, entry["decision_rules"])
1010
+ return entry["decision_rules"]
1011
+
1012
+ async def rules_refused(self, headers):
1013
+ """For a request whose questions select a decision rule -> (why it is refused here: (decision_rules_code,
1014
+ message), or None to pass it on; the replicas it may go to). Never under --blend, --escalate or --fallback,
1015
+ which replace a plain answer (its decision would no longer be the rule's on the probabilities it gives);
1016
+ otherwise only when every ready replica reports the same decision rules (the same file's id and sha256, or
1017
+ none), so it is decided alike whichever replica it reaches. It goes only to the replicas whose rules were read
1018
+ for it and that stayed ready meanwhile (one that became ready during the reading is checked by the next
1019
+ request)."""
1020
+ if self.levels or self.blends or self.fallback:
1021
+ what = ", ".join(f for f, on in (("--escalate", self.levels), ("--blend", self.blends),
1022
+ ("--fallback", self.fallback)) if on)
1023
+ return ("unsupported_routing", f"decision rules are not applied through a router with {what}, which "
1024
+ "replaces answers: send the request to a router without them"), None
1025
+ gens = {r: self.gen.get(r, 0) for r in sorted(self.replicas) if r in self.ready}
1026
+ ask = {k: v for k, v in headers.items() if k not in ("content-type", "content-length")}
1027
+ got = await asyncio.gather(*(self.rules_of(r, ask) for r in gens))
1028
+ seen = set()
1029
+ for r, block in zip(gens, got):
1030
+ if block is UNREAD:
1031
+ return ("rules_mismatch", f"replica {r} does not report its decision rules (GET /v1/models): every "
1032
+ "replica must be basal-serve 3.0 or later for a request that selects a "
1033
+ "rule"), None
1034
+ seen.add(None if not isinstance(block, dict) else (block.get("id"), block.get("sha256")))
1035
+ if len(seen) > 1:
1036
+ return ("rules_mismatch", "the replicas serve different decision rules (--decision-rules): a request that "
1037
+ "selects a rule is decided only when every replica serves the same file"), None
1038
+ return None, {r for r, g in gens.items() if r in self.ready and self.gen.get(r, 0) == g}
1039
+
1040
+ async def _send(self, pool, path, body, headers, key=None, only=None):
1041
+ """One call of a replica of the pool, chosen by key (state_key of the request: None, by load), among `only`
1042
+ when given (a request that selects a decision rule: the replicas whose rules were read for it); with
1043
+ --prefix-affinity or --state-holders, a state the replica answers (200) is remembered for it."""
1044
+ hs = key_blocks(key) if self.prefix and key is not None else None
1045
+ r, how = self.choose(key, pool, hs, only)
1046
+ if r is None:
1047
+ return 503, json.dumps(error_object(path, 503, "no basal replica is ready")).encode(), "application/json"
1048
+ self.load[r] += 1
1049
+ self.routed[(r, how)] += 1
1050
+ import httpx
1051
+ try:
1052
+ # (wait_for: the whole call, however slowly a replica sends its bytes; None: no deadline)
1053
+ resp = await asyncio.wait_for(self.client.post(r + path, content=body, headers=headers), self.timeout)
1054
+ if resp.status_code >= 500:
1055
+ self.failed[r] += 1
1056
+ if resp.status_code == 503: # (starting, perhaps after a restart with another rules file, overloaded or
1057
+ self.forget(r) # stalled: its rules are read again before a request that selects one goes to it)
1058
+ if resp.status_code == 200 and key is not None and (self.prefix or self.holding):
1059
+ self._remember(key, hs, pool, r)
1060
+ return resp.status_code, resp.content, resp.headers.get("content-type", "application/json")
1061
+ except (asyncio.TimeoutError, httpx.TimeoutException) as e:
1062
+ self.failed[r] += 1
1063
+ if isinstance(e, httpx.ConnectTimeout): # unreachable: out until its next /health poll. A call past the
1064
+ self.set_unready(r) # deadline was slow (a large rank request): the replica stays in rotation
1065
+ what = "connecting" if isinstance(e, httpx.ConnectTimeout) else f"after {self.timeout:g} s"
1066
+ body = error_object(path, 504, f"replica {r}: timed out {what}")
1067
+ return 504, json.dumps(body).encode(), "application/json"
1068
+ except Exception as e: # noqa: BLE001
1069
+ self.failed[r] += 1
1070
+ self.set_unready(r)
1071
+ return 502, json.dumps(error_object(path, 502, f"replica {r}: {type(e).__name__}")).encode(), \
1072
+ "application/json"
1073
+ finally:
1074
+ self.load[r] -= 1
1075
+
1076
+ def metrics(self):
1077
+ return prometheus([
1078
+ ("basal_router_replica_ready", "1 when the replica answers /health with 200", "gauge",
1079
+ [({"replica": r}, int(r in self.ready)) for r in self.replicas]),
1080
+ ("basal_router_in_flight", "requests the router has in flight at the replica", "gauge",
1081
+ [({"replica": r}, self.load[r]) for r in self.replicas]),
1082
+ ("basal_router_routed_total", "requests routed, by the state's hash or by load (held: to a replica that "
1083
+ "answered the same state, --state-holders; prefix: to the one that answered its beginning, "
1084
+ "--prefix-affinity)", "counter",
1085
+ [({"replica": r, "by": how}, n) for (r, how), n in self.routed.items()]),
1086
+ ("basal_router_failed_total", "requests the replica answered with 5xx or not at all", "counter",
1087
+ [({"replica": r}, n) for r, n in self.failed.items()]),
1088
+ ("basal_router_requests_in_flight", "decision requests the router holds, from before their body is read to "
1089
+ f"their answer (--max-requests {self.max_requests})", "gauge", [({}, self.in_flight)]),
1090
+ ("basal_router_overloaded_total", "requests answered 503 OVERLOADED, by the limit that refused them "
1091
+ "(max_requests: --max-requests; per_key: --max-requests-per-key)", "counter",
1092
+ [({"limit": k}, n) for k, n in self.overloaded.items()])]
1093
+ + ([("basal_router_affinity_blocks", "beginnings of states --prefix-affinity remembers (block entries, "
1094
+ f"at most {MAX_BLOCKS} per pool)", "gauge", [({}, sum(map(len, self.blocks.values())))])]
1095
+ if self.prefix else [])
1096
+ + ([("basal_router_state_holders", f"states --state-holders remembers the replicas of (at most {HOLDERS})",
1097
+ "gauge", [({}, len(self.holders))])] if self.holding else [])
1098
+ + ([("basal_router_answers_total", "answers by the first replica / escalated (--escalate)", "counter",
1099
+ [({"answered_by": k}, n) for k, n in self.answered.items()])] if self.levels else [])
1100
+ + ([("basal_router_level_answers_total", "answers by cascade level (1: the first replica)", "counter",
1101
+ [({"level": str(k)}, n) for k, n in self.by_level.items()])] if len(self.levels) > 1 else [])
1102
+ + ([("basal_router_fallback_total", "questions sent to the --fallback LLM, by result (answered: its answer "
1103
+ "replaced the basal one)", "counter", [({"result": k}, n) for k, n in self.fallback_counts.items()])]
1104
+ if self.fallback else [])
1105
+ + ([("basal_router_blend_answers_total", "answers blended (--blend), by the number of models in the blend",
1106
+ "counter", [({"models": str(k)}, n) for k, n in sorted(self.blended.items())])] if self.blends else [])
1107
+ + ([("basal_router_script_total", "requests by the script of their state (--route)", "counter",
1108
+ [({"script": k}, n) for k, n in sorted(self.scripts.items())])] if self.scripts else []))
1109
+
1110
+
1111
+ def overloaded_body(path, e):
1112
+ """The 503 body of a request the router refused (Overloaded): basal-serve's {"error", "code": "OVERLOADED"}, and
1113
+ OpenAI's error object on /v1/decisions and /v1/chat/completions (request.error_object), as basal-serve answers
1114
+ each."""
1115
+ return error_object(path, 503, str(e), "OVERLOADED")
1116
+
1117
+
1118
+ def app(router, poll_s=None, procs=(), on_dead=lambda: signal.raise_signal(signal.SIGTERM), on_stop=None, ui=None,
1119
+ max_body=MAX_BODY_BYTES, hosts=None, keys=None):
1120
+ """The router's app. procs: the replicas it started (--gpus); on_stop: called at shutdown (main: Replicas.stop);
1121
+ ui: the basal.router_ui.RouterUI of --ui on (its decision routes recorded, GET /ui/state, and the page at /ui);
1122
+ max_body: --max-body-mb in bytes (a larger body answers 413 before the router reads it whole, as basal-serve);
1123
+ hosts: the Host names a request may give (auth.allowed_hosts; None: not checked); keys: the auth.ApiKeys of
1124
+ --api-keys (None: the router checks no key, the replicas do)."""
1125
+ from contextlib import asynccontextmanager
1126
+ poll_s = POLL_S if poll_s is None else poll_s
1127
+
1128
+ from starlette.applications import Starlette
1129
+ from starlette.requests import ClientDisconnect
1130
+ from starlette.responses import JSONResponse, PlainTextResponse, Response
1131
+ from starlette.routing import Route
1132
+
1133
+ from .disconnect import CLIENT_GONE, until_disconnect
1134
+
1135
+ async def post(request):
1136
+ """A client that disconnects (a timeout, a retry) cancels the request: every call it has made to a replica is
1137
+ cancelled, which closes that connection, so the replica cancels its own request in turn (its queued work is
1138
+ dropped). Without it the router held the replica's connection until the replica answered nobody. The request
1139
+ is admitted first (--max-requests, --max-requests-per-key for the key protect checked): one beyond them
1140
+ answers 503 OVERLOADED before its body is read, and one admitted keeps its place to its answer."""
1141
+ record = request.scope.get("basal.api_key")
1142
+ try:
1143
+ place = router.admit(record["name"] if isinstance(record, dict) else None)
1144
+ except Overloaded as e:
1145
+ return JSONResponse(overloaded_body(request.url.path, e), status_code=503, headers={"Retry-After": "1"})
1146
+ try:
1147
+ headers = {"content-type": "application/json", **key_headers(request.headers.raw)}
1148
+ if is_multipart(request.headers.get("content-type")): # (media as parts: to a replica as it came, by load)
1149
+ headers["content-type"] = request.headers["content-type"]
1150
+ if request.scope.get("basal.request_id"): # (request_ids below: the client's, or one it made)
1151
+ headers["x-request-id"] = request.scope["basal.request_id"]
1152
+ try:
1153
+ body = await request.body()
1154
+ except ClientDisconnect: # the client left while sending the body
1155
+ return JSONResponse(*CLIENT_GONE)
1156
+ out = await until_disconnect(request, router.forward(request.url.path, body, headers))
1157
+ if out is None: # the client is gone
1158
+ return JSONResponse(*CLIENT_GONE)
1159
+ status, content, ctype = out
1160
+ return Response(content, status_code=status, media_type=ctype)
1161
+ finally:
1162
+ place.release()
1163
+
1164
+ def main_ready():
1165
+ """The ready replicas of the pool of ordinary requests: an escalation or blend pool alone serves none."""
1166
+ return sorted(r for r in router.pools["main"] if r in router.ready)
1167
+
1168
+ async def health(_):
1169
+ up = bool(main_ready())
1170
+ body = {"status": "ok" if up else "starting", "ready": len(router.ready),
1171
+ "replicas": len(router.replicas), "in_flight": sum(router.load.values()),
1172
+ "pools": {name: sum(r in router.ready for r in urls) for name, urls in router.pools.items()}}
1173
+ return JSONResponse(body, status_code=200 if up else 503)
1174
+
1175
+ def router_info():
1176
+ """The router's part of GET /v1/capabilities: its own limits and options, which apply before a replica's
1177
+ (counts and switches only: no URL, path or key)."""
1178
+ return {"replicas": len(router.pools["main"]), "ready": len(main_ready()),
1179
+ "max_requests": router.max_requests, "max_requests_per_key": router.max_per_key,
1180
+ "max_body_bytes": max_body, "api_keys": keys is not None, "replica_timeout_s": router.timeout,
1181
+ "load_factor": router.factor, "prefix_affinity": router.prefix, "state_holders": router.holding,
1182
+ "cascade_levels": len(router.levels) + 1 if router.levels else None,
1183
+ "blend_models": len(router.blends) + 1 if router.blends else None,
1184
+ "fallback": router.fallback is not None,
1185
+ "routes": sorted(name.split(":", 1)[1] for name in router.rings if name.startswith("script:"))}
1186
+
1187
+ async def models(request):
1188
+ """GET /v1/models, /v1/capabilities (and /capabilities): the first ready replica's of the main pool; the
1189
+ capabilities with the router's own part added ("router", router_info)."""
1190
+ caps = request.url.path in ("/v1/capabilities", "/capabilities")
1191
+ for r in main_ready():
1192
+ try:
1193
+ resp = await router.client.get(r + request.url.path, timeout=10, headers=key_headers(request.headers.raw))
1194
+ except Exception: # noqa: BLE001
1195
+ continue
1196
+ if caps and resp.status_code == 200:
1197
+ try:
1198
+ data = resp.json()
1199
+ except ValueError:
1200
+ data = None
1201
+ if isinstance(data, dict):
1202
+ return JSONResponse(dict(data, router=router_info()))
1203
+ return Response(resp.content, status_code=resp.status_code, media_type="application/json")
1204
+ return JSONResponse({"error": "no basal replica is ready"}, status_code=503)
1205
+
1206
+ async def metrics(_):
1207
+ return PlainTextResponse(router.metrics(), media_type="text/plain; version=0.0.4")
1208
+
1209
+ @asynccontextmanager
1210
+ async def lifespan(_app):
1211
+ async def loop():
1212
+ while True:
1213
+ await router.poll()
1214
+ if procs and all(p.poll() is not None for p in procs):
1215
+ router.dead = True
1216
+ print("basal-router: every replica exited", file=sys.stderr, flush=True)
1217
+ on_dead() # SIGTERM: uvicorn shuts down, main exits with status 1
1218
+ return
1219
+ await asyncio.sleep(poll_s)
1220
+ task = asyncio.get_running_loop().create_task(loop())
1221
+ yield
1222
+ task.cancel()
1223
+ await router.client.aclose()
1224
+ if on_stop is not None: # (uvicorn's shutdown: before it re-raises the signal that stopped it)
1225
+ await asyncio.get_running_loop().run_in_executor(None, on_stop)
1226
+
1227
+ from starlette.middleware import Middleware
1228
+
1229
+ from .auth import host_check, protect, request_ids
1230
+ ids = [Middleware(request_ids), # x-request-id on every response, passed on to the replicas
1231
+ *([Middleware(protect, keys)] if keys is not None else []), # (401 before anything reads the request)
1232
+ Middleware(limit_body, max_body)] # (413 before a body is read whole)
1233
+ if hosts is not None: # (outermost: DNS rebinding and other sites' pages are refused first)
1234
+ ids.insert(0, Middleware(host_check, hosts))
1235
+ routes = [Route("/v1/systemone", post, methods=["POST"]), Route("/v1/basal", post, methods=["POST"]),
1236
+ Route("/v1/decisions", post, methods=["POST"]), Route("/v1/chat/completions", post, methods=["POST"]),
1237
+ Route("/health", health), Route("/health/", health), Route("/v1/models", models),
1238
+ Route("/v1/capabilities", models), Route("/capabilities", models), Route("/metrics", metrics)]
1239
+ if ui is None:
1240
+ return Starlette(routes=routes, lifespan=lifespan, middleware=ids)
1241
+ return ui.page(Starlette(routes=ui.routes(routes), lifespan=lifespan, middleware=ids))
1242
+
1243
+
1244
+ class Replicas:
1245
+ """The basal-serve processes of --gpus. stop() ends each one's process group (SIGTERM, then SIGKILL after
1246
+ `timeout` seconds), once, from whichever exit path of the router comes first: the app's shutdown, main's signal
1247
+ handler (uvicorn re-raises the signal it caught after its own shutdown, which would end the process before main's
1248
+ finally), main's finally, atexit."""
1249
+
1250
+ def __init__(self, procs=()):
1251
+ self.procs, self.stopped = list(procs), False
1252
+
1253
+ def stop(self, timeout=30):
1254
+ if self.stopped:
1255
+ return
1256
+ self.stopped = True
1257
+ for p in self.procs:
1258
+ _end_group(p)
1259
+ end = time.monotonic() + timeout
1260
+ for p in self.procs:
1261
+ try:
1262
+ p.wait(timeout=max(0.0, end - time.monotonic()))
1263
+ except subprocess.TimeoutExpired:
1264
+ pass
1265
+ for p in self.procs: # a replica past the timeout, or a process a replica left in its group
1266
+ _end_group(p, hard=True)
1267
+ p.wait()
1268
+
1269
+
1270
+ def _end_group(p, hard=False):
1271
+ """SIGTERM (hard: SIGKILL) to a replica's process group; without process groups (Windows) to the replica."""
1272
+ try:
1273
+ if hasattr(os, "killpg"):
1274
+ os.killpg(p.pid, signal.SIGKILL if hard else signal.SIGTERM)
1275
+ elif p.poll() is None:
1276
+ p.kill() if hard else p.terminate()
1277
+ except (ProcessLookupError, PermissionError):
1278
+ pass
1279
+
1280
+
1281
+ def _death_signal():
1282
+ """preexec_fn of a replica on Linux: SIGTERM when the router dies, however it dies (prctl PR_SET_PDEATHSIG);
1283
+ None elsewhere. libc is loaded here, before the fork."""
1284
+ if not sys.platform.startswith("linux"):
1285
+ return None
1286
+ import ctypes
1287
+ try:
1288
+ prctl = ctypes.CDLL(None, use_errno=True).prctl
1289
+ except (OSError, AttributeError):
1290
+ return None
1291
+ parent = os.getpid()
1292
+
1293
+ def child():
1294
+ prctl(1, signal.SIGTERM) # PR_SET_PDEATHSIG
1295
+ if os.getppid() != parent: # the router already died
1296
+ os._exit(1)
1297
+ return child
1298
+
1299
+
1300
+ def devices(gpus, mask=None):
1301
+ """The CUDA_VISIBLE_DEVICES of each replica of --gpus. Without a mask of the user's (CUDA_VISIBLE_DEVICES not
1302
+ set) an entry goes on as given: an index, a GPU UUID. With one, an entry is an index into the mask, as CUDA numbers
1303
+ the GPUs the router sees, and the replica gets the mask's entry at it. Anything else is refused before a replica
1304
+ starts: a number past the mask read as a physical id would mean another GPU than the same number as an index (mask
1305
+ 0,2,3 with --gpus 2,3 put both replicas on GPU 3)."""
1306
+ gpus = [str(g).strip() for g in gpus]
1307
+ if not all(gpus):
1308
+ raise SystemExit(f"basal-router: --gpus {','.join(gpus)}: an empty entry")
1309
+ if mask is None:
1310
+ return gpus
1311
+ seen = [x.strip() for x in mask.split(",") if x.strip()]
1312
+ if not seen:
1313
+ raise SystemExit(f"basal-router: --gpus {','.join(gpus)}: CUDA_VISIBLE_DEVICES is set but lists no GPU; unset "
1314
+ "it to name GPUs by their own ids")
1315
+ bad = [g for g in gpus if not (g.isascii() and g.isdigit() and int(g) < len(seen))]
1316
+ if bad:
1317
+ raise SystemExit(f"basal-router: --gpus {','.join(gpus)}: with CUDA_VISIBLE_DEVICES={mask} an entry is an index "
1318
+ f"of the {len(seen)} GPUs it lists, 0 to {len(seen) - 1} ({', '.join(bad)} is not); unset "
1319
+ "CUDA_VISIBLE_DEVICES to name GPUs by their own ids")
1320
+ return [seen[int(g)] for g in gpus]
1321
+
1322
+
1323
+ def spawn(gpus, port0, serve_args):
1324
+ """One basal-serve per GPU of --gpus (devices: indexes of the user's CUDA_VISIBLE_DEVICES when it is set), on
1325
+ ports port0, port0 + 1, ... -> (processes, URLs). Each in its own process group (Replicas.stop ends the replica
1326
+ and whatever it started) that, on Linux, gets SIGTERM when the router dies. The replicas listen on 127.0.0.1 only
1327
+ (the router reaches them there; basal-serve's own default, 0.0.0.0, would let the network bypass the router)
1328
+ unless the arguments after -- give --host."""
1329
+ procs, urls, pre = [], [], _death_signal()
1330
+ host = [] if any(x == "--host" or x.startswith("--host=") for x in serve_args) else ["--host", "127.0.0.1"]
1331
+ for i, dev in enumerate(devices(gpus, os.environ.get("CUDA_VISIBLE_DEVICES"))):
1332
+ port = port0 + i
1333
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES=dev)
1334
+ procs.append(subprocess.Popen([*SERVE, "--port", str(port), *host, *serve_args], env=env,
1335
+ start_new_session=hasattr(os, "killpg"), preexec_fn=pre))
1336
+ urls.append(f"http://127.0.0.1:{port}")
1337
+ return procs, urls
1338
+
1339
+
1340
+ def levels(escalate, below):
1341
+ """The cascade levels of --escalate URL ... (repeated: levels 2, 3, ...) and --escalate-below P (one per
1342
+ --escalate, in order; none: 0.8 for each) -> [(URLs, threshold), ...]; [] without escalation replicas."""
1343
+ if not any(escalate):
1344
+ return []
1345
+ if not all(escalate):
1346
+ raise SystemExit("basal-router: --escalate without URLs among several --escalate levels")
1347
+ if below and len(below) != len(escalate):
1348
+ raise SystemExit(f"basal-router: {len(escalate)} --escalate levels and {len(below)} --escalate-below "
1349
+ "thresholds (give one per level, in the same order, or none for 0.8)")
1350
+ return [(list(u), b) for u, b in zip(escalate, below or [0.8] * len(escalate))]
1351
+
1352
+
1353
+ def blends(blend, weights, cascade):
1354
+ """The blend of --blend URL ... (repeated: one model each) and --blend-weights W0 W1 ... (W0 for --replicas, then
1355
+ one per --blend) -> (first replica's weight, [(URLs, weight), ...]); (1.0, []) without --blend."""
1356
+ if not blend:
1357
+ if weights is not None:
1358
+ raise SystemExit("basal-router: --blend-weights without --blend")
1359
+ return 1.0, []
1360
+ if cascade:
1361
+ raise SystemExit("basal-router: --blend and --escalate do not go together")
1362
+ if not all(blend):
1363
+ raise SystemExit("basal-router: --blend without URLs")
1364
+ if weights is None or len(weights) != 1 + len(blend):
1365
+ raise SystemExit(f"basal-router: --blend-weights needs {1 + len(blend)} weights (--replicas first, then one "
1366
+ "per --blend, in order)")
1367
+ if any(not math.isfinite(w) or w < 0 for w in weights) or sum(weights) <= 0:
1368
+ raise SystemExit("basal-router: --blend-weights must be finite, >= 0 and not all 0")
1369
+ return weights[0], [(list(u), w) for u, w in zip(blend, weights[1:])]
1370
+
1371
+
1372
+ def fallback_config(a, blend):
1373
+ """--fallback URL --fallback-model NAME [--fallback-below T --fallback-timeout S --fallback-max-tokens N
1374
+ --fallback-extra JSON] -> the Router's fallback dict; None without --fallback."""
1375
+ given = [f for f in ("fallback_model", "fallback_below", "fallback_timeout", "fallback_max_tokens", "fallback_extra")
1376
+ if getattr(a, f) is not None]
1377
+ if not a.fallback:
1378
+ if given:
1379
+ raise SystemExit("basal-router: --fallback-model / -below / -timeout / -max-tokens / -extra need --fallback URL")
1380
+ return None
1381
+ if blend:
1382
+ raise SystemExit("basal-router: --fallback and --blend do not go together")
1383
+ if not a.fallback_model:
1384
+ raise SystemExit("basal-router: --fallback needs --fallback-model NAME (the model the endpoint serves)")
1385
+ below = 0.5 if a.fallback_below is None else a.fallback_below
1386
+ timeout = 60.0 if a.fallback_timeout is None else a.fallback_timeout
1387
+ max_tokens = 8192 if a.fallback_max_tokens is None else a.fallback_max_tokens
1388
+ if not 0 < below <= 1 or not timeout > 0 or max_tokens < 1:
1389
+ raise SystemExit("basal-router: --fallback-below must be in (0, 1], --fallback-timeout > 0, "
1390
+ "--fallback-max-tokens >= 1")
1391
+ try:
1392
+ extra = json.loads(a.fallback_extra) if a.fallback_extra else {}
1393
+ except ValueError:
1394
+ extra = None
1395
+ if not isinstance(extra, dict):
1396
+ raise SystemExit("basal-router: --fallback-extra must be a JSON object")
1397
+ return {"url": a.fallback, "model": a.fallback_model, "below": below, "timeout": timeout, "max_tokens": max_tokens,
1398
+ "extra": extra}
1399
+
1400
+
1401
+ def _positive(text):
1402
+ """argparse type: a whole number >= 1."""
1403
+ try:
1404
+ n = int(text)
1405
+ except ValueError:
1406
+ n = 0
1407
+ if n < 1:
1408
+ raise argparse.ArgumentTypeError(f"{text!r} is not a whole number >= 1")
1409
+ return n
1410
+
1411
+
1412
+ def main(argv=None):
1413
+ from . import cli
1414
+ cli.warn_mixed_install() # basal 2.x next to basal-engine: one line (the replicas it starts stay quiet)
1415
+ argv = list(sys.argv[1:] if argv is None else argv)
1416
+ serve_args = argv[argv.index("--") + 1:] if "--" in argv else []
1417
+ argv = argv[: argv.index("--")] if "--" in argv else argv
1418
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1419
+ ap.add_argument("--replicas", nargs="*", default=[], help="URLs of running basal-serve replicas")
1420
+ ap.add_argument("--gpus", default=None, help="start one basal-serve per GPU, e.g. 0,1,2,3 (arguments after --); "
1421
+ "with CUDA_VISIBLE_DEVICES set, indexes of the GPUs it lists")
1422
+ ap.add_argument("--replica-port", dest="replica_port", type=int, default=8001)
1423
+ ap.add_argument("--host", default="127.0.0.1")
1424
+ ap.add_argument("--allowed-hosts", dest="allowed_hosts", default=None, metavar="H[,H...]",
1425
+ help="the Host names a request may give besides localhost / 127.0.0.1 / ::1 (others: 403); "
1426
+ "checked by default when bound to a loopback --host (DNS rebinding); \"*\": never checked")
1427
+ ap.add_argument("--port", type=int, default=8000)
1428
+ ap.add_argument("--load-factor", dest="load_factor", type=float, default=LOAD_FACTOR,
1429
+ help="a replica already holding more than this x the mean requests in flight takes no new one "
1430
+ "(the ring passes it on; --state-holders and --prefix-affinity choose within the same bound); "
1431
+ "default %(default)s")
1432
+ ap.add_argument("--state-holders", dest="state_holders", choices=["off", "on"], default="off",
1433
+ help="a state's later requests go to the least loaded replica that already answered it, within "
1434
+ "--load-factor: a state passed on once is not a state-cache miss each time (default off)")
1435
+ ap.add_argument("--prefix-affinity", dest="prefix_affinity", choices=["off", "on"], default="off",
1436
+ help="a state that begins with one answered before (a growing agent trace or chat, an edited "
1437
+ "document) goes to the replica that answered it, within --load-factor, so its state cache "
1438
+ "holds the beginning (default off)")
1439
+ ap.add_argument("--escalate", nargs="*", action="append", default=[],
1440
+ help="escalation replicas (a bigger model) for the cascade; repeat for further levels")
1441
+ ap.add_argument("--escalate-below", dest="escalate_below", type=float, action="append", default=[],
1442
+ help="--escalate: questions whose top probability is under this are asked again there (default "
1443
+ "0.8); one per --escalate, in the same order")
1444
+ ap.add_argument("--route", action="append", default=[], help="SCRIPT=URL[,URL]: states in that script go there")
1445
+ ap.add_argument("--max-body-mb", dest="max_body_mb", type=float, default=MAX_BODY_BYTES / 2**20, metavar="MB",
1446
+ help="a request body over MB MiB answers 413 before the router reads it whole (basal-serve's "
1447
+ "default, %(default)s)")
1448
+ ap.add_argument("--max-requests", dest="max_requests", type=_positive, default=None, metavar="N",
1449
+ help="decision requests in flight at the router at once (default: 1,024 per replica of --replicas "
1450
+ "/ --gpus); one beyond them answers 503 (code OVERLOADED, Retry-After: 1) before its body is "
1451
+ "read")
1452
+ ap.add_argument("--api-keys", dest="api_keys", default=None, metavar="PATH",
1453
+ help="check a client's API key at the router (basal-serve's key file of SHA-256 digests, re-read "
1454
+ "when it changes): 401 without a valid one; GET /health stays open, GET /v1/keys needs an "
1455
+ "admin key; the key still goes on to the replicas")
1456
+ ap.add_argument("--max-requests-per-key", dest="max_requests_per_key", type=_positive, default=None, metavar="N",
1457
+ help="with --api-keys: one key's requests in flight at once (default: no cap of its own); one "
1458
+ "beyond them answers 503 OVERLOADED, so a key cannot take every place of --max-requests")
1459
+ ap.add_argument("--replica-timeout", dest="replica_timeout", type=float, default=None,
1460
+ help="seconds a replica has to answer a call (then 504; a cascade level or a blend model keeps the "
1461
+ "previous answers); default: no deadline")
1462
+ ap.add_argument("--blend", nargs="+", action="append", default=[],
1463
+ help="replicas of one more model whose probabilities are blended in; repeat for each model")
1464
+ ap.add_argument("--blend-weights", dest="blend_weights", nargs="+", type=float, default=None,
1465
+ help="--blend: the weight of --replicas, then of each --blend, in order")
1466
+ ap.add_argument("--fallback", default=None, help="base URL of an OpenAI-compatible chat endpoint (an LLM) for "
1467
+ "questions still unsure after the last level, e.g. http://127.0.0.1:8100/v1")
1468
+ ap.add_argument("--fallback-model", dest="fallback_model", default=None, help="--fallback: the model it serves")
1469
+ ap.add_argument("--fallback-below", dest="fallback_below", type=float, default=None,
1470
+ help="--fallback: questions whose top probability is under this go (default 0.5)")
1471
+ ap.add_argument("--fallback-timeout", dest="fallback_timeout", type=float, default=None,
1472
+ help="--fallback: seconds per call (default 60); then the basal answer stays")
1473
+ ap.add_argument("--fallback-max-tokens", dest="fallback_max_tokens", type=int, default=None,
1474
+ help="--fallback: the token budget of a call, thinking included (default 8192; the endpoint's "
1475
+ "context must hold the prompt plus this)")
1476
+ ap.add_argument("--fallback-extra", dest="fallback_extra", default=None,
1477
+ help='--fallback: JSON merged into the chat request, e.g. a thinking switch: '
1478
+ '\'{"chat_template_kwargs": {"enable_thinking": true}}\'')
1479
+ ap.add_argument("--ui", choices=["off", "on"], default="off",
1480
+ help="also serve one live page of the router and every replica at /ui: replicas, readiness, "
1481
+ "routing, requests in flight, failures, traffic through the router since start and its recent "
1482
+ "requests (metadata, never text), and each replica's own status, traffic, state cache and GPU "
1483
+ "telemetry from its /ui/state when the replica runs with --ui on (after -- with --gpus); "
1484
+ "each request adds one append to an in-memory ring. Open like /metrics; the replicas' parts "
1485
+ "need a key when they run with --api-keys (the page asks for it)")
1486
+ a = ap.parse_args(argv)
1487
+ if a.replica_timeout is not None and not (math.isfinite(a.replica_timeout) and a.replica_timeout > 0):
1488
+ raise SystemExit("basal-router: --replica-timeout must be a number of seconds > 0")
1489
+ if not (math.isfinite(a.max_body_mb) and a.max_body_mb > 0):
1490
+ raise SystemExit("basal-router: --max-body-mb must be a number above 0")
1491
+ if a.max_requests_per_key is not None and not a.api_keys:
1492
+ raise SystemExit("basal-router: --max-requests-per-key needs --api-keys (the router counts the keys it checks; "
1493
+ "a key it only passes on could be any text)")
1494
+ if a.api_keys and not os.path.isfile(a.api_keys): # (re-read while running, as basal-serve: only a warning)
1495
+ print(f"warning: --api-keys {a.api_keys}: no such file; every request gets 401 until it exists", file=sys.stderr)
1496
+ cascade = levels(a.escalate, a.escalate_below)
1497
+ first, blend = blends(a.blend, a.blend_weights, cascade)
1498
+ fallback = fallback_config(a, blend)
1499
+ procs, urls = ([], list(a.replicas))
1500
+ if a.gpus:
1501
+ procs, more = spawn(a.gpus.split(","), a.replica_port, serve_args)
1502
+ urls += more
1503
+ replicas = Replicas(procs)
1504
+ atexit.register(replicas.stop) # (from here: a SystemExit below ends the replicas too)
1505
+ if not urls:
1506
+ raise SystemExit("basal-router: no replicas (--replicas URL ... or --gpus 0,1 -- <basal-serve arguments>)")
1507
+ import uvicorn
1508
+ print(f"basal-router: {len(urls)} replicas, port {a.port}", flush=True)
1509
+ routes = {}
1510
+ for x in a.route:
1511
+ k, _, v = x.partition("=")
1512
+ if k not in SCRIPTS + ("other",) or not v:
1513
+ raise SystemExit(f"basal-router: --route {x!r}: SCRIPT=URL[,URL], SCRIPT one of {', '.join(SCRIPTS)}, other")
1514
+ routes[k] = v.split(",")
1515
+ router = Router(urls, factor=a.load_factor, levels=cascade, routes=routes, blend=blend, blend_weight=first,
1516
+ fallback=fallback, timeout=a.replica_timeout, max_requests=a.max_requests,
1517
+ max_per_key=a.max_requests_per_key, prefix_affinity=a.prefix_affinity == "on",
1518
+ state_holders=a.state_holders == "on")
1519
+ ui = None
1520
+ if a.ui == "on": # basal/router_ui.py: the page at /ui, its state at /ui/state
1521
+ from .router_ui import RouterUI
1522
+ ui = RouterUI(router, a, vars(ap.parse_args([])))
1523
+ print(f"basal-router: web UI at http://{a.host}:{a.port}/ui " + (
1524
+ "(its state needs an API key, as every route but /health)" if a.api_keys else
1525
+ "(open to whoever reaches this port, as /metrics is; replicas started with --api-keys need the key on "
1526
+ "the page)"), flush=True)
1527
+
1528
+ def ended(sig, _frame):
1529
+ """SIGTERM / SIGINT / SIGHUP outside uvicorn, or re-raised by it after its shutdown: the replicas end first."""
1530
+ replicas.stop()
1531
+ if router.dead:
1532
+ raise SystemExit(1)
1533
+ signal.signal(sig, signal.SIG_DFL)
1534
+ signal.raise_signal(sig)
1535
+ for name in ("SIGTERM", "SIGINT", "SIGHUP"):
1536
+ if hasattr(signal, name):
1537
+ signal.signal(getattr(signal, name), ended)
1538
+ try:
1539
+ from .auth import ApiKeys, allowed_hosts
1540
+ hosts = allowed_hosts(a.host, a.allowed_hosts, a.api_keys)
1541
+ uvicorn.run(app(router, procs=procs, on_stop=replicas.stop, ui=ui, max_body=int(a.max_body_mb * 2**20),
1542
+ hosts=hosts, keys=ApiKeys(a.api_keys) if a.api_keys else None), host=a.host, port=a.port,
1543
+ log_level="warning")
1544
+ finally:
1545
+ replicas.stop()
1546
+ if router.dead:
1547
+ raise SystemExit(1)
1548
+
1549
+
1550
+ if __name__ == "__main__":
1551
+ main()