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/cli.py
ADDED
|
@@ -0,0 +1,880 @@
|
|
|
1
|
+
"""`modelsaar` command-line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from . import __version__
|
|
17
|
+
from .config import (
|
|
18
|
+
BackendConfig,
|
|
19
|
+
Config,
|
|
20
|
+
ResourcePool,
|
|
21
|
+
config_to_yaml,
|
|
22
|
+
default_config_path,
|
|
23
|
+
generate_key,
|
|
24
|
+
load_config,
|
|
25
|
+
read_keys,
|
|
26
|
+
write_config_atomic,
|
|
27
|
+
write_key_file,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _out(obj: Any, as_json: bool = False) -> None:
|
|
32
|
+
if as_json:
|
|
33
|
+
print(json.dumps(obj, indent=2, default=str))
|
|
34
|
+
else:
|
|
35
|
+
print(obj if isinstance(obj, str) else json.dumps(obj, indent=2, default=str))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _load(args: argparse.Namespace) -> Config:
|
|
39
|
+
path = Path(args.config) if getattr(args, "config", None) else default_config_path()
|
|
40
|
+
try:
|
|
41
|
+
return load_config(path)
|
|
42
|
+
except FileNotFoundError:
|
|
43
|
+
sys.exit(f"config not found at {path}; run `modelsaar init` first (or pass --config)")
|
|
44
|
+
except Exception as e:
|
|
45
|
+
sys.exit(f"invalid config {path}: {e}")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _router_with_evidence(cfg: Config): # type: ignore[no-untyped-def]
|
|
49
|
+
"""Router that sees stored probe/measurement evidence when a state DB exists (never creates one)."""
|
|
50
|
+
from .routing.router import Router
|
|
51
|
+
from .store import Store
|
|
52
|
+
|
|
53
|
+
db = cfg.resolve(cfg.server.state_db)
|
|
54
|
+
return Router(cfg, Store(db) if db.exists() else None)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _admin_client(cfg: Config) -> httpx.Client:
|
|
58
|
+
keys = read_keys(cfg.resolve(cfg.server.admin_key_file))
|
|
59
|
+
if not keys:
|
|
60
|
+
sys.exit("admin key file missing; run `modelsaar keys rotate --admin`")
|
|
61
|
+
return httpx.Client(base_url=f"http://{cfg.server.host}:{cfg.server.port}", headers={"Authorization": f"Bearer {keys[0]}"}, timeout=30)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _api_client(cfg: Config) -> httpx.Client:
|
|
65
|
+
keys = read_keys(cfg.resolve(cfg.server.api_keys_file))
|
|
66
|
+
if not keys:
|
|
67
|
+
sys.exit("api key file missing; run `modelsaar keys rotate`")
|
|
68
|
+
return httpx.Client(base_url=f"http://{cfg.server.host}:{cfg.server.port}", headers={"Authorization": f"Bearer {keys[0]}"}, timeout=120)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# --------------------------------------------------------------------------- #
|
|
72
|
+
def cmd_init(args: argparse.Namespace) -> None:
|
|
73
|
+
path = Path(args.config) if args.config else default_config_path()
|
|
74
|
+
if path.exists() and not args.force:
|
|
75
|
+
sys.exit(f"{path} already exists; use --force to overwrite (keys and state are preserved)")
|
|
76
|
+
endpoint = args.endpoint
|
|
77
|
+
btype = args.type
|
|
78
|
+
if not endpoint:
|
|
79
|
+
# Probe documented loopback defaults only (never scans networks).
|
|
80
|
+
candidates = [("http://127.0.0.1:11434", "ollama"), ("http://127.0.0.1:1234/v1", "openai_compatible"), ("http://127.0.0.1:8080/v1", "openai_compatible"), ("http://127.0.0.1:8000/v1", "openai_compatible")]
|
|
81
|
+
for url, t in candidates:
|
|
82
|
+
try:
|
|
83
|
+
r = httpx.get(url + ("/api/version" if t == "ollama" else "/models"), timeout=1.5)
|
|
84
|
+
if r.status_code == 200:
|
|
85
|
+
endpoint, btype = url, t
|
|
86
|
+
print(f"discovered {t} at {url}")
|
|
87
|
+
break
|
|
88
|
+
except httpx.HTTPError:
|
|
89
|
+
continue
|
|
90
|
+
if not endpoint:
|
|
91
|
+
sys.exit("no inference endpoint found on documented loopback defaults; pass --endpoint URL --type ollama|openai_compatible")
|
|
92
|
+
cfg = Config(
|
|
93
|
+
resource_pools=(ResourcePool(id="local-machine", kind="unified", max_concurrent=args.max_concurrent),),
|
|
94
|
+
backends=(BackendConfig(id=args.backend_id, type=btype, base_url=endpoint, resource_pool="local-machine"),),
|
|
95
|
+
)
|
|
96
|
+
cfg = cfg.model_copy(update={"server": cfg.server.model_copy(update={"port": args.port})})
|
|
97
|
+
cfg = cfg.model_copy(update={"routing": cfg.routing.model_copy(update={"default_profile": args.profile})})
|
|
98
|
+
# The `auto` alias carries its own profile; the advertised default must be what `auto` does.
|
|
99
|
+
aliases = dict(cfg.aliases)
|
|
100
|
+
aliases["auto"] = aliases["auto"].model_copy(update={"profile": args.profile})
|
|
101
|
+
cfg = cfg.model_copy(update={"aliases": aliases, "config_path": str(path)})
|
|
102
|
+
write_config_atomic(cfg, path)
|
|
103
|
+
api_p, adm_p = cfg.resolve(cfg.server.api_keys_file), cfg.resolve(cfg.server.admin_key_file)
|
|
104
|
+
if not read_keys(api_p):
|
|
105
|
+
write_key_file(api_p, [generate_key("msk")])
|
|
106
|
+
if not read_keys(adm_p):
|
|
107
|
+
write_key_file(adm_p, [generate_key("msa")])
|
|
108
|
+
print(f"wrote {path}")
|
|
109
|
+
print(f"API key: {api_p}")
|
|
110
|
+
print(f"admin key: {adm_p}")
|
|
111
|
+
# One-shot discovery so the user sees what will be routable.
|
|
112
|
+
cfg = load_config(path)
|
|
113
|
+
|
|
114
|
+
async def _disc() -> list[dict[str, Any]]:
|
|
115
|
+
r = _router_with_evidence(cfg)
|
|
116
|
+
await r.refresh()
|
|
117
|
+
out = r.registry.snapshot()
|
|
118
|
+
err = r.last_refresh_error
|
|
119
|
+
await r.aclose()
|
|
120
|
+
if err:
|
|
121
|
+
print(f"warning: discovery error: {err}")
|
|
122
|
+
return out
|
|
123
|
+
|
|
124
|
+
deps = asyncio.run(_disc())
|
|
125
|
+
print(f"discovered {len(deps)} deployment(s):")
|
|
126
|
+
for d in deps:
|
|
127
|
+
print(f" {d['id']:40s} role={d['role']:10s} ctx={d['context_length']} tools={d['capabilities']['tools']['value']} vision={d['capabilities']['vision']['value']} locality={d['locality']}")
|
|
128
|
+
print("\nnext steps:")
|
|
129
|
+
print(" modelsaar doctor # check reachability, context assumptions, unknown capabilities")
|
|
130
|
+
print(" modelsaar probe --all # verify tools/json/vision/streaming on each model (uses local compute)")
|
|
131
|
+
print(" modelsaar serve # start the gateway")
|
|
132
|
+
print(" modelsaar client-config open-webui|openclaw|opencode|opencode-v2|hermes")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def cmd_discover(args: argparse.Namespace) -> None:
|
|
136
|
+
cfg = _load(args)
|
|
137
|
+
|
|
138
|
+
async def _run() -> dict[str, Any]:
|
|
139
|
+
r = _router_with_evidence(cfg)
|
|
140
|
+
await r.refresh()
|
|
141
|
+
out = {"error": r.last_refresh_error, "deployments": r.registry.snapshot(), "aliases": {a: r.alias_contract(a) for a in cfg.aliases}}
|
|
142
|
+
await r.aclose()
|
|
143
|
+
return out
|
|
144
|
+
|
|
145
|
+
res = asyncio.run(_run())
|
|
146
|
+
if args.json:
|
|
147
|
+
_out(res, True)
|
|
148
|
+
return
|
|
149
|
+
if res["error"]:
|
|
150
|
+
print(f"error: {res['error']}")
|
|
151
|
+
for d in res["deployments"]:
|
|
152
|
+
st = d["state"]
|
|
153
|
+
print(
|
|
154
|
+
f"{d['id']:40s} {d['role']:10s} ctx={d['context_length']!s:7s} "
|
|
155
|
+
f"tools={d['capabilities']['tools']['value']:11s} vision={d['capabilities']['vision']['value']:11s} "
|
|
156
|
+
f"json_schema={d['capabilities']['json_schema']['value']:11s} loaded={st['loaded']} healthy={st['healthy']} locality={d['locality']}"
|
|
157
|
+
)
|
|
158
|
+
print("aliases:")
|
|
159
|
+
for a, c in res["aliases"].items():
|
|
160
|
+
print(f" {a:14s} " + (f"-> {c['deployments']} ctx>={c['context_length_min']} tools={c['tools']} vision={c['vision']}" if c else "(not advertised: no usable deployment)"))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _gateway_listening(cfg: Config) -> str | None:
|
|
164
|
+
"""'gateway' when a ModelSaar gateway answers /healthz on the configured address, 'other' when
|
|
165
|
+
something else holds the port, None when the port is free."""
|
|
166
|
+
url = f"http://{cfg.server.host}:{cfg.server.port}"
|
|
167
|
+
try:
|
|
168
|
+
r = httpx.get(f"{url}/healthz", timeout=2.0)
|
|
169
|
+
except httpx.ConnectError:
|
|
170
|
+
return None
|
|
171
|
+
except httpx.HTTPError:
|
|
172
|
+
return "other"
|
|
173
|
+
try:
|
|
174
|
+
return "gateway" if r.status_code == 200 and r.json().get("status") == "ok" and "version" in r.json() else "other"
|
|
175
|
+
except ValueError:
|
|
176
|
+
return "other"
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _print_probe_report(rep: dict[str, Any]) -> None:
|
|
180
|
+
for res in rep.get("results", []):
|
|
181
|
+
print(f" {res['capability']:16s} {res['value']:12s} {res['latency_ms']:7.0f}ms {res.get('note', '')}")
|
|
182
|
+
for m in rep.get("measurements", []):
|
|
183
|
+
p50, ttft, load = m.get("p50_ms"), m.get("ttft_ms"), m.get("load_ms")
|
|
184
|
+
print(f" latency p50={p50 and round(p50)}ms ttft={ttft and round(ttft)}ms load~{load and round(load)}ms (samples={m.get('samples')})")
|
|
185
|
+
for e in rep.get("errors", []):
|
|
186
|
+
print(f" error: {e}")
|
|
187
|
+
if rep.get("skipped"):
|
|
188
|
+
print(f" not run (uncertain timeout): {', '.join(rep['skipped'])}")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def cmd_probe(args: argparse.Namespace) -> None:
|
|
192
|
+
"""Probes use inference. While a gateway is running they go through POST /admin/probe so the
|
|
193
|
+
gateway's admission (slots, queue, memory budget) coordinates them with live traffic. Direct
|
|
194
|
+
(offline) probing is only allowed when no gateway listens on the configured port, or with
|
|
195
|
+
--allow-concurrent (the operator accepts uncoordinated concurrent inference)."""
|
|
196
|
+
cfg = _load(args)
|
|
197
|
+
listening = _gateway_listening(cfg)
|
|
198
|
+
if listening == "gateway" and not args.offline:
|
|
199
|
+
_probe_via_gateway(cfg, args)
|
|
200
|
+
return
|
|
201
|
+
if listening is not None and not args.allow_concurrent:
|
|
202
|
+
what = "a ModelSaar gateway" if listening == "gateway" else "another process"
|
|
203
|
+
sys.exit(
|
|
204
|
+
f"{what} is listening on {cfg.server.host}:{cfg.server.port}; direct probing would run inference "
|
|
205
|
+
"outside the gateway's admission control. Drop --offline to probe through the gateway, stop it, "
|
|
206
|
+
"or pass --allow-concurrent to accept uncoordinated concurrent inference."
|
|
207
|
+
)
|
|
208
|
+
if listening is None:
|
|
209
|
+
print(f"no gateway at {cfg.server.host}:{cfg.server.port}; probing directly (offline, uncoordinated with any other inference)")
|
|
210
|
+
_probe_offline(cfg, args)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _probe_via_gateway(cfg: Config, args: argparse.Namespace) -> None:
|
|
214
|
+
reports: list[dict[str, Any]] = []
|
|
215
|
+
with _admin_client(cfg) as c:
|
|
216
|
+
c.timeout = httpx.Timeout(args.timeout * 8 + 60)
|
|
217
|
+
status = c.get("/admin/status")
|
|
218
|
+
if status.status_code != 200:
|
|
219
|
+
sys.exit(f"gateway at {c.base_url} refused the admin key ({status.status_code}); check {cfg.server.admin_key_file}")
|
|
220
|
+
deps = status.json().get("deployments", [])
|
|
221
|
+
targets = [
|
|
222
|
+
d["id"]
|
|
223
|
+
for d in deps
|
|
224
|
+
if d.get("role") == "generative" and (d.get("state") or {}).get("healthy") and (args.all or d["id"] in args.deployment)
|
|
225
|
+
]
|
|
226
|
+
if cfg.security.locality_mode == "local_only":
|
|
227
|
+
targets = [d["id"] for d in deps if d["id"] in targets and d.get("locality") == "local"]
|
|
228
|
+
if not targets:
|
|
229
|
+
print("no matching generative deployments (check `modelsaar discover`)")
|
|
230
|
+
for dep_id in targets:
|
|
231
|
+
print(f"probing {dep_id} via gateway {c.base_url} (admission-coordinated) ...")
|
|
232
|
+
r = c.post("/admin/probe", json={"deployment": dep_id, "which": args.which or None, "timeout": args.timeout})
|
|
233
|
+
if r.status_code != 200:
|
|
234
|
+
print(f" refused ({r.status_code}): {r.json().get('error', {}).get('message', r.text[:200])}")
|
|
235
|
+
continue
|
|
236
|
+
rep = r.json()
|
|
237
|
+
_print_probe_report(rep)
|
|
238
|
+
reports.append(rep)
|
|
239
|
+
if args.json:
|
|
240
|
+
_out(reports, True)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _probe_offline(cfg: Config, args: argparse.Namespace) -> None:
|
|
244
|
+
from .probes import run_probes
|
|
245
|
+
from .routing.router import Router
|
|
246
|
+
from .store import Store
|
|
247
|
+
|
|
248
|
+
async def _run() -> list[dict[str, Any]]:
|
|
249
|
+
store = Store(cfg.resolve(cfg.server.state_db))
|
|
250
|
+
r = Router(cfg, store)
|
|
251
|
+
await r.refresh()
|
|
252
|
+
targets = [d for d in r.registry.all() if d.role == "generative" and d.healthy and (args.all or d.id in args.deployment)]
|
|
253
|
+
if cfg.security.locality_mode == "local_only":
|
|
254
|
+
targets = [d for d in targets if d.locality == "local"]
|
|
255
|
+
if not targets:
|
|
256
|
+
print("no matching generative deployments (check `modelsaar discover`)")
|
|
257
|
+
reports = []
|
|
258
|
+
for d in targets:
|
|
259
|
+
print(f"probing {d.id} (fingerprint {d.fingerprint}) ...")
|
|
260
|
+
# The offline path still respects this process's own admission (pool memory budget, slots).
|
|
261
|
+
reservation = await r.admission.acquire(d, timeout=None)
|
|
262
|
+
try:
|
|
263
|
+
rep = await run_probes(r.adapters[d.backend_id], d, store, args.which or None, timeout=args.timeout)
|
|
264
|
+
except BaseException:
|
|
265
|
+
await reservation.release()
|
|
266
|
+
raise
|
|
267
|
+
if rep.uncertain:
|
|
268
|
+
# The backend may still be computing: in this offline process the hold only delays the
|
|
269
|
+
# next deployment's probes; the gateway-coordinated path holds the real slot.
|
|
270
|
+
await reservation.mark_uncertain()
|
|
271
|
+
await asyncio.sleep(min(r.admission.cfg.uncertain_hold_s, 5.0))
|
|
272
|
+
else:
|
|
273
|
+
await reservation.release()
|
|
274
|
+
_print_probe_report(rep.as_dict())
|
|
275
|
+
reports.append(rep.as_dict())
|
|
276
|
+
await r.aclose()
|
|
277
|
+
store.close()
|
|
278
|
+
return reports
|
|
279
|
+
|
|
280
|
+
reps = asyncio.run(_run())
|
|
281
|
+
if args.json:
|
|
282
|
+
_out(reps, True)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def cmd_serve(args: argparse.Namespace) -> None:
|
|
286
|
+
cfg = _load(args)
|
|
287
|
+
import uvicorn
|
|
288
|
+
|
|
289
|
+
from .runtime import build, configure_logging
|
|
290
|
+
|
|
291
|
+
configure_logging(cfg.observability.log_level)
|
|
292
|
+
app, router, auth, store = build(cfg)
|
|
293
|
+
if not auth.configured:
|
|
294
|
+
sys.exit("API/admin key files are missing; run `modelsaar keys ensure` (or `modelsaar init`)")
|
|
295
|
+
url = f"http://{cfg.server.host}:{cfg.server.port}"
|
|
296
|
+
print(f"ModelSaar {__version__} on {url}/v1 (config {cfg.config_path}, hash {cfg.config_hash})")
|
|
297
|
+
print(f"API key file: {cfg.resolve(cfg.server.api_keys_file)}")
|
|
298
|
+
print(f"admin key file: {cfg.resolve(cfg.server.admin_key_file)}")
|
|
299
|
+
print(f"status page: {url}/admin/ui (enter the admin key)")
|
|
300
|
+
uvicorn.run(app, host=cfg.server.host, port=cfg.server.port, log_level="warning")
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def cmd_status(args: argparse.Namespace) -> None:
|
|
304
|
+
cfg = _load(args)
|
|
305
|
+
try:
|
|
306
|
+
with _admin_client(cfg) as c:
|
|
307
|
+
s = c.get("/admin/status").json()
|
|
308
|
+
except httpx.HTTPError as e:
|
|
309
|
+
sys.exit(f"gateway not reachable at {cfg.server.host}:{cfg.server.port}: {e}")
|
|
310
|
+
if args.json:
|
|
311
|
+
_out(s, True)
|
|
312
|
+
return
|
|
313
|
+
print(f"ModelSaar {s['version']} up {s['uptime_s']}s requests={s['requests_total']} failed={s['requests_failed']} ready={s['ready']}")
|
|
314
|
+
if s.get("last_refresh_error"):
|
|
315
|
+
print(f"refresh error: {s['last_refresh_error']}")
|
|
316
|
+
print("aliases:")
|
|
317
|
+
for a, c in s["aliases"].items():
|
|
318
|
+
print(f" {a:14s} " + (f"{c['deployments']} ctx>={c['context_length_min']} tools={c['tools']} vision={c['vision']}" if c else "(not advertised)"))
|
|
319
|
+
print("deployments:")
|
|
320
|
+
for d in s["deployments"]:
|
|
321
|
+
st = d["state"]
|
|
322
|
+
print(f" {d['id']:40s} {d['role']:10s} healthy={st['healthy']} loaded={st['loaded']} ctx={d['context_length']} tools={d['capabilities']['tools']['value']}")
|
|
323
|
+
print(f"admission: {s['admission']}")
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def cmd_lifecycle(args: argparse.Namespace) -> None:
|
|
327
|
+
"""Managed lifecycle through the running gateway (admin). Only backends with `lifecycle.managed: true`."""
|
|
328
|
+
cfg = _load(args)
|
|
329
|
+
try:
|
|
330
|
+
with _admin_client(cfg) as c:
|
|
331
|
+
c.timeout = httpx.Timeout(600.0)
|
|
332
|
+
if args.action == "status":
|
|
333
|
+
r = c.get("/admin/lifecycle")
|
|
334
|
+
elif args.action == "load":
|
|
335
|
+
body: dict[str, Any] = {"deployment": args.target}
|
|
336
|
+
if args.hold is not None:
|
|
337
|
+
body["hold_s"] = args.hold
|
|
338
|
+
r = c.post("/admin/lifecycle/load", json=body)
|
|
339
|
+
elif args.action == "unload":
|
|
340
|
+
r = c.post("/admin/lifecycle/unload", json={"deployment": args.target})
|
|
341
|
+
else:
|
|
342
|
+
r = c.post("/admin/lifecycle/release", json={"lease": args.target})
|
|
343
|
+
except httpx.HTTPError as e:
|
|
344
|
+
sys.exit(f"gateway not reachable at {cfg.server.host}:{cfg.server.port}: {e} (lifecycle operations go through a running gateway)")
|
|
345
|
+
data = r.json()
|
|
346
|
+
if r.status_code != 200:
|
|
347
|
+
sys.exit(f"refused ({r.status_code} {data.get('error', {}).get('code')}): {data.get('error', {}).get('message')}")
|
|
348
|
+
if args.json or args.action != "status":
|
|
349
|
+
_out(data, True)
|
|
350
|
+
return
|
|
351
|
+
for bid, b in data["backends"].items():
|
|
352
|
+
print(f"{bid:16s} managed={b['managed']} operations={b['operations']} loaded={b['loaded']} in_flight={b['in_flight']}")
|
|
353
|
+
for le in data["leases"]:
|
|
354
|
+
print(f"lease {le['id']} {le['deployment']} holder={le['holder']} expires_in={le['expires_in_s']}s")
|
|
355
|
+
for h in data["history"][-10:]:
|
|
356
|
+
print(f" {time.strftime('%H:%M:%S', time.localtime(h['at']))} {h['operation']:6s} {h['deployment']} -> {h['outcome']} {h['detail']}")
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def cmd_learn(args: argparse.Namespace) -> None:
|
|
360
|
+
"""Opt-in adaptive learning through the running gateway (admin): status, build, activate, rollback, purge."""
|
|
361
|
+
cfg = _load(args)
|
|
362
|
+
try:
|
|
363
|
+
with _admin_client(cfg) as c:
|
|
364
|
+
if args.action == "status":
|
|
365
|
+
r = c.get("/admin/learning")
|
|
366
|
+
else:
|
|
367
|
+
r = c.post(f"/admin/learning/{args.action}", json={"version": args.version} if args.action == "activate" else {})
|
|
368
|
+
except httpx.HTTPError as e:
|
|
369
|
+
sys.exit(f"gateway not reachable at {cfg.server.host}:{cfg.server.port}: {e}")
|
|
370
|
+
data = r.json()
|
|
371
|
+
if r.status_code != 200:
|
|
372
|
+
sys.exit(f"refused ({r.status_code} {data.get('error', {}).get('code')}): {data.get('error', {}).get('message')}")
|
|
373
|
+
_out(data, True)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def cmd_doctor(args: argparse.Namespace) -> None:
|
|
377
|
+
path = Path(args.config) if args.config else default_config_path()
|
|
378
|
+
cfg: Config | None = None
|
|
379
|
+
err: str | None = None
|
|
380
|
+
try:
|
|
381
|
+
cfg = load_config(path)
|
|
382
|
+
except Exception as e:
|
|
383
|
+
err = str(e)
|
|
384
|
+
from .doctor import run_doctor_sync
|
|
385
|
+
|
|
386
|
+
rep = run_doctor_sync(cfg, err, path)
|
|
387
|
+
if args.json:
|
|
388
|
+
_out(rep.as_dict(), True)
|
|
389
|
+
else:
|
|
390
|
+
for f in rep.findings:
|
|
391
|
+
mark = {"ok": "OK ", "warn": "WARN", "fail": "FAIL"}[f.level]
|
|
392
|
+
print(f"[{mark}] {f.area}: {f.message}" + (f"\n -> {f.remedy}" if f.remedy else ""))
|
|
393
|
+
print(f"\n{rep.failures} failure(s)")
|
|
394
|
+
sys.exit(1 if rep.failures else 0)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _explain_body(args: argparse.Namespace) -> dict[str, Any]:
|
|
398
|
+
if args.file:
|
|
399
|
+
return json.loads(Path(args.file).read_text(encoding="utf-8"))
|
|
400
|
+
body: dict[str, Any] = {"model": args.model, "messages": [{"role": "user", "content": args.message or "Hello"}]}
|
|
401
|
+
if args.tools:
|
|
402
|
+
body["tools"] = [{"type": "function", "function": {"name": "bash", "description": "Run a shell command", "parameters": {"type": "object", "properties": {"cmd": {"type": "string"}}}}}]
|
|
403
|
+
if args.image:
|
|
404
|
+
body["messages"][0]["content"] = [{"type": "text", "text": args.message or "Describe"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}]
|
|
405
|
+
if args.json_schema:
|
|
406
|
+
body["response_format"] = {"type": "json_schema", "json_schema": {"name": "x", "schema": {"type": "object"}}}
|
|
407
|
+
return body
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def cmd_explain(args: argparse.Namespace) -> None:
|
|
411
|
+
cfg = _load(args)
|
|
412
|
+
body = _explain_body(args)
|
|
413
|
+
if args.live:
|
|
414
|
+
with _admin_client(cfg) as c:
|
|
415
|
+
dec = c.post("/admin/explain", json=body).json()
|
|
416
|
+
else:
|
|
417
|
+
from .routing.router import NoEligibleDeployment, Router
|
|
418
|
+
from .store import Store
|
|
419
|
+
|
|
420
|
+
async def _run() -> dict[str, Any]:
|
|
421
|
+
store = Store(cfg.resolve(cfg.server.state_db))
|
|
422
|
+
r = Router(cfg, store)
|
|
423
|
+
await r.refresh()
|
|
424
|
+
try:
|
|
425
|
+
d = await r.route_chat(body, {}, "explain")
|
|
426
|
+
d.outcome = "explain_only"
|
|
427
|
+
res = d.as_dict()
|
|
428
|
+
except NoEligibleDeployment as e:
|
|
429
|
+
res = e.decision.as_dict()
|
|
430
|
+
await r.aclose()
|
|
431
|
+
store.close()
|
|
432
|
+
return res
|
|
433
|
+
|
|
434
|
+
dec = asyncio.run(_run())
|
|
435
|
+
if args.json:
|
|
436
|
+
_out(dec, True)
|
|
437
|
+
return
|
|
438
|
+
print(f"request {dec['request_id']}: {dec['requested_model']} -> {dec.get('chosen') or 'NO ELIGIBLE DEPLOYMENT'} (profile {dec['profile']}, {dec['overhead_ms']} ms)")
|
|
439
|
+
req = dec.get("requirements", {})
|
|
440
|
+
print(f"task: {req.get('primary_task')} {req.get('tasks')} ambiguous={req.get('ambiguous')} tokens~{(req.get('tokens') or {}).get('total')}")
|
|
441
|
+
for r in dec.get("reasons", []):
|
|
442
|
+
print(f" - {r}")
|
|
443
|
+
if dec.get("classifier"):
|
|
444
|
+
print(f"classifier: {dec['classifier']}")
|
|
445
|
+
if dec.get("candidates"):
|
|
446
|
+
print("candidates:")
|
|
447
|
+
for c in dec["candidates"]:
|
|
448
|
+
print(f" {c['deployment']:40s} score={c['score']:+.3f} quality={c['quality']:.2f}±{c['uncertainty']:.2f} [{c['evidence']}] latency={c['latency_cost']:.2f} residency={c['residency_cost']:.2f} {c['notes']}")
|
|
449
|
+
if dec.get("exclusions"):
|
|
450
|
+
print("excluded:")
|
|
451
|
+
for d, why in dec["exclusions"].items():
|
|
452
|
+
print(f" {d}: {'; '.join(why)}")
|
|
453
|
+
if dec.get("remedies"):
|
|
454
|
+
print("remedies: " + " | ".join(dec["remedies"]))
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def cmd_decisions(args: argparse.Namespace) -> None:
|
|
458
|
+
cfg = _load(args)
|
|
459
|
+
with _admin_client(cfg) as c:
|
|
460
|
+
if args.request_id:
|
|
461
|
+
_out(c.get(f"/admin/decisions/{args.request_id}").json(), True)
|
|
462
|
+
else:
|
|
463
|
+
for d in c.get(f"/admin/decisions?limit={args.limit}").json()["decisions"]:
|
|
464
|
+
print(f"{d['request_id']} {d['requested_model']:14s} -> {d.get('chosen')!s:40s} {d.get('outcome'):14s} {d['overhead_ms']:6.1f}ms {(d.get('requirements') or {}).get('primary_task')}")
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
HEALTH_SERVICE = "modelsaar"
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def gateway_identity(base_url: str, timeout: float = 5.0) -> tuple[str, dict[str, Any] | None]:
|
|
471
|
+
"""Identify what listens at ``base_url`` WITHOUT sending a key: ``("modelsaar", health)`` when
|
|
472
|
+
GET /healthz returns the ModelSaar health contract (JSON with service=modelsaar); ``("none",
|
|
473
|
+
None)`` when nothing accepts connections; ``("other", None)`` for any other listener (a plain
|
|
474
|
+
200 is not enough — an unrelated service must be treated as a port collision)."""
|
|
475
|
+
try:
|
|
476
|
+
r = httpx.get(base_url.rstrip("/") + "/healthz", timeout=timeout, headers={"Accept": "application/json"})
|
|
477
|
+
except httpx.ConnectError:
|
|
478
|
+
return "none", None
|
|
479
|
+
except httpx.HTTPError:
|
|
480
|
+
return "other", None
|
|
481
|
+
try:
|
|
482
|
+
body = r.json()
|
|
483
|
+
except ValueError:
|
|
484
|
+
return "other", None
|
|
485
|
+
if r.status_code == 200 and isinstance(body, dict) and body.get("service") == HEALTH_SERVICE:
|
|
486
|
+
return "modelsaar", body
|
|
487
|
+
return "other", None
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def cmd_test(args: argparse.Namespace) -> None:
|
|
491
|
+
cfg = _load(args)
|
|
492
|
+
base = f"http://{cfg.server.host}:{cfg.server.port}"
|
|
493
|
+
kind, health = gateway_identity(base)
|
|
494
|
+
if kind == "none":
|
|
495
|
+
sys.exit(
|
|
496
|
+
f"no gateway is listening at {base} — start it with `modelsaar serve` "
|
|
497
|
+
"(in another terminal, or under launchd/systemd; see examples/) and run `modelsaar test` again"
|
|
498
|
+
)
|
|
499
|
+
if kind == "other":
|
|
500
|
+
sys.exit(
|
|
501
|
+
f"something that is not a ModelSaar gateway is listening at {base} (GET /healthz did not return the "
|
|
502
|
+
"ModelSaar health contract). No key was sent. Port collision: stop that service or set server.port to "
|
|
503
|
+
"a free port in the config and restart `modelsaar serve`."
|
|
504
|
+
)
|
|
505
|
+
print(f"GET /healthz -> modelsaar {health.get('version', '?')}")
|
|
506
|
+
with _api_client(cfg) as c:
|
|
507
|
+
r = c.get("/v1/models")
|
|
508
|
+
if r.status_code == 401:
|
|
509
|
+
sys.exit(f"the gateway at {base} rejected the API key from {cfg.resolve(cfg.server.api_keys_file)}; restart the gateway after `modelsaar keys rotate`")
|
|
510
|
+
print(f"GET /v1/models -> {r.status_code}: {[m['id'] for m in r.json().get('data', [])]}")
|
|
511
|
+
body = {"model": args.model, "messages": [{"role": "user", "content": args.message}], "max_tokens": 64}
|
|
512
|
+
t0 = time.monotonic()
|
|
513
|
+
r = c.post("/v1/chat/completions", json=body)
|
|
514
|
+
ms = (time.monotonic() - t0) * 1000
|
|
515
|
+
dep, rid = r.headers.get("x-modelsaar-deployment"), r.headers.get("x-modelsaar-request-id")
|
|
516
|
+
print(f"POST /v1/chat/completions -> {r.status_code} in {ms:.0f}ms; deployment={dep} request={rid}")
|
|
517
|
+
if r.status_code != 200:
|
|
518
|
+
_out(r.json(), True)
|
|
519
|
+
sys.exit(1)
|
|
520
|
+
if not rid or not dep:
|
|
521
|
+
# A 200 without ModelSaar attribution did not come from this gateway's router.
|
|
522
|
+
sys.exit("the response carries no ModelSaar routing attribution (X-ModelSaar-Request-Id / X-ModelSaar-Deployment); this is not a ModelSaar-routed completion")
|
|
523
|
+
try:
|
|
524
|
+
content = r.json()["choices"][0]["message"].get("content") or ""
|
|
525
|
+
except (KeyError, IndexError, TypeError, ValueError):
|
|
526
|
+
sys.exit("the response is not a chat completion envelope")
|
|
527
|
+
print(f"routed: {args.model!r} -> {dep} (request {rid})")
|
|
528
|
+
print("content:", content[:300])
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def cmd_client_config(args: argparse.Namespace) -> None:
|
|
532
|
+
cfg = _load(args)
|
|
533
|
+
from .clientconfig import CLIENTS, AliasInfo, ClientTarget, apply_patch, render
|
|
534
|
+
|
|
535
|
+
aliases: list[AliasInfo] = []
|
|
536
|
+
try:
|
|
537
|
+
with _admin_client(cfg) as c:
|
|
538
|
+
s = c.get("/admin/status").json()
|
|
539
|
+
for a, con in s["aliases"].items():
|
|
540
|
+
if con:
|
|
541
|
+
aliases.append(AliasInfo(a, con["context_length_min"] or 4096, con["tools"] == "supported", con["vision"] == "supported", con.get("description", "")))
|
|
542
|
+
except Exception:
|
|
543
|
+
|
|
544
|
+
async def _run() -> list[AliasInfo]:
|
|
545
|
+
r = _router_with_evidence(cfg)
|
|
546
|
+
await r.refresh()
|
|
547
|
+
out = []
|
|
548
|
+
for a in cfg.aliases:
|
|
549
|
+
con = r.alias_contract(a)
|
|
550
|
+
if con:
|
|
551
|
+
out.append(AliasInfo(a, con["context_length_min"] or 4096, con["tools"] == "supported", con["vision"] == "supported", con.get("description", "")))
|
|
552
|
+
await r.aclose()
|
|
553
|
+
return out
|
|
554
|
+
|
|
555
|
+
aliases = asyncio.run(_run())
|
|
556
|
+
if not aliases:
|
|
557
|
+
print("warning: no alias currently has a usable deployment; generating config with `auto` placeholders")
|
|
558
|
+
t = ClientTarget(gateway_url=f"http://{cfg.server.host}:{cfg.server.port}", aliases=aliases or None, in_docker=args.docker)
|
|
559
|
+
if args.client not in CLIENTS:
|
|
560
|
+
sys.exit(f"unknown client; choose one of {CLIENTS}")
|
|
561
|
+
print(render(args.client, t))
|
|
562
|
+
if args.apply or args.dry_run:
|
|
563
|
+
try:
|
|
564
|
+
res = apply_patch(args.client, t, Path(args.path) if args.path else None, dry_run=not args.apply)
|
|
565
|
+
except ValueError as e:
|
|
566
|
+
sys.exit(str(e))
|
|
567
|
+
if not res["changed"]:
|
|
568
|
+
print(f"{res['path']}: already up to date (idempotent)")
|
|
569
|
+
elif res["applied"]:
|
|
570
|
+
print(f"applied to {res['path']}" + (f" (backup: {res['backup']})" if res["backup"] else " (new file)"))
|
|
571
|
+
else:
|
|
572
|
+
print(f"--- proposed content for {res['path']} (not written; add --apply) ---\n{res['after']}")
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def cmd_keys(args: argparse.Namespace) -> None:
|
|
576
|
+
cfg = _load(args)
|
|
577
|
+
api_p, adm_p = cfg.resolve(cfg.server.api_keys_file), cfg.resolve(cfg.server.admin_key_file)
|
|
578
|
+
if args.keys_cmd == "show":
|
|
579
|
+
print(f"API keys ({api_p}): {len(read_keys(api_p))} key(s)")
|
|
580
|
+
print(f"admin keys ({adm_p}): {len(read_keys(adm_p))} key(s)")
|
|
581
|
+
if args.reveal:
|
|
582
|
+
print("api:", *read_keys(api_p))
|
|
583
|
+
print("admin:", *read_keys(adm_p))
|
|
584
|
+
elif args.keys_cmd == "ensure":
|
|
585
|
+
# Idempotent first-run bootstrap: create missing key files, never rotate existing ones,
|
|
586
|
+
# touch nothing but the key files (the config may be a read-only mount).
|
|
587
|
+
for label, p, prefix in (("API key", api_p, "msk"), ("admin key", adm_p, "msa")):
|
|
588
|
+
if read_keys(p):
|
|
589
|
+
print(f"{label}: unchanged ({p})")
|
|
590
|
+
else:
|
|
591
|
+
write_key_file(p, [generate_key(prefix)])
|
|
592
|
+
print(f"{label}: created ({p})")
|
|
593
|
+
elif args.keys_cmd == "rotate":
|
|
594
|
+
if args.admin:
|
|
595
|
+
write_key_file(adm_p, [generate_key("msa")])
|
|
596
|
+
print(f"rotated admin key -> {adm_p}")
|
|
597
|
+
else:
|
|
598
|
+
write_key_file(api_p, [generate_key("msk")])
|
|
599
|
+
print(f"rotated API key -> {api_p} (restart the gateway and update clients)")
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def cmd_config(args: argparse.Namespace) -> None:
|
|
603
|
+
path = Path(args.config) if args.config else default_config_path()
|
|
604
|
+
if args.config_cmd == "validate":
|
|
605
|
+
cfg = load_config(path)
|
|
606
|
+
print(f"ok: {path} (version {cfg.version}, {len(cfg.backends)} backend(s))")
|
|
607
|
+
elif args.config_cmd == "show":
|
|
608
|
+
print(config_to_yaml(load_config(path)))
|
|
609
|
+
elif args.config_cmd == "example":
|
|
610
|
+
from .config import example_config
|
|
611
|
+
|
|
612
|
+
print(config_to_yaml(example_config()))
|
|
613
|
+
elif args.config_cmd == "migrate":
|
|
614
|
+
import yaml
|
|
615
|
+
|
|
616
|
+
raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
|
617
|
+
v = int(raw.get("version", 0))
|
|
618
|
+
from . import CONFIG_VERSION
|
|
619
|
+
|
|
620
|
+
if v == CONFIG_VERSION:
|
|
621
|
+
print("config already at the current version; nothing to do")
|
|
622
|
+
return
|
|
623
|
+
sys.exit(f"no migration path from version {v} to {CONFIG_VERSION} in this build")
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def cmd_eval(args: argparse.Namespace) -> None:
|
|
627
|
+
from .evaluation.harness import run_eval_cli
|
|
628
|
+
|
|
629
|
+
run_eval_cli(args)
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def cmd_demo(args: argparse.Namespace) -> None:
|
|
633
|
+
"""Start a SIMULATED backend plus a gateway so the UX can be tried without models."""
|
|
634
|
+
import tempfile
|
|
635
|
+
|
|
636
|
+
from .runtime import GatewayThread, free_port
|
|
637
|
+
from .testing.fakebackend import FakeBackend, FakeModel
|
|
638
|
+
|
|
639
|
+
fake = FakeBackend(
|
|
640
|
+
[
|
|
641
|
+
FakeModel("sim-small:1b", ["completion", "tools"], 8192, parameter_size="1.0B", loaded=True, good_at=["conversation", "summarization"]),
|
|
642
|
+
FakeModel("sim-large:27b", ["completion", "tools", "vision", "thinking"], 32768, parameter_size="27B", size_bytes=18_000_000_000, good_at=["coding", "math", "agent", "extraction", "document_vision"]),
|
|
643
|
+
FakeModel("sim-embed:0.6b", ["embedding"], 2048, parameter_size="0.6B"),
|
|
644
|
+
]
|
|
645
|
+
)
|
|
646
|
+
burl = fake.start()
|
|
647
|
+
tmp = Path(tempfile.mkdtemp(prefix="modelsaar-demo-"))
|
|
648
|
+
api_key, admin_key = generate_key("msk"), generate_key("msa")
|
|
649
|
+
write_key_file(tmp / "keys/api_keys", [api_key])
|
|
650
|
+
write_key_file(tmp / "keys/admin_key", [admin_key])
|
|
651
|
+
cfg = Config(
|
|
652
|
+
resource_pools=(ResourcePool(id="sim", max_concurrent=2),),
|
|
653
|
+
backends=(BackendConfig(id="sim", type="ollama", base_url=burl, resource_pool="sim"),),
|
|
654
|
+
)
|
|
655
|
+
cfg = cfg.model_copy(update={"server": cfg.server.model_copy(update={"port": args.port or free_port()}), "config_path": str(tmp / "config.yaml"), "config_hash": "demo"})
|
|
656
|
+
write_config_atomic(cfg, tmp / "config.yaml")
|
|
657
|
+
gw = GatewayThread(cfg)
|
|
658
|
+
url = gw.start()
|
|
659
|
+
print("*** SIMULATED DEMO: the 'models' are fake backends that echo structure; no real inference happens. ***")
|
|
660
|
+
print(f"gateway: {url}/v1 config: {tmp / 'config.yaml'}")
|
|
661
|
+
print(f"API key: {api_key}")
|
|
662
|
+
print(f"admin key: {admin_key}")
|
|
663
|
+
print(f"status UI: {url}/admin/ui")
|
|
664
|
+
print(f"try: curl -s {url}/v1/chat/completions -H 'Authorization: Bearer {api_key}' -H 'Content-Type: application/json' -d '{{\"model\":\"auto\",\"messages\":[{{\"role\":\"user\",\"content\":\"Write a Python function\"}}]}}'")
|
|
665
|
+
print(f" MODELSAAR_CONFIG={tmp / 'config.yaml'} modelsaar explain --message 'refactor this python code' --tools")
|
|
666
|
+
try:
|
|
667
|
+
while True:
|
|
668
|
+
time.sleep(1)
|
|
669
|
+
except KeyboardInterrupt:
|
|
670
|
+
pass
|
|
671
|
+
finally:
|
|
672
|
+
gw.stop()
|
|
673
|
+
fake.stop()
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def _owned_files(home: Path, cfg: Config | None) -> tuple[list[Path], list[Path]]:
|
|
677
|
+
"""Files ModelSaar creates under its home, and the directories it creates for them."""
|
|
678
|
+
api = cfg.resolve(cfg.server.api_keys_file) if cfg else home / "keys/api_keys"
|
|
679
|
+
adm = cfg.resolve(cfg.server.admin_key_file) if cfg else home / "keys/admin_key"
|
|
680
|
+
db = cfg.resolve(cfg.server.state_db) if cfg else home / "state/modelsaar.db"
|
|
681
|
+
files = [home / "config.yaml", home / "config.yaml.tmp", api, api.with_name(api.name + ".tmp"), adm, adm.with_name(adm.name + ".tmp")]
|
|
682
|
+
files += [db, db.with_name(db.name + "-wal"), db.with_name(db.name + "-shm"), db.with_name(db.name + ".tmp")]
|
|
683
|
+
files += sorted(home.glob("config.yaml.bak*")) if home.exists() else []
|
|
684
|
+
dirs = sorted({api.parent, adm.parent, db.parent} - {home}, key=lambda d: len(d.parts), reverse=True)
|
|
685
|
+
return files, dirs
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def cmd_uninstall(args: argparse.Namespace) -> None:
|
|
689
|
+
path = Path(args.config) if args.config else default_config_path()
|
|
690
|
+
home = path.parent
|
|
691
|
+
print("ModelSaar uninstall removes ONLY the gateway's own files:")
|
|
692
|
+
print(f" {home} (config.yaml and its backups, its key files, its state database)")
|
|
693
|
+
print("It does NOT remove models from your inference runtime, nor any client configuration,")
|
|
694
|
+
print("nor any other file you placed under that directory.")
|
|
695
|
+
print("Client configs changed with `client-config --apply` have .bak-<timestamp> backups next to them.")
|
|
696
|
+
print("Afterwards remove the package with: pip uninstall modelsaar (or `uv tool uninstall modelsaar`)")
|
|
697
|
+
if not args.yes:
|
|
698
|
+
ans = input(f"delete ModelSaar's files under {home}? [y/N] ").strip().lower()
|
|
699
|
+
if ans != "y":
|
|
700
|
+
print("aborted")
|
|
701
|
+
return
|
|
702
|
+
if not home.exists():
|
|
703
|
+
print(f"{home} does not exist; nothing to remove")
|
|
704
|
+
return
|
|
705
|
+
cfg: Config | None
|
|
706
|
+
try:
|
|
707
|
+
cfg = load_config(path) if path.exists() else None
|
|
708
|
+
except Exception:
|
|
709
|
+
cfg = None # unparseable config: fall back to the default layout
|
|
710
|
+
files, dirs = _owned_files(home, cfg)
|
|
711
|
+
# Safety boundaries: never operate through symlinks, never outside home.
|
|
712
|
+
for p in [home, *dirs]:
|
|
713
|
+
if p.is_symlink():
|
|
714
|
+
sys.exit(f"{p} is a symlink; refusing to delete through it. Remove ModelSaar's files manually.")
|
|
715
|
+
for f in files:
|
|
716
|
+
try:
|
|
717
|
+
f.resolve().relative_to(home.resolve())
|
|
718
|
+
except ValueError:
|
|
719
|
+
sys.exit(f"{f} resolves outside {home}; refusing. Remove ModelSaar's files manually.")
|
|
720
|
+
for f in files:
|
|
721
|
+
if f.is_symlink():
|
|
722
|
+
print(f"skipped {f} (symlink)")
|
|
723
|
+
continue
|
|
724
|
+
if f.exists():
|
|
725
|
+
f.unlink()
|
|
726
|
+
print(f"removed {f}")
|
|
727
|
+
for d in [*dirs, home]:
|
|
728
|
+
try:
|
|
729
|
+
d.rmdir()
|
|
730
|
+
print(f"removed {d}")
|
|
731
|
+
except OSError:
|
|
732
|
+
if d.exists():
|
|
733
|
+
left = sorted(os.listdir(d))
|
|
734
|
+
print(f"left in place: {d} (not created by ModelSaar or not empty: {left[:5]}{'...' if len(left) > 5 else ''})")
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
# --------------------------------------------------------------------------- #
|
|
738
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
739
|
+
p = argparse.ArgumentParser(prog="modelsaar", description="ModelSaar - intelligent routing for local AI models")
|
|
740
|
+
p.add_argument("--config", help="path to config.yaml (default: $MODELSAAR_CONFIG or ~/.modelsaar/config.yaml)")
|
|
741
|
+
p.add_argument("--version", action="version", version=f"modelsaar {__version__}")
|
|
742
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
743
|
+
|
|
744
|
+
s = sub.add_parser("init", help="create config + keys, discover an endpoint")
|
|
745
|
+
s.add_argument("--endpoint", help="backend base URL (e.g. http://127.0.0.1:11434)")
|
|
746
|
+
s.add_argument("--type", choices=["ollama", "openai_compatible"], default="ollama")
|
|
747
|
+
s.add_argument("--backend-id", default="ollama")
|
|
748
|
+
s.add_argument("--port", type=int, default=8484)
|
|
749
|
+
s.add_argument("--profile", choices=["quality", "balanced", "fast"], default="quality")
|
|
750
|
+
s.add_argument("--max-concurrent", type=int, default=1, help="concurrent inferences on the local machine pool")
|
|
751
|
+
s.add_argument("--force", action="store_true")
|
|
752
|
+
s.set_defaults(fn=cmd_init)
|
|
753
|
+
|
|
754
|
+
s = sub.add_parser("discover", help="discover deployments and show states/capabilities")
|
|
755
|
+
s.add_argument("--json", action="store_true")
|
|
756
|
+
s.set_defaults(fn=cmd_discover)
|
|
757
|
+
|
|
758
|
+
s = sub.add_parser("probe", help="verify capabilities with live probes (uses local compute)")
|
|
759
|
+
s.add_argument("deployment", nargs="*", help="deployment id(s)")
|
|
760
|
+
s.add_argument("--all", action="store_true")
|
|
761
|
+
from .probes import PROBE_NAMES # the one list of probes: the CLI offers exactly what run_probes accepts
|
|
762
|
+
|
|
763
|
+
s.add_argument("--which", nargs="*", choices=sorted(PROBE_NAMES))
|
|
764
|
+
s.add_argument("--timeout", type=float, default=120.0)
|
|
765
|
+
s.add_argument("--json", action="store_true")
|
|
766
|
+
s.add_argument("--offline", action="store_true", help="probe directly instead of through a running gateway (refused while a gateway listens unless --allow-concurrent)")
|
|
767
|
+
s.add_argument("--allow-concurrent", action="store_true", help="accept uncoordinated inference next to a running gateway/other process")
|
|
768
|
+
s.set_defaults(fn=cmd_probe)
|
|
769
|
+
|
|
770
|
+
s = sub.add_parser("serve", help="start the gateway")
|
|
771
|
+
s.set_defaults(fn=cmd_serve)
|
|
772
|
+
|
|
773
|
+
s = sub.add_parser("status", help="status of a running gateway")
|
|
774
|
+
s.add_argument("--json", action="store_true")
|
|
775
|
+
s.set_defaults(fn=cmd_status)
|
|
776
|
+
|
|
777
|
+
s = sub.add_parser("lifecycle", help="managed model lifecycle on opt-in backends: status, load, unload, release a lease")
|
|
778
|
+
s.add_argument("action", choices=["status", "load", "unload", "release"])
|
|
779
|
+
s.add_argument("target", nargs="?", help="deployment id (load/unload) or lease id (release)")
|
|
780
|
+
s.add_argument("--hold", type=float, default=None, help="with load: keep a lease for this many seconds (blocks unload through the gateway)")
|
|
781
|
+
s.add_argument("--json", action="store_true")
|
|
782
|
+
s.set_defaults(fn=cmd_lifecycle)
|
|
783
|
+
|
|
784
|
+
s = sub.add_parser("judge", help="optional LLM-judge pass over rubric tasks (separate report; never merged into eval scores)")
|
|
785
|
+
s.add_argument("--judge", required=True, help="deployment id of the judge (an explicit id, not an alias)")
|
|
786
|
+
s.add_argument("--candidates", nargs="+", required=True, help="deployment ids whose answers are graded")
|
|
787
|
+
s.add_argument("--tasks", help="task file (default: the built-in fixtures)")
|
|
788
|
+
s.add_argument("--limit", type=int, default=0)
|
|
789
|
+
s.add_argument("--out", help="write the JSON report here")
|
|
790
|
+
s.set_defaults(fn=lambda a: __import__("modelsaar.evaluation.judge", fromlist=["run_judge_cli"]).run_judge_cli(a))
|
|
791
|
+
|
|
792
|
+
s = sub.add_parser("learn", help="opt-in adaptive learning: status, build a policy version, activate, rollback, purge")
|
|
793
|
+
s.add_argument("action", choices=["status", "build", "activate", "rollback", "purge"])
|
|
794
|
+
s.add_argument("version", nargs="?", type=int, help="policy version (activate)")
|
|
795
|
+
s.set_defaults(fn=cmd_learn)
|
|
796
|
+
|
|
797
|
+
s = sub.add_parser("doctor", help="diagnose configuration, backends, context and capability issues")
|
|
798
|
+
s.add_argument("--json", action="store_true")
|
|
799
|
+
s.set_defaults(fn=cmd_doctor)
|
|
800
|
+
|
|
801
|
+
s = sub.add_parser("explain", help="dry-run routing for a request and show the decision")
|
|
802
|
+
s.add_argument("--model", default="auto")
|
|
803
|
+
s.add_argument("--message", "-m")
|
|
804
|
+
s.add_argument("--file", help="JSON file with a full chat completions body")
|
|
805
|
+
s.add_argument("--tools", action="store_true", help="add a sample agent tool")
|
|
806
|
+
s.add_argument("--image", action="store_true", help="add a sample image part")
|
|
807
|
+
s.add_argument("--json-schema", action="store_true", help="request strict JSON schema output")
|
|
808
|
+
s.add_argument("--live", action="store_true", help="ask the running gateway instead of routing offline")
|
|
809
|
+
s.add_argument("--json", action="store_true")
|
|
810
|
+
s.set_defaults(fn=cmd_explain)
|
|
811
|
+
|
|
812
|
+
s = sub.add_parser("decisions", help="recent decisions from a running gateway")
|
|
813
|
+
s.add_argument("request_id", nargs="?")
|
|
814
|
+
s.add_argument("--limit", type=int, default=20)
|
|
815
|
+
s.set_defaults(fn=cmd_decisions)
|
|
816
|
+
|
|
817
|
+
s = sub.add_parser("test", help="send a test request through a running gateway")
|
|
818
|
+
s.add_argument("--model", default="auto")
|
|
819
|
+
s.add_argument("--message", default="Reply with one word: ready")
|
|
820
|
+
s.set_defaults(fn=cmd_test)
|
|
821
|
+
|
|
822
|
+
s = sub.add_parser("client-config", help="generate (and optionally apply) client configuration")
|
|
823
|
+
s.add_argument("client", choices=["open-webui", "openclaw", "opencode", "opencode-v2", "hermes"])
|
|
824
|
+
s.add_argument("--docker", action="store_true", help="client runs in a container (use host.docker.internal)")
|
|
825
|
+
s.add_argument("--path", help="config file to merge into (default: the client's documented location)")
|
|
826
|
+
s.add_argument("--dry-run", action="store_true", help="show the merged file without writing")
|
|
827
|
+
s.add_argument("--apply", action="store_true", help="write the merged file (backup created)")
|
|
828
|
+
s.set_defaults(fn=cmd_client_config)
|
|
829
|
+
|
|
830
|
+
s = sub.add_parser("keys", help="show or rotate keys")
|
|
831
|
+
ks = s.add_subparsers(dest="keys_cmd", required=True)
|
|
832
|
+
k = ks.add_parser("show")
|
|
833
|
+
k.add_argument("--reveal", action="store_true")
|
|
834
|
+
k = ks.add_parser("ensure", help="create missing key files (idempotent; never rotates). Used by the container entrypoint.")
|
|
835
|
+
k = ks.add_parser("rotate")
|
|
836
|
+
k.add_argument("--admin", action="store_true")
|
|
837
|
+
s.set_defaults(fn=cmd_keys)
|
|
838
|
+
|
|
839
|
+
s = sub.add_parser("config", help="validate/show/migrate the config")
|
|
840
|
+
cs = s.add_subparsers(dest="config_cmd", required=True)
|
|
841
|
+
for name in ("validate", "show", "example", "migrate"):
|
|
842
|
+
cs.add_parser(name)
|
|
843
|
+
s.set_defaults(fn=cmd_config)
|
|
844
|
+
|
|
845
|
+
s = sub.add_parser("eval", help="run the evaluation harness")
|
|
846
|
+
s.add_argument("--mode", choices=["simulated", "live"], default="simulated")
|
|
847
|
+
s.add_argument("--tasks", help="JSONL task file (default: built-in synthetic fixtures)")
|
|
848
|
+
s.add_argument("--out", help="write the JSON report here")
|
|
849
|
+
s.add_argument("--limit", type=int, default=0)
|
|
850
|
+
s.add_argument("--seed", type=int, default=7)
|
|
851
|
+
s.add_argument("--save-measurements", action="store_true", help="live mode: store per-deployment quality/latency evidence for routing")
|
|
852
|
+
s.add_argument("--probe", action="store_true", help="live mode: run capability probes on every deployment first")
|
|
853
|
+
s.add_argument(
|
|
854
|
+
"--deployments",
|
|
855
|
+
nargs="*",
|
|
856
|
+
help="live mode: restrict the sweep, baselines and the `auto` alias to these deployment ids (or bare model names when unambiguous)",
|
|
857
|
+
)
|
|
858
|
+
s.add_argument("--checkpoint", help="per-task record file (JSONL) for resumable runs; default <out>.records.jsonl when --out is given")
|
|
859
|
+
s.add_argument("--resume", action="store_true", help="skip tasks already recorded in the checkpoint file")
|
|
860
|
+
s.add_argument("--allow-concurrent", action="store_true", help="live mode: run even if a gateway/other process listens on the configured port")
|
|
861
|
+
s.set_defaults(fn=cmd_eval)
|
|
862
|
+
|
|
863
|
+
s = sub.add_parser("demo", help="start a SIMULATED backend + gateway to try the UX without models")
|
|
864
|
+
s.add_argument("--port", type=int, default=0)
|
|
865
|
+
s.set_defaults(fn=cmd_demo)
|
|
866
|
+
|
|
867
|
+
s = sub.add_parser("uninstall", help="remove ModelSaar's own files (never models or client configs)")
|
|
868
|
+
s.add_argument("--yes", action="store_true")
|
|
869
|
+
s.set_defaults(fn=cmd_uninstall)
|
|
870
|
+
return p
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def main(argv: list[str] | None = None) -> None:
|
|
874
|
+
p = build_parser()
|
|
875
|
+
args = p.parse_args(argv)
|
|
876
|
+
args.fn(args)
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
if __name__ == "__main__": # pragma: no cover
|
|
880
|
+
main()
|