import argparse import logging import asyncio import json import re from pathlib import Path import csv from pythonjsonlogger import jsonlogger from langchain_text_splitters import MarkdownHeaderTextSplitter from openai import AsyncOpenAI from pydantic import BaseModel from markdown_it import MarkdownIt logger = logging.getLogger(__name__) logHandler = logging.StreamHandler() formatter = jsonlogger.JsonFormatter("%(asctime)s %(levelname)s %(message)s %(name)s") logHandler.setFormatter(formatter) logger.addHandler(logHandler) logger.setLevel(logging.INFO) class QuestionAnswer(BaseModel): question: str answer: str source_quote: str section: str manufacturer: str = "" game: str = "" class Extraction(BaseModel): qas: list[QuestionAnswer] class RewrittenQuestion(BaseModel): question: str class Validation(BaseModel): accurate: bool grounded: bool reasoning: str async def chat_structured( client: AsyncOpenAI, model: str, messages: list[dict], response_model: type[BaseModel], max_tokens: int, ) -> BaseModel | None: try: resp = await client.chat.completions.create( model=model, messages=messages, max_tokens=max_tokens, ) content = resp.choices[0].message.content or "" stripped = content.strip() if stripped.startswith("```"): stripped = re.sub(r"^```[a-zA-Z]*\s*|\s*```$", "", stripped, flags=re.S) start = stripped.find("{") end = stripped.rfind("}") if start == -1 or end == -1: return None data = json.loads(stripped[start : end + 1]) return response_model.model_validate(data) except Exception: return None async def extract_facts( client: AsyncOpenAI, model: str, text: str, manufacturer: str, game: str ) -> list[QuestionAnswer]: system_prompt = f"""You are an expert at building benchmark questions from pinball rulesheets. The machine is the {game} pinball game, manufactured by {manufacturer}. Your task is to generate self-contained (including machine name), objective question/answer pairs based on the provided markdown text. Guidelines: 1. Topics: Focus on features, rules, scoring, layout, mechanics, and credits. 2. Verifiability: Each question must be answerable using ONLY the provided text. The answer must be a single, verifiable fact. 3. Objectivity: Do NOT include subjective opinions, memories, or uncertain claims. 4. Scope: The text is a CHUNK of the rulesheet, not the full document. Only generate questions whose answers are fully contained within this specific chunk. Output the questions and answers in the requested format. """ parsed = await chat_structured( client, model, [ {"role": "system", "content": system_prompt}, {"role": "user", "content": text}, ], Extraction, max_tokens=32_768, ) if parsed is None: return [] return parsed.qas async def rewrite_self_contained( client: AsyncOpenAI, model: str, question: str, manufacturer: str, game: str ) -> str: system_prompt = f"""You are an expert at making pinball rulesheet benchmark questions self-contained. The question is about the {game} pinball game, manufactured by {manufacturer}. Rewrite the question so it includes the game name (and manufacturer if relevant) so that a reader with no other context can understand it. Keep the same meaning, wording, and answer. Only change the question text; do not change the answer. Return ONLY a JSON document with a single field `question` that is the result of you rewriting the question with the game name. """ parsed = await chat_structured( client, model, [ {"role": "system", "content": system_prompt}, { "role": "user", "content": ( f"Game: {game}\n" f"Manufacturer: {manufacturer}\n" f"Question: {question}\n" ), }, ], RewrittenQuestion, max_tokens=4096, ) if parsed is None: return question return parsed.question async def validate_qa( client: AsyncOpenAI, model: str, question: str, answer: str, text: str ) -> Validation | None: system_prompt = """You are an expert at verifying pinball rulesheet benchmark questions. Given a question, its answer, and the full rulesheet that supposedly supports it, determine: - accurate: whether the answer is factually correct. - grounded: whether the answer is fully supported by the rulesheet (every claim in the answer appears in, or follows directly from, the rulesheet text). - reasoning: rationale for the accurate and grounded results Return ONLY a JSON document with `accurate`, `grounded` and `reasoning` fields. """ parsed = await chat_structured( client, model, [ {"role": "system", "content": system_prompt}, {"role": "user", "content": f"Rulesheet:\n{text}"}, {"role": "user", "content": f"Question: {question}\nAnswer: {answer}\n"}, ], Validation, max_tokens=4096, ) return parsed async def validate_row( client: AsyncOpenAI, model: str, row: dict, text: str ) -> Validation | None: question = row["question"] answer = row["answer"] return await validate_qa(client, model, question, answer, text) def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="pinball_benchmarks", description="Build benchmark questions from pinball rulesheets.", ) subparsers = parser.add_subparsers(dest="action", required=True) extract_p = subparsers.add_parser("extract", help="Extract facts into CSV files.") extract_p.add_argument( "--rules-dir", type=Path, default=Path("/tmp/pinballrules/docs"), help="Directory containing the pinball rulesheets.", ) extract_p.add_argument( "--output-dir", type=Path, default=Path("output"), help="Directory to write CSV outputs to.", ) extract_p.add_argument( "--model", default="deepseek-v4-flash", help="Model to use for extraction.", ) extract_p.add_argument( "--base-url", default="http://localhost:8000/v1", help="OpenAI-compatible API base URL.", ) extract_p.add_argument( "--api-key", default="foobar", help="API key for the OpenAI-compatible server.", ) extract_p.add_argument( "--max-concurrent", type=int, default=5, help="Max concurrent extraction calls per batch.", ) update_p = subparsers.add_parser( "update-to-self-contained", help="Rewrite CSV questions to be self-contained (include the game name).", ) update_p.add_argument( "--output-dir", type=Path, default=Path("output"), help="Directory containing CSV files to update in place.", ) update_p.add_argument( "--start-file", type=Path, default=None, help="CSV filename to start processing from, instead of the first file in the glob.", ) update_p.add_argument( "--model", default="deepseek-v4-flash", help="Model to use for rewriting.", ) update_p.add_argument( "--base-url", default="http://localhost:8000/v1", help="OpenAI-compatible API base URL.", ) update_p.add_argument( "--api-key", default="foobar", help="API key for the OpenAI-compatible server.", ) update_p.add_argument( "--max-concurrent", type=int, default=5, help="Max concurrent rewrite calls per batch.", ) validate_p = subparsers.add_parser( "validate-question", help="Validate that CSV question/answer pairs are accurate and grounded in the rulesheet.", ) validate_p.add_argument( "--rules-dir", type=Path, default=Path("/tmp/pinballrules/docs"), help="Directory containing the pinball rulesheets.", ) validate_p.add_argument( "--output-dir", type=Path, default=Path("output"), help="Directory containing CSV files to validate.", ) validate_p.add_argument( "--model", default="deepseek-v4-flash", help="Model to use for validation.", ) validate_p.add_argument( "--base-url", default="http://localhost:8000/v1", help="OpenAI-compatible API base URL.", ) validate_p.add_argument( "--api-key", default="foobar", help="API key for the OpenAI-compatible server.", ) validate_p.add_argument( "--max-concurrent", type=int, default=5, help="Max concurrent validation calls per batch.", ) return parser async def run_validate_question(args: argparse.Namespace) -> None: rules_path = args.rules_dir output_dir = args.output_dir openai_client = AsyncOpenAI(base_url=args.base_url, api_key=args.api_key) model = args.model max_concurrent = args.max_concurrent csv_paths = sorted(output_dir.glob("*.csv")) logger.info(f"found {len(csv_paths)} csv files") out_path = output_dir / "validation-results.csv" fieldnames = ["game", "question", "answer", "accurate", "grounded", "reasoning"] done: dict[str, set[str]] = {} last_game = "" if out_path.exists(): with open(out_path, mode="r", newline="", encoding="utf-8") as f: reader = csv.DictReader(f) for result in reader: game = result.get("game", "") done.setdefault(game, set()).add(result["question"]) last_game = game logger.info(f"found {len(done)} games already validated, resuming from {last_game!r}") else: logger.info("no validation-results.csv found, starting fresh") written = 0 with open(out_path, mode="w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() for csv_path in csv_paths: md_paths = list(rules_path.rglob(f"{csv_path.stem}.md")) if not md_paths: logger.info(f"skipping {csv_path.name}, no matching rulesheet markdown") continue md_path = md_paths[0] text = md_path.read_text(encoding="utf-8") rows = [] with open(csv_path, mode="r", newline="", encoding="utf-8") as cf: reader = csv.DictReader(cf) for row in reader: rows.append(row) for start in range(0, len(rows), max_concurrent): batch = rows[start : start + max_concurrent] logger.info( f"\t{csv_path.name} validating {start}/{len(rows)} batch ({len(batch)} rows)" ) batch_results = await asyncio.gather( *(validate_row(openai_client, model, row, text) for row in batch) ) for row, result in zip(batch, batch_results): game = row.get("game", "") or csv_path.stem question = row["question"] if game in done and question in done[game]: continue if result is None: logger.info( f"\t{question} -> could not find a relevant chunk" ) continue logger.info( f"\t{question} -> " f"accurate={result.accurate} grounded={result.grounded}" ) writer.writerow( { "game": game, "question": question, "answer": row["answer"], "accurate": result.accurate, "grounded": result.grounded, "reasoning": result.reasoning, } ) f.flush() written += 1 logger.info(f"wrote {written} validation results to {out_path}") async def run_extract(args: argparse.Namespace) -> None: rules_path = args.rules_dir master_list = rules_path / "rulesheet-master-list.md" output_dir = args.output_dir output_dir.mkdir(exist_ok=True) openai_client = AsyncOpenAI(base_url=args.base_url, api_key=args.api_key) model = args.model max_concurrent = args.max_concurrent filename_deny_list = set(["README.md", "rulesheet-master-list.md"]) master_text = master_list.read_text(encoding="utf-8") tokens = MarkdownIt().parse(master_text) markdown_files = sorted( rules_path / (href.lstrip("/") + ".md") for token in tokens if token.type == "inline" and token.children for child in token.children if child.type == "link_open" for href in [child.attrGet("href")] if href.startswith("/") and not href.startswith("http") ) splitter = MarkdownHeaderTextSplitter( headers_to_split_on=[ ("##", "section"), ("###", "subsection"), ], strip_headers=False, ) for idx, md_path in enumerate(markdown_files): if md_path.name in filename_deny_list: continue logger.info(f"Processing file {idx + 1}/{len(markdown_files)}: {md_path.name}") csv_path = output_dir / md_path.with_suffix(".csv").name if csv_path.exists(): logger.info(f"skipping {md_path.name}, {csv_path.name} already exists") continue manufacturer = md_path.parent.name stem = md_path.stem game = ( stem.replace("-rulesheet", "").replace("--rulesheet", "").replace("-", " ") ) text = md_path.read_text(encoding="utf-8") chunks = [chunk.page_content for chunk in splitter.split_text(text)] qas: list[QuestionAnswer] = [] logger.info(f"found {len(chunks)} chunks") for start in range(0, len(chunks), max_concurrent): batch = chunks[start : start + max_concurrent] logger.info(f"\tstarting {start}/{len(chunks)} batch ({len(batch)} chunks)") batch_facts = await asyncio.gather( *( extract_facts(openai_client, model, chunk, manufacturer, game) for chunk in batch ) ) for facts in batch_facts: logger.info(f"\tfound {len(facts)} facts") qas.extend(facts) for qa in qas: qa.manufacturer = manufacturer qa.game = game logger.info(f"=== {md_path.relative_to(rules_path)} ===") # Output to CSV with open(csv_path, mode="w", newline="", encoding="utf-8") as f: writer = csv.DictWriter( f, fieldnames=[ "question", "answer", "source_quote", "section", "manufacturer", "game", ], ) writer.writeheader() for qa in qas: writer.writerow(qa.model_dump()) for qa in qas: logger.info(qa.model_dump()) logger.info(f"finished {md_path.name}") logger.info("") async def run_update_to_self_contained(args: argparse.Namespace) -> None: output_dir = args.output_dir openai_client = AsyncOpenAI(base_url=args.base_url, api_key=args.api_key) model = args.model max_concurrent = args.max_concurrent csv_paths = sorted(output_dir.glob("*.csv")) if args.start_file is not None: start = args.start_file.name try: idx = next(i for i, p in enumerate(csv_paths) if p.name == start) except StopIteration: raise FileNotFoundError( f"--start-file {start} not found among CSV files in {output_dir}" ) csv_paths = csv_paths[idx:] logger.info(f"found {len(csv_paths)} csv files") for csv_path in csv_paths: rows = [] with open(csv_path, mode="r", newline="", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: rows.append(row) fieldnames = list(rows[0].keys()) if rows else [] needs_update: list[dict] = [] for row in rows: question = row["question"] game = row.get("game", "") if game and game.lower() not in question.lower(): needs_update.append(row) logger.info( f"{csv_path.name}: {len(needs_update)}/{len(rows)} questions need updating" ) if not needs_update: continue updated = [] for start in range(0, len(needs_update), max_concurrent): batch = needs_update[start : start + max_concurrent] logger.info( f"\tstarting {start}/{len(needs_update)} batch ({len(batch)} rows)" ) batch_questions = await asyncio.gather( *( rewrite_self_contained( openai_client, model, row["question"], row.get("manufacturer", ""), row.get("game", ""), ) for row in batch ) ) for row, new_question in zip(batch, batch_questions): row["question"] = new_question updated.append(row) with open(csv_path, mode="w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() for row in rows: writer.writerow(row) logger.info(f"finished {csv_path.name}") async def main(args: argparse.Namespace) -> None: if args.action == "extract": await run_extract(args) elif args.action == "update-to-self-contained": await run_update_to_self_contained(args) elif args.action == "validate-question": await run_validate_question(args) else: raise ValueError(f"Unknown action: {args.action}") if __name__ == "__main__": asyncio.run(main(build_parser().parse_args()))