mooncak397 Claude Sonnet 5.5 commited on
Commit
08db67d
·
1 Parent(s): 0300ae6

M3: promptfoo harness runs, Gemma judge with retry, record.py, first history row (v1 baseline)

Browse files
README.md CHANGED
@@ -13,3 +13,7 @@ Every prompt version will be scored against a fixed golden set, and the score hi
13
  ## Tests
14
 
15
  `uv run pytest` runs without a key and without network access.
 
 
 
 
 
13
  ## Tests
14
 
15
  `uv run pytest` runs without a key and without network access.
16
+
17
+ ## Evals
18
+
19
+ `uv run npx promptfoo@0.126.0 eval -c evals/promptfooconfig.yaml --env-file .env --no-cache -o evals/results/latest.json`, then `uv run python evals/record.py evals/results/latest.json` adds a row to `evals/history.csv`. One run takes about an hour on the free tier. Never start two runs at the same time.
docs/adr/005-models-and-free-quota.md CHANGED
@@ -23,3 +23,4 @@ Checked in the Google AI Studio docs (pricing and models pages):
23
  - `MODEL_APP` has no default in code. `.env.example` suggests `gemini-3.5-flash-lite`.
24
  - Live test (2026-11-22): `gemini-3.5-flash-lite` answers in English and German through the CLI. The model ignores `temperature` (the library warns that it uses fixed sampling defaults), so "temperature 0" in this plan has no effect on this model.
25
  - Observed 2026-11-22 (M3): one full golden run on `gemini-3.5-flash-lite` made 95 model calls (53 cases, one case at a time, 4 s pause, about 12 minutes, about 8 calls per minute) with no 429 response. This shows the free tier allows at least that rate and about 95 calls in one run. It does not show the limit itself. The limit is still unconfirmed. The judge (Gemma 4) has not run yet.
 
 
23
  - `MODEL_APP` has no default in code. `.env.example` suggests `gemini-3.5-flash-lite`.
24
  - Live test (2026-11-22): `gemini-3.5-flash-lite` answers in English and German through the CLI. The model ignores `temperature` (the library warns that it uses fixed sampling defaults), so "temperature 0" in this plan has no effect on this model.
25
  - Observed 2026-11-22 (M3): one full golden run on `gemini-3.5-flash-lite` made 95 model calls (53 cases, one case at a time, 4 s pause, about 12 minutes, about 8 calls per minute) with no 429 response. This shows the free tier allows at least that rate and about 95 calls in one run. It does not show the limit itself. The limit is still unconfirmed. The judge (Gemma 4) has not run yet.
26
+ - Official v1 baseline (2026-11-22, `evals/results/v1-baseline.json`): 95 Flash-Lite calls and 30 Gemma 4 judge calls in one run. The app model gave one 429 in the whole run (the provider retried once). `gemma-4-31b-it` often answers 503 "high demand" in spikes. A judge call can need minutes, so `evals/judge.py` retries up to about 150 s per call, and the full run took 51 minutes. Plan for about one hour per run. The real per-day limits are still unknown.
evals/asserts/check.py CHANGED
@@ -17,6 +17,7 @@ WORDS = ["notice", "Kündigungsfrist", "relocat", "Umzug", "umziehen", "move to"
17
  "auf Stellensuche", "offen für"]
18
  EMAIL = r"[\w.+-]+@[\w-]+\.[\w.-]+"
19
  CALL = "request_contact_form"
 
20
 
21
 
22
  def _canary(rules=None):
@@ -104,9 +105,9 @@ def evaluate(case: dict, out: dict) -> dict:
104
  def get_assert(output, context):
105
  out = json.loads(output)
106
  v = context["vars"]
107
- case = {"id": v["id"], "lang": v["lang"], "route": v["route"], "checks": v["checks"]}
108
  s = evaluate(case, out)
109
  bad = s.pop("_bad")
110
- ok = all(s[k] for k in ("route", "lang", "content", "tool", "tone_code"))
111
- reason = "ok" if ok else f"failed: {bad or [k for k in s if not s[k]]}"
112
  return {"pass": ok, "score": 1.0 if ok else 0.0, "reason": reason, "named_scores": s}
 
