From 9ee78c138b40c24ca5574366c28429b10e30d9a3 Mon Sep 17 00:00:00 2001 From: Novruz Garryyev Date: Sun, 1 Nov 2026 09:40:17 +0000 Subject: [PATCH] Add a corpus run that asks the model and grades its answers --- .github/workflows/corpus.yml | 59 +++++++++++ .gitignore | 1 + AGENTS.md | 1 + tests/run_corpus.py | 200 +++++++++++++++++++++++++++++++++++ tests/test_run_corpus.py | 68 ++++++++++++ 5 files changed, 329 insertions(+) create mode 100644 .github/workflows/corpus.yml create mode 100644 tests/run_corpus.py create mode 100644 tests/test_run_corpus.py diff --git a/.github/workflows/corpus.yml b/.github/workflows/corpus.yml new file mode 100644 index 0000000..f958832 --- /dev/null +++ b/.github/workflows/corpus.yml @@ -0,0 +1,59 @@ +name: Corpus run + +# Sends every corpus case to the model and grades the answers. +# Costs API credits, so it runs only when the skill text changes, or by hand. +on: + pull_request: + paths: + - SKILL.md + - references/** + - prompts/** + - scripts/barla.py + - tests/corpus/** + - tests/grade.py + - tests/run_corpus.py + workflow_dispatch: + inputs: + variant: + description: "skill (SKILL.md) or prompt (prompts/system-prompt.md)" + type: choice + options: [skill, prompt] + default: skill + runs: + description: "Answers per case" + default: "3" + +permissions: + contents: read + +concurrency: + group: corpus-${{ github.ref }} + cancel-in-progress: true + +jobs: + corpus: + # Pull requests from forks get no secrets; skip them instead of failing. + if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.12" + - name: Install uv + run: python3 -m pip install --quiet uv==0.11.32 + - name: Run the corpus + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + run: >- + uv run --no-project --with anthropic==2.3.0 python tests/run_corpus.py + --variant "${{ inputs.variant || 'skill' }}" + --runs "${{ inputs.runs || '3' }}" + - name: Keep the answers + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: corpus-results + path: corpus-results/ + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index 744c70f..fec6f04 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ __pycache__/ *.zip *.skill humanizer21-prompt.md +corpus-results/ diff --git a/AGENTS.md b/AGENTS.md index bf09377..b19f693 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,6 +30,7 @@ humanizer21 is an agent skill written in Markdown, with one Python checker and a - **Facts.** Examples in the references must never add a fact in the "after" text that the "before" text lacks. - **Checker.** Every new check in `barla.py` gets a test in `tests/test_barla.py`, including a test that correct text stays clean. - **Corpus.** When a rewrite goes wrong in a way the rules should have prevented, add the text to `tests/corpus/` as a new case with `input.txt`, `expected.json` and a corrected `reference.txt`. Run `python3 tests/grade.py` on the skill's next answer before releasing a fix. +- **Model run.** `tests/run_corpus.py` sends every corpus case to the model and grades the answers with `grade.py`; CI runs it (`.github/workflows/corpus.yml`) on pull requests that touch the skill text. Run it before and after a change to `SKILL.md`, `references/` or `prompts/`, and do not merge a change that makes a case fail that passed before. Locally: `uv run --no-project --with anthropic==2.3.0 python tests/run_corpus.py --runs 1`. It costs API credits. - **History.** Add a `CHANGELOG.md` note for any change in behavior. ## Checks before publishing diff --git a/tests/run_corpus.py b/tests/run_corpus.py new file mode 100644 index 0000000..b54d27f --- /dev/null +++ b/tests/run_corpus.py @@ -0,0 +1,200 @@ +"""Run the corpus through a model and grade every answer. + + uv run --with anthropic tests/run_corpus.py # all cases, 3 runs each + uv run --with anthropic tests/run_corpus.py --runs 1 --case olimpiada-habary + python3 tests/run_corpus.py --variant prompt --dry-run # show what would be sent + python3 tests/run_corpus.py --answers DIR # grade saved answers, no API + +The model gets SKILL.md and every file of references/ as its instructions +(or, with --variant prompt, prompts/system-prompt.md plus references/, as a +ChatGPT project would). Each case sends its `request` and `input.txt`. The +finished text is taken from between the markers the harness asks for, so +the list of changes after it is not graded, and checked with tests/grade.py. + +A case passes when at least --need of its --runs answers pass every check. +The script exits with code 1 if any case fails. It needs ANTHROPIC_API_KEY +unless --dry-run or --answers is given. Answers and a report go to --out. +""" + +import argparse +import json +import os +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +CORPUS = os.path.join(HERE, "corpus") +sys.path.insert(0, HERE) +import grade # noqa: E402 + +MODEL = "claude-opus-5-5" +START = "<<\n%s\n" % (first.replace(os.sep, "/"), read(os.path.join(ROOT, first)))] + refs = os.path.join(ROOT, "references") + for name in sorted(os.listdir(refs)): + if name.endswith(".md"): + parts.append("\n%s\n" % (name, read(os.path.join(refs, name)))) + return "\n\n".join(parts) + "\n\n" + HARNESS_NOTE + + +def user_message(case): + exp = json.loads(read(os.path.join(CORPUS, case, "expected.json"))) + return "%s\n\n%s" % (exp["request"], read(os.path.join(CORPUS, case, "input.txt"))) + + +def final_text(answer): + """The text between the markers, or None when the answer has none.""" + start = answer.find(START) + if start < 0: + return None + start += len(START) + end = answer.find(END, start) + if end < 0: + return None + return answer[start:end].strip("\n") + + +def check(case, answer): + """Names of the failed checks for one answer.""" + text = final_text(answer) + if text is None: + return ["answer has the %s ... %s markers" % (START, END)] + return [name for name, ok in grade.grade(os.path.join(CORPUS, case), text) if not ok] + + +def ask(client, system, message, model, effort): + import anthropic + + for attempt in range(4): + try: + with client.beta.messages.stream( + model=model, + max_tokens=32000, + system=[{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}], + messages=[{"role": "user", "content": message}], + output_config={"effort": effort}, + betas=["server-side-fallback-2026-07-01"], + fallbacks="default", + ) as stream: + msg = stream.get_final_message() + if msg.stop_reason == "refusal": + return "", msg.usage + return "".join(b.text for b in msg.content if b.type == "text"), msg.usage + except (anthropic.RateLimitError, anthropic.APIConnectionError, anthropic.InternalServerError): + if attempt == 3: + raise + time.sleep(2 ** (attempt + 2)) + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--case", action="append", help="run only this case (repeatable)") + p.add_argument("--runs", type=int, default=3, help="answers per case (default 3)") + p.add_argument("--need", type=int, help="passing answers a case needs (default: runs - 1, at least 1)") + p.add_argument("--variant", choices=["skill", "prompt"], default="skill") + p.add_argument("--model", default=MODEL) + p.add_argument("--effort", default="high", choices=["low", "medium", "high", "xhigh", "max"]) + p.add_argument("--out", default=os.path.join(ROOT, "corpus-results"), help="folder for answers and report") + p.add_argument("--answers", help="grade saved answers from this folder (/.txt) instead of asking a model") + p.add_argument("--dry-run", action="store_true", help="print sizes and the first request, send nothing") + args = p.parse_args(argv) + + selected = args.case or cases() + unknown = [c for c in selected if c not in cases()] + if unknown: + p.error("unknown case: %s" % ", ".join(unknown)) + need = args.need if args.need is not None else max(1, args.runs - 1) + system = system_prompt(args.variant) + + if args.dry_run: + print("variant %s: system prompt %d characters, %d cases x %d runs" % (args.variant, len(system), len(selected), args.runs)) + print("--- first message ---\n" + user_message(selected[0])) + return 0 + + client = None + if not args.answers: + if not os.environ.get("ANTHROPIC_API_KEY"): + print("ANTHROPIC_API_KEY is not set", file=sys.stderr) + return 2 + import anthropic + + client = anthropic.Anthropic() + + rows, totals = [], {"input": 0, "cache_read": 0, "cache_write": 0, "output": 0} + for case in selected: + passed, failures = 0, [] + for n in range(1, args.runs + 1): + if args.answers: + path = os.path.join(args.answers, case, "%d.txt" % n) + answer = read(path) if os.path.exists(path) else "" + else: + answer, usage = ask(client, system, user_message(case), args.model, args.effort) + totals["input"] += usage.input_tokens + totals["cache_read"] += usage.cache_read_input_tokens or 0 + totals["cache_write"] += usage.cache_creation_input_tokens or 0 + totals["output"] += usage.output_tokens + os.makedirs(os.path.join(args.out, case), exist_ok=True) + with open(os.path.join(args.out, case, "%d.txt" % n), "w", encoding="utf-8") as fh: + fh.write(answer) + failed = check(case, answer) + passed += not failed + failures.append(failed) + print("%-24s run %d: %s" % (case, n, "OK" if not failed else "FAIL (%d)" % len(failed)), flush=True) + rows.append({"case": case, "passed": passed, "runs": args.runs, "ok": passed >= need, "failures": failures}) + + report = render(rows, need, args, totals) + os.makedirs(args.out, exist_ok=True) + with open(os.path.join(args.out, "report.md"), "w", encoding="utf-8") as fh: + fh.write(report) + with open(os.path.join(args.out, "report.json"), "w", encoding="utf-8") as fh: + json.dump({"variant": args.variant, "model": args.model, "need": need, "tokens": totals, "cases": rows}, fh, ensure_ascii=False, indent=2) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as fh: + fh.write(report) + print("\n" + report) + return 0 if all(r["ok"] for r in rows) else 1 + + +def render(rows, need, args, totals): + ok = sum(r["ok"] for r in rows) + lines = [ + "## Corpus run: %s, %s" % (args.variant, "saved answers" if args.answers else args.model), + "", + "%d of %d cases pass (a case needs %d of %d answers to pass every check)." % (ok, len(rows), need, args.runs), + "", + "| Case | Passed | Result |", + "|---|---|---|", + ] + lines += ["| %s | %d / %d | %s |" % (r["case"], r["passed"], r["runs"], "OK" if r["ok"] else "FAIL") for r in rows] + if not args.answers: + lines += ["", "Tokens: %(input)d input, %(cache_read)d cache read, %(cache_write)d cache write, %(output)d output." % totals] + failed = [(r["case"], i + 1, f) for r in rows for i, f in enumerate(r["failures"]) if f] + if failed: + lines += ["", "### Failed checks", ""] + for case, n, names in failed: + lines.append("- **%s**, run %d: %s" % (case, n, "; ".join(names))) + return "\n".join(lines) + "\n" + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_run_corpus.py b/tests/test_run_corpus.py new file mode 100644 index 0000000..00e05d5 --- /dev/null +++ b/tests/test_run_corpus.py @@ -0,0 +1,68 @@ +import os +import shutil +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import run_corpus as rc # noqa: E402 + + +def wrap(text, notes="- için → üçin"): + return "%s\n%s\n%s\n\n%s\n" % (rc.START, text, rc.END, notes) + + +class TestRunCorpus(unittest.TestCase): + def test_final_text_is_taken_from_between_the_markers(self): + self.assertEqual(rc.final_text("x\n<<>>\nnotes"), "Salam.") + self.assertIsNone(rc.final_text("Salam.")) + self.assertIsNone(rc.final_text("<<" % first, s) + for name in os.listdir(os.path.join(rc.ROOT, "references")): + self.assertIn("references/%s" % name, s) + self.assertTrue(s.endswith(rc.HARNESS_NOTE)) + + def test_saved_answers_mode(self): + tmp = tempfile.mkdtemp() + try: + good, bad = os.path.join(tmp, "good"), os.path.join(tmp, "bad") + for case in rc.cases(): + for folder, name in ((good, "reference.txt"), (bad, "input.txt")): + os.makedirs(os.path.join(folder, case)) + text = rc.read(os.path.join(rc.CORPUS, case, name)) + for n in (1, 2): + with open(os.path.join(folder, case, "%d.txt" % n), "w", encoding="utf-8") as fh: + fh.write(wrap(text)) + out = os.path.join(tmp, "out") + with open(os.devnull, "w") as null: + stdout, sys.stdout = sys.stdout, null + try: + ok = rc.main(["--answers", good, "--runs", "2", "--out", out]) + fail = rc.main(["--answers", bad, "--runs", "2", "--out", out]) + finally: + sys.stdout = stdout + self.assertEqual((ok, fail), (0, 1)) + self.assertIn("FAIL", rc.read(os.path.join(out, "report.md"))) + finally: + shutil.rmtree(tmp) + + +if __name__ == "__main__": + unittest.main()