"""Run a test set through the API and record, per question, the rules, the answer path and where it failed. .venv/bin/python test/rule_trace/run.py --cases SET.json --out RESULTS.jsonl [--hours 4.25] [--resume] [--only-failed OLD.jsonl] [--base http://localhost:8000] Questions run one after another (nothing else may use the API meanwhile). Each row holds the static tags (static_tags.py), the answer, the route of the backend (tools/answers/route_trace.py, read from data/logs/answer_timings.jsonl), the checks and the failure point. The run stops after --hours and continues with --resume. """ from __future__ import annotations import argparse import hashlib import json import sys import time import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[2] for path in (str(ROOT), str(Path(__file__).resolve().parent)): if path not in sys.path: sys.path.insert(0, path) from scoring import check, failure_point, last_branch # noqa: E402 from static_tags import tags # noqa: E402 TIMINGS = ROOT / "data" / "logs" / "answer_timings.jsonl" def _env(name: str) -> str: from tools.evaluation.gold_set import _env as env return env(name) def ask(base: str, question: str, engine: str, token: str | None) -> dict: body = {"query": question, "engine": engine, **({"context_token": token} if token else {})} request = urllib.request.Request(base.rstrip("/") + "/answer", data=json.dumps(body, ensure_ascii=False).encode(), headers={"Content-Type": "application/json", "X-API-Key": _env("SEARCH_API_KEY")}) with urllib.request.urlopen(request, timeout=300) as response: return json.load(response) def trace_of(question: str, offset: int) -> dict: """The timing record of this question: the last line written after `offset` with its hash.""" digest = hashlib.sha256(question.strip().encode()).hexdigest()[:12] try: with TIMINGS.open("rb") as handle: handle.seek(offset) lines = handle.read().decode("utf-8", "ignore").splitlines() except OSError: return {} for line in reversed(lines): try: row = json.loads(line) except ValueError: continue if row.get("q") == digest: return row return {} def run_case(case: dict, base: str) -> dict: token, result, steps = None, {}, [] started = time.time() for question in [s.strip() for s in case["question"].split(" => ") if s.strip()]: offset = TIMINGS.stat().st_size if TIMINGS.exists() else 0 t = time.time() try: result = ask(base, question, case["engine"], token) except Exception as error: # a failed request is a failed case, never skipped result = {"status": "request_error", "reason": repr(error)[:200], "answer": ""} trace = trace_of(question, offset) token = (result.get("conversation_context") or {}).get("token") or token steps.append({"question": question, "status": result.get("status"), "reason": result.get("reason"), "seconds": round(time.time() - t, 1), "route": trace.get("route") or [], "notes": trace.get("notes") or {}, "parts": trace.get("steps") or {}, "model_calls": trace.get("model_calls"), "answer": (result.get("answer") or "")[:600]}) if result.get("status") == "request_error": break return {"result": result, "steps": steps, "seconds": round(time.time() - started, 1)} def main(argv=None) -> int: parser = argparse.ArgumentParser() parser.add_argument("--cases", required=True) parser.add_argument("--out", required=True) parser.add_argument("--base", default="http://localhost:8000") parser.add_argument("--hours", type=float, default=4.25) parser.add_argument("--resume", action="store_true") parser.add_argument("--only-failed", help="results of an earlier run: ask again only its failed cases") args = parser.parse_args(argv) cases = json.loads(Path(args.cases).read_text(encoding="utf-8"))["cases"] if args.only_failed: failed = {json.loads(l)["id"] for l in Path(args.only_failed).read_text(encoding="utf-8").splitlines() if l.strip() and not json.loads(l)["pass"]} cases = [c for c in cases if c["id"] in failed] out = Path(args.out) done = set() if args.resume and out.exists(): done = {json.loads(l)["id"] for l in out.read_text(encoding="utf-8").splitlines() if l.strip()} deadline = time.time() + args.hours * 3600 todo = [c for c in cases if c["id"] not in done] print(f"{len(todo)} otázok, limit {args.hours} h", flush=True) with out.open("a" if args.resume else "w", encoding="utf-8") as handle: for n, case in enumerate(todo, 1): if time.time() > deadline: print("Časový limit: zvyšok pokračuje s --resume.", flush=True) break static = tags(case["question"]) ran = run_case(case, args.base) last = ran["steps"][-1] if ran["steps"] else {} trace = {"route": last.get("route"), "notes": last.get("notes")} checks = check(case, ran["result"]) point = failure_point(case, ran["result"], checks, trace) row = {"id": case["id"], "engine": case["engine"], "category": case.get("category"), "difficulty": case.get("difficulty"), "template": case.get("template"), "origin": case.get("origin"), "question": case["question"], "pass": point is None, "failure_point": point, "failed_checks": [k for k, v in checks.items() if not v], "branch": last_branch(last.get("route") or []), "static": static, "seconds": ran["seconds"], "status": ran["result"].get("status"), "reason": ran["result"].get("reason"), "answer": (ran["result"].get("answer") or "")[:2500], "source_urls": (ran["result"].get("source_urls") or [])[:12], "steps": ran["steps"]} handle.write(json.dumps(row, ensure_ascii=False) + "\n") handle.flush() print(f"{n:04d} {case['id']:<14} {case['engine']:<8} {'PASS' if row['pass'] else 'FAIL'} {ran['seconds']:>6}s " f"{(point or '')[:70]}", flush=True) return 0 if __name__ == "__main__": raise SystemExit(main())