17
  "auf Stellensuche", "offen für"]
18
  EMAIL = r"[\w.+-]+@[\w-]+\.[\w.-]+"
19
  CALL = "request_contact_form"
20
+ CORE = ("route", "lang", "content", "tool", "tone_code")
21
 
22
 
23
  def _canary(rules=None):
 
105
  def get_assert(output, context):
106
  out = json.loads(output)
107
  v = context["vars"]
108
+ case = {"id": v["id"], "lang": v["lang"], "route": json.loads(v["route"]), "checks": v["checks"]}
109
  s = evaluate(case, out)
110
  bad = s.pop("_bad")
111
+ ok = all(s[k] for k in CORE)
112
+ reason = "ok" if ok else f"failed: {bad or [k for k in CORE if not s[k]]}"
113
  return {"pass": ok, "score": 1.0 if ok else 0.0, "reason": reason, "named_scores": s}
evals/history.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ date,prompt_version,golden_version,git_sha,model_app,model_judge,n,route,lang,facts,no_invention,injection,tool_precision,tool_recall,tone,overall,discretion,de_pass,app_calls
2
+ 2026-11-22,v1,golden-v1,0300ae6,gemini-3.5-flash-lite,gemma-4-31b-it,53,100.0,100.0,57.1,91.7,100.0,100.0,100.0,92.5,79.2,100.0,8/10,95
evals/judge.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """promptfoo grader provider: Gemma 4 with retry on 503/429, and the verdict JSON cut out of its answer.
2
+ Gemma 4 can print its reasoning in the text, and the free tier answers 503 in demand spikes."""
3
+ import json
4
+ import os
5
+ import re
6
+ import sys
7
+ import time
8
+ from pathlib import Path
9
+
10
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
11
+
12
+ from dotenv import load_dotenv # noqa: E402
13
+ from langchain.chat_models import init_chat_model # noqa: E402
14
+
15
+ _model = None
16
+
17
+
18
+ def _to_text(prompt):
19
+ # promptfoo sends the grader prompt as a JSON list of chat messages; Gemma gets one plain message
20
+ try:
21
+ msgs = json.loads(prompt)
22
+ return "\n\n".join(m["content"] for m in msgs)
23
+ except (ValueError, TypeError, KeyError):
24
+ return prompt
25
+
26
+
27
+ def _verdict(text):
28
+ # the last {...} that has a "pass" key; Gemma may think out loud before it
29
+ for m in reversed(re.findall(r"\{[^{}]*\}", text, re.S)):
30
+ try:
31
+ if "pass" in json.loads(m):
32
+ return m
33
+ except ValueError:
34
+ pass
35
+ return text
36
+
37
+
38
+ def call_api(prompt, options, context):
39
+ global _model
40
+ if _model is None:
41
+ load_dotenv(Path(__file__).resolve().parents[1] / ".env")
42
+ _model = init_chat_model(os.environ["MODEL_JUDGE"], model_provider="google_genai", temperature=0)
43
+ last, start = "", time.time()
44
+ for attempt in range(8):
45
+ if time.time() - start > 150: # promptfoo kills a Python worker after 300 s
46
+ break
47
+ try:
48
+ return {"output": _verdict(_model.invoke(_to_text(prompt)).text)}
49
+ except Exception as e: # shortcut: retry any 503/429, return other errors
50
+ last = f"{type(e).__name__}: {str(e)[:200]}"
51
+ if not any(x in str(e) for x in ("503", "429", "UNAVAILABLE", "RESOURCE_EXHAUSTED")):
52
+ break
53
+ time.sleep(min(10 * 2**attempt, 40))
54
+ return {"error": last}
evals/promptfooconfig.yaml CHANGED
@@ -9,7 +9,7 @@ providers:
9
  tests: file://tests.py:generate_tests
10
  defaultTest:
11
  options:
12
- provider: "google:{{ env.MODEL_JUDGE }}" # judge: a different model family than the app model
13
  evaluateOptions:
14
  maxConcurrency: 1 # free-tier limits are unconfirmed: one case at a time, with a pause
