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.
Files changed (54) hide show
  1. modelsaar/__init__.py +13 -0
  2. modelsaar/adapters/__init__.py +27 -0
  3. modelsaar/adapters/base.py +274 -0
  4. modelsaar/adapters/ollama.py +317 -0
  5. modelsaar/adapters/openai_compat.py +296 -0
  6. modelsaar/catalogue/__init__.py +72 -0
  7. modelsaar/catalogue/starter.yaml +435 -0
  8. modelsaar/cli.py +880 -0
  9. modelsaar/clientconfig/__init__.py +364 -0
  10. modelsaar/config.py +631 -0
  11. modelsaar/doctor.py +233 -0
  12. modelsaar/evaluation/__init__.py +1 -0
  13. modelsaar/evaluation/fixtures/tasks.jsonl +47 -0
  14. modelsaar/evaluation/harness.py +768 -0
  15. modelsaar/evaluation/judge.py +173 -0
  16. modelsaar/evaluation/sandbox.py +341 -0
  17. modelsaar/evaluation/scoring.py +233 -0
  18. modelsaar/learning.py +227 -0
  19. modelsaar/lifecycle.py +208 -0
  20. modelsaar/pipelines.py +439 -0
  21. modelsaar/probes.py +526 -0
  22. modelsaar/protocol/__init__.py +1 -0
  23. modelsaar/protocol/anthropic.py +401 -0
  24. modelsaar/protocol/decisions.py +229 -0
  25. modelsaar/protocol/openai.py +322 -0
  26. modelsaar/protocol/responses.py +560 -0
  27. modelsaar/protocol/sse.py +181 -0
  28. modelsaar/registry.py +229 -0
  29. modelsaar/responses_store.py +117 -0
  30. modelsaar/routing/__init__.py +1 -0
  31. modelsaar/routing/admission.py +359 -0
  32. modelsaar/routing/affinity.py +131 -0
  33. modelsaar/routing/cascade.py +53 -0
  34. modelsaar/routing/classifier.py +298 -0
  35. modelsaar/routing/decision.py +85 -0
  36. modelsaar/routing/eligibility.py +158 -0
  37. modelsaar/routing/requirements.py +290 -0
  38. modelsaar/routing/router.py +1026 -0
  39. modelsaar/routing/scoring.py +179 -0
  40. modelsaar/routing/tokens.py +114 -0
  41. modelsaar/runtime.py +82 -0
  42. modelsaar/security.py +63 -0
  43. modelsaar/server.py +1546 -0
  44. modelsaar/static/status.html +95 -0
  45. modelsaar/store.py +208 -0
  46. modelsaar/testing/__init__.py +1 -0
  47. modelsaar/testing/fakebackend.py +661 -0
  48. modelsaar-0.2.0.dist-info/METADATA +285 -0
  49. modelsaar-0.2.0.dist-info/RECORD +54 -0
  50. modelsaar-0.2.0.dist-info/WHEEL +5 -0
  51. modelsaar-0.2.0.dist-info/entry_points.txt +2 -0
  52. modelsaar-0.2.0.dist-info/licenses/LICENSE +202 -0
  53. modelsaar-0.2.0.dist-info/licenses/NOTICE +18 -0
  54. modelsaar-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,296 @@
