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,95 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>ModelSaar status</title>
7
+ <style>
8
+ :root { --bg:#fafaf7; --fg:#1d1d1b; --muted:#6b6b66; --line:#e3e1d9; --ok:#1f7a4d; --bad:#b3261e; --warn:#9a6b00; --card:#fff; }
9
+ @media (prefers-color-scheme: dark) { :root { --bg:#15161a; --fg:#ecebe6; --muted:#a3a39c; --line:#2d2f36; --card:#1d1f25; } }
10
+ body { margin:0; background:var(--bg); color:var(--fg); font:15px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif; }
11
+ main { max-width:1100px; margin:0 auto; padding:24px 16px 48px; }
12
+ h1 { font-size:22px; margin:0 0 4px; } h2 { font-size:16px; margin:28px 0 8px; }
13
+ .muted { color:var(--muted); } .row { display:flex; gap:12px; flex-wrap:wrap; align-items:center; }
14
+ input { font:inherit; padding:6px 8px; border:1px solid var(--line); border-radius:6px; background:var(--card); color:var(--fg); min-width:280px; }
15
+ button { font:inherit; padding:6px 12px; border:1px solid var(--line); border-radius:6px; background:var(--card); color:var(--fg); cursor:pointer; }
16
+ table { border-collapse:collapse; width:100%; background:var(--card); border:1px solid var(--line); border-radius:8px; overflow:hidden; }
17
+ th, td { text-align:left; padding:6px 8px; border-bottom:1px solid var(--line); font-size:13px; vertical-align:top; }
18
+ th { color:var(--muted); font-weight:600; }
19
+ .ok { color:var(--ok); } .bad { color:var(--bad); } .warn { color:var(--warn); }
20
+ code { font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:12px; }
21
+ pre { background:var(--card); border:1px solid var(--line); border-radius:8px; padding:10px; overflow:auto; font-size:12px; }
22
+ </style>
23
+ </head>
24
+ <body>
25
+ <main>
26
+ <h1>ModelSaar <span class="muted" id="ver"></span></h1>
27
+ <div class="muted">Intelligent routing for local AI models — status and route inspection. The admin key stays in this tab only.</div>
28
+ <div class="row" style="margin-top:12px">
29
+ <input id="key" type="password" placeholder="admin key (from ~/.modelsaar/keys/admin_key)">
30
+ <button id="load">Load</button>
31
+ <span id="msg" class="muted"></span>
32
+ </div>
33
+ <h2>Gateway</h2>
34
+ <div id="gw" class="muted">Not loaded.</div>
35
+ <h2>Aliases</h2>
36
+ <table id="aliases"><thead><tr><th>alias</th><th>profile</th><th>members</th><th>context (min–max)</th><th>tools</th><th>vision</th><th>json_schema</th></tr></thead><tbody></tbody></table>
37
+ <h2>Deployments</h2>
38
+ <table id="deps"><thead><tr><th>id</th><th>role</th><th>state</th><th>locality</th><th>ctx</th><th>tools</th><th>vision</th><th>json_schema</th><th>evidence</th></tr></thead><tbody></tbody></table>
39
+ <h2>Recent decisions</h2>
40
+ <table id="decs"><thead><tr><th>request</th><th>requested → chosen</th><th>task</th><th>evidence</th><th>overhead</th><th>outcome</th><th>reasons</th></tr></thead><tbody></tbody></table>
41
+ <h2>Explain a request (dry run, nothing is sent to a model)</h2>
42
+ <pre contenteditable="true" id="explain">{"model":"auto","messages":[{"role":"user","content":"Write a Python function that parses ISO dates"}]}</pre>
43
+ <button id="run">Explain</button>
44
+ <pre id="explainOut" class="muted">—</pre>
45
+ </main>
46
+ <script>
47
+ (function(){
48
+ const $ = (s)=>document.querySelector(s);
49
+ let key = '';
50
+ try { key = sessionStorage.getItem('modelsaar_admin_key') || ''; } catch(e) {}
51
+ if (key) $('#key').value = key;
52
+ const esc = (s)=>String(s==null?'':s).replace(/[&<>"]/g, c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
53
+ const tri = (v)=>`<span class="${v==='supported'?'ok':v==='unsupported'?'bad':'warn'}">${esc(v)}</span>`;
54
+ async function api(path, opts){
55
+ const r = await fetch(path, Object.assign({headers:{'Authorization':'Bearer '+key,'Content-Type':'application/json'}}, opts||{}));
56
+ if (!r.ok) throw new Error(r.status+' '+(await r.text()).slice(0,200));
57
+ return r.json();
58
+ }
59
+ async function load(){
60
+ key = $('#key').value.trim();
61
+ try { sessionStorage.setItem('modelsaar_admin_key', key); } catch(e) {}
62
+ $('#msg').textContent = 'loading…';
63
+ try {
64
+ const s = await api('/admin/status');
65
+ $('#ver').textContent = 'v'+s.version;
66
+ $('#gw').innerHTML = `config <code>${esc(s.config_path)}</code> (hash ${esc(s.config_hash)}) · bind <code>${esc(s.security.host)}</code> · locality <b>${esc(s.security.locality_mode)}</b> · prompt logging <b>${s.security.log_prompts?'ON':'off'}</b> · requests ${s.requests_total} (failed ${s.requests_failed}) · ready ${s.ready?'<span class=ok>yes</span>':'<span class=bad>no</span>'}${s.last_refresh_error?' · <span class=bad>'+esc(s.last_refresh_error)+'</span>':''}`;
67
+ const at = $('#aliases tbody'); at.innerHTML='';
68
+ for (const [name,c] of Object.entries(s.aliases)) {
69
+ at.insertAdjacentHTML('beforeend', c ? `<tr><td><code>${esc(name)}</code></td><td>${esc(c.profile)}</td><td>${c.deployments.map(esc).join('<br>')}</td><td>${esc(c.context_length_min)}–${esc(c.context_length_max)}</td><td>${tri(c.tools)}</td><td>${tri(c.vision)}</td><td>${tri(c.json_schema)}</td></tr>`
70
+ : `<tr><td><code>${esc(name)}</code></td><td colspan=6 class=muted>not advertised (no usable deployment)</td></tr>`);
71
+ }
72
+ const dt = $('#deps tbody'); dt.innerHTML='';
73
+ for (const d of s.deployments) {
74
+ const st = d.state; const flags = [st.healthy?'<span class=ok>healthy</span>':'<span class=bad>unhealthy</span>', st.loaded?'loaded':'not loaded', d.enabled?'':'<span class=bad>disabled</span>'].filter(Boolean).join(' · ');
75
+ const ev = Object.keys(d.measurements||{}).length ? 'measured: '+Object.keys(d.measurements).join(', ') : (Object.keys(d.quality_prior||{}).length ? 'prior ('+esc(d.quality_prior_provenance)+')' : 'uncalibrated');
76
+ dt.insertAdjacentHTML('beforeend', `<tr><td><code>${esc(d.id)}</code></td><td>${esc(d.role)}</td><td>${flags}</td><td title="${esc(d.locality_evidence)}">${esc(d.locality)}</td><td>${esc(d.context_length)}</td><td>${tri(d.capabilities.tools.value)}<br><span class=muted>${esc(d.capabilities.tools.provenance)}</span></td><td>${tri(d.capabilities.vision.value)}</td><td>${tri(d.capabilities.json_schema.value)}</td><td>${ev}</td></tr>`);
77
+ }
78
+ const ds = await api('/admin/decisions?limit=25');
79
+ const bt = $('#decs tbody'); bt.innerHTML='';
80
+ for (const d of ds.decisions) {
81
+ bt.insertAdjacentHTML('beforeend', `<tr><td><code>${esc(d.request_id)}</code></td><td>${esc(d.requested_model)} → <b>${esc(d.chosen||'—')}</b></td><td>${esc((d.requirements||{}).primary_task)}</td><td>${esc(d.evidence)}</td><td>${esc(d.overhead_ms)} ms</td><td>${esc(d.outcome)}</td><td class=muted>${(d.reasons||[]).map(esc).join('<br>')}</td></tr>`);
82
+ }
83
+ $('#msg').textContent = 'loaded '+new Date().toLocaleTimeString();
84
+ } catch(e) { $('#msg').innerHTML = '<span class=bad>'+esc(e.message)+'</span>'; }
85
+ }
86
+ $('#load').addEventListener('click', load);
87
+ $('#run').addEventListener('click', async ()=>{
88
+ try { const out = await api('/admin/explain', {method:'POST', body: $('#explain').innerText}); $('#explainOut').textContent = JSON.stringify(out, null, 2); $('#explainOut').className=''; }
89
+ catch(e) { $('#explainOut').textContent = e.message; }
90
+ });
91
+ if (key) load();
92
+ })();
93
+ </script>
94
+ </body>
95
+ </html>
modelsaar/store.py ADDED
@@ -0,0 +1,208 @@
1
+ """Lightweight local persistence (SQLite, stdlib only).
2
+
3
+ Stores probe evidence and measurements keyed by deployment fingerprint, and a
4
+ bounded decision log containing *metadata only* (never prompts).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import sqlite3
12
+ import threading
13
+ import time
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ # Evidence scheme. Bump when the fingerprint inputs or the evaluator/scorer semantics change so
18
+ # that rows written under the old scheme can no longer be trusted. Old rows are kept (for audit)
19
+ # but never loaded; `modelsaar doctor` reports them.
20
+ # 1: 0.1.0 (fingerprint without endpoint/identity; evaluator with lenient scorers)
21
+ # 2: hardening 2026-10-11 (endpoint + identity in fingerprint; strict scorers; conditions column)
22
+ EVIDENCE_SCHEME = 2
23
+
24
+ SCHEMA = """
25
+ CREATE TABLE IF NOT EXISTS probes (
26
+ deployment_id TEXT NOT NULL,
27
+ fingerprint TEXT NOT NULL,
28
+ capability TEXT NOT NULL,
29
+ value TEXT NOT NULL,
30
+ note TEXT NOT NULL DEFAULT '',
31
+ checked_at REAL NOT NULL,
32
+ scheme INTEGER NOT NULL DEFAULT 1,
33
+ PRIMARY KEY (deployment_id, fingerprint, capability)
34
+ );
35
+ CREATE TABLE IF NOT EXISTS measurements (
36
+ deployment_id TEXT NOT NULL,
37
+ fingerprint TEXT NOT NULL,
38
+ task TEXT NOT NULL,
39
+ quality REAL,
40
+ samples INTEGER NOT NULL DEFAULT 0,
41
+ p50_ms REAL, p95_ms REAL, ttft_ms REAL, load_ms REAL,
42
+ source TEXT NOT NULL DEFAULT 'eval',
43
+ measured_at REAL NOT NULL,
44
+ scheme INTEGER NOT NULL DEFAULT 1,
45
+ conditions TEXT NOT NULL DEFAULT '{}',
46
+ PRIMARY KEY (deployment_id, fingerprint, task, source)
47
+ );
48
+ CREATE TABLE IF NOT EXISTS decisions (
49
+ request_id TEXT PRIMARY KEY,
50
+ created_at REAL NOT NULL,
51
+ record TEXT NOT NULL
52
+ );
53
+ CREATE INDEX IF NOT EXISTS decisions_created ON decisions(created_at);
54
+ CREATE TABLE IF NOT EXISTS meta (
55
+ key TEXT PRIMARY KEY,
56
+ value TEXT NOT NULL
57
+ );
58
+ """
59
+
60
+
61
+ class Store:
62
+ def __init__(self, path: Path | str) -> None:
63
+ self.path = Path(path)
64
+ self.path.parent.mkdir(parents=True, exist_ok=True)
65
+ self._lock = threading.Lock()
66
+ self._conn = sqlite3.connect(str(self.path), check_same_thread=False)
67
+ self._conn.execute("PRAGMA journal_mode=WAL")
68
+ self._conn.executescript(SCHEMA)
69
+ self._migrate()
70
+ for suffix in ("", "-wal", "-shm"):
71
+ try:
72
+ os.chmod(str(self.path) + suffix, 0o600)
73
+ except OSError:
74
+ pass
75
+
76
+ def _migrate(self) -> None:
77
+ """Add columns introduced after 0.1.0 and record the evidence scheme. Rows that predate the
78
+ current scheme keep scheme=<old> and are excluded from every load."""
79
+ with self._lock:
80
+ for table, col, ddl in (
81
+ ("probes", "scheme", "ALTER TABLE probes ADD COLUMN scheme INTEGER NOT NULL DEFAULT 1"),
82
+ ("measurements", "scheme", "ALTER TABLE measurements ADD COLUMN scheme INTEGER NOT NULL DEFAULT 1"),
83
+ ("measurements", "conditions", "ALTER TABLE measurements ADD COLUMN conditions TEXT NOT NULL DEFAULT '{}'"),
84
+ ):
85
+ cols = {r[1] for r in self._conn.execute(f"PRAGMA table_info({table})").fetchall()}
86
+ if col not in cols:
87
+ self._conn.execute(ddl)
88
+ row = self._conn.execute("SELECT value FROM meta WHERE key='evidence_scheme'").fetchone()
89
+ previous = int(row[0]) if row else 1
90
+ if previous < EVIDENCE_SCHEME:
91
+ self._conn.execute(
92
+ "INSERT OR REPLACE INTO meta VALUES ('evidence_scheme_migrated_at', ?)", (f"{time.time():.0f}:from {previous}",)
93
+ )
94
+ self._conn.execute("INSERT OR REPLACE INTO meta VALUES ('evidence_scheme', ?)", (str(EVIDENCE_SCHEME),))
95
+ self._conn.commit()
96
+
97
+ def invalidated_counts(self) -> dict[str, int]:
98
+ """Rows written under an older evidence scheme (kept for audit, never loaded)."""
99
+ with self._lock:
100
+ p = self._conn.execute("SELECT COUNT(*) FROM probes WHERE scheme<>?", (EVIDENCE_SCHEME,)).fetchone()[0]
101
+ m = self._conn.execute("SELECT COUNT(*) FROM measurements WHERE scheme<>?", (EVIDENCE_SCHEME,)).fetchone()[0]
102
+ return {"probes": int(p), "measurements": int(m), "scheme": EVIDENCE_SCHEME}
103
+
104
+ def close(self) -> None:
105
+ with self._lock:
106
+ self._conn.close()
107
+
108
+ # probes ---------------------------------------------------------------
109
+ def save_probe(self, deployment_id: str, fingerprint: str, capability: str, value: str, note: str = "") -> None:
110
+ with self._lock:
111
+ self._conn.execute(
112
+ "INSERT OR REPLACE INTO probes (deployment_id, fingerprint, capability, value, note, checked_at, scheme) "
113
+ "VALUES (?,?,?,?,?,?,?)",
114
+ (deployment_id, fingerprint, capability, value, note, time.time(), EVIDENCE_SCHEME),
115
+ )
116
+ self._conn.commit()
117
+
118
+ def load_probes(self, deployment_id: str, fingerprint: str) -> dict[str, dict[str, Any]]:
119
+ with self._lock:
120
+ rows = self._conn.execute(
121
+ "SELECT capability, value, note, checked_at FROM probes WHERE deployment_id=? AND fingerprint=? AND scheme=?",
122
+ (deployment_id, fingerprint, EVIDENCE_SCHEME),
123
+ ).fetchall()
124
+ return {r[0]: {"value": r[1], "note": r[2], "checked_at": r[3]} for r in rows}
125
+
126
+ def stale_probe_fingerprints(self, deployment_id: str, current_fp: str) -> list[str]:
127
+ with self._lock:
128
+ rows = self._conn.execute(
129
+ "SELECT DISTINCT fingerprint FROM probes WHERE deployment_id=? AND fingerprint<>? AND scheme=?",
130
+ (deployment_id, current_fp, EVIDENCE_SCHEME),
131
+ ).fetchall()
132
+ return [r[0] for r in rows]
133
+
134
+ # measurements ---------------------------------------------------------
135
+ def save_measurement(self, deployment_id: str, fingerprint: str, m: dict[str, Any]) -> None:
136
+ with self._lock:
137
+ self._conn.execute(
138
+ "INSERT OR REPLACE INTO measurements (deployment_id, fingerprint, task, quality, samples, p50_ms, p95_ms, "
139
+ "ttft_ms, load_ms, source, measured_at, scheme, conditions) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
140
+ (
141
+ deployment_id,
142
+ fingerprint,
143
+ m["task"],
144
+ m.get("quality"),
145
+ int(m.get("samples", 0)),
146
+ m.get("p50_ms"),
147
+ m.get("p95_ms"),
148
+ m.get("ttft_ms"),
149
+ m.get("load_ms"),
150
+ m.get("source", "eval"),
151
+ m.get("measured_at") or time.time(),
152
+ EVIDENCE_SCHEME,
153
+ json.dumps(m.get("conditions") or {}, sort_keys=True, separators=(",", ":")),
154
+ ),
155
+ )
156
+ self._conn.commit()
157
+
158
+ def load_measurements(self, deployment_id: str, fingerprint: str) -> list[dict[str, Any]]:
159
+ with self._lock:
160
+ rows = self._conn.execute(
161
+ "SELECT task, quality, samples, p50_ms, p95_ms, ttft_ms, load_ms, source, measured_at, conditions "
162
+ "FROM measurements WHERE deployment_id=? AND fingerprint=? AND scheme=?",
163
+ (deployment_id, fingerprint, EVIDENCE_SCHEME),
164
+ ).fetchall()
165
+ keys = ["task", "quality", "samples", "p50_ms", "p95_ms", "ttft_ms", "load_ms", "source", "measured_at", "conditions"]
166
+ out = []
167
+ for r in rows:
168
+ d = dict(zip(keys, r, strict=True))
169
+ try:
170
+ d["conditions"] = json.loads(d["conditions"] or "{}")
171
+ except ValueError:
172
+ d["conditions"] = {}
173
+ out.append(d)
174
+ return out
175
+
176
+ # decisions ------------------------------------------------------------
177
+ def save_decision(self, request_id: str, record: dict[str, Any], retention_days: int = 7) -> None:
178
+ with self._lock:
179
+ self._conn.execute(
180
+ "INSERT OR REPLACE INTO decisions VALUES (?,?,?)",
181
+ (request_id, time.time(), json.dumps(record, separators=(",", ":"))),
182
+ )
183
+ cutoff = time.time() - retention_days * 86400
184
+ self._conn.execute("DELETE FROM decisions WHERE created_at < ?", (cutoff,))
185
+ self._conn.commit()
186
+
187
+ def get_decision(self, request_id: str) -> dict[str, Any] | None:
188
+ with self._lock:
189
+ row = self._conn.execute("SELECT record FROM decisions WHERE request_id=?", (request_id,)).fetchone()
190
+ return json.loads(row[0]) if row else None
191
+
192
+ def recent_decisions(self, limit: int = 50) -> list[dict[str, Any]]:
193
+ with self._lock:
194
+ rows = self._conn.execute(
195
+ "SELECT record FROM decisions ORDER BY created_at DESC LIMIT ?", (limit,)
196
+ ).fetchall()
197
+ return [json.loads(r[0]) for r in rows]
198
+
199
+ # meta -----------------------------------------------------------------
200
+ def set_meta(self, key: str, value: str) -> None:
201
+ with self._lock:
202
+ self._conn.execute("INSERT OR REPLACE INTO meta VALUES (?,?)", (key, value))
203
+ self._conn.commit()
204
+
205
+ def get_meta(self, key: str) -> str | None:
206
+ with self._lock:
207
+ row = self._conn.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone()
208
+ return row[0] if row else None
@@ -0,0 +1 @@
1
+ """Test and demo fixtures (controlled fake backends). Nothing here talks to a real model."""