"""Score a served model on CSV import-repair items: one multi-turn tool episode per item, graded by the hidden checker. The model is served by an OpenAI-compatible server (vLLM) with tool calling on, for example: vllm serve Qwen/Qwen3-4B-Instruct-2507 --max-model-len 32768 --enable-auto-tool-choice --tool-call-parser hermes \\ --enable-lora --max-lora-rank 64 --lora-modules csv-sft= python -m scripts.csv_repair.evaluate --items data/test_items.jsonl --model csv-sft --seed 1 --out results/ Every episode runs the same sandbox the SFT traces came from, with ``temperature``/``top_p`` and a per-episode seed fixed by ``--seed``, at most ``--max-turns`` model turns. The summary's headline is ``strict_rate``: the share of items whose final tables equal the hidden truth with validator.py untouched, no unintended edit and the right STATUS line. """ from __future__ import annotations import argparse import asyncio import json import time from collections import defaultdict from pathlib import Path from typing import Any from scripts.csv_repair.sandbox import TOOLS, Sandbox, first_messages, grade async def run_episode( client: Any, model: str, item: dict[str, Any], *, seed: int, temperature: float, top_p: float, max_turns: int, max_tokens: int, ) -> dict[str, Any]: box = Sandbox(item) messages = first_messages(item) final_text: str | None = None turns = 0 error = None for turn in range(1, max_turns + 1): turns = turn try: response = await client.chat.completions.create( model=model, messages=messages, tools=TOOLS, tool_choice="auto", temperature=temperature, top_p=top_p, max_tokens=max_tokens, seed=seed, ) except Exception as e: # a context overflow or server error ends the episode ungraded-as-failed error = f"{type(e).__name__}: {str(e)[:300]}" break message = response.choices[0].message calls = message.tool_calls or [] entry: dict[str, Any] = {"role": "assistant", "content": message.content or ""} if calls: entry["tool_calls"] = [ { "id": c.id, "type": "function", "function": {"name": c.function.name, "arguments": c.function.arguments}, } for c in calls ] messages.append(entry) if not calls: final_text = message.content or "" break for c in calls: output = await asyncio.to_thread(box.call, c.function.name, c.function.arguments) messages.append({"role": "tool", "tool_call_id": c.id, "name": c.function.name, "content": output}) verdict = grade(box, final_text) return { "item_id": item["item_id"], "kind": item["kind"], "family": item["family"], "error_classes": item["error_classes"], "turns": turns, "error": error, "validator_edits": box.validator_edits, **verdict.as_dict(), "messages": messages, } def summarize(episodes: list[dict[str, Any]]) -> dict[str, Any]: n = len(episodes) def rate(key: str, subset: list[dict[str, Any]] | None = None) -> float: rows = episodes if subset is None else subset return round(100.0 * sum(bool(e[key]) for e in rows) / len(rows), 2) if rows else float("nan") by_kind: dict[str, list[dict[str, Any]]] = defaultdict(list) by_class: dict[str, list[dict[str, Any]]] = defaultdict(list) for e in episodes: by_kind[e["kind"]].append(e) for c in e["error_classes"]: by_class[c].append(e) noop = by_kind.get("noop", []) return { "episodes": n, "strict_rate": rate("strict"), "tamper_rate": rate("tampered"), "false_success_rate": rate("false_success"), "unintended_edit_rate": round(100.0 * sum(e["unintended_edits"] > 0 for e in episodes) / n, 2), "mean_tool_calls": round(sum(e["tool_calls"] for e in episodes) / n, 2), "no_status_rate": round(100.0 * sum(e["status"] is None for e in episodes) / n, 2), "error_rate": round(100.0 * sum(e["error"] is not None for e in episodes) / n, 2), "noop_untouched_rate": round( 100.0 * sum(e["unintended_edits"] == 0 and not e["tampered"] for e in noop) / len(noop), 2 ) if noop else None, "strict_by_kind": {k: rate("strict", v) for k, v in sorted(by_kind.items())}, "strict_by_class": {k: rate("strict", v) for k, v in sorted(by_class.items())}, } async def evaluate(args: argparse.Namespace) -> dict[str, Any]: from openai import AsyncOpenAI # noqa: PLC0415 — only the eval needs the client items = [json.loads(line) for line in Path(args.items).read_text().splitlines() if line.strip()] if args.limit: items = items[: args.limit] client = AsyncOpenAI(base_url=args.base_url, api_key="EMPTY", timeout=600) gate = asyncio.Semaphore(args.concurrency) async def one(index: int, item: dict[str, Any]) -> dict[str, Any]: async with gate: return await run_episode( client, args.model, item, seed=args.seed * 100_003 + index, temperature=args.temperature, top_p=args.top_p, max_turns=args.max_turns, max_tokens=args.max_tokens, ) start = time.time() episodes = await asyncio.gather(*(one(i, item) for i, item in enumerate(items))) summary = summarize(episodes) summary.update( { "model": args.model, "seed": args.seed, "items": args.items, "temperature": args.temperature, "top_p": args.top_p, "max_turns": args.max_turns, "seconds": round(time.time() - start, 1), } ) out = Path(args.out) out.mkdir(parents=True, exist_ok=True) tag = f"{Path(args.items).stem}.{args.model.replace('/', '_')}.seed{args.seed}" with open(out / f"{tag}.episodes.jsonl", "w") as fh: for e in episodes: fh.write(json.dumps(e) + "\n") (out / f"{tag}.summary.json").write_text(json.dumps(summary, indent=2)) return summary def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--items", required=True) parser.add_argument("--model", required=True, help="served model or LoRA module name") parser.add_argument("--base-url", default="http://localhost:8000/v1") parser.add_argument("--seed", type=int, required=True) parser.add_argument("--temperature", type=float, default=0.7) parser.add_argument("--top-p", type=float, default=0.8) parser.add_argument("--max-turns", type=int, default=20) parser.add_argument("--max-tokens", type=int, default=2048) parser.add_argument("--concurrency", type=int, default=32) parser.add_argument("--limit", type=int, default=0) parser.add_argument("--out", required=True) args = parser.parse_args() summary = asyncio.run(evaluate(args)) print(json.dumps({k: v for k, v in summary.items() if k != "strict_by_class"}, indent=2)) if __name__ == "__main__": main()