Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
184 changes: 184 additions & 0 deletions tests/test_judge.py
Original file line number Diff line number Diff line change
@@ -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()
1 change: 1 addition & 0 deletions tests/test_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
31 changes: 31 additions & 0 deletions writeprint/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)

Expand Down
Loading
Loading