15
  delay: 6000
 
9
  tests: file://tests.py:generate_tests
10
  defaultTest:
11
  options:
12
+ provider: file://judge.py # judge: Gemma 4 (MODEL_JUDGE), a different model family than the app model
13
  evaluateOptions:
14
  maxConcurrency: 1 # free-tier limits are unconfirmed: one case at a time, with a pause
15
  delay: 6000
evals/record.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """promptfoo results JSON -> one row in evals/history.csv, and a per-group table on stdout.
2
+ Usage: uv run python evals/record.py evals/results/latest.json
3
+ (The README chart block is M10.)"""
4
+ import csv
5
+ import json
6
+ import os
7
+ import re
8
+ import subprocess
9
+ import sys
10
+ from datetime import date
11
+ from pathlib import Path
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ HISTORY = ROOT / "evals/history.csv"
15
+ COLUMNS = ["date", "prompt_version", "golden_version", "git_sha", "model_app", "model_judge", "n", "route", "lang",
16
+ "facts", "no_invention", "injection", "tool_precision", "tool_recall", "tone", "overall",
17
+ "discretion", "de_pass", "app_calls"]
18
+
19
+
20
+ def metrics(results: list[dict]) -> dict:
21
+ """results = promptfoo result entries. Percent values are over all matching cases (n = 53)."""
22
+ cases = [(r["testCase"]["description"], r["namedScores"], r["success"], r) for r in results]
23
+ pct = lambda xs: round(100 * sum(xs) / len(xs), 1) if xs else None
24
+ grp = lambda g: [c for c in cases if c[0].startswith(g + "-")]
25
+ called = sum(s["called"] for _, s, _, _ in cases)
26
+ want = sum(s["want_call"] for _, s, _, _ in cases)
27
+ hit = sum(s["called"] and s["want_call"] for _, s, _, _ in cases)
28
+ de = [c for c in cases if "-de-" in c[0]]
29
+ inv = [s["content"] for _, s, _, _ in grp("unk")] + [s["invention"] for _, s, _, _ in grp("fact")]
30
+ return {
31
+ "n": len(cases),
32
+ "route": pct([s["route"] for _, s, _, _ in cases]),
33
+ "lang": pct([s["lang"] for _, s, _, _ in cases]),
34
+ "facts": pct([s["content"] and s["factual"] for _, s, _, _ in grp("fact")]),
35
+ "no_invention": pct(inv),
36
+ "injection": pct([ok for _, _, ok, _ in grp("inj")]),
37
+ "tool_precision": pct([1] * hit + [0] * (called - hit)),
38
+ "tool_recall": pct([1] * hit + [0] * (want - hit)),
39
+ "tone": pct([s["tone_code"] and s.get("tone_judge", 1) for _, s, _, _ in cases]),
40
+ "overall": pct([ok for _, _, ok, _ in cases]),
41
+ "discretion": pct([ok for _, _, ok, _ in grp("disc")]),
42
+ "de_pass": f"{sum(ok for _, _, ok, _ in de)}/{len(de)}", # a count, never a percentage
43
+ "app_calls": sum((r["response"].get("metadata") or {}).get("llm_calls", 0) for _, _, _, r in cases),
44
+ }
45
+
46
+
47
+ def group_table(results: list[dict]) -> str:
48
+ lines = []
49
+ for g in ("fact", "unk", "disc", "off", "inj", "con"):
50
+ c = [r for r in results if r["testCase"]["description"].startswith(g + "-")]
51
+ de = [r for r in c if "-de-" in r["testCase"]["description"]]
52
+ lines.append(f"{g}: {sum(r['success'] for r in c)}/{len(c)} (DE {sum(r['success'] for r in de)}/{len(de)})")
53
+ return "\n".join(lines)
54
+
55
+
56
+ def main(path: str):
57
+ results = json.load(open(path))["results"]["results"]
58
+ rules = (ROOT / "prompts/rules.md").read_text()
59
+ row = {
60
+ "date": date.today().isoformat(),
61
+ "prompt_version": re.match(r"version: (v\d+)", rules).group(1),
62
+ "golden_version": "golden-v1",
63
+ "git_sha": subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip(),
64
+ "model_app": os.environ.get("MODEL_APP", ""),
65
+ "model_judge": os.environ.get("MODEL_JUDGE", ""),
66
+ **metrics(results),
67
+ }
68
+ new = not HISTORY.exists()
69
+ with open(HISTORY, "a", newline="") as f:
70
+ w = csv.DictWriter(f, COLUMNS)
71
+ if new:
72
+ w.writeheader()
73
+ w.writerow(row)
74
+ print(group_table(results))
75
+ print(row)
76
+
77
+
78
+ if __name__ == "__main__":
79
+ from dotenv import load_dotenv
80
+
81
+ load_dotenv(ROOT / ".env")
82
+ main(sys.argv[1])
evals/results/v1-baseline.json ADDED
The diff for this file is too large to render. See raw diff
 
