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.
Files changed (79) hide show
  1. quantcheck/__init__.py +3 -0
  2. quantcheck/auth/__init__.py +6 -0
  3. quantcheck/auth/base.py +74 -0
  4. quantcheck/auth/callback.py +73 -0
  5. quantcheck/auth/fake.py +40 -0
  6. quantcheck/auth/service.py +49 -0
  7. quantcheck/auth/store.py +63 -0
  8. quantcheck/auth/supabase.py +168 -0
  9. quantcheck/bench.py +38 -0
  10. quantcheck/candidates.py +138 -0
  11. quantcheck/cli.py +251 -0
  12. quantcheck/config.py +63 -0
  13. quantcheck/executors/__init__.py +0 -0
  14. quantcheck/hardware.py +52 -0
  15. quantcheck/limits.py +19 -0
  16. quantcheck/pipeline.py +172 -0
  17. quantcheck/prompt.py +67 -0
  18. quantcheck/recommend.py +131 -0
  19. quantcheck/report/__init__.py +0 -0
  20. quantcheck/report/html.py +38 -0
  21. quantcheck/report/templates/report.html.j2 +272 -0
  22. quantcheck/report/terminal.py +90 -0
  23. quantcheck/report/tokens.py +41 -0
  24. quantcheck/report/view.py +161 -0
  25. quantcheck/runners/__init__.py +3 -0
  26. quantcheck/runners/base.py +87 -0
  27. quantcheck/runners/fake.py +68 -0
  28. quantcheck/runners/llamacpp_runner.py +185 -0
  29. quantcheck/runners/mlx_runner.py +153 -0
  30. quantcheck/runners/toolparse.py +107 -0
  31. quantcheck/scoring/__init__.py +0 -0
  32. quantcheck/scoring/checks.py +342 -0
  33. quantcheck/scoring/fake_judge.py +50 -0
  34. quantcheck/scoring/judge.py +171 -0
  35. quantcheck/scoring/language.py +99 -0
  36. quantcheck/scoring/models.py +92 -0
  37. quantcheck/scoring/score.py +167 -0
  38. quantcheck/scoring/stats.py +60 -0
  39. quantcheck/settings.py +14 -0
  40. quantcheck/store.py +88 -0
  41. quantcheck/tests_io.py +169 -0
  42. quantcheck/ui/__init__.py +1 -0
  43. quantcheck/ui/app.py +534 -0
  44. quantcheck/ui/catalog.py +47 -0
  45. quantcheck/ui/chat.py +211 -0
  46. quantcheck/ui/compare.py +63 -0
  47. quantcheck/ui/downloads.py +172 -0
  48. quantcheck/ui/jobs.py +173 -0
  49. quantcheck/ui/modeldetail.py +97 -0
  50. quantcheck/ui/reviews.py +59 -0
  51. quantcheck/ui/security.py +45 -0
  52. quantcheck/ui/static/chat.js +312 -0
  53. quantcheck/ui/static/fonts/JetBrainsMono-latin-b87346.woff2 +0 -0
  54. quantcheck/ui/static/fonts/JetBrainsMono-latin-ext-9326b4.woff2 +0 -0
  55. quantcheck/ui/static/fonts/NotoSansDevanagari-devanagari-3819bb.woff2 +0 -0
  56. quantcheck/ui/static/fonts/NotoSansDevanagari-latin-ext-542103.woff2 +0 -0
  57. quantcheck/ui/static/fonts/NotoSansDevanagari-latin-f3aaed.woff2 +0 -0
  58. quantcheck/ui/static/fonts/NotoSansTamil-latin-17e6dc.woff2 +0 -0
  59. quantcheck/ui/static/fonts/NotoSansTamil-latin-ext-027c12.woff2 +0 -0
  60. quantcheck/ui/static/fonts/NotoSansTamil-tamil-a57d5e.woff2 +0 -0
  61. quantcheck/ui/static/fonts/Outfit-latin-ebadd8.woff2 +0 -0
  62. quantcheck/ui/static/fonts/Outfit-latin-ext-744997.woff2 +0 -0
  63. quantcheck/ui/static/fonts/README.md +14 -0
  64. quantcheck/ui/static/fonts.css +228 -0
  65. quantcheck/ui/static/index.html +24 -0
  66. quantcheck/ui/static/lab.css +768 -0
  67. quantcheck/ui/static/lab.js +896 -0
  68. quantcheck/ui/static/logo.svg +5 -0
  69. quantcheck/ui/static/review.js +127 -0
  70. quantcheck/ui/static/setup.js +132 -0
  71. quantcheck/ui/static/testsets.js +527 -0
  72. quantcheck/ui/summary.py +104 -0
  73. quantcheck/ui/system.py +101 -0
  74. quantcheck/ui/testsets.py +243 -0
  75. quantcheck-0.0.1.dist-info/METADATA +115 -0
  76. quantcheck-0.0.1.dist-info/RECORD +79 -0
  77. quantcheck-0.0.1.dist-info/WHEEL +4 -0
  78. quantcheck-0.0.1.dist-info/entry_points.txt +2 -0
  79. quantcheck-0.0.1.dist-info/licenses/LICENSE +202 -0
