quantcheck 0.0.1__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.
- quantcheck/__init__.py +3 -0
- quantcheck/auth/__init__.py +6 -0
- quantcheck/auth/base.py +74 -0
- quantcheck/auth/callback.py +73 -0
- quantcheck/auth/fake.py +40 -0
- quantcheck/auth/service.py +49 -0
- quantcheck/auth/store.py +63 -0
- quantcheck/auth/supabase.py +168 -0
- quantcheck/bench.py +38 -0
- quantcheck/candidates.py +138 -0
- quantcheck/cli.py +251 -0
- quantcheck/config.py +63 -0
- quantcheck/executors/__init__.py +0 -0
- quantcheck/hardware.py +52 -0
- quantcheck/limits.py +19 -0
- quantcheck/pipeline.py +172 -0
- quantcheck/prompt.py +67 -0
- quantcheck/recommend.py +131 -0
- quantcheck/report/__init__.py +0 -0
- quantcheck/report/html.py +38 -0
- quantcheck/report/templates/report.html.j2 +272 -0
- quantcheck/report/terminal.py +90 -0
- quantcheck/report/tokens.py +41 -0
- quantcheck/report/view.py +161 -0
- quantcheck/runners/__init__.py +3 -0
- quantcheck/runners/base.py +87 -0
- quantcheck/runners/fake.py +68 -0
- quantcheck/runners/llamacpp_runner.py +185 -0
- quantcheck/runners/mlx_runner.py +153 -0
- quantcheck/runners/toolparse.py +107 -0
- quantcheck/scoring/__init__.py +0 -0
- quantcheck/scoring/checks.py +342 -0
- quantcheck/scoring/fake_judge.py +50 -0
- quantcheck/scoring/judge.py +171 -0
- quantcheck/scoring/language.py +99 -0
- quantcheck/scoring/models.py +92 -0
- quantcheck/scoring/score.py +167 -0
- quantcheck/scoring/stats.py +60 -0
- quantcheck/settings.py +14 -0
- quantcheck/store.py +88 -0
- quantcheck/tests_io.py +169 -0
- quantcheck/ui/__init__.py +1 -0
- quantcheck/ui/app.py +534 -0
- quantcheck/ui/catalog.py +47 -0
- quantcheck/ui/chat.py +211 -0
- quantcheck/ui/compare.py +63 -0
- quantcheck/ui/downloads.py +172 -0
- quantcheck/ui/jobs.py +173 -0
- quantcheck/ui/modeldetail.py +97 -0
- quantcheck/ui/reviews.py +59 -0
- quantcheck/ui/security.py +45 -0
- quantcheck/ui/static/chat.js +312 -0
- quantcheck/ui/static/fonts/JetBrainsMono-latin-b87346.woff2 +0 -0
- quantcheck/ui/static/fonts/JetBrainsMono-latin-ext-9326b4.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansDevanagari-devanagari-3819bb.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansDevanagari-latin-ext-542103.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansDevanagari-latin-f3aaed.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansTamil-latin-17e6dc.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansTamil-latin-ext-027c12.woff2 +0 -0
- quantcheck/ui/static/fonts/NotoSansTamil-tamil-a57d5e.woff2 +0 -0
- quantcheck/ui/static/fonts/Outfit-latin-ebadd8.woff2 +0 -0
- quantcheck/ui/static/fonts/Outfit-latin-ext-744997.woff2 +0 -0
- quantcheck/ui/static/fonts/README.md +14 -0
- quantcheck/ui/static/fonts.css +228 -0
- quantcheck/ui/static/index.html +24 -0
- quantcheck/ui/static/lab.css +768 -0
- quantcheck/ui/static/lab.js +896 -0
- quantcheck/ui/static/logo.svg +5 -0
- quantcheck/ui/static/review.js +127 -0
- quantcheck/ui/static/setup.js +132 -0
- quantcheck/ui/static/testsets.js +527 -0
- quantcheck/ui/summary.py +104 -0
- quantcheck/ui/system.py +101 -0
- quantcheck/ui/testsets.py +243 -0
- quantcheck-0.0.1.dist-info/METADATA +115 -0
- quantcheck-0.0.1.dist-info/RECORD +79 -0
- quantcheck-0.0.1.dist-info/WHEEL +4 -0
- quantcheck-0.0.1.dist-info/entry_points.txt +2 -0
- quantcheck-0.0.1.dist-info/licenses/LICENSE +202 -0
quantcheck/ui/app.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
"""The lab web app (FastAPI). Same pipeline as the CLI; nothing leaves this machine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import queue
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import threading
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Literal
|
|
13
|
+
|
|
14
|
+
from fastapi import Depends, FastAPI, HTTPException, Request
|
|
15
|
+
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
|
|
16
|
+
from fastapi.staticfiles import StaticFiles
|
|
17
|
+
from pydantic import BaseModel, Field, ValidationError
|
|
18
|
+
|
|
19
|
+
from quantcheck import __version__, limits
|
|
20
|
+
from quantcheck.auth.base import AuthError, AuthProvider, Session
|
|
21
|
+
from quantcheck.auth.service import require_session
|
|
22
|
+
from quantcheck.auth.store import SessionStore
|
|
23
|
+
from quantcheck.config import RunConfig
|
|
24
|
+
from quantcheck.pipeline import JobError, PreparedJob, prepare_job
|
|
25
|
+
from quantcheck.report.tokens import DARK, LIGHT, css_vars
|
|
26
|
+
from quantcheck.report.view import build_view
|
|
27
|
+
from quantcheck.scoring import language
|
|
28
|
+
from quantcheck.store import JsonResultsStore
|
|
29
|
+
from quantcheck.tests_io import SetHeader, TestFileError, loads_tests
|
|
30
|
+
from quantcheck.ui import compare as compare_mod
|
|
31
|
+
from quantcheck.ui import jobs as jobs_mod
|
|
32
|
+
from quantcheck.ui import modeldetail as modeldetail_mod
|
|
33
|
+
from quantcheck.ui import reviews as reviews_mod
|
|
34
|
+
from quantcheck.ui import summary as summary_mod
|
|
35
|
+
from quantcheck.ui import testsets as testsets_mod
|
|
36
|
+
from quantcheck.ui.catalog import SETUP_MODELS, SUGGESTED
|
|
37
|
+
from quantcheck.ui.chat import ChatBusy, ChatError, ChatSession
|
|
38
|
+
from quantcheck.ui.downloads import DownloadBusy, DownloadError, DownloadManager
|
|
39
|
+
from quantcheck.ui.jobs import Busy, JobManager
|
|
40
|
+
from quantcheck.ui.reviews import ReviewIn
|
|
41
|
+
from quantcheck.ui.security import LocalOnlyGuard, allowed_hosts
|
|
42
|
+
from quantcheck.ui.system import cached_models, system_status
|
|
43
|
+
|
|
44
|
+
STATIC = Path(__file__).parent / "static"
|
|
45
|
+
_ID = re.compile(r"^[0-9A-Za-z_-]{1,64}$")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AuthFlow:
|
|
49
|
+
"""One browser sign-in at a time, run in a thread so the page can poll for the result."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, store: SessionStore, provider: Callable[[], AuthProvider]) -> None:
|
|
52
|
+
self.store, self.provider = store, provider
|
|
53
|
+
self.state, self.error = "idle", None # idle | pending | signed_in | error
|
|
54
|
+
self._lock = threading.Lock()
|
|
55
|
+
|
|
56
|
+
def start(self, idp: str) -> str:
|
|
57
|
+
"""Begin sign-in; returns the URL the browser must open."""
|
|
58
|
+
with self._lock:
|
|
59
|
+
if self.state == "pending":
|
|
60
|
+
raise AuthError("a sign-in is already in progress: finish it in the other tab")
|
|
61
|
+
self.state, self.error = "pending", None
|
|
62
|
+
urls: queue.Queue[str] = queue.Queue()
|
|
63
|
+
|
|
64
|
+
def work() -> None:
|
|
65
|
+
try:
|
|
66
|
+
session = self.provider().login(urls.put, idp)
|
|
67
|
+
self.store.save(session)
|
|
68
|
+
self.state = "signed_in"
|
|
69
|
+
except AuthError as e:
|
|
70
|
+
self.state, self.error = "error", str(e)
|
|
71
|
+
except Exception as e: # a broken provider must not leave "pending" forever
|
|
72
|
+
self.state, self.error = "error", f"sign-in failed: {e}"
|
|
73
|
+
|
|
74
|
+
threading.Thread(target=work, daemon=True).start()
|
|
75
|
+
try:
|
|
76
|
+
return urls.get(timeout=10)
|
|
77
|
+
except queue.Empty:
|
|
78
|
+
raise AuthError(self.error or "sign-in did not start") from None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class LabState:
|
|
83
|
+
"""Everything the routes need. Tests build one with fakes."""
|
|
84
|
+
|
|
85
|
+
store: SessionStore
|
|
86
|
+
provider: Callable[[], AuthProvider]
|
|
87
|
+
data_dir: Path
|
|
88
|
+
port: int
|
|
89
|
+
prepare: Callable[[RunConfig], PreparedJob] = prepare_job
|
|
90
|
+
extra_hosts: set[str] = field(default_factory=set)
|
|
91
|
+
run_in_thread: bool = True
|
|
92
|
+
runs_dir: Path = field(init=False)
|
|
93
|
+
jobs: JobManager = field(init=False)
|
|
94
|
+
chat: ChatSession = field(init=False)
|
|
95
|
+
downloads: DownloadManager = field(init=False)
|
|
96
|
+
auth: AuthFlow = field(init=False)
|
|
97
|
+
|
|
98
|
+
def __post_init__(self) -> None:
|
|
99
|
+
self.runs_dir = self.data_dir / "runs"
|
|
100
|
+
self.jobs = JobManager(self.runs_dir, self.run_in_thread)
|
|
101
|
+
self.chat = ChatSession(run_in_thread=self.run_in_thread)
|
|
102
|
+
self.downloads = DownloadManager(
|
|
103
|
+
free_gb_fn=lambda: (
|
|
104
|
+
shutil.disk_usage(self.data_dir if self.data_dir.exists() else Path.home()).free
|
|
105
|
+
/ 1e9
|
|
106
|
+
),
|
|
107
|
+
run_in_thread=self.run_in_thread,
|
|
108
|
+
)
|
|
109
|
+
self.auth = AuthFlow(self.store, self.provider)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class AuthStart(BaseModel):
|
|
113
|
+
idp: Literal["google", "github"] = "google"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class StartRun(BaseModel):
|
|
117
|
+
model: str = Field(min_length=1)
|
|
118
|
+
runtime: Literal["mlx", "llamacpp"] = "mlx"
|
|
119
|
+
versions: list[str] = Field(min_length=1)
|
|
120
|
+
tests: str = Field(min_length=1)
|
|
121
|
+
judge_model: str | None = None
|
|
122
|
+
max_tokens: int | None = None
|
|
123
|
+
quality_limit: float | None = None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class ChatColumnIn(BaseModel):
|
|
127
|
+
model: str = Field(min_length=1)
|
|
128
|
+
runtime: Literal["mlx", "llamacpp"] = "mlx"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class DownloadIn(BaseModel):
|
|
132
|
+
repo: str = Field(min_length=3, max_length=200)
|
|
133
|
+
label: str = Field(default="", max_length=60)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class DownloadStart(BaseModel):
|
|
137
|
+
models: list[DownloadIn] = Field(min_length=1, max_length=6)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class ChatLoad(BaseModel):
|
|
141
|
+
columns: list[ChatColumnIn] = Field(min_length=1)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class ChatAsk(BaseModel):
|
|
145
|
+
text: str = Field(min_length=1, max_length=8000)
|
|
146
|
+
tests: str | None = None # a test set whose instructions and tools are sent with the question
|
|
147
|
+
documents: list[str] = Field(default_factory=list, max_length=20)
|
|
148
|
+
max_tokens: int = Field(default=limits.DEFAULT_ANSWER_TOKENS, gt=0, le=limits.MAX_ANSWER_TOKENS)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class SetBody(BaseModel):
|
|
152
|
+
header: dict[str, Any] = Field(default_factory=dict)
|
|
153
|
+
cases: list[dict[str, Any]] = Field(default_factory=list)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class PreviewBody(BaseModel):
|
|
157
|
+
header: dict[str, Any] = Field(default_factory=dict)
|
|
158
|
+
case: dict[str, Any]
|
|
159
|
+
context_tokens: int = Field(default=testsets_mod.TYPICAL_CONTEXT_TOKENS, ge=512)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def create_app(state: LabState) -> FastAPI:
|
|
163
|
+
"""Build the app around ``state``."""
|
|
164
|
+
app = FastAPI(title="quantcheck lab", version=__version__, docs_url=None, redoc_url=None)
|
|
165
|
+
app.add_middleware(LocalOnlyGuard, hosts=allowed_hosts(state.port, state.extra_hosts))
|
|
166
|
+
|
|
167
|
+
def user() -> Session:
|
|
168
|
+
try:
|
|
169
|
+
return require_session(state.store, state.provider())
|
|
170
|
+
except AuthError as e:
|
|
171
|
+
raise HTTPException(401, str(e)) from e
|
|
172
|
+
|
|
173
|
+
@app.middleware("http")
|
|
174
|
+
async def no_store(request: Request, call_next): # noqa: ANN001, ANN202
|
|
175
|
+
response = await call_next(request)
|
|
176
|
+
path = request.url.path
|
|
177
|
+
if path.startswith("/api/"):
|
|
178
|
+
response.headers["Cache-Control"] = "no-store"
|
|
179
|
+
elif path == "/" or path.startswith("/static/"):
|
|
180
|
+
response.headers["Cache-Control"] = "no-cache" # local files: always revalidate
|
|
181
|
+
return response
|
|
182
|
+
|
|
183
|
+
# ---- static front end -----------------------------------------------------------------
|
|
184
|
+
@app.get("/", response_class=HTMLResponse)
|
|
185
|
+
def index() -> Response:
|
|
186
|
+
return FileResponse(STATIC / "index.html")
|
|
187
|
+
|
|
188
|
+
@app.get("/static/tokens.css")
|
|
189
|
+
def tokens() -> Response:
|
|
190
|
+
css = (
|
|
191
|
+
f":root {{\n{css_vars(LIGHT)}\n}}\n"
|
|
192
|
+
f'@media (prefers-color-scheme: dark) {{\n :root:not([data-theme="light"]) {{\n'
|
|
193
|
+
f"{css_vars(DARK, ' ')}\n }}\n}}\n"
|
|
194
|
+
f':root[data-theme="dark"] {{\n{css_vars(DARK)}\n}}\n'
|
|
195
|
+
)
|
|
196
|
+
return Response(css, media_type="text/css")
|
|
197
|
+
|
|
198
|
+
app.mount("/static", StaticFiles(directory=STATIC), name="static")
|
|
199
|
+
|
|
200
|
+
# ---- status + account -----------------------------------------------------------------
|
|
201
|
+
@app.get("/api/status")
|
|
202
|
+
def status() -> dict[str, Any]:
|
|
203
|
+
try:
|
|
204
|
+
who = require_session(state.store, state.provider())
|
|
205
|
+
account: dict[str, Any] | None = {
|
|
206
|
+
"email": who.email,
|
|
207
|
+
"name": who.name,
|
|
208
|
+
"plan": who.plan,
|
|
209
|
+
}
|
|
210
|
+
except AuthError:
|
|
211
|
+
account = None
|
|
212
|
+
return {"version": __version__, "account": account, "port": state.port}
|
|
213
|
+
|
|
214
|
+
@app.get("/api/limits")
|
|
215
|
+
def limits_info() -> dict[str, Any]:
|
|
216
|
+
f = RunConfig.model_fields
|
|
217
|
+
defaults = {
|
|
218
|
+
"seed": f["seed"].default,
|
|
219
|
+
"temperature": 0,
|
|
220
|
+
"max_tokens": f["max_tokens"].default,
|
|
221
|
+
"quality_limit": f["quality_limit"].default,
|
|
222
|
+
"judge_model": f["judge_model"].default,
|
|
223
|
+
}
|
|
224
|
+
return {**{k: getattr(limits, k) for k in dir(limits) if k.isupper()}, "defaults": defaults}
|
|
225
|
+
|
|
226
|
+
@app.get("/api/system")
|
|
227
|
+
def system(_: Session = Depends(user)) -> dict[str, Any]:
|
|
228
|
+
return system_status(state.data_dir)
|
|
229
|
+
|
|
230
|
+
@app.post("/api/auth/start")
|
|
231
|
+
def auth_start(body: AuthStart) -> dict[str, str]:
|
|
232
|
+
try:
|
|
233
|
+
return {"url": state.auth.start(body.idp)}
|
|
234
|
+
except AuthError as e:
|
|
235
|
+
raise HTTPException(400, str(e)) from e
|
|
236
|
+
|
|
237
|
+
@app.get("/api/auth/state")
|
|
238
|
+
def auth_state() -> dict[str, Any]:
|
|
239
|
+
return {"state": state.auth.state, "error": state.auth.error}
|
|
240
|
+
|
|
241
|
+
@app.post("/api/auth/logout")
|
|
242
|
+
def auth_logout() -> dict[str, bool]:
|
|
243
|
+
session = state.store.load()
|
|
244
|
+
if session:
|
|
245
|
+
state.provider().logout(session)
|
|
246
|
+
state.store.clear()
|
|
247
|
+
state.auth.state = "idle"
|
|
248
|
+
return {"ok": True}
|
|
249
|
+
|
|
250
|
+
# ---- runs and reports -----------------------------------------------------------------
|
|
251
|
+
@app.get("/api/runs")
|
|
252
|
+
def runs(_: Session = Depends(user)) -> list[dict[str, Any]]:
|
|
253
|
+
return [summary_mod.run_row(r) for r in summary_mod.load_runs(state.runs_dir)]
|
|
254
|
+
|
|
255
|
+
@app.get("/api/summary")
|
|
256
|
+
def week_summary(_: Session = Depends(user)) -> dict[str, Any]:
|
|
257
|
+
return summary_mod.weekly(summary_mod.load_runs(state.runs_dir))
|
|
258
|
+
|
|
259
|
+
@app.get("/api/runs/{run_id}/report")
|
|
260
|
+
def run_report(run_id: str, _: Session = Depends(user)) -> Response:
|
|
261
|
+
if not _ID.match(run_id):
|
|
262
|
+
raise HTTPException(404, "no such run")
|
|
263
|
+
path = state.runs_dir / run_id / "report.html"
|
|
264
|
+
if not path.is_file():
|
|
265
|
+
raise HTTPException(404, "no report for this run")
|
|
266
|
+
return FileResponse(path, media_type="text/html")
|
|
267
|
+
|
|
268
|
+
def load_run(run_id: str) -> tuple[Path, Any]:
|
|
269
|
+
if not _ID.match(run_id):
|
|
270
|
+
raise HTTPException(404, "no such run")
|
|
271
|
+
try:
|
|
272
|
+
return state.runs_dir / run_id, JsonResultsStore(state.runs_dir).load(run_id)
|
|
273
|
+
except FileNotFoundError as e:
|
|
274
|
+
raise HTTPException(404, "no such run") from e
|
|
275
|
+
except ValueError as e:
|
|
276
|
+
raise HTTPException(422, f"this run cannot be read: {e}") from e
|
|
277
|
+
|
|
278
|
+
@app.get("/api/runs/{run_id}/changes")
|
|
279
|
+
def run_changes(run_id: str, _: Session = Depends(user)) -> dict[str, Any]:
|
|
280
|
+
run_dir, result = load_run(run_id)
|
|
281
|
+
view = build_view(result)
|
|
282
|
+
scored_n = (
|
|
283
|
+
{c.label: c.n_scored for c in result.scoring.candidates} if result.scoring else {}
|
|
284
|
+
)
|
|
285
|
+
return {
|
|
286
|
+
**view.model_dump(include={
|
|
287
|
+
"run_id", "model", "created_at", "n_prompts", "scored", "reference_label",
|
|
288
|
+
"changes", "changes_total", "reference_failures", "unscored",
|
|
289
|
+
}),
|
|
290
|
+
"versions": [{"label": r.label, "status": r.status, "verdict": r.verdict,
|
|
291
|
+
"n_worse": r.n_worse, "is_reference": r.is_reference,
|
|
292
|
+
"quality": r.quality, "n_scored": scored_n.get(r.label, 0)}
|
|
293
|
+
for r in view.rows],
|
|
294
|
+
"reference_quality": next((r.quality for r in view.rows if r.is_reference), None),
|
|
295
|
+
"message": view.recommendation.message if view.recommendation else None,
|
|
296
|
+
"reviews": reviews_mod.load(run_dir),
|
|
297
|
+
} # fmt: skip
|
|
298
|
+
|
|
299
|
+
@app.put("/api/runs/{run_id}/reviews")
|
|
300
|
+
def run_review(run_id: str, body: ReviewIn, _: Session = Depends(user)) -> dict[str, Any]:
|
|
301
|
+
run_dir, result = load_run(run_id)
|
|
302
|
+
if body.version not in {c.label for c in result.candidates}:
|
|
303
|
+
raise HTTPException(422, f"version: no '{body.version}' in this run")
|
|
304
|
+
if body.case_id not in {c.id for c in result.testset.cases}:
|
|
305
|
+
raise HTTPException(422, f"case_id: no '{body.case_id}' in this run")
|
|
306
|
+
return {"reviews": reviews_mod.save_one(run_dir, body)}
|
|
307
|
+
|
|
308
|
+
@app.post("/api/runs")
|
|
309
|
+
def start_run(body: StartRun, _: Session = Depends(user)) -> JSONResponse:
|
|
310
|
+
if state.chat.active():
|
|
311
|
+
raise HTTPException(
|
|
312
|
+
409, "Chat has models loaded. Close Chat first, then start the test."
|
|
313
|
+
)
|
|
314
|
+
tests = Path(body.tests).expanduser()
|
|
315
|
+
if not tests.is_absolute():
|
|
316
|
+
tests = state.data_dir / "tests" / tests
|
|
317
|
+
data: dict[str, Any] = {"model": body.model, "runtime": body.runtime,
|
|
318
|
+
"versions": body.versions, "tests": tests,
|
|
319
|
+
"output_dir": state.runs_dir} # fmt: skip
|
|
320
|
+
for key in ("judge_model", "max_tokens", "quality_limit"):
|
|
321
|
+
if getattr(body, key) is not None:
|
|
322
|
+
data[key] = getattr(body, key)
|
|
323
|
+
try:
|
|
324
|
+
cfg = RunConfig.model_validate(data)
|
|
325
|
+
prepared = state.prepare(cfg)
|
|
326
|
+
job = state.jobs.start(prepared)
|
|
327
|
+
except ValidationError as e:
|
|
328
|
+
first = e.errors()[0]
|
|
329
|
+
raise HTTPException(422, f"{'.'.join(map(str, first['loc']))}: {first['msg']}") from e
|
|
330
|
+
except JobError as e:
|
|
331
|
+
raise HTTPException(422, str(e)) from e
|
|
332
|
+
except Busy as e:
|
|
333
|
+
raise HTTPException(409, str(e)) from e
|
|
334
|
+
return JSONResponse(job.public(), status_code=202)
|
|
335
|
+
|
|
336
|
+
@app.get("/api/jobs/active")
|
|
337
|
+
def active_job(_: Session = Depends(user)) -> dict[str, Any] | None:
|
|
338
|
+
job = state.jobs.active()
|
|
339
|
+
return job.public() if job else None
|
|
340
|
+
|
|
341
|
+
@app.get("/api/jobs/{job_id}")
|
|
342
|
+
def job_status(job_id: str, _: Session = Depends(user)) -> dict[str, Any]:
|
|
343
|
+
job = state.jobs.get(job_id)
|
|
344
|
+
if job is None:
|
|
345
|
+
raise HTTPException(404, "no such job")
|
|
346
|
+
return job.public()
|
|
347
|
+
|
|
348
|
+
# ---- models and test sets -------------------------------------------------------------
|
|
349
|
+
@app.get("/api/compare")
|
|
350
|
+
def compare_runs(tests: str | None = None, _: Session = Depends(user)) -> dict[str, Any]:
|
|
351
|
+
runs_all = summary_mod.load_runs(state.runs_dir)
|
|
352
|
+
sets = compare_mod.test_sets(runs_all)
|
|
353
|
+
pick = (
|
|
354
|
+
tests
|
|
355
|
+
or next((x["name"] for x in sets if x["models"] >= 2), None)
|
|
356
|
+
or (sets[0]["name"] if sets else None)
|
|
357
|
+
)
|
|
358
|
+
body = (
|
|
359
|
+
compare_mod.compare(runs_all, pick) if pick else {"tests": None, "rows": [], "tags": []}
|
|
360
|
+
)
|
|
361
|
+
return {"test_sets": sets, **body}
|
|
362
|
+
|
|
363
|
+
# ---- model downloads (first-run setup) ----------------------------------------------
|
|
364
|
+
@app.get("/api/downloads")
|
|
365
|
+
def downloads_state(_: Session = Depends(user)) -> dict[str, Any]:
|
|
366
|
+
return state.downloads.public()
|
|
367
|
+
|
|
368
|
+
@app.post("/api/downloads")
|
|
369
|
+
def downloads_start(body: DownloadStart, _: Session = Depends(user)) -> dict[str, Any]:
|
|
370
|
+
try:
|
|
371
|
+
state.downloads.start([m.model_dump() for m in body.models])
|
|
372
|
+
except DownloadError as e:
|
|
373
|
+
raise HTTPException(422, str(e)) from e
|
|
374
|
+
except DownloadBusy as e:
|
|
375
|
+
raise HTTPException(409, str(e)) from e
|
|
376
|
+
return state.downloads.public()
|
|
377
|
+
|
|
378
|
+
# ---- chat side by side ----------------------------------------------------------------
|
|
379
|
+
@app.get("/api/chat")
|
|
380
|
+
def chat_state(_: Session = Depends(user)) -> dict[str, Any]:
|
|
381
|
+
return state.chat.public()
|
|
382
|
+
|
|
383
|
+
@app.post("/api/chat/load")
|
|
384
|
+
def chat_load(body: ChatLoad, _: Session = Depends(user)) -> dict[str, Any]:
|
|
385
|
+
if state.jobs.active():
|
|
386
|
+
raise HTTPException(
|
|
387
|
+
409, "A test is running. Wait for it to finish before opening Chat."
|
|
388
|
+
)
|
|
389
|
+
sizes = {m["id"]: m["size_mb"] / 1000 for m in cached_models()}
|
|
390
|
+
info = system_status(state.data_dir)
|
|
391
|
+
ram = info["hardware"]["ram_gb"]
|
|
392
|
+
free = round(info["memory"]["total_gb"] - info["memory"]["used_gb"], 1)
|
|
393
|
+
try:
|
|
394
|
+
state.chat.load([c.model_dump() for c in body.columns], sizes, ram, free)
|
|
395
|
+
except ChatError as e:
|
|
396
|
+
raise HTTPException(422, str(e)) from e
|
|
397
|
+
except ChatBusy as e:
|
|
398
|
+
raise HTTPException(409, str(e)) from e
|
|
399
|
+
return state.chat.public()
|
|
400
|
+
|
|
401
|
+
@app.post("/api/chat/ask")
|
|
402
|
+
def chat_ask(body: ChatAsk, _: Session = Depends(user)) -> dict[str, Any]:
|
|
403
|
+
header = SetHeader()
|
|
404
|
+
if body.tests:
|
|
405
|
+
try:
|
|
406
|
+
header = loads_tests(set_path(body.tests).read_text(encoding="utf-8")).header
|
|
407
|
+
except TestFileError as e:
|
|
408
|
+
raise HTTPException(422, str(e)) from e
|
|
409
|
+
try:
|
|
410
|
+
state.chat.ask(body.text, header, body.documents, body.max_tokens)
|
|
411
|
+
except ChatError as e:
|
|
412
|
+
raise HTTPException(422, str(e)) from e
|
|
413
|
+
except ChatBusy as e:
|
|
414
|
+
raise HTTPException(409, str(e)) from e
|
|
415
|
+
return state.chat.public()
|
|
416
|
+
|
|
417
|
+
@app.post("/api/chat/close")
|
|
418
|
+
def chat_close(_: Session = Depends(user)) -> dict[str, Any]:
|
|
419
|
+
try:
|
|
420
|
+
state.chat.close()
|
|
421
|
+
except ChatBusy as e:
|
|
422
|
+
raise HTTPException(409, str(e)) from e
|
|
423
|
+
return state.chat.public()
|
|
424
|
+
|
|
425
|
+
@app.get("/api/models/suggested")
|
|
426
|
+
def models_suggested(_: Session = Depends(user)) -> list[dict[str, Any]]:
|
|
427
|
+
return SUGGESTED
|
|
428
|
+
|
|
429
|
+
@app.get("/api/models/setup")
|
|
430
|
+
def models_setup(_: Session = Depends(user)) -> list[dict[str, Any]]:
|
|
431
|
+
return SETUP_MODELS
|
|
432
|
+
|
|
433
|
+
@app.get("/api/model")
|
|
434
|
+
def model_detail(id: str, _: Session = Depends(user)) -> dict[str, Any]:
|
|
435
|
+
sys_info = system_status(state.data_dir)
|
|
436
|
+
return modeldetail_mod.detail(id, cached_models(), summary_mod.load_runs(state.runs_dir),
|
|
437
|
+
sys_info["hardware"]["ram_gb"]) # fmt: skip
|
|
438
|
+
|
|
439
|
+
@app.get("/api/models")
|
|
440
|
+
def models(_: Session = Depends(user)) -> list[dict[str, Any]]:
|
|
441
|
+
return cached_models()
|
|
442
|
+
|
|
443
|
+
tests_dir = state.data_dir / "tests"
|
|
444
|
+
|
|
445
|
+
def set_path(name: str, must_exist: bool = True) -> Path:
|
|
446
|
+
try:
|
|
447
|
+
path = testsets_mod.safe_path(tests_dir, name)
|
|
448
|
+
except ValueError as e:
|
|
449
|
+
raise HTTPException(422, str(e)) from e
|
|
450
|
+
if must_exist and not path.is_file():
|
|
451
|
+
raise HTTPException(404, "no such test set")
|
|
452
|
+
return path
|
|
453
|
+
|
|
454
|
+
@app.get("/api/testsets")
|
|
455
|
+
def testsets(_: Session = Depends(user)) -> list[dict[str, Any]]:
|
|
456
|
+
if not tests_dir.is_dir():
|
|
457
|
+
return []
|
|
458
|
+
return [testsets_mod.summarize(p) for p in sorted(tests_dir.glob("*.jsonl"))]
|
|
459
|
+
|
|
460
|
+
@app.get("/api/testsets/help")
|
|
461
|
+
def testsets_help(_: Session = Depends(user)) -> dict[str, Any]:
|
|
462
|
+
return {
|
|
463
|
+
"checks": testsets_mod.check_catalog(),
|
|
464
|
+
"examples": testsets_mod.EXAMPLES, "languages": language.SUPPORTED,
|
|
465
|
+
"limits": {"max_prompts": limits.MAX_PROMPTS, "warn_prompts": limits.WARN_PROMPTS,
|
|
466
|
+
"max_tools": limits.MAX_TOOLS, "warn_tools": limits.WARN_TOOLS,
|
|
467
|
+
"context_tokens": testsets_mod.TYPICAL_CONTEXT_TOKENS},
|
|
468
|
+
} # fmt: skip
|
|
469
|
+
|
|
470
|
+
@app.post("/api/testsets/validate")
|
|
471
|
+
def testsets_validate(body: SetBody, _: Session = Depends(user)) -> dict[str, Any]:
|
|
472
|
+
try:
|
|
473
|
+
parsed, _text = testsets_mod.validate(body.header, body.cases)
|
|
474
|
+
except TestFileError as e:
|
|
475
|
+
return {"ok": False, "error": str(e), "warnings": []}
|
|
476
|
+
return {"ok": True, "error": None, "warnings": parsed.warnings}
|
|
477
|
+
|
|
478
|
+
@app.post("/api/testsets/preview")
|
|
479
|
+
def testsets_preview(body: PreviewBody, _: Session = Depends(user)) -> dict[str, Any]:
|
|
480
|
+
try:
|
|
481
|
+
return testsets_mod.preview(body.header, body.case, body.context_tokens)
|
|
482
|
+
except ValidationError as e:
|
|
483
|
+
first = e.errors()[0]
|
|
484
|
+
raise HTTPException(422, f"{'.'.join(map(str, first['loc']))}: {first['msg']}") from e
|
|
485
|
+
|
|
486
|
+
@app.get("/api/testsets/{name}/context")
|
|
487
|
+
def testset_context(name: str, _: Session = Depends(user)) -> dict[str, Any]:
|
|
488
|
+
try:
|
|
489
|
+
return testsets_mod.context_fit(set_path(name))
|
|
490
|
+
except TestFileError as e:
|
|
491
|
+
raise HTTPException(422, str(e)) from e
|
|
492
|
+
|
|
493
|
+
@app.get("/api/testsets/{name}")
|
|
494
|
+
def testset_read(name: str, _: Session = Depends(user)) -> dict[str, Any]:
|
|
495
|
+
try:
|
|
496
|
+
return testsets_mod.read_set(set_path(name))
|
|
497
|
+
except TestFileError as e:
|
|
498
|
+
raise HTTPException(422, str(e)) from e
|
|
499
|
+
|
|
500
|
+
@app.put("/api/testsets/{name}")
|
|
501
|
+
def testset_save(name: str, body: SetBody, _: Session = Depends(user)) -> dict[str, Any]:
|
|
502
|
+
path = set_path(name, must_exist=False)
|
|
503
|
+
try:
|
|
504
|
+
_parsed, text = testsets_mod.validate(body.header, body.cases)
|
|
505
|
+
except TestFileError as e:
|
|
506
|
+
raise HTTPException(422, str(e)) from e
|
|
507
|
+
tests_dir.mkdir(parents=True, exist_ok=True)
|
|
508
|
+
tmp = path.with_suffix(".jsonl.tmp")
|
|
509
|
+
tmp.write_text(text, encoding="utf-8")
|
|
510
|
+
tmp.replace(path) # a crash mid-save never leaves a half-written set
|
|
511
|
+
return testsets_mod.summarize(path)
|
|
512
|
+
|
|
513
|
+
@app.post("/api/testsets/{name}/duplicate")
|
|
514
|
+
def testset_duplicate(name: str, _: Session = Depends(user)) -> dict[str, Any]:
|
|
515
|
+
src = set_path(name)
|
|
516
|
+
n = 1
|
|
517
|
+
while True:
|
|
518
|
+
suffix = "-copy" if n == 1 else f"-copy{n}"
|
|
519
|
+
dest = set_path(f"{src.stem}{suffix}"[:64], must_exist=False)
|
|
520
|
+
if not dest.exists():
|
|
521
|
+
break
|
|
522
|
+
n += 1
|
|
523
|
+
dest.write_text(src.read_text(encoding="utf-8"), encoding="utf-8")
|
|
524
|
+
return testsets_mod.summarize(dest)
|
|
525
|
+
|
|
526
|
+
@app.delete("/api/testsets/{name}")
|
|
527
|
+
def testset_delete(name: str, _: Session = Depends(user)) -> dict[str, bool]:
|
|
528
|
+
set_path(name).unlink()
|
|
529
|
+
return {"ok": True}
|
|
530
|
+
|
|
531
|
+
return app
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
__all__ = ["LabState", "create_app", "jobs_mod"]
|
quantcheck/ui/catalog.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""A short, hand-kept list of open models worth trying, for the Models > Discover section.
|
|
2
|
+
|
|
3
|
+
Nothing here is fetched: the lab makes no network call to build this list. Parameter counts
|
|
4
|
+
are the published ones; sizes shown in the lab are estimates (parameters x bits / 8, plus ~10%).
|
|
5
|
+
``mlx_id`` is the repo a test starts from; the exact versions are looked up when a test runs,
|
|
6
|
+
and a missing one is skipped with a message.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
SUGGESTED: list[dict[str, Any]] = [
|
|
14
|
+
{"name": "Sarvam-1", "params_b": 2.0, "note": "Built for 10 Indian languages",
|
|
15
|
+
"mlx_id": "mlx-community/sarvam-1", "indian": True},
|
|
16
|
+
{"name": "Qwen3-4B", "params_b": 4.0, "note": "Small, strong multilingual model",
|
|
17
|
+
"mlx_id": "mlx-community/Qwen3-4B", "indian": True},
|
|
18
|
+
{"name": "Qwen3-8B", "params_b": 8.0, "note": "Strong multilingual reasoning",
|
|
19
|
+
"mlx_id": "mlx-community/Qwen3-8B", "indian": True},
|
|
20
|
+
{"name": "Qwen3-14B", "params_b": 14.0, "note": "Larger multilingual model",
|
|
21
|
+
"mlx_id": "mlx-community/Qwen3-14B", "indian": True},
|
|
22
|
+
{"name": "Gemma-3-4B", "params_b": 4.0, "note": "Good multilingual chat",
|
|
23
|
+
"mlx_id": "mlx-community/gemma-3-4b-it", "indian": True},
|
|
24
|
+
{"name": "Gemma-3-12B", "params_b": 12.0, "note": "Good multilingual chat, larger",
|
|
25
|
+
"mlx_id": "mlx-community/gemma-3-12b-it", "indian": True},
|
|
26
|
+
{"name": "Llama-3.1-8B", "params_b": 8.0, "note": "Popular general-purpose model",
|
|
27
|
+
"mlx_id": "mlx-community/Meta-Llama-3.1-8B-Instruct", "indian": False},
|
|
28
|
+
{"name": "Phi-4-mini", "params_b": 3.8, "note": "Compact model for reasoning and code",
|
|
29
|
+
"mlx_id": "mlx-community/Phi-4-mini-instruct", "indian": False},
|
|
30
|
+
{"name": "Llama-3.3-70B", "params_b": 70.0, "note": "Very large: needs a big GPU",
|
|
31
|
+
"mlx_id": "mlx-community/Llama-3.3-70B-Instruct", "indian": False},
|
|
32
|
+
] # fmt: skip
|
|
33
|
+
|
|
34
|
+
# First-run Setup: models that have a ready-made 8/6/4-bit MLX version on Hugging Face (checked
|
|
35
|
+
# 28 Nov 2026). Exact sizes are read from Hugging Face when a download starts; the screen only
|
|
36
|
+
# shows estimates (parameters x bits / 8, plus about 10%) before that.
|
|
37
|
+
SETUP_MODELS: list[dict[str, Any]] = [
|
|
38
|
+
{"key": "qwen3-8b", "name": "Qwen3-8B", "params_b": 8.0, "tag": "Recommended",
|
|
39
|
+
"why": "Strongest of the three, needs the most memory", "repo_base": "mlx-community/Qwen3-8B",
|
|
40
|
+
"bits": [8, 6, 4]},
|
|
41
|
+
{"key": "qwen3-4b", "name": "Qwen3-4B", "params_b": 4.0, "tag": "Quickest",
|
|
42
|
+
"why": "Small and fast, good for a first try", "repo_base": "mlx-community/Qwen3-4B",
|
|
43
|
+
"bits": [8, 6, 4]},
|
|
44
|
+
{"key": "gemma-3-4b", "name": "Gemma-3-4B", "params_b": 4.0, "tag": "Multilingual chat",
|
|
45
|
+
"why": "Good multilingual chat in a small size",
|
|
46
|
+
"repo_base": "mlx-community/gemma-3-4b-it", "bits": [8, 6, 4]},
|
|
47
|
+
] # fmt: skip
|