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
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"""Typed, allow-listed view of the OpenAI Chat Completions / Embeddings requests.
|
|
2
|
+
|
|
3
|
+
We validate the structure we rely on (messages, tools, response_format,
|
|
4
|
+
tool_choice, token limits) and carry the original body through for
|
|
5
|
+
forwarding. Unknown top-level fields are preserved for forwarding only when
|
|
6
|
+
allow-listed by the adapter; otherwise they are rejected with a clear error.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
|
|
15
|
+
|
|
16
|
+
# Fields we understand and forward unchanged (per adapter allow-list).
|
|
17
|
+
FORWARDABLE_CHAT_FIELDS = frozenset(
|
|
18
|
+
{
|
|
19
|
+
"model",
|
|
20
|
+
"messages",
|
|
21
|
+
"tools",
|
|
22
|
+
"tool_choice",
|
|
23
|
+
"parallel_tool_calls",
|
|
24
|
+
"response_format",
|
|
25
|
+
"stream",
|
|
26
|
+
"stream_options",
|
|
27
|
+
"temperature",
|
|
28
|
+
"top_p",
|
|
29
|
+
"max_tokens",
|
|
30
|
+
"max_completion_tokens",
|
|
31
|
+
"stop",
|
|
32
|
+
"presence_penalty",
|
|
33
|
+
"frequency_penalty",
|
|
34
|
+
"seed",
|
|
35
|
+
"n",
|
|
36
|
+
"logprobs",
|
|
37
|
+
"top_logprobs",
|
|
38
|
+
"logit_bias",
|
|
39
|
+
"user",
|
|
40
|
+
"reasoning_effort",
|
|
41
|
+
"metadata",
|
|
42
|
+
"store",
|
|
43
|
+
"prompt_cache_key",
|
|
44
|
+
"service_tier",
|
|
45
|
+
"modalities",
|
|
46
|
+
"prediction",
|
|
47
|
+
"audio",
|
|
48
|
+
"web_search_options",
|
|
49
|
+
}
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# Fields that are ModelSaar-specific and must never be forwarded.
|
|
53
|
+
MODELSAAR_FIELDS = frozenset({"modelsaar"})
|
|
54
|
+
|
|
55
|
+
# Client-compatibility fields the gateway CONSUMES and never forwards. Some clients that know they talk to a
|
|
56
|
+
# self-hosted OpenAI-compatible server add llama.cpp-style hints (Odysseus's ``_apply_local_cache_affinity``
|
|
57
|
+
# sends ``session_id`` and ``cache_prompt=true``). The gateway gives them a defined meaning instead of either
|
|
58
|
+
# rejecting the request or passing them to a backend that may not implement them:
|
|
59
|
+
# session_id -> caller-scoped conversation affinity (same semantics as ``modelsaar.session``)
|
|
60
|
+
# cache_prompt -> advisory performance hint; the backend manages its own prompt cache, nothing is promised
|
|
61
|
+
CLIENT_COMPAT_FIELDS = frozenset({"session_id", "cache_prompt"})
|
|
62
|
+
SESSION_ID_MAX_LEN = 256
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class ProtocolError(Exception):
|
|
66
|
+
def __init__(self, message: str, status: int = 400, code: str = "invalid_request_error", param: str | None = None):
|
|
67
|
+
super().__init__(message)
|
|
68
|
+
self.message = message
|
|
69
|
+
self.status = status
|
|
70
|
+
self.code = code
|
|
71
|
+
self.param = param
|
|
72
|
+
|
|
73
|
+
def body(self) -> dict[str, Any]:
|
|
74
|
+
return {"error": {"message": self.message, "type": self.code, "param": self.param, "code": self.code}}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ToolFunction(BaseModel):
|
|
78
|
+
model_config = ConfigDict(extra="allow")
|
|
79
|
+
name: str
|
|
80
|
+
description: str | None = None
|
|
81
|
+
parameters: dict[str, Any] | None = None
|
|
82
|
+
strict: bool | None = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ToolDef(BaseModel):
|
|
86
|
+
model_config = ConfigDict(extra="allow")
|
|
87
|
+
type: str = "function"
|
|
88
|
+
function: ToolFunction
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ToolCall(BaseModel):
|
|
92
|
+
model_config = ConfigDict(extra="allow")
|
|
93
|
+
id: str
|
|
94
|
+
type: str = "function"
|
|
95
|
+
function: dict[str, Any]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# Content part types the gateway understands. Everything else (audio_url, video_url, input_video,
|
|
99
|
+
# file, input_file, refusal, ...) is rejected before any backend is contacted: a part the gateway
|
|
100
|
+
# cannot classify could carry media or fetch instructions for a backend that is not allowed to
|
|
101
|
+
# receive them.
|
|
102
|
+
SUPPORTED_PART_TYPES = frozenset({"text", "image_url", "input_audio", "video_url"})
|
|
103
|
+
_PART_KEYS = {
|
|
104
|
+
"text": {"type", "text"},
|
|
105
|
+
"image_url": {"type", "image_url"},
|
|
106
|
+
"input_audio": {"type", "input_audio"},
|
|
107
|
+
"video_url": {"type", "video_url"},
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def validate_content_parts(content: Any, where: str) -> None:
|
|
112
|
+
"""Typed validation of multipart message content. Raises ProtocolError (400) on anything unknown."""
|
|
113
|
+
if content is None or isinstance(content, str):
|
|
114
|
+
return
|
|
115
|
+
if not isinstance(content, list):
|
|
116
|
+
raise ProtocolError(f"{where}: content must be a string or a list of content parts", param=where)
|
|
117
|
+
for i, part in enumerate(content):
|
|
118
|
+
loc = f"{where}.content[{i}]"
|
|
119
|
+
if not isinstance(part, dict):
|
|
120
|
+
raise ProtocolError(f"{loc}: content part must be an object", param=loc)
|
|
121
|
+
t = part.get("type")
|
|
122
|
+
if t not in SUPPORTED_PART_TYPES:
|
|
123
|
+
raise ProtocolError(
|
|
124
|
+
f"{loc}: unsupported content part type {t!r}; ModelSaar 0.1 accepts "
|
|
125
|
+
f"{sorted(SUPPORTED_PART_TYPES)} only (audio/video/file parts are not forwarded to any backend)",
|
|
126
|
+
param=loc,
|
|
127
|
+
code="unsupported_content_type",
|
|
128
|
+
)
|
|
129
|
+
extra = set(part.keys()) - _PART_KEYS[t]
|
|
130
|
+
if extra:
|
|
131
|
+
raise ProtocolError(f"{loc}: unexpected keys {sorted(extra)} in a {t} part", param=loc)
|
|
132
|
+
if t == "text" and not isinstance(part.get("text"), str):
|
|
133
|
+
raise ProtocolError(f"{loc}: text part requires a string 'text'", param=loc)
|
|
134
|
+
if t == "image_url":
|
|
135
|
+
iu = part.get("image_url")
|
|
136
|
+
url = iu.get("url") if isinstance(iu, dict) else iu
|
|
137
|
+
if not isinstance(url, str) or not url:
|
|
138
|
+
raise ProtocolError(f"{loc}: image_url part requires image_url.url (string)", param=loc)
|
|
139
|
+
if isinstance(iu, dict) and set(iu.keys()) - {"url", "detail"}:
|
|
140
|
+
raise ProtocolError(f"{loc}: unexpected keys in image_url", param=loc)
|
|
141
|
+
if t == "video_url":
|
|
142
|
+
# vLLM documents `video_url` chat parts. The gateway accepts them only INLINE (data:video/...):
|
|
143
|
+
# a remote URL would be fetched by the backend, which the gateway never arranges.
|
|
144
|
+
vu = part.get("video_url")
|
|
145
|
+
url = vu.get("url") if isinstance(vu, dict) else None
|
|
146
|
+
if not isinstance(url, str) or not url.startswith("data:video/") or set(vu) - {"url"}:
|
|
147
|
+
raise ProtocolError(
|
|
148
|
+
f"{loc}: video_url parts must carry an inline data:video/... URL (remote video is not fetched or forwarded)",
|
|
149
|
+
param=loc,
|
|
150
|
+
code="unsupported_content_type",
|
|
151
|
+
)
|
|
152
|
+
if t == "input_audio":
|
|
153
|
+
ia = part.get("input_audio")
|
|
154
|
+
if not isinstance(ia, dict) or not isinstance(ia.get("data"), str) or not isinstance(ia.get("format"), str):
|
|
155
|
+
raise ProtocolError(f"{loc}: input_audio part requires inline input_audio.data and .format", param=loc)
|
|
156
|
+
if set(ia.keys()) - {"data", "format"}:
|
|
157
|
+
raise ProtocolError(f"{loc}: unexpected keys in input_audio (remote audio is not fetched)", param=loc)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class Message(BaseModel):
|
|
161
|
+
model_config = ConfigDict(extra="allow")
|
|
162
|
+
role: str
|
|
163
|
+
content: Any = None
|
|
164
|
+
name: str | None = None
|
|
165
|
+
tool_calls: list[ToolCall] | None = None
|
|
166
|
+
tool_call_id: str | None = None
|
|
167
|
+
reasoning_content: str | None = None
|
|
168
|
+
|
|
169
|
+
@field_validator("role")
|
|
170
|
+
@classmethod
|
|
171
|
+
def _role(cls, v: str) -> str:
|
|
172
|
+
if v not in ("system", "developer", "user", "assistant", "tool", "function"):
|
|
173
|
+
raise ValueError(f"unsupported role {v!r}")
|
|
174
|
+
return v
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class ChatRequest(BaseModel):
|
|
178
|
+
"""Validated view. The raw body is kept separately for forwarding."""
|
|
179
|
+
|
|
180
|
+
model_config = ConfigDict(extra="allow")
|
|
181
|
+
model: str
|
|
182
|
+
messages: list[Message] = Field(min_length=1)
|
|
183
|
+
tools: list[ToolDef] | None = None
|
|
184
|
+
tool_choice: Any = None
|
|
185
|
+
parallel_tool_calls: bool | None = None
|
|
186
|
+
response_format: dict[str, Any] | None = None
|
|
187
|
+
stream: bool = False
|
|
188
|
+
stream_options: dict[str, Any] | None = None
|
|
189
|
+
max_tokens: int | None = Field(default=None, ge=1, le=10_000_000)
|
|
190
|
+
max_completion_tokens: int | None = Field(default=None, ge=1, le=10_000_000)
|
|
191
|
+
reasoning_effort: str | None = None
|
|
192
|
+
n: int | None = None
|
|
193
|
+
user: str | None = None
|
|
194
|
+
prompt_cache_key: str | None = None
|
|
195
|
+
modelsaar: dict[str, Any] | None = None # per-request routing hints (session, profile)
|
|
196
|
+
session_id: Any = None # client-compat conversation id (validated below; consumed, never forwarded)
|
|
197
|
+
cache_prompt: Any = None # client-compat advisory cache hint (validated below; consumed, never forwarded)
|
|
198
|
+
|
|
199
|
+
@field_validator("n")
|
|
200
|
+
@classmethod
|
|
201
|
+
def _n(cls, v: int | None) -> int | None:
|
|
202
|
+
if v is not None and v != 1:
|
|
203
|
+
raise ValueError("n > 1 is not supported by the gateway")
|
|
204
|
+
return v
|
|
205
|
+
|
|
206
|
+
@field_validator("session_id")
|
|
207
|
+
@classmethod
|
|
208
|
+
def _session_id(cls, v: Any) -> str | None:
|
|
209
|
+
if v is None:
|
|
210
|
+
return None
|
|
211
|
+
if not isinstance(v, str) or not v.strip() or len(v) > SESSION_ID_MAX_LEN or any(ord(ch) < 32 or ch == "\x7f" for ch in v):
|
|
212
|
+
raise ValueError(
|
|
213
|
+
f"session_id must be a non-empty printable string of at most {SESSION_ID_MAX_LEN} characters "
|
|
214
|
+
"(a client conversation id; the gateway uses it as caller-scoped conversation affinity)"
|
|
215
|
+
)
|
|
216
|
+
return v
|
|
217
|
+
|
|
218
|
+
@field_validator("cache_prompt")
|
|
219
|
+
@classmethod
|
|
220
|
+
def _cache_prompt(cls, v: Any) -> bool | None:
|
|
221
|
+
if v is None:
|
|
222
|
+
return None
|
|
223
|
+
if not isinstance(v, bool):
|
|
224
|
+
raise ValueError("cache_prompt must be a JSON boolean (an advisory prompt-cache hint; the gateway does not coerce strings or numbers)")
|
|
225
|
+
return v
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class EmbeddingsRequest(BaseModel):
|
|
229
|
+
model_config = ConfigDict(extra="allow")
|
|
230
|
+
model: str
|
|
231
|
+
input: Any
|
|
232
|
+
encoding_format: str | None = None
|
|
233
|
+
dimensions: int | None = None
|
|
234
|
+
user: str | None = None
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def parse_chat_request(body: dict[str, Any]) -> ChatRequest:
|
|
238
|
+
try:
|
|
239
|
+
req = ChatRequest.model_validate(body)
|
|
240
|
+
except ValidationError as e:
|
|
241
|
+
first = e.errors()[0]
|
|
242
|
+
loc = ".".join(str(x) for x in first.get("loc", ()))
|
|
243
|
+
raise ProtocolError(f"invalid chat request: {first.get('msg')} at {loc}", param=loc or None) from e
|
|
244
|
+
for i, m in enumerate(body.get("messages") or []):
|
|
245
|
+
if isinstance(m, dict):
|
|
246
|
+
validate_content_parts(m.get("content"), f"messages[{i}]")
|
|
247
|
+
unknown = set(body.keys()) - FORWARDABLE_CHAT_FIELDS - MODELSAAR_FIELDS - CLIENT_COMPAT_FIELDS
|
|
248
|
+
if unknown:
|
|
249
|
+
raise ProtocolError(
|
|
250
|
+
f"unsupported request field(s): {sorted(unknown)}; the gateway forwards only allow-listed fields "
|
|
251
|
+
"and does not silently drop unknown semantics",
|
|
252
|
+
param=sorted(unknown)[0],
|
|
253
|
+
)
|
|
254
|
+
return req
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def parse_embeddings_request(body: dict[str, Any]) -> EmbeddingsRequest:
|
|
258
|
+
try:
|
|
259
|
+
return EmbeddingsRequest.model_validate(body)
|
|
260
|
+
except ValidationError as e:
|
|
261
|
+
first = e.errors()[0]
|
|
262
|
+
raise ProtocolError(f"invalid embeddings request: {first.get('msg')}") from e
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def embedding_media_items(body: dict[str, Any]) -> list[dict[str, Any]] | None:
|
|
266
|
+
"""Multimodal embedding input. ``input`` may be a list whose items are strings or typed objects —
|
|
267
|
+
``{"type": "text", "text"}``, ``{"type": "image_url", "image_url": {"url": "data:..."}}``,
|
|
268
|
+
``{"type": "input_audio", "input_audio": {"data", "format"}}`` — one vector per item. Returns the
|
|
269
|
+
normalised items when at least one object item is present, None for the plain text contract.
|
|
270
|
+
Media must be inline: the gateway fetches nothing. Video is not accepted."""
|
|
271
|
+
inp = body.get("input")
|
|
272
|
+
if not isinstance(inp, list) or not any(isinstance(x, dict) for x in inp):
|
|
273
|
+
return None
|
|
274
|
+
out: list[dict[str, Any]] = []
|
|
275
|
+
for i, x in enumerate(inp):
|
|
276
|
+
loc = f"input[{i}]"
|
|
277
|
+
if isinstance(x, str):
|
|
278
|
+
out.append({"modality": "text", "text": x})
|
|
279
|
+
continue
|
|
280
|
+
if not isinstance(x, dict):
|
|
281
|
+
raise ProtocolError(f"{loc}: items must be strings or typed objects when media items are present", param=loc)
|
|
282
|
+
t = x.get("type")
|
|
283
|
+
if t == "text" and isinstance(x.get("text"), str) and not set(x) - {"type", "text"}:
|
|
284
|
+
out.append({"modality": "text", "text": x["text"]})
|
|
285
|
+
elif t == "image_url":
|
|
286
|
+
iu = x.get("image_url")
|
|
287
|
+
url = iu.get("url") if isinstance(iu, dict) else None
|
|
288
|
+
if not isinstance(url, str) or set(x) - {"type", "image_url"} or set(iu) - {"url"}:
|
|
289
|
+
raise ProtocolError(f"{loc}: image_url item requires image_url.url only", param=loc)
|
|
290
|
+
if not url.startswith("data:image/"):
|
|
291
|
+
raise ProtocolError(f"{loc}: only inline data:image/... URLs are embedded; the gateway never fetches media", param=loc, code="unsupported_image_source")
|
|
292
|
+
out.append({"modality": "image", "part": {"type": "image_url", "image_url": {"url": url}}})
|
|
293
|
+
elif t == "input_audio":
|
|
294
|
+
ia = x.get("input_audio")
|
|
295
|
+
if not isinstance(ia, dict) or not isinstance(ia.get("data"), str) or not isinstance(ia.get("format"), str) or set(ia) - {"data", "format"} or set(x) - {"type", "input_audio"}:
|
|
296
|
+
raise ProtocolError(f"{loc}: input_audio item requires inline input_audio.data and .format", param=loc)
|
|
297
|
+
out.append({"modality": "audio", "part": {"type": "input_audio", "input_audio": {"data": ia["data"], "format": ia["format"]}}})
|
|
298
|
+
elif t == "video_url":
|
|
299
|
+
vu = x.get("video_url")
|
|
300
|
+
url = vu.get("url") if isinstance(vu, dict) else None
|
|
301
|
+
if not isinstance(url, str) or not url.startswith("data:video/") or set(x) - {"type", "video_url"} or set(vu) - {"url"}:
|
|
302
|
+
raise ProtocolError(f"{loc}: video_url item requires an inline data:video/... URL only", param=loc, code="unsupported_content_type")
|
|
303
|
+
out.append({"modality": "video", "part": {"type": "video_url", "video_url": {"url": url}}})
|
|
304
|
+
else:
|
|
305
|
+
raise ProtocolError(
|
|
306
|
+
f"{loc}: unsupported embedding input type {t!r} (supported: text, image_url, input_audio, video_url; files are not embedded)",
|
|
307
|
+
param=loc,
|
|
308
|
+
code="unsupported_content_type",
|
|
309
|
+
)
|
|
310
|
+
if len(out) > 64:
|
|
311
|
+
raise ProtocolError("at most 64 items per multimodal embeddings request", param="input")
|
|
312
|
+
return out
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def error_body(message: str, code: str = "invalid_request_error", param: str | None = None, **extra: Any) -> dict:
|
|
316
|
+
err: dict[str, Any] = {"message": message, "type": code, "param": param, "code": code}
|
|
317
|
+
err.update(extra)
|
|
318
|
+
return {"error": err}
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def sse_error_frame(message: str, code: str = "upstream_error", **extra: Any) -> bytes:
|
|
322
|
+
return b"data: " + json.dumps(error_body(message, code, **extra), separators=(",", ":")).encode() + b"\n\n"
|