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
@@ -0,0 +1,107 @@
1
+ """Read the tool call a model wrote, from its raw text. Tools are never run.
2
+
3
+ Each model family writes tool calls in its own way. Supported formats:
4
+ ``hermes`` (``<tool_call>{json}</tool_call>``: Qwen 2.5/3, Hermes), ``mistral``
5
+ (``[TOOL_CALLS][{json}]``) and ``llama3`` (a bare JSON object with ``name`` and
6
+ ``parameters``, optionally after ``<|python_tag|>``). A model whose format is not listed
7
+ returns no tool calls, which the ``tool_call`` check then reports as a failure.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import re
14
+
15
+ from quantcheck.tests_io import ToolCall
16
+
17
+ _THINK = re.compile(r"<think>.*?</think>\s*", re.S)
18
+
19
+
20
+ def clean_answer(text: str) -> str:
21
+ """Drop any ``<think>`` reasoning block so checks and judges see only the answer."""
22
+ return _THINK.sub("", text).strip()
23
+
24
+
25
+ def split_tool_calls(text: str, start: str | None, end: str | None) -> tuple[str, list[str]]:
26
+ """Separate the model's tool-call blocks from its plain answer text.
27
+
28
+ Returns (answer text without tool blocks, raw text inside each block). A block that never
29
+ closes (cut off by max_tokens) is returned as text so the failure is visible, not hidden.
30
+ """
31
+ if not start or not end:
32
+ return text, []
33
+ segments: list[str] = []
34
+ out: list[str] = []
35
+ pos = 0
36
+ while (i := text.find(start, pos)) != -1:
37
+ j = text.find(end, i + len(start))
38
+ if j == -1:
39
+ break
40
+ out.append(text[pos:i])
41
+ segments.append(text[i + len(start) : j])
42
+ pos = j + len(end)
43
+ out.append(text[pos:])
44
+ return "".join(out).strip(), segments
45
+
46
+
47
+ def detect_style(chat_template: str) -> str | None:
48
+ """Which tool-call format a chat template uses, from its text. None if unknown."""
49
+ if "<tool_call>" in chat_template:
50
+ return "hermes"
51
+ if "[TOOL_CALLS]" in chat_template:
52
+ return "mistral"
53
+ if "<|python_tag|>" in chat_template or '"parameters"' in chat_template:
54
+ return "llama3"
55
+ return None
56
+
57
+
58
+ def _to_call(obj: object) -> ToolCall:
59
+ if not isinstance(obj, dict) or not isinstance(obj.get("name"), str):
60
+ raise ValueError("tool call has no 'name'")
61
+ args = obj.get("arguments", obj.get("parameters", {}))
62
+ if isinstance(args, str):
63
+ args = json.loads(args)
64
+ if not isinstance(args, dict):
65
+ raise ValueError("tool call arguments are not an object")
66
+ return ToolCall(name=obj["name"], arguments=args)
67
+
68
+
69
+ def _first_json(text: str) -> object | None:
70
+ start = min((i for i in (text.find("{"), text.find("[")) if i != -1), default=-1)
71
+ if start == -1:
72
+ return None
73
+ try:
74
+ return json.JSONDecoder().raw_decode(text[start:])[0]
75
+ except json.JSONDecodeError:
76
+ return None
77
+
78
+
79
+ def parse_tool_calls(text: str, style: str | None) -> tuple[str, list[ToolCall], str | None]:
80
+ """(answer text without tool calls, tool calls, error). A garbled call sets ``error``."""
81
+ if style is None:
82
+ return text, [], None
83
+ calls: list[ToolCall] = []
84
+ error = None
85
+ try:
86
+ if style == "hermes":
87
+ rest, segs = split_tool_calls(text, "<tool_call>", "</tool_call>")
88
+ for seg in segs:
89
+ try:
90
+ calls.append(_to_call(json.loads(seg.strip())))
91
+ except (ValueError, json.JSONDecodeError) as e:
92
+ error = f"unreadable tool call: {e}"
93
+ return rest, calls, error
94
+ if style == "mistral" and "[TOOL_CALLS]" in text:
95
+ before, _, after = text.partition("[TOOL_CALLS]")
96
+ data = _first_json(after)
97
+ items = data if isinstance(data, list) else [data]
98
+ calls = [_to_call(x) for x in items if x is not None]
99
+ return before.strip(), calls, None if calls else "unreadable tool call"
100
+ if style == "llama3":
101
+ body = text.replace("<|python_tag|>", "", 1).strip()
102
+ data = _first_json(body) if body[:1] in "{[" else None
103
+ if isinstance(data, dict) and "name" in data:
104
+ return "", [_to_call(data)], None
105
+ except (ValueError, json.JSONDecodeError) as e:
106
+ return text, [], f"unreadable tool call: {e}"
107
+ return text, [], None
File without changes
@@ -0,0 +1,342 @@
1
+ """Checks: hard yes/no rules on an answer (F5), registered by type name.
2
+
3
+ A check returns ``passed=True/False``, or ``None`` when it needs the judge (``grounded``),
4
+ which is evaluated in the scoring step. Add a check by registering a class; the pipeline
5
+ does not change.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from abc import ABC, abstractmethod
13
+
14
+ import jsonschema
15
+ from pydantic import BaseModel, Field
16
+
17
+ from quantcheck.scoring import language
18
+ from quantcheck.scoring.models import CheckResult
19
+ from quantcheck.store import AnswerRecord
20
+ from quantcheck.tests_io import CheckSpec, SetHeader, TestCase, TestSet, ToolCall
21
+
22
+
23
+ class CheckContext(BaseModel):
24
+ """Everything a check may look at for one answer."""
25
+
26
+ case: TestCase
27
+ header: SetHeader
28
+ text: str # the answer a customer would read
29
+ tool_calls: list[ToolCall] = Field(default_factory=list) # first-turn tool calls
30
+
31
+
32
+ class Check(ABC):
33
+ """One check type. ``validate`` catches a bad spec before any model is loaded."""
34
+
35
+ type: str
36
+ needs_judge: bool = False
37
+
38
+ def validate(self, spec: CheckSpec, case: TestCase, header: SetHeader) -> str | None:
39
+ """Return a problem description, or None if the spec is usable."""
40
+ return None
41
+
42
+ @abstractmethod
43
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult: ...
44
+
45
+ def _r(self, passed: bool | None, detail: str = "") -> CheckResult:
46
+ return CheckResult(type=self.type, passed=passed, detail=detail)
47
+
48
+
49
+ CHECKS: dict[str, Check] = {}
50
+
51
+
52
+ def register_check(cls: type[Check]) -> type[Check]:
53
+ """Class decorator: register a check under its ``type`` name."""
54
+ CHECKS[cls.type] = cls()
55
+ return cls
56
+
57
+
58
+ _FENCE = re.compile(r"^```[a-zA-Z]*\s*\n(.*?)\n?```\s*$", re.S)
59
+
60
+
61
+ def parse_json_answer(text: str) -> object:
62
+ """Parse the answer as JSON. A single ```json fence is allowed; any other prose is not."""
63
+ s = text.strip()
64
+ if m := _FENCE.match(s):
65
+ s = m.group(1).strip()
66
+ return json.loads(s)
67
+
68
+
69
+ def _as_list(value: object) -> list[str]:
70
+ return [value] if isinstance(value, str) else list(value) if isinstance(value, list) else []
71
+
72
+
73
+ @register_check
74
+ class JsonCheck(Check):
75
+ """The answer is valid JSON, exactly as an app would parse it."""
76
+
77
+ type = "json"
78
+
79
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
80
+ try:
81
+ parse_json_answer(ctx.text)
82
+ except json.JSONDecodeError as e:
83
+ return self._r(False, f"not valid JSON ({e.msg})")
84
+ return self._r(True, "valid JSON")
85
+
86
+
87
+ @register_check
88
+ class JsonSchemaCheck(Check):
89
+ """Valid JSON that matches a JSON schema, e.g. ``{"required": ["name", "city"]}``."""
90
+
91
+ type = "json_schema"
92
+
93
+ def validate(self, spec: CheckSpec, case: TestCase, header: SetHeader) -> str | None:
94
+ if not isinstance(spec.value, dict):
95
+ return "json_schema needs a schema object as value"
96
+ try:
97
+ jsonschema.Draft202012Validator.check_schema(spec.value)
98
+ except jsonschema.SchemaError as e:
99
+ return f"invalid JSON schema: {e.message}"
100
+ return None
101
+
102
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
103
+ try:
104
+ data = parse_json_answer(ctx.text)
105
+ except json.JSONDecodeError as e:
106
+ return self._r(False, f"not valid JSON ({e.msg})")
107
+ err = jsonschema.Draft202012Validator(spec.value).iter_errors(data)
108
+ first = next(err, None)
109
+ if first:
110
+ where = ".".join(str(p) for p in first.absolute_path) or "answer"
111
+ return self._r(False, f"{where}: {first.message}")
112
+ return self._r(True, "matches the schema")
113
+
114
+
115
+ @register_check
116
+ class RegexCheck(Check):
117
+ """The answer matches a regular expression (search, multi-line)."""
118
+
119
+ type = "regex"
120
+
121
+ def validate(self, spec: CheckSpec, case: TestCase, header: SetHeader) -> str | None:
122
+ if not isinstance(spec.value, str):
123
+ return "regex needs a pattern string as value"
124
+ try:
125
+ re.compile(spec.value)
126
+ except re.error as e:
127
+ return f"invalid regex: {e}"
128
+ return None
129
+
130
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
131
+ ok = re.search(str(spec.value), ctx.text, re.M | re.S) is not None
132
+ return self._r(ok, "matched" if ok else f"no match for /{spec.value}/")
133
+
134
+
135
+ class _TextListCheck(Check):
136
+ def validate(self, spec: CheckSpec, case: TestCase, header: SetHeader) -> str | None:
137
+ if not _as_list(spec.value) or not all(
138
+ isinstance(v, str) and v for v in _as_list(spec.value)
139
+ ):
140
+ return f"{self.type} needs a string or a list of strings as value"
141
+ return None
142
+
143
+
144
+ @register_check
145
+ class ContainsCheck(_TextListCheck):
146
+ """Every given text appears in the answer (ignoring upper/lower case)."""
147
+
148
+ type = "contains"
149
+
150
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
151
+ low = ctx.text.lower()
152
+ missing = [v for v in _as_list(spec.value) if v.lower() not in low]
153
+ return self._r(not missing, "all found" if not missing else f"missing: {missing}")
154
+
155
+
156
+ @register_check
157
+ class NotContainsCheck(_TextListCheck):
158
+ """None of the given texts appears in the answer (ignoring upper/lower case)."""
159
+
160
+ type = "not_contains"
161
+
162
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
163
+ low = ctx.text.lower()
164
+ found = [v for v in _as_list(spec.value) if v.lower() in low]
165
+ return self._r(not found, "none found" if not found else f"found: {found}")
166
+
167
+
168
+ @register_check
169
+ class LanguageCheck(Check):
170
+ """The answer is in the given language (ISO code). See ``scoring/language.py``."""
171
+
172
+ type = "language"
173
+
174
+ def validate(self, spec: CheckSpec, case: TestCase, header: SetHeader) -> str | None:
175
+ if not isinstance(spec.value, str) or spec.value.lower() not in language.SUPPORTED:
176
+ return f"language '{spec.value}' is not supported yet. Supported: {language.SUPPORTED}"
177
+ return None
178
+
179
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
180
+ ok, why = language.check_language(ctx.text, str(spec.value))
181
+ return self._r(ok, why)
182
+
183
+
184
+ class _LengthCheck(Check):
185
+ def validate(self, spec: CheckSpec, case: TestCase, header: SetHeader) -> str | None:
186
+ v = spec.value
187
+ if isinstance(v, bool) or not isinstance(v, int) or v < 0:
188
+ return f"{self.type} needs a whole number (characters) as value"
189
+ return None
190
+
191
+
192
+ @register_check
193
+ class MinLengthCheck(_LengthCheck):
194
+ """The answer has at least N characters."""
195
+
196
+ type = "min_length"
197
+
198
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
199
+ n = len(ctx.text.strip())
200
+ return self._r(n >= spec.value, f"{n} characters (min {spec.value})")
201
+
202
+
203
+ @register_check
204
+ class MaxLengthCheck(_LengthCheck):
205
+ """The answer has at most N characters."""
206
+
207
+ type = "max_length"
208
+
209
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
210
+ n = len(ctx.text.strip())
211
+ return self._r(n <= spec.value, f"{n} characters (max {spec.value})")
212
+
213
+
214
+ def _same(expected: object, actual: object) -> bool:
215
+ if isinstance(expected, str) and isinstance(actual, str):
216
+ return expected.strip().casefold() == actual.strip().casefold()
217
+ return expected == actual
218
+
219
+
220
+ @register_check
221
+ class ToolCallCheck(Check):
222
+ """The model wrote the right tool call: name, schema-valid arguments, expected values.
223
+
224
+ The tool is never run; only the call the model wrote is read.
225
+ """
226
+
227
+ type = "tool_call"
228
+
229
+ def validate(self, spec: CheckSpec, case: TestCase, header: SetHeader) -> str | None:
230
+ if case.expected_tool_call is None:
231
+ return "tool_call needs expected_tool_call on the test case"
232
+ return None
233
+
234
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
235
+ want = ctx.case.expected_tool_call
236
+ if not ctx.tool_calls:
237
+ return self._r(False, f"no tool call written (expected '{want.name}')")
238
+ got = ctx.tool_calls[0]
239
+ if got.name != want.name:
240
+ return self._r(False, f"called '{got.name}', expected '{want.name}'")
241
+ tool = next((t for t in ctx.header.tools if t.name == got.name), None)
242
+ if tool is not None:
243
+ err = next(
244
+ jsonschema.Draft202012Validator(tool.parameters).iter_errors(got.arguments), None
245
+ )
246
+ if err:
247
+ return self._r(False, f"arguments break the tool schema: {err.message}")
248
+ for key, val in want.arguments.items():
249
+ if key not in got.arguments or not _same(val, got.arguments[key]):
250
+ return self._r(
251
+ False, f"argument {key}={got.arguments.get(key)!r}, expected {val!r}"
252
+ )
253
+ return self._r(True, f"called {got.name} with the expected arguments")
254
+
255
+
256
+ _REFUSALS = [
257
+ # English
258
+ "i don't know", "i do not know", "i'm not sure", "i am not sure", "i couldn't find",
259
+ "i could not find", "i can't find", "i cannot find", "no information", "don't have information",
260
+ "do not have information", "not mentioned", "not covered", "not available in", "unable to find",
261
+ "can't help with", "cannot help with", "isn't something", "i don't have",
262
+ "don't sell", "do not sell", "don't offer", "do not offer", "not able to help",
263
+ "can't provide", "cannot provide", "only help with", "doesn't mention", "do not mention",
264
+ "not provided",
265
+ # Hinglish
266
+ "pata nahi", "jankari nahi", "maloom nahi", "nahi dete", "nahi karte",
267
+ # Hindi
268
+ "मुझे नहीं पता", "मुझे नहीं मालूम", "जानकारी नहीं", "उपलब्ध नहीं", "नहीं देते", "नहीं देता",
269
+ "नहीं करते",
270
+ # Marathi
271
+ "माहित नाही", "माहिती नाही",
272
+ # Tamil
273
+ "தெரியாது", "தகவல் இல்லை", "தகவல் கிடைக்கவில்லை",
274
+ # Telugu
275
+ "తెలియదు", "సమాచారం లేదు",
276
+ # Bengali
277
+ "জানি না", "তথ্য নেই",
278
+ ] # fmt: skip
279
+
280
+
281
+ @register_check
282
+ class RefusalCheck(Check):
283
+ """The model says it doesn't know instead of inventing an answer.
284
+
285
+ A phrase check (English, Hinglish and the main Indian languages). It is a heuristic:
286
+ add your own phrases with ``value`` (a string or list). Judge-assisted version: later.
287
+ """
288
+
289
+ type = "refusal"
290
+
291
+ def validate(self, spec: CheckSpec, case: TestCase, header: SetHeader) -> str | None:
292
+ if spec.value is not None and not _as_list(spec.value):
293
+ return "refusal value must be a string or list of extra phrases"
294
+ return None
295
+
296
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
297
+ low = ctx.text.lower().replace("’", "'")
298
+ phrases = [p.lower() for p in [*_REFUSALS, *_as_list(spec.value)]]
299
+ hit = next((p for p in phrases if p in low), None)
300
+ return self._r(hit is not None, f"says: '{hit}'" if hit else "no 'I don't know' wording")
301
+
302
+
303
+ @register_check
304
+ class GroundedCheck(Check):
305
+ """No facts outside the provided documents. Judge-assisted, so decided in the scoring step."""
306
+
307
+ type = "grounded"
308
+ needs_judge = True
309
+
310
+ def run(self, ctx: CheckContext, spec: CheckSpec) -> CheckResult:
311
+ return self._r(None, "needs the judge")
312
+
313
+
314
+ def validate_checks(testset: TestSet) -> list[str]:
315
+ """Problems with any check in the test set (unknown type, bad value). Empty means fine."""
316
+ problems: list[str] = []
317
+ for case in testset.cases:
318
+ for spec in case.checks:
319
+ check = CHECKS.get(spec.type)
320
+ if check is None:
321
+ problems.append(f"{case.id}: unknown check '{spec.type}'. Known: {sorted(CHECKS)}")
322
+ elif msg := check.validate(spec, case, testset.header):
323
+ problems.append(f"{case.id}: {msg}")
324
+ return problems
325
+
326
+
327
+ def run_checks(case: TestCase, header: SetHeader, record: AnswerRecord) -> list[CheckResult]:
328
+ """Run every check on one answer. A crash inside a check counts as a failure, shown."""
329
+ ctx = CheckContext(
330
+ case=case,
331
+ header=header,
332
+ text=record.final_text,
333
+ tool_calls=record.generation.tool_calls,
334
+ )
335
+ results: list[CheckResult] = []
336
+ for spec in case.checks:
337
+ check = CHECKS[spec.type]
338
+ try:
339
+ results.append(check.run(ctx, spec))
340
+ except Exception as e:
341
+ results.append(CheckResult(type=spec.type, passed=False, detail=f"check crashed: {e}"))
342
+ return results
@@ -0,0 +1,50 @@
1
+ """FakeJudge: canned scores for unit tests. Never loads a model."""
2
+
3
+ from quantcheck.scoring.judge import Judge, register_judge
4
+ from quantcheck.scoring.models import GroundedResult, JudgeResult
5
+
6
+
7
+ class FakeJudge(Judge):
8
+ """Score by substring of the answer; ungrounded when the answer contains a flagged word."""
9
+
10
+ name = "fake"
11
+
12
+ def __init__(
13
+ self,
14
+ scores: dict[str, float] | None = None,
15
+ default: float = 10.0,
16
+ ungrounded: tuple[str, ...] = (),
17
+ fail: bool = False,
18
+ ) -> None:
19
+ self.scores = scores or {}
20
+ self.default = default
21
+ self.ungrounded = ungrounded
22
+ self.fail = fail
23
+ self.score_calls = 0
24
+ self.grounded_calls = 0
25
+ self.loaded = False
26
+
27
+ def load(self) -> None:
28
+ self.loaded = True
29
+
30
+ def unload(self) -> None:
31
+ self.loaded = False
32
+
33
+ def score(self, question: str, answer: str, reference: str, rubric: str) -> JudgeResult:
34
+ self.score_calls += 1
35
+ if self.fail:
36
+ return JudgeResult(error="judge down")
37
+ for key, val in self.scores.items():
38
+ if key in answer:
39
+ return JudgeResult(score=val, reason=f"matched '{key}'")
40
+ return JudgeResult(score=self.default, reason="default")
41
+
42
+ def grounded(self, documents: list[str], answer: str, question: str) -> GroundedResult:
43
+ self.grounded_calls += 1
44
+ if self.fail:
45
+ return GroundedResult(error="judge down")
46
+ bad = next((w for w in self.ungrounded if w in answer), None)
47
+ return GroundedResult(passed=bad is None, unsupported=bad or "")
48
+
49
+
50
+ register_judge("fake", lambda model: FakeJudge())
@@ -0,0 +1,171 @@
1
+ """Judges (F6): score an answer 0-10 against a reference, and decide ``grounded``.
2
+
3
+ A judge is registered by name. ``local`` runs a fixed MLX model on this Mac, so scores stay
4
+ comparable between runs and nothing leaves the machine. The judge model is loaded only after
5
+ all versions have finished, never next to a version being tested.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from abc import ABC, abstractmethod
13
+ from collections.abc import Callable
14
+ from pathlib import Path
15
+
16
+ from quantcheck.candidates import Candidate
17
+ from quantcheck.prompt import Prompt
18
+ from quantcheck.runners.base import GenSettings
19
+ from quantcheck.scoring.models import GroundedResult, JudgeResult
20
+
21
+ DEFAULT_RUBRIC = """\
22
+ Score from 0 to 10 how well the candidate answer matches the reference answer.
23
+ 10 = same meaning and facts as the reference.
24
+ 7-9 = right answer, small omissions or wording differences.
25
+ 4-6 = partly right, or an important detail is missing.
26
+ 1-3 = mostly wrong, or contradicts the reference.
27
+ 0 = wrong, empty, or unrelated.
28
+ Judge meaning, not wording. Do not reward length. Penalise facts that are not in the reference,
29
+ ignored instructions, and an answer in a different language from the question."""
30
+
31
+ _SCORE_SYSTEM = (
32
+ "You are a strict, fair grader of AI assistant answers. Reply with JSON only: "
33
+ '{"score": <number 0-10>, "reason": "<one short sentence>"}'
34
+ )
35
+ _GROUNDED_SYSTEM = (
36
+ "You check whether an answer uses only facts found in the provided documents. "
37
+ 'Reply with JSON only: {"grounded": true or false, "unsupported": "<the claim the '
38
+ 'documents do not support, or empty>"}'
39
+ )
40
+
41
+
42
+ def load_rubric(path: str | Path | None) -> str:
43
+ """The rubric text: the user's file, or the built-in default."""
44
+ if path is None:
45
+ return DEFAULT_RUBRIC
46
+ p = Path(path)
47
+ if not p.is_file():
48
+ raise FileNotFoundError(f"rubric file not found: {p}")
49
+ return p.read_text(encoding="utf-8").strip()
50
+
51
+
52
+ def parse_judge_json(text: str) -> dict | None:
53
+ """First JSON object in a judge reply (it may add prose or a code fence)."""
54
+ start = text.find("{")
55
+ while start != -1:
56
+ try:
57
+ obj, _ = json.JSONDecoder().raw_decode(text[start:])
58
+ except json.JSONDecodeError:
59
+ start = text.find("{", start + 1)
60
+ continue
61
+ if isinstance(obj, dict):
62
+ return obj
63
+ start = text.find("{", start + 1)
64
+ return None
65
+
66
+
67
+ def parse_score(text: str) -> JudgeResult:
68
+ """Turn a judge reply into a JudgeResult. Falls back to a ``score: N`` pattern."""
69
+ obj = parse_judge_json(text)
70
+ raw = obj.get("score") if obj else None
71
+ if raw is None and (m := re.search(r"score\W{0,4}(\d+(?:\.\d+)?)", text, re.I)):
72
+ raw = m.group(1)
73
+ try:
74
+ score = max(0.0, min(10.0, float(raw)))
75
+ except (TypeError, ValueError):
76
+ return JudgeResult(error=f"judge reply had no score: {text[:80]!r}")
77
+ return JudgeResult(score=score, reason=str((obj or {}).get("reason", ""))[:300])
78
+
79
+
80
+ def parse_grounded(text: str) -> GroundedResult:
81
+ """Turn a judge reply into a GroundedResult."""
82
+ obj = parse_judge_json(text)
83
+ flag = obj.get("grounded") if obj else None
84
+ if isinstance(flag, str):
85
+ flag = {"true": True, "false": False}.get(flag.strip().lower())
86
+ if not isinstance(flag, bool):
87
+ return GroundedResult(error=f"judge reply had no verdict: {text[:80]!r}")
88
+ return GroundedResult(passed=flag, unsupported=str((obj or {}).get("unsupported", ""))[:300])
89
+
90
+
91
+ class Judge(ABC):
92
+ """Scores answers. ``load``/``unload`` bracket a scoring pass."""
93
+
94
+ name: str
95
+ model: str | None = None
96
+
97
+ def load(self) -> None: # noqa: B027 (optional hook)
98
+ """Load the judge model, if it has one."""
99
+
100
+ def unload(self) -> None: # noqa: B027
101
+ """Free the judge model."""
102
+
103
+ @abstractmethod
104
+ def score(self, question: str, answer: str, reference: str, rubric: str) -> JudgeResult: ...
105
+
106
+ @abstractmethod
107
+ def grounded(self, documents: list[str], answer: str, question: str) -> GroundedResult: ...
108
+
109
+
110
+ class LocalJudge(Judge):
111
+ """A fixed MLX model on this Mac, run with temperature 0 and a fixed seed."""
112
+
113
+ name = "local"
114
+
115
+ def __init__(self, model: str) -> None:
116
+ from quantcheck.runners.mlx_runner import MLXRunner
117
+
118
+ self.model = model
119
+ self._runner = MLXRunner()
120
+ self._settings = GenSettings(temperature=0.0, seed=0, max_tokens=200)
121
+
122
+ def load(self) -> None:
123
+ self._runner.load(Candidate(model=self.model))
124
+
125
+ def unload(self) -> None:
126
+ self._runner.unload()
127
+
128
+ def _ask(self, system: str, user: str) -> str:
129
+ prompt = Prompt(
130
+ messages=[{"role": "system", "content": system}, {"role": "user", "content": user}]
131
+ )
132
+ gen = self._runner.generate(prompt, self._settings)
133
+ if gen.error:
134
+ raise RuntimeError(gen.error)
135
+ return gen.text
136
+
137
+ def score(self, question: str, answer: str, reference: str, rubric: str) -> JudgeResult:
138
+ user = (
139
+ f"Rubric:\n{rubric}\n\nQuestion given to the assistant:\n{question}\n\n"
140
+ f"Reference answer:\n{reference}\n\nCandidate answer:\n{answer}"
141
+ )
142
+ try:
143
+ return parse_score(self._ask(_SCORE_SYSTEM, user))
144
+ except Exception as e:
145
+ return JudgeResult(error=str(e))
146
+
147
+ def grounded(self, documents: list[str], answer: str, question: str) -> GroundedResult:
148
+ docs = "\n".join(f"[{i}] {d}" for i, d in enumerate(documents, 1)) or "(no documents)"
149
+ user = f"Documents:\n{docs}\n\nQuestion: {question}\n\nAnswer to check:\n{answer}"
150
+ try:
151
+ return parse_grounded(self._ask(_GROUNDED_SYSTEM, user))
152
+ except Exception as e:
153
+ return GroundedResult(error=str(e))
154
+
155
+
156
+ _JUDGES: dict[str, Callable[[str | None], Judge]] = {}
157
+
158
+
159
+ def register_judge(name: str, factory: Callable[[str | None], Judge]) -> None:
160
+ """Register a judge factory taking the configured judge model."""
161
+ _JUDGES[name] = factory
162
+
163
+
164
+ def get_judge(name: str, model: str | None = None) -> Judge:
165
+ """Create a judge by name; fail clearly if unknown or not built yet."""
166
+ if name not in _JUDGES:
167
+ raise KeyError(f"Judge '{name}' is not available yet. Available: {sorted(_JUDGES)}")
168
+ return _JUDGES[name](model)
169
+
170
+
171
+ register_judge("local", lambda model: LocalJudge(model or "mlx-community/Qwen3-8B-4bit"))