quantcheck/cli.py ADDED
@@ -0,0 +1,251 @@
1
+ """Command-line entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import webbrowser
7
+ from pathlib import Path
8
+ from typing import Annotated
9
+
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.progress import BarColumn, Progress, TextColumn, TimeRemainingColumn
13
+ from rich.table import Table
14
+
15
+ from quantcheck import __version__, runners # noqa: F401 (importing registers runners)
16
+ from quantcheck.auth import AuthError, NotSignedIn
17
+ from quantcheck.auth.service import default_provider, default_store, require_session
18
+ from quantcheck.config import ConfigError, load_config
19
+ from quantcheck.hardware import hardware_info
20
+ from quantcheck.pipeline import JobError, prepare_job, run_job, score_job
21
+ from quantcheck.report.html import write_report
22
+ from quantcheck.report.terminal import render
23
+ from quantcheck.report.view import build_view
24
+ from quantcheck.scoring.judge import get_judge, load_rubric
25
+ from quantcheck.settings import DEFAULT_HOST, DEFAULT_PORT, data_dir
26
+ from quantcheck.store import JsonResultsStore
27
+
28
+ app = typer.Typer(
29
+ help="QuantCheck: test quantized models on your own prompts.", no_args_is_help=True
30
+ )
31
+ console = Console()
32
+
33
+
34
+ @app.callback()
35
+ def main() -> None:
36
+ """QuantCheck command group."""
37
+
38
+
39
+ @app.command()
40
+ def version() -> None:
41
+ """Print the installed version."""
42
+ typer.echo(__version__)
43
+
44
+
45
+ @app.command()
46
+ def hw() -> None:
47
+ """Show this machine: chip, memory, free disk."""
48
+ info = hardware_info()
49
+ table = Table(show_header=False)
50
+ for key, val in info.items():
51
+ table.add_row(key, str(val))
52
+ console.print(table)
53
+
54
+
55
+ def _fail(msg: str) -> typer.Exit:
56
+ console.print(f"[red]Error:[/red] {msg}")
57
+ return typer.Exit(code=1)
58
+
59
+
60
+ def get_store():
61
+ """The session store (the Keychain). A function so tests can replace it."""
62
+ return default_store()
63
+
64
+
65
+ def get_auth_provider():
66
+ """The configured sign-in provider. A function so tests can replace it."""
67
+ return default_provider()
68
+
69
+
70
+ def _require_login() -> None:
71
+ """Stop with a clear message unless someone is signed in on this machine."""
72
+ try:
73
+ require_session(get_store(), get_auth_provider())
74
+ except AuthError as e: # NotSignedIn, or the provider is not configured
75
+ raise _fail(str(e)) from e
76
+
77
+
78
+ @app.command()
79
+ def login(
80
+ with_: Annotated[str, typer.Option("--with", help="google or github")] = "google",
81
+ ) -> None:
82
+ """Sign in (opens your browser). Needed once per machine."""
83
+
84
+ def open_url(url: str) -> None:
85
+ console.print("Opening your browser to sign in. If nothing opens, visit:")
86
+ console.print(url, soft_wrap=True, highlight=False)
87
+ webbrowser.open(url)
88
+
89
+ try:
90
+ session = get_auth_provider().login(open_url, with_)
91
+ except AuthError as e:
92
+ raise _fail(str(e)) from e
93
+ get_store().save(session)
94
+ console.print(f"Signed in as {session.name or session.email} ({session.email}).")
95
+ console.print("quantcheck now works offline. Prompts and answers never leave this machine.")
96
+
97
+
98
+ @app.command()
99
+ def logout() -> None:
100
+ """Sign out on this machine. Your local runs and reports are kept."""
101
+ store = get_store()
102
+ session = store.load()
103
+ if session is None:
104
+ console.print("Not signed in.")
105
+ return
106
+ get_auth_provider().logout(session)
107
+ store.clear()
108
+ console.print("Signed out. Your local runs and reports are kept.")
109
+
110
+
111
+ @app.command()
112
+ def whoami() -> None:
113
+ """Show who is signed in."""
114
+ try:
115
+ session = require_session(get_store(), get_auth_provider())
116
+ except NotSignedIn as e:
117
+ raise _fail(str(e)) from e
118
+ except AuthError as e:
119
+ raise _fail(str(e)) from e
120
+ console.print(f"{session.name or '-'} <{session.email}> plan: {session.plan}")
121
+
122
+
123
+ @app.command()
124
+ def run(config_path: Annotated[Path, typer.Argument(help="Path to quantcheck.yaml")]) -> None:
125
+ """Run every prompt through every version and save results.json."""
126
+ _require_login()
127
+ try:
128
+ cfg = load_config(config_path)
129
+ job = prepare_job(cfg)
130
+ except (ConfigError, JobError) as e:
131
+ raise _fail(str(e)) from e
132
+
133
+ for w in job.testset.warnings:
134
+ console.print(f"[yellow]Note:[/yellow] {w}")
135
+ for label, why in job.resolution.skipped.items():
136
+ console.print(f"[yellow]Skipping {label}:[/yellow] {why}")
137
+
138
+ total = len(job.testset.cases) * len(job.resolution.candidates)
139
+ with Progress(
140
+ TextColumn("{task.description}"), BarColumn(), TimeRemainingColumn(), console=console
141
+ ) as bar:
142
+ task = bar.add_task("starting", total=total)
143
+
144
+ def on_progress(label: str, done: int, _n: int) -> None:
145
+ bar.update(
146
+ task, description=f"{label}: prompt {done}/{len(job.testset.cases)}", advance=1
147
+ )
148
+
149
+ store = JsonResultsStore(cfg.output_dir)
150
+ result = run_job(cfg, job.testset, job.resolution, job.runner, store, on_progress)
151
+
152
+ scoring_error = _score(result, job.judge, job.rubric, store, cfg.quality_limit)
153
+
154
+ report_path = write_report(result, cfg.output_dir / result.run_id / "report.html")
155
+ render(build_view(result), console, report_path)
156
+ console.print(f"Saved: {cfg.output_dir / result.run_id / 'results.json'}")
157
+ if scoring_error:
158
+ raise _fail(
159
+ f"scoring stopped: {scoring_error}. Answers are saved; fix the judge and rerun."
160
+ )
161
+
162
+
163
+ @app.command()
164
+ def report(
165
+ run_ref: Annotated[str, typer.Argument(help="Run id, run folder, or results.json")],
166
+ runs_dir: Annotated[Path, typer.Option(help="Where runs are saved")] = Path("runs"),
167
+ ) -> None:
168
+ """Show the summary of a saved run and rebuild its report.html."""
169
+ store = JsonResultsStore(runs_dir)
170
+ try:
171
+ result = store.load(run_ref)
172
+ except (FileNotFoundError, ValueError) as e:
173
+ raise _fail(str(e)) from e
174
+ path = write_report(result, runs_dir / result.run_id / "report.html")
175
+ render(build_view(result), console, path)
176
+
177
+
178
+ @app.command()
179
+ def rescore(
180
+ run_ref: Annotated[str, typer.Argument(help="Run id, run folder, or results.json")],
181
+ runs_dir: Annotated[Path, typer.Option(help="Where runs are saved")] = Path("runs"),
182
+ ) -> None:
183
+ """Score a saved run again (new checks or judge) without running the models.
184
+
185
+ The answers stay as they are. The old results.json is kept as results.previous.json.
186
+ """
187
+ _require_login()
188
+ store = JsonResultsStore(runs_dir)
189
+ try:
190
+ result = store.load(run_ref)
191
+ cfg = result.config # the dict saved with the run
192
+ judge = get_judge(cfg["judge"], cfg["judge_model"])
193
+ rubric = load_rubric(Path(cfg["rubric"]) if cfg.get("rubric") else None)
194
+ except (FileNotFoundError, ValueError, KeyError) as e:
195
+ raise _fail(str(e)) from e
196
+ folder = runs_dir / result.run_id
197
+ shutil.copy(folder / "results.json", folder / "results.previous.json")
198
+ if error := _score(result, judge, rubric, store, cfg["quality_limit"]):
199
+ raise _fail(f"scoring stopped: {error}. The saved results were not changed.")
200
+ path = write_report(result, folder / "report.html")
201
+ render(build_view(result), console, path)
202
+
203
+
204
+ @app.command()
205
+ def ui(
206
+ port: Annotated[int, typer.Option(help="Port to serve on")] = DEFAULT_PORT,
207
+ host: Annotated[str, typer.Option(help="Address to listen on")] = DEFAULT_HOST,
208
+ no_browser: Annotated[bool, typer.Option("--no-browser", help="Do not open a tab")] = False,
209
+ ) -> None:
210
+ """Open the local lab in your browser (runs only on this Mac)."""
211
+ import socket
212
+
213
+ import uvicorn
214
+
215
+ from quantcheck.ui.app import LabState, create_app
216
+ from quantcheck.ui.system import print_status, system_status
217
+
218
+ with socket.socket() as probe:
219
+ if probe.connect_ex((host if host != "0.0.0.0" else "127.0.0.1", port)) == 0: # noqa: S104
220
+ raise _fail(f"port {port} is already in use. Try: quantcheck ui --port {port + 1}")
221
+ if host not in ("127.0.0.1", "localhost", "::1"):
222
+ console.print(
223
+ f"[yellow]Warning:[/yellow] listening on {host} makes the lab reachable from other "
224
+ "devices on your network. Use the default (127.0.0.1) unless you know you need this."
225
+ )
226
+ folder = data_dir()
227
+ state = LabState(store=get_store(), provider=get_auth_provider, data_dir=folder, port=port,
228
+ extra_hosts={host}) # fmt: skip
229
+ url = f"http://localhost:{port}"
230
+ print_status(console, system_status(folder), url, opening_browser=not no_browser)
231
+ if not no_browser:
232
+ webbrowser.open(url)
233
+ uvicorn.run(create_app(state), host=host, port=port, log_level="warning")
234
+
235
+
236
+ def _pct(value: float | None) -> str:
237
+ return f"{value:.0%}" if value is not None else "-"
238
+
239
+
240
+ def _score(result, judge, rubric: str, store: JsonResultsStore, quality_limit: float) -> str | None:
241
+ """Judge pass with a progress bar. Returns an error message, or None."""
242
+ total = sum(len(c.answers) for c in result.candidates if c.status == "ok")
243
+ with Progress(
244
+ TextColumn("{task.description}"), BarColumn(), TimeRemainingColumn(), console=console
245
+ ) as bar:
246
+ task = bar.add_task("judging", total=total)
247
+
248
+ def on_progress(label: str, done: int, n: int) -> None:
249
+ bar.update(task, description=f"judging {label}: {done}/{n}", advance=1)
250
+
251
+ return score_job(result, judge, rubric, store, quality_limit, on_progress)
quantcheck/config.py ADDED
@@ -0,0 +1,63 @@
1
+ """quantcheck.yaml: the run configuration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ import yaml
9
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
10
+
11
+ from quantcheck import limits
12
+ from quantcheck.runners.base import GenSettings
13
+
14
+
15
+ class ConfigError(ValueError):
16
+ """quantcheck.yaml is missing or invalid."""
17
+
18
+
19
+ class RunConfig(BaseModel):
20
+ """Phase 1 fields. Later phases add hardware, search, serving, executor and cost."""
21
+
22
+ model_config = ConfigDict(extra="forbid")
23
+
24
+ model: str
25
+ runtime: Literal["mlx", "llamacpp"] = "mlx"
26
+ versions: list[str] = Field(min_length=1)
27
+ tests: Path
28
+ judge: Literal["local", "claude"] = "local"
29
+ judge_model: str = "mlx-community/Qwen3-8B-4bit" # used by the local judge; keep fixed
30
+ rubric: Path | None = None # text file replacing the default rubric
31
+ quality_limit: float = Field(default=0.97, gt=0, le=1)
32
+ max_tokens: int = Field(default=limits.DEFAULT_ANSWER_TOKENS, gt=0, le=limits.MAX_ANSWER_TOKENS)
33
+ seed: int = 42
34
+ output_dir: Path = Path("runs")
35
+
36
+ def settings(self) -> GenSettings:
37
+ """Generation settings shared by every candidate: temperature 0, fixed seed."""
38
+ return GenSettings(temperature=0.0, seed=self.seed, max_tokens=self.max_tokens)
39
+
40
+
41
+ def load_config(path: str | Path) -> RunConfig:
42
+ """Read quantcheck.yaml. ``tests`` is resolved relative to the yaml file's folder."""
43
+ p = Path(path)
44
+ if not p.is_file():
45
+ raise ConfigError(f"config not found: {p}")
46
+ try:
47
+ data = yaml.safe_load(p.read_text(encoding="utf-8"))
48
+ except yaml.YAMLError as e:
49
+ raise ConfigError(f"{p}: not valid YAML ({e})") from e
50
+ if not isinstance(data, dict):
51
+ raise ConfigError(f"{p}: expected a mapping of settings")
52
+ try:
53
+ cfg = RunConfig.model_validate(data)
54
+ except ValidationError as e:
55
+ first = e.errors()[0]
56
+ loc = ".".join(str(x) for x in first["loc"])
57
+ raise ConfigError(f"{p}: {loc}: {first['msg']}") from e
58
+ updates: dict[str, Path] = {}
59
+ for name in ("tests", "rubric"):
60
+ value = getattr(cfg, name)
61
+ if value is not None and not value.is_absolute():
62
+ updates[name] = (p.parent / value).resolve()
63
+ return cfg.model_copy(update=updates) if updates else cfg
File without changes
quantcheck/hardware.py ADDED
@@ -0,0 +1,52 @@
1
+ """Machine info: chip, RAM, free disk. Saved with every run."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ import shutil
7
+ import subprocess
8
+ from importlib import metadata
9
+ from pathlib import Path
10
+
11
+ import psutil
12
+
13
+ _LIBS = ["quantcheck", "mlx", "mlx-lm", "llama-cpp-python", "pydantic", "typer"]
14
+
15
+
16
+ def _chip() -> str:
17
+ if platform.system() == "Darwin":
18
+ try:
19
+ out = subprocess.run(
20
+ ["sysctl", "-n", "machdep.cpu.brand_string"],
21
+ capture_output=True,
22
+ text=True,
23
+ timeout=5,
24
+ check=True,
25
+ )
26
+ return out.stdout.strip() or platform.processor()
27
+ except (OSError, subprocess.SubprocessError):
28
+ pass
29
+ return platform.processor() or platform.machine()
30
+
31
+
32
+ def hardware_info(disk_path: str | Path = ".") -> dict:
33
+ """Chip, OS, RAM and free disk as plain values."""
34
+ return {
35
+ "chip": _chip(),
36
+ "os": f"{platform.system()} {platform.release()}",
37
+ "machine": platform.machine(),
38
+ "cpu_count": psutil.cpu_count(logical=True),
39
+ "ram_gb": round(psutil.virtual_memory().total / 1e9, 1),
40
+ "free_disk_gb": round(shutil.disk_usage(disk_path).free / 1e9, 1),
41
+ }
42
+
43
+
44
+ def library_versions() -> dict[str, str | None]:
45
+ """Installed versions of the libraries that affect results (None if not installed)."""
46
+ out: dict[str, str | None] = {"python": platform.python_version()}
47
+ for lib in _LIBS:
48
+ try:
49
+ out[lib] = metadata.version(lib)
50
+ except metadata.PackageNotFoundError:
51
+ out[lib] = None
52
+ return out
quantcheck/limits.py ADDED
@@ -0,0 +1,19 @@
1
+ """Safety limits for the free lab, in one place so they are easy to change.
2
+
3
+ Warn limits print a friendly message; hard limits stop the run.
4
+ """
5
+
6
+ MAX_PROMPTS = 2000
7
+ WARN_PROMPTS = 500
8
+ MAX_VERSIONS = 6
9
+ MAX_TOOLS = 32
10
+ WARN_TOOLS = 16
11
+ MAX_ANSWER_TOKENS = 2048
12
+ DEFAULT_ANSWER_TOKENS = 512
13
+ CONTEXT_WARN_FRACTION = 0.8 # warn when the full prompt fills 80% of the context window
14
+
15
+ MIN_PROMPTS_FOR_VERDICT = 20 # below this, no version is called safe: the sample is too small
16
+ BOOTSTRAP_RESAMPLES = 2000
17
+ CONFIDENCE = 0.95
18
+
19
+ MAX_CHAT_COLUMNS = 4 # models held in memory side by side in Chat
quantcheck/pipeline.py ADDED
@@ -0,0 +1,172 @@
1
+ """The run pipeline (F3): every prompt through every version with identical settings.
2
+
3
+ One model is loaded at a time. A version that fails to load is skipped with a reason and
4
+ the run continues. Tools are never executed: when the model writes a tool call and the
5
+ test case has a recorded result, that result is played back for a second turn.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import secrets
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass
13
+ from datetime import UTC, datetime
14
+
15
+ from quantcheck import runners # noqa: F401 (importing registers runners)
16
+ from quantcheck.candidates import Resolution, resolve_candidates
17
+ from quantcheck.config import RunConfig
18
+ from quantcheck.hardware import hardware_info, library_versions
19
+ from quantcheck.prompt import build_prompt, followup_prompt
20
+ from quantcheck.recommend import recommend
21
+ from quantcheck.runners.base import Generation, GenSettings, Runner, get_runner
22
+ from quantcheck.scoring.checks import validate_checks
23
+ from quantcheck.scoring.judge import Judge, get_judge, load_rubric
24
+ from quantcheck.scoring.score import score_run
25
+ from quantcheck.store import AnswerRecord, CandidateRun, ResultsStore, RunResult
26
+ from quantcheck.tests_io import SetHeader, TestCase, TestSet, load_tests
27
+
28
+ Progress = Callable[[str, int, int], None] # (version label, prompts done, prompts total)
29
+ AnswerSeen = Callable[[str, TestCase, AnswerRecord], None] # (version label, case, its answer)
30
+
31
+
32
+ def new_run_id(now: datetime | None = None) -> str:
33
+ """Sortable id such as ``20261126-153012-a1b2``."""
34
+ now = now or datetime.now(UTC)
35
+ return f"{now:%Y%m%d-%H%M%S}-{secrets.token_hex(2)}"
36
+
37
+
38
+ def answer_case(
39
+ runner: Runner, header: SetHeader, case: TestCase, settings: GenSettings
40
+ ) -> AnswerRecord:
41
+ """Run one test case, including the recorded-tool-result follow-up turn."""
42
+ prompt = build_prompt(header, case)
43
+ try:
44
+ first = runner.generate(prompt, settings)
45
+ except Exception as e: # one bad prompt must not stop the run
46
+ return AnswerRecord(case_id=case.id, generation=Generation(text="", error=str(e)))
47
+ followup = None
48
+ if first.tool_calls and not first.error:
49
+ call = first.tool_calls[0]
50
+ if call.name in case.tool_results:
51
+ try:
52
+ followup = runner.generate(
53
+ followup_prompt(prompt, call, case.tool_results[call.name]), settings
54
+ )
55
+ except Exception as e:
56
+ followup = Generation(text="", error=str(e))
57
+ return AnswerRecord(case_id=case.id, generation=first, followup=followup)
58
+
59
+
60
+ def _run_candidate(
61
+ runner: Runner,
62
+ candidate_run: CandidateRun,
63
+ testset: TestSet,
64
+ settings: GenSettings,
65
+ on_progress: Progress | None,
66
+ on_answer: AnswerSeen | None = None,
67
+ ) -> CandidateRun:
68
+ total = len(testset.cases)
69
+ for i, case in enumerate(testset.cases, start=1):
70
+ record = answer_case(runner, testset.header, case, settings)
71
+ candidate_run.answers.append(record)
72
+ if on_answer:
73
+ on_answer(candidate_run.label, case, record)
74
+ if on_progress:
75
+ on_progress(candidate_run.label, i, total)
76
+ return candidate_run
77
+
78
+
79
+ def run_job(
80
+ config: RunConfig,
81
+ testset: TestSet,
82
+ resolution: Resolution,
83
+ runner: Runner,
84
+ store: ResultsStore | None = None,
85
+ on_progress: Progress | None = None,
86
+ on_answer: AnswerSeen | None = None,
87
+ ) -> RunResult:
88
+ """Run the whole test; save to ``store`` if given. Returns the full record."""
89
+ settings = config.settings()
90
+ runs: list[CandidateRun] = []
91
+ for candidate in resolution.candidates:
92
+ cr = CandidateRun(label=candidate.quantization, candidate=candidate)
93
+ try:
94
+ runner.load(candidate)
95
+ except Exception as e:
96
+ cr.status, cr.reason = "skipped", f"failed to load: {e}"
97
+ runs.append(cr)
98
+ continue
99
+ cr.file_size_mb = runner.model_info().get("file_size_mb")
100
+ try:
101
+ runs.append(_run_candidate(runner, cr, testset, settings, on_progress, on_answer))
102
+ finally:
103
+ runner.unload()
104
+ for label, why in resolution.skipped.items():
105
+ runs.append(CandidateRun(label=label, status="skipped", reason=why))
106
+
107
+ result = RunResult(
108
+ run_id=new_run_id(),
109
+ created_at=datetime.now(UTC).isoformat(timespec="seconds"),
110
+ config=config.model_dump(mode="json"),
111
+ environment={"hardware": hardware_info(), "libraries": library_versions()},
112
+ testset=testset,
113
+ candidates=runs,
114
+ )
115
+ if store:
116
+ store.save(result)
117
+ return result
118
+
119
+
120
+ class JobError(ValueError):
121
+ """The job cannot start: a message that is safe to show to the user."""
122
+
123
+
124
+ @dataclass
125
+ class PreparedJob:
126
+ """Everything a run needs, checked before any model is loaded."""
127
+
128
+ config: RunConfig
129
+ testset: TestSet
130
+ resolution: Resolution
131
+ runner: Runner
132
+ judge: Judge
133
+ rubric: str
134
+
135
+
136
+ def prepare_job(config: RunConfig) -> PreparedJob:
137
+ """Load and check tests, versions, runner, judge and rubric. Raises JobError."""
138
+ try:
139
+ testset = load_tests(config.tests)
140
+ resolution = resolve_candidates(config.model, config.versions, config.runtime)
141
+ runner = get_runner(config.runtime)
142
+ judge = get_judge(config.judge, config.judge_model)
143
+ rubric = load_rubric(config.rubric)
144
+ except (ValueError, KeyError, FileNotFoundError) as e: # TestFileError is a ValueError
145
+ raise JobError(str(e)) from e
146
+ problems = validate_checks(testset)
147
+ if problems:
148
+ raise JobError("bad checks in the tests file:\n " + "\n ".join(problems))
149
+ return PreparedJob(config, testset, resolution, runner, judge, rubric)
150
+
151
+
152
+ def score_job(
153
+ result: RunResult,
154
+ judge: Judge,
155
+ rubric: str,
156
+ store: ResultsStore,
157
+ quality_limit: float,
158
+ on_progress: Progress | None = None,
159
+ ) -> str | None:
160
+ """Judge pass after all versions finished. Returns an error message, or None.
161
+
162
+ The answers are already saved before this runs, so a judge failure loses nothing.
163
+ """
164
+ if sum(len(c.answers) for c in result.candidates if c.status == "ok") == 0:
165
+ return None
166
+ try:
167
+ result.scoring = score_run(result, judge, rubric, on_progress)
168
+ result.recommendation = recommend(result, quality_limit)
169
+ except Exception as e: # judge model missing, out of memory...
170
+ return str(e)
171
+ store.save(result)
172
+ return None
quantcheck/prompt.py ADDED
@@ -0,0 +1,67 @@
1
+ """Build the full prompt the customer's app would send: instructions, documents, tools, question.
2
+
3
+ The result is structured (messages + tools), not one string, so each runner can apply the
4
+ model's own chat template and native tool-calling format.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+
11
+ from pydantic import BaseModel, Field
12
+
13
+ from quantcheck.tests_io import SetHeader, TestCase, ToolCall
14
+
15
+
16
+ class Prompt(BaseModel):
17
+ """OpenAI-style messages plus tool definitions (what HF chat templates expect)."""
18
+
19
+ messages: list[dict]
20
+ tools: list[dict] = Field(default_factory=list)
21
+
22
+ @property
23
+ def user_text(self) -> str:
24
+ """Content of the last user message."""
25
+ for m in reversed(self.messages):
26
+ if m["role"] == "user":
27
+ return str(m["content"])
28
+ return ""
29
+
30
+
31
+ def _tool_defs(header: SetHeader) -> list[dict]:
32
+ return [
33
+ {
34
+ "type": "function",
35
+ "function": {"name": t.name, "description": t.description, "parameters": t.parameters},
36
+ }
37
+ for t in header.tools
38
+ ]
39
+
40
+
41
+ def _user_content(case: TestCase) -> str:
42
+ if not case.context:
43
+ return case.prompt
44
+ docs = "\n".join(f"[{i}] {d}" for i, d in enumerate(case.context, start=1))
45
+ return f"Documents:\n{docs}\n\nQuestion: {case.prompt}"
46
+
47
+
48
+ def build_prompt(header: SetHeader, case: TestCase) -> Prompt:
49
+ """The first-turn prompt for one test case."""
50
+ messages: list[dict] = []
51
+ if header.system:
52
+ messages.append({"role": "system", "content": header.system})
53
+ messages.append({"role": "user", "content": _user_content(case)})
54
+ return Prompt(messages=messages, tools=_tool_defs(header))
55
+
56
+
57
+ def followup_prompt(prompt: Prompt, call: ToolCall, result: object) -> Prompt:
58
+ """Second turn: the model's tool call plus the recorded result. The tool is never run."""
59
+ assistant = {
60
+ "role": "assistant",
61
+ "content": "",
62
+ "tool_calls": [
63
+ {"type": "function", "function": {"name": call.name, "arguments": call.arguments}}
64
+ ],
65
+ }
66
+ tool = {"role": "tool", "name": call.name, "content": json.dumps(result, ensure_ascii=False)}
67
+ return Prompt(messages=[*prompt.messages, assistant, tool], tools=prompt.tools)