kpranav022's picture
Claude Opus 5.5 (1M context)
Stop paying twice, measure every run, and make the picture, voice and props hold up
13354e2
Raw History Blame Contribute Delete
9.4 kB
"""Run the creative pipeline over a fixed set of briefs and score it.
python scripts/eval.py # every brief in evals/briefs.jsonl
python scripts/eval.py --limit 5
python scripts/eval.py --compare evals/results/<baseline>.json
python scripts/eval.py --agent-models '{"script_generator":"gemini-3.1-pro-preview"}'
THIS MAKES PAID MODEL CALLS — every brief is a full generation. See evals/README.md.
Nothing reaches the database. The store is wrapped: evidence reads go to the real
Supabase (the brain is what makes a generation good, so an eval without it would
measure the wrong thing), while every write — the asset row, each agent_outputs
log, any insert or update — is kept in memory. Each brief runs under a synthetic
asset id that exists only in that memory.
"""
from __future__ import annotations
import argparse
import json
import statistics
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from uuid import UUID, uuid4
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
BRIEFS = ROOT / "evals" / "briefs.jsonl"
RESULTS = ROOT / "evals" / "results"
class EvalStore:
"""A SupabaseStore stand-in that can read the real one and never write to it.
Fails closed: only the named read methods pass through. Any other attribute —
including `client`, and any write method added to SupabaseStore later —
raises, so a new write path shows up as a crash in the eval, not a row in prod.
"""
READS = ("select", "count", "list_feedback")
def __init__(self, real: Any) -> None:
self._real = real
self.assets: dict[str, dict] = {}
self.logs: list[dict] = [] # every log_agent_output, in order
self.writes: list[tuple[str, tuple, dict]] = [] # every other captured write
def __getattr__(self, name: str) -> Any:
if name in self.READS:
return getattr(self._real, name)
raise AttributeError(f"EvalStore does not pass {name!r} through to the real store")
# --- the asset lives only here ---
def create_asset(self, payload: dict) -> dict:
row = {"id": str(uuid4()), "revision_counts": {}, "human_actions": [], **payload}
self.assets[str(row["id"])] = row
return row
def get_asset(self, asset_id: UUID | str) -> dict | None:
return self.assets.get(str(asset_id))
def update_asset(self, asset_id: UUID | str, values: dict) -> dict:
row = self.assets.setdefault(str(asset_id), {"id": str(asset_id)})
row.update(values)
return row
# --- the audit trail lives only here ---
def log_agent_output(self, asset_id, *, agent: str, stage: str, output: dict, schema_valid: bool = True) -> dict:
row = {
"asset_id": str(asset_id),
"agent": agent,
"stage": stage,
"output": {**output, "internal_agent": agent},
"schema_valid": schema_valid,
}
self.logs.append(row)
return row
def list_agent_outputs(self, asset_id: UUID | str) -> list[dict]:
return [r for r in self.logs if r["asset_id"] == str(asset_id)]
def insert(self, table: str, values: dict) -> dict:
self.writes.append(("insert", (table,), values))
return {"id": str(uuid4()), **values}
def update(self, table: str, filters: dict, values: dict) -> list[dict]:
self.writes.append(("update", (table, filters), values))
return []
def add_feedback(self, row: dict) -> dict:
self.writes.append(("add_feedback", (), row))
return row
def log_human_action(self, asset_id, *, action: str, detail: dict) -> dict:
self.writes.append(("log_human_action", (str(asset_id), action), detail))
return self.assets.get(str(asset_id), {})
def spend(logs: list[dict]) -> dict:
"""Cost and tokens summed from the captured agent_outputs payloads."""
total = {"cost_usd": 0.0, "input_tokens": 0, "output_tokens": 0, "cached_tokens": 0}
for row in logs:
out = row.get("output") or {}
total["cost_usd"] += float(out.get("cost_usd") or 0)
for key in ("input_tokens", "output_tokens", "cached_tokens"):
total[key] += int((out.get("usage") or {}).get(key) or 0)
total["cost_usd"] = round(total["cost_usd"], 6)
return total
def run_brief(real_store: Any, payload: dict) -> dict:
"""One generation, measured. An exception is a failed brief, not a failed eval."""
from app.schemas import GenerationRequest
from app.services.workflow import CreativeWorkflow
store = EvalStore(real_store)
brief = GenerationRequest.model_validate(payload)
asset_id = UUID(store.create_asset({"niche": brief.niche, "stage": "intake"})["id"])
record: dict[str, Any] = {"asset_id": str(asset_id), "niche": brief.niche}
started = time.perf_counter()
try:
result = CreativeWorkflow(store, asset_id, brief).execute()
winner = next(
c for c in result.candidates if c.candidate_number == result.recommended_candidate_number
)
record.update(
candidate_scores=[c.final_score for c in result.candidates],
passed=bool(winner.qa.passed),
winner_score=winner.final_score,
)
except Exception as exc: # noqa: BLE001 - recorded and counted as a fail
record.update(candidate_scores=[], passed=False, winner_score=None, error=str(exc))
record["latency_s"] = round(time.perf_counter() - started, 2)
record["revisions"] = int((store.assets[str(asset_id)].get("revision_counts") or {}).get("workflow", 0))
record.update(spend(store.logs))
return record
def summarize(records: list[dict]) -> dict:
"""Winner score is averaged over briefs that finished; a crash counts against
the pass rate instead, so neither number hides the other."""
scores = [r["winner_score"] for r in records if r.get("winner_score") is not None]
latencies = sorted(r["latency_s"] for r in records)
n = len(records)
def pct(p: float) -> float:
return latencies[min(n - 1, round(p * (n - 1)))] if n else 0.0
return {
"briefs": n,
"mean_winner_score": round(statistics.fmean(scores), 2) if scores else 0.0,
"pass_rate": round(sum(1 for r in records if r.get("passed")) / n, 4) if n else 0.0,
"mean_cost_usd": round(statistics.fmean(r["cost_usd"] for r in records), 6) if n else 0.0,
"p50_latency_s": pct(0.50),
"p95_latency_s": pct(0.95),
"errors": sum(1 for r in records if r.get("error")),
}
def compare(current: dict, baseline: dict, max_drop: float = 2.0) -> list[str]:
"""Regressions of `current` vs `baseline` summaries. Empty = no regression."""
problems = []
drop = baseline["mean_winner_score"] - current["mean_winner_score"]
if drop > max_drop:
problems.append(
f"mean winner score fell {drop:.2f} "
f"({baseline['mean_winner_score']} -> {current['mean_winner_score']}), limit {max_drop}"
)
if current["pass_rate"] < baseline["pass_rate"]:
problems.append(f"pass rate fell {baseline['pass_rate']} -> {current['pass_rate']}")
return problems
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--briefs", type=Path, default=BRIEFS)
parser.add_argument("--limit", type=int, default=None, help="run only the first N briefs")
parser.add_argument("--agent-models", default=None, help="JSON overriding AGENT_MODELS for this run")
parser.add_argument("--compare", type=Path, default=None, help="baseline results JSON")
parser.add_argument("--max-drop", type=float, default=2.0)
args = parser.parse_args(argv)
from app.core.config import settings
from app.services.supabase_store import SupabaseStore
if args.agent_models is not None:
settings.agent_models = json.loads(args.agent_models)
payloads = [json.loads(line) for line in args.briefs.read_text().splitlines() if line.strip()]
payloads = payloads[: args.limit] if args.limit else payloads
real = SupabaseStore()
records = []
for i, payload in enumerate(payloads, 1):
record = run_brief(real, payload)
records.append(record)
print(
f"[{i}/{len(payloads)}] {record['niche']}: score={record['winner_score']} "
f"passed={record['passed']} ${record['cost_usd']:.4f} {record['latency_s']}s"
+ (f" ERROR {record['error']}" if record.get("error") else "")
)
summary = summarize(records)
RESULTS.mkdir(parents=True, exist_ok=True)
out = RESULTS / f"{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json"
out.write_text(json.dumps(
{"agent_models": settings.agent_models, "gemini_model": settings.gemini_model,
"summary": summary, "briefs": records},
indent=2,
))
print(json.dumps(summary, indent=2))
print(f"wrote {out}")
if args.compare:
problems = compare(summary, json.loads(args.compare.read_text())["summary"], args.max_drop)
for problem in problems:
print(f"REGRESSION: {problem}")
return 1 if problems else 0
return 0
if __name__ == "__main__":
sys.exit(main())