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
modelsaar/config.py ADDED
@@ -0,0 +1,631 @@
1
+ """Versioned configuration: one YAML file, typed validation, immutable snapshots.
2
+
3
+ The configuration is loaded into an immutable ``Config`` object; a request
4
+ captures the router/config snapshot at entry. Configuration changes take effect
5
+ by restarting ``modelsaar serve`` (there is no hot reload in 0.1).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import secrets
12
+ from enum import Enum
13
+ from pathlib import Path
14
+ from typing import Any, Literal
15
+
16
+ import yaml
17
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
18
+
19
+ from . import CONFIG_VERSION
20
+
21
+ Tri = Literal["supported", "unsupported", "unknown"]
22
+
23
+
24
+ class StrictModel(BaseModel):
25
+ model_config = ConfigDict(extra="forbid", frozen=True)
26
+
27
+
28
+ # --------------------------------------------------------------------------- #
29
+ # Server / security
30
+ # --------------------------------------------------------------------------- #
31
+ class ServerConfig(StrictModel):
32
+ host: str = "127.0.0.1"
33
+ port: int = 8484
34
+ # Paths are relative to the config directory unless absolute.
35
+ api_keys_file: str = "keys/api_keys"
36
+ admin_key_file: str = "keys/admin_key"
37
+ state_db: str = "state/modelsaar.db"
38
+ request_timeout_s: float = 600.0
39
+ max_request_bytes: int = 32 * 1024 * 1024
40
+ # What the `model` field of responses carries: the requested alias (safe
41
+ # for clients that validate model ids) or the selected deployment id.
42
+ # The selected deployment is always available in X-ModelSaar-Deployment.
43
+ response_model_field: Literal["requested", "deployment"] = "requested"
44
+ # Background refresh intervals.
45
+ residency_refresh_s: float = 15.0
46
+ discovery_refresh_s: float = 120.0
47
+
48
+ @field_validator("port")
49
+ @classmethod
50
+ def _port(cls, v: int) -> int:
51
+ if not (1 <= v <= 65535):
52
+ raise ValueError("port must be 1..65535")
53
+ return v
54
+
55
+
56
+ class SecurityConfig(StrictModel):
57
+ # LAN exposure is opt-in and must be paired with a non-loopback bind.
58
+ allow_lan: bool = False
59
+ # local_only: only deployments with locality=local are eligible.
60
+ locality_mode: Literal["local_only", "allow_remote"] = "local_only"
61
+ # Backends may only be contacted at these hosts (exact host or host:port).
62
+ # Populated from backend base_urls at load time; extra entries allowed.
63
+ allowed_backend_hosts: tuple[str, ...] = ()
64
+ # Media handling: the gateway never fetches remote image URLs by default.
65
+ fetch_remote_media: bool = False
66
+ # Never log prompts/responses/tool args/reasoning by default.
67
+ log_prompts: bool = False
68
+ telemetry_opt_in: bool = False
69
+
70
+
71
+ # --------------------------------------------------------------------------- #
72
+ # Backends / pools / deployments
73
+ # --------------------------------------------------------------------------- #
74
+ class ResourcePool(StrictModel):
75
+ id: str
76
+ kind: Literal["unified", "gpu", "cpu", "remote"] = "unified"
77
+ memory_gb: float | None = None
78
+ max_concurrent: int = 1
79
+ max_queue: int = 16
80
+ queue_timeout_s: float = 30.0
81
+ # Memory headroom kept free on the pool. A dispatch is admitted only when the resident
82
+ # set (distinct loaded deployments, including the classifier) plus the candidate's
83
+ # memory estimate plus this margin fits in memory_gb.
84
+ memory_margin_gb: float = 0.0
85
+ # What to do with a deployment whose memory estimate is unknown when memory_gb is set:
86
+ # "allow" admits it (counted as 0, labelled unknown in the decision); "reject" treats
87
+ # it as not fitting — and applies to every counted member (resident, reserved or assumed
88
+ # resident), not only the candidate: one unknown model makes the budget unverifiable.
89
+ unknown_memory_policy: Literal["allow", "reject"] = "allow"
90
+ # After a dispatch completes its request slot is released but the weights stay loaded. The
91
+ # pool keeps counting them ("assumed resident") until the runtime's residency observation
92
+ # (Ollama /api/ps on refresh) reconciles the registry. Runtimes that cannot report residency
93
+ # keep the assumption indefinitely unless this TTL (seconds) is set; this is the conservative
94
+ # choice because the gateway cannot see when such a runtime evicts a model.
95
+ assumed_residency_ttl_s: float | None = None
96
+
97
+
98
+ class LifecycleConfig(StrictModel):
99
+ """Opt-in managed lifecycle for one backend (docs/lifecycle.md). Off by default: the gateway never
100
+ loads or unloads a model on a backend that does not say ``managed: true``."""
101
+
102
+ managed: bool = False
103
+ # keep_alive sent with an explicit load (seconds; None = the runtime's own default).
104
+ keep_alive_s: int | None = Field(default=None, ge=0, le=7 * 24 * 3600)
105
+ load_timeout_s: float = Field(default=300.0, gt=0, le=3600)
106
+ # Upper bound for an explicit lease created with a load (`hold_s`).
107
+ max_lease_s: float = Field(default=3600.0, gt=0, le=7 * 24 * 3600)
108
+
109
+
110
+ class BackendConfig(StrictModel):
111
+ id: str
112
+ type: Literal["ollama", "openai_compatible"]
113
+ base_url: str
114
+ api_key_env: str | None = None
115
+ api_key: str | None = None
116
+ # Declared execution locality. "local" is a trust declaration that is
117
+ # cross-checked where the adapter has evidence (e.g. Ollama remote_model).
118
+ locality: Literal["local", "remote"] = "local"
119
+ resource_pool: str | None = None
120
+ discover: bool = True
121
+ # Models to register when discovery is unavailable or incomplete.
122
+ models: tuple[DeclaredModel, ...] = ()
123
+ timeout_s: float = 600.0
124
+ connect_timeout_s: float = 5.0
125
+ # Per-backend concurrency ceiling (in addition to pool limits).
126
+ max_concurrent: int = 4
127
+ circuit_failure_threshold: int = 3
128
+ circuit_cooldown_s: float = 30.0
129
+ # Ollama only. The server-wide default context the operator configured on the runtime
130
+ # (OLLAMA_CONTEXT_LENGTH / the app's context slider). Ollama does not expose that default for a
131
+ # model that is not loaded, so without this the gateway assumes 4096 for every model whose
132
+ # Modelfile sets no num_ctx. A declaration, with visible provenance; capped at the trained context.
133
+ default_context_length: int | None = Field(default=None, ge=256, le=10_000_000)
134
+ # Ollama only, opt-in. Remember the served context observed through /api/ps while a model was
135
+ # loaded (per deployment fingerprint) and keep using it after the model unloads, instead of
136
+ # falling back to the assumed default. Trade-off: if the runtime's context configuration is
137
+ # lowered afterwards, the remembered value overstates the served context until the model is next
138
+ # observed loaded - leave this off when the runtime's settings change often.
139
+ remember_served_context: bool = False
140
+ lifecycle: LifecycleConfig = LifecycleConfig()
141
+ # openai_compatible only. How image/audio items are sent to an embedding model: "vllm_chat" is vLLM's
142
+ # documented chat-style embeddings request (POST /v1/embeddings with `messages`); "auto" uses it when
143
+ # the server is detected as vLLM; "none" refuses media items for this backend.
144
+ multimodal_embeddings: Literal["auto", "vllm_chat", "none"] = "auto"
145
+
146
+ @field_validator("base_url")
147
+ @classmethod
148
+ def _url(cls, v: str) -> str:
149
+ if not (v.startswith("http://") or v.startswith("https://")):
150
+ raise ValueError("base_url must start with http:// or https://")
151
+ return v.rstrip("/")
152
+
153
+
154
+ class Capabilities(StrictModel):
155
+ """Three-state capability declarations (operator overrides)."""
156
+
157
+ tools: Tri = "unknown"
158
+ tool_choice_required: Tri = "unknown"
159
+ parallel_tools: Tri = "unknown"
160
+ json_schema: Tri = "unknown"
161
+ json_object: Tri = "unknown"
162
+ streaming: Tri = "unknown"
163
+ vision: Tri = "unknown"
164
+ audio_in: Tri = "unknown"
165
+ video_in: Tri = "unknown"
166
+ thinking: Tri = "unknown"
167
+ continuation: Tri = "unknown"
168
+
169
+
170
+ class DeclaredModel(StrictModel):
171
+ name: str
172
+ role: Literal["generative", "embedding", "decision", "ocr", "rerank", "guardrail"] = "generative"
173
+ context_length: int | None = None
174
+ max_output_tokens: int | None = None
175
+ capabilities: Capabilities = Capabilities()
176
+ tags: tuple[str, ...] = ()
177
+ enabled: bool = True
178
+ # Catalogue entry id for prior quality hints (optional).
179
+ catalogue_id: str | None = None
180
+ memory_gb_estimate: float | None = None
181
+ embedding_dimensions: int | None = None
182
+ # Operator-declared model identity (e.g. a weights digest or an exact revision id) for
183
+ # backends that expose none. Used to prove that two embedding deployments are the same
184
+ # model; a bare name match never is.
185
+ identity: str | None = None
186
+
187
+
188
+ class DeploymentOverride(StrictModel):
189
+ """Operator override applied after discovery, keyed by backend + model name."""
190
+
191
+ backend: str
192
+ model: str
193
+ enabled: bool | None = None
194
+ role: Literal["generative", "embedding", "decision", "ocr", "rerank", "guardrail"] | None = None
195
+ context_length: int | None = None
196
+ max_output_tokens: int | None = None
197
+ capabilities: Capabilities | None = None
198
+ tags: tuple[str, ...] | None = None
199
+ catalogue_id: str | None = None
200
+ memory_gb_estimate: float | None = None
201
+ quality_prior: dict[str, float] | None = None # task -> 0..1, labelled "operator"
202
+ intended_use_note: str | None = None
203
+
204
+
205
+ # --------------------------------------------------------------------------- #
206
+ # Routing
207
+ # --------------------------------------------------------------------------- #
208
+ class ProfileWeights(StrictModel):
209
+ quality: float = 1.0
210
+ latency: float = 0.2
211
+ residency: float = 0.15
212
+ overhead: float = 0.05
213
+
214
+
215
+ class RoutingProfiles(StrictModel):
216
+ quality: ProfileWeights = ProfileWeights(quality=1.0, latency=0.15, residency=0.1, overhead=0.05)
217
+ balanced: ProfileWeights = ProfileWeights(quality=1.0, latency=0.45, residency=0.3, overhead=0.1)
218
+ fast: ProfileWeights = ProfileWeights(quality=0.6, latency=1.0, residency=0.6, overhead=0.2)
219
+
220
+
221
+ class ClassifierConfig(StrictModel):
222
+ enabled: bool = False
223
+ backend: str | None = None
224
+ model: str | None = None
225
+ # How the classifier deployment is asked:
226
+ # "chat" — a small generative model answers a JSON object through chat completions (default);
227
+ # "decision" — a decision model (role=decision, e.g. Ollama's nimble/clef/laya) answers one
228
+ # `choice` question over the task labels through its native decision endpoint
229
+ # (Ollama POST /v1/systemone) and returns per-label probabilities, no free text.
230
+ mode: Literal["chat", "decision"] = "chat"
231
+ timeout_s: float = 2.0
232
+ max_input_chars: int = 1500
233
+ # Only consult the classifier when deterministic classification is unsure.
234
+ only_when_ambiguous: bool = True
235
+ max_output_tokens: int = 64
236
+ # The classifier receives an excerpt of the user's message. It must be a local deployment
237
+ # unless the operator explicitly allows a remote one here AND security.locality_mode permits it.
238
+ allow_remote: bool = False
239
+
240
+
241
+ class TokenEstimateConfig(StrictModel):
242
+ chars_per_token: float = 3.0 # conservative (most tokenizers ~3.5-4.5 chars/token for English)
243
+ per_message_overhead: int = 8
244
+ image_tokens: int = 1200
245
+ # Allowance per inline video part. No runtime reports video token cost before decoding; this is a
246
+ # deliberately large placeholder so a video request is not squeezed into a small context.
247
+ video_tokens: int = 8192
248
+ tool_definition_overhead: int = 24
249
+ default_max_output: int = 1024
250
+ reasoning_budget: int = 2048
251
+ safety_margin: float = 0.05
252
+ # Total wall-clock budget for exact token counting across all candidate deployments.
253
+ exact_count_deadline_s: float = 1.5
254
+
255
+
256
+ class RoutingConfig(StrictModel):
257
+ default_profile: Literal["quality", "balanced", "fast"] = "quality"
258
+ profiles: RoutingProfiles = RoutingProfiles()
259
+ # Penalty subtracted from a non-resident deployment's score (hysteresis).
260
+ switching_penalty: float = 0.08
261
+ classifier: ClassifierConfig = ClassifierConfig()
262
+ token_estimate: TokenEstimateConfig = TokenEstimateConfig()
263
+ # Allow one bounded failover before response commitment on connection errors.
264
+ pre_commit_failover: bool = True
265
+ max_failover_attempts: int = 1
266
+ # Conservative prior for deployments with no evidence (labelled uncalibrated).
267
+ uncalibrated_prior: float = 0.5
268
+ # Scheduling across hosts. "least_loaded": when the chosen deployment has verified replicas (the same
269
+ # model identity served by another backend/host), dispatch to the replica whose backend and pool are
270
+ # least occupied (in-flight + uncertain + queued, relative to their limits), and spill over to the next
271
+ # replica when admission refuses the first. Different models are never treated as replicas, and a pinned
272
+ # session, tool round trip or continuation stays where it is. "off": ranking order only (default).
273
+ replica_scheduling: Literal["off", "least_loaded"] = "off"
274
+
275
+
276
+ class CascadeConfig(StrictModel):
277
+ """Opt-in cascade for one alias (routing/cascade.py): the best deployment under ``first_profile`` answers
278
+ first; on a structural trigger the request is re-run on the next stage (the alias's own ranking).
279
+ Non-streaming requests only; never inside a tool round trip, continuation or pinned session."""
280
+
281
+ enabled: bool = False
282
+ first_profile: Literal["fast", "balanced"] = "fast"
283
+ escalate_on: tuple[Literal["length", "empty", "invalid_json", "missing_tool_call"], ...] = ("length", "empty", "invalid_json", "missing_tool_call")
284
+ max_stages: int = Field(default=2, ge=2, le=3)
285
+
286
+
287
+ class AliasConfig(StrictModel):
288
+ profile: Literal["quality", "balanced", "fast"] = "quality"
289
+ cascade: CascadeConfig = CascadeConfig()
290
+ require_tags: tuple[str, ...] = ()
291
+ require_vision: bool = False
292
+ # Restrict to these deployment ids (optional).
293
+ deployments: tuple[str, ...] = ()
294
+ description: str = ""
295
+
296
+
297
+ class AffinityConfig(StrictModel):
298
+ mode: Literal["session", "stateless"] = "session"
299
+ ttl_s: float = 3600.0
300
+ max_sessions: int = 10000
301
+ session_headers: tuple[str, ...] = ("X-ModelSaar-Session", "X-OpenWebUI-Chat-Id")
302
+ body_fields: tuple[str, ...] = ("prompt_cache_key",)
303
+ # Keep the same deployment while a tool round trip is outstanding even
304
+ # without a session id (uses the tool_call ids as the continuity key).
305
+ tool_round_trip_affinity: bool = True
306
+
307
+
308
+ class EmbeddingContract(StrictModel):
309
+ alias: str
310
+ deployments: tuple[str, ...] # all must be the same model identity; validated at refresh
311
+ dimensions: int | None = None
312
+ normalized: bool = True
313
+ # Reserved: the gateway never rewrites embedding inputs, so any non-empty prefix would be
314
+ # a silent contract change. Rejected at load.
315
+ query_prefix: str = ""
316
+ document_prefix: str = ""
317
+ # Optional expected identity (digest / revision) every member must match.
318
+ identity: str | None = None
319
+ note: str = ""
320
+ # Input modalities of this index contract. Text-only by default: an image or audio item is refused
321
+ # unless the contract lists the modality (and the deployment and backend path can embed it).
322
+ modalities: tuple[Literal["text", "image", "audio", "video"], ...] = ("text",)
323
+
324
+ @model_validator(mode="after")
325
+ def _check(self) -> EmbeddingContract:
326
+ if not self.deployments:
327
+ raise ValueError(f"embedding contract {self.alias!r} lists no deployments")
328
+ if self.query_prefix or self.document_prefix:
329
+ raise ValueError(
330
+ f"embedding contract {self.alias!r}: query_prefix/document_prefix are not applied by"
331
+ " the gateway (inputs are forwarded verbatim); remove them"
332
+ )
333
+ return self
334
+
335
+
336
+ class ObservabilityConfig(StrictModel):
337
+ decision_log: bool = True
338
+ retention_days: int = 7
339
+ log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
340
+
341
+
342
+ class AdmissionConfig(StrictModel):
343
+ # Hold an "uncertain" reservation after a disconnect until the backend is
344
+ # confirmed idle or this many seconds elapse.
345
+ uncertain_hold_s: float = 20.0
346
+ max_queue: int = 32
347
+ queue_timeout_s: float = 30.0
348
+
349
+
350
+ class GuardrailPipelineConfig(StrictModel):
351
+ """``POST /v1/guardrails``. The guardian block follows the structure documented for IBM Granite
352
+ Guardian (mode instruction, ``### Criteria:``, ``### Scoring Schema:``; block sent as the final user
353
+ message). Its wording belongs to the judge model: adjust it to the model card you verified."""
354
+
355
+ # Named criteria the operator vouches for (name -> criterion text). The gateway ships none.
356
+ criteria: dict[str, str] = Field(default_factory=dict)
357
+ template: str = (
358
+ "<guardian>{mode}\n\n### Criteria: {criteria}\n\n"
359
+ "### Scoring Schema: If the last {target}'s text meets the criteria, return 'yes'; otherwise, return 'no'."
360
+ )
361
+ think_instruction: str = "<think>"
362
+ no_think_instruction: str = "<no-think>"
363
+ max_criteria: int = Field(default=8, ge=1, le=32)
364
+ max_output_tokens: int = Field(default=64, ge=8, le=4096)
365
+ max_output_tokens_think: int = Field(default=1024, ge=64, le=16384)
366
+
367
+ @field_validator("template")
368
+ @classmethod
369
+ def _tpl(cls, v: str) -> str:
370
+ for ph in ("{mode}", "{criteria}", "{target}"):
371
+ if ph not in v:
372
+ raise ValueError(f"pipelines.guardrail.template must contain {ph}")
373
+ return v
374
+
375
+
376
+ class OcrLayoutConfig(StrictModel):
377
+ """Optional layout stage for ``POST /v1/ocr`` (``"layout": true``): an operator-run layout-detection
378
+ service is asked for the page's regions, the gateway crops them (needs the ``ocr-layout`` extra) and the
379
+ OCR model recognises each one. The gateway runs no layout model itself. ``url`` is the full endpoint,
380
+ e.g. a PaddleX-served PP-DocLayout model; the request is ``{<image_field>: <base64 image>}``."""
381
+
382
+ url: str | None = None
383
+ image_field: str = "image"
384
+ # Extra JSON fields sent with every layout request, e.g. {"visualize": false} for a PaddleX-served
385
+ # pipeline so that it does not return a rendered image.
386
+ request_extra: dict[str, bool | int | float | str | None] = Field(default_factory=dict)
387
+ locality: Literal["local", "remote"] = "local"
388
+ timeout_s: float = Field(default=60.0, gt=0, le=600)
389
+ min_score: float = Field(default=0.5, ge=0.0, le=1.0)
390
+ # Resource bounds of the layout stage. The compressed-size cap (max_image_bytes) does not bound what a
391
+ # decoder allocates, so the DECODED page is limited by its header dimensions before any pixel is loaded,
392
+ # and the crops by their summed area (before cropping) and summed encoded size (while cropping).
393
+ max_page_pixels: int = Field(default=40_000_000, ge=1, le=400_000_000)
394
+ max_crop_pixels_total: int = Field(default=80_000_000, ge=1, le=800_000_000)
395
+ max_crop_bytes_total: int = Field(default=64_000_000, ge=1, le=1_000_000_000)
396
+ # Bounds on the layout service's answer: bytes read and boxes accepted.
397
+ max_response_bytes: int = Field(default=4_000_000, ge=64, le=64_000_000)
398
+ max_boxes: int = Field(default=512, ge=1, le=10_000)
399
+ # Layout label -> OCR task; labels listed in skip_labels are reported but not recognised; any other
400
+ # label is recognised as text.
401
+ label_tasks: dict[str, str] = Field(default_factory=lambda: {"table": "table", "formula": "formula", "display formula": "formula", "display_formula": "formula"})
402
+ skip_labels: tuple[str, ...] = ("image", "figure", "chart", "seal", "header image", "footer image", "header_image", "footer_image")
403
+
404
+ @field_validator("url")
405
+ @classmethod
406
+ def _u(cls, v: str | None) -> str | None:
407
+ if v is not None and not (v.startswith("http://") or v.startswith("https://")):
408
+ raise ValueError("pipelines.ocr.layout.url must start with http:// or https://")
409
+ return v
410
+
411
+
412
+ class OcrPipelineConfig(StrictModel):
413
+ """``POST /v1/ocr``: recognition stage only (no layout analysis). Task -> the model's task-prefix prompt."""
414
+
415
+ task_prompts: dict[str, str] = Field(
416
+ default_factory=lambda: {"text": "Text Recognition:", "table": "Table Recognition:", "formula": "Formula Recognition:"}
417
+ )
418
+ max_regions: int = Field(default=16, ge=1, le=256)
419
+ max_output_tokens: int = Field(default=4096, ge=16, le=65536)
420
+ max_image_bytes: int = Field(default=8_000_000, ge=1024, le=64_000_000)
421
+ layout: OcrLayoutConfig = OcrLayoutConfig()
422
+
423
+
424
+ class LearningConfig(StrictModel):
425
+ """Opt-in adaptive learning from outcomes (learning.py, docs/learning.md). Disabled = nothing recorded."""
426
+
427
+ enabled: bool = False
428
+ holdout_fraction: float = Field(default=0.2, gt=0.0, lt=0.9)
429
+ # A (deployment, task) cell enters a policy only with at least this many training outcomes.
430
+ min_samples: int = Field(default=20, ge=1)
431
+ # A policy can be activated only when at least this many holdout outcomes were scored ...
432
+ min_holdout: int = Field(default=10, ge=1)
433
+ # ... and its Brier score beats the current estimates by at least this margin.
434
+ min_improvement: float = Field(default=0.0, ge=0.0, le=1.0)
435
+ retention_days: int = Field(default=30, ge=1, le=3650)
436
+
437
+
438
+ class ResponsesStoreConfig(StrictModel):
439
+ """Opt-in local response store for ``POST /v1/responses`` (responses_store.py). Enabling it lets a
440
+ request ask for ``store: true`` and continue with ``previous_response_id``; content is then kept at
441
+ rest in the state database, per API key, until ``ttl_s`` passes or the response is deleted."""
442
+
443
+ enabled: bool = False
444
+ ttl_s: float = Field(default=86400.0, gt=0, le=90 * 86400)
445
+ max_bytes: int = Field(default=2_000_000, ge=1024, le=64_000_000)
446
+ max_chain: int = Field(default=64, ge=1, le=1024)
447
+
448
+
449
+ class ProtocolsConfig(StrictModel):
450
+ responses_store: ResponsesStoreConfig = ResponsesStoreConfig()
451
+
452
+
453
+ class EnsembleConfig(StrictModel):
454
+ """Bounded ensembles over CLOSED choices only (``POST /v1/vote``; ``ensemble`` on ``/v1/guardrails``).
455
+ Free-text answers are never aggregated."""
456
+
457
+ max_members: int = Field(default=3, ge=2, le=9)
458
+ max_choices: int = Field(default=16, ge=2, le=64)
459
+ max_output_tokens: int = Field(default=1024, ge=16, le=8192)
460
+
461
+
462
+ class PipelinesConfig(StrictModel):
463
+ guardrail: GuardrailPipelineConfig = GuardrailPipelineConfig()
464
+ ocr: OcrPipelineConfig = OcrPipelineConfig()
465
+ ensemble: EnsembleConfig = EnsembleConfig()
466
+
467
+
468
+ class Config(StrictModel):
469
+ version: int = CONFIG_VERSION
470
+ server: ServerConfig = ServerConfig()
471
+ security: SecurityConfig = SecurityConfig()
472
+ resource_pools: tuple[ResourcePool, ...] = ()
473
+ backends: tuple[BackendConfig, ...] = ()
474
+ deployments: tuple[DeploymentOverride, ...] = ()
475
+ aliases: dict[str, AliasConfig] = Field(
476
+ default_factory=lambda: {
477
+ "auto": AliasConfig(profile="quality", description="Best expected quality within limits"),
478
+ "auto-quality": AliasConfig(profile="quality"),
479
+ "auto-balanced": AliasConfig(profile="balanced"),
480
+ "auto-fast": AliasConfig(profile="fast"),
481
+ "auto-code": AliasConfig(profile="quality", require_tags=("code",)),
482
+ "auto-vision": AliasConfig(profile="quality", require_vision=True),
483
+ }
484
+ )
485
+ routing: RoutingConfig = RoutingConfig()
486
+ affinity: AffinityConfig = AffinityConfig()
487
+ embeddings: tuple[EmbeddingContract, ...] = ()
488
+ admission: AdmissionConfig = AdmissionConfig()
489
+ observability: ObservabilityConfig = ObservabilityConfig()
490
+ pipelines: PipelinesConfig = PipelinesConfig()
491
+ learning: LearningConfig = LearningConfig()
492
+ protocols: ProtocolsConfig = ProtocolsConfig()
493
+
494
+ # Set by the loader; not part of the file.
495
+ config_path: str | None = Field(default=None, exclude=True)
496
+ config_hash: str = Field(default="", exclude=True)
497
+
498
+ @model_validator(mode="after")
499
+ def _check(self) -> Config:
500
+ if self.version != CONFIG_VERSION:
501
+ raise ValueError(
502
+ f"config version {self.version} is not supported by this build (expected {CONFIG_VERSION}); "
503
+ "run `modelsaar config migrate`"
504
+ )
505
+ ids = [b.id for b in self.backends]
506
+ if len(ids) != len(set(ids)):
507
+ raise ValueError("backend ids must be unique")
508
+ pools = {p.id for p in self.resource_pools}
509
+ for b in self.backends:
510
+ if b.resource_pool and b.resource_pool not in pools:
511
+ raise ValueError(f"backend {b.id} references unknown resource_pool {b.resource_pool}")
512
+ if self.security.allow_lan is False and self.server.host not in ("127.0.0.1", "localhost", "::1"):
513
+ raise ValueError(
514
+ "server.host is not loopback but security.allow_lan is false; "
515
+ "set security.allow_lan: true explicitly to expose the gateway on the LAN"
516
+ )
517
+ for a in self.aliases:
518
+ if not a.startswith("auto"):
519
+ raise ValueError(f"alias names must start with 'auto' (got {a!r})")
520
+ cl = self.routing.classifier
521
+ if cl.enabled and (not cl.backend or not cl.model):
522
+ raise ValueError("routing.classifier.enabled requires backend and model")
523
+ return self
524
+
525
+ # Resolve a path relative to the config directory.
526
+ def resolve(self, p: str) -> Path:
527
+ path = Path(p).expanduser()
528
+ if path.is_absolute():
529
+ return path
530
+ base = Path(self.config_path).parent if self.config_path else Path.cwd()
531
+ return base / path
532
+
533
+ @property
534
+ def config_dir(self) -> Path:
535
+ return Path(self.config_path).parent if self.config_path else Path.cwd()
536
+
537
+
538
+ def default_config_path() -> Path:
539
+ env = os.environ.get("MODELSAAR_CONFIG")
540
+ if env:
541
+ return Path(env).expanduser()
542
+ home = os.environ.get("MODELSAAR_HOME")
543
+ base = Path(home).expanduser() if home else Path.home() / ".modelsaar"
544
+ return base / "config.yaml"
545
+
546
+
547
+ def load_config(path: Path | None = None) -> Config:
548
+ path = path or default_config_path()
549
+ raw = path.read_text(encoding="utf-8")
550
+ data = yaml.safe_load(raw) or {}
551
+ if not isinstance(data, dict):
552
+ raise ValueError("config root must be a mapping")
553
+ cfg = Config.model_validate(data)
554
+ import hashlib
555
+
556
+ h = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
557
+ return cfg.model_copy(update={"config_path": str(path), "config_hash": h})
558
+
559
+
560
+ def config_to_yaml(cfg: Config) -> str:
561
+ data = cfg.model_dump(mode="json", exclude_none=True)
562
+ return yaml.safe_dump(data, sort_keys=False, allow_unicode=True)
563
+
564
+
565
+ def _write_private_atomic(path: Path, text: str) -> None:
566
+ """Create with mode 0600 from the first byte (no world-readable window), fsync, then replace."""
567
+ path.parent.mkdir(parents=True, exist_ok=True)
568
+ try:
569
+ os.chmod(path.parent, 0o700)
570
+ except OSError:
571
+ pass
572
+ tmp = path.with_suffix(path.suffix + ".tmp")
573
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
574
+ try:
575
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
576
+ f.write(text)
577
+ f.flush()
578
+ os.fsync(f.fileno())
579
+ except Exception:
580
+ try:
581
+ os.unlink(tmp)
582
+ except OSError:
583
+ pass
584
+ raise
585
+ os.replace(tmp, path)
586
+ try:
587
+ os.chmod(path, 0o600)
588
+ except OSError:
589
+ pass
590
+
591
+
592
+ def write_config_atomic(cfg: Config, path: Path) -> None:
593
+ _write_private_atomic(path, config_to_yaml(cfg))
594
+
595
+
596
+ def generate_key(prefix: str = "msk") -> str:
597
+ return f"{prefix}_{secrets.token_urlsafe(32)}"
598
+
599
+
600
+ def read_keys(path: Path) -> list[str]:
601
+ if not path.exists():
602
+ return []
603
+ return [ln.strip() for ln in path.read_text(encoding="utf-8").splitlines() if ln.strip() and not ln.startswith("#")]
604
+
605
+
606
+ def write_key_file(path: Path, keys: list[str]) -> None:
607
+ _write_private_atomic(path, "\n".join(keys) + "\n")
608
+
609
+
610
+ class ExampleKind(str, Enum):
611
+ ollama = "ollama"
612
+
613
+
614
+ def example_config(backend_url: str = "http://127.0.0.1:11434", backend_type: str = "ollama") -> Config:
615
+ return Config(
616
+ resource_pools=(ResourcePool(id="local-machine", kind="unified", max_concurrent=1),),
617
+ backends=(
618
+ BackendConfig(
619
+ id="ollama",
620
+ type=backend_type, # type: ignore[arg-type]
621
+ base_url=backend_url,
622
+ resource_pool="local-machine",
623
+ ),
624
+ ),
625
+ )
626
+
627
+
628
+ def dump_any(obj: Any) -> Any:
629
+ if isinstance(obj, BaseModel):
630
+ return obj.model_dump(mode="json")
631
+ return obj