mooncak397 Claude Opus 5.5 commited on
Commit ·
cfc0582
1
Parent(s): 59bc960
evals: per-case partial results and resume after a stop; app calls per case vs the 500/day quota
Browse filesprovider.py appends each finished case to <result>.partial.jsonl (EVAL_PARTIAL) and replays it on the
next run. run.py keeps the file only for the same prompt, profile, app code and model (fingerprint)
and deletes it when the result file is complete. summary prints avg/max app calls per case and how
many cases fit in 500 requests/day. Tests for timeout, quota stop, resume and the per-case line.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- evals/provider.py +23 -2
- evals/run.py +48 -1
- tests/test_eval_resume.py +100 -0
evals/provider.py
CHANGED
|
@@ -18,6 +18,7 @@ from app.texts import BUSY # noqa: E402
|
|
| 18 |
from evals import usage # noqa: E402
|
| 19 |
|
| 20 |
_graph = None
|
|
|
|
| 21 |
STOP = Path(__file__).resolve().parent / "results/.quota-day" # written on a daily-quota 429; run.py stops the run
|
| 22 |
|
| 23 |
|
|
@@ -54,10 +55,30 @@ def _quota_reset() -> str:
|
|
| 54 |
return reset.astimezone().strftime("%Y-%m-%d %H:%M %Z")
|
| 55 |
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
def call_api(prompt, options, context):
|
| 58 |
global _graph
|
| 59 |
if STOP.exists(): # the daily quota is gone: no more calls in this run
|
| 60 |
return {"error": "quota-day: run stopped"}
|
|
|
|
|
|
|
|
|
|
| 61 |
_graph = _graph or build_graph(get_model())
|
| 62 |
waits = 0
|
| 63 |
graph_log = logging.getLogger("app.graph")
|
|
@@ -87,5 +108,5 @@ def call_api(prompt, options, context):
|
|
| 87 |
return {"error": "rate limited after 6 tries"}
|
| 88 |
out = {"route": s["route"], "lang": s["lang"], "answer": s["messages"][-1].text,
|
| 89 |
"tool_calls": s["tool_calls"], "show_form": s["show_form"]}
|
| 90 |
-
return {"output": json.dumps(out, ensure_ascii=False),
|
| 91 |
-
|
|
|
|
| 18 |
from evals import usage # noqa: E402
|
| 19 |
|
| 20 |
_graph = None
|
| 21 |
+
_done = None # prompt -> saved result, loaded once per worker
|
| 22 |
STOP = Path(__file__).resolve().parent / "results/.quota-day" # written on a daily-quota 429; run.py stops the run
|
| 23 |
|
| 24 |
|
|
|
|
| 55 |
return reset.astimezone().strftime("%Y-%m-%d %H:%M %Z")
|
| 56 |
|
| 57 |
|
| 58 |
+
def _saved() -> dict:
|
| 59 |
+
"""Finished cases of a stopped run (EVAL_PARTIAL, set by run.py), keyed by the message."""
|
| 60 |
+
global _done
|
| 61 |
+
if _done is None:
|
| 62 |
+
p = os.environ.get("EVAL_PARTIAL")
|
| 63 |
+
rows = [json.loads(line) for line in open(p)] if p and Path(p).exists() else []
|
| 64 |
+
_done = {r["prompt"]: r for r in rows if "prompt" in r}
|
| 65 |
+
return _done
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _save(prompt, result: dict) -> dict:
|
| 69 |
+
if p := os.environ.get("EVAL_PARTIAL"):
|
| 70 |
+
with open(p, "a") as f: # one short line per case: appends from parallel workers do not mix
|
| 71 |
+
f.write(json.dumps({"prompt": prompt, **result}, ensure_ascii=False) + "\n")
|
| 72 |
+
return result
|
| 73 |
+
|
| 74 |
+
|
| 75 |
def call_api(prompt, options, context):
|
| 76 |
global _graph
|
| 77 |
if STOP.exists(): # the daily quota is gone: no more calls in this run
|
| 78 |
return {"error": "quota-day: run stopped"}
|
| 79 |
+
if prompt in _saved(): # resume: this case finished before the stop
|
| 80 |
+
r = _saved()[prompt]
|
| 81 |
+
return {"output": r["output"], "metadata": {**r.get("metadata", {}), "resumed": True}}
|
| 82 |
_graph = _graph or build_graph(get_model())
|
| 83 |
waits = 0
|
| 84 |
graph_log = logging.getLogger("app.graph")
|
|
|
|
| 108 |
return {"error": "rate limited after 6 tries"}
|
| 109 |
out = {"route": s["route"], "lang": s["lang"], "answer": s["messages"][-1].text,
|
| 110 |
"tool_calls": s["tool_calls"], "show_form": s["show_form"]}
|
| 111 |
+
return _save(prompt, {"output": json.dumps(out, ensure_ascii=False),
|
| 112 |
+
"metadata": {"llm_calls": counter.n, "rate_limited": waits}})
|
evals/run.py
CHANGED
|
@@ -4,6 +4,7 @@
|
|
| 4 |
uv run python evals/run.py version [--compare previous-official.json] one full judged run and the official row
|
| 5 |
uv run python evals/run.py release [--compare ...] 3 judged runs, majority, one row (resumes: an existing run file is kept)"""
|
| 6 |
import argparse
|
|
|
|
| 7 |
import json
|
| 8 |
import os
|
| 9 |
import subprocess
|
|
@@ -55,15 +56,46 @@ def run_eval(out: Path, ids=None, judge=True, delay=None, replay_from=None):
|
|
| 55 |
if replay_from: # grade saved answers again, no app call
|
| 56 |
env["REPLAY_FROM"] = str(replay_from)
|
| 57 |
cmd += ["-r", "file://replay.py"]
|
|
|
|
|
|
|
| 58 |
out.parent.mkdir(exist_ok=True)
|
| 59 |
out.unlink(missing_ok=True)
|
| 60 |
STOP.unlink(missing_ok=True)
|
| 61 |
subprocess.run(cmd, cwd=ROOT, env=env) # promptfoo exits non-zero when a case fails: not an error here
|
| 62 |
if STOP.exists(): # evals/provider.py hit the daily quota: this result file is incomplete
|
| 63 |
out.unlink(missing_ok=True)
|
| 64 |
-
sys.exit(f"Run stopped: {STOP.read_text().strip()}"
|
|
|
|
| 65 |
if not out.exists():
|
| 66 |
sys.exit(f"promptfoo wrote no result file: {out}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
|
| 69 |
def regrade_errors(out: Path, rounds: int = 2, pause: int | None = None):
|
|
@@ -113,9 +145,24 @@ def summary(out: Path, seconds: float):
|
|
| 113 |
print(f"{len(rs)} cases, {len(rs) - len(bad)} pass, {seconds:.0f} s, app calls {sum(m.get('llm_calls', 0) for m in meta)}, "
|
| 114 |
f"rate_limited {sum(m.get('rate_limited', 0) for m in meta)}")
|
| 115 |
print("failing:", " ".join(bad) or "none")
|
|
|
|
| 116 |
print("usage:", cost_report())
|
| 117 |
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
def main(argv=None):
|
| 120 |
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 121 |
sub = ap.add_subparsers(dest="mode", required=True)
|
|
|
|
| 4 |
uv run python evals/run.py version [--compare previous-official.json] one full judged run and the official row
|
| 5 |
uv run python evals/run.py release [--compare ...] 3 judged runs, majority, one row (resumes: an existing run file is kept)"""
|
| 6 |
import argparse
|
| 7 |
+
import hashlib
|
| 8 |
import json
|
| 9 |
import os
|
| 10 |
import subprocess
|
|
|
|
| 56 |
if replay_from: # grade saved answers again, no app call
|
| 57 |
env["REPLAY_FROM"] = str(replay_from)
|
| 58 |
cmd += ["-r", "file://replay.py"]
|
| 59 |
+
else: # evals/provider.py saves each finished case here and replays it after a stop
|
| 60 |
+
env["EVAL_PARTIAL"] = str(open_partial(out))
|
| 61 |
out.parent.mkdir(exist_ok=True)
|
| 62 |
out.unlink(missing_ok=True)
|
| 63 |
STOP.unlink(missing_ok=True)
|
| 64 |
subprocess.run(cmd, cwd=ROOT, env=env) # promptfoo exits non-zero when a case fails: not an error here
|
| 65 |
if STOP.exists(): # evals/provider.py hit the daily quota: this result file is incomplete
|
| 66 |
out.unlink(missing_ok=True)
|
| 67 |
+
sys.exit(f"Run stopped: {STOP.read_text().strip()}\n"
|
| 68 |
+
f"Run the same command again then: finished cases come from {partial_path(out).name}, no new calls.")
|
| 69 |
if not out.exists():
|
| 70 |
sys.exit(f"promptfoo wrote no result file: {out}")
|
| 71 |
+
partial_path(out).unlink(missing_ok=True) # the result file is complete
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def partial_path(out: Path) -> Path:
|
| 75 |
+
return out.with_name(out.stem + ".partial.jsonl")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def fingerprint() -> str:
|
| 79 |
+
"""Prompt, profile, app code and model: saved answers from other code must not be replayed."""
|
| 80 |
+
h = hashlib.sha256()
|
| 81 |
+
for f in [ROOT / "prompts/rules.md", ROOT / "profile/profile.md", *sorted((ROOT / "app").glob("*.py"))]:
|
| 82 |
+
h.update(f.read_bytes())
|
| 83 |
+
h.update((os.environ.get("PROVIDER_APP", "google") + os.environ.get("MODEL_APP", "")).encode())
|
| 84 |
+
return h.hexdigest()[:16]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def open_partial(out: Path) -> Path:
|
| 88 |
+
"""Keep the per-case JSONL of a stopped run with the same fingerprint, else start a new one."""
|
| 89 |
+
p, fp = partial_path(out), fingerprint()
|
| 90 |
+
lines = p.read_text().splitlines() if p.exists() else []
|
| 91 |
+
if lines and json.loads(lines[0]).get("fingerprint") == fp:
|
| 92 |
+
print(f"resuming {out.name}: {len(lines) - 1} finished cases in {p.name}")
|
| 93 |
+
return p
|
| 94 |
+
if lines:
|
| 95 |
+
print(f"{p.name} is from other code or another model: starting fresh")
|
| 96 |
+
p.parent.mkdir(exist_ok=True)
|
| 97 |
+
p.write_text(json.dumps({"fingerprint": fp}) + "\n")
|
| 98 |
+
return p
|
| 99 |
|
| 100 |
|
| 101 |
def regrade_errors(out: Path, rounds: int = 2, pause: int | None = None):
|
|
|
|
| 145 |
print(f"{len(rs)} cases, {len(rs) - len(bad)} pass, {seconds:.0f} s, app calls {sum(m.get('llm_calls', 0) for m in meta)}, "
|
| 146 |
f"rate_limited {sum(m.get('rate_limited', 0) for m in meta)}")
|
| 147 |
print("failing:", " ".join(bad) or "none")
|
| 148 |
+
print(calls_per_case(rs))
|
| 149 |
print("usage:", cost_report())
|
| 150 |
|
| 151 |
|
| 152 |
+
FREE_PER_DAY = 500 # gemini-3.5-flash-lite free tier: requests per day
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def calls_per_case(rs: list[dict]) -> str:
|
| 156 |
+
"""App calls per case (classify + answer + tool), to plan a run against the free daily quota."""
|
| 157 |
+
n = [(r["response"].get("metadata") or {}).get("llm_calls", 0) for r in rs]
|
| 158 |
+
avg = sum(n) / len(n) if n else 0
|
| 159 |
+
if not avg:
|
| 160 |
+
return "app calls per case: none logged"
|
| 161 |
+
i = max(range(len(n)), key=n.__getitem__)
|
| 162 |
+
return (f"app calls per case: avg {avg:.1f}, max {n[i]} ({rs[i]['testCase']['description']}); "
|
| 163 |
+
f"{FREE_PER_DAY} requests/day = about {int(FREE_PER_DAY // avg)} cases")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
def main(argv=None):
|
| 167 |
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 168 |
sub = ap.add_subparsers(dest="mode", required=True)
|
tests/test_eval_resume.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Eval runner gaps from the Gemini run: client timeout, daily-quota stop, per-case partial results and resume.
|
| 2 |
+
No key, no network: the graph and promptfoo are faked."""
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
from langchain_core.messages import AIMessage
|
| 8 |
+
|
| 9 |
+
from app.texts import BUSY
|
| 10 |
+
from evals import provider, run
|
| 11 |
+
|
| 12 |
+
STATE = {"route": "cv_question", "lang": "en", "tool_calls": [], "show_form": False}
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class FakeGraph:
|
| 16 |
+
"""Returns one reply; can log a model error the way app/graph.py's _call does."""
|
| 17 |
+
|
| 18 |
+
def __init__(self, reply="He works at DATEV.", error=None):
|
| 19 |
+
self.reply, self.error, self.calls = reply, error, 0
|
| 20 |
+
|
| 21 |
+
def invoke(self, _input, config=None):
|
| 22 |
+
self.calls += 1
|
| 23 |
+
if self.error is not None:
|
| 24 |
+
logging.getLogger("app.graph").warning("model_error", extra={"error": self.error})
|
| 25 |
+
return {**STATE, "messages": [AIMessage(self.reply)]}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@pytest.fixture
|
| 29 |
+
def fresh(tmp_path, monkeypatch):
|
| 30 |
+
monkeypatch.setattr(provider, "STOP", tmp_path / ".quota-day")
|
| 31 |
+
monkeypatch.setattr(provider, "_done", None)
|
| 32 |
+
monkeypatch.setenv("EVAL_PARTIAL", str(tmp_path / "v1.partial.jsonl"))
|
| 33 |
+
return tmp_path
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_daily_quota_stops_at_once_and_marks_the_case(fresh, monkeypatch):
|
| 37 |
+
monkeypatch.setenv("PROVIDER_APP", "google")
|
| 38 |
+
g = FakeGraph(reply=BUSY["en"], error=RuntimeError("429 RESOURCE_EXHAUSTED GenerateRequestsPerDayPerProjectPerModel"))
|
| 39 |
+
monkeypatch.setattr(provider, "_graph", g)
|
| 40 |
+
out = provider.call_api("Where does he work?", {}, {})
|
| 41 |
+
assert out["error"].startswith("quota-day") and g.calls == 1 # no retry
|
| 42 |
+
assert provider.STOP.exists() and "retry after" in provider.STOP.read_text()
|
| 43 |
+
assert provider.call_api("Next question?", {}, {})["error"].startswith("quota-day") and g.calls == 1
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_finished_cases_are_saved_and_replayed_on_resume(fresh, monkeypatch):
|
| 47 |
+
g = FakeGraph()
|
| 48 |
+
monkeypatch.setattr(provider, "_graph", g)
|
| 49 |
+
first = provider.call_api("Where does he work?", {}, {})
|
| 50 |
+
row = json.loads((fresh / "v1.partial.jsonl").read_text().splitlines()[-1])
|
| 51 |
+
assert row["prompt"] == "Where does he work?" and row["metadata"]["llm_calls"] == 0 # FakeGraph fires no callback
|
| 52 |
+
monkeypatch.setattr(provider, "_done", None) # a new process after a stop
|
| 53 |
+
again = provider.call_api("Where does he work?", {}, {})
|
| 54 |
+
assert again["output"] == first["output"] and again["metadata"]["resumed"] and g.calls == 1
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_run_eval_stops_on_the_quota_marker_and_keeps_the_partial_file(tmp_path, monkeypatch):
|
| 58 |
+
out = tmp_path / "v1-run1.json"
|
| 59 |
+
monkeypatch.setattr(run, "STOP", tmp_path / ".quota-day")
|
| 60 |
+
monkeypatch.setattr(provider, "STOP", tmp_path / ".quota-day")
|
| 61 |
+
|
| 62 |
+
def fake_promptfoo(cmd, cwd, env):
|
| 63 |
+
out.write_text("{}")
|
| 64 |
+
open(env["EVAL_PARTIAL"], "a").write(json.dumps({"prompt": "q", "output": "{}", "metadata": {}}) + "\n")
|
| 65 |
+
run.STOP.write_text("quota-day hit; retry after 2026-11-23 09:00")
|
| 66 |
+
|
| 67 |
+
monkeypatch.setattr(run.subprocess, "run", fake_promptfoo)
|
| 68 |
+
with pytest.raises(SystemExit, match="retry after 2026-11-23 09:00"):
|
| 69 |
+
run.run_eval(out)
|
| 70 |
+
assert not out.exists() # a stopped run file must not count as finished (release resume keeps run files)
|
| 71 |
+
assert run.partial_path(out).exists()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_partial_file_from_other_code_is_dropped(tmp_path, monkeypatch):
|
| 75 |
+
out = tmp_path / "v1.json"
|
| 76 |
+
p = run.partial_path(out)
|
| 77 |
+
p.write_text(json.dumps({"fingerprint": "old"}) + "\n" + json.dumps({"prompt": "q", "output": "{}"}) + "\n")
|
| 78 |
+
run.open_partial(out)
|
| 79 |
+
assert p.read_text().splitlines() == [json.dumps({"fingerprint": run.fingerprint()})]
|
| 80 |
+
p.write_text(p.read_text() + json.dumps({"prompt": "q", "output": "{}"}) + "\n")
|
| 81 |
+
run.open_partial(out) # same code: keep the finished cases
|
| 82 |
+
assert len(p.read_text().splitlines()) == 2
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_gemini_client_has_a_timeout(monkeypatch):
|
| 86 |
+
from app import llm
|
| 87 |
+
|
| 88 |
+
seen = {}
|
| 89 |
+
monkeypatch.setattr(llm, "load_dotenv", lambda: None)
|
| 90 |
+
monkeypatch.setattr(llm, "init_chat_model", lambda name, **k: seen.update(k))
|
| 91 |
+
monkeypatch.setenv("MODEL_APP", "gemini-x")
|
| 92 |
+
monkeypatch.setenv("GEMINI_API_KEY", "test")
|
| 93 |
+
monkeypatch.delenv("PROVIDER_APP", raising=False)
|
| 94 |
+
llm.get_model()
|
| 95 |
+
assert seen["timeout"] == 60
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_calls_per_case_line():
|
| 99 |
+
rs = [{"testCase": {"description": f"c{i}"}, "response": {"metadata": {"llm_calls": n}}} for i, n in enumerate([2, 2, 3, 1])]
|
| 100 |
+
assert run.calls_per_case(rs) == "app calls per case: avg 2.0, max 3 (c2); 500 requests/day = about 250 cases"
|