import json import os import re import time from pathlib import Path from deepeval.metrics import GEval from deepeval.models import GPTModel from deepeval.test_case import LLMTestCase, SingleTurnParams, LLMTestCaseParams BASE_DIR = Path(__file__).resolve().parent INPUTS_DIR = BASE_DIR / "inputs" OUTPUTS_DIR = BASE_DIR / "outputs" THEOREM_MAP = INPUTS_DIR / "theorem_map.md" CONJECTURES_DIR = INPUTS_DIR / "generated_conjectures" JSON_OUT = OUTPUTS_DIR / "deepeval_quality_scores.json" MD_OUT = OUTPUTS_DIR / "deepeval_quality_scores.md" DEEPEVAL_RETRY_SLEEP_SECONDS = 5 def read_text(path: Path) -> str: if not path.exists(): raise FileNotFoundError(f"Missing file: {path}") return path.read_text(encoding="utf-8") def extract_result_ids_from_conjectures() -> list[str]: result_ids = [] for path in sorted(CONJECTURES_DIR.glob("result_*_conjecture.md")): match = re.search(r"(result_\d+)_conjecture\.md$", path.name) if match: result_ids.append(match.group(1)) return result_ids def extract_formal_statement(conjecture_text: str, path: Path | None = None) -> str: """ Extract only the Formal Statement section from a generated conjecture file. The current conjecture-generation prompt requires a '## Formal Statement' section. If the model fails to follow the format, fall back to the full file and print a warning so the evaluation can still run. """ match = re.search( r"## Formal Statement\s*(.*?)(?=\n## |\Z)", conjecture_text, flags=re.DOTALL, ) if match: return match.group(1).strip() label = f" in {path}" if path else "" print( f"WARNING: Could not find '## Formal Statement'{label}; using full file.", flush=True, ) return conjecture_text.strip() def extract_source_theorem_from_map(theorem_map_text: str, result_id: str) -> str: """ Extract the source theorem statement for a result ID from theorem_map.md. Robust to headings like: ### result_001 ### `result_001` ### result_001: Theorem \\ref{central} Robust to labels like: - **Exact statement:** ... - Exact statement: ... - **Formal Statement:** ... - Formal Statement: ... """ lines = theorem_map_text.splitlines() # 1. Find the result section heading. start = None heading_re = re.compile( rf"^###\s+`?{re.escape(result_id)}`?(?:\s*:.*)?\s*$", flags=re.IGNORECASE, ) for i, line in enumerate(lines): if heading_re.match(line.strip()): start = i + 1 break if start is None: raise ValueError(f"Could not find section for {result_id} in theorem_map.md") # 2. Find the end of this result section. end = len(lines) next_result_re = re.compile( r"^###\s+`?result_\d+`?(?:\s*:.*)?\s*$", flags=re.IGNORECASE, ) for i in range(start, len(lines)): stripped = lines[i].strip() if next_result_re.match(stripped) or stripped.startswith("## Summary") or stripped.startswith("## Final Summary"): end = i break section_lines = lines[start:end] # 3. Find a statement field. statement_labels = { "statement", "statement (exact from paper)", "exact statement", "exact theorem statement", "theorem statement", "formal statement", } for i, line in enumerate(section_lines): stripped = line.strip() # Only consider Markdown bullet fields. if not stripped.startswith("-"): continue field = stripped[1:].strip() # Remove bold wrapping around the label, but not the value. # Examples: # **Exact statement:** Let ... # Exact statement: Let ... field = field.replace("**", "") if ":" not in field: continue label, value = field.split(":", 1) label = label.strip().lower() value = value.strip() if label not in statement_labels: continue statement_parts = [] if value: statement_parts.append(value) # Capture continuation lines until the next bullet or heading. for continuation in section_lines[i + 1:]: continuation_stripped = continuation.strip() if continuation_stripped.startswith("- ") or continuation_stripped.startswith("### ") or continuation_stripped.startswith("## "): break if continuation_stripped: statement_parts.append(continuation_stripped) statement = "\n".join(statement_parts).strip() # Remove markdown blockquote markers. statement = re.sub(r"^\s*>\s?", "", statement, flags=re.MULTILINE).strip() if statement: return statement raise ValueError(f"Could not find theorem statement for {result_id} in theorem_map.md") def make_rcd_model(): api_key = os.environ.get("RCD_LLM_API_KEY") if not api_key: raise RuntimeError( "RCD_LLM_API_KEY is not set. Run: " 'export RCD_LLM_API_KEY="$(cat ~/.secrets/rcd_llm_key)"' ) return GPTModel( model="gemma-4-31b", api_key=api_key, base_url="https://llm.rcd.clemson.edu/v1", temperature=0, ) def make_conjecture_quality_metric(): return GEval( model=make_rcd_model(), name="Conjecture Quality", evaluation_steps=[ ( "Evaluate the actual output as a generated mathematical conjecture. " "The goal is to assign a score based on the quality, relevance, and " "mathematical usefulness of the conjecture." ), ( "Use the input as the context that was provided to the conjecture-generating " "model. Use the expected output as a theorem from a mathematics paper whose " "preceding text was used to generate the conjecture. Use the actual output " "as the generated conjecture being evaluated." ), ( "First, compare the actual output to the expected output. Determine whether " "the actual output is essentially the same as the expected theorem, a close " "variant, a related generalization or specialization, loosely related, or " "unrelated." ), ( "Second, remove fluff. Ignore generic motivational language, vague claims " "of importance, broad exposition, future-work language, and text that does " "not assert a mathematical claim. Determine whether a clear mathematical " "statement remains." ), ( "Assess whether anything mathematically meaningful remains after removing " "fluff. If the remaining content does not contain a clear mathematical " "statement, assign a low score. If it appears to contain a potentially new " "mathematical statement, continue evaluating it using the knownness, " "simple-case plausibility, and relevance criteria below." ), ( "Assess simple-case plausibility. Penalize statements that are internally " "inconsistent, obviously false, missing necessary hypotheses, overgeneralized " "in a way that would likely fail immediately, or likely to fail on the first " "interesting example. Do not perform extensive computation; use basic " "mathematical reasoning only." ), ( "Assess knownness and novelty. A known result is less valuable as a new " "conjecture than a plausible new statement. However, do not overly penalize " "close recovery of the expected theorem: similarity to the expected theorem " "is evidence that the output is mathematically meaningful, interesting, and " "contextually relevant." ), ( "Assess relevance to the expected theorem. Outputs close to the expected " "theorem should generally receive higher scores. Outputs very different from " "the expected theorem should often receive C-level scores if they contain " "substantive mathematical content but are difficult to evaluate confidently." ), ( "Assign a continuous score from 0 to 1 using this scale: " "1.0 means A-level: clear, substantive, plausible, highly relevant, and " "mathematically interesting; it closely recovers, usefully refines, or " "interestingly extends the expected theorem. " "0.75 means B-level: good mathematical conjecture; mostly clear, plausible, " "and relevant, but less precise, less novel, or less strong than A. " "0.5 means C-level: contains potentially interesting mathematical content, " "but its relevance, novelty, precision, or plausibility is uncertain; this " "includes many outputs that are quite different from the expected theorem " "but not clearly bad. " "0.25 means D-level: weak conjecture; little substance remains after removing " "fluff, or the statement is vague, trivial, mostly known, poorly connected, " "or mathematically imprecise. " "0.0 means E-level: no usable conjecture; incoherent, unrelated, essentially " "only fluff, or obviously false in simple cases." ), ( "Use intermediate values when appropriate. For example, a score of 0.6 may " "indicate an output between C and B, while a score of 0.9 may indicate a " "very strong output that is slightly below ideal." ), ], evaluation_params=[ LLMTestCaseParams.INPUT, LLMTestCaseParams.ACTUAL_OUTPUT, LLMTestCaseParams.EXPECTED_OUTPUT, ], threshold=0.5, ) def measure_with_retries(test_case: LLMTestCase, result_id: str) -> GEval: """ Run the DeepEval metric for one example, retrying the same example until it succeeds. This is intentionally unbounded so transient DeepEval/model/API failures do not cause the script to skip an example or move on prematurely. """ attempt = 1 while True: try: if attempt > 1: print(f"Retrying {result_id} DeepEval call, attempt {attempt}...", flush=True) conjecture_quality = make_conjecture_quality_metric() conjecture_quality.measure(test_case) return conjecture_quality except Exception as exc: print( f"WARNING: DeepEval failed for {result_id} on attempt {attempt}: " f"{type(exc).__name__}: {exc}", flush=True, ) attempt += 1 time.sleep(DEEPEVAL_RETRY_SLEEP_SECONDS) def main(): OUTPUTS_DIR.mkdir(parents=True, exist_ok=True) theorem_map_text = read_text(THEOREM_MAP) result_ids = extract_result_ids_from_conjectures() if not result_ids: raise RuntimeError(f"No conjecture files found in {CONJECTURES_DIR}") results = [] for result_id in result_ids: conjecture_path = CONJECTURES_DIR / f"{result_id}_conjecture.md" actual_full_text = read_text(conjecture_path) actual_output = extract_formal_statement(actual_full_text, conjecture_path) expected_output = extract_source_theorem_from_map(theorem_map_text, result_id) judge_actual_output = actual_output[:12000] judge_expected_output = expected_output[:8000] print(f"Evaluating {result_id}...", flush=True) print(f" actual chars: {len(actual_output)} -> judging {len(judge_actual_output)}", flush=True) print(f" expected chars: {len(expected_output)} -> judging {len(judge_expected_output)}", flush=True) test_case = LLMTestCase( input=( "" ), actual_output=judge_actual_output, expected_output=judge_expected_output, ) conjecture_quality = measure_with_retries(test_case, result_id) results.append( { "result_id": result_id, "conjecture_file": str(conjecture_path.relative_to(BASE_DIR)), "expected_output": expected_output, "actual_output": actual_output, "conjecture_quality_score": conjecture_quality.score, "conjecture_quality_reason": conjecture_quality.reason, "passed": conjecture_quality.is_successful(), } ) JSON_OUT.write_text(json.dumps(results, indent=2), encoding="utf-8") lines = [ "# DeepEval Conjecture Quality Scores", "", "| Result ID | Conjecture Quality Score | Passed? |", "|---|---:|---|", ] for row in results: lines.append( f"| {row['result_id']} | {row['conjecture_quality_score']:.3f} | {row['passed']} |" ) lines.extend(["", "## Details", ""]) for row in results: lines.extend( [ f"### {row['result_id']}", "", f"**Score:** {row['conjecture_quality_score']:.3f}", "", f"**Passed:** {row['passed']}", "", row["conjecture_quality_reason"] or "No reason provided.", "", ] ) MD_OUT.write_text("\n".join(lines), encoding="utf-8") print(f"Wrote {JSON_OUT}") print(f"Wrote {MD_OUT}") if __name__ == "__main__": main()