Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(eval): read judge, keyword and recipe-judge verdicts by their structure (#1467) (#1472)
Jillur Rahman73634f9f5caf
diff --git a/changelog.d/0.75.1/1472.fixed.md b/changelog.d/0.75.1/1472.fixed.mdnew file mode 100644index 00000000..15369581--- /dev/null+++ b/changelog.d/0.75.1/1472.fixed.md@@ -0,0 +1 @@+- Model output is now read by its structure. The LLM judge (`soup eval judge`, the eval gate's judge task and `soup ship`'s `judge_score`) reads the reply's whole JSON object, so reasoning that quotes a nested object no longer scores every criterion at the minimum; criterion keys match case-insensitively, `{"score": N}` is accepted, and a missing or non-numeric criterion, or one scored under two spellings, raises an error naming it; a reply longer than 65,536 characters is refused unread. `soup eval checklist` keywords and `soup eval behavior --evidence` oracle labels match when they start or end with punctuation (`-5`, `(B)`, `C++`, `100%`), still as whole words on both sides. The judge node of `soup data recipe --execute` reads the first word of the reply: `OK` keeps the row, `REJECT` or `NOT OK` drops it, and any other reply counts as a failed call; its default prompt asks for a one-word verdict (#1467 by @developerjillur in #1472).diff --git a/docs/data.md b/docs/data.mdindex bc624552..23f26b0f 100644--- a/docs/data.md+++ b/docs/data.md@@ -1158,8 +1158,11 @@ command prints a warning whenever this mode is active.Live provider-call failures are counted: if every attempted call for an `llm_text`or `judge` node fails, the command names the endpoint and exits 1. Partial failures-keep usable rows and report their count in the completion summary, while a provider-that legitimately returns an empty completion still counts as a successful call.+keep usable rows and report their count in the completion summary, while an `llm_text`+provider that legitimately returns an empty completion still counts as a successful call.+A live `judge` node reads the first word of each reply: `OK` keeps the row, `REJECT`+or `NOT OK` drops it, and a reply with neither, an empty one included, is dropped and+counted as a failed call.Six node kinds now run live: **seed** (JSONL load), **llm_text** (LLM generation viaOllama, Anthropic, or vLLM), **code** (execution via RLVR sandbox), **judge** (binary scoring),diff --git a/docs/evaluation.md b/docs/evaluation.mdindex feec8398..26e20c9d 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -705,6 +705,8 @@ soup eval leaderboard --format csvsoup eval human --input prompts.jsonl --model-a ./model_a --model-b ./model_b```+`soup eval judge` asks the judge for one JSON object, `{"scores": {"<criterion>": <number>, ...}, "reasoning": "..."}`, and reads the first object in the reply that has a `scores` key, so reasoning that quotes JSON of its own does not get in the way. Criterion names match case-insensitively, and a score given as `{"score": N}` is read as `N`. A reply with no JSON object, with no finite number for a rubric criterion, or with one criterion under two spellings (`Helpfulness` and `helpfulness`) is an error that names the criterion where there is one, instead of a score at the scale minimum. A reply longer than 65,536 characters is refused unread; the judge is asked for at most 1,024 tokens, so only a runaway reply gets that long. `soup eval judge` skips such an item with a warning that carries the error and counts it (it exits `1` only when every item fails), an eval-gate judge task fails with the error as its reason (`soup eval gate` exits `2`), and `soup ship --task-mode judge_score` stops with `live ship verdict failed: ValueError: ...` and exits `1` without a verdict.+soup eval compare and soup eval leaderboard use the newest eval row for each benchmark (on the leaderboard, for each model and benchmark), so re-running a benchmark replaces its score; rows with the same created_at resolve to the later insert. soup registry diff compares eval scores the same way.### Aider Polyglot@@ -878,7 +880,7 @@ Without the live `--base-model` path, `--evidence` is required. An evidence-lessrun is an input error (exit `3`), not a neutral OK report; the error names theexpected `pre_responses`, `post_responses`, and `oracle` arrays.-Scoring depends on the path. With `--evidence`, each `oracle` entry is a word that must appear in the matching response (word-boundary and case-insensitive, so `"safe"` does not match `"unsafe"`). With `--base-model`, each generation is classified as a refusal or not: `safe` (XSTest) and `answer` (JailbreakBench) expect an answer, and `refuse` (HarmBench, JailbreakBench) expects a refusal. `elephant` and `syceval` (oracle `disagree`) need a judgement a refusal classifier cannot make, so `--base-model` refuses them before loading a model (exit `3`); score saved generations with `--evidence`. OK/MINOR/MAJOR thresholds match the v0.26 / v0.56 taxonomy.+Scoring depends on the path. With `--evidence`, each `oracle` entry is a word that must appear in the matching response (as a whole word and case-insensitive, so `"safe"` does not match `"unsafe"`, while a label with punctuation such as `(B)` or `-5` still matches). With `--base-model`, each generation is classified as a refusal or not: `safe` (XSTest) and `answer` (JailbreakBench) expect an answer, and `refuse` (HarmBench, JailbreakBench) expects a refusal. `elephant` and `syceval` (oracle `disagree`) need a judgement a refusal classifier cannot make, so `--base-model` refuses them before loading a model (exit `3`); score saved generations with `--evidence`. OK/MINOR/MAJOR thresholds match the v0.26 / v0.56 taxonomy.**Capability auto-suite** — pre-bundled profile selector with friendly `lm-eval-harness` task ids:@@ -919,7 +921,7 @@ soup eval checklist tests.yaml --evidence responses.jsonstrings. Omitting it exits `3` instead of rendering an OK result with zeromeasurements.-`mft` = response must contain a keyword as a whole word (`"sand"` won't pass for `"and"`); `inv` = all paraphrases must agree; `dir` = directional expectation under perturbation.+`mft` = response must contain a keyword as a whole word (`"sand"` won't pass for `"and"`, and keywords may start or end with punctuation, such as `-5`, `(B)` or `C++`); `inv` = all paraphrases must agree; `dir` = directional expectation under perturbation.**IRT subset selection** — pick a smaller eval set that preserves ranking power:diff --git a/src/soup_cli/eval/judge.py b/src/soup_cli/eval/judge.pyindex 08db2316..0b709760 100644--- a/src/soup_cli/eval/judge.py+++ b/src/soup_cli/eval/judge.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonimport logging+import mathimport osimport refrom dataclasses import dataclass, field@@ -178,23 +179,72 @@ def _build_judge_prompt()+#: A judge reply longer than this is refused before it is scanned (#1467). The+#: judge is asked for at most 1,024 tokens, so a real reply is far shorter, and+#: scanning a runaway reply made of ``{`` costs time quadratic in its length.+_MAX_JUDGE_REPLY_CHARS = 64 * 1024+++def _first_json_object(text: str) -> Optional[dict]:+ """The first JSON object in ``text`` that has a ``scores`` key (#1467).++ Each ``{`` is tried in turn with ``json.JSONDecoder.raw_decode``, so an+ object nested at any depth (a quoted ``{...}`` in the reasoning) is read+ whole. Falls back to the first JSON object when none has ``scores``.+ Nesting deeper than the decoder's recursion limit (a model repeating+ ``{"a":`` in a loop) ends the scan instead of retrying every ``{``.+ """+ decoder = json.JSONDecoder()+ first: Optional[dict] = None+ start = text.find("{")+ while start != -1:+ try:+ obj, _end = decoder.raw_decode(text, start)+ except json.JSONDecodeError:+ obj = None+ except RecursionError:+ return first+ if isinstance(obj, dict):+ if "scores" in obj:+ return obj+ if first is None:+ first = obj+ start = text.find("{", start + 1)+ return first++def _parse_judge_response(text: str,rubric: dict,) -> tuple[dict[str, float], str]:- """Parse judge LLM response into scores and reasoning."""- # Try to extract JSON from response (supports nested braces)- json_match = re.search(r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}', text, re.DOTALL)- if not json_match:- raise ValueError(f"No JSON found in judge response: {text[:200]}")-- try:- data = json.loads(json_match.group())- except json.JSONDecodeError as exc:- raise ValueError(f"Invalid JSON in judge response: {exc}") from exc+ """Parse judge LLM response into scores and reasoning.++ Criterion keys match case-insensitively and a ``{"score": N}`` value is+ unwrapped. A criterion the reply does not score, scores under two+ spellings (``Helpfulness`` and ``helpfulness``), or scores with anything+ but a finite number, raises ``ValueError`` naming it rather than counting+ as the scale minimum, and a reply over ``_MAX_JUDGE_REPLY_CHARS`` is+ refused unread (#1467).+ """+ if len(text) > _MAX_JUDGE_REPLY_CHARS:+ raise ValueError(+ f"Judge response is {len(text):,} characters, over the "+ f"{_MAX_JUDGE_REPLY_CHARS:,}-character limit"+ )+ data = _first_json_object(text)+ if data is None:+ raise ValueError(f"No JSON object found in judge response: {text[:200]}")scores = data.get("scores", {})+ if not isinstance(scores, dict):+ raise ValueError("Judge response 'scores' must be a JSON object")reasoning = str(data.get("reasoning", ""))+ folded: dict[str, object] = {}+ spellings: dict[str, list[str]] = {}+ for reply_key, reply_val in scores.items():+ folded_key = str(reply_key).strip().lower()+ folded[folded_key] = reply_val+ spellings.setdefault(folded_key, []).append(str(reply_key))# Validate scores against rubric criteriascale = rubric.get("scale", {"min": 1, "max": 5})@@ -204,11 +254,27 @@ def _parse_judge_response(validated_scores: dict[str, float] = {}for crit in rubric["criteria"]:name = crit["name"]- val = scores.get(name, scale_min)+ key = str(name).strip().lower()+ if key not in folded:+ raise ValueError(f"Judge response has no score for criterion {name!r}")+ if len(spellings[key]) > 1:+ raise ValueError(+ f"Judge response scores criterion {name!r} more than once, as "+ + ", ".join(repr(spelling) for spelling in spellings[key])+ )+ val = folded[key]+ if isinstance(val, dict) and "score" in val:+ val = val["score"]+ if isinstance(val, bool):+ val = Nonetry:val = float(val)- except (TypeError, ValueError):- val = float(scale_min)+ except (TypeError, ValueError, OverflowError):+ val = math.nan+ if not math.isfinite(val):+ raise ValueError(+ f"Judge score for criterion {name!r} is not a number: {folded[key]!r}"+ )val = max(scale_min, min(scale_max, val))validated_scores[name] = valdiff --git a/src/soup_cli/utils/behavior_battery.py b/src/soup_cli/utils/behavior_battery.pyindex f1e9b802..bc4183ef 100644--- a/src/soup_cli/utils/behavior_battery.py+++ b/src/soup_cli/utils/behavior_battery.py@@ -230,17 +230,30 @@ class BehaviorDiffReport:}+def contains_whole_word(text: str, word: str) -> bool:+ """``word`` appears in ``text`` with no word character right before or after it.++ The whole-word rule shared by ``_agreement_rate`` and the CheckList+ matchers (#1467): ``"and"`` does not match ``"sand"``, and a keyword whose+ edge is not a word character (``-5``, ``(B)``, ``C++``, ``100%``) still+ matches, which ``\\b`` cannot do because it needs a word character at the+ keyword's edge. Callers pass both strings lower-cased.+ """+ return re.search(rf"(?<!\w){re.escape(word)}(?!\w)", text) is not None++def _agreement_rate(responses: Sequence[object],oracle: Sequence[object],) -> float:- """Word-boundary agreement.+ """Whole-word agreement.The oracle label must appear as a standalone word (not substring) in theresponse — defends against ``"safe" in "unsafe"`` false positives.Punctuation-aware: ``"safe."`` is recognised as the word ``"safe"``(review H4 fix — whitespace-tokenised version dropped trailing-punct rows).- Case-insensitive.+ A label with a punctuation edge such as ``(B)`` or ``-5`` matches too+ (#1467, see ``contains_whole_word``). Case-insensitive."""if len(responses) != len(oracle):raise ValueError(@@ -258,10 +271,7 @@ def _agreement_rate(target = o.strip().lower()if not target:continue- # Word-boundary regex; oracle as a whole word in the response.- if re.search(- rf"\b{re.escape(target)}\b", r.lower()- ):+ if contains_whole_word(r.lower(), target):correct += 1return correct / len(responses)diff --git a/src/soup_cli/utils/checklist_dsl.py b/src/soup_cli/utils/checklist_dsl.pyindex fd9fc8ed..d2362eaf 100644--- a/src/soup_cli/utils/checklist_dsl.py+++ b/src/soup_cli/utils/checklist_dsl.py@@ -30,13 +30,14 @@ Operator-supplied responses are passed in via the ``evidence`` mapping:from __future__ import annotationsimport os-import reimport statfrom dataclasses import dataclassfrom typing import Mapping, Optional, Sequenceimport yaml+from soup_cli.utils.behavior_battery import contains_whole_word+# Closed allowlist.CHECKLIST_KINDS = frozenset({"mft", "inv", "dir"})@@ -304,15 +305,16 @@ def _mft_pass(response: str, expected: Sequence[str]) -> bool:"""MFT pass: any expected keyword appears as a whole WORD in the response.Whole-word match (review M2 fix — substring would let ``"and"`` pass on- ``"sand"``); case-insensitive. Mirrors the v0.65.0 Part B- ``behavior_battery._agreement_rate`` policy.+ ``"sand"``); case-insensitive. Shares ``behavior_battery``'s+ ``contains_whole_word`` with ``_agreement_rate``, so a keyword such as+ ``-5`` or ``(B)`` matches too (#1467)."""lower = response.lower()for kw in expected:target = kw.lower().strip()if not target:continue- if re.search(rf"\b{re.escape(target)}\b", lower):+ if contains_whole_word(lower, target):return Truereturn Falsediff --git a/src/soup_cli/utils/recipe_run.py b/src/soup_cli/utils/recipe_run.pyindex b7aedf6f..7a93ca4f 100644--- a/src/soup_cli/utils/recipe_run.py+++ b/src/soup_cli/utils/recipe_run.py@@ -372,6 +372,23 @@ def _node_llm_text()+#: A judge reply's verdict is its first word (#1467): ``OK`` or ``OKAY`` keeps the+#: row, ``REJECT`` and ``NOT OK`` drop it. A substring test kept ``NOT OK`` and+#: ``This looks broken`` (both contain ``OK``).+_JUDGE_VERDICT = re.compile(r"^\W*(not\W+)?(ok(?:ay)?|reject(?:ed)?)\b", re.IGNORECASE)+++def _read_judge_verdict(text: str) -> Optional[bool]:+ """``True`` keeps the row, ``False`` drops it, ``None`` means no verdict."""+ match = _JUDGE_VERDICT.match(text)+ if match is None:+ return None+ negated = match.group(1) is not None+ if match.group(2).lower().startswith("reject"):+ return None if negated else False+ return not negated++def _node_judge(node: "RecipeNode",inputs: Sequence[Sequence[Mapping[str, Any]]],@@ -382,12 +399,13 @@ def _node_judge() -> _ProviderNodeResult:"""Binary OK/REJECT classification via an LLM provider.- Rows for which the model emits a string containing ``"OK"`` are kept- (with ``<node.name>=True``); others are dropped.+ Rows whose reply starts with ``OK`` are kept (with ``<node.name>=True``);+ ``REJECT`` or ``NOT OK`` drops the row, and a reply with no verdict is+ dropped and counted in ``failure_count`` (#1467)."""prompt_template = node.config.get("prompt",- "Classify the following as OK or REJECT.\n\n{text}",+ "Classify the following as OK or REJECT. Reply with one word, OK or REJECT.\n\n{text}",)if not isinstance(prompt_template, str) or not prompt_template:raise ValueError(f"judge node {node.name!r}: 'prompt' must be a string")@@ -430,8 +448,11 @@ def _node_judge(if not isinstance(text, str):failures += 1continue- text = text.upper()- if "OK" in text and "REJECT" not in text:+ verdict = _read_judge_verdict(text)+ if verdict is None:+ _LOG.debug("judge node %s: no OK/REJECT verdict in %r", node.name, text[:80])+ failures += 1+ elif verdict:kept.append({**row, node.name: True})return _ProviderNodeResult(tuple(kept),diff --git a/tests/test_issue1467_verdict_matching.py b/tests/test_issue1467_verdict_matching.pynew file mode 100644index 00000000..e344377f--- /dev/null+++ b/tests/test_issue1467_verdict_matching.py@@ -0,0 +1,306 @@+"""#1467: model output is read by its structure, not by a pattern that fails silently.++Four readers used to fail in the direction that looks like a real result: the LLM+judge floored a valid reply to the scale minimum when its reasoning quoted a nested+object, keyword matching with ``\\b`` could never match a keyword such as ``-5`` or+``(B)``, and the recipe judge kept any reply containing the letters ``OK``.+"""++from __future__ import annotations++import json++import pytest+import yaml+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.eval.judge import DEFAULT_RUBRIC, _parse_judge_response+from soup_cli.utils.behavior_battery import _agreement_rate+from soup_cli.utils.checklist_dsl import _mft_pass++runner = CliRunner()++NESTED_REASONING = 'It returns {"function": {"name": "get_weather"}} as asked.'+FIVES = {"helpfulness": 5.0, "accuracy": 5.0, "safety": 5.0}+#: ``_MAX_JUDGE_REPLY_CHARS`` in ``soup_cli.eval.judge``, spelled out so the limit is pinned.+JUDGE_REPLY_LIMIT = 65_536+++class TestJudgeReadsTheWholeObject:+ def test_nested_reasoning_scores_first(self) -> None:+ reply = json.dumps({+ "scores": {"helpfulness": 5, "accuracy": 5, "safety": 5},+ "reasoning": NESTED_REASONING,+ })+ assert _parse_judge_response(reply, DEFAULT_RUBRIC) == (FIVES, NESTED_REASONING)++ def test_nested_reasoning_before_scores(self) -> None:+ reply = json.dumps({+ "reasoning": NESTED_REASONING,+ "scores": {"helpfulness": 5, "accuracy": 5, "safety": 5},+ })+ assert _parse_judge_response(reply, DEFAULT_RUBRIC) == (FIVES, NESTED_REASONING)++ def test_code_like_reasoning_and_surrounding_prose(self) -> None:+ body = json.dumps({+ "scores": {"helpfulness": 4, "accuracy": 3, "safety": 5},+ "reasoning": "cfg = {'a': {'b': 1}}",+ })+ scores, reasoning = _parse_judge_response(+ f"Here is my verdict {{draft}}:\n```json\n{body}\n```", DEFAULT_RUBRIC+ )+ assert scores == {"helpfulness": 4.0, "accuracy": 3.0, "safety": 5.0}+ assert reasoning == "cfg = {'a': {'b': 1}}"++ def test_capitalised_keys_and_score_objects_are_read(self) -> None:+ reply = json.dumps({+ "scores": {"Helpfulness": 4, "ACCURACY": {"score": 2}, "safety": {"score": "5"}},+ })+ scores, _ = _parse_judge_response(reply, DEFAULT_RUBRIC)+ assert scores == {"helpfulness": 4.0, "accuracy": 2.0, "safety": 5.0}++ def test_missing_criterion_names_it(self) -> None:+ reply = json.dumps({"scores": {"helpfulness": 5, "accuracy": 5}})+ with pytest.raises(ValueError, match="no score for criterion 'safety'"):+ _parse_judge_response(reply, DEFAULT_RUBRIC)++ @pytest.mark.parametrize(+ "value", ["high", None, True, [5], {"points": 5}, "NaN", 10**400]+ )+ def test_unreadable_score_names_the_criterion(self, value: object) -> None:+ reply = json.dumps({"scores": {"helpfulness": 5, "accuracy": value, "safety": 5}})+ with pytest.raises(ValueError, match="criterion 'accuracy' is not a number"):+ _parse_judge_response(reply, DEFAULT_RUBRIC)+++def test_degenerate_nesting_is_an_unreadable_reply_not_a_crash() -> None:+ # _first_json_object, without `except RecursionError` the error escapes. 13,000+ # levels exceed the decoder's nesting limit on every supported Python (1,000 on 3.10+ # and 3.11, 10,000 on 3.12) and the reply stays under the size limit.+ reply = '{"a":' * 13_000+ assert len(reply) <= JUDGE_REPLY_LIMIT+ with pytest.raises(ValueError, match="No JSON object found"):+ _parse_judge_response(reply, DEFAULT_RUBRIC)+++def test_a_capitalised_rubric_criterion_is_found_under_any_reply_casing() -> None:+ # _parse_judge_response, fold only the reply side+ rubric = {"criteria": [{"name": "Helpfulness", "weight": 1.0}], "scale": {"min": 1, "max": 5}}+ for reply_key in ("Helpfulness", "helpfulness", "HELPFULNESS"):+ scores, _ = _parse_judge_response(json.dumps({"scores": {reply_key: 4}}), rubric)+ assert scores == {"Helpfulness": 4.0}+++def test_the_object_with_a_scores_key_wins_over_an_earlier_object() -> None:+ # _first_json_object, drop the preference for an object that has "scores"+ reply = '{"note": "draft"} then ' + json.dumps(+ {"scores": {"helpfulness": 5, "accuracy": 5, "safety": 5}, "reasoning": "final"}+ )+ scores, reasoning = _parse_judge_response(reply, DEFAULT_RUBRIC)+ assert scores == {"helpfulness": 5.0, "accuracy": 5.0, "safety": 5.0}+ assert reasoning == "final"++[email protected]("scores", [[5, 5, 5], "5,5,5", 5, None])+def test_scores_that_is_not_an_object_is_a_value_error(scores: object) -> None:+ # _parse_judge_response, without the guard `.items()` raises AttributeError+ with pytest.raises(ValueError, match="'scores' must be a JSON object"):+ _parse_judge_response(json.dumps({"scores": scores}), DEFAULT_RUBRIC)+++def test_a_criterion_scored_under_two_spellings_is_refused() -> None:+ # _parse_judge_response, without the check the later spelling's score wins+ reply = json.dumps(+ {"scores": {"Helpfulness": 5, "helpfulness": 1, "accuracy": 5, "safety": 5}}+ )+ with pytest.raises(+ ValueError,+ match="criterion 'helpfulness' more than once, as 'Helpfulness', 'helpfulness'",+ ):+ _parse_judge_response(reply, DEFAULT_RUBRIC)+++def test_a_reply_over_the_size_limit_is_refused_before_it_is_scanned(monkeypatch) -> None:+ # _parse_judge_response, without the length check the reply is scanned+ import soup_cli.eval.judge as judge++ def scan(_text: str) -> None:+ raise AssertionError("an oversized reply was scanned")++ monkeypatch.setattr(judge, "_first_json_object", scan)+ with pytest.raises(ValueError, match="100,000 characters, over the 65,536-character limit"):+ _parse_judge_response("{ " * 50_000, DEFAULT_RUBRIC)+++def test_a_reply_at_the_size_limit_is_still_read() -> None:+ # _parse_judge_response, `>=` in the length check refuses this reply+ body = json.dumps({"scores": {"helpfulness": 5, "accuracy": 5, "safety": 5}})+ reply = body + " " * (JUDGE_REPLY_LIMIT - len(body))+ assert len(reply) == JUDGE_REPLY_LIMIT+ assert _parse_judge_response(reply, DEFAULT_RUBRIC) == (FIVES, "")+++PUNCTUATION_EDGES = (+ ("The answer is -5.", "-5"),+ ("-5", "-5"),+ ("Answer: (B)", "(B)"),+ ("I use C++ daily", "C++"),+ ("I use C# at work", "C#"),+ ("It costs $5 now", "$5"),+ ("Made in the U.S. today", "U.S."),+ ("Built on .NET 8", ".NET"),+ ("Coverage is 100% here", "100%"),+ ("Well, yes! Of course", "yes!"),+ ("Answer: (B)", "B"),+)+++class TestKeywordsWithPunctuationEdges:+ @pytest.mark.parametrize(("response", "keyword"), PUNCTUATION_EDGES)+ def test_checklist_and_battery_match(self, response: str, keyword: str) -> None:+ assert _mft_pass(response, [keyword])+ assert _agreement_rate([response], [keyword]) == 1.0++ @pytest.mark.parametrize(+ ("response", "keyword"),+ [+ ("sand castle", "and"), ("unsafe", "safe"), ("C++ and C", "C#"), ("x-5y", "-5"),+ ("the safety net", "safe"), ("uses C++11 here", "C++"), ("andy came", "and"),+ ("5th", "5"),+ ],+ )+ def test_whole_word_rule_still_holds(self, response: str, keyword: str) -> None:+ assert not _mft_pass(response, [keyword])+ assert _agreement_rate([response], [keyword]) == 0.0++ def test_both_readers_share_one_matcher(self) -> None:+ from soup_cli.utils.behavior_battery import contains_whole_word++ assert contains_whole_word("answer: (b)", "(b)")+ assert not contains_whole_word("sand", "and")++ def test_checklist_cli_passes_a_correct_negative_answer(self, tmp_path, monkeypatch) -> None:+ monkeypatch.chdir(tmp_path)+ (tmp_path / "spec.yaml").write_text(+ yaml.safe_dump({+ "tests": [+ {+ "name": "neg",+ "kind": "mft",+ "prompts": ["What is 2 - 7?"],+ "expected": ["-5"],+ }+ ]+ }),+ encoding="utf-8",+ )+ (tmp_path / "evidence.json").write_text(+ json.dumps({"neg": ["The answer is -5."]}), encoding="utf-8"+ )+ result = runner.invoke(app, ["eval", "checklist", "spec.yaml", "-e", "evidence.json"])+ assert result.exit_code == 0, (result.output, repr(result.exception))++ def test_behavior_evidence_cli_matches_lettered_options(self, tmp_path, monkeypatch) -> None:+ monkeypatch.chdir(tmp_path)+ (tmp_path / "behavior.json").write_text(+ json.dumps({+ "pre_responses": ["Answer: (B)", "Answer: (A)"],+ "post_responses": ["Answer: (B)", "Answer: (A)"],+ "oracle": ["(B)", "(A)"],+ }),+ encoding="utf-8",+ )+ result = runner.invoke(+ app,+ ["eval", "behavior", "run1", "--battery", "syceval", "--evidence", "behavior.json"],+ )+ assert result.exit_code == 0, (result.output, repr(result.exception))+++def _run_judge_node(monkeypatch, replies: list[str]):+ import soup_cli.utils.data_forge as data_forge+ from soup_cli.utils.recipe_dag import RecipeNode+ from soup_cli.utils.recipe_run import _node_judge++ answers = iter(replies)+ monkeypatch.setattr(+ data_forge,+ "make_judge_provider_fn",+ lambda *a, **k: (lambda prompt: {"text": next(answers)}),+ )+ rows = [[{"text": f"row {i}"} for i in range(len(replies))]]+ return _node_judge(+ RecipeNode(name="j", kind="judge", config={}),+ rows,+ judge_provider="ollama",+ judge_model=None,+ judge_base_url=None,+ )+++class TestRecipeJudgeReadsTheVerdict:+ @pytest.mark.parametrize(+ "reply",+ ["OK", "OK, nothing to REJECT", "ok.", "**OK**", "Okay", "OK - no reason to reject it"],+ )+ def test_positive_verdict_keeps_the_row(self, monkeypatch, reply: str) -> None:+ result = _run_judge_node(monkeypatch, [reply])+ assert len(result.rows) == 1+ assert result.failure_count == 0++ @pytest.mark.parametrize("reply", ["REJECT", "NOT OK", "not okay", "Rejected: off topic"])+ def test_negative_verdict_drops_the_row(self, monkeypatch, reply: str) -> None:+ result = _run_judge_node(monkeypatch, [reply])+ assert result.rows == ()+ assert result.failure_count == 0++ @pytest.mark.parametrize(+ "reply",+ [+ "This looks broken",+ "BAD - token limit",+ "The answer is a joke",+ "Books are fine? No.",+ "OKAYISH",+ "NOT REJECT",+ "",+ ],+ )+ def test_reply_without_a_verdict_is_a_failure(self, monkeypatch, reply: str) -> None:+ result = _run_judge_node(monkeypatch, [reply])+ assert result.rows == ()+ assert result.failure_count == 1+ assert result.call_count == 1+++def test_the_recipe_judge_default_prompt_asks_for_one_word(monkeypatch) -> None:+ # _node_judge, revert the default prompt to the old wording+ import soup_cli.utils.data_forge as data_forge+ from soup_cli.utils.recipe_dag import RecipeNode+ from soup_cli.utils.recipe_run import _node_judge++ seen: list[str] = []++ def factory(*_args, **_kwargs):+ def call(prompt: str) -> dict:+ seen.append(prompt)+ return {"text": "OK"}++ return call++ monkeypatch.setattr(data_forge, "make_judge_provider_fn", factory)+ _node_judge(+ RecipeNode(name="j", kind="judge", config={}),+ [[{"text": "row"}]],+ judge_provider="ollama",+ judge_model=None,+ judge_base_url=None,+ )+ assert "one word" in seen[0]+++def test_judge_accepts_a_rubric_name_that_is_not_a_string() -> None:+ rubric = {"criteria": [{"name": 1, "weight": 1.0}], "scale": {"min": 1, "max": 5}}+ scores, _ = _parse_judge_response(json.dumps({"scores": {"1": 4}}), rubric)+ assert scores == {1: 4.0}