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,364 @@
1
+ """Client configuration generators (Open WebUI, OpenClaw, OpenCode V1/V2, Hermes Agent).
2
+
3
+ Every key emitted here was checked against the client's current primary
4
+ documentation on 2026-10-11 (see docs/clients/*.md for sources). Generators
5
+ only *propose* changes; ``--apply`` writes a backup and merges into the file,
6
+ preserving unrelated settings.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import stat
14
+ import time
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import yaml
20
+
21
+
22
+ @dataclass
23
+ class AliasInfo:
24
+ name: str
25
+ context_length: int
26
+ tools: bool
27
+ vision: bool
28
+ description: str = ""
29
+
30
+
31
+ @dataclass
32
+ class ClientTarget:
33
+ gateway_url: str # e.g. http://127.0.0.1:8484 (no /v1)
34
+ api_key_env: str = "MODELSAAR_API_KEY"
35
+ aliases: list[AliasInfo] | None = None
36
+ in_docker: bool = False
37
+
38
+ @property
39
+ def base_v1(self) -> str:
40
+ url = self.gateway_url.rstrip("/")
41
+ if self.in_docker:
42
+ url = url.replace("127.0.0.1", "host.docker.internal").replace("localhost", "host.docker.internal")
43
+ return url + "/v1"
44
+
45
+ def alias_list(self) -> list[AliasInfo]:
46
+ return self.aliases or [AliasInfo("auto", 8192, False, False, "Best expected quality within limits")]
47
+
48
+
49
+ CLIENTS = ("open-webui", "openclaw", "opencode", "opencode-v2", "hermes")
50
+
51
+
52
+ # --------------------------------------------------------------------------- #
53
+ def open_webui(t: ClientTarget) -> str:
54
+ aliases = t.alias_list()
55
+ names = ", ".join(a.name for a in aliases)
56
+ return f"""# Open WebUI -> ModelSaar (checked against docs 2026-10-11)
57
+
58
+ Open WebUI concatenates paths onto the connection URL (`{{url}}/chat/completions`, `{{url}}/models`),
59
+ so the URL MUST include `/v1` and must not end with a slash.
60
+
61
+ ## UI steps
62
+ 1. Admin Panel -> Settings -> Connections -> "Manage OpenAI API Connections" -> Add Connection
63
+ 2. URL: {t.base_v1}
64
+ 3. API Key: <your ModelSaar API key> (file: ~/.modelsaar/keys/api_keys)
65
+ 4. Save, then "Verify Connection" (this calls GET {t.base_v1}/models with a Bearer token).
66
+ Models are auto-listed from /models: {names} plus concrete deployments.
67
+
68
+ ## Environment-variable equivalent (Docker / compose)
69
+ ENABLE_OPENAI_API=true
70
+ OPENAI_API_BASE_URLS={t.base_v1}
71
+ OPENAI_API_KEYS=<your ModelSaar API key>
72
+ # Route Open WebUI's background tasks (titles, tags, follow-ups) to the fast alias instead of the chat model:
73
+ TASK_MODEL_EXTERNAL=auto-fast
74
+ # Optional: forward the chat id so ModelSaar keeps a conversation on one deployment (session affinity):
75
+ ENABLE_FORWARD_USER_INFO_HEADERS=true # sends X-OpenWebUI-Chat-Id (and user headers) to the gateway
76
+
77
+ ## Docker networking
78
+ Open WebUI in a container cannot reach 127.0.0.1 of the host. Use host.docker.internal (macOS/Windows);
79
+ on Linux add `--add-host=host.docker.internal:host-gateway` and bind ModelSaar to a non-loopback address
80
+ (server.host: 0.0.0.0, security.allow_lan: true) - only on a trusted network. Podman: host.containers.internal.
81
+
82
+ ## Notes
83
+ - Tool calling: Native (default) mode sends `tools`; Open WebUI does not send tool_choice.
84
+ - Per-model capability toggles (vision, etc.) live in Admin -> Models; ModelSaar also enforces them server-side.
85
+ """
86
+
87
+
88
+ def openclaw(t: ClientTarget) -> dict[str, Any]:
89
+ models = []
90
+ for a in t.alias_list():
91
+ models.append(
92
+ {
93
+ "id": a.name,
94
+ "name": f"ModelSaar {a.name}",
95
+ "reasoning": False,
96
+ "input": ["text", "image"] if a.vision else ["text"],
97
+ "contextWindow": a.context_length,
98
+ "maxTokens": min(32000, max(1024, a.context_length // 4)),
99
+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
100
+ "compat": {"supportsTools": a.tools, "supportsPromptCacheKey": True},
101
+ }
102
+ )
103
+ primary = t.alias_list()[0].name
104
+ return {
105
+ "agents": {"defaults": {"model": {"primary": f"modelsaar/{primary}"}}},
106
+ "models": {
107
+ "mode": "merge",
108
+ "providers": {
109
+ "modelsaar": {
110
+ "baseUrl": t.base_v1,
111
+ "apiKey": f"${{{t.api_key_env}}}",
112
+ "api": "openai-completions",
113
+ "timeoutSeconds": 300,
114
+ "models": models,
115
+ }
116
+ },
117
+ },
118
+ }
119
+
120
+
121
+ def openclaw_text(t: ClientTarget) -> str:
122
+ cfg = openclaw(t)
123
+ return f"""# OpenClaw -> ModelSaar (checked against docs.openclaw.ai 2026-10-11, release v2026.9.9)
124
+
125
+ File: ~/.openclaw/openclaw.json (JSON5; comments allowed). Custom providers are NOT auto-discovered from
126
+ /v1/models, so each alias you want must be declared under models.providers.modelsaar.models[].
127
+ `api: "openai-completions"` is the Chat Completions adapter (default when omitted; do not use openai-responses).
128
+ `compat.supportsPromptCacheKey: true` makes OpenClaw send `prompt_cache_key` (session id) so ModelSaar can keep
129
+ a session on one deployment. Set the key in your environment: export {t.api_key_env}=<your key>.
130
+
131
+ Merge this into your config (`modelsaar client-config openclaw --apply` does it with a backup when the file is plain JSON):
132
+
133
+ {json.dumps(cfg, indent=2)}
134
+ """
135
+
136
+
137
+ def opencode_v1(t: ClientTarget) -> dict[str, Any]:
138
+ models: dict[str, Any] = {}
139
+ for a in t.alias_list():
140
+ models[a.name] = {
141
+ "name": f"ModelSaar {a.name}",
142
+ "tool_call": a.tools,
143
+ "reasoning": False,
144
+ "attachment": a.vision,
145
+ "modalities": {"input": ["text", "image"] if a.vision else ["text"], "output": ["text"]},
146
+ "limit": {"context": a.context_length, "output": min(32000, max(1024, a.context_length // 4))},
147
+ "cost": {"input": 0, "output": 0},
148
+ }
149
+ return {
150
+ "$schema": "https://opencode.ai/config.json",
151
+ "model": f"modelsaar/{t.alias_list()[0].name}",
152
+ "provider": {
153
+ "modelsaar": {
154
+ "npm": "@ai-sdk/openai-compatible",
155
+ "name": "ModelSaar",
156
+ "options": {"baseURL": t.base_v1, "apiKey": f"{{env:{t.api_key_env}}}", "setCacheKey": True},
157
+ "models": models,
158
+ }
159
+ },
160
+ }
161
+
162
+
163
+ def opencode_v2(t: ClientTarget) -> dict[str, Any]:
164
+ models: dict[str, Any] = {}
165
+ for a in t.alias_list():
166
+ models[a.name] = {
167
+ "name": f"ModelSaar {a.name}",
168
+ "capabilities": {"tools": a.tools, "input": ["text", "image"] if a.vision else ["text"], "output": ["text"]},
169
+ }
170
+ return {
171
+ "$schema": "https://opencode.ai/config.json",
172
+ "providers": {
173
+ "modelsaar": {
174
+ "name": "ModelSaar",
175
+ "env": [t.api_key_env],
176
+ "package": "@opencode/ai/providers/openai-compatible",
177
+ "settings": {"baseURL": t.base_v1},
178
+ "models": models,
179
+ }
180
+ },
181
+ }
182
+
183
+
184
+ def opencode_text(t: ClientTarget, v2: bool = False) -> str:
185
+ if v2:
186
+ return f"""# OpenCode V2 -> ModelSaar (checked against opencode.ai/v2/docs 2026-10-11)
187
+
188
+ File: ~/.config/opencode/opencode.json(c) or <project>/.opencode/opencode.json(c).
189
+ V2 uses top-level `providers` / `package` / `settings` / `capabilities`. NEVER mix with V1 keys
190
+ (`provider` / `npm` / `options` / `tool_call`) in one entry. Credential comes from the env var listed in `env`.
191
+ `@opencode/ai/providers/openai-compatible` speaks Chat Completions; include /v1 in baseURL.
192
+
193
+ {json.dumps(opencode_v2(t), indent=2)}
194
+ """
195
+ return f"""# OpenCode V1 -> ModelSaar (checked against opencode.ai/docs 2026-10-11, docs updated Oct 8 2026)
196
+
197
+ File: ~/.config/opencode/opencode.json (global) or ./opencode.json (project). JSON or JSONC.
198
+ V1 uses top-level `provider` (singular) with `npm: "@ai-sdk/openai-compatible"` (Chat Completions; do NOT use
199
+ `@ai-sdk/openai`, which defaults to the Responses API that ModelSaar does not implement). Include /v1 in baseURL.
200
+ Models are declared manually; `tool_call: true` is required for agent use. `setCacheKey: true` asks OpenCode to
201
+ attach its session id as a prompt cache key (whether the compatible transport emits it on the wire is not
202
+ documented - affinity falls back to tool-round-trip continuity, which always works).
203
+ Set the key: export {t.api_key_env}=<your key>
204
+
205
+ {json.dumps(opencode_v1(t), indent=2)}
206
+ """
207
+
208
+
209
+ def hermes(t: ClientTarget) -> dict[str, Any]:
210
+ primary = t.alias_list()[0]
211
+ return {
212
+ "model": {
213
+ "default": primary.name,
214
+ "provider": "custom",
215
+ "base_url": t.base_v1,
216
+ "key_env": t.api_key_env,
217
+ "context_length": primary.context_length,
218
+ },
219
+ "providers": {
220
+ "modelsaar": {
221
+ "api": t.base_v1,
222
+ "key_env": t.api_key_env,
223
+ "transport": "chat_completions",
224
+ "default_model": primary.name,
225
+ "context_length": primary.context_length,
226
+ "session_affinity_header": "X-ModelSaar-Session",
227
+ }
228
+ },
229
+ }
230
+
231
+
232
+ def hermes_text(t: ClientTarget) -> str:
233
+ return f"""# NousResearch Hermes Agent -> ModelSaar (checked against hermes-agent.nousresearch.com docs 2026-10-11)
234
+
235
+ File: ~/.hermes/config.yaml (single source of truth); secrets in ~/.hermes/.env.
236
+ Each provider has ITS OWN credential setting (`key_env` / `api_key` / `key_cmd`). There is no generic
237
+ HERMES_* variable for custom endpoints, and OPENAI_BASE_URL applies only to the built-in openai-api provider.
238
+ `transport: chat_completions` (default) is what ModelSaar implements. `session_affinity_header` makes Hermes
239
+ send its conversation id in that header; ModelSaar reads X-ModelSaar-Session by default.
240
+ Interactive alternative: `hermes model` -> "Custom endpoint" -> URL {t.base_v1}.
241
+
242
+ ~/.hermes/.env:
243
+ {t.api_key_env}=<your ModelSaar API key>
244
+
245
+ ~/.hermes/config.yaml (merge; `modelsaar client-config hermes --apply` merges with a backup):
246
+ {yaml.safe_dump(hermes(t), sort_keys=False)}
247
+ """
248
+
249
+
250
+ # --------------------------------------------------------------------------- #
251
+ def render(client: str, t: ClientTarget) -> str:
252
+ if client == "open-webui":
253
+ return open_webui(t)
254
+ if client == "openclaw":
255
+ return openclaw_text(t)
256
+ if client == "opencode":
257
+ return opencode_text(t, v2=False)
258
+ if client == "opencode-v2":
259
+ return opencode_text(t, v2=True)
260
+ if client == "hermes":
261
+ return hermes_text(t)
262
+ raise ValueError(f"unknown client {client}; choose one of {CLIENTS}")
263
+
264
+
265
+ def _deep_merge(base: Any, patch: Any) -> Any:
266
+ if isinstance(base, dict) and isinstance(patch, dict):
267
+ out = dict(base)
268
+ for k, v in patch.items():
269
+ out[k] = _deep_merge(out.get(k), v) if k in out else v
270
+ return out
271
+ return patch
272
+
273
+
274
+ def default_path(client: str) -> Path | None:
275
+ home = Path.home()
276
+ return {
277
+ "openclaw": home / ".openclaw" / "openclaw.json",
278
+ "opencode": home / ".config" / "opencode" / "opencode.json",
279
+ "opencode-v2": home / ".config" / "opencode" / "opencode.json",
280
+ "hermes": home / ".hermes" / "config.yaml",
281
+ }.get(client)
282
+
283
+
284
+ def proposed_patch(client: str, t: ClientTarget) -> dict[str, Any] | None:
285
+ if client == "openclaw":
286
+ return openclaw(t)
287
+ if client == "opencode":
288
+ return opencode_v1(t)
289
+ if client == "opencode-v2":
290
+ return opencode_v2(t)
291
+ if client == "hermes":
292
+ return hermes(t)
293
+ return None
294
+
295
+
296
+ def apply_patch(client: str, t: ClientTarget, path: Path | None = None, dry_run: bool = True) -> dict[str, Any]:
297
+ """Merge the proposed snippet into the client's config file.
298
+
299
+ Returns {path, existed, backup, before, after, applied}. Idempotent: re-applying yields no change.
300
+ """
301
+ patch = proposed_patch(client, t)
302
+ if patch is None:
303
+ raise ValueError(f"{client} is configured through its UI/env; nothing to apply")
304
+ path = path or default_path(client)
305
+ assert path is not None
306
+ existed = path.exists()
307
+ text = path.read_text(encoding="utf-8") if existed else ""
308
+ is_yaml = path.suffix in (".yaml", ".yml")
309
+ if existed and text.strip():
310
+ try:
311
+ current = yaml.safe_load(text) if is_yaml else json.loads(text)
312
+ except Exception as e:
313
+ raise ValueError(
314
+ f"{path} is not parseable as {'YAML' if is_yaml else 'strict JSON'} ({e}); "
315
+ "it may use JSON5/JSONC comments. Merge the printed snippet manually."
316
+ ) from e
317
+ else:
318
+ current = {}
319
+ if client in ("opencode", "opencode-v2") and isinstance(current, dict):
320
+ if client == "opencode" and "providers" in current:
321
+ raise ValueError("this file uses the OpenCode V2 schema (`providers`); use `client-config opencode-v2`")
322
+ if client == "opencode-v2" and "provider" in current:
323
+ raise ValueError("this file uses the OpenCode V1 schema (`provider`); use `client-config opencode`")
324
+ merged = _deep_merge(current or {}, patch)
325
+ after = yaml.safe_dump(merged, sort_keys=False) if is_yaml else json.dumps(merged, indent=2) + "\n"
326
+ changed = after != text
327
+ result = {"path": str(path), "existed": existed, "backup": None, "changed": changed, "applied": False, "after": after}
328
+ if dry_run or not changed:
329
+ return result
330
+ path.parent.mkdir(parents=True, exist_ok=True)
331
+ # Preserve the existing mode (never weaken it); new files are private because the snippet
332
+ # carries the gateway API key.
333
+ mode = stat.S_IMODE(path.stat().st_mode) if existed else 0o600
334
+ if existed:
335
+ stamp = time.strftime("%Y%m%d-%H%M%S")
336
+ backup = path.with_name(path.name + f".bak-{stamp}")
337
+ n = 1
338
+ while backup.exists():
339
+ n += 1
340
+ backup = path.with_name(path.name + f".bak-{stamp}-{n}")
341
+ _write_with_mode(backup, text, mode)
342
+ result["backup"] = str(backup)
343
+ tmp = path.with_name(path.name + ".tmp")
344
+ _write_with_mode(tmp, after, mode)
345
+ tmp.replace(path)
346
+ result["applied"] = True
347
+ return result
348
+
349
+
350
+ def _write_with_mode(target: Path, content: str, mode: int) -> None:
351
+ """Create ``target`` with ``mode`` from the first byte (O_EXCL: never follow a planted symlink)."""
352
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
353
+ try:
354
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
355
+ f.write(content)
356
+ f.flush()
357
+ os.fsync(f.fileno())
358
+ os.chmod(target, mode) # the open() mode is subject to umask; enforce the intended bits
359
+ except Exception:
360
+ try:
361
+ target.unlink()
362
+ except OSError:
363
+ pass
364
+ raise