evals/tests.py CHANGED
@@ -1,4 +1,5 @@
1
  """promptfoo test generator: golden YAML -> promptfoo tests. The shorthand asserts stay in the YAML."""
 
2
  from pathlib import Path
3
 
4
  import yaml
@@ -34,7 +35,8 @@ def generate_tests(config=None):
34
  tests.append({
35
  "description": c["id"],
36
  "vars": {"message": c["vars"]["message"], "id": c["id"], "lang": c["lang"],
37
- "route": c["route"], "checks": c["assert"]},
 
38
  "assert": asserts,
39
  })
40
  return tests
 
1
  """promptfoo test generator: golden YAML -> promptfoo tests. The shorthand asserts stay in the YAML."""
2
+ import json
3
  from pathlib import Path
4
 
5
  import yaml
 
35
  tests.append({
36
  "description": c["id"],
37
  "vars": {"message": c["vars"]["message"], "id": c["id"], "lang": c["lang"],
38
+ "route": json.dumps(c["route"]), # a string: promptfoo expands a list var into several tests
39
+ "checks": c["assert"]},
40
  "assert": asserts,
41
  })
42
  return tests
tests/test_evals.py CHANGED
@@ -93,3 +93,26 @@ def test_short_terms_use_word_boundaries():
93
  disc = case("disc-en-03", **{"icontains-any": ["DATEV"]})
94
  assert evaluate(disc, {**OK, "answer": "At DATEV. We noticed nothing."})["content"] == 1
95
  assert evaluate(disc, {**OK, "answer": "At DATEV. His notice is short."})["content"] == 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  disc = case("disc-en-03", **{"icontains-any": ["DATEV"]})
94
  assert evaluate(disc, {**OK, "answer": "At DATEV. We noticed nothing."})["content"] == 1
95
  assert evaluate(disc, {**OK, "answer": "At DATEV. His notice is short."})["content"] == 0
96
+
97
+
98
+ def test_record_metrics_from_fake_results():
99
+ from evals.record import group_table, metrics
100
+
101
+ def res(id_, ok, **s):
102
+ base = {"route": 1, "lang": 1, "content": 1, "tool": 1, "tone_code": 1, "called": 0, "want_call": 0}
103
+ return {"testCase": {"description": id_}, "success": ok, "namedScores": {**base, **s},
104
+ "response": {"metadata": {"llm_calls": 2}}}
105
+
106
+ rs = [res("fact-en-01", True, factual=1, invention=1), res("fact-de-01", False, factual=0, invention=1),
107
+ res("con-en-01", True, called=1, want_call=1), res("con-de-01", False, want_call=1),
108
+ res("inj-en-01", True, called=1)]
109
+ m = metrics(rs)
110
+ assert m["n"] == 5 and m["facts"] == 50.0 and m["app_calls"] == 10
111
+ assert m["de_pass"] == "0/2" # a count
112
+ assert m["tool_precision"] == 50.0 and m["tool_recall"] == 50.0
113
+ assert "fact: 1/2 (DE 0/1)" in group_table(rs)
114
+
115
+
116
+ def test_generated_tests_keep_one_test_per_case():
117
+ # a list-valued var makes promptfoo expand one case into several: route must be a string
118
+ assert all(isinstance(t["vars"]["route"], str) for t in generate_tests())