judgeproof 0.1.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.
- judgeproof/__init__.py +4 -0
- judgeproof/__main__.py +6 -0
- judgeproof/agreement.py +222 -0
- judgeproof/capture.py +265 -0
- judgeproof/cli.py +119 -0
- judgeproof/input_check.py +284 -0
- judgeproof/labels_needed.py +140 -0
- judgeproof/position_bias.py +121 -0
- judgeproof-0.1.0.dist-info/METADATA +224 -0
- judgeproof-0.1.0.dist-info/RECORD +13 -0
- judgeproof-0.1.0.dist-info/WHEEL +4 -0
- judgeproof-0.1.0.dist-info/entry_points.txt +2 -0
- judgeproof-0.1.0.dist-info/licenses/LICENSE +21 -0
judgeproof/__init__.py
ADDED
judgeproof/__main__.py
ADDED
judgeproof/agreement.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# MIT License. Copyright (c) 2026 Woq. See LICENSE.
|
|
2
|
+
"""Check your LLM judge against human labels.
|
|
3
|
+
|
|
4
|
+
Give it a CSV with one row per labeled example:
|
|
5
|
+
|
|
6
|
+
id,human,judge
|
|
7
|
+
t-001,pass,pass
|
|
8
|
+
t-002,fail,pass
|
|
9
|
+
...
|
|
10
|
+
|
|
11
|
+
Labels can be any strings (pass/fail, 1-5, good/bad/unsure). Rows that share
|
|
12
|
+
an id (for example two people labeled the same example) are kept together
|
|
13
|
+
when resampling. Add a column such as "category" and pass --group category
|
|
14
|
+
to get the same report per group.
|
|
15
|
+
|
|
16
|
+
It prints: n, raw agreement, Cohen's kappa with a 95% bootstrap CI, the
|
|
17
|
+
confusion matrix, precision and recall per label, and what a judge that always
|
|
18
|
+
gives the most common human label would score.
|
|
19
|
+
|
|
20
|
+
With --min-kappa or --min-recall it becomes a gate: it exits 1 when the
|
|
21
|
+
judge misses a threshold, so CI stops before the judge's scores are used.
|
|
22
|
+
Thresholds are checked on the "all rows" report.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import csv
|
|
27
|
+
import json
|
|
28
|
+
import sys
|
|
29
|
+
from collections import Counter
|
|
30
|
+
|
|
31
|
+
import numpy as np
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def kappa(cm):
|
|
35
|
+
"""Cohen's kappa from confusion matrices (rows: human, columns: judge).
|
|
36
|
+
Works on one matrix or a stack of them. NaN when undefined (both sides
|
|
37
|
+
used a single label)."""
|
|
38
|
+
cm = np.asarray(cm, dtype=float)
|
|
39
|
+
n = cm.sum(axis=(-2, -1))
|
|
40
|
+
p_obs = np.trace(cm, axis1=-2, axis2=-1) / n
|
|
41
|
+
p_chance = (cm.sum(axis=-1) * cm.sum(axis=-2)).sum(axis=-1) / n**2
|
|
42
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
43
|
+
k = (p_obs - p_chance) / (1 - p_chance)
|
|
44
|
+
return np.where(np.isclose(p_chance, 1), np.nan, k)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def agreement(cm):
|
|
48
|
+
return np.trace(cm, axis1=-2, axis2=-1) / cm.sum(axis=(-2, -1))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def report(rows, labels, reps=2000, seed=0):
|
|
52
|
+
"""rows: list of (id, human, judge). Returns a dict of metrics."""
|
|
53
|
+
ix = {lab: i for i, lab in enumerate(labels)}
|
|
54
|
+
k = len(labels)
|
|
55
|
+
ids = sorted({r[0] for r in rows})
|
|
56
|
+
pos = {i: n for n, i in enumerate(ids)}
|
|
57
|
+
# One small confusion matrix per id, so the bootstrap resamples ids.
|
|
58
|
+
tables = np.zeros((len(ids), k, k))
|
|
59
|
+
for i, h, j in rows:
|
|
60
|
+
tables[pos[i], ix[h], ix[j]] += 1
|
|
61
|
+
cm = tables.sum(axis=0)
|
|
62
|
+
n_ids = len(ids)
|
|
63
|
+
|
|
64
|
+
rng = np.random.default_rng(seed)
|
|
65
|
+
w = rng.multinomial(n_ids, np.full(n_ids, 1 / n_ids), size=reps)
|
|
66
|
+
boot = (w @ tables.reshape(n_ids, -1)).reshape(reps, k, k)
|
|
67
|
+
|
|
68
|
+
def ci(point, samples):
|
|
69
|
+
ok = samples[~np.isnan(samples)]
|
|
70
|
+
lo, hi = (np.percentile(ok, [2.5, 97.5]) if len(ok) else (np.nan, np.nan))
|
|
71
|
+
return {"value": float(point), "ci95": [float(lo), float(hi)]}
|
|
72
|
+
|
|
73
|
+
per_label = {}
|
|
74
|
+
for lab, i in ix.items():
|
|
75
|
+
col, row = cm[:, i].sum(), cm[i, :].sum()
|
|
76
|
+
per_label[lab] = {
|
|
77
|
+
"human_count": int(row), "judge_count": int(col),
|
|
78
|
+
"precision": float(cm[i, i] / col) if col else None,
|
|
79
|
+
"recall": float(cm[i, i] / row) if row else None,
|
|
80
|
+
}
|
|
81
|
+
top = int(np.argmax(cm.sum(axis=1)))
|
|
82
|
+
warnings = []
|
|
83
|
+
if len(rows) < 100:
|
|
84
|
+
warnings.append(f"only {len(rows)} labeled rows: expect a wide CI on kappa")
|
|
85
|
+
for lab, s in per_label.items():
|
|
86
|
+
if s["human_count"] and s["human_count"] < 10:
|
|
87
|
+
warnings.append(f"only {s['human_count']} human '{lab}' labels: its recall is very uncertain")
|
|
88
|
+
disagreements = int(cm.sum() - np.trace(cm))
|
|
89
|
+
if disagreements == 0:
|
|
90
|
+
warnings.append(
|
|
91
|
+
"no disagreements at all, so the bootstrap CI collapses to a point; "
|
|
92
|
+
f"the true disagreement rate could still be up to about {min(1, 3 / len(rows)):.0%} (rule of three)")
|
|
93
|
+
if np.isnan(kappa(cm)):
|
|
94
|
+
warnings.append("kappa is undefined: human and judge each used only one label")
|
|
95
|
+
return {
|
|
96
|
+
"n_rows": len(rows),
|
|
97
|
+
"n_ids": n_ids,
|
|
98
|
+
"labels": labels,
|
|
99
|
+
"agreement": ci(agreement(cm), agreement(boot)),
|
|
100
|
+
"kappa": ci(kappa(cm), kappa(boot)),
|
|
101
|
+
"confusion_rows_human_cols_judge": cm.astype(int).tolist(),
|
|
102
|
+
"per_label": per_label,
|
|
103
|
+
"always_majority_baseline": {
|
|
104
|
+
"label": labels[top],
|
|
105
|
+
"agreement": float(cm[top].sum() / cm.sum()),
|
|
106
|
+
"kappa": 0.0,
|
|
107
|
+
},
|
|
108
|
+
"warnings": warnings,
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def print_report(name, r):
|
|
113
|
+
print(f"\n== {name} ==")
|
|
114
|
+
print(f"rows: {r['n_rows']} (distinct ids: {r['n_ids']})")
|
|
115
|
+
a, k = r["agreement"], r["kappa"]
|
|
116
|
+
print(f"agreement: {a['value']:.1%} (95% CI {a['ci95'][0]:.1%} to {a['ci95'][1]:.1%})")
|
|
117
|
+
if np.isnan(k["value"]):
|
|
118
|
+
print("Cohen's kappa: undefined (see warnings)")
|
|
119
|
+
else:
|
|
120
|
+
print(f"Cohen's kappa: {k['value']:.3f} (95% CI {k['ci95'][0]:.3f} to {k['ci95'][1]:.3f})")
|
|
121
|
+
b = r["always_majority_baseline"]
|
|
122
|
+
print(f"a judge that always says '{b['label']}': agreement {b['agreement']:.1%}, kappa 0")
|
|
123
|
+
labels = r["labels"]
|
|
124
|
+
w = max(8, *(len(lab) for lab in labels)) + 2
|
|
125
|
+
print("\nconfusion matrix (rows: human, columns: judge)")
|
|
126
|
+
print(" " * w + "".join(f"{lab:>{w}}" for lab in labels))
|
|
127
|
+
for lab, row in zip(labels, r["confusion_rows_human_cols_judge"]):
|
|
128
|
+
print(f"{lab:>{w}}" + "".join(f"{c:>{w}}" for c in row))
|
|
129
|
+
print("\nper label: precision = when the judge says it, how often the human agrees;")
|
|
130
|
+
print(" recall = when the human says it, how often the judge agrees")
|
|
131
|
+
for lab, s in r["per_label"].items():
|
|
132
|
+
p = "n/a" if s["precision"] is None else f"{s['precision']:.1%}"
|
|
133
|
+
rc = "n/a" if s["recall"] is None else f"{s['recall']:.1%}"
|
|
134
|
+
print(f" {lab:>{w}} precision {p:>6} recall {rc:>6} (human {s['human_count']}, judge {s['judge_count']})")
|
|
135
|
+
for msg in r["warnings"]:
|
|
136
|
+
print(f"warning: {msg}")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class InputError(Exception):
|
|
140
|
+
pass
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def read_labels(path, group=None, human="human", judge="judge", id_col="id"):
|
|
144
|
+
"""Read (id, human, judge, group) rows. Rows with an empty label are skipped."""
|
|
145
|
+
with open(path, newline="", encoding="utf-8") as f:
|
|
146
|
+
reader = csv.DictReader(f)
|
|
147
|
+
need = {id_col, human, judge} | ({group} if group else set())
|
|
148
|
+
missing = need - set(reader.fieldnames or [])
|
|
149
|
+
if missing:
|
|
150
|
+
raise InputError(f"missing column(s): {', '.join(sorted(missing))}")
|
|
151
|
+
rows, skipped = [], 0
|
|
152
|
+
for r in reader:
|
|
153
|
+
h, j = (r[human] or "").strip(), (r[judge] or "").strip()
|
|
154
|
+
if not h or not j:
|
|
155
|
+
skipped += 1
|
|
156
|
+
continue
|
|
157
|
+
rows.append((r[id_col], h, j, r[group] if group else None))
|
|
158
|
+
if not rows:
|
|
159
|
+
raise InputError("no rows with both a human and a judge label")
|
|
160
|
+
return rows, skipped
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def label_order(rows):
|
|
164
|
+
counts = Counter(lab for r in rows for lab in r[1:3])
|
|
165
|
+
return sorted(counts, key=lambda lab: (-counts[lab], lab))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def gate(r, min_kappa=None, min_recall=None):
|
|
169
|
+
"""Threshold failures for one report, as readable strings."""
|
|
170
|
+
failures = []
|
|
171
|
+
if min_kappa is not None:
|
|
172
|
+
lo = r["kappa"]["ci95"][0]
|
|
173
|
+
if np.isnan(r["kappa"]["value"]) or np.isnan(lo) or lo < min_kappa:
|
|
174
|
+
shown = "undefined" if np.isnan(lo) else f"{lo:.3f}"
|
|
175
|
+
failures.append(f"kappa CI lower bound {shown} is below --min-kappa {min_kappa}")
|
|
176
|
+
for spec in min_recall or []:
|
|
177
|
+
label, _, value = spec.rpartition("=")
|
|
178
|
+
if not label:
|
|
179
|
+
raise InputError(f"--min-recall expects LABEL=VALUE, got {spec!r}")
|
|
180
|
+
s = r["per_label"].get(label)
|
|
181
|
+
if s is None:
|
|
182
|
+
raise InputError(f"--min-recall: label {label!r} not in the data (labels: {', '.join(r['labels'])})")
|
|
183
|
+
if s["recall"] is None or s["recall"] < float(value):
|
|
184
|
+
got = "n/a" if s["recall"] is None else f"{s['recall']:.1%}"
|
|
185
|
+
failures.append(f"recall on '{label}' is {got}, below --min-recall {float(value):.1%}")
|
|
186
|
+
return failures
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def run(args) -> int:
|
|
190
|
+
try:
|
|
191
|
+
rows, skipped = read_labels(args.csv, args.group, args.human_col, args.judge_col, args.id_col)
|
|
192
|
+
except (OSError, InputError) as exc:
|
|
193
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
194
|
+
return 2
|
|
195
|
+
if skipped:
|
|
196
|
+
print(f"skipped {skipped} row(s) with an empty human or judge label")
|
|
197
|
+
labels = label_order(rows)
|
|
198
|
+
out = {"all": report([r[:3] for r in rows], labels, args.reps, args.seed)}
|
|
199
|
+
print_report("all rows", out["all"])
|
|
200
|
+
if args.group:
|
|
201
|
+
for g in sorted({r[3] for r in rows}):
|
|
202
|
+
sub = [r[:3] for r in rows if r[3] == g]
|
|
203
|
+
out[g] = report(sub, labels, args.reps, args.seed)
|
|
204
|
+
print_report(f"{args.group} = {g}", out[g])
|
|
205
|
+
try:
|
|
206
|
+
failures = gate(out["all"], args.min_kappa, args.min_recall)
|
|
207
|
+
except InputError as exc:
|
|
208
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
209
|
+
return 2
|
|
210
|
+
if args.json:
|
|
211
|
+
with open(args.json, "w", encoding="utf-8") as f:
|
|
212
|
+
json.dump(dict(out, gate={"failures": failures}), f, indent=2)
|
|
213
|
+
print(f"\nwrote {args.json}")
|
|
214
|
+
if args.min_kappa is not None or args.min_recall:
|
|
215
|
+
print("\ngate:")
|
|
216
|
+
for msg in failures:
|
|
217
|
+
print(f" [FAIL] {msg}")
|
|
218
|
+
if failures:
|
|
219
|
+
print(f" BLOCK: {len(failures)} threshold(s) missed; exit 1")
|
|
220
|
+
return 1
|
|
221
|
+
print(" OK: all thresholds met")
|
|
222
|
+
return 0
|
judgeproof/capture.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
# MIT License. Copyright (c) 2026 Woq. See LICENSE.
|
|
2
|
+
"""judgeproof capture: a fake LLM judge that records every request.
|
|
3
|
+
|
|
4
|
+
A tiny OpenAI-compatible server for dry runs. No model runs. Point your eval
|
|
5
|
+
tool's judge base URL at it; it saves the exact bytes each judge call sends,
|
|
6
|
+
then returns a fixed "pass" verdict shaped so the tool can parse it:
|
|
7
|
+
|
|
8
|
+
* if the request asks for a JSON schema, it returns the smallest object that
|
|
9
|
+
fits the schema (booleans true, numbers 1, enums their first value);
|
|
10
|
+
* if the request forces a function call, it returns that call with arguments
|
|
11
|
+
built the same way;
|
|
12
|
+
* otherwise it returns plain text that the common grader formats accept.
|
|
13
|
+
|
|
14
|
+
The verdicts mean nothing; only the captured inputs matter. Feed the captured
|
|
15
|
+
*.request.json files to `judgeproof input check --packet`.
|
|
16
|
+
|
|
17
|
+
Put a label in the URL to sort captures by tool and test case, e.g. a tool
|
|
18
|
+
pointed at http://127.0.0.1:8765/deepeval-trace/v1 saves its requests under
|
|
19
|
+
captures/deepeval-trace/. Standard library only.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import itertools
|
|
24
|
+
import json
|
|
25
|
+
import pathlib
|
|
26
|
+
import threading
|
|
27
|
+
import time
|
|
28
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
29
|
+
|
|
30
|
+
FIXED_TEXT = (
|
|
31
|
+
"The response is correct and complete.\n"
|
|
32
|
+
"GRADE: C\n"
|
|
33
|
+
'{"pass": true, "score": 1, "reason": "fake judge: fixed verdict", "verdict": "yes"}'
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
_counter = itertools.count(1)
|
|
37
|
+
_lock = threading.Lock()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def instance_from_schema(schema, defs=None, depth=0):
|
|
41
|
+
"""Smallest value that validates against a JSON schema (enough for graders)."""
|
|
42
|
+
if depth > 20:
|
|
43
|
+
return None
|
|
44
|
+
if defs is None:
|
|
45
|
+
defs = dict(schema.get("$defs", {}), **schema.get("definitions", {}))
|
|
46
|
+
if "$ref" in schema:
|
|
47
|
+
name = schema["$ref"].split("/")[-1]
|
|
48
|
+
return instance_from_schema(defs.get(name, {}), defs, depth + 1)
|
|
49
|
+
if "const" in schema:
|
|
50
|
+
return schema["const"]
|
|
51
|
+
if "enum" in schema:
|
|
52
|
+
return schema["enum"][0]
|
|
53
|
+
for key in ("anyOf", "oneOf"):
|
|
54
|
+
if key in schema:
|
|
55
|
+
options = [s for s in schema[key] if s.get("type") != "null"] or schema[key]
|
|
56
|
+
return instance_from_schema(options[0], defs, depth + 1)
|
|
57
|
+
if "allOf" in schema:
|
|
58
|
+
merged = {}
|
|
59
|
+
for part in schema["allOf"]:
|
|
60
|
+
value = instance_from_schema(part, defs, depth + 1)
|
|
61
|
+
if isinstance(value, dict):
|
|
62
|
+
merged.update(value)
|
|
63
|
+
return merged
|
|
64
|
+
kind = schema.get("type")
|
|
65
|
+
if isinstance(kind, list):
|
|
66
|
+
kind = next((k for k in kind if k != "null"), "string")
|
|
67
|
+
if kind == "object" or "properties" in schema:
|
|
68
|
+
return {k: instance_from_schema(v, defs, depth + 1) for k, v in schema.get("properties", {}).items()}
|
|
69
|
+
if kind == "array":
|
|
70
|
+
items = schema.get("items", {"type": "string"})
|
|
71
|
+
return [instance_from_schema(items, defs, depth + 1) for _ in range(max(1, schema.get("minItems", 1)))]
|
|
72
|
+
if kind == "boolean":
|
|
73
|
+
return True
|
|
74
|
+
if kind == "integer":
|
|
75
|
+
return max(1, schema.get("minimum", 1))
|
|
76
|
+
if kind == "number":
|
|
77
|
+
return float(min(1, schema.get("maximum", 1)))
|
|
78
|
+
return "fake judge: fixed verdict"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def response_schema(body):
|
|
82
|
+
"""The JSON schema a request asks for, if any (chat completions or responses API)."""
|
|
83
|
+
fmt = body.get("response_format") or (body.get("text") or {}).get("format")
|
|
84
|
+
if isinstance(fmt, dict) and fmt.get("type") == "json_schema":
|
|
85
|
+
inner = fmt.get("json_schema", fmt)
|
|
86
|
+
return inner.get("schema")
|
|
87
|
+
if isinstance(fmt, dict) and fmt.get("type") == "json_object":
|
|
88
|
+
return {"type": "object", "properties": {
|
|
89
|
+
"pass": {"type": "boolean"}, "score": {"type": "number"},
|
|
90
|
+
"reason": {"type": "string"}, "verdict": {"type": "string"}}}
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def forced_function(body):
|
|
95
|
+
"""The function the judge should "call", if the request offers any.
|
|
96
|
+
|
|
97
|
+
Graders only offer functions as a way to get structured verdicts, so the
|
|
98
|
+
fake judge calls the named function, or the first one offered.
|
|
99
|
+
"""
|
|
100
|
+
tools = body.get("tools") or []
|
|
101
|
+
choice = body.get("tool_choice")
|
|
102
|
+
if not tools or choice == "none":
|
|
103
|
+
return None
|
|
104
|
+
name = None
|
|
105
|
+
if isinstance(choice, dict):
|
|
106
|
+
name = (choice.get("function") or {}).get("name") or choice.get("name")
|
|
107
|
+
for tool in tools:
|
|
108
|
+
fn = tool.get("function", tool)
|
|
109
|
+
if name is None or fn.get("name") == name:
|
|
110
|
+
return fn
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def prompt_text(body):
|
|
115
|
+
"""Readable text of everything the judge was shown, in order."""
|
|
116
|
+
parts = []
|
|
117
|
+
if "messages" in body:
|
|
118
|
+
for m in body["messages"]:
|
|
119
|
+
content = m.get("content")
|
|
120
|
+
if isinstance(content, list):
|
|
121
|
+
content = "\n".join(c.get("text", "") if isinstance(c, dict) else str(c) for c in content)
|
|
122
|
+
parts.append(f"--- [{m.get('role')}] ---\n{content if content is not None else ''}")
|
|
123
|
+
if m.get("tool_calls"):
|
|
124
|
+
parts.append(json.dumps(m["tool_calls"], indent=2, ensure_ascii=False))
|
|
125
|
+
if "input" in body:
|
|
126
|
+
items = body["input"] if isinstance(body["input"], list) else [{"role": "user", "content": body["input"]}]
|
|
127
|
+
if body.get("instructions"):
|
|
128
|
+
parts.append(f"--- [instructions] ---\n{body['instructions']}")
|
|
129
|
+
for m in items:
|
|
130
|
+
content = m.get("content")
|
|
131
|
+
if isinstance(content, list):
|
|
132
|
+
content = "\n".join(c.get("text", "") if isinstance(c, dict) else str(c) for c in content)
|
|
133
|
+
parts.append(f"--- [{m.get('role', m.get('type'))}] ---\n{content if content is not None else ''}")
|
|
134
|
+
if "prompt" in body:
|
|
135
|
+
parts.append(f"--- [prompt] ---\n{body['prompt']}")
|
|
136
|
+
return "\n\n".join(parts) + "\n"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class Handler(BaseHTTPRequestHandler):
|
|
140
|
+
out_dir: pathlib.Path = pathlib.Path("captures")
|
|
141
|
+
|
|
142
|
+
def log_message(self, fmt, *args): # quiet
|
|
143
|
+
return
|
|
144
|
+
|
|
145
|
+
def _send(self, payload, status=200):
|
|
146
|
+
data = json.dumps(payload).encode()
|
|
147
|
+
self.send_response(status)
|
|
148
|
+
self.send_header("Content-Type", "application/json")
|
|
149
|
+
self.send_header("Content-Length", str(len(data)))
|
|
150
|
+
self.end_headers()
|
|
151
|
+
self.wfile.write(data)
|
|
152
|
+
|
|
153
|
+
def _label_and_route(self):
|
|
154
|
+
parts = [p for p in self.path.split("?")[0].split("/") if p]
|
|
155
|
+
if "v1" in parts:
|
|
156
|
+
i = parts.index("v1")
|
|
157
|
+
label = "-".join(parts[:i]) or "unlabelled"
|
|
158
|
+
route = "/".join(parts[i + 1:])
|
|
159
|
+
else:
|
|
160
|
+
label, route = "unlabelled", "/".join(parts)
|
|
161
|
+
return label, route
|
|
162
|
+
|
|
163
|
+
def do_GET(self):
|
|
164
|
+
label, route = self._label_and_route()
|
|
165
|
+
if route == "models":
|
|
166
|
+
return self._send({"object": "list", "data": [{"id": "fake-judge", "object": "model", "owned_by": "local"}]})
|
|
167
|
+
self._send({"ok": True, "label": label})
|
|
168
|
+
|
|
169
|
+
def do_POST(self):
|
|
170
|
+
label, route = self._label_and_route()
|
|
171
|
+
raw = self.rfile.read(int(self.headers.get("Content-Length", 0) or 0))
|
|
172
|
+
try:
|
|
173
|
+
body = json.loads(raw or b"{}")
|
|
174
|
+
except json.JSONDecodeError:
|
|
175
|
+
body = {}
|
|
176
|
+
with _lock:
|
|
177
|
+
seq = next(_counter)
|
|
178
|
+
folder = self.out_dir / label
|
|
179
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
180
|
+
stem = f"{seq:04d}-{route.replace('/', '_') or 'root'}"
|
|
181
|
+
(folder / f"{stem}.request.json").write_bytes(raw)
|
|
182
|
+
(folder / f"{stem}.prompt.txt").write_text(prompt_text(body), encoding="utf-8")
|
|
183
|
+
meta = {
|
|
184
|
+
"seq": seq, "label": label, "route": route, "time": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
|
185
|
+
"user_agent": self.headers.get("User-Agent"), "bytes": len(raw), "model": body.get("model"),
|
|
186
|
+
"stream": bool(body.get("stream")),
|
|
187
|
+
}
|
|
188
|
+
(folder / f"{stem}.meta.json").write_text(json.dumps(meta, indent=2))
|
|
189
|
+
|
|
190
|
+
schema = response_schema(body)
|
|
191
|
+
fn = forced_function(body)
|
|
192
|
+
tool_call = None
|
|
193
|
+
if fn is not None:
|
|
194
|
+
args = instance_from_schema(fn.get("parameters", {"type": "object"}))
|
|
195
|
+
tool_call = {"id": f"call_fake_{seq}", "type": "function",
|
|
196
|
+
"function": {"name": fn.get("name"), "arguments": json.dumps(args)}}
|
|
197
|
+
text = None
|
|
198
|
+
elif schema is not None:
|
|
199
|
+
text = json.dumps(instance_from_schema(schema))
|
|
200
|
+
else:
|
|
201
|
+
text = FIXED_TEXT
|
|
202
|
+
|
|
203
|
+
model = body.get("model", "fake-judge")
|
|
204
|
+
if route.endswith("responses"):
|
|
205
|
+
output = []
|
|
206
|
+
if tool_call:
|
|
207
|
+
output.append({"type": "function_call", "id": f"fc_{seq}", "call_id": tool_call["id"],
|
|
208
|
+
"name": tool_call["function"]["name"], "arguments": tool_call["function"]["arguments"],
|
|
209
|
+
"status": "completed"})
|
|
210
|
+
else:
|
|
211
|
+
output.append({"type": "message", "id": f"msg_{seq}", "role": "assistant", "status": "completed",
|
|
212
|
+
"content": [{"type": "output_text", "text": text, "annotations": []}]})
|
|
213
|
+
return self._send({"id": f"resp_{seq}", "object": "response", "created_at": int(time.time()),
|
|
214
|
+
"status": "completed", "model": model, "output": output,
|
|
215
|
+
"usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}})
|
|
216
|
+
|
|
217
|
+
if route.endswith("completions") and "messages" not in body: # legacy completions
|
|
218
|
+
return self._send({"id": f"cmpl_{seq}", "object": "text_completion", "created": int(time.time()),
|
|
219
|
+
"model": model, "choices": [{"index": 0, "text": text or "", "finish_reason": "stop",
|
|
220
|
+
"logprobs": None}],
|
|
221
|
+
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}})
|
|
222
|
+
|
|
223
|
+
message = {"role": "assistant", "content": text}
|
|
224
|
+
if tool_call:
|
|
225
|
+
message["tool_calls"] = [tool_call]
|
|
226
|
+
finish = "tool_calls" if tool_call else "stop"
|
|
227
|
+
if body.get("stream"):
|
|
228
|
+
delta = dict(message)
|
|
229
|
+
if tool_call:
|
|
230
|
+
delta["tool_calls"] = [dict(tool_call, index=0)]
|
|
231
|
+
chunks = [
|
|
232
|
+
{"id": f"chatcmpl_{seq}", "object": "chat.completion.chunk", "created": int(time.time()), "model": model,
|
|
233
|
+
"choices": [{"index": 0, "delta": delta, "finish_reason": None}]},
|
|
234
|
+
{"id": f"chatcmpl_{seq}", "object": "chat.completion.chunk", "created": int(time.time()), "model": model,
|
|
235
|
+
"choices": [{"index": 0, "delta": {}, "finish_reason": finish}],
|
|
236
|
+
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}},
|
|
237
|
+
]
|
|
238
|
+
data = "".join(f"data: {json.dumps(c)}\n\n" for c in chunks) + "data: [DONE]\n\n"
|
|
239
|
+
self.send_response(200)
|
|
240
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
241
|
+
self.send_header("Content-Length", str(len(data.encode())))
|
|
242
|
+
self.end_headers()
|
|
243
|
+
self.wfile.write(data.encode())
|
|
244
|
+
return
|
|
245
|
+
self._send({"id": f"chatcmpl_{seq}", "object": "chat.completion", "created": int(time.time()), "model": model,
|
|
246
|
+
"choices": [{"index": 0, "message": message, "finish_reason": finish, "logprobs": None}],
|
|
247
|
+
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}})
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def serve(port: int = 8765, out: str = "captures", host: str = "127.0.0.1") -> None:
|
|
251
|
+
Handler.out_dir = pathlib.Path(out)
|
|
252
|
+
Handler.out_dir.mkdir(parents=True, exist_ok=True)
|
|
253
|
+
server = ThreadingHTTPServer((host, port), Handler)
|
|
254
|
+
print(f"fake judge listening on http://{host}:{port}/<label>/v1 (captures -> {Handler.out_dir})", flush=True)
|
|
255
|
+
try:
|
|
256
|
+
server.serve_forever()
|
|
257
|
+
except KeyboardInterrupt:
|
|
258
|
+
pass
|
|
259
|
+
finally:
|
|
260
|
+
server.server_close()
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def run(args) -> int:
|
|
264
|
+
serve(args.port, args.out, args.host)
|
|
265
|
+
return 0
|
judgeproof/cli.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# MIT License. Copyright (c) 2026 Woq. See LICENSE.
|
|
2
|
+
"""judgeproof: checks for your LLM-as-a-judge evals.
|
|
3
|
+
|
|
4
|
+
Commands
|
|
5
|
+
agreement does the judge agree with your human labels? (kappa with a CI)
|
|
6
|
+
labels-needed how many human labels before that CI is narrow enough?
|
|
7
|
+
input check did the judge see the tool calls, results and reply it grades?
|
|
8
|
+
input verify is the judge reading the same bytes that were checked?
|
|
9
|
+
position-bias does a pairwise judge change its mind when answers swap places?
|
|
10
|
+
capture a fake, recording judge for dry runs (feeds `input check`)
|
|
11
|
+
|
|
12
|
+
Every check exits 0 when it passes, 1 when it fails and 2 on bad input, so
|
|
13
|
+
any of them can gate a CI pipeline. Run `judgeproof <command> -h` for details.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import sys
|
|
19
|
+
|
|
20
|
+
from . import __version__
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _first_line(doc: str) -> str:
|
|
24
|
+
return doc.strip().splitlines()[0]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _label_cols(p):
|
|
28
|
+
p.add_argument("--id-col", default="id", help="id column (default: id)")
|
|
29
|
+
p.add_argument("--human-col", default="human", help="human label column (default: human)")
|
|
30
|
+
p.add_argument("--judge-col", default="judge", help="judge label column (default: judge)")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
34
|
+
from . import agreement, capture, input_check, labels_needed, position_bias
|
|
35
|
+
|
|
36
|
+
raw = argparse.RawDescriptionHelpFormatter
|
|
37
|
+
parser = argparse.ArgumentParser(prog="judgeproof", description=__doc__, formatter_class=raw)
|
|
38
|
+
parser.add_argument("--version", action="version", version=f"judgeproof {__version__}")
|
|
39
|
+
sub = parser.add_subparsers(dest="command", required=True, metavar="command")
|
|
40
|
+
|
|
41
|
+
p = sub.add_parser("agreement", help=_first_line(agreement.__doc__), description=agreement.__doc__,
|
|
42
|
+
formatter_class=raw)
|
|
43
|
+
p.add_argument("csv", help="CSV with columns id, human, judge (plus any group column)")
|
|
44
|
+
p.add_argument("--group", help="optional column to break the report down by")
|
|
45
|
+
_label_cols(p)
|
|
46
|
+
p.add_argument("--reps", type=int, default=2000, help="bootstrap resamples (default 2000)")
|
|
47
|
+
p.add_argument("--seed", type=int, default=0)
|
|
48
|
+
p.add_argument("--json", help="also write the full report to this JSON file")
|
|
49
|
+
p.add_argument("--min-kappa", type=float, metavar="K",
|
|
50
|
+
help="fail (exit 1) if the lower end of kappa's 95%% CI is below K")
|
|
51
|
+
p.add_argument("--min-recall", action="append", metavar="LABEL=R",
|
|
52
|
+
help="fail if the judge's recall on LABEL is below R, e.g. fail=0.8 (repeatable)")
|
|
53
|
+
p.set_defaults(func=agreement.run)
|
|
54
|
+
|
|
55
|
+
p = sub.add_parser("labels-needed", help=_first_line(labels_needed.__doc__), description=labels_needed.__doc__,
|
|
56
|
+
formatter_class=raw)
|
|
57
|
+
p.add_argument("--pilot", metavar="CSV", help="labels you already have (columns id, human, judge)")
|
|
58
|
+
_label_cols(p)
|
|
59
|
+
p.add_argument("--kappa", type=float, help="expected kappa, if you have no pilot labels")
|
|
60
|
+
p.add_argument("--minority", type=float, help="share of the rarer label among human labels, e.g. 0.15")
|
|
61
|
+
p.add_argument("--judge-minority", type=float, help="share of the rarer label among judge labels "
|
|
62
|
+
"(default: same as --minority)")
|
|
63
|
+
p.add_argument("--width", type=float, default=0.2, help="target width of kappa's 95%% CI (default 0.2)")
|
|
64
|
+
p.add_argument("--n", type=int, action="append", help="label counts to simulate (repeatable; default "
|
|
65
|
+
"25 50 100 200 400 800 1600)")
|
|
66
|
+
p.add_argument("--sims", type=int, default=200, help="simulated label sets per count (default 200)")
|
|
67
|
+
p.add_argument("--reps", type=int, default=1000, help="bootstrap resamples per set (default 1000)")
|
|
68
|
+
p.add_argument("--seed", type=int, default=0)
|
|
69
|
+
p.add_argument("--json", help="also write the result to this JSON file")
|
|
70
|
+
p.set_defaults(func=labels_needed.run)
|
|
71
|
+
|
|
72
|
+
p = sub.add_parser("input", help="did the judge see what it grades? (check, verify)",
|
|
73
|
+
description=input_check.__doc__, formatter_class=raw)
|
|
74
|
+
isub = p.add_subparsers(dest="input_command", required=True, metavar="check|verify")
|
|
75
|
+
c = isub.add_parser("check", help="obligations 1-3 (and record hashes for 4)")
|
|
76
|
+
c.add_argument("--run", required=True, help="agent run: OpenAI-style messages JSON")
|
|
77
|
+
c.add_argument("--packet", required=True, action="append", help="what the judge received (repeatable)")
|
|
78
|
+
c.add_argument("--require", help=f"comma-separated parts to require (default: all of "
|
|
79
|
+
f"{','.join(input_check.PARTS)})")
|
|
80
|
+
c.add_argument("--min-result-coverage", type=float, default=1.0,
|
|
81
|
+
help="share of each tool result that must reach the judge (default 1.0 = all of it)")
|
|
82
|
+
c.add_argument("--spec", help="JSON spec of judging criteria and the run parts each needs")
|
|
83
|
+
c.add_argument("--manifest", help="write SHA-256 of each checked packet here, for `verify`")
|
|
84
|
+
c.set_defaults(func=input_check.cmd_check)
|
|
85
|
+
v = isub.add_parser("verify", help="obligation 4: compare sent packets with the checked ones")
|
|
86
|
+
v.add_argument("--manifest", required=True)
|
|
87
|
+
v.add_argument("--packet", required=True, action="append")
|
|
88
|
+
v.set_defaults(func=input_check.cmd_verify)
|
|
89
|
+
|
|
90
|
+
p = sub.add_parser("position-bias", help=_first_line(position_bias.__doc__), description=position_bias.__doc__,
|
|
91
|
+
formatter_class=raw)
|
|
92
|
+
p.add_argument("csv", help="CSV with columns id, verdict_ab, verdict_ba")
|
|
93
|
+
p.add_argument("--id-col", default="id")
|
|
94
|
+
p.add_argument("--ab-col", default="verdict_ab", help="verdict with A shown first (default: verdict_ab)")
|
|
95
|
+
p.add_argument("--ba-col", default="verdict_ba", help="verdict with B shown first (default: verdict_ba)")
|
|
96
|
+
p.add_argument("--a-label", default="A", help="label meaning answer A won (default: A)")
|
|
97
|
+
p.add_argument("--b-label", default="B", help="label meaning answer B won (default: B)")
|
|
98
|
+
p.add_argument("--reps", type=int, default=2000)
|
|
99
|
+
p.add_argument("--seed", type=int, default=0)
|
|
100
|
+
p.add_argument("--json", help="also write the result to this JSON file")
|
|
101
|
+
p.add_argument("--max-flip-rate", type=float, metavar="R", help="fail (exit 1) if the flip rate is above R")
|
|
102
|
+
p.set_defaults(func=position_bias.run)
|
|
103
|
+
|
|
104
|
+
p = sub.add_parser("capture", help="a fake, recording judge for dry runs", description=capture.__doc__,
|
|
105
|
+
formatter_class=raw)
|
|
106
|
+
p.add_argument("--port", type=int, default=8765)
|
|
107
|
+
p.add_argument("--host", default="127.0.0.1")
|
|
108
|
+
p.add_argument("--out", default="captures", help="folder for captured requests (default: ./captures)")
|
|
109
|
+
p.set_defaults(func=capture.run)
|
|
110
|
+
return parser
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def main(argv=None) -> int:
|
|
114
|
+
args = build_parser().parse_args(argv)
|
|
115
|
+
return args.func(args)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
if __name__ == "__main__":
|
|
119
|
+
sys.exit(main())
|