Compare commits

...

2 Commits

Author SHA1 Message Date
juvenal.diaz e3564e211b Rank doctor models with blinded reviews
Homelab Main / validate (push) Successful in 1m18s Details
Homelab Main / running-update (push) Successful in 3s Details
Homelab Main / debian-ops (push) Failing after 3s Details
2026-11-12 17:43:15 -06:00
juvenal.diaz f487e701c9 Compare installed models in doctor lab 2026-11-12 13:06:34 -06:00
5 changed files with 301 additions and 35 deletions

View File

@ -105,13 +105,18 @@ verifies its SHA-256 before importing it for Colibri:
The suite runs ten synthetic diagnostic cases twice per backend, including
contrasting known and unknown intent for the runner, stopped services, and a
maintenance window. Sandbox intent is tested as unknown. Pass a repeat
count from 1 to 5 to `doctor-suite` to change that. It uses the existing
`qwen2.5-coder:7b` Ollama model on CPU for Ollama and llama.cpp, and
Qwen3-Coder-30B-A3B Q4_K_M on CPU for Colibri. The 30B model is the largest
count from 1 to 5 to `doctor-suite` to change that. It tests the existing
Ollama models `qwen2.5:0.5b`, `llama3.2:3b`, `qwen2.5-coder:7b`, and
`qwen2.5:14b` sequentially on CPU. Missing models are reported as skipped;
models whose GGUF weights alone reach the 8 GiB limit are also skipped. The
installed 14B model is approximately 9 GB, so it is expected to be skipped.
It also tests the 7B GGUF using llama.cpp and Qwen3-Coder-30B-A3B Q4_K_M
using Colibri, both on CPU. The 30B model is the largest
candidate in Colibri's pinned catalog with an 8 GB minimum, not a guarantee
that this particular GGUF and context will fit. Keep at least 22 GiB free in
the lab workspace for the download and at least 9 GiB of host MemAvailable
before each backend starts. The suite requires a functioning systemd user
before each backend starts; it waits up to 60 seconds for memory to recover
between runs. The suite requires a functioning systemd user
manager and cgroup v2 memory controller. It refuses to load a model unless an
8 GiB memory limit and zero swap are verified; a low-memory watchdog stops its
own scope. This limit can terminate a model and cannot eliminate host pressure.
@ -123,9 +128,36 @@ review the cases and responses manually. The lab accepts one complete outer
JSON code fence before applying the same validator and preserves raw answers;
it does not change production Doctor parsing. Different model sizes and output
constraints also mean Colibri quality results do not isolate engine performance.
The suite also sends the same **synthetic cases** to the smart direct model in
`models.env` through the loopback OmniRoute gateway. If no direct model is
recorded, it uses the smart route alias. Override with
`LAB_DOCTOR_LAB_OMNI_MODEL` or `LAB_DOCTOR_LAB_OMNI_URL` (loopback `/v1` only).
OmniRoute can fall back or change providers; the report records the requested
and returned model names where available, which are not proof of backend identity.
This can use an external provider and its quotas; no live Doctor evidence is sent.
External inference has no local scope memory measurement or GPU equivalence.
This experiment does not change the production doctor model or stop services.
Ollama must be idle before the test; stop or unload models deliberately first.
Each run writes `report.json` and a shuffled `blind-review.json` in its private
report directory. Review the evidence, rubric and answer in each entry and fill
in three integer fields: `accuracy` (0 wrong, 1 partial, 2 supported),
`uncertainty` (0 unsupported certainty, 1 partial, 2 appropriate uncertainty),
and `next_step` (0 unhelpful or unsafe, 1 useful and safe). IDs conceal the
backend but output style may reveal it. Leave null if not reviewed. Then run:
```sh
./jeannie ai-lab doctor-rank /path/to/report.json /path/to/blind-review.json
```
The ranking averages the five available points over all cases and repeats.
Contract failures or request errors score zero; skipped, incomplete, and
partially reviewed backends remain unranked. Equal scores tie; latency and
memory are separate columns and do not change quality rank. This is a small,
human-scored benchmark, not a statistical accuracy guarantee. Scores depend on
the evaluator and the cases; run additional cases and independent reviews before
changing production routing.
## Repeated comparison suite
After the llama.cpp and Colibri installation and model preparation above:

