farient-deckcheck / scripts /calibrate.py
Xander Labide
Claude Opus 4.7 (1M context)
Initial commit — Farient DeckCheck
fdfe81a
Raw History Blame Contribute Delete
9.97 kB
"""Calibration harness CLI for the Farient brand-review agentic system.
Usage
-----
cd apps/api
uv run python -m scripts.calibrate \\
--deck "../../Doc Reference/Annotated_20260511 IDEXX Peer Group Assessment - DRAFT 20260330 (3).pptx" \\
--out calibration_report.md \\
--json calibration_report.json \\
[--cached]
Options
-------
--deck PATH Path to the annotated IDEXX .pptx file.
--out PATH Output path for the Markdown report. [default: calibration_report.md]
--json PATH Output path for the JSON report. [default: calibration_report.json]
--cached Re-use the most recent cached agent run from calibration_runs/<ts>/
instead of calling OpenAI. Critical for re-grading without re-paying.
Caching
-------
Each live run writes its FinalAuditResult JSON to:
calibration_runs/<ISO-timestamp>/final.json
Pass --cached to load the latest directory. You can also seed
calibration_runs/synthetic/final.json
with hand-crafted data for smoke-testing without any OpenAI calls.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import logging
import os
import sys
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
# Load apps/api/.env (gitignored) so the CLI picks up OPENAI_API_KEY without
# requiring a shell export. Real shell env still wins (override=False).
from dotenv import load_dotenv as _load_dotenv
_load_dotenv(Path(__file__).resolve().parent.parent / ".env", override=True)
# ---- ensure apps/api is on sys.path when run as -m scripts.calibrate -------
_HERE = Path(__file__).resolve().parent # apps/api/scripts/
_API_ROOT = _HERE.parent # apps/api/
if str(_API_ROOT) not in sys.path:
sys.path.insert(0, str(_API_ROOT))
from agents.output_schemas import FinalAuditResult # noqa: E402
from scripts.grader import grade # noqa: E402
from scripts.ground_truth import extract_ground_truth # noqa: E402
from scripts.report import write_report # noqa: E402
logger = logging.getLogger(__name__)
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s %(name)s %(message)s",
)
# ---------------------------------------------------------------------------
# Cache helpers
# ---------------------------------------------------------------------------
_RUNS_DIR = _API_ROOT / "calibration_runs"
def _list_cached_runs() -> list[Path]:
"""Return calibration_runs/* dirs sorted oldest→newest."""
if not _RUNS_DIR.exists():
return []
return sorted(
[d for d in _RUNS_DIR.iterdir() if d.is_dir() and (d / "final.json").exists()]
)
def _latest_cached_run() -> Path | None:
runs = _list_cached_runs()
return runs[-1] if runs else None
def _save_run(result: FinalAuditResult) -> Path:
"""Write FinalAuditResult JSON to calibration_runs/<timestamp>/final.json."""
ts = datetime.now(tz=timezone.utc).strftime("%Y%m%dT%H%M%SZ")
run_dir = _RUNS_DIR / ts
run_dir.mkdir(parents=True, exist_ok=True)
out = run_dir / "final.json"
out.write_text(
json.dumps(result.model_dump(), indent=2, ensure_ascii=False),
encoding="utf-8",
)
logger.info("Agent output cached → %s", out)
return run_dir
def _load_cached_run(run_dir: Path) -> FinalAuditResult:
"""Load and validate a cached FinalAuditResult from *run_dir/final.json*."""
payload = json.loads((run_dir / "final.json").read_text(encoding="utf-8"))
return FinalAuditResult.model_validate(payload)
# ---------------------------------------------------------------------------
# FindingLike adapter (wraps FinalAuditResult findings for grader)
# ---------------------------------------------------------------------------
@dataclass
class _FindingAdapter:
"""Thin wrapper so agent Finding fields satisfy grader.FindingLike."""
category: str
def _build_agent_findings(
result: FinalAuditResult,
) -> dict[int, list[_FindingAdapter]]:
"""Extract ``{slide_n: [FindingAdapter, ...]}`` from a FinalAuditResult."""
out: dict[int, list[_FindingAdapter]] = {}
for slide_env in result.slides:
adapters = [_FindingAdapter(category=f.category) for f in slide_env.findings]
if adapters:
out[slide_env.slide_number] = adapters
return out
# ---------------------------------------------------------------------------
# Live agent run
# ---------------------------------------------------------------------------
async def _run_live(deck_path: Path, job_id: str) -> FinalAuditResult:
"""Run the full agent pipeline against *deck_path* and return the result."""
# Import here to avoid loading the agent stack when running --cached.
from agents.runner import run_audit # noqa: PLC0415
from agents.context import AuditContext # noqa: PLC0415
from rubric.loader import load_rubric # noqa: PLC0415
from services.parser import parse_deck # noqa: PLC0415
from services.renderer import render_deck # noqa: PLC0415
logger.info("Parsing deck: %s", deck_path)
parsed = parse_deck(deck_path)
logger.info("Rendering deck (%d slides)…", parsed.slide_count)
render_result = render_deck(deck_path, out_dir=_API_ROOT / "tmp" / job_id)
logger.info("Loading rubric…")
rubric = load_rubric()
ctx = AuditContext(
parsed_deck=parsed,
render_result=render_result,
rubric=rubric,
out_dir=_API_ROOT / "tmp" / job_id,
)
logger.info("Running agentic audit (this may take a few minutes)…")
result = await run_audit(ctx, job_id, file_name=deck_path.name)
return result
# ---------------------------------------------------------------------------
# CLI entry point
# ---------------------------------------------------------------------------
def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
prog="scripts.calibrate",
description=(
"Calibration harness: run the agentic review on an annotated IDEXX deck "
"and produce a precision/recall report."
),
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
parser.add_argument(
"--deck",
required=True,
metavar="PATH",
help="Path to the annotated IDEXX .pptx file.",
)
parser.add_argument(
"--out",
default="calibration_report.md",
metavar="PATH",
help="Output path for the Markdown report. [default: calibration_report.md]",
)
parser.add_argument(
"--json",
default="calibration_report.json",
metavar="PATH",
dest="json_out",
help="Output path for the JSON report. [default: calibration_report.json]",
)
parser.add_argument(
"--cached",
action="store_true",
help=(
"Re-use the most recent cached agent output instead of calling OpenAI. "
"Looks for calibration_runs/<latest>/final.json."
),
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
args = _parse_args(argv)
deck_path = Path(args.deck).resolve()
if not deck_path.exists():
logger.error("Deck not found: %s", deck_path)
return 1
out_md = Path(args.out)
out_json = Path(args.json_out)
# ---- Obtain agent result (cached or live) --------------------------------
run_id: str | None = None
if args.cached:
run_dir = _latest_cached_run()
if run_dir is None:
logger.error(
"--cached specified but no calibration_runs/ directory found. "
"Run without --cached first, or seed calibration_runs/synthetic/final.json."
)
return 1
logger.info("Loading cached run: %s", run_dir)
result = _load_cached_run(run_dir)
run_id = run_dir.name
else:
job_id = f"calib_{datetime.now(tz=timezone.utc).strftime('%Y%m%dT%H%M%SZ')}"
result = asyncio.run(_run_live(deck_path, job_id))
run_dir = _save_run(result)
run_id = run_dir.name
# ---- Extract ground truth -----------------------------------------------
logger.info("Extracting ground-truth notes from deck…")
raw_notes, ground_truth = extract_ground_truth(deck_path)
logger.info(
"Ground truth: %d slides with annotated eval categories",
len(ground_truth),
)
# ---- Build agent findings dict ------------------------------------------
agent_findings = _build_agent_findings(result)
logger.info(
"Agent findings: %d slides with findings",
len(agent_findings),
)
# ---- Grade ---------------------------------------------------------------
grade_result = grade(
agent_findings,
ground_truth,
total_slides=result.slide_count,
)
# ---- Report --------------------------------------------------------------
trace_url_base = os.environ.get("OPENAI_TRACE_URL_BASE", "")
write_report(
grade_result,
raw_notes,
deck_path,
out_md=out_md,
out_json=out_json,
run_id=run_id,
trace_url_base=trace_url_base or None,
)
# ---- Print summary -------------------------------------------------------
status = "PASS" if grade_result.pass_bar else "FAIL"
print(f"\nCalibration complete — pass-bar: {status}")
print(f" Eval categories with ≥1 TP: {grade_result.categories_with_tp}/6")
print(f" Deck recall: {_fmt_pct(grade_result.deck_recall)}")
print(f" Deck precision: {_fmt_pct(grade_result.deck_precision)}")
print(f" Report: {out_md}")
print(f" JSON: {out_json}")
return 0
def _fmt_pct(v: float | None) -> str:
return f"{v * 100:.1f}%" if v is not None else "N/A"
if __name__ == "__main__":
sys.exit(main())