diff --git a/docs/ai-lab.md b/docs/ai-lab.md index 7d9e888..c32e42c 100644 --- a/docs/ai-lab.md +++ b/docs/ai-lab.md @@ -157,6 +157,19 @@ report remains intact. To automatically score an existing report, run: ./jeannie ai-lab doctor-auto-rank /path/to/report.json ``` +To compare one additional OmniRoute model with a previous complete report and +its automatic ranking, without rerunning previous candidates or judging their +responses again: + +```sh +./jeannie ai-lab doctor-add-external /path/to/report.json /path/to/auto-ranking.json nvidia/meta/llama-3.3-70b-instruct +``` + +The lab checks that the saved evidence, rubric, review IDs and judge match the +current suite, runs the new model with the baseline repeat count, and makes a +new combined report and ranking. It preserves the old reports. Previously +unscored answers remain unscored; reused scores retain the original judge's bias. + The ranking averages accuracy (0-2), uncertainty (0-2) and next step (0-1) over all cases and repeats. Skipped, incomplete, unscored and wholly invalid backends remain unranked. Equal scores tie; latency and memory are separate and diff --git a/internal/jeannieworkflow/environment_test.go b/internal/jeannieworkflow/environment_test.go index 5928b3e..3379eb1 100644 --- a/internal/jeannieworkflow/environment_test.go +++ b/internal/jeannieworkflow/environment_test.go @@ -28,7 +28,7 @@ func TestCommandTimeoutForLongAILabWork(t *testing.T) { t.Errorf("%s timeout = %s", action, got) } } - for _, action := range []string{"doctor-prepare", "doctor-suite", "doctor-auto-rank"} { + for _, action := range []string{"doctor-prepare", "doctor-suite", "doctor-auto-rank", "doctor-add-external"} { if got := CommandTimeout("ai-lab", []string{action}); got != 6*time.Hour { t.Errorf("%s: got %v, want 6h", action, got) } diff --git a/internal/jeannieworkflow/workflow.go b/internal/jeannieworkflow/workflow.go index e4dceb5..b12e81b 100644 --- a/internal/jeannieworkflow/workflow.go +++ b/internal/jeannieworkflow/workflow.go @@ -45,7 +45,7 @@ func CommandEnvironment() []string { func CommandTimeout(command string, args []string) time.Duration { if command == "ai-lab" && len(args) > 0 { switch args[0] { - case "doctor-prepare", "doctor-suite", "doctor-auto-rank": + case "doctor-prepare", "doctor-suite", "doctor-auto-rank", "doctor-add-external": return 6 * time.Hour case "suite", "install", "colibri-install", "colibri-prepare": return 2 * time.Hour diff --git a/jeannie b/jeannie index fefca90..cd0a50d 100755 --- a/jeannie +++ b/jeannie @@ -86,7 +86,7 @@ Build And Bootstrap deploy-ai-tools Install/wire local AI CLIs to the AI gateway. goose-graph [question] Explore the repo with Goose and Graphify. - ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND|suite [REPEATS]|doctor-prepare|doctor-suite [REPEATS]|doctor-auto-rank REPORT|doctor-rank REPORT REVIEW} Manage AI experiments. + ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND|suite [REPEATS]|doctor-prepare|doctor-suite [REPEATS]|doctor-auto-rank REPORT|doctor-add-external REPORT RANKING MODEL|doctor-rank REPORT REVIEW} Manage AI experiments. lab-window Apply the scheduled lab power window. deploy-omniroute Deploy the OmniRoute LLM routing gateway. deploy-hermes Deploy the Hermes agent (git-install + venv + gateway service). @@ -332,6 +332,7 @@ case "${1:-}" in doctor-suite) [[ $# -le 3 && "${3:-2}" =~ ^[1-5]$ ]] || { echo "Usage: ./jeannie ai-lab doctor-suite [REPEATS 1-5]" >&2; exit 2; } ;; doctor-rank) [[ $# -eq 4 ]] || { echo "Usage: ./jeannie ai-lab doctor-rank REPORT REVIEW" >&2; exit 2; } ;; doctor-auto-rank) [[ $# -eq 3 ]] || { echo "Usage: ./jeannie ai-lab doctor-auto-rank REPORT" >&2; exit 2; } ;; + doctor-add-external) [[ $# -eq 5 ]] || { echo "Usage: ./jeannie ai-lab doctor-add-external REPORT RANKING MODEL" >&2; exit 2; } ;; *) echo "Usage: ./jeannie ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench|suite|doctor-prepare|doctor-suite|doctor-rank}" >&2; exit 2 ;; esac case "${2:-plan}" in install|colibri-install|colibri-prepare|doctor-prepare) record_change_journal "ai-lab" "$@" ;; esac @@ -345,6 +346,8 @@ case "${1:-}" in python3 "${REPO_ROOT}/scripts/doctor-model-rank.py" "${@:3}" elif [[ "${2:-plan}" == doctor-auto-rank ]]; then python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" auto-rank "$3" + elif [[ "${2:-plan}" == doctor-add-external ]]; then + python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" add-external "${@:3}" else python3 "${REPO_ROOT}/scripts/ai-lab.py" "${@:2}" fi diff --git a/scripts/doctor-model-lab.py b/scripts/doctor-model-lab.py index b5f773d..0519148 100644 --- a/scripts/doctor-model-lab.py +++ b/scripts/doctor-model-lab.py @@ -368,7 +368,7 @@ def evaluate_answer(server, backend, model, report): return final -def auto_rank(path): +def auto_rank(path, prior_reviews=None): """Score blinded synthetic cases with an isolated local LLM judge.""" path = Path(path).resolve() report = json.loads(path.read_text()) @@ -380,9 +380,13 @@ def auto_rank(path): base = f"http://127.0.0.1:{chosen_port}" env = dict(os.environ, OLLAMA_HOST=f"127.0.0.1:{chosen_port}", OLLAMA_MODELS=str(model_path.parent.parent), OLLAMA_VULKAN="0") server = ScopedServer([shutil.which("ollama"), "serve"], env, base, "/api/tags", path.parent, "judge-" + uuid.uuid4().hex[:8]) - valid = [row for row in report["results"] if row.get("contract") == "valid"] + cached = {item["id"]: item for item in (prior_reviews or [])} + valid_ids = {row["review_id"] for row in report["results"] if row.get("contract") == "valid"} + if len(cached) != len(prior_reviews or []) or not set(cached).issubset(valid_ids): + raise RuntimeError("Prior judge scores do not match the report") + valid = [row for row in report["results"] if row.get("contract") == "valid" and row["review_id"] not in cached] secrets.SystemRandom().shuffle(valid) - reviews = [] + reviews = list(cached.values()) schema = {"type": "object", "additionalProperties": False, "required": ["accuracy", "uncertainty", "next_step"], "properties": { "accuracy": {"type": "integer", "minimum": 0, "maximum": 2}, @@ -419,6 +423,7 @@ def auto_rank(path): result["method"] = "Automated blinded LLM judge: " + result["method"].replace("Blinded human", "model-graded") result["judge"] = {"model": OLLAMA_MODEL, "bias_warning": "The judge is also a candidate; its rankings can favor itself or similar models. Scores are estimates, not verified accuracy."} result["judge_failures"] = sum("error" in item for item in reviews) + result["reused_reviews"] = len(cached) result["reviews"] = reviews output = path.parent / ("auto-ranking-" + uuid.uuid4().hex[:8] + ".json") fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) @@ -429,6 +434,74 @@ def auto_rank(path): print(f"Automatic ranking: {output}") +def add_external(baseline_path, ranking_path, model_name): + """Evaluate one OmniRoute model and reuse a matching benchmark and judge.""" + baseline_path = Path(baseline_path).resolve() + ranking_path = Path(ranking_path).resolve() + report = json.loads(baseline_path.read_text()) + previous = json.loads(ranking_path.read_text()) + if previous.get("judge", {}).get("model") != OLLAMA_MODEL: + raise RuntimeError("Prior ranking used a different or unknown judge") + prior_reviews = previous.get("reviews") + if not isinstance(prior_reviews, list): + raise RuntimeError("Prior ranking has no reusable judge scores") + ranker.rank(report, {"responses": prior_reviews}) + if report.get("cases") != [name for name, _ in CASES] or report.get("review_rubric") != RUBRIC: + raise RuntimeError("Baseline cases or rubric differ from the current lab; run a new full suite") + if not re.fullmatch(r"[a-zA-Z0-9_./:-]+", model_name): + raise RuntimeError("Invalid OmniRoute model name") + os.environ["LAB_DOCTOR_LAB_OMNI_MODEL"] = model_name + base, chosen_model, api_key = external_config() + server = ExternalServer(base, api_key) + backend = "omniroute-extra-" + uuid.uuid4().hex[:8] + report_dir = lab.ROOT / "reports" / (datetime.now(timezone.utc).strftime("doctor-compare-%Y%m%dT%H%M%SZ-") + uuid.uuid4().hex[:8]) + report_dir.mkdir(parents=True, mode=0o700) + expected_cases = dict(CASES) + copied = set() + for row in report["results"]: + parts = (row["case"], str(row["repeat"]), row["backend"]) + if any(not re.fullmatch(r"[a-zA-Z0-9_.-]+", part) for part in parts): + raise RuntimeError("Invalid baseline evidence filename") + filename = f"{parts[0]}-{parts[1]}-{parts[2]}.tsv" + if filename in copied: + continue + source = baseline_path.parent / filename + if row["case"] not in expected_cases or source.read_text() != expected_cases[row["case"]]: + raise RuntimeError("Baseline evidence differs from current cases; run a new full suite") + destination = report_dir / filename + fd = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w") as stream: + stream.write(source.read_text()) + copied.add(filename) + new_rows = [] + print(f"Testing only {chosen_model} via OmniRoute; synthetic cases leave this host.", flush=True) + for repeat in range(report["repeats"]): + for case_id, tsv in CASES: + print(f"[{repeat + 1}/{report['repeats']}] {case_id}", flush=True) + case = case_report(case_id + f"-{repeat + 1}-{backend}", tsv, report_dir) + row = {"backend": backend, "model": chosen_model, "case": case_id, "repeat": repeat + 1, + "review_id": uuid.uuid4().hex, "manual_review_required": False} + row.update(evaluate_answer(server, "omniroute", chosen_model, case)) + new_rows.append(row) + report["results"].extend(new_rows) + times = [row["elapsed_seconds"] for row in new_rows] + report["summary"][backend] = {"completed": len(new_rows), "valid": sum(row["contract"] == "valid" for row in new_rows), + "rejected": sum(row["contract"] == "rejected" for row in new_rows), + "errors": sum(row["contract"] == "error" for row in new_rows), + "median_seconds": round(statistics.median(times), 2) if times else None, + "scope_peak_bytes": None, "sampled_minimum_host_available_bytes": None} + report["baseline"] = {"report": str(baseline_path), "ranking": str(ranking_path), "judge_scores_reused": len(prior_reviews)} + path = report_dir / "report.json" + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w") as stream: + json.dump(report, stream, indent=2) + stream.write("\n") + print(f"Combined report: {path}", flush=True) + auto_rank(path, prior_reviews) + if any(row["contract"] == "error" for row in new_rows): + raise RuntimeError("One or more NVIDIA requests failed; combined report retained") + + def suite_run(repeats): if not 1 <= repeats <= 5: raise RuntimeError("Repeat count must be between 1 and 5") @@ -563,8 +636,8 @@ def suite_run(repeats): def main(): - if len(sys.argv) < 2 or sys.argv[1] not in ("prepare", "suite", "auto-rank"): - raise RuntimeError("Usage: ./jeannie ai-lab {doctor-prepare|doctor-suite [REPEATS 1-5]|doctor-auto-rank REPORT}") + if len(sys.argv) < 2 or sys.argv[1] not in ("prepare", "suite", "auto-rank", "add-external"): + raise RuntimeError("Usage: ./jeannie ai-lab {doctor-prepare|doctor-suite [REPEATS 1-5]|doctor-auto-rank REPORT|doctor-add-external REPORT RANKING MODEL}") if sys.argv[1] == "prepare": if len(sys.argv) != 2: raise RuntimeError("doctor-prepare accepts no arguments") @@ -572,6 +645,8 @@ def main(): else: if sys.argv[1] == "auto-rank" and len(sys.argv) != 3: raise RuntimeError("doctor-auto-rank requires a report path") + if sys.argv[1] == "add-external" and len(sys.argv) != 5: + raise RuntimeError("doctor-add-external requires a report, ranking, and model") if sys.argv[1] == "suite" and len(sys.argv) > 3: raise RuntimeError("doctor-suite accepts at most one repeat count") lab.workspace() @@ -582,6 +657,8 @@ def main(): raise RuntimeError("Another AI lab suite is running") from exc if sys.argv[1] == "auto-rank": auto_rank(sys.argv[2]) + elif sys.argv[1] == "add-external": + add_external(*sys.argv[2:]) else: suite_run(int(sys.argv[2]) if len(sys.argv) == 3 else 2) diff --git a/tests/jeannie/test_doctor_model_lab.py b/tests/jeannie/test_doctor_model_lab.py index fee1535..07c98d2 100644 --- a/tests/jeannie/test_doctor_model_lab.py +++ b/tests/jeannie/test_doctor_model_lab.py @@ -16,6 +16,33 @@ rank_spec.loader.exec_module(ranker) class DoctorModelLabTests(unittest.TestCase): + def test_incremental_external_reuses_baseline_without_retesting(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cases = (("one", "warn\tA\tB\tbad\tdetail\t./jeannie explain status\t\t\n"),) + rubric = {"one": "assess evidence"} + baseline = {"cases": ["one"], "repeats": 1, "review_rubric": rubric, + "summary": {"old": {"median_seconds": 1}}, + "results": [{"backend": "old", "model": "old-model", "case": "one", "repeat": 1, + "review_id": "old-id", "contract": "valid"}]} + ranking = {"judge": {"model": lab.OLLAMA_MODEL}, "reviews": [ + {"id": "old-id", "accuracy": 2, "uncertainty": 2, "next_step": 1}]} + baseline_path, ranking_path = root / "report.json", root / "ranking.json" + baseline_path.write_text(json.dumps(baseline)) + ranking_path.write_text(json.dumps(ranking)) + (root / "one-1-old.tsv").write_text(cases[0][1]) + with mock.patch.object(lab, "CASES", cases), mock.patch.object(lab, "RUBRIC", rubric), \ + mock.patch.object(lab.lab, "ROOT", root), \ + mock.patch.object(lab, "external_config", return_value=("http://127.0.0.1:20128", "nvidia/meta/model", "key")), \ + mock.patch.object(lab, "evaluate_answer", return_value={"contract": "valid", "elapsed_seconds": 1}), \ + mock.patch.object(lab, "auto_rank") as judge, \ + mock.patch.dict(lab.os.environ, {}, clear=False): + lab.add_external(baseline_path, ranking_path, "nvidia/meta/model") + combined = json.loads(Path(judge.call_args.args[0]).read_text()) + self.assertEqual(len(combined["results"]), 2) + self.assertEqual(combined["results"][0]["review_id"], "old-id") + self.assertEqual(judge.call_args.args[1], ranking["reviews"]) + def test_auto_rank_scores_previous_report_without_manual_input(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory)