bhyve-workflow / eval /run_eval.py
akashdahad's picture
Deploy bhyve-workflow (FastAPI + embedded Postgres)
74d4552 verified
Raw History Blame Contribute Delete
6.47 kB
"""Extraction-quality eval harness.
Sweeps the thinking_budget (and is trivially extendable to other settings) and scores
the real pipeline against the gold standard Claude hand-built from the audit PDFs
(eval/gold_standard.json). It calls the LIVE Gemini API, so it CANNOT run until the
key is restricted (see the gemini-key-403 note) β€” by design this is the only step that
waits for the key; everything it exercises is already built and unit-tested.
Run: uv run python -m eval.run_eval # sweeps [0, 512, 2048]
uv run python -m eval.run_eval 0 1024 # custom budgets
What it measures, per (budget, file):
- coverage: extracted observation count vs gold count
- recall: of gold field-values, how many the pipeline captured (non-empty, grounded)
- accuracy: of captured values, how many match gold (normalized containment)
- cost: USD spent on that file (from the metered ledger delta)
It aligns extracted rows to gold rows in document order (both are emitted in order).
"""
import difflib
import json
import re
import sys
from pathlib import Path
from app import config
from app.compile import compile_to_engine
from app.engine import run_workflow
from app.llm import total_spend_usd
from app.parsing import parse_document
GOLD_PATH = Path(__file__).parent / "gold_standard.json"
# The benchmark use case (audit observations) β€” expressed as the authoring column-model,
# compiled to the engine exactly as a saved workflow would be. Generic engine, example config.
MODEL = {
"name": "Audit observations",
"anchor": "Observation",
"columns": [
{"name": "Company", "source": "per_document"},
{"name": "Process", "source": "per_document"},
{"name": "Period", "source": "per_document"},
{"name": "Observation", "description": "the full audit finding (what was found)", "source": "per_row"},
{"name": "Grading", "description": "the rating: Critical, Major, Medium, Low (or High/Medium/Low)", "source": "per_row"},
{"name": "Root Cause", "description": "the root-cause category or code", "source": "per_row"},
{"name": "Risk & Impact", "source": "per_row"},
{"name": "Recommendation", "source": "per_row"},
{"name": "Management Response", "source": "per_row"},
{"name": "Responsible Official", "source": "per_row"},
{"name": "Target Completion Date", "source": "per_row"},
],
}
# gold key -> output column name
FIELDS = {
"observation": "Observation", "grading": "Grading", "root_cause": "Root Cause",
"risk_impact": "Risk & Impact", "recommendation": "Recommendation",
"management_response": "Management Response", "responsible_official": "Responsible Official",
"target_completion_date": "Target Completion Date",
}
def _norm(s):
return re.sub(r"[^a-z0-9]", "", str(s or "").lower())
def _match(extracted_val, gold_val):
a, b = _norm(extracted_val), _norm(gold_val)
if not b:
return None # gold is blank here -> not scored
if not a:
return False
return a in b or b in a or a[:24] == b[:24]
def _align(rows, gobs):
"""Greedily pair each gold observation with the extracted row whose Observation text
matches best (NOT by index β€” coverage differs, so index-alignment compares the wrong
findings). Returns [(gold_obs, row_or_None)]."""
used, pairs = set(), []
for g in gobs:
gt = g.get("observation", "")
best, best_s = -1, 0.0
for ri, row in enumerate(rows):
if ri in used:
continue
s = difflib.SequenceMatcher(None, _norm(gt), _norm((row.get("Observation") or {}).get("value", ""))).ratio()
if s > best_s:
best_s, best = s, ri
row = rows[best] if (best >= 0 and best_s >= 0.4) else None
if row is not None:
used.add(best)
pairs.append((g, row))
return pairs
def score_file(gold, model_def):
path = gold["path"]
doc = parse_document(Path(path).name, open(path, "rb").read())
res = run_workflow(model_def, doc, {})
rows = res.rows if res.status == "succeeded" else []
gobs = gold["observations"]
pairs = _align(rows, gobs)
matched = sum(1 for _, r in pairs if r is not None)
recall_hit = recall_tot = acc_hit = acc_tot = 0
for g, row in pairs:
for gkey, col in FIELDS.items():
gv = g.get(gkey, "")
if not _norm(gv):
continue
recall_tot += 1
ev = (row.get(col) or {}).get("value", "") if row else ""
if _norm(ev):
recall_hit += 1
acc_tot += 1
if _match(ev, gv):
acc_hit += 1
return {
"file": gold["file"], "status": res.status,
"gold_obs": len(gobs), "got_obs": len(rows), "matched": matched,
"recall": (recall_hit / recall_tot) if recall_tot else 0.0,
"accuracy": (acc_hit / acc_tot) if acc_tot else 0.0,
}
def main():
budgets = [int(x) for x in sys.argv[1:]] or [0, 512, 2048]
if not GOLD_PATH.exists():
print(f"Gold standard not found at {GOLD_PATH} β€” build it first (build-gold-standard workflow).")
return
gold = json.loads(GOLD_PATH.read_text())
model_def = compile_to_engine(MODEL)
import app.blocks.extract # noqa: ensure settings is the same object the block reads
print(f"{'budget':>7} {'file':<10} {'status':<10} {'got/gold':<9} {'matched':>8} {'recall':>7} {'accuracy':>9} {'cost$':>8}")
for b in budgets:
config.settings.gemini_thinking_budget = b
from app.db import SessionLocal
for g in gold:
tag = Path(g["file"]).name.split("_")[2] if "_" in Path(g["file"]).name else Path(g["file"]).name[:10]
db = SessionLocal()
before = total_spend_usd(db); db.close()
try:
s = score_file(g, model_def)
except Exception as e:
print(f"{b:>7} {tag[:10]:<10} ERROR {str(e)[:60]}")
continue
db = SessionLocal(); after = total_spend_usd(db); db.close()
print(f"{b:>7} {tag[:10]:<10} {s['status']:<10} "
f"{str(s['got_obs'])+'/'+str(s['gold_obs']):<9} "
f"{str(s['matched'])+'/'+str(s['gold_obs']):>8} "
f"{s['recall']*100:>6.1f}% {s['accuracy']*100:>8.1f}% {after-before:>8.4f}")
if __name__ == "__main__":
main()