1
+ """Generic OpenAI-compatible adapter (vLLM, llama.cpp server, LM Studio, SGLang, ...).
2
+
3
+ Discovery via ``GET /models`` yields names only; capabilities stay ``unknown``
4
+ until declared by the operator (``backends[].models``) or verified by probes.
5
+ vLLM's ``/tokenize`` endpoint is used for tokenizer-based text counts when present (template overhead stays estimated).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from typing import Any
12
+
13
+ from ..config import DeclaredModel
14
+ from ..registry import Deployment, merge_capabilities
15
+ from .base import AdapterError, BaseAdapter, UpstreamResponse
16
+
17
+
18
+ class OpenAICompatAdapter(BaseAdapter):
19
+ type_name = "openai_compatible"
20
+ adapter_capabilities = {"streaming": "supported"}
21
+
22
+ def __init__(self, cfg, allowed_hosts): # type: ignore[no-untyped-def]
23
+ super().__init__(cfg, allowed_hosts)
24
+ self._tokenize_supported: bool | None = None
25
+ # Detected server flavour: "vllm" (/v1/models reports max_model_len), "llama.cpp" (/props answers
26
+ # with n_ctx) or "generic". Detection uses metadata endpoints only; it never sends request content.
27
+ self.flavor: str = "generic"
28
+ self._served_ctx: dict[str, tuple[int, str]] = {}
29
+ self._chat_tokenize_supported: bool | None = None
30
+ self._swap_running: set[str] | None = None
31
+
32
+ async def _detect(self, models: list[dict[str, Any]]) -> None:
33
+ self._served_ctx = {}
34
+ flavor = "generic"
35
+ for m in models:
36
+ mml = m.get("max_model_len")
37
+ if isinstance(mml, int) and mml > 0 and m.get("id"):
38
+ flavor = "vllm"
39
+ self._served_ctx[str(m["id"])] = (mml, "vLLM /v1/models max_model_len (served)")
40
+ self._swap_running = None
41
+ if flavor == "generic":
42
+ running = await self._swap_query()
43
+ if running is not None:
44
+ # llama-swap: an OpenAI-compatible proxy that starts/stops one upstream server per model.
45
+ flavor = "llama-swap"
46
+ if flavor == "generic":
47
+ try:
48
+ r = await self._client.get(self._root_url("/props"), timeout=3.0)
49
+ props = r.json() if r.status_code == 200 else None
50
+ except Exception: # noqa: BLE001 - metadata only; a server without /props is simply generic
51
+ props = None
52
+ if isinstance(props, dict) and isinstance(props.get("default_generation_settings"), dict):
53
+ flavor = "llama.cpp"
54
+ n_ctx = props["default_generation_settings"].get("n_ctx")
55
+ # /props describes the one loaded model. It is applied only when the server lists exactly
56
+ # one model (classic llama-server); a router-mode server needs declared context lengths.
57
+ if isinstance(n_ctx, int) and n_ctx > 0 and len(models) == 1 and models[0].get("id"):
58
+ self._served_ctx[str(models[0]["id"])] = (n_ctx, "llama.cpp /props default_generation_settings.n_ctx (served, per slot)")
59
+ if flavor != self.flavor:
60
+ self._tokenize_supported = None
61
+ self._chat_tokenize_supported = None
62
+ self.flavor = flavor
63
+
64
+ async def health(self) -> tuple[bool, str]:
65
+ try:
66
+ await self._get_json("/models")
67
+ return True, "openai-compatible endpoint reachable"
68
+ except AdapterError as e:
69
+ return False, e.message
70
+
71
+ async def discover(self) -> list[Deployment]:
72
+ declared: dict[str, DeclaredModel] = {m.name: m for m in self.cfg.models}
73
+ names: list[str] = []
74
+ ok, _ = await self.health()
75
+ if self.cfg.discover and ok:
76
+ try:
77
+ data = await self._get_json("/models")
78
+ listed = [m for m in data.get("data", []) or [] if isinstance(m, dict) and m.get("id")]
79
+ names.extend(str(m["id"]) for m in listed)
80
+ await self._detect(listed)
81
+ except AdapterError:
82
+ pass
83
+ for n in declared:
84
+ if n not in names:
85
+ names.append(n)
86
+ loaded = await self.loaded_models() if self.flavor == "llama-swap" else None
87
+ deps: list[Deployment] = []
88
+ for name in names:
89
+ dep = Deployment(
90
+ id=f"{self.cfg.id}/{name}",
91
+ backend_id=self.cfg.id,
92
+ backend_type="openai_compatible",
93
+ model=name,
94
+ runtime="openai_compatible",
95
+ endpoint=self.endpoint,
96
+ resource_pool=self.cfg.resource_pool,
97
+ discovered=name in names,
98
+ available_on_disk=ok,
99
+ discovered_at=time.time(),
100
+ healthy=ok,
101
+ health_checked_at=time.time(),
102
+ locality=self.cfg.locality,
103
+ locality_evidence=(
104
+ f"operator declared backend locality={self.cfg.locality} (trust assumption: a generic endpoint "
105
+ "exposes no execution-location evidence)"
106
+ ),
107
+ )
108
+ merge_capabilities(dep, dict(self.adapter_capabilities), "adapter") # type: ignore[arg-type]
109
+ dep.raw_metadata["server_flavor"] = self.flavor
110
+ if self.flavor == "llama-swap" and loaded is not None and name in loaded:
111
+ dep.loaded = True
112
+ dep.loaded_observed_at = time.time()
113
+ if name in self._served_ctx:
114
+ # Served context reported by the runtime itself. An operator declaration below still wins.
115
+ dep.context_length, dep.raw_metadata["context_source"] = self._served_ctx[name]
116
+ d = declared.get(name)
117
+ if d:
118
+ dep.configured = True
119
+ dep.role = d.role
120
+ if d.context_length is not None:
121
+ if name in self._served_ctx and self._served_ctx[name][0] != d.context_length:
122
+ dep.raw_metadata["context_source"] = (
123
+ f"operator declaration ({d.context_length}); the runtime reports {self._served_ctx[name][0]} "
124
+ f"via {self._served_ctx[name][1]}"
125
+ )
126
+ else:
127
+ dep.raw_metadata["context_source"] = "operator declaration"
128
+ dep.context_length = d.context_length
129
+ dep.max_output_tokens = d.max_output_tokens
130
+ dep.tags = list(d.tags)
131
+ dep.enabled = d.enabled
132
+ dep.catalogue_id = d.catalogue_id
133
+ dep.memory_gb_estimate = d.memory_gb_estimate
134
+ dep.embedding_dimensions = d.embedding_dimensions
135
+ if d.identity:
136
+ dep.identity = d.identity
137
+ dep.identity_source = "operator declaration"
138
+ if d.memory_gb_estimate:
139
+ dep.memory_estimate_provenance = "operator declaration"
140
+ merge_capabilities(
141
+ dep,
142
+ {k: v for k, v in d.capabilities.model_dump().items() if v != "unknown"},
143
+ "operator",
144
+ note="backends[].models declaration",
145
+ )
146
+ dep.compute_fingerprint()
147
+ deps.append(dep)
148
+ return deps
149
+
150
+ async def embed_media(self, dep: Deployment, part: dict[str, Any], timeout: float | None = None) -> UpstreamResponse:
151
+ mode = self.cfg.multimodal_embeddings
152
+ if mode == "none" or (mode == "auto" and self.flavor != "vllm"):
153
+ raise AdapterError(
154
+ f"backend {self.cfg.id}: image/audio embeddings are not enabled for this OpenAI-compatible server "
155
+ f"(detected flavour {self.flavor}); set backends[].multimodal_embeddings: vllm_chat if it implements vLLM's "
156
+ "chat-style embeddings request",
157
+ status=501,
158
+ kind="unsupported",
159
+ )
160
+ # vLLM's documented chat-style embeddings request: one prompt (here one media part) -> one vector.
161
+ body = {"model": dep.model, "messages": [{"role": "user", "content": [part]}], "encoding_format": "float"}
162
+ return await self._post_json("/embeddings", body, timeout=timeout)
163
+
164
+ # ---- llama-swap composition: residency from /running, per-model unload ----
165
+ @property
166
+ def reports_residency(self) -> bool: # type: ignore[override]
167
+ return self.flavor == "llama-swap"
168
+
169
+ async def _swap_query(self) -> set[str] | None:
170
+ """Model ids llama-swap reports as running (``GET /running``); None when the server is not
171
+ llama-swap or the query failed (a failed query is never read as "nothing is running")."""
172
+ try:
173
+ r = await self._client.get(self._root_url("/running"), timeout=3.0)
174
+ data = r.json() if r.status_code == 200 else None
175
+ except Exception: # noqa: BLE001
176
+ return None
177
+ if not isinstance(data, dict) or not isinstance(data.get("running"), list):
178
+ return None
179
+ out: set[str] = set()
180
+ for item in data["running"]:
181
+ if isinstance(item, str):
182
+ out.add(item)
183
+ elif isinstance(item, dict) and item.get("model") and item.get("state", "ready") in ("ready", "running"):
184
+ out.add(str(item["model"]))
185
+ return out
186
+
187
+ async def loaded_models(self) -> dict[str, dict[str, Any]] | None:
188
+ if self.flavor != "llama-swap":
189
+ return None
190
+ running = await self._swap_query()
191
+ self.last_residency_observation_ok = running is not None
192
+ return None if running is None else {m: {} for m in running}
193
+
194
+ def lifecycle_operations(self) -> frozenset[str]:
195
+ # llama-swap loads a model on its first request (no separate load call is documented).
196
+ return frozenset({"unload"}) if self.flavor == "llama-swap" else frozenset()
197
+
198
+ async def unload_model(self, dep: Deployment, timeout: float) -> None:
199
+ if self.flavor != "llama-swap":
200
+ await super().unload_model(dep, timeout)
201
+ return
202
+ from urllib.parse import quote
203
+
204
+ try:
205
+ r = await self._client.post(self._root_url("/api/models/unload/" + quote(dep.model, safe="")), timeout=self._deadline(timeout))
206
+ except Exception as e: # noqa: BLE001
207
+ raise AdapterError(f"llama-swap unload request failed: {e}") from e
208
+ if r.status_code not in (200, 204):
209
+ raise AdapterError(f"llama-swap answered {r.status_code} to the unload request: {r.text[:200]}")
210
+
211
+ async def tokenize(self, dep: Deployment, text: str) -> int | None:
212
+ """Tokenizer count of a text. vLLM serves ``/tokenize`` at the server root with ``{model, prompt}``;
213
+ llama.cpp at the root with ``{content}``; a generic server is tried at the base URL as before."""
214
+ if self._tokenize_supported is False:
215
+ return None
216
+ if self.flavor == "llama.cpp":
217
+ url, payload = self._root_url("/tokenize"), {"content": text}
218
+ elif self.flavor == "vllm":
219
+ url, payload = self._root_url("/tokenize"), {"model": dep.model, "prompt": text}
220
+ else:
221
+ url, payload = self._url("/tokenize"), {"model": dep.model, "prompt": text}
222
+ data = await self._tok_post(url, payload)
223
+ if data is None:
224
+ self._tokenize_supported = False
225
+ return None
226
+ self._tokenize_supported = True
227
+ if isinstance(data.get("count"), int):
228
+ return data["count"]
229
+ toks = data.get("tokens")
230
+ return len(toks) if isinstance(toks, list) else None
231
+
232
+ async def _tok_post(self, url: str, payload: dict[str, Any]) -> dict[str, Any] | None:
233
+ try:
234
+ r = await self._client.post(url, json=payload, timeout=5.0)
235
+ if r.status_code != 200:
236
+ return None
237
+ data = r.json()
238
+ except Exception: # noqa: BLE001 - counting is best effort
239
+ return None
240
+ return data if isinstance(data, dict) else None
241
+
242
+ async def tokenize_chat(self, dep: Deployment, body: dict[str, Any]) -> tuple[int, str] | None:
243
+ """Exact input count with the runtime's own chat template. vLLM: ``POST /tokenize`` with the
244
+ messages and tools. llama.cpp: ``POST /apply-template`` renders the prompt, ``POST /tokenize``
245
+ counts it. Generic servers: not available (the text count plus template estimate is used)."""
246
+ if self._chat_tokenize_supported is False or self.flavor == "generic":
247
+ return None
248
+ chat: dict[str, Any] = {"messages": body.get("messages") or []}
249
+ if body.get("tools"):
250
+ chat["tools"] = body["tools"]
251
+ count: int | None = None
252
+ label = ""
253
+ if self.flavor == "vllm":
254
+ data = await self._tok_post(self._root_url("/tokenize"), {"model": dep.model, **chat, "add_generation_prompt": True})
255
+ if data is not None and isinstance(data.get("count"), int):
256
+ count, label = data["count"], f"tokenize:{self.cfg.id} vllm chat template (exact)"
257
+ elif self.flavor == "llama.cpp":
258
+ data = await self._tok_post(self._root_url("/apply-template"), chat)
259
+ if data is not None and isinstance(data.get("prompt"), str):
260
+ tk = await self._tok_post(self._root_url("/tokenize"), {"content": data["prompt"], "add_special": True})
261
+ if tk is not None and isinstance(tk.get("tokens"), list):
262
+ count, label = len(tk["tokens"]), f"tokenize:{self.cfg.id} llama.cpp apply-template (exact)"
263
+ if count is None:
264
+ self._chat_tokenize_supported = False
265
+ return None
266
+ self._chat_tokenize_supported = True
267
+ return count, label
268
+
269
+ def translate_chat_body(self, body: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
270
+ out = dict(body)
271
+ notes: list[str] = []
272
+ for k in ("modelsaar",):
273
+ out.pop(k, None)
274
+ # llama.cpp-style hints are consumed by the gateway; a private address does not mean the server
275
+ # implements llama.cpp's extensions, so they are not forwarded to any OpenAI-compatible backend.
276
+ for k in ("session_id", "cache_prompt"):
277
+ if k in out:
278
+ out.pop(k)
279
+ notes.append(f"client-compatibility field {k} consumed by the gateway; not forwarded")
280
+ return out, notes
281
+
282
+ async def chat(self, dep: Deployment, body: dict[str, Any], stream: bool, timeout: float | None = None):
283
+ fwd, _ = self.translate_chat_body(body)
284
+ fwd["model"] = dep.model
285
+ fwd["stream"] = stream
286
+ if stream:
287
+ so = dict(fwd.get("stream_options") or {})
288
+ so.setdefault("include_usage", True)
289
+ fwd["stream_options"] = so
290
+ return await self._post_stream("/chat/completions", fwd, timeout=timeout)
291
+ return await self._post_json("/chat/completions", fwd, timeout=timeout)
292
+
293
+ async def embeddings(self, dep: Deployment, body: dict[str, Any], timeout: float | None = None) -> UpstreamResponse:
294
+ fwd = {k: v for k, v in body.items() if k in ("input", "encoding_format", "dimensions", "user")}
295
+ fwd["model"] = dep.model
296
+ return await self._post_json("/embeddings", fwd, timeout=timeout)
@@ -0,0 +1,72 @@
1
+ """Verified starter catalogue: model-card evidence (sources + dates), kept
2
+ separate from locally probed capabilities and measured task performance.
3
+
4
+ Matching a discovered deployment to a catalogue entry only supplies *priors*
5
+ (labelled ``catalogue``) and tags. It never asserts a capability as
6
+ "supported" on its own: card claims become ``source_claim`` evidence, which
7
+ the eligibility filter still treats as a claim, not a probe. Operators can
8
+ promote a claim with an override or verify it with ``modelsaar probe``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import fnmatch
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import yaml
18
+
19
+ from ..registry import Deployment, merge_capabilities
20
+
21
+ _CATALOGUE_PATH = Path(__file__).parent / "starter.yaml"
22
+
23
+
24
+ def load_catalogue(extra_paths: list[Path] | None = None) -> list[dict[str, Any]]:
25
+ entries: list[dict[str, Any]] = []
26
+ for p in [_CATALOGUE_PATH, *(extra_paths or [])]:
27
+ if p.exists():
28
+ data = yaml.safe_load(p.read_text(encoding="utf-8")) or {}
29
+ entries.extend(data.get("entries", []))
30
+ return entries
31
+
32
+
33
+ def match_entry(dep: Deployment, entries: list[dict[str, Any]]) -> dict[str, Any] | None:
34
+ name = dep.model.lower()
35
+ for e in entries:
36
+ for pat in e.get("match", {}).get("ollama", []) or []:
37
+ if fnmatch.fnmatch(name, pat.lower()):
38
+ return e
39
+ for pat in e.get("match", {}).get("names", []) or []:
40
+ if fnmatch.fnmatch(name, pat.lower()):
41
+ return e
42
+ return None
43
+
44
+
45
+ def apply_catalogue(dep: Deployment, entries: list[dict[str, Any]]) -> str | None:
46
+ e = match_entry(dep, entries)
47
+ if not e:
48
+ return None
49
+ if e.get("enabled_by_default") is False or e.get("availability") != "released_weights":
50
+ # Unresolved/announced entries never contribute defaults.
51
+ return None
52
+ dep.catalogue_id = e["id"]
53
+ dep.publisher = dep.publisher or e.get("publisher", "")
54
+ for t in e.get("tags", []) or []:
55
+ if t not in dep.tags:
56
+ dep.tags.append(t)
57
+ if e.get("role") and dep.role == "generative" and e["role"] != "generative":
58
+ dep.role = e["role"]
59
+ # The card's context length is informational only; the *served* context comes from the runtime
60
+ # or an operator override, never from the catalogue.
61
+ if e.get("context_length"):
62
+ dep.raw_metadata["catalogue_context_length"] = int(e["context_length"])
63
+ claims = {k: v for k, v in (e.get("capability_claims") or {}).items()}
64
+ if claims:
65
+ merge_capabilities(dep, claims, "source_claim", note=f"catalogue {e['id']} (model card)")
66
+ priors = e.get("quality_prior") or {}
67
+ if priors and not dep.quality_prior:
68
+ dep.quality_prior = {k: float(v) for k, v in priors.items()}
69
+ dep.quality_prior_provenance = "catalogue" # model-card/vendor derived hypothesis, NOT a local measurement
70
+ if e.get("intended_use_note"):
71
+ dep.intended_use_note = e["intended_use_note"]
72
+ return e["id"]