View File

@ -86,7 +86,7 @@ Build And Bootstrap
deploy-ai-tools Install/wire local AI CLIs to the AI gateway.
goose-graph <update|context|learn|propose> [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]} Manage AI experiments.
ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND|suite [REPEATS]|doctor-prepare|doctor-suite [REPEATS]|doctor-rank REPORT REVIEW} Manage AI experiments.
lab-window <start|stop|status> 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).
@ -330,7 +330,8 @@ case "${1:-}" in
bench) [[ $# -eq 3 && "${3}" =~ ^(ollama|cpu|vulkan|colibri|qwen-cpu)$ ]] || { echo "Usage: ./jeannie ai-lab bench {ollama|cpu|vulkan|colibri|qwen-cpu}" >&2; exit 2; } ;;
suite) [[ $# -le 3 && "${3:-3}" =~ ^([1-9]|10)$ ]] || { echo "Usage: ./jeannie ai-lab suite [REPEATS 1-10]" >&2; exit 2; } ;;
doctor-suite) [[ $# -le 3 && "${3:-2}" =~ ^[1-5]$ ]] || { echo "Usage: ./jeannie ai-lab doctor-suite [REPEATS 1-5]" >&2; exit 2; } ;;
*) echo "Usage: ./jeannie ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench|suite|doctor-prepare|doctor-suite}" >&2; exit 2 ;;
doctor-rank) [[ $# -eq 4 ]] || { echo "Usage: ./jeannie ai-lab doctor-rank REPORT REVIEW" >&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
if [[ "${2:-plan}" == suite ]]; then
@ -339,6 +340,8 @@ case "${1:-}" in
python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" prepare
elif [[ "${2:-plan}" == doctor-suite ]]; then
python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" suite "${@:3}"
elif [[ "${2:-plan}" == doctor-rank ]]; then
python3 "${REPO_ROOT}/scripts/doctor-model-rank.py" "${@:3}"
else
python3 "${REPO_ROOT}/scripts/ai-lab.py" "${@:2}"
fi

View File

@ -6,6 +6,7 @@ import json
import os
import re
import signal
import secrets
from pathlib import Path
import shutil
import socket
@ -18,6 +19,7 @@ import time
import urllib.error
import urllib.request
import uuid
from urllib.parse import urlsplit
from datetime import datetime, timezone
@ -38,6 +40,7 @@ MODEL_SHA256 = "f6050b4da22869aa3fb9d94bb3314e9fc5a027d4741c1f97761c387d6b2b2335
MODEL_FILE = lab.ROOT / "models" / MODEL_NAME
MODEL_DIR = lab.ROOT / "models" / "qwen3-coder-30b-doctor-colibri"
OLLAMA_MODEL = "qwen2.5-coder:7b"
OLLAMA_MODELS = ("qwen2.5:0.5b", "llama3.2:3b", OLLAMA_MODEL, "qwen2.5:14b")
MEMORY_MAX = 8 * 1024 ** 3
START_AVAILABLE = 9 * 1024 ** 3
STOP_AVAILABLE = 768 * 1024 ** 2
@ -76,6 +79,14 @@ def available_bytes():
raise RuntimeError("Cannot read MemAvailable")
def wait_for_available_memory():
deadline = time.monotonic() + 60
while available_bytes() < START_AVAILABLE:
if time.monotonic() >= deadline:
raise RuntimeError("Need at least 9 GiB MemAvailable before starting a model with a 1 GiB reserve")
time.sleep(2)
def prepare():
lab.workspace()
if not lab.COLIBRI_CLI.is_file() or not (lab.COLIBRI_SOURCE / "c/qwen36").is_file():
@ -122,9 +133,9 @@ def port():
return sock.getsockname()[1]
def request(url, payload=None, timeout=5):
def request(url, payload=None, timeout=5, headers=None):
data = json.dumps(payload).encode() if payload is not None else None
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json", **(headers or {})})
with urllib.request.urlopen(req, timeout=timeout) as response:
return json.load(response)
@ -185,8 +196,7 @@ class ScopedServer:
return
def start(self):
if available_bytes() < START_AVAILABLE:
raise RuntimeError("Need at least 9 GiB MemAvailable before starting a model with a 1 GiB reserve")
wait_for_available_memory()
if not shutil.which("systemd-run") or not shutil.which("systemctl"):
raise RuntimeError("systemd-run and a working user manager are required for the 8 GiB memory limit")
path = self.directory / (self.backend + "-server.log")
@ -236,6 +246,24 @@ class ScopedServer:
raise
class ExternalServer:
"""An already running gateway; never stop it or claim its memory use."""
cgroup = None
minimum_available = None
low_memory = False
process = None
def __init__(self, base, api_key):
self.base = base
self.api_key = api_key
def start(self):
pass
def stop(self):
pass
def case_report(case_id, tsv, directory):
path = directory / (case_id + ".tsv")
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
@ -246,17 +274,52 @@ def case_report(case_id, tsv, directory):
def answer(server, backend, model, report):
prompt = doctor.build_prompt(report)
if backend == "ollama":
if backend.startswith("ollama-"):
payload = {"model": model, "prompt": prompt, "format": doctor.schema(report), "stream": False,
"keep_alive": "5m", "options": {"num_ctx": CONTEXT, "num_predict": OUTPUT_TOKENS, "temperature": 0, "num_gpu": 0}}
data = request(server.base + "/api/generate", payload, timeout=1800)
return data.get("response", ""), data.get("eval_count")
return data.get("response", ""), data.get("eval_count"), data.get("model")
payload = {"model": model, "messages": [{"role": "user", "content": prompt}], "temperature": 0,
"max_tokens": OUTPUT_TOKENS, "stream": False}
if backend == "llama-cpu":
payload["response_format"] = {"type": "json_object"}
data = request(server.base + "/v1/chat/completions", payload, timeout=1800)
return data["choices"][0]["message"].get("content", ""), (data.get("usage") or {}).get("completion_tokens")
if backend == "omniroute":
payload["response_format"] = {"type": "json_object"}
headers = {"Authorization": "Bearer " + server.api_key} if backend == "omniroute" else None
if headers is None:
data = request(server.base + "/v1/chat/completions", payload, timeout=1800)
else:
data = request(server.base + "/v1/chat/completions", payload, timeout=1800, headers=headers)
return data["choices"][0]["message"].get("content", ""), (data.get("usage") or {}).get("completion_tokens"), data.get("model")
def read_env_values(path, keys):
"""Read generated KEY=value files as data without executing shell code."""
values = {}
try:
for line in Path(path).read_text().splitlines():
key, separator, value = line.removeprefix("export ").partition("=")
if separator and key in keys:
values[key] = value.strip().strip("\"'")
except FileNotFoundError:
pass
return values
def external_config():
routes = read_env_values(os.getenv("LAB_AI_STACK_MODEL_ROUTES_FILE", "/data/homelab-ai-stack/models.env"),
{"AI_STACK_AGENT_SMART_DIRECT_MODEL", "AI_STACK_AGENT_SMART_MODEL"})
settings = read_env_values(os.getenv("LAB_AI_STACK_TOOLS_ENV_FILE", "/data/homelab-ai-stack/ai-tools.env"),
{"OPENAI_BASE_URL", "OPENAI_API_KEY", "OMNIROUTE_API_KEY"})
url = os.getenv("LAB_DOCTOR_LAB_OMNI_URL", settings.get("OPENAI_BASE_URL", "http://127.0.0.1:20128/v1")).rstrip("/")
parsed = urlsplit(url)
if parsed.scheme != "http" or parsed.hostname not in ("localhost", "127.0.0.1", "::1") or parsed.path != "/v1" or parsed.query or parsed.fragment or parsed.username or parsed.password:
raise RuntimeError("Doctor lab OmniRoute endpoint must be local HTTP with a /v1 path")
model = os.getenv("LAB_DOCTOR_LAB_OMNI_MODEL") or routes.get("AI_STACK_AGENT_SMART_DIRECT_MODEL") or routes.get("AI_STACK_AGENT_SMART_MODEL")
if not model:
raise RuntimeError("No OmniRoute model found in the generated routes file")
key = os.getenv("LAB_DOCTOR_LAB_OMNI_KEY") or settings.get("OMNIROUTE_API_KEY") or settings.get("OPENAI_API_KEY") or "sk_omniroute"
return url[:-3], model, key
def parse_answer(response):
@ -276,37 +339,66 @@ def suite_run(repeats):
if not server_bin.is_file() or not shutil.which("ollama"):
raise RuntimeError("Install llama.cpp with ./jeannie ai-lab install and ensure Ollama is installed")
lab.require_idle_ollama()
model_path = suite.model_from_modelfile(OLLAMA_MODEL)
if not model_path.is_file() or model_path.parent.name != "blobs":
raise RuntimeError("The Ollama 7B GGUF blob is unavailable or not in a model store")
with model_path.open("rb") as stream:
if stream.read(4) != b"GGUF":
raise RuntimeError("The Ollama 7B model is not a GGUF file")
model_sha = lab.digest(model_path)
models = {}
skipped = {}
for name in OLLAMA_MODELS:
key = "ollama-" + name.replace(":", "-")
try:
path = suite.model_from_modelfile(name)
if not path.is_file() or path.parent.name != "blobs":
raise RuntimeError("model GGUF is unavailable or not in an Ollama model store")
with path.open("rb") as stream:
if stream.read(4) != b"GGUF":
raise RuntimeError("model file is not GGUF")
if path.stat().st_size >= MEMORY_MAX:
raise RuntimeError("model weights alone are at least the 8 GiB scope limit")
models[name] = {"path": path, "sha256": lab.digest(path)}
except (RuntimeError, OSError, subprocess.TimeoutExpired) as exc:
skipped[key] = str(exc)
try:
external_base, external_model, external_key = external_config()
except (OSError, RuntimeError, ValueError):
external_base, external_model, external_key = "", "unavailable", ""
skipped["omniroute"] = "OmniRoute local endpoint or generated model route is unavailable"
backends = [("omniroute", external_model)]
backends += [("ollama-" + name.replace(":", "-"), name) for name in OLLAMA_MODELS]
backends += [("llama-cpu", OLLAMA_MODEL), ("colibri", MODEL_NAME)]
if OLLAMA_MODEL not in models:
skipped["llama-cpu"] = "The 7B Ollama GGUF is unavailable or exceeds the scope limit"
report_dir = lab.ROOT / "reports" / (datetime.now(timezone.utc).strftime("doctor-suite-%Y%m%dT%H%M%SZ-") + uuid.uuid4().hex[:8])
report_dir.mkdir(parents=True, mode=0o700)
results = []
resource_usage = {}
try:
for backend in ("ollama", "llama-cpu", "colibri"):
lab.require_idle_ollama()
for backend, selected_model in backends:
if backend in skipped:
print(f"Skipping {backend}: {skipped[backend]}", flush=True)
continue
if backend != "omniroute":
lab.require_idle_ollama()
chosen_port = port()
base = f"http://127.0.0.1:{chosen_port}"
env = dict(os.environ)
env.pop("COLI_API_KEY", None)
env.update(COLI_VULKAN="0", COLI_CUDA="0")
if backend == "ollama":
if backend == "omniroute":
server = ExternalServer(external_base, external_key)
model = selected_model
elif backend.startswith("ollama-"):
model_path = models[selected_model]["path"]
env.update(OLLAMA_HOST=f"127.0.0.1:{chosen_port}", OLLAMA_MODELS=str(model_path.parent.parent), OLLAMA_VULKAN="0")
command, model, health = [shutil.which("ollama"), "serve"], OLLAMA_MODEL, "/api/tags"
command, model, health = [shutil.which("ollama"), "serve"], selected_model, "/api/tags"
elif backend == "llama-cpu":
model_path = models[OLLAMA_MODEL]["path"]
command = [str(server_bin), "-m", str(model_path), "--host", "127.0.0.1", "--port", str(chosen_port), "--alias", "doctor-lab-7b", "--device", "none", "-ngl", "0", "-c", str(CONTEXT)]
model, health = "doctor-lab-7b", "/health"
else:
command = [sys.executable, str(lab.COLIBRI_CLI), "serve", "--model", str(MODEL_DIR), "--host", "127.0.0.1", "--port", str(chosen_port), "--model-id", "doctor-lab-30b", "--cap", "32", "--gpu", "none", "--ctx", str(CONTEXT), "--ngen", str(OUTPUT_TOKENS)]
model, health = "doctor-lab-30b", "/health"
server = ScopedServer(command, env, base, health, report_dir, backend)
if backend != "omniroute":
server = ScopedServer(command, env, base, health, report_dir, backend)
try:
print(f"Starting {backend} ({model}) in an 8 GiB, zero-swap scope...", flush=True)
print(f"Testing {backend} ({model})" + (" through OmniRoute; synthetic cases leave this host." if backend == "omniroute" else " in an 8 GiB, zero-swap scope..."), flush=True)
server.start()
for repeat in range(repeats):
for case_id, tsv in CASES:
@ -314,10 +406,10 @@ def suite_run(repeats):
report = case_report(case_id + f"-{repeat + 1}-{backend}", tsv, report_dir)
start = time.monotonic()
row = {"backend": backend, "model": model, "case": case_id, "repeat": repeat + 1,
"manual_review_required": True}
"review_id": uuid.uuid4().hex, "manual_review_required": True}
try:
response, tokens = answer(server, backend, model, report)
row.update(elapsed_seconds=round(time.monotonic() - start, 2), generated_tokens=tokens)
response, tokens, returned_model = answer(server, backend, model, report)
row.update(elapsed_seconds=round(time.monotonic() - start, 2), generated_tokens=tokens, returned_model=returned_model)
try:
doctor.validate(parse_answer(response), report)
row["contract"] = "valid"
@ -327,7 +419,7 @@ def suite_run(repeats):
except (OSError, ValueError, KeyError, IndexError, urllib.error.URLError) as exc:
row.update(contract="error", error=str(exc), elapsed_seconds=round(time.monotonic() - start, 2))
results.append(row)
if server.low_memory or server.process.poll() is not None:
if server.low_memory or (server.process is not None and server.process.poll() is not None):
raise RuntimeError(f"{backend} stopped during inference; see its private server log")
finally:
peak = None
@ -340,7 +432,7 @@ def suite_run(repeats):
server.stop()
finally:
summary = {}
for backend in ("ollama", "llama-cpu", "colibri"):
for backend, _ in backends:
rows = [row for row in results if row["backend"] == backend]
times = [row["elapsed_seconds"] for row in rows if "elapsed_seconds" in row]
summary[backend] = {"completed": len(rows), "valid": sum(row.get("contract") == "valid" for row in rows),
@ -348,19 +440,33 @@ def suite_run(repeats):
"errors": sum(row.get("contract") == "error" for row in rows),
"median_seconds": round(statistics.median(times), 2) if times else None,
**resource_usage.get(backend, {})}
if backend in skipped:
summary[backend]["skipped"] = skipped[backend]
output = {"cases": [entry[0] for entry in CASES], "review_rubric": RUBRIC, "repeats": repeats, "results": results,
"summary": summary,
"models": {"ollama_and_llama": {"name": OLLAMA_MODEL, "sha256": model_sha},
"models": {**{name: {"sha256": details["sha256"]} for name, details in models.items()},
"colibri": {"name": MODEL_NAME, "sha256": MODEL_SHA256}},
"limits": {"scope_memory_max_bytes": MEMORY_MAX, "scope_swap_max_bytes": 0,
"minimum_start_available_bytes": START_AVAILABLE, "watchdog_stop_available_bytes": STOP_AVAILABLE},
"interpretation": "Contract validation does not establish diagnostic correctness. Compare responses manually; models differ between Colibri and the other engines."}
"interpretation": "Contract validation does not establish diagnostic correctness. Compare responses manually; model families, provider constraints and hardware differ. OmniRoute can route or fall back to another model."}
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(output, stream, indent=2)
stream.write("\n")
print(f"Private report: {path}", flush=True)
cases = dict(CASES)
review = [{"id": row["review_id"], "case": row["case"], "evidence": cases[row["case"]],
"rubric": RUBRIC[row["case"]], "response": row.get("response", ""),
"accuracy": None, "uncertainty": None, "next_step": None}
for row in results if row.get("contract") == "valid"]
secrets.SystemRandom().shuffle(review)
review_path = report_dir / "blind-review.json"
fd = os.open(review_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as stream:
json.dump({"instructions": "Score accuracy and uncertainty 0-2 each, next_step 0-1. Leave null if unreviewed. Answers are blinded; do not include sensitive information.", "responses": review}, stream, indent=2)
stream.write("\n")
print(f"Blinded review: {review_path}", flush=True)
print(json.dumps(summary, indent=2), flush=True)
if any(row.get("contract") == "error" for row in results):
raise RuntimeError("One or more inference requests failed; see the private report and logs")

View File

@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Rank Doctor lab results after a blinded human review."""
import json
from pathlib import Path
import sys
def rank(report, review):
rows = report["results"]
reviewed = {}
for item in review["responses"]:
key = item["id"]
if key in reviewed:
raise ValueError("duplicate review ID")
scores = [item.get("accuracy"), item.get("uncertainty"), item.get("next_step")]
if any(value is None for value in scores):
reviewed[key] = None
continue
if any(type(value) is not int or not 0 <= value <= maximum
for value, maximum in zip(scores, (2, 2, 1))):
raise ValueError("review scores must be integers: accuracy 0-2, uncertainty 0-2, next_step 0-1")
reviewed[key] = sum(scores)
ids = [row.get("review_id") for row in rows]
if None in ids or len(ids) != len(set(ids)):
raise ValueError("report review IDs missing or duplicated")
expected_ids = {row["review_id"] for row in rows if row.get("contract") == "valid"}
if set(reviewed) != expected_ids:
raise ValueError("review IDs do not match the report's valid responses")
expected_cases = {(case, repeat) for case in report["cases"] for repeat in range(1, report["repeats"] + 1)}
entries = []
for backend, summary in report["summary"].items():
selected = [row for row in rows if row["backend"] == backend]
keys = [(row["case"], row["repeat"]) for row in selected]
complete = len(keys) == len(expected_cases) and set(keys) == expected_cases
pending = sum(reviewed[row["review_id"]] is None for row in selected if row.get("contract") == "valid")
scores = [reviewed[row["review_id"]] if row.get("contract") == "valid" else 0 for row in selected]
entry = {"backend": backend, "model": selected[0]["model"] if selected else None,
"completed": len(selected), "expected": len(expected_cases), "pending_review": pending,
"contract_failures_scored_zero": sum(row.get("contract") != "valid" for row in selected),
"median_seconds": summary.get("median_seconds"), "scope_peak_bytes": summary.get("scope_peak_bytes"),
"score_out_of_5": round(sum(scores) / len(expected_cases), 3) if complete and not pending else None}
if summary.get("skipped"):
entry["skipped"] = summary["skipped"]
entries.append(entry)
entries.sort(key=lambda entry: (entry["score_out_of_5"] is None, -(entry["score_out_of_5"] or 0), entry["backend"]))
return {"method": "Blinded human accuracy 0-2, uncertainty 0-2 and next step 0-1 per valid response; contract failures score zero. Complete runs only; equal scores tie. Speed and memory are reported separately.", "ranking": entries}
def main():
if len(sys.argv) != 3:
raise ValueError("Usage: ./jeannie ai-lab doctor-rank REPORT.json blind-review.json")
with Path(sys.argv[1]).open() as stream:
report = json.load(stream)
with Path(sys.argv[2]).open() as stream:
review = json.load(stream)
print(json.dumps(rank(report, review), indent=2))
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError) as exc:
print(f"Doctor model ranking: {exc}", file=sys.stderr)
sys.exit(1)

View File

@ -10,9 +10,70 @@ ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location("doctor_model_lab", ROOT / "scripts/doctor-model-lab.py")
lab = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lab)
rank_spec = importlib.util.spec_from_file_location("doctor_model_rank", ROOT / "scripts/doctor-model-rank.py")
ranker = importlib.util.module_from_spec(rank_spec)
rank_spec.loader.exec_module(ranker)
class DoctorModelLabTests(unittest.TestCase):
def test_external_request_uses_the_same_evidence_and_private_key(self):
with tempfile.TemporaryDirectory() as directory:
name, tsv = lab.CASES[0]
report = lab.case_report(name, tsv, Path(directory))
server = lab.ExternalServer("http://127.0.0.1:20128", "example-private-key")
result = {"choices": [{"message": {"content": "{}"}}], "model": "provider/model"}
with mock.patch.object(lab, "request", return_value=result) as call:
_, _, actual = lab.answer(server, "omniroute", "provider/model", report)
self.assertEqual(actual, "provider/model")
self.assertEqual(call.call_args.args[0], "http://127.0.0.1:20128/v1/chat/completions")
self.assertIn("gitea-runner", call.call_args.args[1]["messages"][0]["content"])
self.assertEqual(call.call_args.kwargs["headers"]["Authorization"], "Bearer example-private-key")
def test_external_config_reads_values_without_executing_them_and_requires_loopback(self):
with tempfile.TemporaryDirectory() as directory:
routes = Path(directory) / "routes"
config = Path(directory) / "settings"
routes.write_text("AI_STACK_AGENT_SMART_DIRECT_MODEL=provider/model\n")
config.write_text("OPENAI_BASE_URL=http://127.0.0.1:20128/v1\nOPENAI_API_KEY=private\n")
env = {"LAB_AI_STACK_MODEL_ROUTES_FILE": str(routes), "LAB_AI_STACK_TOOLS_ENV_FILE": str(config)}
with mock.patch.dict(lab.os.environ, env, clear=True):
self.assertEqual(lab.external_config(), ("http://127.0.0.1:20128", "provider/model", "private"))
with mock.patch.dict(lab.os.environ, {**env, "LAB_DOCTOR_LAB_OMNI_URL": "http://outside.example/v1"}, clear=True):
with self.assertRaises(RuntimeError):
lab.external_config()
def test_ranking_requires_complete_blind_reviews_and_scores_failures_zero(self):
report = {"cases": ["one", "two"], "repeats": 1,
"summary": {"a": {"median_seconds": 2}, "b": {}, "skipped": {"skipped": "missing"}},
"results": [{"backend": "a", "model": "A", "case": "one", "repeat": 1, "review_id": "1", "contract": "valid"},
{"backend": "a", "model": "A", "case": "two", "repeat": 1, "review_id": "2", "contract": "rejected"},
{"backend": "b", "model": "B", "case": "one", "repeat": 1, "review_id": "3", "contract": "valid"}]}
review = {"responses": [{"id": "1", "accuracy": 2, "uncertainty": 2, "next_step": 1},
{"id": "3", "accuracy": None, "uncertainty": None, "next_step": None}]}
result = ranker.rank(report, review)["ranking"]
self.assertEqual(result[0]["score_out_of_5"], 2.5)
self.assertEqual(result[0]["contract_failures_scored_zero"], 1)
self.assertTrue(all(row["score_out_of_5"] is None for row in result[1:]))
review["responses"][0]["accuracy"] = 3
with self.assertRaises(ValueError):
ranker.rank(report, review)
def test_comparison_includes_the_installed_models(self):
self.assertEqual(lab.OLLAMA_MODELS, ("qwen2.5:0.5b", "llama3.2:3b", "qwen2.5-coder:7b", "qwen2.5:14b"))
def test_each_ollama_model_uses_the_isolated_ollama_api(self):
with tempfile.TemporaryDirectory() as directory:
name, tsv = lab.CASES[0]
report = lab.case_report(name, tsv, Path(directory))
server = mock.Mock(base="http://127.0.0.1:9999")
for model in lab.OLLAMA_MODELS:
backend = "ollama-" + model.replace(":", "-")
with mock.patch.object(lab, "request", return_value={"response": "{}", "eval_count": 2}) as call:
lab.answer(server, backend, model, report)
self.assertEqual(call.call_args.args[0], "http://127.0.0.1:9999/api/generate")
self.assertEqual(call.call_args.args[1]["model"], model)
self.assertEqual(call.call_args.args[1]["options"]["num_gpu"], 0)
def test_desired_state_cases_distinguish_known_from_unknown(self):
cases = dict(lab.CASES)
self.assertIn("intentionally", cases["runner_disabled"])
@ -58,7 +119,7 @@ class DoctorModelLabTests(unittest.TestCase):
lab.doctor.validate(response, report)
def test_memory_preflight_does_not_start_server(self):
with mock.patch.object(lab, "available_bytes", return_value=lab.START_AVAILABLE - 1), \
with mock.patch.object(lab, "wait_for_available_memory", side_effect=RuntimeError("Need at least 9 GiB")), \
mock.patch.object(lab.subprocess, "Popen") as launch:
server = lab.ScopedServer([], {}, "", "", Path("/unused"), "test")
with self.assertRaisesRegex(RuntimeError, "9 GiB"):