From fa795fcd4bc7dcb74a0243107133902cb5b42999 Mon Sep 17 00:00:00 2001 From: PsychoSid <75582188+kryptek2000@users.noreply.github.com> Date: Tue, 29 Sep 2026 12:54:59 -0400 Subject: [PATCH] feat: opt-in LLM judge for nuanced cases (v1.6) - writeprint/judge.py: stdlib-only OpenAI-compatible client, structured advisory verdicts, graceful degradation to uncertain - cli judge with env/flag config; clean exit-2 when unconfigured - 14 new tests incl. stub-server roundtrips (43 passing); README docs --- README.md | 26 ++++++- tests/test_judge.py | 184 ++++++++++++++++++++++++++++++++++++++++++++ tests/test_web.py | 1 + writeprint/cli.py | 31 ++++++++ writeprint/judge.py | 158 +++++++++++++++++++++++++++++++++++++ 5 files changed, 399 insertions(+), 1 deletion(-) create mode 100644 tests/test_judge.py create mode 100644 writeprint/judge.py diff --git a/README.md b/README.md index afafba1..8b1b6bf 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,30 @@ python -m writeprint.cli batch baselines/student_a.json \ One row per submission — student, file, score, band, flag count, top divergent habits — ready for gradebook-adjacent workflows. +## LLM judge (opt-in second opinion, v1.6) + +For the nuanced middle (`mild divergence`), an optional LLM pass can +weigh the habits in prose. Offline-first: it does nothing unless you +configure it. + +```bash +export WRITEPRINT_JUDGE_URL=https://your-endpoint/v1/chat/completions +export WRITEPRINT_JUDGE_MODEL=your-model +export WRITEPRINT_JUDGE_KEY=... # omit for local servers like Ollama +python -m writeprint.cli judge baselines/student_a.json submission.txt +``` + +Any OpenAI-compatible endpoint works, including a fully local Ollama +server. Three rules, enforced by design: + +1. **It can only advise.** Output is consistency + confidence + reasons, + always labeled advisory; unparseable replies degrade to `uncertain`, + never to a false verdict. +2. **Student text leaves the machine only if you say so.** No endpoint, + no call. Prefer local models; get consent otherwise. +3. **Statistics + teacher outrank it.** The last line of every + assessment says so. + ## Validation: baselines are student-specific The bundled two-student corpus proves the point of the tool. Scored @@ -204,5 +228,5 @@ Two warnings, both serious: - [x] Two-student validation corpus + CSV batch export (`writeprint batch`, v1.3) - [x] Real-prose validation: Gutenberg corpus, honest negative result (v1.4) - [x] Real student writing: ASAP false-flag study, published rates (v1.5) +- [x] Opt-in LLM judge for nuanced cases, offline by default (v1.6) - [ ] Classroom pilot: multi-sample baselines from live student work -- [ ] Optional LLM judge for nuanced cases (v1 is fully offline by design) diff --git a/tests/test_judge.py b/tests/test_judge.py new file mode 100644 index 0000000..5c3f52c --- /dev/null +++ b/tests/test_judge.py @@ -0,0 +1,184 @@ +"""Tests for the opt-in LLM judge (no real API calls).""" + +import json +import os +import sys +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) + +from writeprint.compare import build_baseline +from writeprint.features import extract +from writeprint.judge import (JudgeError, build_prompt, call_judge, + judge_config, parse_response) + +SAMPLES = os.path.join(os.path.dirname(__file__), "..", "samples") + + +def read(name): + with open(os.path.join(SAMPLES, name), encoding="utf-8") as fh: + return fh.read() + + +def sample_baseline(): + texts = [read("student_a_baseline%d.txt" % i) for i in (1, 2, 3)] + profile = build_baseline([extract(t) for t in texts]) + profile["student"] = "student_a" + return profile + + +class TestPrompt(unittest.TestCase): + def test_prompt_contains_habits_and_submission(self): + system, user = build_prompt( + sample_baseline(), "Some new text here.", "student_a") + self.assertIn("JSON", system) + self.assertIn("advisory", system) + self.assertIn("avg_sentence_len", user) + self.assertIn("Some new text here.", user) + self.assertIn("student_a", user) + + def test_long_submission_truncated(self): + _, user = build_prompt(sample_baseline(), "x" * 5000) + self.assertIn("truncated", user) + self.assertLess(len(user), 4500) + + +class TestParse(unittest.TestCase): + def test_valid_json(self): + out = parse_response(json.dumps({ + "consistency": "divergent", "confidence": 0.8, + "reasons": ["No contractions at all."], + "caveat": "Advisory."})) + self.assertEqual(out["consistency"], "divergent") + self.assertEqual(out["confidence"], 0.8) + self.assertEqual(out["reasons"], ["No contractions at all."]) + + def test_fenced_json(self): + out = parse_response("```json\n" + json.dumps({ + "consistency": "consistent", "confidence": 0.6, + "reasons": [], "caveat": "c"}) + "\n```") + self.assertEqual(out["consistency"], "consistent") + + def test_garbage_becomes_uncertain(self): + out = parse_response("The student definitely cheated, trust me") + self.assertEqual(out["consistency"], "uncertain") + self.assertEqual(out["confidence"], 0.0) + + def test_wrong_shape_becomes_uncertain(self): + out = parse_response(json.dumps({"verdict": "guilty"})) + self.assertEqual(out["consistency"], "uncertain") + + def test_confidence_clamped(self): + out = parse_response(json.dumps({ + "consistency": "consistent", "confidence": 99, + "reasons": [], "caveat": "c"})) + self.assertEqual(out["confidence"], 1.0) + + +class TestConfig(unittest.TestCase): + def test_missing_config_raises_helpfully(self): + env = {"WRITEPRINT_JUDGE_URL": "", "WRITEPRINT_JUDGE_MODEL": ""} + old = {k: os.environ.get(k) for k in env} + try: + os.environ.update(env) + os.environ.pop("WRITEPRINT_JUDGE_KEY", None) + with self.assertRaises(JudgeError) as ctx: + judge_config() + self.assertIn("WRITEPRINT_JUDGE_URL", str(ctx.exception)) + finally: + for k, v in old.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + + def test_flags_beat_env(self): + url, key, model = judge_config("http://x/v1", "k", "m") + self.assertEqual((url, key, model), ("http://x/v1", "k", "m")) + + +class StubHandler(BaseHTTPRequestHandler): + mode = "ok" + + def log_message(self, *args): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length", 0)) + self.rfile.read(length) + if self.mode == "error": + self.send_response(500) + self.send_header("Content-Length", "0") + self.end_headers() + return + if self.mode == "bad-shape": + body = json.dumps({"nope": True}).encode() + elif self.mode == "garbage-text": + body = json.dumps({ + "choices": [{"message": {"content": "just vibes"}}]}).encode() + else: + body = json.dumps({"choices": [{"message": {"content": json.dumps({ + "consistency": "uncertain", "confidence": 0.4, + "reasons": ["Mixed signals."], + "caveat": "Stub."})}}]}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +class TestCallJudge(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = ThreadingHTTPServer(("127.0.0.1", 0), StubHandler) + cls.url = "http://127.0.0.1:%d/chat" % cls.server.server_address[1] + cls.thread = threading.Thread( + target=cls.server.serve_forever, daemon=True) + cls.thread.start() + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.thread.join() + cls.server.server_close() + + def test_roundtrip(self): + out = call_judge("sys", "user", self.url, "k", "m") + self.assertEqual(out["consistency"], "uncertain") + self.assertEqual(out["reasons"], ["Mixed signals."]) + + def test_garbage_text_becomes_uncertain(self): + StubHandler.mode = "garbage-text" + try: + out = call_judge("sys", "user", self.url, "k", "m") + self.assertEqual(out["consistency"], "uncertain") + finally: + StubHandler.mode = "ok" + + def test_bad_shape_raises(self): + StubHandler.mode = "bad-shape" + try: + with self.assertRaises(JudgeError): + call_judge("sys", "user", self.url, "k", "m") + finally: + StubHandler.mode = "ok" + + def test_http_error_raises(self): + StubHandler.mode = "error" + try: + with self.assertRaises(JudgeError): + call_judge("sys", "user", self.url, "k", "m") + finally: + StubHandler.mode = "ok" + + def test_unreachable_raises(self): + with self.assertRaises(JudgeError): + call_judge("sys", "user", "http://127.0.0.1:1/nope", "k", "m", + timeout=2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_web.py b/tests/test_web.py index 119d896..258b39d 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -73,6 +73,7 @@ def setUpClass(cls): def tearDownClass(cls): cls.server.shutdown() cls.thread.join() + cls.server.server_close() def request(self, method, path, body=None): conn = HTTPConnection("127.0.0.1", self.port, timeout=10) diff --git a/writeprint/cli.py b/writeprint/cli.py index a28b0cc..3f29b29 100644 --- a/writeprint/cli.py +++ b/writeprint/cli.py @@ -16,6 +16,8 @@ ) from .web import DEFAULT_PORT, serve from .export import rows_for, write_csv +from .judge import (JudgeError, build_prompt, call_judge, judge_config, + render_assessment) def cmd_build(args): @@ -49,6 +51,24 @@ def cmd_serve(args): serve(args.port) +def cmd_judge(args): + with open(args.baseline, encoding="utf-8") as fh: + baseline = json.load(fh) + with open(args.submission, encoding="utf-8") as fh: + text = fh.read() + try: + endpoint, api_key, model = judge_config( + args.endpoint, args.key, args.model) + system, user = build_prompt( + baseline, text, baseline.get("student", "?")) + assessment = call_judge(system, user, endpoint, api_key, model) + except JudgeError as exc: + print("writeprint judge: %s" % exc) + raise SystemExit(2) + print(render_assessment(baseline.get("student", "?"), + args.submission, assessment)) + + def cmd_batch(args): with open(args.baseline, encoding="utf-8") as fh: baseline = json.load(fh) @@ -138,6 +158,17 @@ def main(argv=None): help="Thresholds JSON from 'calibrate --out'.") p_batch.set_defaults(func=cmd_batch) + p_judge = sub.add_parser("judge", help="Ask an LLM for a second opinion (opt-in).") + p_judge.add_argument("baseline", help="Baseline JSON from 'build'.") + p_judge.add_argument("submission", help="Submission text file to assess.") + p_judge.add_argument("--endpoint", default=None, + help="Chat-completions URL (or WRITEPRINT_JUDGE_URL).") + p_judge.add_argument("--key", default=None, + help="Bearer token (or WRITEPRINT_JUDGE_KEY).") + p_judge.add_argument("--model", default=None, + help="Model name (or WRITEPRINT_JUDGE_MODEL).") + p_judge.set_defaults(func=cmd_judge) + args = parser.parse_args(argv) args.func(args) diff --git a/writeprint/judge.py b/writeprint/judge.py new file mode 100644 index 0000000..500647a --- /dev/null +++ b/writeprint/judge.py @@ -0,0 +1,158 @@ +"""Optional LLM judge for nuanced cases. Disabled by default. + +The statistical engine stays offline and dependency-free. This module adds +an opt-in second opinion: it describes the student's baseline habits to +any OpenAI-compatible chat endpoint and asks for a structured consistency +assessment. Standard library only (urllib) — no SDKs, no new dependencies. + +Privacy warning: using this sends student text to a third party. Get +consent, prefer a local model (e.g. Ollama) or your institution's +endpoint, and never use it as the sole basis for an accusation. + +Config (flags override env): + WRITEPRINT_JUDGE_URL chat-completions endpoint URL + WRITEPRINT_JUDGE_KEY bearer token (may be empty for local servers) + WRITEPRINT_JUDGE_MODEL model name +""" + +import json +import os +import urllib.request + +JUDGE_SYSTEM = ( + "You compare a student's new submission against a profile of their " + "known writing habits. Reply with JSON only: " + '{"consistency": "consistent" | "uncertain" | "divergent", ' + '"confidence": 0.0-1.0, ' + '"reasons": ["short, specific observations"], ' + '"caveat": "one sentence on why this is advisory, not proof"}. ' + "A single unusual feature is curiosity, not evidence. Only call a " + "submission divergent when several independent habits all point the " + "same way." +) + + +class JudgeError(Exception): + """Configuration or transport failure (not a model verdict).""" + + +def summarize_baseline(profile, top_n=12): + """Render baseline means as compact prose for the prompt.""" + feats = profile["features"] + # Lead with the most human-readable habits, then the rest. + first = ["avg_sentence_len", "avg_word_len", "type_token_ratio", + "contractions_per_100", "first_person_per_100", + "commas_per_100", "semicolons_per_100", "exclaim_per_100"] + names = first + [n for n in sorted(feats) if n not in first] + lines = [] + for name in names[:top_n]: + lines.append(" - %s: usually %.2f" % (name, feats[name]["mean"])) + lines.append(" (plus %d more measured habits)" % (len(feats) - top_n)) + return "\n".join(lines) + + +def build_prompt(profile, submission, student="student", max_chars=3000): + """Build the (system, user) messages for the judge call.""" + excerpt = submission[:max_chars] + if len(submission) > max_chars: + excerpt += "\n[... truncated for length ...]" + user = ( + "Student '%s' baseline writing habits " + "(averages over %d known-genuine samples):\n%s\n\n" + "New submission to assess:\n---\n%s\n---\n" + "How consistent is this submission with the baseline habits?" + % (student, profile.get("n_samples", "?"), + summarize_baseline(profile), excerpt) + ) + return JUDGE_SYSTEM, user + + +def parse_response(text): + """Parse the model's reply into an assessment dict. Never raises: + unparseable output becomes an explicit 'uncertain' verdict.""" + cleaned = text.strip() + if cleaned.startswith("```"): + lines = cleaned.split("\n") + cleaned = "\n".join(lines[1:-1] if len(lines) > 2 else lines[1:]) + try: + data = json.loads(cleaned) + except (ValueError, TypeError): + return {"consistency": "uncertain", "confidence": 0.0, + "reasons": ["Judge output was not valid JSON."], + "caveat": "Unparseable response; treat as no opinion."} + if not isinstance(data, dict) or data.get("consistency") not in ( + "consistent", "uncertain", "divergent"): + return {"consistency": "uncertain", "confidence": 0.0, + "reasons": ["Judge output missed the required fields."], + "caveat": "Malformed verdict; treat as no opinion."} + try: + confidence = float(data.get("confidence", 0.0)) + except (TypeError, ValueError): + confidence = 0.0 + reasons = data.get("reasons", []) + if not isinstance(reasons, list): + reasons = [str(reasons)] + return {"consistency": data["consistency"], + "confidence": max(0.0, min(1.0, confidence)), + "reasons": [str(r) for r in reasons][:6], + "caveat": str(data.get("caveat", "Advisory only, not proof."))} + + +def judge_config(endpoint=None, api_key=None, model=None): + """Resolve config from flags-or-env. Raises JudgeError if unusable.""" + url = endpoint or os.environ.get("WRITEPRINT_JUDGE_URL", "") + key = api_key if api_key is not None else os.environ.get("WRITEPRINT_JUDGE_KEY", "") + name = model or os.environ.get("WRITEPRINT_JUDGE_MODEL", "") + missing = [n for n, v in (("endpoint URL", url), ("model", name)) if not v] + if missing: + raise JudgeError( + "LLM judge not configured (missing %s). Set WRITEPRINT_JUDGE_URL " + "and WRITEPRINT_JUDGE_MODEL (plus WRITEPRINT_JUDGE_KEY unless " + "your endpoint needs none), or pass --endpoint/--model. " + "Any OpenAI-compatible /chat/completions endpoint works, " + "including a local Ollama server." % " and ".join(missing)) + return url, key, name + + +def call_judge(system, user, endpoint, api_key, model, timeout=60): + """POST to the endpoint, return the parsed assessment. Transport + problems raise JudgeError; model-output problems become 'uncertain'.""" + body = json.dumps({ + "model": model, + "temperature": 0, + "messages": [{"role": "system", "content": system}, + {"role": "user", "content": user}], + }).encode("utf-8") + req = urllib.request.Request( + endpoint, data=body, + headers={"Content-Type": "application/json", + "Authorization": "Bearer %s" % api_key}) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + payload = json.loads(resp.read().decode("utf-8")) + except OSError as exc: + raise JudgeError("Could not reach judge endpoint: %s" % exc) + except (ValueError, UnicodeDecodeError) as exc: + raise JudgeError("Judge endpoint returned invalid JSON: %s" % exc) + try: + text = payload["choices"][0]["message"]["content"] + except (KeyError, IndexError, TypeError): + raise JudgeError("Judge endpoint reply missed choices[0].message.content.") + return parse_response(text) + + +def render_assessment(student, filename, assessment): + """Render the assessment for the terminal.""" + lines = [ + "Writeprint LLM assessment (second opinion — advisory only)", + " Student: %s" % student, + " Submission: %s" % filename, + " Reading: %s (confidence %.2f)" % ( + assessment["consistency"].upper(), assessment["confidence"]), + "", + ] + for reason in assessment["reasons"]: + lines.append(" - %s" % reason) + lines += ["", " Caveat: %s" % assessment["caveat"], + "A statistical check plus a teacher's judgment outrank this."] + return "\n".join(lines)