modelsaar 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- modelsaar/__init__.py +13 -0
- modelsaar/adapters/__init__.py +27 -0
- modelsaar/adapters/base.py +274 -0
- modelsaar/adapters/ollama.py +317 -0
- modelsaar/adapters/openai_compat.py +296 -0
- modelsaar/catalogue/__init__.py +72 -0
- modelsaar/catalogue/starter.yaml +435 -0
- modelsaar/cli.py +880 -0
- modelsaar/clientconfig/__init__.py +364 -0
- modelsaar/config.py +631 -0
- modelsaar/doctor.py +233 -0
- modelsaar/evaluation/__init__.py +1 -0
- modelsaar/evaluation/fixtures/tasks.jsonl +47 -0
- modelsaar/evaluation/harness.py +768 -0
- modelsaar/evaluation/judge.py +173 -0
- modelsaar/evaluation/sandbox.py +341 -0
- modelsaar/evaluation/scoring.py +233 -0
- modelsaar/learning.py +227 -0
- modelsaar/lifecycle.py +208 -0
- modelsaar/pipelines.py +439 -0
- modelsaar/probes.py +526 -0
- modelsaar/protocol/__init__.py +1 -0
- modelsaar/protocol/anthropic.py +401 -0
- modelsaar/protocol/decisions.py +229 -0
- modelsaar/protocol/openai.py +322 -0
- modelsaar/protocol/responses.py +560 -0
- modelsaar/protocol/sse.py +181 -0
- modelsaar/registry.py +229 -0
- modelsaar/responses_store.py +117 -0
- modelsaar/routing/__init__.py +1 -0
- modelsaar/routing/admission.py +359 -0
- modelsaar/routing/affinity.py +131 -0
- modelsaar/routing/cascade.py +53 -0
- modelsaar/routing/classifier.py +298 -0
- modelsaar/routing/decision.py +85 -0
- modelsaar/routing/eligibility.py +158 -0
- modelsaar/routing/requirements.py +290 -0
- modelsaar/routing/router.py +1026 -0
- modelsaar/routing/scoring.py +179 -0
- modelsaar/routing/tokens.py +114 -0
- modelsaar/runtime.py +82 -0
- modelsaar/security.py +63 -0
- modelsaar/server.py +1546 -0
- modelsaar/static/status.html +95 -0
- modelsaar/store.py +208 -0
- modelsaar/testing/__init__.py +1 -0
- modelsaar/testing/fakebackend.py +661 -0
- modelsaar-0.2.0.dist-info/METADATA +285 -0
- modelsaar-0.2.0.dist-info/RECORD +54 -0
- modelsaar-0.2.0.dist-info/WHEEL +5 -0
- modelsaar-0.2.0.dist-info/entry_points.txt +2 -0
- modelsaar-0.2.0.dist-info/licenses/LICENSE +202 -0
- modelsaar-0.2.0.dist-info/licenses/NOTICE +18 -0
- modelsaar-0.2.0.dist-info/top_level.txt +1 -0
modelsaar/server.py
ADDED
|
@@ -0,0 +1,1546 @@
|
|
|
1
|
+
"""HTTP gateway (Starlette). Implements the OpenAI-compatible surface, the
|
|
2
|
+
protected inspection API and the response-commitment rules:
|
|
3
|
+
|
|
4
|
+
* Bounded failover is allowed only *before* any response header/byte is
|
|
5
|
+
committed, only on connection-level failures or upstream 5xx with no body
|
|
6
|
+
streamed, and only to another deployment that passed the same hard filters.
|
|
7
|
+
* After commitment, failures terminate the stream with an SSE error frame;
|
|
8
|
+
the gateway never switches deployments or splices a replacement answer.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import contextlib
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
import time
|
|
18
|
+
import uuid
|
|
19
|
+
from collections.abc import AsyncIterator
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
from starlette.applications import Starlette
|
|
25
|
+
from starlette.requests import Request
|
|
26
|
+
from starlette.responses import HTMLResponse, JSONResponse, Response, StreamingResponse
|
|
27
|
+
from starlette.routing import Route
|
|
28
|
+
|
|
29
|
+
from . import __version__
|
|
30
|
+
from .adapters.base import AdapterError, UpstreamResponse, UpstreamStream
|
|
31
|
+
from .config import Config
|
|
32
|
+
from .learning import LearningError
|
|
33
|
+
from .lifecycle import LifecycleError
|
|
34
|
+
from .pipelines import (
|
|
35
|
+
crop_regions,
|
|
36
|
+
guardrail_chat_body,
|
|
37
|
+
ocr_chat_body,
|
|
38
|
+
open_page,
|
|
39
|
+
parse_ballot,
|
|
40
|
+
parse_guardrail_answer,
|
|
41
|
+
parse_guardrail_request,
|
|
42
|
+
parse_layout_boxes,
|
|
43
|
+
parse_ocr_answer,
|
|
44
|
+
parse_ocr_request,
|
|
45
|
+
parse_vote_request,
|
|
46
|
+
vote_chat_body,
|
|
47
|
+
)
|
|
48
|
+
from .pipelines import decide as ensemble_decide
|
|
49
|
+
from .protocol.anthropic import (
|
|
50
|
+
MessagesStreamTranslator,
|
|
51
|
+
chat_to_message,
|
|
52
|
+
error_to_anthropic,
|
|
53
|
+
messages_to_chat,
|
|
54
|
+
)
|
|
55
|
+
from .protocol.decisions import decision_answers_problem, parse_decisions_request
|
|
56
|
+
from .protocol.openai import (
|
|
57
|
+
ProtocolError,
|
|
58
|
+
embedding_media_items,
|
|
59
|
+
error_body,
|
|
60
|
+
parse_chat_request,
|
|
61
|
+
parse_embeddings_request,
|
|
62
|
+
sse_error_frame,
|
|
63
|
+
)
|
|
64
|
+
from .protocol.responses import (
|
|
65
|
+
ResponsesStreamTranslator,
|
|
66
|
+
chat_to_response,
|
|
67
|
+
error_to_responses,
|
|
68
|
+
responses_to_chat,
|
|
69
|
+
)
|
|
70
|
+
from .protocol.sse import SSEParser, StreamObserver, rewrite_model_field
|
|
71
|
+
from .responses_store import ResponseStore, ResponseStoreError
|
|
72
|
+
from .routing.admission import AdmissionRejected
|
|
73
|
+
from .routing.cascade import acceptance_problem
|
|
74
|
+
from .routing.decision import Decision
|
|
75
|
+
from .routing.router import NoEligibleDeployment, Router
|
|
76
|
+
from .security import Auth, redact
|
|
77
|
+
from .store import Store
|
|
78
|
+
|
|
79
|
+
log = logging.getLogger("modelsaar.server")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class GatewayState:
|
|
83
|
+
def __init__(self, cfg: Config, router: Router, auth: Auth, store: Store | None) -> None:
|
|
84
|
+
self.cfg = cfg
|
|
85
|
+
self.router = router
|
|
86
|
+
self.auth = auth
|
|
87
|
+
self.store = store
|
|
88
|
+
self.started_at = time.time()
|
|
89
|
+
self.ready = False
|
|
90
|
+
self.requests_total = 0
|
|
91
|
+
self.requests_failed = 0
|
|
92
|
+
self._bg: list[asyncio.Task] = []
|
|
93
|
+
self.response_store = ResponseStore(store, cfg.protocols.responses_store)
|
|
94
|
+
self.loop: asyncio.AbstractEventLoop | None = None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _json(status: int, body: dict[str, Any], headers: dict[str, str] | None = None) -> JSONResponse:
|
|
98
|
+
return JSONResponse(body, status_code=status, headers=headers)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _no_eligible_response(dec: Decision) -> JSONResponse:
|
|
102
|
+
status = 404 if dec.outcome == "unknown_model" else 503 if dec.outcome == "admission_rejected" else 422
|
|
103
|
+
body = error_body(
|
|
104
|
+
"; ".join(dec.reasons) or "no eligible deployment",
|
|
105
|
+
code="no_eligible_deployment" if dec.outcome != "unknown_model" else "model_not_found",
|
|
106
|
+
param="model",
|
|
107
|
+
modelsaar={
|
|
108
|
+
"request_id": dec.request_id,
|
|
109
|
+
"blockers": dec.exclusions,
|
|
110
|
+
"remedies": dec.remedies,
|
|
111
|
+
"requirements": dec.requirements,
|
|
112
|
+
},
|
|
113
|
+
)
|
|
114
|
+
headers = {"X-ModelSaar-Request-Id": dec.request_id}
|
|
115
|
+
if status == 503:
|
|
116
|
+
headers["Retry-After"] = "2"
|
|
117
|
+
body["error"]["code"] = "admission_rejected"
|
|
118
|
+
return _json(status, body, headers)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
async def _read_json(request: Request, limit: int) -> dict[str, Any]:
|
|
122
|
+
"""Read a JSON object body of at most ``limit`` bytes (``server.max_request_bytes``). A declared
|
|
123
|
+
``Content-Length`` above the limit is refused before any byte is read; a streamed/chunked body is
|
|
124
|
+
read incrementally and refused as soon as the limit is exceeded, so the gateway never buffers more
|
|
125
|
+
than ``limit`` bytes of one request."""
|
|
126
|
+
cl = request.headers.get("content-length")
|
|
127
|
+
if cl and cl.isdigit() and int(cl) > limit:
|
|
128
|
+
raise ProtocolError("request body too large", status=413)
|
|
129
|
+
chunks: list[bytes] = []
|
|
130
|
+
size = 0
|
|
131
|
+
async for chunk in request.stream():
|
|
132
|
+
size += len(chunk)
|
|
133
|
+
if size > limit:
|
|
134
|
+
raise ProtocolError("request body too large", status=413)
|
|
135
|
+
chunks.append(chunk)
|
|
136
|
+
raw = b"".join(chunks)
|
|
137
|
+
try:
|
|
138
|
+
data = json.loads(raw)
|
|
139
|
+
except json.JSONDecodeError as e:
|
|
140
|
+
raise ProtocolError(f"invalid JSON body: {e.msg}") from e
|
|
141
|
+
if not isinstance(data, dict):
|
|
142
|
+
raise ProtocolError("request body must be a JSON object")
|
|
143
|
+
return data
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _require_caller(state: GatewayState, request: Request) -> str:
|
|
147
|
+
caller = state.auth.caller(dict(request.headers))
|
|
148
|
+
if not caller:
|
|
149
|
+
raise ProtocolError("missing or invalid API key", status=401, code="authentication_error")
|
|
150
|
+
return caller
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _require_admin(state: GatewayState, request: Request) -> None:
|
|
154
|
+
if not state.auth.is_admin(dict(request.headers)):
|
|
155
|
+
raise ProtocolError("admin key required", status=403, code="permission_error")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# --------------------------------------------------------------------------- #
|
|
159
|
+
# Chat completions
|
|
160
|
+
# --------------------------------------------------------------------------- #
|
|
161
|
+
async def chat_completions(request: Request) -> Response:
|
|
162
|
+
state: GatewayState = request.app.state.gw
|
|
163
|
+
router = state.router # snapshot for this request
|
|
164
|
+
state.requests_total += 1
|
|
165
|
+
try:
|
|
166
|
+
caller = _require_caller(state, request)
|
|
167
|
+
body = await _read_json(request, state.cfg.server.max_request_bytes)
|
|
168
|
+
req = parse_chat_request(body)
|
|
169
|
+
except ProtocolError as e:
|
|
170
|
+
state.requests_failed += 1
|
|
171
|
+
return _json(e.status, e.body())
|
|
172
|
+
|
|
173
|
+
return await _chat_core(state, router, caller, dict(request.headers), body, req)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
async def _chat_core(
|
|
177
|
+
state: GatewayState,
|
|
178
|
+
router: Router,
|
|
179
|
+
caller: str,
|
|
180
|
+
req_headers: dict[str, str],
|
|
181
|
+
body: dict[str, Any],
|
|
182
|
+
req: Any,
|
|
183
|
+
protocol: str = "chat",
|
|
184
|
+
protocol_notes: list[str] | None = None,
|
|
185
|
+
) -> Response:
|
|
186
|
+
"""Route and dispatch one validated chat-completions body. Shared by ``/v1/chat/completions`` and by
|
|
187
|
+
the protocol translations (``/v1/responses``, ``/v1/messages``), which hand in an already translated
|
|
188
|
+
body: every protocol goes through the same eligibility, admission, failover and commitment rules."""
|
|
189
|
+
|
|
190
|
+
def _mark(dec: Decision) -> None:
|
|
191
|
+
if protocol != "chat":
|
|
192
|
+
dec.endpoint = protocol
|
|
193
|
+
dec.compat["protocol"] = f"{protocol}: translated to the chat path (stateless, fail-closed)"
|
|
194
|
+
if protocol_notes:
|
|
195
|
+
dec.compat["protocol_notes"] = "; ".join(protocol_notes)
|
|
196
|
+
|
|
197
|
+
try:
|
|
198
|
+
dec = await router.route_chat(body, req_headers, caller)
|
|
199
|
+
except NoEligibleDeployment as e:
|
|
200
|
+
state.requests_failed += 1
|
|
201
|
+
_mark(e.decision)
|
|
202
|
+
return _no_eligible_response(e.decision)
|
|
203
|
+
_mark(dec)
|
|
204
|
+
|
|
205
|
+
base_headers = {"X-ModelSaar-Request-Id": dec.request_id}
|
|
206
|
+
attempts = 0
|
|
207
|
+
max_attempts = 1 + (state.cfg.routing.max_failover_attempts if state.cfg.routing.pre_commit_failover else 0)
|
|
208
|
+
tried: list[str] = []
|
|
209
|
+
candidate_ids = [c["deployment"] for c in dec.candidates]
|
|
210
|
+
|
|
211
|
+
while True:
|
|
212
|
+
dep_id = dec.chosen
|
|
213
|
+
dep = router.registry.get(dep_id)
|
|
214
|
+
if dep is None:
|
|
215
|
+
state.requests_failed += 1
|
|
216
|
+
dec.outcome = "internal_error"
|
|
217
|
+
router.record(dec)
|
|
218
|
+
return _json(500, error_body("selected deployment vanished", code="internal_error"), base_headers)
|
|
219
|
+
adapter = router.adapters[dep.backend_id]
|
|
220
|
+
attempts += 1
|
|
221
|
+
tried.append(dep_id)
|
|
222
|
+
# Client-compatibility hint `cache_prompt`: decided per backend path BEFORE anything is sent. `true` is
|
|
223
|
+
# advisory (recorded, not forwarded); `false` is refused unless this path can guarantee a cache bypass.
|
|
224
|
+
if req.cache_prompt is not None:
|
|
225
|
+
accepted, note = adapter.cache_prompt_policy(req.cache_prompt)
|
|
226
|
+
dec.compat["cache_prompt"] = f"{dep_id}: {note}"
|
|
227
|
+
if not accepted:
|
|
228
|
+
state.requests_failed += 1
|
|
229
|
+
dec.outcome = "unsupported_capability"
|
|
230
|
+
dec.outcome_detail = note
|
|
231
|
+
router.record(dec)
|
|
232
|
+
return _json(
|
|
233
|
+
400,
|
|
234
|
+
error_body(note, code="unsupported_capability", param="cache_prompt", modelsaar={"request_id": dec.request_id, "deployment": dep_id}),
|
|
235
|
+
base_headers,
|
|
236
|
+
)
|
|
237
|
+
# Attribution follows the deployment actually dispatched to (per attempt, not once).
|
|
238
|
+
response_model = dec.requested_model if state.cfg.server.response_model_field == "requested" else dep_id
|
|
239
|
+
try:
|
|
240
|
+
reservation = await router.admission.acquire(dep, timeout=None)
|
|
241
|
+
except AdmissionRejected as e:
|
|
242
|
+
# Scheduling across hosts: a verified replica of the same model on another backend may take the
|
|
243
|
+
# request (nothing has been dispatched). Never for a pinned or continuity-bound request.
|
|
244
|
+
spill = next((r for r in dec.scheduling.get("replicas", []) if r not in tried), None) if dec.failover_allowed else None
|
|
245
|
+
if spill:
|
|
246
|
+
dec.reasons.append(f"replica scheduling: admission refused {dep_id} ({e.message}); spilling over to replica {spill}")
|
|
247
|
+
dec.chosen = spill
|
|
248
|
+
continue
|
|
249
|
+
state.requests_failed += 1
|
|
250
|
+
dec.outcome = "admission_rejected"
|
|
251
|
+
dec.outcome_detail = e.message
|
|
252
|
+
router.record(dec)
|
|
253
|
+
return _json(
|
|
254
|
+
e.status,
|
|
255
|
+
error_body(e.message, code="admission_rejected", modelsaar={"request_id": dec.request_id, "deployment": dep_id}),
|
|
256
|
+
{**base_headers, "Retry-After": "2"},
|
|
257
|
+
)
|
|
258
|
+
headers = {**base_headers, "X-ModelSaar-Deployment": dep_id, "X-ModelSaar-Profile": dec.profile}
|
|
259
|
+
circuit = router.admission.circuit(dep.backend_id)
|
|
260
|
+
try:
|
|
261
|
+
# Record what the adapter path changes (typed, allow-listed translations only).
|
|
262
|
+
translate = getattr(adapter, "translate_chat_body", None)
|
|
263
|
+
if translate:
|
|
264
|
+
_, notes = translate(body)
|
|
265
|
+
if notes:
|
|
266
|
+
dec.translation_notes = [f"{dep_id}: {n}" for n in notes]
|
|
267
|
+
if req.stream:
|
|
268
|
+
upstream: UpstreamStream = await adapter.chat(dep, body, stream=True, timeout=state.cfg.server.request_timeout_s)
|
|
269
|
+
if upstream.status >= 500 or upstream.status in (502, 503, 504):
|
|
270
|
+
# Nothing has been committed to the client yet: safe, bounded failover.
|
|
271
|
+
text = (await upstream.aread())[:300]
|
|
272
|
+
await upstream.close()
|
|
273
|
+
raise AdapterError(f"upstream {upstream.status}: {redact(text.decode('utf-8', 'replace'))}", status=502, retryable=True)
|
|
274
|
+
if upstream.status != 200:
|
|
275
|
+
text = await upstream.aread()
|
|
276
|
+
await upstream.close()
|
|
277
|
+
await reservation.release()
|
|
278
|
+
dec.outcome = "upstream_error"
|
|
279
|
+
dec.outcome_detail = f"upstream {upstream.status}"
|
|
280
|
+
router.record(dec)
|
|
281
|
+
try:
|
|
282
|
+
payload = json.loads(text)
|
|
283
|
+
except Exception:
|
|
284
|
+
payload = error_body(redact(text.decode("utf-8", "replace")[:500]), code="upstream_error")
|
|
285
|
+
return _json(upstream.status, payload, headers)
|
|
286
|
+
ctype = (upstream.headers.get("content-type") or "").lower()
|
|
287
|
+
if "text/event-stream" not in ctype:
|
|
288
|
+
# A 200 that is not an SSE stream (proxy HTML page, JSON error with 200) is not a
|
|
289
|
+
# completion. Nothing has been sent to the client: typed error, no pin, no success.
|
|
290
|
+
text = (await upstream.aread())[:300]
|
|
291
|
+
await upstream.close()
|
|
292
|
+
raise AdapterError(
|
|
293
|
+
f"upstream returned 200 with content-type {ctype or 'missing'!r} instead of text/event-stream",
|
|
294
|
+
status=502,
|
|
295
|
+
retryable=False,
|
|
296
|
+
kind="bad_envelope",
|
|
297
|
+
)
|
|
298
|
+
# Circuit success and session pinning are recorded once the stream completes (see _relay).
|
|
299
|
+
return StreamingResponse(
|
|
300
|
+
_relay(state, router, dec, dep_id, upstream, reservation, response_model, caller),
|
|
301
|
+
status_code=200,
|
|
302
|
+
media_type="text/event-stream",
|
|
303
|
+
headers={**headers, "Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
|
304
|
+
)
|
|
305
|
+
else:
|
|
306
|
+
resp: UpstreamResponse = await adapter.chat(dep, body, stream=False, timeout=state.cfg.server.request_timeout_s)
|
|
307
|
+
await reservation.release()
|
|
308
|
+
if resp.status >= 500:
|
|
309
|
+
raise AdapterError(f"upstream {resp.status}", status=502, retryable=True)
|
|
310
|
+
if resp.status != 200:
|
|
311
|
+
dec.outcome = "upstream_error"
|
|
312
|
+
dec.outcome_detail = f"upstream {resp.status}"
|
|
313
|
+
router.record(dec)
|
|
314
|
+
return _json(resp.status, resp.body, headers)
|
|
315
|
+
why = _envelope_problem(resp.body)
|
|
316
|
+
if why:
|
|
317
|
+
raise AdapterError(f"upstream returned 200 but {why}", status=502, retryable=False, kind="bad_envelope")
|
|
318
|
+
if circuit:
|
|
319
|
+
circuit.record_success()
|
|
320
|
+
stages = dec.cascade.get("stages")
|
|
321
|
+
if stages and dep_id in stages:
|
|
322
|
+
# Cascade: a structurally unusable answer from an earlier stage is discarded (nothing was
|
|
323
|
+
# sent to the client yet) and the next stage answers. The last stage's answer is returned
|
|
324
|
+
# as it is, with the trace saying whether it passed.
|
|
325
|
+
why = acceptance_problem(body, resp.body, tuple(dec.cascade.get("escalate_on") or ()))
|
|
326
|
+
nxt = next((s_ for s_ in stages[stages.index(dep_id) + 1 :] if s_ not in tried), None)
|
|
327
|
+
dec.cascade["trace"].append({"deployment": dep_id, "accepted": why is None, "reason": why or "", "ms": round(resp.elapsed_ms)})
|
|
328
|
+
if why and nxt:
|
|
329
|
+
dec.reasons.append(f"cascade: {dep_id} answered but {why}; escalating to {nxt}")
|
|
330
|
+
dec.chosen = nxt
|
|
331
|
+
continue
|
|
332
|
+
headers["X-ModelSaar-Cascade"] = f"stages={len(dec.cascade['trace'])}; accepted={'true' if why is None else 'false'}"
|
|
333
|
+
out = dict(resp.body)
|
|
334
|
+
out["model"] = response_model
|
|
335
|
+
router.pin_session(dec, caller, dep_id)
|
|
336
|
+
_remember_tool_calls(router, caller, dep_id, out)
|
|
337
|
+
dec.outcome = "ok"
|
|
338
|
+
dec.outcome_detail = f"{resp.elapsed_ms:.0f}ms"
|
|
339
|
+
router.record(dec)
|
|
340
|
+
return _json(200, out, headers)
|
|
341
|
+
except Exception as e: # noqa: BLE001 - every failure path must release the slot
|
|
342
|
+
if isinstance(e, AdapterError) and e.kind == "timeout":
|
|
343
|
+
# The backend did not answer in time but may still be generating: hold the slot.
|
|
344
|
+
await reservation.mark_uncertain()
|
|
345
|
+
elif isinstance(e, AdapterError) and e.kind == "connect":
|
|
346
|
+
# Proven pre-dispatch failure: nothing reached the runtime, so no weights were loaded.
|
|
347
|
+
await reservation.release(submitted=False)
|
|
348
|
+
else:
|
|
349
|
+
await reservation.release()
|
|
350
|
+
if not isinstance(e, AdapterError):
|
|
351
|
+
state.requests_failed += 1
|
|
352
|
+
dec.outcome = "internal_error"
|
|
353
|
+
dec.outcome_detail = redact(f"{e.__class__.__name__}: {e}")[:200]
|
|
354
|
+
router.record(dec)
|
|
355
|
+
log.exception("unexpected error dispatching to %s", dep_id)
|
|
356
|
+
return _json(500, error_body("internal gateway error", code="internal_error", modelsaar={"request_id": dec.request_id}), headers)
|
|
357
|
+
if circuit:
|
|
358
|
+
circuit.record_failure()
|
|
359
|
+
dec.failover.append({"deployment": dep_id, "error": redact(e.message)[:200], "retryable": e.retryable})
|
|
360
|
+
if e.kind == "unsupported_semantics":
|
|
361
|
+
dec.outcome = "unsupported_semantics"
|
|
362
|
+
router.record(dec)
|
|
363
|
+
return _json(400, error_body(e.message, code="unsupported_semantics", modelsaar={"request_id": dec.request_id}), headers)
|
|
364
|
+
next_id = next((c for c in candidate_ids if c not in tried), None)
|
|
365
|
+
if e.retryable and attempts < max_attempts and next_id and dec.failover_allowed:
|
|
366
|
+
dec.reasons.append(f"failover: {dep_id} failed before response commitment ({e.kind}); trying {next_id}")
|
|
367
|
+
dec.chosen = next_id
|
|
368
|
+
continue
|
|
369
|
+
if e.retryable and next_id and not dec.failover_allowed:
|
|
370
|
+
dec.reasons.append(f"failover refused: {dec.failover_note}")
|
|
371
|
+
state.requests_failed += 1
|
|
372
|
+
dec.outcome = "upstream_bad_response" if e.kind == "bad_envelope" else "upstream_error"
|
|
373
|
+
dec.outcome_detail = redact(e.message)[:200]
|
|
374
|
+
router.record(dec)
|
|
375
|
+
return _json(
|
|
376
|
+
e.status,
|
|
377
|
+
error_body(
|
|
378
|
+
f"backend failed before a response was committed: {redact(e.message)}",
|
|
379
|
+
code="upstream_bad_response" if e.kind == "bad_envelope" else "upstream_error",
|
|
380
|
+
modelsaar={
|
|
381
|
+
"request_id": dec.request_id,
|
|
382
|
+
"deployment": dep_id,
|
|
383
|
+
"failover": dec.failover,
|
|
384
|
+
"failover_allowed": dec.failover_allowed,
|
|
385
|
+
"failover_note": dec.failover_note,
|
|
386
|
+
},
|
|
387
|
+
),
|
|
388
|
+
headers,
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
class _UpstreamStreamError(Exception):
|
|
393
|
+
"""The upstream stream ended abnormally after the response was committed."""
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _envelope_problem(body: Any) -> str | None:
|
|
397
|
+
"""Return why ``body`` is not a chat completion envelope, or None if it is one."""
|
|
398
|
+
if not isinstance(body, dict):
|
|
399
|
+
return "body is not a JSON object"
|
|
400
|
+
if "error" in body and "choices" not in body:
|
|
401
|
+
return "body is an error object"
|
|
402
|
+
choices = body.get("choices")
|
|
403
|
+
if not isinstance(choices, list) or not choices:
|
|
404
|
+
return "choices is missing or empty"
|
|
405
|
+
first = choices[0]
|
|
406
|
+
if not isinstance(first, dict) or not isinstance(first.get("message"), dict):
|
|
407
|
+
return "choices[0].message is missing"
|
|
408
|
+
return None
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _remember_tool_calls(router: Router, caller: str, dep_id: str, resp: dict[str, Any]) -> None:
|
|
412
|
+
ids: list[str] = []
|
|
413
|
+
for ch in resp.get("choices") or []:
|
|
414
|
+
msg = ch.get("message") or {}
|
|
415
|
+
for tc in msg.get("tool_calls") or []:
|
|
416
|
+
if isinstance(tc, dict) and tc.get("id"):
|
|
417
|
+
ids.append(str(tc["id"]))
|
|
418
|
+
if ids:
|
|
419
|
+
router.affinity.remember_tool_calls(caller, ids, dep_id)
|
|
420
|
+
for i in ids:
|
|
421
|
+
router.affinity.remember_tool_calls(caller, [i], dep_id)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
async def _relay(
|
|
425
|
+
state: GatewayState,
|
|
426
|
+
router: Router,
|
|
427
|
+
dec: Decision,
|
|
428
|
+
dep_id: str,
|
|
429
|
+
upstream: UpstreamStream,
|
|
430
|
+
reservation,
|
|
431
|
+
response_model: str,
|
|
432
|
+
caller: str,
|
|
433
|
+
) -> AsyncIterator[bytes]:
|
|
434
|
+
"""Relay upstream SSE to the client. After the first byte the response is committed.
|
|
435
|
+
|
|
436
|
+
Occupancy: the reservation is released only on confirmed completion or a confirmed upstream
|
|
437
|
+
failure (the backend ended the stream). A read timeout or client disconnect leaves the backend
|
|
438
|
+
possibly still generating, so the slot and the pool memory are held as *uncertain* until the
|
|
439
|
+
configured hold expires (admission.uncertain_hold_s) — the same rule as non-streaming timeouts."""
|
|
440
|
+
parser = SSEParser()
|
|
441
|
+
obs = StreamObserver()
|
|
442
|
+
tool_ids: list[str] = []
|
|
443
|
+
completed = False
|
|
444
|
+
uncertain = False
|
|
445
|
+
try:
|
|
446
|
+
async for chunk in upstream.aiter_bytes():
|
|
447
|
+
if obs.first_byte_at is None:
|
|
448
|
+
obs.first_byte_at = time.monotonic()
|
|
449
|
+
for ev in parser.feed(chunk):
|
|
450
|
+
obs.observe(ev)
|
|
451
|
+
if ev.kind == "malformed":
|
|
452
|
+
# Not forwarded: it is not a completion structure. The stream is invalidated below.
|
|
453
|
+
continue
|
|
454
|
+
if ev.kind == "done":
|
|
455
|
+
# The upstream terminal marker is held back: the downstream [DONE] is emitted
|
|
456
|
+
# exactly once, after validation, so any error frame precedes it.
|
|
457
|
+
continue
|
|
458
|
+
obj = ev.json()
|
|
459
|
+
if obj:
|
|
460
|
+
for ch in obj.get("choices") or []:
|
|
461
|
+
for tc in (ch.get("delta") or {}).get("tool_calls") or []:
|
|
462
|
+
if isinstance(tc, dict) and tc.get("id"):
|
|
463
|
+
tool_ids.append(str(tc["id"]))
|
|
464
|
+
yield rewrite_model_field(ev, response_model)
|
|
465
|
+
for ev in parser.flush():
|
|
466
|
+
obs.observe(ev)
|
|
467
|
+
if ev.kind not in ("malformed", "done"):
|
|
468
|
+
yield rewrite_model_field(ev, response_model)
|
|
469
|
+
problem = obs.completion_problem()
|
|
470
|
+
if problem:
|
|
471
|
+
raise _UpstreamStreamError(problem)
|
|
472
|
+
completed = True
|
|
473
|
+
# Exactly one terminal marker, after every validated event.
|
|
474
|
+
yield b"data: [DONE]\n\n"
|
|
475
|
+
except (asyncio.CancelledError, GeneratorExit):
|
|
476
|
+
# Client went away. The backend may still be generating: hold the slot as uncertain.
|
|
477
|
+
dec.outcome = "client_disconnected"
|
|
478
|
+
dec.outcome_detail = f"after {obs.events} events"
|
|
479
|
+
await reservation.mark_uncertain()
|
|
480
|
+
await upstream.close()
|
|
481
|
+
router.record(dec)
|
|
482
|
+
raise
|
|
483
|
+
except Exception as e: # upstream failure mid-stream: terminate, never switch.
|
|
484
|
+
if isinstance(e, AdapterError) and e.kind == "timeout":
|
|
485
|
+
# The gateway stopped waiting; the backend did not end the stream and may still compute.
|
|
486
|
+
uncertain = True
|
|
487
|
+
dec.outcome = "stream_timeout_after_commit"
|
|
488
|
+
elif isinstance(e, _UpstreamStreamError):
|
|
489
|
+
dec.outcome = "stream_invalid_after_commit" if obs.malformed or not obs.valid_chunks else "stream_truncated_after_commit"
|
|
490
|
+
else:
|
|
491
|
+
dec.outcome = "stream_failed_after_commit"
|
|
492
|
+
dec.outcome_detail = redact(str(e))[:200]
|
|
493
|
+
c = router.admission.circuit(router.registry.get(dep_id).backend_id) if router.registry.get(dep_id) else None
|
|
494
|
+
if c:
|
|
495
|
+
c.record_failure()
|
|
496
|
+
yield sse_error_frame(
|
|
497
|
+
"upstream stream failed after the response was committed; the gateway does not switch models "
|
|
498
|
+
f"mid-response ({redact(str(e))[:160]})",
|
|
499
|
+
code="upstream_stream_error",
|
|
500
|
+
modelsaar={"request_id": dec.request_id, "deployment": dep_id, "events_delivered": obs.events, "outcome": dec.outcome},
|
|
501
|
+
)
|
|
502
|
+
yield b"data: [DONE]\n\n"
|
|
503
|
+
finally:
|
|
504
|
+
if completed:
|
|
505
|
+
dec.outcome = "ok"
|
|
506
|
+
dec.outcome_detail = (
|
|
507
|
+
f"events={obs.events} chunks={obs.valid_chunks} finish={obs.finish_reason} tool_deltas={obs.tool_call_deltas} "
|
|
508
|
+
f"usage={'yes' if obs.usage else 'no'}"
|
|
509
|
+
)
|
|
510
|
+
await reservation.release()
|
|
511
|
+
await upstream.close()
|
|
512
|
+
# Only a validated, complete stream counts as a success for the circuit and for pinning.
|
|
513
|
+
d = router.registry.get(dep_id)
|
|
514
|
+
c = router.admission.circuit(d.backend_id) if d else None
|
|
515
|
+
if c:
|
|
516
|
+
c.record_success()
|
|
517
|
+
router.pin_session(dec, caller, dep_id)
|
|
518
|
+
if tool_ids:
|
|
519
|
+
router.affinity.remember_tool_calls(caller, tool_ids, dep_id)
|
|
520
|
+
for i in tool_ids:
|
|
521
|
+
router.affinity.remember_tool_calls(caller, [i], dep_id)
|
|
522
|
+
router.record(dec)
|
|
523
|
+
elif uncertain:
|
|
524
|
+
await reservation.mark_uncertain()
|
|
525
|
+
await upstream.close()
|
|
526
|
+
router.record(dec)
|
|
527
|
+
elif dec.outcome in ("stream_failed_after_commit", "stream_truncated_after_commit", "stream_invalid_after_commit"):
|
|
528
|
+
await reservation.release()
|
|
529
|
+
await upstream.close()
|
|
530
|
+
router.record(dec)
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
# --------------------------------------------------------------------------- #
|
|
534
|
+
# Embeddings
|
|
535
|
+
# --------------------------------------------------------------------------- #
|
|
536
|
+
async def embeddings(request: Request) -> Response:
|
|
537
|
+
state: GatewayState = request.app.state.gw
|
|
538
|
+
router = state.router
|
|
539
|
+
state.requests_total += 1
|
|
540
|
+
try:
|
|
541
|
+
caller = _require_caller(state, request)
|
|
542
|
+
body = await _read_json(request, state.cfg.server.max_request_bytes)
|
|
543
|
+
parse_embeddings_request(body)
|
|
544
|
+
media = embedding_media_items(body)
|
|
545
|
+
except ProtocolError as e:
|
|
546
|
+
state.requests_failed += 1
|
|
547
|
+
return _json(e.status, e.body())
|
|
548
|
+
try:
|
|
549
|
+
dec = await router.route_embeddings(body, caller)
|
|
550
|
+
except NoEligibleDeployment as e:
|
|
551
|
+
state.requests_failed += 1
|
|
552
|
+
return _no_eligible_response(e.decision)
|
|
553
|
+
dep = router.registry.get(dec.chosen) # type: ignore[arg-type]
|
|
554
|
+
adapter = router.adapters[dep.backend_id]
|
|
555
|
+
headers = {"X-ModelSaar-Request-Id": dec.request_id, "X-ModelSaar-Deployment": dep.id}
|
|
556
|
+
contract = next((c for c in state.cfg.embeddings if c.alias == dec.alias), None) if dec.alias else None
|
|
557
|
+
problem = router.embedding_request_problem(body, contract, dep)
|
|
558
|
+
if problem:
|
|
559
|
+
state.requests_failed += 1
|
|
560
|
+
dec.outcome = "unsupported_contract_option"
|
|
561
|
+
dec.outcome_detail = problem
|
|
562
|
+
router.record(dec)
|
|
563
|
+
return _json(400, error_body(problem, code="unsupported_contract_option", modelsaar={"request_id": dec.request_id}), headers)
|
|
564
|
+
if media is not None:
|
|
565
|
+
# Multimodal items: the contract must list each modality and the deployment must be able to take it.
|
|
566
|
+
used = sorted({it["modality"] for it in media})
|
|
567
|
+
allowed = set(contract.modalities) if contract else {"text", "image", "audio", "video"}
|
|
568
|
+
missing = [m for m in used if m not in allowed]
|
|
569
|
+
cap_for = {"image": "vision", "audio": "audio_in", "video": "video_in"}
|
|
570
|
+
lacking = [f"{m} ({cap_for[m]} is {dep.cap(cap_for[m])})" for m in used if m in cap_for and dep.cap(cap_for[m]) != "supported"]
|
|
571
|
+
problem = (
|
|
572
|
+
f"embeddings alias {contract.alias!r} is a {'/'.join(contract.modalities)} contract; it does not accept {', '.join(missing)} items "
|
|
573
|
+
"(add the modality to embeddings[].modalities only if the index was built with this model's multimodal space)"
|
|
574
|
+
if missing
|
|
575
|
+
else f"{dep.id} cannot embed {', '.join(lacking)}; a text-only embedding model is never given media"
|
|
576
|
+
if lacking
|
|
577
|
+
else None
|
|
578
|
+
)
|
|
579
|
+
if problem:
|
|
580
|
+
state.requests_failed += 1
|
|
581
|
+
dec.outcome = "unsupported_contract_option"
|
|
582
|
+
dec.outcome_detail = problem
|
|
583
|
+
router.record(dec)
|
|
584
|
+
return _json(400 if missing else 422, error_body(problem, code="unsupported_contract_option" if missing else "no_eligible_deployment", modelsaar={"request_id": dec.request_id, "deployment": dep.id}), headers)
|
|
585
|
+
try:
|
|
586
|
+
reservation = await router.admission.acquire(dep)
|
|
587
|
+
except AdmissionRejected as e:
|
|
588
|
+
dec.outcome = "admission_rejected"
|
|
589
|
+
router.record(dec)
|
|
590
|
+
return _json(e.status, error_body(e.message, code="admission_rejected"), headers)
|
|
591
|
+
try:
|
|
592
|
+
# Same deadline rule as chat: the server request timeout or the backend timeout, whichever is tighter.
|
|
593
|
+
if media is None:
|
|
594
|
+
resp = await adapter.embeddings(dep, body, timeout=state.cfg.server.request_timeout_s)
|
|
595
|
+
else:
|
|
596
|
+
resp = await _embed_items(adapter, dep, media, state.cfg.server.request_timeout_s)
|
|
597
|
+
except AdapterError as e:
|
|
598
|
+
if e.kind == "timeout":
|
|
599
|
+
# The backend may still be computing: hold the slot/memory as uncertain, do not release.
|
|
600
|
+
await reservation.mark_uncertain()
|
|
601
|
+
else:
|
|
602
|
+
await reservation.release(submitted=e.kind not in ("connect", "unsupported"))
|
|
603
|
+
state.requests_failed += 1
|
|
604
|
+
dec.outcome = "upstream_timeout" if e.kind == "timeout" else "unsupported_backend" if e.kind == "unsupported" else "upstream_error"
|
|
605
|
+
dec.outcome_detail = redact(e.message)[:200]
|
|
606
|
+
router.record(dec)
|
|
607
|
+
return _json(e.status, error_body(redact(e.message), code=dec.outcome, modelsaar={"request_id": dec.request_id, "deployment": dep.id}), headers)
|
|
608
|
+
except Exception as e: # noqa: BLE001 - every failure path must account for the slot
|
|
609
|
+
await reservation.release()
|
|
610
|
+
state.requests_failed += 1
|
|
611
|
+
dec.outcome = "internal_error"
|
|
612
|
+
dec.outcome_detail = redact(f"{e.__class__.__name__}: {e}")[:200]
|
|
613
|
+
router.record(dec)
|
|
614
|
+
log.exception("unexpected error in embeddings dispatch to %s", dep.id)
|
|
615
|
+
return _json(500, error_body("internal gateway error", code="internal_error", modelsaar={"request_id": dec.request_id}), headers)
|
|
616
|
+
await reservation.release()
|
|
617
|
+
if resp.status != 200:
|
|
618
|
+
dec.outcome = "upstream_error"
|
|
619
|
+
router.record(dec)
|
|
620
|
+
return _json(resp.status, resp.body, headers)
|
|
621
|
+
expected_dims = (contract.dimensions if contract else None) or dep.embedding_dimensions
|
|
622
|
+
violation = _embedding_problem(resp.body, _embedding_input_count(body.get("input")), expected_dims, contract.normalized if contract else None)
|
|
623
|
+
if violation:
|
|
624
|
+
state.requests_failed += 1
|
|
625
|
+
dec.outcome = "embedding_contract_violation"
|
|
626
|
+
dec.outcome_detail = violation
|
|
627
|
+
router.record(dec)
|
|
628
|
+
return _json(
|
|
629
|
+
502,
|
|
630
|
+
error_body(
|
|
631
|
+
f"backend output violates the embedding contract: {violation}",
|
|
632
|
+
code="embedding_contract_violation",
|
|
633
|
+
modelsaar={"request_id": dec.request_id, "deployment": dep.id},
|
|
634
|
+
),
|
|
635
|
+
headers,
|
|
636
|
+
)
|
|
637
|
+
out = dict(resp.body)
|
|
638
|
+
out["model"] = dec.requested_model if state.cfg.server.response_model_field == "requested" else dep.id
|
|
639
|
+
if contract:
|
|
640
|
+
router.record_embedding_identity(contract.alias, dep)
|
|
641
|
+
dec.outcome = "ok"
|
|
642
|
+
router.record(dec)
|
|
643
|
+
return _json(200, out, headers)
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
# --------------------------------------------------------------------------- #
|
|
647
|
+
# Decisions (decision models: Ollama System One)
|
|
648
|
+
# --------------------------------------------------------------------------- #
|
|
649
|
+
async def decisions(request: Request) -> Response:
|
|
650
|
+
"""``POST /v1/decisions``: typed questions about a state, answered by a decision model with
|
|
651
|
+
per-option probabilities (no generated text). Contract: ``protocol/decisions.py``."""
|
|
652
|
+
state: GatewayState = request.app.state.gw
|
|
653
|
+
router = state.router
|
|
654
|
+
state.requests_total += 1
|
|
655
|
+
try:
|
|
656
|
+
caller = _require_caller(state, request)
|
|
657
|
+
body = await _read_json(request, state.cfg.server.max_request_bytes)
|
|
658
|
+
req = parse_decisions_request(body)
|
|
659
|
+
except ProtocolError as e:
|
|
660
|
+
state.requests_failed += 1
|
|
661
|
+
return _json(e.status, e.body())
|
|
662
|
+
try:
|
|
663
|
+
dec = await router.route_decisions(body, caller, needs_vision=bool(req.images))
|
|
664
|
+
except NoEligibleDeployment as e:
|
|
665
|
+
state.requests_failed += 1
|
|
666
|
+
return _no_eligible_response(e.decision)
|
|
667
|
+
dep = router.registry.get(dec.chosen) # type: ignore[arg-type]
|
|
668
|
+
adapter = router.adapters[dep.backend_id]
|
|
669
|
+
headers = {"X-ModelSaar-Request-Id": dec.request_id, "X-ModelSaar-Deployment": dep.id}
|
|
670
|
+
try:
|
|
671
|
+
reservation = await router.admission.acquire(dep)
|
|
672
|
+
except AdmissionRejected as e:
|
|
673
|
+
dec.outcome = "admission_rejected"
|
|
674
|
+
router.record(dec)
|
|
675
|
+
return _json(e.status, error_body(e.message, code="admission_rejected"), headers)
|
|
676
|
+
try:
|
|
677
|
+
# Same deadline rule as chat and embeddings: the server request timeout or the backend timeout, whichever is tighter.
|
|
678
|
+
resp = await adapter.decide(dep, req.state, req.upstream_questions(), timeout=state.cfg.server.request_timeout_s, images=req.images)
|
|
679
|
+
except AdapterError as e:
|
|
680
|
+
if e.kind == "timeout":
|
|
681
|
+
await reservation.mark_uncertain() # the backend may still be scoring: hold the slot as uncertain
|
|
682
|
+
else:
|
|
683
|
+
await reservation.release(submitted=e.kind not in ("connect", "unsupported"))
|
|
684
|
+
state.requests_failed += 1
|
|
685
|
+
code = "upstream_timeout" if e.kind == "timeout" else "unsupported_backend" if e.kind == "unsupported" else "upstream_error"
|
|
686
|
+
dec.outcome = code
|
|
687
|
+
dec.outcome_detail = redact(e.message)[:200]
|
|
688
|
+
router.record(dec)
|
|
689
|
+
return _json(e.status, error_body(redact(e.message), code=code, modelsaar={"request_id": dec.request_id, "deployment": dep.id}), headers)
|
|
690
|
+
except Exception as e: # noqa: BLE001 - every failure path must account for the slot
|
|
691
|
+
await reservation.release()
|
|
692
|
+
state.requests_failed += 1
|
|
693
|
+
dec.outcome = "internal_error"
|
|
694
|
+
dec.outcome_detail = redact(f"{e.__class__.__name__}: {e}")[:200]
|
|
695
|
+
router.record(dec)
|
|
696
|
+
log.exception("unexpected error in decisions dispatch to %s", dep.id)
|
|
697
|
+
return _json(500, error_body("internal gateway error", code="internal_error", modelsaar={"request_id": dec.request_id}), headers)
|
|
698
|
+
await reservation.release()
|
|
699
|
+
if resp.status != 200:
|
|
700
|
+
state.requests_failed += 1
|
|
701
|
+
err = resp.body.get("error") if isinstance(resp.body, dict) else None
|
|
702
|
+
message = err if isinstance(err, str) else (err.get("message", "") if isinstance(err, dict) else "") or f"upstream HTTP {resp.status}"
|
|
703
|
+
dec.outcome = "upstream_error"
|
|
704
|
+
dec.outcome_detail = redact(str(message))[:200]
|
|
705
|
+
router.record(dec)
|
|
706
|
+
return _json(
|
|
707
|
+
resp.status if 400 <= resp.status < 600 else 502,
|
|
708
|
+
error_body(f"decision model backend: {redact(str(message))}", code="upstream_error", modelsaar={"request_id": dec.request_id, "deployment": dep.id}),
|
|
709
|
+
headers,
|
|
710
|
+
)
|
|
711
|
+
violation = decision_answers_problem(req, resp.body)
|
|
712
|
+
if violation:
|
|
713
|
+
state.requests_failed += 1
|
|
714
|
+
dec.outcome = "decision_contract_violation"
|
|
715
|
+
dec.outcome_detail = violation
|
|
716
|
+
router.record(dec)
|
|
717
|
+
return _json(
|
|
718
|
+
502,
|
|
719
|
+
error_body(
|
|
720
|
+
f"backend answer violates the decision contract: {violation}",
|
|
721
|
+
code="decision_contract_violation",
|
|
722
|
+
modelsaar={"request_id": dec.request_id, "deployment": dep.id},
|
|
723
|
+
),
|
|
724
|
+
headers,
|
|
725
|
+
)
|
|
726
|
+
out = {
|
|
727
|
+
"model": dec.requested_model if state.cfg.server.response_model_field == "requested" else dep.id,
|
|
728
|
+
"answers": resp.body["answers"],
|
|
729
|
+
"usage": resp.body.get("usage") or {},
|
|
730
|
+
}
|
|
731
|
+
dec.outcome = "ok"
|
|
732
|
+
dec.outcome_detail = f"{int(resp.elapsed_ms)}ms"
|
|
733
|
+
router.record(dec)
|
|
734
|
+
return _json(200, out, headers)
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
# --------------------------------------------------------------------------- #
|
|
738
|
+
# Pipelines with separate results: guardrail verdicts, OCR recognition
|
|
739
|
+
# --------------------------------------------------------------------------- #
|
|
740
|
+
async def _role_call(state: GatewayState, router: Router, dec: Decision, chat_body: dict[str, Any]) -> tuple[dict[str, Any] | None, Response | None]:
|
|
741
|
+
"""One non-streaming inference on the role deployment chosen in ``dec`` under normal admission.
|
|
742
|
+
Returns (chat completion, None) or (None, error response). The decision is NOT recorded here."""
|
|
743
|
+
dep = router.registry.get(dec.chosen) # type: ignore[arg-type]
|
|
744
|
+
adapter = router.adapters[dep.backend_id]
|
|
745
|
+
headers = {"X-ModelSaar-Request-Id": dec.request_id, "X-ModelSaar-Deployment": dep.id}
|
|
746
|
+
diag = {"request_id": dec.request_id, "deployment": dep.id}
|
|
747
|
+
try:
|
|
748
|
+
reservation = await router.admission.acquire(dep)
|
|
749
|
+
except AdmissionRejected as e:
|
|
750
|
+
dec.outcome, dec.outcome_detail = "admission_rejected", e.message
|
|
751
|
+
return None, _json(e.status, error_body(e.message, code="admission_rejected", modelsaar=diag), {**headers, "Retry-After": "2"})
|
|
752
|
+
circuit = router.admission.circuit(dep.backend_id)
|
|
753
|
+
try:
|
|
754
|
+
resp = await adapter.chat(dep, chat_body, stream=False, timeout=state.cfg.server.request_timeout_s)
|
|
755
|
+
except AdapterError as e:
|
|
756
|
+
if e.kind == "timeout":
|
|
757
|
+
await reservation.mark_uncertain()
|
|
758
|
+
else:
|
|
759
|
+
await reservation.release(submitted=e.kind != "connect")
|
|
760
|
+
if circuit:
|
|
761
|
+
circuit.record_failure()
|
|
762
|
+
dec.outcome, dec.outcome_detail = "upstream_error", redact(e.message)[:200]
|
|
763
|
+
return None, _json(e.status, error_body(redact(e.message), code="upstream_timeout" if e.kind == "timeout" else "upstream_error", modelsaar=diag), headers)
|
|
764
|
+
except Exception as e: # noqa: BLE001 - every failure path must account for the slot
|
|
765
|
+
await reservation.release()
|
|
766
|
+
dec.outcome, dec.outcome_detail = "internal_error", redact(f"{e.__class__.__name__}: {e}")[:200]
|
|
767
|
+
log.exception("unexpected error in pipeline dispatch to %s", dep.id)
|
|
768
|
+
return None, _json(500, error_body("internal gateway error", code="internal_error", modelsaar=diag), headers)
|
|
769
|
+
await reservation.release()
|
|
770
|
+
if resp.status != 200 or _envelope_problem(resp.body):
|
|
771
|
+
if circuit and resp.status >= 500:
|
|
772
|
+
circuit.record_failure()
|
|
773
|
+
why = f"upstream HTTP {resp.status}" if resp.status != 200 else f"upstream returned 200 but {_envelope_problem(resp.body)}"
|
|
774
|
+
dec.outcome, dec.outcome_detail = "upstream_error", why
|
|
775
|
+
return None, _json(resp.status if 400 <= resp.status < 600 else 502, error_body(why, code="upstream_error", modelsaar=diag), headers)
|
|
776
|
+
if circuit:
|
|
777
|
+
circuit.record_success()
|
|
778
|
+
return resp.body, None
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def _sum_usage(total: dict[str, int], chat: dict[str, Any]) -> None:
|
|
782
|
+
u = chat.get("usage") if isinstance(chat.get("usage"), dict) else {}
|
|
783
|
+
total["input_tokens"] += int(u.get("prompt_tokens") or 0)
|
|
784
|
+
total["output_tokens"] += int(u.get("completion_tokens") or 0)
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
async def guardrails_endpoint(request: Request) -> Response:
|
|
788
|
+
"""``POST /v1/guardrails``: yes/no verdicts from a guardrail-role judge model, one inference per
|
|
789
|
+
criterion, returned as their own object. The gateway reports; it does not block anything."""
|
|
790
|
+
state: GatewayState = request.app.state.gw
|
|
791
|
+
router = state.router
|
|
792
|
+
state.requests_total += 1
|
|
793
|
+
gcfg = state.cfg.pipelines.guardrail
|
|
794
|
+
try:
|
|
795
|
+
_require_caller(state, request)
|
|
796
|
+
body = await _read_json(request, state.cfg.server.max_request_bytes)
|
|
797
|
+
req = parse_guardrail_request(body, gcfg)
|
|
798
|
+
except ProtocolError as e:
|
|
799
|
+
state.requests_failed += 1
|
|
800
|
+
return _json(e.status, e.body())
|
|
801
|
+
bodies = [(name, guardrail_chat_body(req, text, gcfg)) for name, text in req["criteria"]]
|
|
802
|
+
try:
|
|
803
|
+
dec = router.route_role("guardrail", "guardrails", req["model"], max(bodies, key=lambda b: len(b[1]["messages"][-1]["content"]))[1], False, f"guardrails:{len(bodies)} criteria, target={req['target']}")
|
|
804
|
+
except NoEligibleDeployment as e:
|
|
805
|
+
state.requests_failed += 1
|
|
806
|
+
return _no_eligible_response(e.decision)
|
|
807
|
+
headers = {"X-ModelSaar-Request-Id": dec.request_id, "X-ModelSaar-Deployment": dec.chosen or ""}
|
|
808
|
+
results: list[dict[str, Any]] = []
|
|
809
|
+
usage = {"input_tokens": 0, "output_tokens": 0}
|
|
810
|
+
ens = req["ensemble"]
|
|
811
|
+
members = [dec.chosen]
|
|
812
|
+
if ens:
|
|
813
|
+
# Bounded ensemble over a closed (yes/no) verdict: several judge deployments, one policy.
|
|
814
|
+
members = [c["deployment"] for c in dec.candidates][: ens["members"]]
|
|
815
|
+
if dec.explicit or len(members) < ens["members"] or not 2 <= ens["members"] <= state.cfg.pipelines.ensemble.max_members or ens["policy"] == "plurality":
|
|
816
|
+
state.requests_failed += 1
|
|
817
|
+
why = (
|
|
818
|
+
"an ensemble needs model 'auto'" if dec.explicit
|
|
819
|
+
else f"members must be 2..{state.cfg.pipelines.ensemble.max_members} and policy one of any, all, majority, unanimous" if len(members) >= ens["members"] or ens["policy"] == "plurality"
|
|
820
|
+
else f"only {len(members)} eligible guardrail deployment(s) for an ensemble of {ens['members']}; a judge is never asked twice to fake a quorum"
|
|
821
|
+
)
|
|
822
|
+
dec.outcome, dec.outcome_detail = "insufficient_members", why
|
|
823
|
+
router.record(dec)
|
|
824
|
+
return _json(422, error_body(why, code="insufficient_members", modelsaar={"request_id": dec.request_id, "eligible": members}), headers)
|
|
825
|
+
headers["X-ModelSaar-Deployment"] = ",".join(members)
|
|
826
|
+
for name, chat_body in bodies:
|
|
827
|
+
votes: dict[str, str] = {}
|
|
828
|
+
for member in members:
|
|
829
|
+
dec.chosen = member
|
|
830
|
+
chat, err = await _role_call(state, router, dec, chat_body)
|
|
831
|
+
if err is not None:
|
|
832
|
+
state.requests_failed += 1
|
|
833
|
+
router.record(dec)
|
|
834
|
+
return err
|
|
835
|
+
verdict, problem = parse_guardrail_answer(chat)
|
|
836
|
+
if verdict is None:
|
|
837
|
+
state.requests_failed += 1
|
|
838
|
+
dec.outcome, dec.outcome_detail = "guardrail_contract_violation", f"{name}: {problem}"
|
|
839
|
+
router.record(dec)
|
|
840
|
+
return _json(
|
|
841
|
+
502,
|
|
842
|
+
error_body(f"judge answer for criterion {name!r} is not a verdict: {problem}", code="guardrail_contract_violation", modelsaar={"request_id": dec.request_id, "deployment": dec.chosen}),
|
|
843
|
+
headers,
|
|
844
|
+
)
|
|
845
|
+
_sum_usage(usage, chat)
|
|
846
|
+
votes[member] = verdict
|
|
847
|
+
if ens:
|
|
848
|
+
winner, _ = ensemble_decide(list(votes.values()), ens["policy"], positive="yes")
|
|
849
|
+
results.append({"criterion": name, "flagged": winner == "yes", "score": winner if winner in ("yes", "no") else "undecided", "votes": votes, "policy": ens["policy"]})
|
|
850
|
+
else:
|
|
851
|
+
results.append({"criterion": name, "flagged": verdict == "yes", "score": verdict})
|
|
852
|
+
dec.chosen = members[0]
|
|
853
|
+
dec.outcome = "ok"
|
|
854
|
+
dec.outcome_detail = f"{len(results)} verdict(s), {sum(1 for r in results if r['flagged'])} flagged"
|
|
855
|
+
router.record(dec)
|
|
856
|
+
return _json(
|
|
857
|
+
200,
|
|
858
|
+
{
|
|
859
|
+
"object": "guardrail.result",
|
|
860
|
+
"model": dec.requested_model if state.cfg.server.response_model_field == "requested" else dec.chosen,
|
|
861
|
+
"target": req["target"],
|
|
862
|
+
"flagged": any(r["flagged"] for r in results),
|
|
863
|
+
"results": results,
|
|
864
|
+
"usage": usage,
|
|
865
|
+
},
|
|
866
|
+
headers,
|
|
867
|
+
)
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
async def vote_endpoint(request: Request) -> Response:
|
|
871
|
+
"""``POST /v1/vote``: a bounded ensemble over a CLOSED set of choices. Up to ``voters`` distinct eligible
|
|
872
|
+
deployments of a chat alias each cast one schema-constrained ballot; the tally and every ballot are
|
|
873
|
+
returned. No free-text answer is aggregated, and a tie or unmet threshold is reported as undecided."""
|
|
874
|
+
state: GatewayState = request.app.state.gw
|
|
875
|
+
router = state.router
|
|
876
|
+
state.requests_total += 1
|
|
877
|
+
ecfg = state.cfg.pipelines.ensemble
|
|
878
|
+
try:
|
|
879
|
+
caller = _require_caller(state, request)
|
|
880
|
+
body = await _read_json(request, state.cfg.server.max_request_bytes)
|
|
881
|
+
req = parse_vote_request(body, ecfg)
|
|
882
|
+
chat_body = vote_chat_body(req, ecfg)
|
|
883
|
+
parse_chat_request(chat_body)
|
|
884
|
+
except ProtocolError as e:
|
|
885
|
+
state.requests_failed += 1
|
|
886
|
+
return _json(e.status, e.body())
|
|
887
|
+
try:
|
|
888
|
+
dec = await router.route_chat(chat_body, {}, caller)
|
|
889
|
+
except NoEligibleDeployment as e:
|
|
890
|
+
state.requests_failed += 1
|
|
891
|
+
e.decision.endpoint = "vote"
|
|
892
|
+
return _no_eligible_response(e.decision)
|
|
893
|
+
dec.endpoint = "vote"
|
|
894
|
+
voters = [c["deployment"] for c in dec.candidates][: req["voters"]]
|
|
895
|
+
headers = {"X-ModelSaar-Request-Id": dec.request_id, "X-ModelSaar-Deployment": ",".join(voters)}
|
|
896
|
+
if dec.explicit or len(voters) < 2:
|
|
897
|
+
state.requests_failed += 1
|
|
898
|
+
why = "voting needs a chat alias with at least two eligible deployments that have a verified json_schema capability" + (" (an explicit deployment is one voter)" if dec.explicit else f" ({len(voters)} eligible)")
|
|
899
|
+
dec.outcome, dec.outcome_detail = "insufficient_members", why
|
|
900
|
+
router.record(dec)
|
|
901
|
+
return _json(422, error_body(why, code="insufficient_members", modelsaar={"request_id": dec.request_id, "blockers": dec.exclusions}), headers)
|
|
902
|
+
ballots: list[dict[str, Any]] = []
|
|
903
|
+
usage = {"input_tokens": 0, "output_tokens": 0}
|
|
904
|
+
for v in voters:
|
|
905
|
+
dec.chosen = v
|
|
906
|
+
chat, err = await _role_call(state, router, dec, {**chat_body, "model": v})
|
|
907
|
+
if err is not None:
|
|
908
|
+
state.requests_failed += 1
|
|
909
|
+
router.record(dec)
|
|
910
|
+
return err
|
|
911
|
+
_sum_usage(usage, chat)
|
|
912
|
+
choice = parse_ballot(chat, req["choices"])
|
|
913
|
+
ballots.append({"deployment": v, "choice": choice, "valid": choice is not None})
|
|
914
|
+
winner, tally = ensemble_decide([b["choice"] for b in ballots], req["policy"])
|
|
915
|
+
dec.chosen = voters[0]
|
|
916
|
+
dec.outcome = "ok"
|
|
917
|
+
dec.outcome_detail = f"{len(ballots)} ballots, policy {req['policy']}, {'winner decided' if winner else 'undecided'}"
|
|
918
|
+
dec.reasons.append(f"ensemble vote: {len(voters)} of {len(dec.candidates)} eligible deployments asked (bounded by voters={req['voters']})")
|
|
919
|
+
router.record(dec)
|
|
920
|
+
return _json(
|
|
921
|
+
200,
|
|
922
|
+
{"object": "vote.result", "model": dec.requested_model, "policy": req["policy"], "choices": req["choices"], "decided": winner is not None, "winner": winner, "tally": tally, "ballots": ballots, "usage": usage},
|
|
923
|
+
headers,
|
|
924
|
+
)
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
async def ocr_endpoint(request: Request) -> Response:
|
|
928
|
+
"""``POST /v1/ocr``: recognition by an OCR-role vision model (task-prefix prompt + one inline image per
|
|
929
|
+
region). No layout analysis, no fetching. Regions are processed one after another under admission."""
|
|
930
|
+
state: GatewayState = request.app.state.gw
|
|
931
|
+
router = state.router
|
|
932
|
+
state.requests_total += 1
|
|
933
|
+
ocfg = state.cfg.pipelines.ocr
|
|
934
|
+
try:
|
|
935
|
+
_require_caller(state, request)
|
|
936
|
+
body = await _read_json(request, state.cfg.server.max_request_bytes)
|
|
937
|
+
req = parse_ocr_request(body, ocfg)
|
|
938
|
+
except ProtocolError as e:
|
|
939
|
+
state.requests_failed += 1
|
|
940
|
+
return _json(e.status, e.body())
|
|
941
|
+
layout_info: dict[str, Any] | None = None
|
|
942
|
+
if req.get("layout_image"):
|
|
943
|
+
# Layout stage: ask the operator-configured layout service for the regions, crop them here.
|
|
944
|
+
lc = ocfg.layout
|
|
945
|
+
if not lc.url:
|
|
946
|
+
state.requests_failed += 1
|
|
947
|
+
return _json(501, error_body("layout=true needs an operator-run layout service (pipelines.ocr.layout.url); the gateway runs no layout model itself", code="layout_unavailable"))
|
|
948
|
+
if lc.locality != "local" and state.cfg.security.locality_mode == "local_only":
|
|
949
|
+
state.requests_failed += 1
|
|
950
|
+
return _json(422, error_body("the configured layout service is declared remote; refused under security.locality_mode=local_only", code="locality"))
|
|
951
|
+
try:
|
|
952
|
+
page = open_page(req["layout_image"], ocfg) # header only: an oversized page is refused before any decode or call
|
|
953
|
+
answer = bytearray()
|
|
954
|
+
async with httpx.AsyncClient(timeout=lc.timeout_s, follow_redirects=False) as hc:
|
|
955
|
+
async with hc.stream("POST", lc.url, json={**lc.request_extra, lc.image_field: req["layout_image"].split(",", 1)[1]}) as lr:
|
|
956
|
+
if lr.status_code != 200:
|
|
957
|
+
raise ValueError(f"HTTP {lr.status_code}")
|
|
958
|
+
async for chunk in lr.aiter_bytes():
|
|
959
|
+
answer += chunk
|
|
960
|
+
if len(answer) > lc.max_response_bytes:
|
|
961
|
+
raise ValueError(f"answer exceeds pipelines.ocr.layout.max_response_bytes={lc.max_response_bytes}")
|
|
962
|
+
boxes = parse_layout_boxes(json.loads(answer), lc.min_score, lc.max_boxes)
|
|
963
|
+
cropped = crop_regions(page, boxes, ocfg)
|
|
964
|
+
except ProtocolError as e:
|
|
965
|
+
state.requests_failed += 1
|
|
966
|
+
return _json(e.status, e.body())
|
|
967
|
+
except (httpx.HTTPError, ValueError) as e:
|
|
968
|
+
state.requests_failed += 1
|
|
969
|
+
return _json(502, error_body(f"layout service answer is unusable: {redact(str(e))[:200]}", code="layout_contract_violation"))
|
|
970
|
+
req["regions"] = [r for r in cropped if not r.get("skipped")]
|
|
971
|
+
layout_info = {"boxes": len(boxes), "recognised": len(req["regions"]), "skipped": [{"id": r["id"], "label": r["label"], "bbox": r["bbox"]} for r in cropped if r.get("skipped")]}
|
|
972
|
+
if not req["regions"] or len(req["regions"]) > ocfg.max_regions:
|
|
973
|
+
state.requests_failed += 1
|
|
974
|
+
why = "the layout service reported no recognisable region" if not req["regions"] else f"the layout service reported {len(req['regions'])} regions; the limit is pipelines.ocr.max_regions={ocfg.max_regions}"
|
|
975
|
+
return _json(422 if not req["regions"] else 413, error_body(why, code="layout_regions", modelsaar={"layout": layout_info}))
|
|
976
|
+
try:
|
|
977
|
+
dec = router.route_role("ocr", "ocr", req["model"], ocr_chat_body(req["model"], req["regions"][0], ocfg), True, f"ocr:{len(req['regions'])} region(s){' after layout' if layout_info else ''}")
|
|
978
|
+
except NoEligibleDeployment as e:
|
|
979
|
+
state.requests_failed += 1
|
|
980
|
+
return _no_eligible_response(e.decision)
|
|
981
|
+
headers = {"X-ModelSaar-Request-Id": dec.request_id, "X-ModelSaar-Deployment": dec.chosen or ""}
|
|
982
|
+
out: list[dict[str, Any]] = []
|
|
983
|
+
usage = {"input_tokens": 0, "output_tokens": 0}
|
|
984
|
+
for region in req["regions"]:
|
|
985
|
+
chat, err = await _role_call(state, router, dec, ocr_chat_body(req["model"], region, ocfg))
|
|
986
|
+
if err is not None:
|
|
987
|
+
state.requests_failed += 1
|
|
988
|
+
dec.outcome_detail = f"region {region['id']}: {dec.outcome_detail}"
|
|
989
|
+
router.record(dec)
|
|
990
|
+
return err
|
|
991
|
+
text, problem, truncated = parse_ocr_answer(chat)
|
|
992
|
+
if text is None:
|
|
993
|
+
state.requests_failed += 1
|
|
994
|
+
dec.outcome, dec.outcome_detail = "ocr_contract_violation", f"region {region['id']}: {problem}"
|
|
995
|
+
router.record(dec)
|
|
996
|
+
return _json(502, error_body(f"OCR answer for region {region['id']!r} is unusable: {problem}", code="ocr_contract_violation", modelsaar={"request_id": dec.request_id, "deployment": dec.chosen}), headers)
|
|
997
|
+
_sum_usage(usage, chat)
|
|
998
|
+
out.append({"id": region["id"], "task": region["task"], "text": text, "truncated": truncated, **({"label": region["label"], "bbox": region["bbox"]} if layout_info else {})})
|
|
999
|
+
dec.outcome = "ok"
|
|
1000
|
+
dec.outcome_detail = f"{len(out)} region(s)" + (", truncated output present" if any(r["truncated"] for r in out) else "")
|
|
1001
|
+
router.record(dec)
|
|
1002
|
+
result: dict[str, Any] = {
|
|
1003
|
+
"object": "ocr.result",
|
|
1004
|
+
"model": dec.requested_model if state.cfg.server.response_model_field == "requested" else dec.chosen,
|
|
1005
|
+
"layout_analysis": layout_info is not None,
|
|
1006
|
+
"usage": usage,
|
|
1007
|
+
}
|
|
1008
|
+
if layout_info:
|
|
1009
|
+
result["layout"] = layout_info
|
|
1010
|
+
if req["single"]:
|
|
1011
|
+
result.update({"task": out[0]["task"], "text": out[0]["text"], "truncated": out[0]["truncated"]})
|
|
1012
|
+
else:
|
|
1013
|
+
result["regions"] = out
|
|
1014
|
+
return _json(200, result, headers)
|
|
1015
|
+
|
|
1016
|
+
|
|
1017
|
+
async def _embed_items(adapter: Any, dep: Any, items: list[dict[str, Any]], timeout: float) -> UpstreamResponse:
|
|
1018
|
+
"""One vector per item, in order, on ONE deployment (one embedding space): text items through the
|
|
1019
|
+
normal embeddings call, media items through the backend's verified multimodal form. Any failing item
|
|
1020
|
+
fails the whole request; a partial list is never returned."""
|
|
1021
|
+
data: list[dict[str, Any]] = []
|
|
1022
|
+
usage = {"prompt_tokens": 0, "total_tokens": 0}
|
|
1023
|
+
t0 = time.monotonic()
|
|
1024
|
+
for i, it in enumerate(items):
|
|
1025
|
+
if it["modality"] == "text":
|
|
1026
|
+
r = await adapter.embeddings(dep, {"input": it["text"]}, timeout=timeout)
|
|
1027
|
+
else:
|
|
1028
|
+
r = await adapter.embed_media(dep, it["part"], timeout=timeout)
|
|
1029
|
+
rows = r.body.get("data") if isinstance(r.body, dict) else None
|
|
1030
|
+
if r.status != 200 or not isinstance(rows, list) or len(rows) != 1 or not isinstance(rows[0], dict):
|
|
1031
|
+
if r.status == 200:
|
|
1032
|
+
return UpstreamResponse(status=502, headers={}, body=error_body(f"backend returned no single vector for input[{i}] ({it['modality']})", code="embedding_contract_violation"), elapsed_ms=(time.monotonic() - t0) * 1000)
|
|
1033
|
+
return r
|
|
1034
|
+
data.append({"object": "embedding", "index": i, "embedding": rows[0].get("embedding")})
|
|
1035
|
+
u = r.body.get("usage") if isinstance(r.body.get("usage"), dict) else {}
|
|
1036
|
+
usage["prompt_tokens"] += int(u.get("prompt_tokens") or 0)
|
|
1037
|
+
usage["total_tokens"] += int(u.get("total_tokens") or 0)
|
|
1038
|
+
return UpstreamResponse(status=200, headers={}, body={"object": "list", "data": data, "model": dep.model, "usage": usage}, elapsed_ms=(time.monotonic() - t0) * 1000)
|
|
1039
|
+
|
|
1040
|
+
|
|
1041
|
+
def _embedding_input_count(inp: Any) -> int:
|
|
1042
|
+
if isinstance(inp, str):
|
|
1043
|
+
return 1
|
|
1044
|
+
if isinstance(inp, list):
|
|
1045
|
+
if inp and all(isinstance(x, int) for x in inp):
|
|
1046
|
+
return 1 # one token array
|
|
1047
|
+
return len(inp)
|
|
1048
|
+
return 1
|
|
1049
|
+
|
|
1050
|
+
|
|
1051
|
+
def _embedding_problem(body: Any, n_inputs: int, dims: int | None, normalized: bool | None) -> str | None:
|
|
1052
|
+
"""Validate count, indices, dimensions, finiteness and (when the contract says so) unit norm."""
|
|
1053
|
+
import math
|
|
1054
|
+
|
|
1055
|
+
if not isinstance(body, dict) or not isinstance(body.get("data"), list):
|
|
1056
|
+
return "response has no data list"
|
|
1057
|
+
data = body["data"]
|
|
1058
|
+
if len(data) != n_inputs:
|
|
1059
|
+
return f"{len(data)} vectors returned for {n_inputs} inputs"
|
|
1060
|
+
seen_dims: int | None = None
|
|
1061
|
+
for i, item in enumerate(data):
|
|
1062
|
+
if not isinstance(item, dict):
|
|
1063
|
+
return f"data[{i}] is not an object"
|
|
1064
|
+
if item.get("index") != i:
|
|
1065
|
+
return f"data[{i}].index is {item.get('index')!r}"
|
|
1066
|
+
vec = item.get("embedding")
|
|
1067
|
+
if not isinstance(vec, list) or not vec:
|
|
1068
|
+
return f"data[{i}].embedding is not a non-empty list (base64 encodings are not supported)"
|
|
1069
|
+
if not all(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) for v in vec):
|
|
1070
|
+
return f"data[{i}].embedding contains non-finite or non-numeric values"
|
|
1071
|
+
if seen_dims is None:
|
|
1072
|
+
seen_dims = len(vec)
|
|
1073
|
+
elif len(vec) != seen_dims:
|
|
1074
|
+
return f"data[{i}].embedding has {len(vec)} dimensions, data[0] has {seen_dims}"
|
|
1075
|
+
if dims and len(vec) != dims:
|
|
1076
|
+
return f"data[{i}].embedding has {len(vec)} dimensions; contract requires {dims}"
|
|
1077
|
+
if normalized:
|
|
1078
|
+
norm = math.sqrt(sum(v * v for v in vec))
|
|
1079
|
+
if abs(norm - 1.0) > 1e-2:
|
|
1080
|
+
return f"data[{i}].embedding has L2 norm {norm:.3f}; contract declares normalized vectors (set normalized: false if the model does not normalize)"
|
|
1081
|
+
return None
|
|
1082
|
+
|
|
1083
|
+
|
|
1084
|
+
# --------------------------------------------------------------------------- #
|
|
1085
|
+
# Models, health, unsupported protocols
|
|
1086
|
+
# --------------------------------------------------------------------------- #
|
|
1087
|
+
async def list_models(request: Request) -> Response:
|
|
1088
|
+
state: GatewayState = request.app.state.gw
|
|
1089
|
+
try:
|
|
1090
|
+
_require_caller(state, request)
|
|
1091
|
+
except ProtocolError as e:
|
|
1092
|
+
return _json(e.status, e.body())
|
|
1093
|
+
return _json(200, {"object": "list", "data": state.router.models_listing()})
|
|
1094
|
+
|
|
1095
|
+
|
|
1096
|
+
async def healthz(request: Request) -> Response:
|
|
1097
|
+
# Unauthenticated identification contract used by `modelsaar test` and the installer to tell a
|
|
1098
|
+
# ModelSaar gateway from another service on the same port before any key is sent. It is a
|
|
1099
|
+
# collision check, not authentication: anything can imitate it.
|
|
1100
|
+
return _json(200, {"status": "ok", "service": "modelsaar", "version": __version__, "api": "openai-compatible"})
|
|
1101
|
+
|
|
1102
|
+
|
|
1103
|
+
async def readyz(request: Request) -> Response:
|
|
1104
|
+
state: GatewayState = request.app.state.gw
|
|
1105
|
+
healthy = [d for d in state.router.registry.all() if d.healthy and d.enabled]
|
|
1106
|
+
ok = state.ready and bool(healthy)
|
|
1107
|
+
return _json(
|
|
1108
|
+
200 if ok else 503,
|
|
1109
|
+
{
|
|
1110
|
+
"status": "ready" if ok else "not_ready",
|
|
1111
|
+
"registry_version": state.router.registry.version,
|
|
1112
|
+
"healthy_deployments": len(healthy),
|
|
1113
|
+
"last_refresh_error": state.router.last_refresh_error,
|
|
1114
|
+
},
|
|
1115
|
+
)
|
|
1116
|
+
|
|
1117
|
+
|
|
1118
|
+
async def unsupported_protocol(request: Request) -> Response:
|
|
1119
|
+
return _json(
|
|
1120
|
+
501,
|
|
1121
|
+
error_body(
|
|
1122
|
+
f"{request.url.path} is not implemented by ModelSaar. Use /v1/chat/completions, the stateless "
|
|
1123
|
+
"/v1/responses subset or /v1/messages (docs/protocols.md). The gateway does not emulate stateful protocols.",
|
|
1124
|
+
code="unsupported_protocol",
|
|
1125
|
+
),
|
|
1126
|
+
)
|
|
1127
|
+
|
|
1128
|
+
|
|
1129
|
+
# --------------------------------------------------------------------------- #
|
|
1130
|
+
# Protocol translations: Responses (stateless subset) and Anthropic Messages
|
|
1131
|
+
# --------------------------------------------------------------------------- #
|
|
1132
|
+
async def _translated_stream(inner: AsyncIterator[bytes], translator: Any, on_done: Any = None) -> AsyncIterator[bytes]:
|
|
1133
|
+
"""Re-encode the gateway's own validated chat SSE as another protocol's events. The inner iterator is
|
|
1134
|
+
``_relay``: it owns commitment, occupancy and decision recording; a client disconnect or cancellation
|
|
1135
|
+
propagates into it unchanged."""
|
|
1136
|
+
parser = SSEParser()
|
|
1137
|
+
try:
|
|
1138
|
+
async for chunk in inner:
|
|
1139
|
+
for ev in parser.feed(chunk):
|
|
1140
|
+
if ev.kind == "done":
|
|
1141
|
+
frames = translator.finish()
|
|
1142
|
+
if frames and on_done is not None and not getattr(translator, "failed", False):
|
|
1143
|
+
on_done(translator.resp) # persist before the terminal event is sent
|
|
1144
|
+
for frame in frames:
|
|
1145
|
+
yield frame
|
|
1146
|
+
continue
|
|
1147
|
+
obj = ev.json()
|
|
1148
|
+
if not isinstance(obj, dict):
|
|
1149
|
+
continue
|
|
1150
|
+
frames = translator.error(obj) if "error" in obj and "choices" not in obj else translator.feed(obj)
|
|
1151
|
+
for frame in frames:
|
|
1152
|
+
yield frame
|
|
1153
|
+
finally:
|
|
1154
|
+
aclose = getattr(inner, "aclose", None)
|
|
1155
|
+
if aclose:
|
|
1156
|
+
await aclose()
|
|
1157
|
+
|
|
1158
|
+
|
|
1159
|
+
async def _translated_endpoint(request: Request, protocol: str) -> Response:
|
|
1160
|
+
state: GatewayState = request.app.state.gw
|
|
1161
|
+
router = state.router
|
|
1162
|
+
state.requests_total += 1
|
|
1163
|
+
if protocol == "responses":
|
|
1164
|
+
to_chat, from_chat, translator_cls = responses_to_chat, chat_to_response, ResponsesStreamTranslator
|
|
1165
|
+
|
|
1166
|
+
def err(status: int, payload: Any) -> Any:
|
|
1167
|
+
return error_to_responses(payload)
|
|
1168
|
+
else:
|
|
1169
|
+
to_chat, from_chat, translator_cls = messages_to_chat, chat_to_message, MessagesStreamTranslator
|
|
1170
|
+
err = error_to_anthropic
|
|
1171
|
+
rstore = state.response_store if protocol == "responses" else None
|
|
1172
|
+
req_headers = dict(request.headers)
|
|
1173
|
+
save = None
|
|
1174
|
+
try:
|
|
1175
|
+
caller = _require_caller(state, request)
|
|
1176
|
+
body = await _read_json(request, state.cfg.server.max_request_bytes)
|
|
1177
|
+
if rstore is not None and rstore.enabled:
|
|
1178
|
+
chat_body, ctx = to_chat(body, stateful=True)
|
|
1179
|
+
notes = ctx.setdefault("notes", [])
|
|
1180
|
+
root = None
|
|
1181
|
+
if ctx["previous_response_id"]:
|
|
1182
|
+
history, root = rstore.history(ctx["previous_response_id"], caller)
|
|
1183
|
+
sysmsgs = [m for m in chat_body["messages"][:1] if m["role"] == "system" and body.get("instructions") is not None]
|
|
1184
|
+
chat_body["messages"] = [*sysmsgs, *history, *ctx["input_messages"]]
|
|
1185
|
+
notes.append(f"continued from stored response {ctx['previous_response_id']} ({len(history)} replayed messages; stored reasoning items are not replayed)")
|
|
1186
|
+
if ctx["store"] or root:
|
|
1187
|
+
# One conversation chain = one affinity session (keyed by the chain's first response id), so
|
|
1188
|
+
# follow-up turns prefer the deployment that answered before. Hard filters still apply.
|
|
1189
|
+
ctx["response_id"] = "resp_" + uuid.uuid4().hex[:24]
|
|
1190
|
+
req_headers["x-modelsaar-session"] = f"resp-chain:{root or ctx['response_id']}"
|
|
1191
|
+
if ctx["store"]:
|
|
1192
|
+
|
|
1193
|
+
def save(resp_obj: dict[str, Any], dep: str | None = None) -> None:
|
|
1194
|
+
rstore.save(caller, resp_obj, ctx["input_messages"], ctx["previous_response_id"], dep)
|
|
1195
|
+
|
|
1196
|
+
else:
|
|
1197
|
+
chat_body, ctx = to_chat(body)
|
|
1198
|
+
req = parse_chat_request(chat_body)
|
|
1199
|
+
except ProtocolError as e:
|
|
1200
|
+
state.requests_failed += 1
|
|
1201
|
+
return _json(e.status, err(e.status, e.body()))
|
|
1202
|
+
except ResponseStoreError as e:
|
|
1203
|
+
state.requests_failed += 1
|
|
1204
|
+
return _json(e.status, error_body(e.message, code=e.code, param=e.param))
|
|
1205
|
+
resp = await _chat_core(state, router, caller, req_headers, chat_body, req, protocol=protocol, protocol_notes=ctx.get("notes"))
|
|
1206
|
+
keep = {k: v for k, v in resp.headers.items() if k.lower().startswith("x-modelsaar-") or k.lower() == "retry-after"}
|
|
1207
|
+
if isinstance(resp, StreamingResponse):
|
|
1208
|
+
on_done = None
|
|
1209
|
+
if save is not None:
|
|
1210
|
+
|
|
1211
|
+
def on_done(resp_obj: dict[str, Any]) -> None:
|
|
1212
|
+
try:
|
|
1213
|
+
save(resp_obj, keep.get("x-modelsaar-deployment"))
|
|
1214
|
+
except ResponseStoreError as e:
|
|
1215
|
+
log.warning("response not stored: %s", e.message)
|
|
1216
|
+
|
|
1217
|
+
return StreamingResponse(
|
|
1218
|
+
_translated_stream(resp.body_iterator, translator_cls(ctx), on_done),
|
|
1219
|
+
status_code=200,
|
|
1220
|
+
media_type="text/event-stream",
|
|
1221
|
+
headers={**keep, "Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
|
1222
|
+
)
|
|
1223
|
+
try:
|
|
1224
|
+
payload = json.loads(bytes(resp.body))
|
|
1225
|
+
except Exception: # noqa: BLE001 - never forward an unparsed body under another protocol's name
|
|
1226
|
+
payload = error_body("gateway produced an unreadable response", code="internal_error")
|
|
1227
|
+
return _json(500, err(500, payload), keep)
|
|
1228
|
+
if resp.status_code != 200:
|
|
1229
|
+
return _json(resp.status_code, err(resp.status_code, payload), keep)
|
|
1230
|
+
try:
|
|
1231
|
+
out = from_chat(payload, ctx)
|
|
1232
|
+
if save is not None:
|
|
1233
|
+
try:
|
|
1234
|
+
save(out, keep.get("x-modelsaar-deployment"))
|
|
1235
|
+
except ResponseStoreError as e:
|
|
1236
|
+
return _json(e.status, error_body(e.message, code=e.code), keep)
|
|
1237
|
+
return _json(200, out, keep)
|
|
1238
|
+
except ValueError as e:
|
|
1239
|
+
# The backend answered, but the answer cannot be represented faithfully in the requested protocol.
|
|
1240
|
+
state.requests_failed += 1
|
|
1241
|
+
bad = error_body(
|
|
1242
|
+
f"backend answer cannot be represented as a {protocol} response: {e}",
|
|
1243
|
+
code="upstream_bad_response",
|
|
1244
|
+
modelsaar={"request_id": keep.get("x-modelsaar-request-id")},
|
|
1245
|
+
)
|
|
1246
|
+
return _json(502, err(502, bad), keep)
|
|
1247
|
+
|
|
1248
|
+
|
|
1249
|
+
async def responses_endpoint(request: Request) -> Response:
|
|
1250
|
+
return await _translated_endpoint(request, "responses")
|
|
1251
|
+
|
|
1252
|
+
|
|
1253
|
+
async def stored_response(request: Request) -> Response:
|
|
1254
|
+
"""``GET`` / ``DELETE /v1/responses/{id}`` — only with the opt-in local response store; otherwise 501."""
|
|
1255
|
+
state: GatewayState = request.app.state.gw
|
|
1256
|
+
if not state.response_store.enabled:
|
|
1257
|
+
return await unsupported_protocol(request)
|
|
1258
|
+
try:
|
|
1259
|
+
caller = _require_caller(state, request)
|
|
1260
|
+
except ProtocolError as e:
|
|
1261
|
+
return _json(e.status, e.body())
|
|
1262
|
+
rid = request.path_params["response_id"]
|
|
1263
|
+
if request.method == "DELETE":
|
|
1264
|
+
if state.response_store.delete(rid, caller):
|
|
1265
|
+
return _json(200, {"id": rid, "object": "response", "deleted": True})
|
|
1266
|
+
else:
|
|
1267
|
+
obj = state.response_store.get(rid, caller)
|
|
1268
|
+
if obj is not None:
|
|
1269
|
+
return _json(200, obj)
|
|
1270
|
+
return _json(404, error_body(f"response {rid!r} was not found for this API key", code="response_not_found", param="response_id"))
|
|
1271
|
+
|
|
1272
|
+
|
|
1273
|
+
async def messages_endpoint(request: Request) -> Response:
|
|
1274
|
+
return await _translated_endpoint(request, "messages")
|
|
1275
|
+
|
|
1276
|
+
|
|
1277
|
+
# --------------------------------------------------------------------------- #
|
|
1278
|
+
# Admin / inspection
|
|
1279
|
+
# --------------------------------------------------------------------------- #
|
|
1280
|
+
async def admin_status(request: Request) -> Response:
|
|
1281
|
+
state: GatewayState = request.app.state.gw
|
|
1282
|
+
try:
|
|
1283
|
+
_require_admin(state, request)
|
|
1284
|
+
except ProtocolError as e:
|
|
1285
|
+
return _json(e.status, e.body())
|
|
1286
|
+
r = state.router
|
|
1287
|
+
return _json(
|
|
1288
|
+
200,
|
|
1289
|
+
{
|
|
1290
|
+
"version": __version__,
|
|
1291
|
+
"uptime_s": round(time.time() - state.started_at, 1),
|
|
1292
|
+
"config_path": state.cfg.config_path,
|
|
1293
|
+
"config_hash": state.cfg.config_hash,
|
|
1294
|
+
"ready": state.ready,
|
|
1295
|
+
"requests_total": state.requests_total,
|
|
1296
|
+
"requests_failed": state.requests_failed,
|
|
1297
|
+
"registry_version": r.registry.version,
|
|
1298
|
+
"last_refresh_error": r.last_refresh_error,
|
|
1299
|
+
"aliases": {a: r.alias_contract(a) for a in state.cfg.aliases},
|
|
1300
|
+
"deployments": r.registry.snapshot(),
|
|
1301
|
+
"admission": r.admission.stats(),
|
|
1302
|
+
"affinity": r.affinity.stats(),
|
|
1303
|
+
"classifier": r.classifier.stats(),
|
|
1304
|
+
"security": {
|
|
1305
|
+
"host": state.cfg.server.host,
|
|
1306
|
+
"allow_lan": state.cfg.security.allow_lan,
|
|
1307
|
+
"locality_mode": state.cfg.security.locality_mode,
|
|
1308
|
+
"log_prompts": state.cfg.security.log_prompts,
|
|
1309
|
+
"telemetry_opt_in": state.cfg.security.telemetry_opt_in,
|
|
1310
|
+
},
|
|
1311
|
+
},
|
|
1312
|
+
)
|
|
1313
|
+
|
|
1314
|
+
|
|
1315
|
+
async def admin_decisions(request: Request) -> Response:
|
|
1316
|
+
state: GatewayState = request.app.state.gw
|
|
1317
|
+
try:
|
|
1318
|
+
_require_admin(state, request)
|
|
1319
|
+
except ProtocolError as e:
|
|
1320
|
+
return _json(e.status, e.body())
|
|
1321
|
+
if not state.store:
|
|
1322
|
+
return _json(200, {"decisions": []})
|
|
1323
|
+
rid = request.path_params.get("request_id")
|
|
1324
|
+
if rid:
|
|
1325
|
+
d = state.store.get_decision(rid)
|
|
1326
|
+
return _json(200 if d else 404, d or error_body("decision not found", code="not_found"))
|
|
1327
|
+
try:
|
|
1328
|
+
limit = int(request.query_params.get("limit", "50"))
|
|
1329
|
+
except ValueError:
|
|
1330
|
+
return _json(400, error_body("limit must be an integer"))
|
|
1331
|
+
limit = max(1, min(limit, 500))
|
|
1332
|
+
return _json(200, {"decisions": state.store.recent_decisions(limit)})
|
|
1333
|
+
|
|
1334
|
+
|
|
1335
|
+
async def admin_explain(request: Request) -> Response:
|
|
1336
|
+
"""Dry-run routing for a request body without dispatching it."""
|
|
1337
|
+
state: GatewayState = request.app.state.gw
|
|
1338
|
+
try:
|
|
1339
|
+
_require_admin(state, request)
|
|
1340
|
+
body = await _read_json(request, state.cfg.server.max_request_bytes)
|
|
1341
|
+
parse_chat_request(body)
|
|
1342
|
+
except ProtocolError as e:
|
|
1343
|
+
return _json(e.status, e.body())
|
|
1344
|
+
try:
|
|
1345
|
+
dec = await state.router.route_chat(body, dict(request.headers), "explain")
|
|
1346
|
+
dec.outcome = "explain_only"
|
|
1347
|
+
return _json(200, dec.as_dict())
|
|
1348
|
+
except NoEligibleDeployment as e:
|
|
1349
|
+
return _json(200, e.decision.as_dict())
|
|
1350
|
+
|
|
1351
|
+
|
|
1352
|
+
async def admin_refresh(request: Request) -> Response:
|
|
1353
|
+
state: GatewayState = request.app.state.gw
|
|
1354
|
+
try:
|
|
1355
|
+
_require_admin(state, request)
|
|
1356
|
+
except ProtocolError as e:
|
|
1357
|
+
return _json(e.status, e.body())
|
|
1358
|
+
await state.router.refresh()
|
|
1359
|
+
return _json(200, {"registry_version": state.router.registry.version, "error": state.router.last_refresh_error})
|
|
1360
|
+
|
|
1361
|
+
|
|
1362
|
+
async def admin_probe(request: Request) -> Response:
|
|
1363
|
+
"""Run capability probes for one deployment under the gateway's own admission (slots, memory
|
|
1364
|
+
budget, queue). This is the coordinated path `modelsaar probe` uses while a gateway is running,
|
|
1365
|
+
so probe inference never overlaps with serving beyond the configured limits."""
|
|
1366
|
+
state: GatewayState = request.app.state.gw
|
|
1367
|
+
try:
|
|
1368
|
+
_require_admin(state, request)
|
|
1369
|
+
body = await _read_json(request, state.cfg.server.max_request_bytes)
|
|
1370
|
+
except ProtocolError as e:
|
|
1371
|
+
return _json(e.status, e.body())
|
|
1372
|
+
from .probes import PROBE_NAMES, run_probes
|
|
1373
|
+
|
|
1374
|
+
router = state.router
|
|
1375
|
+
dep_id = str(body.get("deployment", ""))
|
|
1376
|
+
dep = router.registry.get(dep_id)
|
|
1377
|
+
if dep is None:
|
|
1378
|
+
return _json(404, error_body(f"deployment {dep_id!r} not found", code="unknown_deployment"))
|
|
1379
|
+
if dep.role != "generative" or not dep.healthy:
|
|
1380
|
+
return _json(422, error_body(f"{dep_id} is not a healthy generative deployment", code="not_probeable"))
|
|
1381
|
+
if state.cfg.security.locality_mode == "local_only" and dep.locality != "local":
|
|
1382
|
+
return _json(422, error_body(f"{dep_id} is not local; probes send prompts and are refused under local_only", code="locality"))
|
|
1383
|
+
which = body.get("which") or None
|
|
1384
|
+
if which is not None and (not isinstance(which, list) or any(w not in PROBE_NAMES for w in which)):
|
|
1385
|
+
return _json(400, error_body(f"which must be a subset of {sorted(PROBE_NAMES)}", code="invalid_request_error"))
|
|
1386
|
+
timeout = float(body.get("timeout") or 120.0)
|
|
1387
|
+
try:
|
|
1388
|
+
reservation = await router.admission.acquire(dep, timeout=None)
|
|
1389
|
+
except AdmissionRejected as e:
|
|
1390
|
+
return _json(e.status, error_body(e.message, code="admission_rejected"), {"Retry-After": "2"})
|
|
1391
|
+
try:
|
|
1392
|
+
rep = await run_probes(router.adapters[dep.backend_id], dep, state.store, which, timeout=timeout)
|
|
1393
|
+
except BaseException:
|
|
1394
|
+
await reservation.release()
|
|
1395
|
+
raise
|
|
1396
|
+
if rep.uncertain:
|
|
1397
|
+
# A probe inference timed out: the runner stopped and the backend may still be computing.
|
|
1398
|
+
# Hold the slot and the pool memory as uncertain (same rule as serving timeouts).
|
|
1399
|
+
await reservation.mark_uncertain()
|
|
1400
|
+
else:
|
|
1401
|
+
await reservation.release()
|
|
1402
|
+
await router.refresh()
|
|
1403
|
+
return _json(200, rep.as_dict())
|
|
1404
|
+
|
|
1405
|
+
|
|
1406
|
+
async def admin_lifecycle(request: Request) -> Response:
|
|
1407
|
+
"""Managed lifecycle (opt-in per backend; docs/lifecycle.md): status, explicit load/unload, lease release."""
|
|
1408
|
+
state: GatewayState = request.app.state.gw
|
|
1409
|
+
lm = state.router.lifecycle
|
|
1410
|
+
try:
|
|
1411
|
+
_require_admin(state, request)
|
|
1412
|
+
if request.method == "GET":
|
|
1413
|
+
return _json(200, lm.status())
|
|
1414
|
+
body = await _read_json(request, 65536)
|
|
1415
|
+
except ProtocolError as e:
|
|
1416
|
+
return _json(e.status, e.body())
|
|
1417
|
+
op = request.path_params.get("op")
|
|
1418
|
+
try:
|
|
1419
|
+
if op == "load":
|
|
1420
|
+
hold = body.get("hold_s")
|
|
1421
|
+
if hold is not None and (isinstance(hold, bool) or not isinstance(hold, (int, float))):
|
|
1422
|
+
return _json(400, error_body("hold_s must be a number of seconds", code="invalid_request_error"))
|
|
1423
|
+
return _json(200, await lm.load(str(body.get("deployment", "")), hold_s=hold, holder=str(body.get("holder") or "admin")[:64]))
|
|
1424
|
+
if op == "unload":
|
|
1425
|
+
return _json(200, await lm.unload(str(body.get("deployment", ""))))
|
|
1426
|
+
if op == "release":
|
|
1427
|
+
return _json(200, lm.release(str(body.get("lease", ""))))
|
|
1428
|
+
except LifecycleError as e:
|
|
1429
|
+
return _json(e.status, error_body(e.message, code=e.code))
|
|
1430
|
+
return _json(404, error_body(f"unknown lifecycle operation {op!r}", code="not_found"))
|
|
1431
|
+
|
|
1432
|
+
|
|
1433
|
+
async def feedback_endpoint(request: Request) -> Response:
|
|
1434
|
+
"""``POST /v1/feedback``: a client's explicit verdict for a request it made (opt-in learning only).
|
|
1435
|
+
Stores one boolean against the request id; never any content."""
|
|
1436
|
+
state: GatewayState = request.app.state.gw
|
|
1437
|
+
try:
|
|
1438
|
+
_require_caller(state, request)
|
|
1439
|
+
body = await _read_json(request, 4096)
|
|
1440
|
+
if set(body) - {"request_id", "success"} or not isinstance(body.get("request_id"), str) or not isinstance(body.get("success"), bool):
|
|
1441
|
+
raise ProtocolError("feedback takes exactly {request_id: string, success: boolean}; free text is not accepted or stored")
|
|
1442
|
+
return _json(200, state.router.learning.feedback(state.router, body["request_id"], body["success"]))
|
|
1443
|
+
except ProtocolError as e:
|
|
1444
|
+
return _json(e.status, e.body())
|
|
1445
|
+
except LearningError as e:
|
|
1446
|
+
return _json(e.status, error_body(e.message, code=e.code))
|
|
1447
|
+
|
|
1448
|
+
|
|
1449
|
+
async def admin_learning(request: Request) -> Response:
|
|
1450
|
+
"""Adaptive learning administration: status, build a policy version, activate, rollback, purge."""
|
|
1451
|
+
state: GatewayState = request.app.state.gw
|
|
1452
|
+
ln = state.router.learning
|
|
1453
|
+
try:
|
|
1454
|
+
_require_admin(state, request)
|
|
1455
|
+
if request.method == "GET":
|
|
1456
|
+
return _json(200, ln.status())
|
|
1457
|
+
body = await _read_json(request, 4096)
|
|
1458
|
+
except ProtocolError as e:
|
|
1459
|
+
return _json(e.status, e.body())
|
|
1460
|
+
op = request.path_params.get("op")
|
|
1461
|
+
try:
|
|
1462
|
+
if op == "build":
|
|
1463
|
+
return _json(200, ln.build(state.router))
|
|
1464
|
+
if op in ("activate", "rollback", "purge"):
|
|
1465
|
+
if op == "activate" and (isinstance(body.get("version"), bool) or not isinstance(body.get("version"), int)):
|
|
1466
|
+
return _json(400, error_body("activate needs {version: integer}", code="invalid_request_error"))
|
|
1467
|
+
out = ln.activate(body["version"]) if op == "activate" else ln.rollback() if op == "rollback" else ln.purge()
|
|
1468
|
+
await state.router.refresh() # estimates are (de)attached on the registry at once
|
|
1469
|
+
return _json(200, out)
|
|
1470
|
+
except LearningError as e:
|
|
1471
|
+
return _json(e.status, error_body(e.message, code=e.code))
|
|
1472
|
+
return _json(404, error_body(f"unknown learning operation {op!r}", code="not_found"))
|
|
1473
|
+
|
|
1474
|
+
|
|
1475
|
+
async def admin_ui(request: Request) -> Response:
|
|
1476
|
+
page = Path(__file__).parent / "static" / "status.html"
|
|
1477
|
+
return HTMLResponse(page.read_text(encoding="utf-8"))
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
# --------------------------------------------------------------------------- #
|
|
1481
|
+
def build_app(cfg: Config, router: Router, auth: Auth, store: Store | None) -> Starlette:
|
|
1482
|
+
state = GatewayState(cfg, router, auth, store)
|
|
1483
|
+
|
|
1484
|
+
@contextlib.asynccontextmanager
|
|
1485
|
+
async def lifespan(app: Starlette):
|
|
1486
|
+
state.loop = asyncio.get_running_loop()
|
|
1487
|
+
await router.refresh()
|
|
1488
|
+
state.ready = True
|
|
1489
|
+
state._bg.append(asyncio.create_task(_background(state)))
|
|
1490
|
+
try:
|
|
1491
|
+
yield
|
|
1492
|
+
finally:
|
|
1493
|
+
for t in state._bg:
|
|
1494
|
+
t.cancel()
|
|
1495
|
+
await router.aclose()
|
|
1496
|
+
|
|
1497
|
+
app = Starlette(
|
|
1498
|
+
routes=[
|
|
1499
|
+
Route("/v1/chat/completions", chat_completions, methods=["POST"]),
|
|
1500
|
+
Route("/v1/embeddings", embeddings, methods=["POST"]),
|
|
1501
|
+
Route("/v1/decisions", decisions, methods=["POST"]),
|
|
1502
|
+
Route("/v1/guardrails", guardrails_endpoint, methods=["POST"]),
|
|
1503
|
+
Route("/v1/ocr", ocr_endpoint, methods=["POST"]),
|
|
1504
|
+
Route("/v1/vote", vote_endpoint, methods=["POST"]),
|
|
1505
|
+
Route("/v1/models", list_models, methods=["GET"]),
|
|
1506
|
+
Route("/v1/responses", responses_endpoint, methods=["POST"]),
|
|
1507
|
+
Route("/v1/responses/{response_id}", stored_response, methods=["GET", "DELETE"]),
|
|
1508
|
+
Route("/v1/responses/{rest:path}", unsupported_protocol, methods=["GET", "POST", "DELETE"]),
|
|
1509
|
+
Route("/v1/messages", messages_endpoint, methods=["POST"]),
|
|
1510
|
+
Route("/v1/messages/{rest:path}", unsupported_protocol, methods=["GET", "POST"]),
|
|
1511
|
+
Route("/v1/completions", unsupported_protocol, methods=["POST"]),
|
|
1512
|
+
Route("/healthz", healthz, methods=["GET"]),
|
|
1513
|
+
Route("/readyz", readyz, methods=["GET"]),
|
|
1514
|
+
Route("/admin/status", admin_status, methods=["GET"]),
|
|
1515
|
+
Route("/admin/decisions", admin_decisions, methods=["GET"]),
|
|
1516
|
+
Route("/admin/decisions/{request_id}", admin_decisions, methods=["GET"]),
|
|
1517
|
+
Route("/admin/explain", admin_explain, methods=["POST"]),
|
|
1518
|
+
Route("/admin/refresh", admin_refresh, methods=["POST"]),
|
|
1519
|
+
Route("/admin/probe", admin_probe, methods=["POST"]),
|
|
1520
|
+
Route("/v1/feedback", feedback_endpoint, methods=["POST"]),
|
|
1521
|
+
Route("/admin/learning", admin_learning, methods=["GET"]),
|
|
1522
|
+
Route("/admin/learning/{op}", admin_learning, methods=["POST"]),
|
|
1523
|
+
Route("/admin/lifecycle", admin_lifecycle, methods=["GET"]),
|
|
1524
|
+
Route("/admin/lifecycle/{op}", admin_lifecycle, methods=["POST"]),
|
|
1525
|
+
Route("/admin/ui", admin_ui, methods=["GET"]),
|
|
1526
|
+
],
|
|
1527
|
+
lifespan=lifespan,
|
|
1528
|
+
)
|
|
1529
|
+
app.state.gw = state
|
|
1530
|
+
return app
|
|
1531
|
+
|
|
1532
|
+
|
|
1533
|
+
async def _background(state: GatewayState) -> None:
|
|
1534
|
+
last_full = time.monotonic()
|
|
1535
|
+
while True:
|
|
1536
|
+
try:
|
|
1537
|
+
await asyncio.sleep(state.cfg.server.residency_refresh_s)
|
|
1538
|
+
if time.monotonic() - last_full >= state.cfg.server.discovery_refresh_s:
|
|
1539
|
+
await state.router.refresh()
|
|
1540
|
+
last_full = time.monotonic()
|
|
1541
|
+
else:
|
|
1542
|
+
await state.router.refresh_residency()
|
|
1543
|
+
except asyncio.CancelledError:
|
|
1544
|
+
return
|
|
1545
|
+
except Exception as e: # pragma: no cover
|
|
1546
|
+
log.warning("background refresh failed: %s", redact(str(e)))
|