DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
chore: remove benchmark and iso_solve test from dev
Bingxi Zhao (Frank)ee419e832ff9
diff --git a/benchmark/README.md b/benchmark/README.mddeleted file mode 100644index 95fc15c31..000000000--- a/benchmark/README.md+++ /dev/null@@ -1,236 +0,0 @@-# Benchmark - Tutor Evaluation System--本模块用于生成 AI 辅导系统的评测数据、运行对话模拟,并对 tutor 表现进行 LLM-as-judge 评估。--## 目录结构--```-benchmark/-├── config/-│ └── benchmark_config.yaml # 数据生成与评测配置-├── data/-│ ├── generated/ # 生成的 entries(JSONL、单文件 JSON)-│ ├── transcripts/ # 对话 transcript 输出-│ └── evaluations/ # 评测结果输出-├── data_generation/ # 数据生成流水线-├── simulation/ # 对话模拟(StudentAgent + 人/LLM Tutor)-├── evaluation/ # 评测逻辑(LLM-as-judge)-├── prompts/ # 各阶段 LLM prompt 模板-└── README.md-```-------## 一、数据生成 (Data Generation)--### 流程概览--```-知识库 (KB)- │- ▼ Stage 1: 发现 KB- │- ▼ Stage 2: RAG 查询 → 生成 knowledge scope- │- ▼ Stage 3: 生成学生 profile(beginner/intermediate/advanced)- │- ▼ Stage 4-5: 对每个 profile 循环直到达标- │ ├── 从 content_list 随机选 10 页连续内容- │ ├── 生成 gaps(带 source_pages)- │ ├── 生成 tasks(partition + 拒绝采样)- │ └── 若 task 数 < min_tasks_per_profile,继续生成- │- ▼ Stage 6: 输出 entries(JSONL + 单文件 JSON)-```--### 核心概念--- **Profile**:虚拟学生画像(背景、知识状态、性格、学习目的)-- **Gap**:知识缺口(misconception / incomplete / missing),含 `source_pages`-- **Task**:学习任务,对应若干 gaps,含 `initial_message`、`success_criteria`-- **Entry**:一条评测样本 = profile + gaps + task + source_content--### 配置要点 (`benchmark_config.yaml`)--| 配置项 | 说明 |-|--------|------|-| `profile_generation.profiles_per_subtopic` | 每个 KB 生成的学生数(默认 3) |-| `gap_generation.use_content_list` | 是否用 content_list 做 page-grounded gaps |-| `gap_generation.pages_per_profile` | 每个 profile 选取的连续页数(默认 10) |-| `gap_generation.rejection_sampling` | 是否对 task 做批量拒绝采样 |-| `task_generation.min_tasks_per_profile` | 每个学生至少的 task 数(默认 3) |-| `task_generation.gaps_per_batch` | 每批生成的 gap 数 |--### 使用方法--```bash-# 生成 calc1 的评测数据-python3 -m benchmark.data_generation.pipeline --kb-names calc1--# 指定配置文件-python3 -m benchmark.data_generation.pipeline --config path/to/config.yaml --kb-names calc1-```--### 输出--- `benchmark/data/generated/benchmark_{timestamp}/`- - `{entry_id}.json`:单条 entry- - `_all_entries.jsonl`:全部 entries- - `_summary.json`:统计摘要-- `benchmark/data/generated/knowledge_scopes/{kb_name}.json`:knowledge scope-------## 二、对话模拟 (Simulation)--### 模式--1. **Interactive**:人扮演 tutor,在终端或编辑器中输入回复-2. **Auto**:LLM 扮演 mock tutor--### 单次对话--```bash-# 交互模式(默认用 $EDITOR)-python3 -m benchmark.simulation.conversation --entry benchmark/data/generated/benchmark_xxx/calc1_xxx_task_001.json--# 控制台输入(空行 + Enter 发送)-python3 -m benchmark.simulation.conversation --entry path/to/entry.json --inline--# Auto 模式(LLM 当 tutor)-python3 -m benchmark.simulation.conversation --entry path/to/entry.json --auto --max-turns 10-```--### 多 Session(同一学生多次返回)--```bash-# 按 profile 从 JSONL 筛选,跑多 session-python3 -m benchmark.simulation.conversation \- --entry benchmark/data/generated/benchmark_xxx/_all_entries.jsonl \- --profile calc1_beginner_00 \- --multi-session --auto--# 显式指定 entry 列表-python3 -m benchmark.simulation.conversation \- --entries entry1.json,entry2.json,entry3.json \- --multi-session --auto--# 关闭 profile 演化-python3 -m benchmark.simulation.conversation --entry ... --profile ... --multi-session --no-evolve-```--### 输出--- Transcript 保存到 `benchmark/data/transcripts/`-- 单 session:`{entry_id}_{timestamp}.json`-- 多 session:`multi_{profile_id}_{timestamp}.json`-------## 三、评测 (Evaluation)--### 评测指标--**Turn 级**(单轮回复):-- 50% 个性化:`profile_adaptation`、`misconception_targeting`-- 25% 有效性:`response_quality`、`engagement`-- 25% 知识源对齐:`knowledge_source_alignment`(有 source_content 时)--**Dialog 级**(整场对话):-- 50% 个性化:`adaptation_consistency`、`gap_resolution`、`success_criteria_met`-- 25% 质量:`session_quality`、`student_agency`-- 25% 知识源对齐:`knowledge_source_alignment`--**综合分数**:`combined_overall_score` = 0.4 × Turn 平均 + 0.6 × Dialog 分数--### 使用方法--```bash-# 评测单个 transcript-python3 -m benchmark.evaluation.run --transcript benchmark/data/transcripts/xxx.json--# 仅 dialog 级(更快)-python3 -m benchmark.evaluation.run --transcript xxx.json --dialog-only--# 评测目录下所有 transcript-python3 -m benchmark.evaluation.run --transcript-dir benchmark/data/transcripts--# 指定输出路径-python3 -m benchmark.evaluation.run --transcript xxx.json -o results.json-```--### 输出--- 默认保存到 `benchmark/data/evaluations/{stem}_eval_{timestamp}.json`-- 支持单 session 与 multi-session transcript-------## 四、完整工作流示例--```bash-# 1. 生成数据-python3 -m benchmark.data_generation.pipeline --kb-names calc1--# 2. 运行对话(auto 或 interactive)-python3 -m benchmark.simulation.conversation \- --entry benchmark/data/generated/benchmark_xxx/_all_entries.jsonl \- --profile calc1_beginner_00 \- --multi-session --auto --max-turns 5--# 3. 评测 transcript-python3 -m benchmark.evaluation.run \- --transcript benchmark/data/transcripts/multi_calc1_beginner_00_xxx.json-```-------## 五、CLI 参数速查--### 数据生成 (`benchmark.data_generation.pipeline`)--| 参数 | 说明 |-|------|------|-| `--config` | 配置文件路径 |-| `--kb-names` | 指定 KB 名称列表(覆盖 config) |--### 对话模拟 (`benchmark.simulation.conversation`)--| 参数 | 说明 |-|------|------|-| `--entry` | Entry JSON 或 JSONL 路径 |-| `--multi-session` | 多 session 模式 |-| `--profile` | 从 JSONL 筛选的 profile_id(配合 `--entry` + `--multi-session`) |-| `--entries` | 逗号分隔的 entry 路径(配合 `--multi-session`) |-| `--no-evolve` | 关闭 profile 演化 |-| `--auto` | LLM 扮演 tutor |-| `--max-turns` | 最大轮数(默认 20) |-| `--output-dir` | transcript 输出目录 |-| `--entry-index` | JSONL 时使用的 entry 索引(默认 0) |-| `--inline` | 控制台输入(否则用编辑器) |--### 评测 (`benchmark.evaluation.run`)--| 参数 | 说明 |-|------|------|-| `--transcript` | 单个 transcript 路径 |-| `--transcript-dir` | transcript 目录(评测全部) |-| `--dialog-only` | 仅 dialog 级评测 |-| `--output` / `-o` | 结果输出路径 |-| `--temperature` | LLM 温度(默认 0.2) |-| `--verbose` / `-v` | 调试日志 |-------## 六、关键文件说明--| 文件 | 作用 |-|------|------|-| `data_generation/pipeline.py` | 数据生成主流程 |-| `data_generation/content_loader.py` | 从 content_list 加载连续 10 页 |-| `data_generation/gap_generator.py` | 生成 page-grounded gaps |-| `data_generation/task_generator.py` | 生成 tasks + 拒绝采样 |-| `simulation/student_agent.py` | LLM 学生角色 |-| `simulation/conversation.py` | 对话运行器(单/多 session) |-| `simulation/profile_evolver.py` | 多 session 间 profile 演化 |-| `evaluation/evaluator.py` | LLM-as-judge 评测逻辑 |diff --git a/benchmark/__init__.py b/benchmark/__init__.pydeleted file mode 100644index ba8ba1023..000000000--- a/benchmark/__init__.py+++ /dev/null@@ -1 +0,0 @@-# Benchmark - DeepTutor Evaluation Frameworkdiff --git a/benchmark/config/__init__.py b/benchmark/config/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/benchmark/config/benchmark_config.yaml b/benchmark/config/benchmark_config.yamldeleted file mode 100644index 852efbf10..000000000--- a/benchmark/config/benchmark_config.yaml+++ /dev/null@@ -1,83 +0,0 @@-# =============================================================================-# Benchmark Configuration - Tutor Evaluation Data Generation-# =============================================================================-# This config is used to generate evaluation data from existing per-subtopic-# knowledge bases. Subtopics have been manually split, each topic corresponds-# to a pre-built RAG knowledge base.--# Knowledge base configuration-knowledge_bases:- # Base directory for knowledge bases (may be overridden by main.yaml paths.knowledge_bases_dir)- base_dir: "./data/knowledge_bases"- # List of KB names to process (empty = auto-discover all registered KBs)- kb_names: []--# Profile generation configuration-profile_generation:- # Number of profiles to generate per subtopic- profiles_per_subtopic: 3- # Student background types- background_types:- - "beginner" # Novice, almost no relevant background- - "intermediate" # Some foundation, partial knowledge- - "advanced" # Solid foundation, wants deeper understanding--# Knowledge gap generation configuration-gap_generation:- # Use content_list for page-grounded gaps (each gap has source_pages)- use_content_list: true- # Number of pages to randomly select from content_list- pages_per_profile: 10- # Batch rejection sampling: verify task + gaps align with source- rejection_sampling: true- # Number of knowledge gaps per profile- gaps_per_profile: 3- # Gap type distribution- severity_levels:- - name: "misconception" # Has incorrect understanding- weight: 0.3- - name: "incomplete" # Partial / one-sided understanding- weight: 0.4- - name: "missing" # Completely missing a knowledge point- weight: 0.3--# Task generation configuration-task_generation:- # Minimum tasks per profile; keep generating gaps+tasks until达标- min_tasks_per_profile: 3- # Gaps per batch when generating more to meet min_tasks- gaps_per_batch: 3- # Task types- task_types:- - name: "concept_understanding" # Wants to understand a concept- weight: 0.3- - name: "problem_solving" # Wants to solve a type of problem- weight: 0.3- - name: "application" # Wants to know how to apply knowledge- weight: 0.2- - name: "comparison" # Wants to distinguish confusable concepts- weight: 0.2--# RAG query configuration (used to extract knowledge scope from KBs)-rag_query:- # Query mode- mode: "naive"- # Seed queries for probing KB content- seed_queries:- - "What are the main knowledge points and core concepts in this content?"- - "What key theorems, formulas, or methods does this content cover?"- - "What are typical application scenarios and example problems in this content?"--# LLM configuration (leave empty to use system default LLM config)-llm:- temperature: 0.7- max_tokens: 4096--# Output configuration-output:- # Output directory- output_dir: "./benchmark/data/generated"- # Output format- format: "jsonl" # jsonl / json- # Whether to save intermediate results- save_intermediate: truediff --git a/benchmark/data_generation/__init__.py b/benchmark/data_generation/__init__.pydeleted file mode 100644index 22aab44b2..000000000--- a/benchmark/data_generation/__init__.py+++ /dev/null@@ -1,14 +0,0 @@-# Data Generation Pipeline for Benchmark-#-# Modules:-# - llm_utils: LLM calling utilities (prompt loading, JSON parsing)-# - scope_generator: Generate knowledge scope from KB via RAG-# - profile_generator: Generate student profiles-# - gap_generator: Generate knowledge gaps-# - task_generator: Generate learning tasks-# - pipeline: Orchestrate the full pipeline--from benchmark.data_generation.pipeline import DataGenerationPipeline-from benchmark.data_generation.request_pipeline import main as generate_requests_main--__all__ = ["DataGenerationPipeline", "generate_requests_main"]diff --git a/benchmark/data_generation/batch_profiles.py b/benchmark/data_generation/batch_profiles.pydeleted file mode 100644index 156ebe9b8..000000000--- a/benchmark/data_generation/batch_profiles.py+++ /dev/null@@ -1,235 +0,0 @@-#!/usr/bin/env python3-"""-Batch Profile Generator — generate profiles for all healthy knowledge bases.--Discovers usable KBs, generates knowledge scope + student profiles in parallel.--Usage:- python3 -m benchmark.data_generation.batch_profiles- python3 -m benchmark.data_generation.batch_profiles --kb-dir data/knowledge_bases --concurrency 8- python3 -m benchmark.data_generation.batch_profiles --kb-names kb1,kb2,kb3-"""-from __future__ import annotations--import argparse-import asyncio-import json-import logging-import sys-from datetime import datetime-from pathlib import Path--import yaml--_THIS_FILE = Path(__file__).resolve()-PROJECT_ROOT = _THIS_FILE.parents[2]-if str(PROJECT_ROOT) not in sys.path:- sys.path.insert(0, str(PROJECT_ROOT))--from benchmark.data_generation.profile_generator import generate_profiles_for_kb-from benchmark.data_generation.scope_generator import generate_knowledge_scope--logger = logging.getLogger("benchmark.batch_profiles")--DEFAULT_CONFIG = PROJECT_ROOT / "benchmark" / "config" / "benchmark_config.yaml"--CRITICAL_RAG_FILES = [- "kv_store_text_chunks.json",- "kv_store_full_docs.json",- "kv_store_full_entities.json",- "kv_store_full_relations.json",- "vdb_chunks.json",- "vdb_entities.json",- "vdb_relationships.json",- "graph_chunk_entity_relation.graphml",-]---def _discover_healthy_kbs(kb_base_dir: Path) -> list[str]:- """Return names of KBs whose RAG storage is complete."""- healthy = []- for d in sorted(kb_base_dir.iterdir()):- if not d.is_dir():- continue- rag_dir = d / "rag_storage"- if not rag_dir.is_dir():- continue- ok = True- for fname in CRITICAL_RAG_FILES:- fpath = rag_dir / fname- if not fpath.exists() or fpath.stat().st_size == 0:- ok = False- break- if ok:- healthy.append(d.name)- return healthy---async def _process_one_kb(- kb_name: str,- kb_base_dir: str,- profile_cfg: dict,- rag_cfg: dict,- output_dir: Path,- semaphore: asyncio.Semaphore,-) -> dict | None:- """Generate scope + profiles for a single KB."""- out_path = output_dir / f"{kb_name}.json"- if out_path.exists():- try:- with open(out_path, encoding="utf-8") as f:- existing = json.load(f)- if existing.get("profiles") and existing.get("knowledge_scope"):- logger.info("SKIP (complete): %s", kb_name)- return existing- except Exception:- pass-- async with semaphore:- logger.info("Processing: %s", kb_name)- try:- scope = await generate_knowledge_scope(- kb_name=kb_name,- seed_queries=rag_cfg.get("seed_queries"),- mode=rag_cfg.get("mode", "naive"),- kb_base_dir=kb_base_dir,- )- profiles = await generate_profiles_for_kb(- knowledge_scope=scope,- background_types=profile_cfg.get(- "background_types", ["beginner", "intermediate", "advanced"]- ),- profiles_per_kb=profile_cfg.get("profiles_per_subtopic", 3),- )-- out = {- "kb_name": kb_name,- "knowledge_scope": scope,- "profiles": profiles,- "num_profiles": len(profiles),- }- with open(out_path, "w", encoding="utf-8") as f:- json.dump(out, f, ensure_ascii=False, indent=2)- logger.info("Done: %s -> %d profiles", kb_name, len(profiles))- return out- except Exception as e:- logger.error("FAILED: %s — %s", kb_name, e)- return None---async def main() -> None:- logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )-- parser = argparse.ArgumentParser(- description="Batch generate profiles for all healthy knowledge bases"- )- parser.add_argument(- "--kb-dir",- default="data/knowledge_bases",- help="Path to knowledge_bases directory (default: data/knowledge_bases)",- )- parser.add_argument(- "--config",- default=str(DEFAULT_CONFIG),- help=f"Benchmark config path (default: {DEFAULT_CONFIG})",- )- parser.add_argument(- "--output-dir",- default=None,- help="Output directory. If omitted, creates a new timestamped dir.",- )- parser.add_argument(- "--kb-names",- default=None,- help="Comma-separated KB names to process (default: auto-discover all healthy KBs).",- )- parser.add_argument(- "--concurrency",- type=int,- default=6,- help="Max parallel KB processing (default: 6)",- )- parser.add_argument(- "--force",- action="store_true",- help="Force regeneration even if output already exists.",- )- args = parser.parse_args()-- kb_base_dir = Path(args.kb_dir)- if not kb_base_dir.is_absolute():- kb_base_dir = (PROJECT_ROOT / kb_base_dir).resolve()-- cfg_path = Path(args.config)- if not cfg_path.is_absolute():- cfg_path = (PROJECT_ROOT / cfg_path).resolve()- with open(cfg_path, encoding="utf-8") as f:- cfg = yaml.safe_load(f) or {}-- profile_cfg = cfg.get("profile_generation", {})- rag_cfg = cfg.get("rag_query", {})-- if args.kb_names:- kb_names = [n.strip() for n in args.kb_names.split(",") if n.strip()]- else:- kb_names = _discover_healthy_kbs(kb_base_dir)-- if not kb_names:- print("No healthy knowledge bases found.")- sys.exit(0)-- if args.output_dir:- output_dir = Path(args.output_dir)- if not output_dir.is_absolute():- output_dir = (PROJECT_ROOT / output_dir).resolve()- else:- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- output_dir = PROJECT_ROOT / "benchmark" / "data" / "generated" / f"profiles_{timestamp}"- output_dir.mkdir(parents=True, exist_ok=True)-- print(f"KBs: {len(kb_names)} | Concurrency: {args.concurrency} | Output: {output_dir}")- for name in kb_names:- print(f" - {name}")-- semaphore = asyncio.Semaphore(args.concurrency)- tasks = [- _process_one_kb(- kb_name=name,- kb_base_dir=str(kb_base_dir),- profile_cfg=profile_cfg,- rag_cfg=rag_cfg,- output_dir=output_dir,- semaphore=semaphore,- )- for name in kb_names- ]- results = await asyncio.gather(*tasks)-- success = [r for r in results if r is not None]- failed = len(results) - len(success)-- summary = {- "timestamp": datetime.now().isoformat(),- "kb_base_dir": str(kb_base_dir),- "num_kbs": len(kb_names),- "num_success": len(success),- "num_failed": failed,- "results": [- {"kb_name": r["kb_name"], "num_profiles": r["num_profiles"]}- for r in success- ],- }- summary_path = output_dir / "_summary.json"- with open(summary_path, "w", encoding="utf-8") as f:- json.dump(summary, f, ensure_ascii=False, indent=2)-- print(f"\nDone. Success: {len(success)}/{len(kb_names)} | Failed: {failed}")- print(f"Output: {output_dir}")- print(f"Summary: {summary_path}")---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/data_generation/content_loader.py b/benchmark/data_generation/content_loader.pydeleted file mode 100644index 9cb249781..000000000--- a/benchmark/data_generation/content_loader.py+++ /dev/null@@ -1,146 +0,0 @@-#!/usr/bin/env python-"""-Content List Loader - Load and extract page content from KB content_list--Used for page-grounded gap generation: randomly select N pages and extract-text content for LLM-based gap generation and evaluator source alignment.-"""--import json-import logging-import random-from collections import defaultdict-from pathlib import Path--logger = logging.getLogger("benchmark.content_loader")---def load_content_list(kb_base_dir: str | Path, kb_name: str) -> list[dict] | None:- """- Load content list JSON for a knowledge base.-- Args:- kb_base_dir: Base directory for knowledge bases- kb_name: KB name (e.g. calc1)-- Returns:- List of content items (type, text, page_idx, ...) or None if not found- """- base = Path(kb_base_dir)- content_list_dir = base / kb_name / "content_list"- if not content_list_dir.exists():- logger.warning(f"Content list dir not found: {content_list_dir}")- return None-- json_files = sorted(content_list_dir.glob("*.json"))- if not json_files:- logger.warning(f"No JSON files in {content_list_dir}")- return None-- with open(json_files[0], encoding="utf-8") as f:- items = json.load(f)-- if not isinstance(items, list):- logger.warning(f"Content list is not a list: {type(items)}")- return None-- return items---def extract_page_content(- content_items: list[dict],- page_indices: list[int] | None = None,-) -> dict[int, str]:- """- Extract text content grouped by page_idx.-- Args:- content_items: List of items from content_list (each has type, text?, page_idx?)- page_indices: If provided, only extract these pages. If None, use all pages.-- Returns:- Dict mapping page_idx -> concatenated text content- """- text_by_page: dict[int, list[str]] = defaultdict(list)-- for item in content_items:- if item.get("type") != "text":- continue- text = item.get("text", "").strip()- if not text:- continue- page_idx = item.get("page_idx", 0)- if page_indices is not None and page_idx not in page_indices:- continue- text_by_page[page_idx].append(text)-- return {p: "\n".join(text_by_page[p]) for p in sorted(text_by_page.keys())}---def select_random_pages(- content_items: list[dict],- num_pages: int = 10,- seed: int | None = None,-) -> list[int]:- """- Select N consecutive pages with random start position.-- Args:- content_items: Content list items- num_pages: Number of consecutive pages to select- seed: Optional random seed for reproducibility-- Returns:- List of consecutive page_idx values- """- all_pages = sorted(- set(item["page_idx"] for item in content_items if "page_idx" in item)- )- if not all_pages:- return []-- n = min(num_pages, len(all_pages))- max_start = len(all_pages) - n- if max_start < 0:- return all_pages-- if seed is not None:- rng = random.Random(seed)- start = rng.randint(0, max_start)- else:- start = random.randint(0, max_start)-- return all_pages[start : start + n]---def load_page_content_for_profile(- kb_base_dir: str | Path,- kb_name: str,- num_pages: int = 10,- profile_id: str | None = None,-) -> tuple[dict[int, str], list[int]] | None:- """- Load content list, select N random pages, extract text.-- Args:- kb_base_dir: KB base directory- kb_name: KB name- num_pages: Number of pages to select- profile_id: Optional, used as seed for reproducible page selection per profile-- Returns:- (page_content dict, selected_page_indices) or None if content_list not found- """- items = load_content_list(kb_base_dir, kb_name)- if not items:- return None-- seed = hash(profile_id) % (2**32) if profile_id else None- selected = select_random_pages(items, num_pages=num_pages, seed=seed)- page_content = extract_page_content(items, page_indices=selected)-- logger.info(- f" Loaded {len(page_content)} pages for {profile_id or kb_name}: "- f"page_indices={selected}"- )- return page_content, selecteddiff --git a/benchmark/data_generation/gap_generator.py b/benchmark/data_generation/gap_generator.pydeleted file mode 100644index 726777205..000000000--- a/benchmark/data_generation/gap_generator.py+++ /dev/null@@ -1,233 +0,0 @@-#!/usr/bin/env python-"""-Gap Generator - Generate knowledge gaps for student profiles--Creates realistic knowledge gaps (misconceptions, incomplete understanding,-missing knowledge) tailored to each student's profile and the subtopic's-knowledge scope.--Supports two modes:-- Scope-based: uses knowledge_scope (RAG query result)-- Page-grounded: uses content_list page content; each gap has source_pages-"""--import json-import logging--from benchmark.data_generation.llm_utils import call_llm_json, load_prompt, render_prompt--logger = logging.getLogger("benchmark.gap_generator")---async def generate_gaps(- knowledge_scope: dict,- student_profile: dict,- num_gaps: int = 3,- severity_weights: dict[str, float] | None = None,- gap_id_offset: int = 0,-) -> list[dict]:- """- Generate knowledge gaps for a specific (scope, profile) pair.-- Args:- knowledge_scope: Knowledge scope dictionary- student_profile: Student profile dictionary- num_gaps: Number of gaps to generate- severity_weights: Distribution of gap types, e.g.:- {"misconception": 0.3, "incomplete": 0.4, "missing": 0.3}-- Returns:- List of knowledge gap dictionaries- """- if severity_weights is None:- severity_weights = {"misconception": 0.3, "incomplete": 0.4, "missing": 0.3}-- profile_id = student_profile.get("profile_id", "unknown")- logger.info(f"Generating {num_gaps} gaps for profile '{profile_id}'")-- prompt = load_prompt("generate_gaps")-- scope_text = json.dumps(knowledge_scope, ensure_ascii=False, indent=2)- profile_text = json.dumps(student_profile, ensure_ascii=False, indent=2)-- user_prompt = render_prompt(- prompt["user_template"],- knowledge_scope=scope_text,- student_profile=profile_text,- num_gaps=num_gaps,- misconception_weight=severity_weights.get("misconception", 0.3),- incomplete_weight=severity_weights.get("incomplete", 0.4),- missing_weight=severity_weights.get("missing", 0.3),- )-- result = await call_llm_json(- user_prompt=user_prompt,- system_prompt=prompt["system"],- temperature=0.7,- max_tokens=4096,- )-- gaps = result.get("gaps", [])-- # Ensure gap IDs are unique- for i, gap in enumerate(gaps):- if "gap_id" not in gap:- gap["gap_id"] = f"gap_{profile_id}_{i + gap_id_offset:02d}"-- logger.info(f" Generated {len(gaps)} gaps: {[g.get('type', '?') for g in gaps]}")- return gaps---async def generate_gaps_for_profiles(- knowledge_scope: dict,- profiles: list[dict],- gaps_per_profile: int = 3,- severity_weights: dict[str, float] | None = None,-) -> dict[str, list[dict]]:- """- Generate gaps for multiple profiles under the same knowledge scope.-- Args:- knowledge_scope: Knowledge scope dictionary- profiles: List of student profile dictionaries- gaps_per_profile: Number of gaps per profile- severity_weights: Distribution of gap types-- Returns:- Dictionary mapping profile_id -> list of gaps- """- all_gaps: dict[str, list[dict]] = {}-- for profile in profiles:- profile_id = profile.get("profile_id", "unknown")-- try:- gaps = await generate_gaps(- knowledge_scope=knowledge_scope,- student_profile=profile,- num_gaps=gaps_per_profile,- severity_weights=severity_weights,- )- all_gaps[profile_id] = gaps- except Exception as e:- logger.error(f"Failed to generate gaps for profile {profile_id}: {e}")- all_gaps[profile_id] = []-- return all_gaps---def _format_page_content(page_content: dict[int, str]) -> str:- """Format page_content dict for prompt."""- lines = []- for page_idx in sorted(page_content.keys()):- text = page_content[page_idx]- if text:- lines.append(f"### Page {page_idx}\n{text[:3000]}{'...' if len(text) > 3000 else ''}")- return "\n\n".join(lines) if lines else "(no content)"---async def generate_gaps_from_pages(- page_content: dict[int, str],- student_profile: dict,- num_gaps: int = 3,- severity_weights: dict[str, float] | None = None,- gap_id_offset: int = 0,-) -> list[dict]:- """- Generate knowledge gaps grounded in specific page content.-- Each gap will have source_pages (list of page indices).-- Args:- page_content: Dict mapping page_idx -> text content- student_profile: Student profile dictionary- num_gaps: Number of gaps to generate- severity_weights: Distribution of gap types-- Returns:- List of gap dicts with source_pages field- """- if severity_weights is None:- severity_weights = {"misconception": 0.3, "incomplete": 0.4, "missing": 0.3}-- profile_id = student_profile.get("profile_id", "unknown")- logger.info(f"Generating {num_gaps} page-grounded gaps for profile '{profile_id}'")-- prompt = load_prompt("generate_gaps_page")- page_text = _format_page_content(page_content)- profile_text = json.dumps(student_profile, ensure_ascii=False, indent=2)-- user_prompt = render_prompt(- prompt["user_template"],- page_content=page_text,- student_profile=profile_text,- num_gaps=num_gaps,- misconception_weight=severity_weights.get("misconception", 0.3),- incomplete_weight=severity_weights.get("incomplete", 0.4),- missing_weight=severity_weights.get("missing", 0.3),- )-- result = await call_llm_json(- user_prompt=user_prompt,- system_prompt=prompt["system"],- temperature=0.7,- max_tokens=4096,- )-- gaps = result.get("gaps", [])-- for i, gap in enumerate(gaps):- if "gap_id" not in gap:- gap["gap_id"] = f"gap_{profile_id}_{i + gap_id_offset:02d}"- if "source_pages" not in gap or not isinstance(gap["source_pages"], list):- gap["source_pages"] = list(page_content.keys())[:1] if page_content else []-- logger.info(- f" Generated {len(gaps)} gaps: {[g.get('type', '?') for g in gaps]}, "- f"source_pages={[g.get('source_pages', []) for g in gaps]}"- )- return gaps---async def generate_gaps_for_profiles_with_pages(- page_content_by_profile: dict[str, tuple[dict[int, str], list[int]]],- profiles: list[dict],- gaps_per_profile: int = 3,- severity_weights: dict[str, float] | None = None,-) -> dict[str, list[dict]]:- """- Generate page-grounded gaps for multiple profiles.-- Args:- page_content_by_profile: profile_id -> (page_content dict, selected_page_indices)- profiles: List of student profiles- gaps_per_profile: Number of gaps per profile- severity_weights: Gap type distribution-- Returns:- profile_id -> list of gaps (each with source_pages)- """- all_gaps: dict[str, list[dict]] = {}-- for profile in profiles:- profile_id = profile.get("profile_id", "unknown")- pc_data = page_content_by_profile.get(profile_id)- if not pc_data:- logger.warning(f"No page content for profile {profile_id}, skipping")- all_gaps[profile_id] = []- continue-- page_content, _selected = pc_data- try:- gaps = await generate_gaps_from_pages(- page_content=page_content,- student_profile=profile,- num_gaps=gaps_per_profile,- severity_weights=severity_weights,- )- all_gaps[profile_id] = gaps- except Exception as e:- logger.error(f"Failed to generate gaps for profile {profile_id}: {e}")- all_gaps[profile_id] = []-- return all_gapsdiff --git a/benchmark/data_generation/init_kbs_and_profiles.py b/benchmark/data_generation/init_kbs_and_profiles.pydeleted file mode 100644index 51fe496bb..000000000--- a/benchmark/data_generation/init_kbs_and_profiles.py+++ /dev/null@@ -1,752 +0,0 @@-#!/usr/bin/env python3-"""-Initialize one KB per PDF from ../documents, then generate profiles.--Flow per PDF:- 1) Create KB (name derived from PDF filename)- 2) Process document into RAG KB- 3) Generate knowledge scope- 4) Generate student profiles- 5) Save outputs under benchmark/data/generated/profiles_from_documents_<timestamp>/-"""--from __future__ import annotations--import argparse-import asyncio-import json-import logging-import os-import re-import shutil-import sys-from datetime import datetime-from pathlib import Path--import yaml--# Ensure project root is importable when script is executed directly.-_THIS_FILE = Path(__file__).resolve()-_PROJECT_ROOT_FOR_IMPORT = _THIS_FILE.parents[2]-if str(_PROJECT_ROOT_FOR_IMPORT) not in sys.path:- sys.path.insert(0, str(_PROJECT_ROOT_FOR_IMPORT))--from benchmark.data_generation.profile_generator import generate_profiles_for_kb-from benchmark.data_generation.scope_generator import generate_knowledge_scope-from src.knowledge.initializer import KnowledgeBaseInitializer--logger = logging.getLogger("benchmark.init_kbs_profiles")--PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent-DEFAULT_CONFIG = PROJECT_ROOT / "benchmark" / "config" / "benchmark_config.yaml"-DEFAULT_DOCS_DIR = PROJECT_ROOT.parent / "documents"-MAX_CONCURRENCY = 4---class PipelineAbortError(RuntimeError):- """Abort all processing when any single PDF pipeline fails."""---def _runtime_status(message: str) -> None:- """Print concise runtime scheduler status."""- print(message, flush=True)---class _LightRAGProgressHandler(logging.Handler):- """Direct handler for LightRAG chunk progress.-- NOT a StreamHandler subclass, so LightRAGLogContext won't remove it.- """-- _formatter = logging.Formatter("%(asctime)s [lightrag] %(levelname)s: %(message)s")-- def emit(self, record: logging.LogRecord) -> None:- try:- print(self._formatter.format(record), flush=True)- except Exception:- self.handleError(record)---def _configure_logging() -> None:- """Configure default logging (INFO)."""- logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )-- lightrag_logger = logging.getLogger("lightrag")- lightrag_logger.setLevel(logging.INFO)- handler = _LightRAGProgressHandler()- handler.setLevel(logging.INFO)- lightrag_logger.addHandler(handler)---def _sanitize_kb_name(name: str) -> str:- """Convert filename stem into a valid kb_name."""- s = name.strip().lower()- s = re.sub(r"[^a-z0-9]+", "_", s)- s = s.strip("_")- return s or "kb"---def _unique_name(base: str, used: set[str]) -> str:- """Make KB name unique in current run."""- if base not in used:- used.add(base)- return base- i = 2- while f"{base}_{i}" in used:- i += 1- name = f"{base}_{i}"- used.add(name)- return name---def _load_config(path: Path) -> dict:- with open(path, encoding="utf-8") as f:- return yaml.safe_load(f) or {}---def _cleanup_failed_kb_data(kb_base_dir: Path, kb_name: str, output_dir: Path) -> None:- """Remove artifacts for a failed PDF pipeline."""- kb_dir = kb_base_dir / kb_name- output_json = output_dir / f"{kb_name}.json"-- if output_json.exists():- try:- output_json.unlink()- logger.info("Removed failed output file: %s", output_json)- except Exception as e:- logger.warning("Failed to remove output file %s: %s", output_json, e)-- if kb_dir.exists():- try:- shutil.rmtree(kb_dir)- logger.info("Removed failed KB directory: %s", kb_dir)- except Exception as e:- logger.warning("Failed to remove KB directory %s: %s", kb_dir, e)---def _parse_gpu_ids(raw: str) -> list[str]:- ids = [p.strip() for p in raw.split(",") if p.strip()]- return ids or ["0"]---_RAG_CRITICAL_FILES = [- "kv_store_text_chunks.json",- "kv_store_full_docs.json",- "kv_store_full_entities.json",- "kv_store_full_relations.json",- "vdb_chunks.json",- "vdb_entities.json",- "vdb_relationships.json",- "graph_chunk_entity_relation.graphml",-]---def _is_kb_rag_complete(kb_base_dir: Path, kb_name: str) -> bool:- """Check if a KB's RAG storage is fully built (all critical files present and non-empty)."""- rag_dir = kb_base_dir / kb_name / "rag_storage"- if not rag_dir.is_dir():- return False- for fname in _RAG_CRITICAL_FILES:- fpath = rag_dir / fname- if not fpath.exists() or fpath.stat().st_size == 0:- return False- # Check doc_status: all documents should be 'processed'- status_path = rag_dir / "kv_store_doc_status.json"- if status_path.exists():- try:- with open(status_path, encoding="utf-8") as f:- doc_status = json.load(f)- for doc in doc_status.values():- if isinstance(doc, dict) and doc.get("status") not in ("processed",):- return False- except Exception:- return False- return True---def _is_profile_complete(output_dir: Path, kb_name: str) -> bool:- """Check if profile output already exists with valid content."""- out_path = output_dir / f"{kb_name}.json"- if not out_path.exists():- return False- try:- with open(out_path, encoding="utf-8") as f:- data = json.load(f)- return bool(data.get("profiles")) and bool(data.get("knowledge_scope"))- except Exception:- return False---async def _process_pdf(- *,- pdf_path: Path,- kb_name: str,- kb_base_dir: Path,- profile_cfg: dict,- rag_cfg: dict,- output_dir: Path,- skip_processing: bool,- skip_extract: bool,- use_mineru_api: bool,- mineru_api_token: str | None,- mineru_model_version: str,- force: bool = False,- kb_only: bool = False,-) -> dict | None:- """Initialize KB from one PDF and generate profiles."""- if not kb_only and not force and _is_profile_complete(output_dir, kb_name):- logger.info("SKIP (complete): %s — profile already exists", kb_name)- return None-- logger.info("=" * 70)- logger.info("PDF: %s", pdf_path.name)- logger.info("KB : %s", kb_name)- logger.info("=" * 70)-- if not skip_processing:- if not force and _is_kb_rag_complete(kb_base_dir, kb_name):- logger.info("SKIP RAG build (complete): %s — rag_storage already built", kb_name)- else:- initializer = KnowledgeBaseInitializer(- kb_name=kb_name,- base_dir=str(kb_base_dir),- )- initializer.create_directory_structure()- copied = initializer.copy_documents([str(pdf_path)])- if not copied:- raise RuntimeError(f"Failed to copy PDF: {pdf_path}")-- await initializer.process_documents(- use_mineru_api=use_mineru_api,- mineru_api_token=mineru_api_token,- mineru_model_version=mineru_model_version,- )-- return await _run_post_gpu_stage(- pdf_path=pdf_path,- kb_name=kb_name,- kb_base_dir=kb_base_dir,- profile_cfg=profile_cfg,- rag_cfg=rag_cfg,- output_dir=output_dir,- skip_extract=skip_extract,- kb_only=kb_only,- )---async def _run_gpu_stage_only(- *,- pdf_path: Path,- kb_name: str,- kb_base_dir: Path,- use_mineru_api: bool,- mineru_api_token: str | None,- mineru_model_version: str,- force: bool = False,-) -> None:- """Run only GPU-heavy stage: create/copy/process documents."""- if not force and _is_kb_rag_complete(kb_base_dir, kb_name):- logger.info("SKIP GPU stage (complete): %s — rag_storage already built", kb_name)- return- try:- logger.info("=" * 70)- logger.info("GPU stage start | PDF: %s | KB: %s", pdf_path.name, kb_name)- logger.info("=" * 70)- initializer = KnowledgeBaseInitializer(kb_name=kb_name, base_dir=str(kb_base_dir))- initializer.create_directory_structure()- copied = initializer.copy_documents([str(pdf_path)])- if not copied:- raise RuntimeError(f"Failed to copy PDF: {pdf_path}")- await initializer.process_documents(- use_mineru_api=use_mineru_api,- mineru_api_token=mineru_api_token,- mineru_model_version=mineru_model_version,- )- except Exception as e:- logger.exception("Failed on %s -> %s: %s", pdf_path.name, kb_name, e)- raise PipelineAbortError(- f"GPU stage failed for {pdf_path.name} (kb={kb_name}). Program terminated."- ) from e---async def _run_post_gpu_stage(- *,- pdf_path: Path,- kb_name: str,- kb_base_dir: Path,- profile_cfg: dict,- rag_cfg: dict,- output_dir: Path,- skip_extract: bool,- kb_only: bool = False,-) -> dict:- """Run non-GPU stage after documents are processed."""- initializer = KnowledgeBaseInitializer(kb_name=kb_name, base_dir=str(kb_base_dir))- if not skip_extract:- await asyncio.to_thread(initializer.extract_numbered_items)-- if kb_only:- logger.info("KB-only mode: skipping profile generation for %s", kb_name)- return {"pdf_file": str(pdf_path), "kb_name": kb_name, "knowledge_scope": {}, "profiles": [], "num_profiles": 0}-- scope = await generate_knowledge_scope(- kb_name=kb_name,- seed_queries=rag_cfg.get("seed_queries"),- mode=rag_cfg.get("mode", "naive"),- kb_base_dir=str(kb_base_dir),- )- profiles = await generate_profiles_for_kb(- knowledge_scope=scope,- background_types=profile_cfg.get(- "background_types", ["beginner", "intermediate", "advanced"]- ),- profiles_per_kb=profile_cfg.get("profiles_per_subtopic", 3),- )-- out = {- "pdf_file": str(pdf_path),- "kb_name": kb_name,- "knowledge_scope": scope,- "profiles": profiles,- "num_profiles": len(profiles),- }- out_path = output_dir / f"{kb_name}.json"- with open(out_path, "w", encoding="utf-8") as f:- json.dump(out, f, ensure_ascii=False, indent=2)- logger.info("Saved: %s", out_path)- return out---async def _run_jobs_with_gpu_pipeline(- *,- jobs: list[tuple[Path, str]],- gpu_ids: list[str],- config_path: Path,- kb_base_dir: Path,- profile_cfg: dict,- rag_cfg: dict,- output_dir: Path,- skip_extract: bool,- use_mineru_api: bool,- mineru_api_token: str | None,- mineru_model_version: str,- force: bool = False,- kb_only: bool = False,-) -> list[dict]:- """Run jobs with GPU-stage sharding and immediate refill."""- if not kb_only and not force:- original_count = len(jobs)- jobs = [- (pdf, kb) for pdf, kb in jobs- if not _is_profile_complete(output_dir, kb)- ]- skipped = original_count - len(jobs)- if skipped:- logger.info("Resume: skipping %d already-complete jobs", skipped)- if not jobs:- logger.info("All jobs already complete — nothing to do.")- return []-- available_gpus = list(gpu_ids)- running: list[dict] = []- waiting_jobs = list(jobs)- results: list[dict] = []- post_tasks: set[asyncio.Task] = set()-- async def _start_one(pdf_path: Path, kb_name: str, gpu_id: str) -> dict:- cmd = [- sys.executable,- str(Path(__file__).resolve()),- "--single-gpu-stage",- str(pdf_path),- "--single-kb-name",- kb_name,- "--config",- str(config_path),- "--mineru-model-version",- mineru_model_version,- "--gpu-ids",- gpu_id,- ]- if skip_extract:- cmd.append("--skip-extract")- if use_mineru_api:- cmd.append("--use-mineru-api")- else:- cmd.append("--no-use-mineru-api")- if mineru_api_token:- cmd.extend(["--mineru-api-token", mineru_api_token])- if force:- cmd.append("--force")-- env = os.environ.copy()- env["CUDA_VISIBLE_DEVICES"] = gpu_id- remaining_after_dispatch = len(waiting_jobs)- _runtime_status(- f"[GPU {gpu_id}] running {pdf_path.name} | queue remaining: {remaining_after_dispatch}"- )- proc = await asyncio.create_subprocess_exec(*cmd, env=env)- wait_task = asyncio.create_task(proc.wait())- return {- "pdf_path": pdf_path,- "kb_name": kb_name,- "gpu_id": gpu_id,- "proc": proc,- "wait_task": wait_task,- }-- while waiting_jobs or running or post_tasks:- while waiting_jobs and available_gpus:- pdf_path, kb_name = waiting_jobs.pop(0)- gpu_id = available_gpus.pop(0)- running.append(await _start_one(pdf_path, kb_name, gpu_id))-- if not running and not post_tasks:- break-- wait_targets = [r["wait_task"] for r in running] + list(post_tasks)- if not wait_targets:- break- done, _ = await asyncio.wait(wait_targets, return_when=asyncio.FIRST_COMPLETED)-- finished_entries = [r for r in running if r["wait_task"] in done]- for entry in finished_entries:- running.remove(entry)- available_gpus.append(entry["gpu_id"])-- exit_code = entry["wait_task"].result()- if exit_code != 0:- logger.error(- "Job failed: %s (pdf=%s) on GPU %s, exit_code=%s",- entry["kb_name"],- entry["pdf_path"].name,- entry["gpu_id"],- exit_code,- )- for other in running:- other["proc"].terminate()- await asyncio.gather(*[r["wait_task"] for r in running], return_exceptions=True)- for task in post_tasks:- task.cancel()- await asyncio.gather(*post_tasks, return_exceptions=True)- _cleanup_failed_kb_data(- kb_base_dir=kb_base_dir, kb_name=entry["kb_name"], output_dir=output_dir- )- raise PipelineAbortError(- f"Pipeline failed for {entry['pdf_path'].name} (kb={entry['kb_name']})."- )-- # GPU stage done -> immediately schedule non-GPU stage.- post_task = asyncio.create_task(- _run_post_gpu_stage(- pdf_path=entry["pdf_path"],- kb_name=entry["kb_name"],- kb_base_dir=kb_base_dir,- profile_cfg=profile_cfg,- rag_cfg=rag_cfg,- output_dir=output_dir,- skip_extract=skip_extract,- kb_only=kb_only,- )- )- post_tasks.add(post_task)-- finished_post = [t for t in post_tasks if t in done]- for task in finished_post:- post_tasks.remove(task)- exc = task.exception()- if exc is not None:- for other in running:- other["proc"].terminate()- await asyncio.gather(*[r["wait_task"] for r in running], return_exceptions=True)- for t in post_tasks:- t.cancel()- await asyncio.gather(*post_tasks, return_exceptions=True)- raise PipelineAbortError(str(exc))- results.append(task.result())-- return results---async def main() -> None:- parser = argparse.ArgumentParser(- description="Initialize one KB per PDF in ../documents, then generate profiles."- )- parser.add_argument(- "--docs-dir",- default=str(DEFAULT_DOCS_DIR),- help=f"Directory containing PDF files (default: {DEFAULT_DOCS_DIR})",- )- parser.add_argument(- "--docs-folder",- default=None,- help=(- "Folder name under project parent directory. "- "Example: --docs-folder documents_alt -> ../documents_alt"- ),- )- parser.add_argument(- "--config",- default=str(DEFAULT_CONFIG),- help=f"Benchmark config path (default: {DEFAULT_CONFIG})",- )- parser.add_argument(- "--skip-extract",- action="store_true",- help="Skip numbered items extraction for faster initialization",- )- parser.add_argument(- "--skip-processing",- action="store_true",- help="Skip document parsing/processing and reuse existing KB content_list/rag_storage.",- )- parser.add_argument(- "--limit",- type=int,- default=0,- help="Only process first N PDFs (0 = all)",- )- parser.add_argument(- "--use-mineru-api",- action=argparse.BooleanOptionalAction,- default=True,- help="Use MinerU cloud API for parsing (default: True). Use --no-use-mineru-api for local parser.",- )- parser.add_argument(- "--mineru-api-token",- default=None,- help="MinerU API token (falls back to MINERU_API_TOKEN env var if omitted).",- )- parser.add_argument(- "--mineru-model-version",- default="vlm",- help='MinerU API model version (default: "vlm").',- )- parser.add_argument(- "--gpu-ids",- default="0,1,2,3",- help='GPU ids for sharding workloads, comma-separated (default: "0,1,2,3").',- )- parser.add_argument(- "--serial",- action="store_true",- help="Run in serial mode (default is parallel GPU pipeline mode).",- )- parser.add_argument(- "--output-dir",- default=None,- help="Resume into an existing output directory instead of creating a new one.",- )- parser.add_argument(- "--kb-only",- action="store_true",- help="Only build knowledge bases, skip profile generation.",- )- parser.add_argument(- "--force",- action="store_true",- help="Force re-processing of all KBs, ignoring existing results.",- )- parser.add_argument("--single-gpu-stage", default=None, help=argparse.SUPPRESS)- parser.add_argument("--single-kb-name", default=None, help=argparse.SUPPRESS)- args = parser.parse_args()-- _configure_logging()-- cfg_path = Path(args.config)- if not cfg_path.is_absolute():- cfg_path = (PROJECT_ROOT / cfg_path).resolve()- cfg = _load_config(cfg_path)-- kb_base_dir = Path(- cfg.get("knowledge_bases", {}).get("base_dir", "./data/knowledge_bases")- )- if not kb_base_dir.is_absolute():- kb_base_dir = (PROJECT_ROOT / kb_base_dir).resolve()-- profile_cfg = cfg.get("profile_generation", {})- rag_cfg = cfg.get("rag_query", {})-- if args.single_gpu_stage:- if not args.single_kb_name:- raise ValueError("--single-gpu-stage mode requires --single-kb-name")- pdf_path = Path(args.single_gpu_stage).resolve()- await _run_gpu_stage_only(- pdf_path=pdf_path,- kb_name=args.single_kb_name,- kb_base_dir=kb_base_dir,- use_mineru_api=args.use_mineru_api,- mineru_api_token=args.mineru_api_token,- mineru_model_version=args.mineru_model_version,- force=args.force,- )- return-- if args.docs_folder:- docs_dir = (PROJECT_ROOT.parent / args.docs_folder).resolve()- else:- docs_dir = Path(args.docs_dir)- if not docs_dir.is_absolute():- docs_dir = (PROJECT_ROOT / docs_dir).resolve()- if not docs_dir.exists():- raise FileNotFoundError(f"Documents dir not found: {docs_dir}")-- if args.output_dir:- output_dir = Path(args.output_dir)- if not output_dir.is_absolute():- output_dir = (PROJECT_ROOT / output_dir).resolve()- output_dir.mkdir(parents=True, exist_ok=True)- timestamp = output_dir.name.replace("profiles_from_documents_", "")- logger.info("Resuming into existing output dir: %s", output_dir)- else:- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- output_dir = PROJECT_ROOT / "benchmark" / "data" / "generated" / f"profiles_from_documents_{timestamp}"- output_dir.mkdir(parents=True, exist_ok=True)-- pdfs = sorted(docs_dir.glob("*.pdf"))- if args.limit and args.limit > 0:- pdfs = pdfs[: args.limit]- if not pdfs:- raise ValueError(f"No PDF files found in: {docs_dir}")-- used_names: set[str] = set()- jobs = []- for pdf in pdfs:- kb_name = _unique_name(_sanitize_kb_name(pdf.stem), used_names)- jobs.append((pdf, kb_name))-- gpu_ids = _parse_gpu_ids(args.gpu_ids)- if args.skip_processing:- _runtime_status(- f"Start reuse-existing run | mode=skip_processing | total_pdfs={len(jobs)}"- )- results = []- for idx, (pdf_path, kb_name) in enumerate(jobs, start=1):- if not args.force and _is_profile_complete(output_dir, kb_name):- logger.info("SKIP (complete) [%d/%d]: %s", idx, len(jobs), kb_name)- continue- logger.info(- "Running reuse-existing pipeline [%d/%d]: %s -> %s",- idx,- len(jobs),- pdf_path.name,- kb_name,- )- try:- result = await _run_post_gpu_stage(- pdf_path=pdf_path,- kb_name=kb_name,- kb_base_dir=kb_base_dir,- profile_cfg=profile_cfg,- rag_cfg=rag_cfg,- output_dir=output_dir,- skip_extract=args.skip_extract,- kb_only=args.kb_only,- )- results.append(result)- except Exception as e:- logger.exception(- "Reuse-existing pipeline failed on %s -> %s: %s",- pdf_path.name,- kb_name,- e,- )- raise SystemExit(1)- elif args.serial:- _runtime_status(- f"Start serial run | gpus={','.join(gpu_ids[:MAX_CONCURRENCY])} | "- f"mode={'mineru_api' if args.use_mineru_api else 'local'} | total_pdfs={len(jobs)}"- )- results = []- for idx, (pdf_path, kb_name) in enumerate(jobs, start=1):- logger.info(- "Running serial pipeline [%d/%d]: %s -> %s",- idx,- len(jobs),- pdf_path.name,- kb_name,- )- try:- result = await _process_pdf(- pdf_path=pdf_path,- kb_name=kb_name,- kb_base_dir=kb_base_dir,- profile_cfg=profile_cfg,- rag_cfg=rag_cfg,- output_dir=output_dir,- skip_processing=args.skip_processing,- skip_extract=args.skip_extract,- use_mineru_api=args.use_mineru_api,- mineru_api_token=args.mineru_api_token,- mineru_model_version=args.mineru_model_version,- force=args.force,- kb_only=args.kb_only,- )- if result is not None:- results.append(result)- except Exception as e:- logger.exception("Pipeline failed on %s -> %s: %s", pdf_path.name, kb_name, e)- _cleanup_failed_kb_data(- kb_base_dir=kb_base_dir, kb_name=kb_name, output_dir=output_dir- )- raise SystemExit(1)- else:- _runtime_status(- f"Start parallel run | gpus={','.join(gpu_ids[:MAX_CONCURRENCY])} | "- f"mode={'mineru_api' if args.use_mineru_api else 'local'} | total_pdfs={len(jobs)}"- )- try:- results = await _run_jobs_with_gpu_pipeline(- jobs=jobs,- gpu_ids=gpu_ids[:MAX_CONCURRENCY],- config_path=cfg_path,- kb_base_dir=kb_base_dir,- profile_cfg=profile_cfg,- rag_cfg=rag_cfg,- output_dir=output_dir,- skip_extract=args.skip_extract,- use_mineru_api=args.use_mineru_api,- mineru_api_token=args.mineru_api_token,- mineru_model_version=args.mineru_model_version,- force=args.force,- kb_only=args.kb_only,- )- except PipelineAbortError as e:- logger.error("%s", e)- raise SystemExit(1)-- all_profiles = sorted(output_dir.glob("*.json"))- all_profiles = [p for p in all_profiles if p.name != "_summary.json"]- total_complete = len(all_profiles)-- summary = {- "timestamp": timestamp,- "docs_dir": str(docs_dir),- "kb_base_dir": str(kb_base_dir),- "num_pdfs": len(pdfs),- "num_new": len(results),- "num_total_complete": total_complete,- "results": [- {- "pdf_file": r["pdf_file"],- "kb_name": r["kb_name"],- "num_profiles": r["num_profiles"],- }- for r in results- ],- }- summary_path = output_dir / "_summary.json"- with open(summary_path, "w", encoding="utf-8") as f:- json.dump(summary, f, ensure_ascii=False, indent=2)-- print("\nDone.")- print(f"Output dir: {output_dir}")- print(f"Summary: {summary_path}")- print(f"This run: {len(results)} new | Total complete: {total_complete}/{len(pdfs)} PDFs")---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/data_generation/llm_utils.py b/benchmark/data_generation/llm_utils.pydeleted file mode 100644index 2ae2f55a9..000000000--- a/benchmark/data_generation/llm_utils.py+++ /dev/null@@ -1,220 +0,0 @@-#!/usr/bin/env python-"""-LLM Utilities for Benchmark Data Generation--Provides:-- Prompt template loading (from benchmark/prompts/*.yaml)-- Unified LLM calling with JSON parsing (via src.services.llm.factory)-- Template rendering-"""--import json-import logging-import re-from pathlib import Path--import yaml--logger = logging.getLogger("benchmark.llm_utils")--# Project root: benchmark/data_generation/llm_utils.py → project root-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent---def _normalize_json_like_text(text: str) -> str:- """Normalize common LLM artifacts before JSON parsing."""- if not isinstance(text, str):- text = str(text)- text = text.replace("\ufeff", "").replace("\x00", "").strip()- # Normalize smart quotes that occasionally appear in model outputs.- text = (- text.replace("“", '"')- .replace("”", '"')- .replace("’", "'")- .replace("‘", "'")- )- return text---def _cleanup_json_candidate(candidate: str) -> str:- """Best-effort cleanup for a JSON substring candidate."""- s = _normalize_json_like_text(candidate)- # If a fence label leaked into content, strip it.- if s.lower().startswith("json"):- s = s[4:].lstrip()- # Remove trailing commas before object/array close.- s = re.sub(r",\s*([}\]])", r"\1", s)- return s---def _yield_json_candidates(text: str):- """Yield likely JSON substrings from noisy LLM output."""- t = _normalize_json_like_text(text)- if not t:- return-- # Candidate 1: full response- yield t-- # Candidate 2: fenced code blocks (prefer explicit json fences)- for m in re.finditer(r"```json\s*(.*?)\s*```", t, re.DOTALL | re.IGNORECASE):- yield m.group(1)- for m in re.finditer(r"```(.*?)```", t, re.DOTALL):- yield m.group(1)-- # Candidate 3: streaming scan with JSONDecoder from each possible start.- decoder = json.JSONDecoder()- starts = [i for i, ch in enumerate(t) if ch in "{["]- for idx in starts:- try:- _, end = decoder.raw_decode(t, idx)- yield t[idx:end]- except Exception:- continue---def load_prompt(prompt_name: str) -> dict:- """- Load a prompt template from benchmark/prompts/.-- Args:- prompt_name: Prompt file name without extension (e.g., "generate_profile")-- Returns:- dict with 'system' and 'user_template' keys- """- prompt_path = PROJECT_ROOT / "benchmark" / "prompts" / f"{prompt_name}.yaml"- if not prompt_path.exists():- raise FileNotFoundError(f"Prompt template not found: {prompt_path}")-- with open(prompt_path, encoding="utf-8") as f:- return yaml.safe_load(f)---async def call_llm(- user_prompt: str,- system_prompt: str,- temperature: float = 0.7,- max_tokens: int = 4096,- **kwargs,-) -> str:- """- Call LLM via the project's unified LLM factory.-- Uses src.services.llm.factory.complete() which handles provider routing,- retry with exponential backoff, etc.-- Args:- user_prompt: User prompt text- system_prompt: System prompt text- temperature: Sampling temperature- max_tokens: Maximum tokens in response- **kwargs: Additional arguments (model, api_key, base_url overrides)-- Returns:- LLM response text- """- from src.services.llm import factory-- return await factory.complete(- prompt=user_prompt,- system_prompt=system_prompt,- temperature=temperature,- max_tokens=max_tokens,- **kwargs,- )---async def call_llm_json(- user_prompt: str,- system_prompt: str,- temperature: float = 0.7,- max_tokens: int = 4096,- **kwargs,-) -> dict:- """- Call LLM and parse response as JSON.-- Attempts multiple strategies to extract valid JSON from the response.-- Args:- user_prompt: User prompt text- system_prompt: System prompt text- temperature: Sampling temperature- max_tokens: Maximum tokens in response- **kwargs: Additional arguments passed to call_llm-- Returns:- Parsed JSON dictionary-- Raises:- json.JSONDecodeError: If response cannot be parsed as JSON- """- response = await call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- temperature=temperature,- max_tokens=max_tokens,- **kwargs,- )-- return extract_json(response)---def extract_json(text: str) -> dict:- """- Extract JSON from text that may contain markdown code fences or extra text.-- Args:- text: Raw text potentially containing JSON-- Returns:- Parsed JSON dictionary- """- normalized = _normalize_json_like_text(text)- if not normalized:- raise json.JSONDecodeError("Empty LLM response, no JSON to parse", text, 0)-- last_error: Exception | None = None- for candidate in _yield_json_candidates(normalized):- cleaned = _cleanup_json_candidate(candidate)- if not cleaned:- continue- try:- parsed = json.loads(cleaned)- except Exception as e:- last_error = e- continue-- if isinstance(parsed, dict):- return parsed- # Tolerate list-wrapped single object: [{...}]- if (- isinstance(parsed, list)- and len(parsed) == 1- and isinstance(parsed[0], dict)- ):- return parsed[0]-- preview = normalized[:240].replace("\n", "\\n")- msg = f"Cannot extract JSON from LLM response (preview='{preview}')"- if isinstance(last_error, json.JSONDecodeError):- raise json.JSONDecodeError(msg, normalized, last_error.pos)- raise json.JSONDecodeError(msg, normalized, 0)---def render_prompt(template: str, **kwargs) -> str:- """- Render a prompt template with the given variables.-- Args:- template: Template string with {variable} placeholders- **kwargs: Variables to substitute-- Returns:- Rendered prompt string- """- try:- return template.format(**kwargs)- except KeyError as e:- raise ValueError(f"Missing template variable: {e}")diff --git a/benchmark/data_generation/pipeline.py b/benchmark/data_generation/pipeline.pydeleted file mode 100644index eccca51a6..000000000--- a/benchmark/data_generation/pipeline.py+++ /dev/null@@ -1,486 +0,0 @@-#!/usr/bin/env python-"""-Data Generation Pipeline--Orchestrates the full benchmark data generation from existing knowledge bases:-- Existing KBs (per-subtopic)- │- ▼ Stage 1: Discover KBs- │- ▼ Stage 2: Query each KB → generate knowledge scope (saved separately)- │- ▼ Stage 3: Generate student profiles (beginner/intermediate/advanced)- │- ▼ Stage 4: Generate knowledge gaps per profile- │- ▼ Stage 5: Generate one task per gap → one benchmark entry per (profile, gap, task)- │- ▼ Stage 6: Output benchmark entries (JSONL, no scope duplication)--Output structure:- benchmark/data/generated/- ├── knowledge_scopes/- │ └── {kb_name}.json # knowledge scope per KB- └── benchmark_{timestamp}.jsonl # evaluation entries (profile + gap + task)-"""--import asyncio-import json-import logging-from datetime import datetime-from pathlib import Path--import yaml--from benchmark.data_generation.content_loader import load_page_content_for_profile-from benchmark.data_generation.gap_generator import (- generate_gaps,- generate_gaps_for_profiles,- generate_gaps_for_profiles_with_pages,- generate_gaps_from_pages,-)-from benchmark.data_generation.profile_generator import generate_profiles_for_kb-from benchmark.data_generation.scope_generator import generate_knowledge_scope-from benchmark.data_generation.task_generator import (- MIN_GAPS_PER_TASK,- generate_tasks_with_partition,- generate_tasks_with_partition_and_rejection,-)--logger = logging.getLogger("benchmark.pipeline")--# Project root-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent---class DataGenerationPipeline:- """- Full data generation pipeline: KB → evaluation data.-- Assumes subtopics have already been split and each topic has its own- RAG knowledge base ready to query.-- Output:- - knowledge_scopes/{kb_name}.json — scope reference (not used in evaluation)- - benchmark_{timestamp}.jsonl — one entry per (profile, gap, task) triple-- Usage:- pipeline = DataGenerationPipeline()- entries = await pipeline.run()- """-- def __init__(self, config_path: str | Path | None = None):- """- Initialize the pipeline.-- Args:- config_path: Path to benchmark_config.yaml.- If None, uses benchmark/config/benchmark_config.yaml.- """- if config_path is None:- config_path = PROJECT_ROOT / "benchmark" / "config" / "benchmark_config.yaml"- else:- config_path = Path(config_path)- if not config_path.is_absolute():- config_path = PROJECT_ROOT / config_path-- with open(config_path, encoding="utf-8") as f:- self.config = yaml.safe_load(f)-- # Output directory- self.output_dir = Path(self.config["output"]["output_dir"])- if not self.output_dir.is_absolute():- self.output_dir = PROJECT_ROOT / self.output_dir- self.output_dir.mkdir(parents=True, exist_ok=True)-- # Knowledge scopes directory (separate from entries)- self.scopes_dir = self.output_dir / "knowledge_scopes"- self.scopes_dir.mkdir(parents=True, exist_ok=True)-- # KB base directory- kb_cfg = self.config.get("knowledge_bases", {})- self.kb_base_dir = kb_cfg.get("base_dir", "./data/knowledge_bases")- if not Path(self.kb_base_dir).is_absolute():- self.kb_base_dir = str(PROJECT_ROOT / self.kb_base_dir)-- # Pipeline state- self.kb_names: list[str] = []- self.knowledge_scopes: dict[str, dict] = {} # kb_name → scope- self.profiles: dict[str, list[dict]] = {} # kb_name → [profile]- self.gaps: dict[str, dict[str, list[dict]]] = {} # kb_name → {pid → [gap]}- self.benchmark_entries: list[dict] = []-- # Configure logging- logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )-- async def run(self, kb_names: list[str] | None = None) -> list[dict]:- """- Run the complete data generation pipeline.-- Args:- kb_names: Explicit list of KB names to process.- If None, uses config or auto-discovers.-- Returns:- List of benchmark entries- """- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- logger.info("=" * 60)- logger.info("Starting Benchmark Data Generation Pipeline")- logger.info("=" * 60)-- # Stage 1: Discover KBs- await self._stage_discover_kbs(kb_names)-- # Stages 2-5: Process each KB- for kb_name in self.kb_names:- await self._process_single_kb(kb_name)-- # Stage 6: Output- await self._stage_output(timestamp)-- logger.info("=" * 60)- logger.info(f"Pipeline complete! Generated {len(self.benchmark_entries)} benchmark entries")- logger.info("=" * 60)-- return self.benchmark_entries-- # =========================================================================- # Pipeline Stages- # =========================================================================-- async def _stage_discover_kbs(self, kb_names: list[str] | None = None):- """Stage 1: Discover which knowledge bases to process."""- logger.info("[Stage 1] Discovering knowledge bases...")-- if kb_names:- self.kb_names = kb_names- else:- configured = self.config.get("knowledge_bases", {}).get("kb_names", [])- if configured:- self.kb_names = configured- else:- # Auto-discover from KB manager- from src.knowledge.manager import KnowledgeBaseManager-- manager = KnowledgeBaseManager(self.kb_base_dir)- self.kb_names = manager.list_knowledge_bases()-- logger.info(f"Will process {len(self.kb_names)} knowledge bases: {self.kb_names}")-- async def _process_single_kb(self, kb_name: str):- """Stages 2-5 for a single knowledge base."""- logger.info(f"\n{'='*50}")- logger.info(f"Processing KB: {kb_name}")- logger.info(f"{'='*50}")-- # Stage 2: Generate knowledge scope → saved to separate file- logger.info(f"[Stage 2] Generating knowledge scope for '{kb_name}'...")- rag_cfg = self.config.get("rag_query", {})- try:- scope = await generate_knowledge_scope(- kb_name=kb_name,- seed_queries=rag_cfg.get("seed_queries"),- mode=rag_cfg.get("mode", "naive"),- kb_base_dir=self.kb_base_dir,- )- self.knowledge_scopes[kb_name] = scope-- # Save scope to its own file (reference only, not used in evaluation)- scope_file = self.scopes_dir / f"{kb_name}.json"- with open(scope_file, "w", encoding="utf-8") as f:- json.dump(scope, f, ensure_ascii=False, indent=2)- logger.info(f" Knowledge scope saved → {scope_file}")-- except Exception as e:- logger.error(f"Failed to generate scope for '{kb_name}': {e}")- return-- # Stage 3: Generate profiles- logger.info(f"[Stage 3] Generating student profiles for '{kb_name}'...")- profile_cfg = self.config.get("profile_generation", {})- profiles = await generate_profiles_for_kb(- knowledge_scope=scope,- background_types=profile_cfg.get(- "background_types", ["beginner", "intermediate", "advanced"]- ),- profiles_per_kb=profile_cfg.get("profiles_per_subtopic", 3),- )- self.profiles[kb_name] = profiles-- # Stage 4 & 5: Generate gaps + tasks per profile, loop until min_tasks达标- gap_cfg = self.config.get("gap_generation", {})- task_cfg = self.config.get("task_generation", {})- logger.info(f"[Stage 4-5] Generating gaps and tasks for '{kb_name}' (min {task_cfg.get('min_tasks_per_profile', 3)} tasks/profile)...")- min_tasks = task_cfg.get("min_tasks_per_profile", 3)- gaps_per_batch_cfg = task_cfg.get("gaps_per_batch", 3)- gaps_per_batch = max(gaps_per_batch_cfg, MIN_GAPS_PER_TASK)- if gaps_per_batch_cfg < MIN_GAPS_PER_TASK:- logger.warning(- "task_generation.gaps_per_batch=%d is too small; bumping to %d "- "to enforce >=%d gaps per task",- gaps_per_batch_cfg,- gaps_per_batch,- MIN_GAPS_PER_TASK,- )- severity_weights = {}- for level in gap_cfg.get("severity_levels", []):- severity_weights[level["name"]] = level["weight"]-- use_content_list = gap_cfg.get("use_content_list", False)- rejection_sampling = use_content_list and gap_cfg.get("rejection_sampling", False)- page_content_by_profile: dict[str, tuple[dict[int, str], list[int]]] = {}-- if use_content_list:- num_pages = gap_cfg.get("pages_per_profile", 10)- for profile in profiles:- profile_id = profile.get("profile_id", "unknown")- result = load_page_content_for_profile(- kb_base_dir=self.kb_base_dir,- kb_name=kb_name,- num_pages=num_pages,- profile_id=profile_id,- )- if result:- page_content_by_profile[profile_id] = result- if not page_content_by_profile:- logger.warning(" No content_list found, falling back to scope-based gaps")- use_content_list = False-- profile_gaps: dict[str, list[dict]] = {p.get("profile_id", "?"): [] for p in profiles}-- for profile in profiles:- profile_id = profile.get("profile_id", "unknown")- page_content, _ = page_content_by_profile.get(profile_id, (None, []))- all_gaps: list[dict] = []- all_tasks: list[dict] = []- task_index_offset = 0-- max_batches = 10- batch_num = 0- while len(all_tasks) < min_tasks and batch_num < max_batches:- batch_num += 1- batch_size = gaps_per_batch- try:- if use_content_list and page_content:- new_gaps = await generate_gaps_from_pages(- page_content=page_content,- student_profile=profile,- num_gaps=batch_size,- severity_weights=severity_weights or None,- gap_id_offset=len(all_gaps),- )- else:- new_gaps = await generate_gaps(- knowledge_scope=scope,- student_profile=profile,- num_gaps=batch_size,- severity_weights=severity_weights or None,- gap_id_offset=len(all_gaps),- )-- if not new_gaps:- logger.warning(f" No new gaps for {profile_id}, stopping")- break-- all_gaps.extend(new_gaps)-- if rejection_sampling and page_content:- tasks = await generate_tasks_with_partition_and_rejection(- knowledge_scope=scope,- student_profile=profile,- knowledge_gaps=new_gaps,- page_content=page_content,- task_index_offset=task_index_offset,- )- else:- tasks = await generate_tasks_with_partition(- knowledge_scope=scope,- student_profile=profile,- knowledge_gaps=new_gaps,- task_index_offset=task_index_offset,- )-- all_tasks.extend(tasks)- task_index_offset += len(tasks)-- if len(all_tasks) >= min_tasks:- logger.info(f" {profile_id}: {len(all_tasks)} tasks (达标)")- break- logger.info(f" {profile_id}: {len(all_tasks)}/{min_tasks} tasks, generating more gaps...")-- except Exception as e:- logger.error(f"Failed for {profile_id}: {e}")- break-- profile_gaps[profile_id] = all_gaps- gap_by_id = {g["gap_id"]: g for g in all_gaps if "gap_id" in g}-- for task in all_tasks:- task_id = task.get("task_id", "unknown")- target_gap_ids = task.get("target_gaps", [])- target_gaps = [gap_by_id[gid] for gid in target_gap_ids if gid in gap_by_id]-- entry = {- "entry_id": f"{kb_name}_{profile_id}_{task_id}",- "kb_name": kb_name,- "profile": profile,- "gaps": target_gaps,- "task": task,- }- if page_content is not None:- entry["source_content"] = page_content- self.benchmark_entries.append(entry)-- self.gaps[kb_name] = profile_gaps-- # Save intermediate per-KB result (includes scope for debugging)- if self.config["output"].get("save_intermediate", True):- self._save_intermediate(- f"kb_{kb_name}.json",- {- "kb_name": kb_name,- "knowledge_scope": scope,- "profiles": profiles,- "gaps": profile_gaps,- "num_entries": sum(- 1- for e in self.benchmark_entries- if e.get("kb_name") == kb_name- ),- },- )-- kb_entries = sum(1 for e in self.benchmark_entries if e["kb_name"] == kb_name)- logger.info(f"Completed KB '{kb_name}': {len(profiles)} profiles, {kb_entries} entries")-- async def _stage_output(self, timestamp: str):- """Stage 6: Save final output — organized by KB, each with its own _all_entries.jsonl."""- logger.info("[Stage 6] Saving benchmark dataset...")-- run_dir = self.output_dir / f"benchmark_{timestamp}"- run_dir.mkdir(parents=True, exist_ok=True)-- # Group entries by KB- entries_by_kb: dict[str, list[dict]] = {}- for entry in self.benchmark_entries:- kb = entry.get("kb_name", "unknown")- entries_by_kb.setdefault(kb, []).append(entry)-- # Write per-KB directories- for kb_name, kb_entries in entries_by_kb.items():- kb_dir = run_dir / kb_name- kb_dir.mkdir(parents=True, exist_ok=True)-- seen_entry_ids: dict[str, int] = {}- for entry in kb_entries:- base_entry_id = str(entry.get("entry_id", "unknown"))- dup_count = seen_entry_ids.get(base_entry_id, 0)- seen_entry_ids[base_entry_id] = dup_count + 1-- if dup_count == 0:- entry_id = base_entry_id- else:- entry_id = f"{base_entry_id}__dup{dup_count + 1:02d}"- logger.warning(- "Duplicate entry_id detected: %s -> renamed to %s",- base_entry_id, entry_id,- )- entry["entry_id"] = entry_id-- entry_file = kb_dir / f"{entry_id}.json"- with open(entry_file, "w", encoding="utf-8") as f:- json.dump(entry, f, ensure_ascii=False, indent=2)-- kb_jsonl = kb_dir / "_all_entries.jsonl"- with open(kb_jsonl, "w", encoding="utf-8") as f:- for entry in kb_entries:- f.write(json.dumps(entry, ensure_ascii=False) + "\n")-- logger.info(f" {kb_name}: {len(kb_entries)} entries → {kb_dir}/")-- # Also write a combined JSONL at the run level- combined_file = run_dir / "_all_entries.jsonl"- with open(combined_file, "w", encoding="utf-8") as f:- for entry in self.benchmark_entries:- f.write(json.dumps(entry, ensure_ascii=False) + "\n")- logger.info(f"Combined JSONL → {combined_file}")-- # Summary- summary = {- "timestamp": timestamp,- "statistics": {- "total_entries": len(self.benchmark_entries),- "num_kbs": len(self.kb_names),- "num_profiles": sum(len(p) for p in self.profiles.values()),- "per_kb": [- {- "kb_name": kb,- "num_profiles": len(self.profiles.get(kb, [])),- "num_entries": len(entries_by_kb.get(kb, [])),- }- for kb in self.kb_names- ],- },- "entries_dir": str(run_dir),- "knowledge_scopes_dir": str(self.scopes_dir),- }-- summary_file = run_dir / "_summary.json"- with open(summary_file, "w", encoding="utf-8") as f:- json.dump(summary, f, ensure_ascii=False, indent=2)-- logger.info(f"Summary → {summary_file}")-- # =========================================================================- # Utilities- # =========================================================================-- def _save_intermediate(self, filename: str, data):- """Save intermediate results to output directory."""- intermediate_dir = self.output_dir / "intermediate"- intermediate_dir.mkdir(exist_ok=True)- filepath = intermediate_dir / filename-- with open(filepath, "w", encoding="utf-8") as f:- json.dump(data, f, ensure_ascii=False, indent=2)-- logger.debug(f"Saved intermediate: {filepath}")---# =============================================================================-# CLI Entry Point-# =============================================================================---async def main():- """CLI entry point for running the data generation pipeline."""- import argparse-- parser = argparse.ArgumentParser(- description="Benchmark Data Generation: KB → Evaluation Data"- )- parser.add_argument(- "--config",- default=None,- help="Path to benchmark config file (default: benchmark/config/benchmark_config.yaml)",- )- parser.add_argument(- "--kb-names",- nargs="+",- default=None,- help="Explicit list of KB names to process (overrides config)",- )-- args = parser.parse_args()-- pipeline = DataGenerationPipeline(args.config)- await pipeline.run(kb_names=args.kb_names)---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/data_generation/profile_generator.py b/benchmark/data_generation/profile_generator.pydeleted file mode 100644index 924ba8a73..000000000--- a/benchmark/data_generation/profile_generator.py+++ /dev/null@@ -1,112 +0,0 @@-#!/usr/bin/env python-"""-Profile Generator - Generate realistic student profiles--Creates diverse student profiles with varying backgrounds, knowledge states,-and personalities based on a knowledge scope description.-"""--import json-import logging--from benchmark.data_generation.llm_utils import call_llm_json, load_prompt, render_prompt--logger = logging.getLogger("benchmark.profile_generator")---async def generate_profile(- knowledge_scope: dict,- background_type: str = "intermediate",- profile_id: str | None = None,-) -> dict:- """- Generate a single student profile for a given knowledge scope.-- Args:- knowledge_scope: Knowledge scope dictionary (from scope_generator)- background_type: One of "beginner", "intermediate", "advanced"- profile_id: Optional specific profile ID-- Returns:- Student profile dictionary with fields:- - profile_id- - education_background (single string)- - learning_purpose- - knowledge_state: {known_well, partially_known, unknown}- - personality (single paragraph)- - source_kb- """- kb_name = knowledge_scope.get("source_kb", "unknown")- logger.info(f"Generating {background_type} profile for KB: {kb_name}")-- prompt = load_prompt("generate_profile")-- # Format knowledge scope as readable text- scope_text = json.dumps(knowledge_scope, ensure_ascii=False, indent=2)-- user_prompt = render_prompt(- prompt["user_template"],- knowledge_scope=scope_text,- background_type=background_type,- )-- result = await call_llm_json(- user_prompt=user_prompt,- system_prompt=prompt["system"],- temperature=0.7,- max_tokens=4096,- )-- # Ensure fields are set- if profile_id:- result["profile_id"] = profile_id- elif "profile_id" not in result:- result["profile_id"] = f"profile_{background_type}"-- result["source_kb"] = kb_name-- return result---async def generate_profiles_for_kb(- knowledge_scope: dict,- background_types: list[str] | None = None,- profiles_per_kb: int = 3,-) -> list[dict]:- """- Generate multiple student profiles for a knowledge scope.-- Distributes profiles across background types. For example, with- profiles_per_kb=3 and types=["beginner","intermediate","advanced"],- generates one of each type.-- Args:- knowledge_scope: Knowledge scope dictionary- background_types: List of background types- profiles_per_kb: Total number of profiles to generate-- Returns:- List of student profile dictionaries- """- if background_types is None:- background_types = ["beginner", "intermediate", "advanced"]-- kb_name = knowledge_scope.get("source_kb", "unknown")- profiles = []-- for i in range(profiles_per_kb):- bg_type = background_types[i % len(background_types)]- pid = f"{kb_name}_{bg_type}_{i:02d}"-- try:- profile = await generate_profile(- knowledge_scope=knowledge_scope,- background_type=bg_type,- profile_id=pid,- )- profiles.append(profile)- logger.info(f" ✓ Profile: {profile.get('profile_id', pid)}")- except Exception as e:- logger.error(f" ✗ Failed to generate profile {pid}: {e}")-- return profilesdiff --git a/benchmark/data_generation/request_pipeline.py b/benchmark/data_generation/request_pipeline.pydeleted file mode 100644index 1d1fe3645..000000000--- a/benchmark/data_generation/request_pipeline.py+++ /dev/null@@ -1,378 +0,0 @@-#!/usr/bin/env python3-"""-Request Generation Pipeline--Generate evaluation requests from existing benchmark task entries:- - one solve request per profile- - one question request per profile (generated by LLM from topic, in English)--Input:- benchmark/data/generated/benchmark_<timestamp>/*.json--Output:- benchmark/data/generated/requests_<timestamp>/- - <profile_entry_id>.json- - _all_requests.jsonl- - _summary.json-"""--from __future__ import annotations--import argparse-import asyncio-import json-import logging-import sys-from datetime import datetime-from pathlib import Path-from typing import Any--import yaml--# Ensure project root is importable when script is executed directly.-_THIS_FILE = Path(__file__).resolve()-_PROJECT_ROOT_FOR_IMPORT = _THIS_FILE.parents[2]-if str(_PROJECT_ROOT_FOR_IMPORT) not in sys.path:- sys.path.insert(0, str(_PROJECT_ROOT_FOR_IMPORT))--from benchmark.data_generation.llm_utils import call_llm--logger = logging.getLogger("benchmark.request_pipeline")--PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent-DEFAULT_CONFIG = PROJECT_ROOT / "benchmark" / "config" / "benchmark_config.yaml"---def _load_config(path: Path) -> dict[str, Any]:- with open(path, encoding="utf-8") as f:- return yaml.safe_load(f) or {}---def _normalize_space(text: str) -> str:- return " ".join((text or "").strip().split())---def _clean_llm_text(text: str) -> str:- cleaned = _normalize_space(text)- if cleaned.startswith("```") and cleaned.endswith("```"):- cleaned = _normalize_space(cleaned.strip("`"))- cleaned = cleaned.strip().strip('"').strip("'")- return cleaned---def _to_profile_level(profile: dict[str, Any]) -> str:- profile_id = str(profile.get("profile_id", "")).lower()- if "beginner" in profile_id:- return "beginner"- if "advanced" in profile_id:- return "advanced"- return "intermediate"---def _pick_profile_topic(entries: list[dict[str, Any]]) -> str:- titles: list[str] = []- for entry in entries:- task = entry.get("task", {}) or {}- title = _normalize_space(str(task.get("title", "")))- if title and title not in titles:- titles.append(title)- if not titles:- return "the current study topic"- if len(titles) == 1:- return titles[0]- return " | ".join(titles[:3])---def _build_solve_query(profile: dict[str, Any], topic: str, entries: list[dict[str, Any]]) -> str:- # Prefer an existing initial message only when it already appears to be English.- for entry in entries:- task = entry.get("task", {}) or {}- initial_message = _normalize_space(str(task.get("initial_message", "")))- if initial_message and initial_message.isascii():- return initial_message-- level = _to_profile_level(profile)- if level == "beginner":- depth = "Please keep it foundational and concrete."- elif level == "advanced":- depth = "Please include concise formal reasoning."- else:- depth = "Please explain step by step with one concrete example."-- return (- f"I am studying {topic} and need help solving a representative problem from this topic. "- f"{depth}"- )---async def _build_question_query_with_llm(profile: dict[str, Any], topic: str) -> str:- level = _to_profile_level(profile)-- if level == "beginner":- level_hint = "beginner-level, simple and foundational"- elif level == "advanced":- level_hint = "advanced-level, slightly challenging"- else:- level_hint = "intermediate-level, moderate difficulty"-- system_prompt = (- "You are generating realistic student requests for benchmark evaluation. "- "Return exactly one short request sentence in English only."- )- user_prompt = (- "Write one realistic student request asking a tutor to generate exactly one practice question.\n"- f"Topic: {topic}\n"- f"Difficulty preference: {level_hint}\n"- "Constraints:\n"- "- English only\n"- "- Do not mention benchmark, evaluation, profile, or gaps\n"- "- Ask for exactly one question\n"- "- Ask not to reveal the answer yet\n"- "Output only the request sentence."- )-- try:- query = await call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- temperature=0.3,- max_tokens=128,- )- cleaned = _clean_llm_text(query)- if cleaned:- return cleaned- except Exception as e:- logger.warning("LLM generation failed for question request, using fallback template: %s", e)-- # Safe fallback in English- return (- f"I just studied {topic}. Please give me exactly one practice question at {level_hint} "- "difficulty, and do not show the answer yet."- )---def _group_entries_by_profile(entries: list[dict[str, Any]]) -> dict[tuple[str, str], list[dict[str, Any]]]:- groups: dict[tuple[str, str], list[dict[str, Any]]] = {}- for entry in entries:- kb_name = str(entry.get("kb_name", ""))- profile = entry.get("profile", {}) or {}- profile_id = str(profile.get("profile_id", "unknown"))- key = (kb_name, profile_id)- groups.setdefault(key, []).append(entry)- return groups---async def _build_request_record_for_profile(- kb_name: str,- profile_id: str,- entries: list[dict[str, Any]],-) -> dict[str, Any]:- profile = entries[0].get("profile", {}) or {}- topic = _pick_profile_topic(entries)- question_query = await _build_question_query_with_llm(profile, topic)- profile_entry_id = f"{kb_name}_{profile_id}"-- task_ids = []- for entry in entries:- task = entry.get("task", {}) or {}- task_id = str(task.get("task_id", ""))- if task_id:- task_ids.append(task_id)-- return {- "profile_entry_id": profile_entry_id,- "kb_name": kb_name,- "profile_id": profile_id,- "topic": topic,- "source_task_ids": sorted(set(task_ids)),- "solve_request": {- "query": _build_solve_query(profile, topic, entries),- },- "question_request": {- "query": question_query,- },- }---def _discover_latest_benchmark_dir(base_output_dir: Path) -> Path:- candidates = [- p for p in base_output_dir.glob("benchmark_*")- if p.is_dir() and p.name[10:].replace("_", "").isdigit()- ]- if not candidates:- raise FileNotFoundError(- f"No benchmark_* directories found under: {base_output_dir}"- )- return max(candidates, key=lambda p: p.stat().st_mtime)---def _load_entries(input_dir: Path, limit: int) -> list[dict[str, Any]]:- files = sorted(- p for p in input_dir.glob("*.json")- if not p.name.startswith("_")- )- if limit > 0:- files = files[:limit]- if not files:- raise ValueError(f"No entry JSON files found in: {input_dir}")-- entries: list[dict[str, Any]] = []- for path in files:- with open(path, encoding="utf-8") as f:- data = json.load(f)- if isinstance(data, dict):- entries.append(data)- else:- logger.warning("Skip non-dict entry file: %s", path)- return entries---def _save_requests(output_dir: Path, records: list[dict[str, Any]]) -> None:- output_dir.mkdir(parents=True, exist_ok=True)-- # Save one request file per profile- for rec in records:- profile_entry_id = str(rec.get("profile_entry_id", "unknown"))- out_path = output_dir / f"{profile_entry_id}.json"- with open(out_path, "w", encoding="utf-8") as f:- json.dump(rec, f, ensure_ascii=False, indent=2)-- # Save combined JSONL- jsonl_path = output_dir / "_all_requests.jsonl"- with open(jsonl_path, "w", encoding="utf-8") as f:- for rec in records:- f.write(json.dumps(rec, ensure_ascii=False) + "\n")---def _save_summary(- output_dir: Path,- *,- input_dir: Path,- timestamp: str,- num_profiles: int,- num_input_entries: int,-) -> Path:- summary = {- "timestamp": timestamp,- "input_dir": str(input_dir),- "output_dir": str(output_dir),- "num_input_entries": num_input_entries,- "num_profiles": num_profiles,- }- summary_path = output_dir / "_summary.json"- with open(summary_path, "w", encoding="utf-8") as f:- json.dump(summary, f, ensure_ascii=False, indent=2)- return summary_path---def _parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(- description="Generate solve/question requests from benchmark task entries."- )- parser.add_argument(- "--config",- default=str(DEFAULT_CONFIG),- help=f"Benchmark config path (default: {DEFAULT_CONFIG})",- )- parser.add_argument(- "--input-dir",- default=None,- help=(- "Input benchmark entry directory (e.g. benchmark/data/generated/benchmark_YYYYMMDD_HHMMSS). "- "If omitted, auto-pick latest benchmark_* directory."- ),- )- parser.add_argument(- "--output-dir",- default=None,- help=(- "Output directory. If omitted, writes to "- "benchmark/data/generated/requests_<timestamp>."- ),- )- parser.add_argument(- "--limit",- type=int,- default=0,- help="Only process first N entries (0 = all).",- )- return parser.parse_args()---async def _generate_records(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:- groups = _group_entries_by_profile(entries)- logger.info("Grouped into %d profiles", len(groups))-- records: list[dict[str, Any]] = []- for (kb_name, profile_id), profile_entries in sorted(groups.items()):- rec = await _build_request_record_for_profile(- kb_name=kb_name,- profile_id=profile_id,- entries=profile_entries,- )- records.append(rec)- return records---async def async_main() -> None:- args = _parse_args()-- logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )-- cfg_path = Path(args.config)- if not cfg_path.is_absolute():- cfg_path = (PROJECT_ROOT / cfg_path).resolve()- cfg = _load_config(cfg_path)-- base_output_dir = Path(cfg.get("output", {}).get("output_dir", "./benchmark/data/generated"))- if not base_output_dir.is_absolute():- base_output_dir = (PROJECT_ROOT / base_output_dir).resolve()-- if args.input_dir:- input_dir = Path(args.input_dir)- if not input_dir.is_absolute():- input_dir = (PROJECT_ROOT / input_dir).resolve()- else:- input_dir = _discover_latest_benchmark_dir(base_output_dir)-- if not input_dir.exists():- raise FileNotFoundError(f"Input dir not found: {input_dir}")-- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- if args.output_dir:- output_dir = Path(args.output_dir)- if not output_dir.is_absolute():- output_dir = (PROJECT_ROOT / output_dir).resolve()- else:- output_dir = base_output_dir / f"requests_{timestamp}"-- entries = _load_entries(input_dir, args.limit)- logger.info("Loaded %d benchmark task entries from %s", len(entries), input_dir)-- records = await _generate_records(entries)- _save_requests(output_dir, records)- summary_path = _save_summary(- output_dir,- input_dir=input_dir,- timestamp=timestamp,- num_profiles=len(records),- num_input_entries=len(entries),- )-- print("\nDone.")- print(f"Input dir : {input_dir}")- print(f"Output dir: {output_dir}")- print(f"Summary : {summary_path}")- print(f"Profiles : {len(records)}")- print(f"Input tasks: {len(entries)}")---def main() -> None:- asyncio.run(async_main())---if __name__ == "__main__":- main()diff --git a/benchmark/data_generation/scope_generator.py b/benchmark/data_generation/scope_generator.pydeleted file mode 100644index 6c133a3e7..000000000--- a/benchmark/data_generation/scope_generator.py+++ /dev/null@@ -1,130 +0,0 @@-#!/usr/bin/env python-"""-Knowledge Scope Generator--Queries an existing knowledge base via RAGService and uses LLM to-generate a structured knowledge scope description. This scope is the-foundation for all downstream generation (profiles, gaps, tasks).-"""--import json-import logging--from benchmark.data_generation.llm_utils import call_llm_json, load_prompt, render_prompt--logger = logging.getLogger("benchmark.scope_generator")---async def query_kb_for_content(- kb_name: str,- seed_queries: list[str] | None = None,- mode: str = "naive",- kb_base_dir: str | None = None,-) -> str:- """- Query a knowledge base with seed queries to extract representative content.-- Uses RAGService (the project's unified RAG interface) to retrieve- content from the KB without LLM answer generation.-- Args:- kb_name: Name of the knowledge base- seed_queries: List of queries to probe the KB- mode: RAG query mode ("naive", "hybrid", "local", "global")- kb_base_dir: Override KB base directory-- Returns:- Concatenated content string from all queries- """- from src.services.rag.service import RAGService-- if seed_queries is None:- seed_queries = [- "What are the main knowledge points and core concepts in this content?",- "What key theorems, formulas, or methods does this content cover?",- "What are typical application scenarios and example problems in this content?",- ]-- service = RAGService(kb_base_dir=kb_base_dir)- all_contents = []-- for query in seed_queries:- try:- result = await service.search(- query=query,- kb_name=kb_name,- mode=mode,- )- content = result.get("content", result.get("answer", ""))- if content and content.strip():- all_contents.append(f"--- Query: {query} ---\n{content}")- except Exception as e:- logger.warning(f"Failed to query KB '{kb_name}' with '{query[:30]}...': {e}")-- if not all_contents:- logger.error(f"No content retrieved from KB '{kb_name}'")- return ""-- return "\n\n".join(all_contents)---async def generate_knowledge_scope(- kb_name: str,- kb_contents: str | None = None,- seed_queries: list[str] | None = None,- mode: str = "naive",- kb_base_dir: str | None = None,-) -> dict:- """- Generate a structured knowledge scope description for a KB.-- If kb_contents is not provided, queries the KB first using seed_queries.-- Args:- kb_name: Knowledge base name- kb_contents: Pre-fetched KB content (optional)- seed_queries: Seed queries for KB probing (if kb_contents not provided)- mode: RAG query mode- kb_base_dir: Override KB base directory-- Returns:- Knowledge scope dictionary with domain, concepts, hierarchy, etc.- """- logger.info(f"Generating knowledge scope for KB: {kb_name}")-- # Fetch KB content if not provided- if not kb_contents:- kb_contents = await query_kb_for_content(- kb_name=kb_name,- seed_queries=seed_queries,- mode=mode,- kb_base_dir=kb_base_dir,- )-- if not kb_contents:- raise ValueError(f"Cannot generate scope: no content from KB '{kb_name}'")-- # Load prompt and call LLM- prompt = load_prompt("generate_knowledge_scope")- user_prompt = render_prompt(- prompt["user_template"],- kb_name=kb_name,- kb_contents=kb_contents,- )-- result = await call_llm_json(- user_prompt=user_prompt,- system_prompt=prompt["system"],- temperature=0.5,- max_tokens=4096,- )-- # Tag with source KB- result["source_kb"] = kb_name-- logger.info(- f"Knowledge scope generated for '{kb_name}': "- f"{result.get('domain', '?')} / {result.get('subtopic_title', '?')} "- f"({len(result.get('core_concepts', []))} concepts)"- )- return resultdiff --git a/benchmark/data_generation/task_generator.py b/benchmark/data_generation/task_generator.pydeleted file mode 100644index e45885a18..000000000--- a/benchmark/data_generation/task_generator.py+++ /dev/null@@ -1,464 +0,0 @@-#!/usr/bin/env python-"""-Task Generator - Generate learning tasks for a profile's knowledge gaps--Creates natural learning tasks that, when pursued in conversation with a tutor,-will organically expose one or more of the student's knowledge gaps.-Each task may target one or multiple gaps — the LLM decides.--When using generate_tasks_with_partition(), each gap is assigned to exactly one task:-gaps are removed from the pool after each task is generated (hardcoded partition).-"""--import json-import logging--from benchmark.data_generation.llm_utils import call_llm_json, load_prompt, render_prompt--logger = logging.getLogger("benchmark.task_generator")-MIN_GAPS_PER_TASK = 3---def _normalize_task_id(task: dict, task_index: int) -> str:- """- Build a deterministic task_id from generation index.-- We preserve a simple prefix signal from model output (e.g. task_reflect),- but always rewrite the numeric suffix so IDs are unique within a profile.- """- raw_id = str(task.get("task_id", "") or "")- prefix = "task_reflect" if raw_id.startswith("task_reflect") else "task"- return f"{prefix}_{task_index + 1:03d}"---def _build_default_gap_pacing_plan(target_gaps: list[str]) -> list[dict]:- """- Build a deterministic staged gap exposure plan.-- Rule of thumb:- - first gap: turns 1-2- - second gap: turns 3-4- - third gap: turns 5-6- """- plan = []- for idx, gid in enumerate(target_gaps):- start_turn = idx * 2 + 1- plan.append(- {- "gap_id": gid,- "turn_window": f"{start_turn}-{start_turn + 1}",- "trigger": "Reveal only when current confusion is partly addressed.",- }- )- return plan---def _normalize_gap_pacing_plan(task: dict, target_gaps: list[str]) -> list[dict]:- """- Normalize LLM-provided gap_pacing_plan; fall back to default if malformed.- """- raw = task.get("gap_pacing_plan", [])- if not isinstance(raw, list):- return _build_default_gap_pacing_plan(target_gaps)-- valid_set = set(target_gaps)- normalized = []- used = set()- for item in raw:- if not isinstance(item, dict):- continue- gid = item.get("gap_id")- if gid in valid_set and gid not in used:- normalized.append(- {- "gap_id": gid,- "turn_window": str(item.get("turn_window", "")) or "later",- "trigger": str(item.get("trigger", "")) or "Reveal progressively.",- }- )- used.add(gid)-- # Ensure all target gaps appear exactly once in plan- if len(normalized) != len(target_gaps):- return _build_default_gap_pacing_plan(target_gaps)- return normalized---async def generate_tasks(- knowledge_scope: dict,- student_profile: dict,- knowledge_gaps: list[dict],- num_tasks: int = 2,-) -> list[dict]:- """- Generate learning tasks for a (profile, gaps) combination.-- The LLM receives all gaps and decides which gaps each task targets.- Each task specifies its target_gaps (list of gap_ids).-- Args:- knowledge_scope: Knowledge scope dictionary- student_profile: Student profile dictionary- knowledge_gaps: All knowledge gap dictionaries for this profile- num_tasks: Number of tasks to generate-- Returns:- List of task dictionaries, each with a 'target_gaps' field- """- profile_id = student_profile.get("profile_id", "unknown")- logger.info(f"Generating {num_tasks} tasks for profile '{profile_id}' ({len(knowledge_gaps)} gaps)")-- prompt = load_prompt("generate_tasks")-- scope_text = json.dumps(knowledge_scope, ensure_ascii=False, indent=2)- profile_text = json.dumps(student_profile, ensure_ascii=False, indent=2)- gaps_text = json.dumps(knowledge_gaps, ensure_ascii=False, indent=2)-- user_prompt = render_prompt(- prompt["user_template"],- knowledge_scope=scope_text,- student_profile=profile_text,- knowledge_gaps=gaps_text,- num_tasks=num_tasks,- )-- result = await call_llm_json(- user_prompt=user_prompt,- system_prompt=prompt["system"],- temperature=0.7,- max_tokens=4096,- )-- tasks = result.get("tasks", [])-- # If the LLM returned a single task object instead of a list, wrap it- if not isinstance(tasks, list):- tasks = [result] if "task_id" in result or "title" in result else []-- # Ensure task IDs and validate target_gaps- gap_ids = {g.get("gap_id") for g in knowledge_gaps}- for i, task in enumerate(tasks):- task["task_id"] = _normalize_task_id(task, i)-- # Ensure target_gaps is a list of valid gap_ids- target = task.get("target_gaps", [])- if isinstance(target, str):- target = [target]- task["target_gaps"] = [gid for gid in target if gid in gap_ids]-- if not task["target_gaps"]:- logger.warning(f" Task {task['task_id']} has no valid target_gaps")-- logger.info(f" Generated {len(tasks)} tasks: {[t.get('type', '?') for t in tasks]}")- return tasks---async def generate_single_task(- knowledge_scope: dict,- student_profile: dict,- available_gaps: list[dict],- task_index: int = 0,-) -> dict | None:- """- Generate a single task from the available (remaining) gaps.-- Used for iterative partition: each call consumes some gaps; the caller- removes them from the pool before the next call.-- Args:- knowledge_scope: Knowledge scope dictionary- student_profile: Student profile dictionary- available_gaps: Gaps not yet assigned to any task- task_index: 0-based index for task_id-- Returns:- Task dict with target_gaps, or None if no gaps available- """- if not available_gaps:- return None- if len(available_gaps) < MIN_GAPS_PER_TASK:- logger.warning(- "Insufficient available gaps for one task: need >= %d, got %d",- MIN_GAPS_PER_TASK,- len(available_gaps),- )- return None-- profile_id = student_profile.get("profile_id", "unknown")- ordered_gap_ids = [g.get("gap_id") for g in available_gaps if g.get("gap_id")]- gap_ids = set(ordered_gap_ids)- logger.info(- f"Generating task {task_index + 1} for profile '{profile_id}' "- f"({len(available_gaps)} gaps available)"- )-- prompt = load_prompt("generate_task_single")- scope_text = json.dumps(knowledge_scope, ensure_ascii=False, indent=2)- profile_text = json.dumps(student_profile, ensure_ascii=False, indent=2)- gaps_text = json.dumps(available_gaps, ensure_ascii=False, indent=2)-- user_prompt = render_prompt(- prompt["user_template"],- knowledge_scope=scope_text,- student_profile=profile_text,- available_gaps=gaps_text,- )-- result = await call_llm_json(- user_prompt=user_prompt,- system_prompt=prompt["system"],- temperature=0.7,- max_tokens=2048,- )-- task = result if isinstance(result, dict) else {}- task["task_id"] = _normalize_task_id(task, task_index)-- target = task.get("target_gaps", [])- if isinstance(target, str):- target = [target]-- # Keep only valid IDs, deduplicated, preserving order.- seen = set()- normalized = []- for gid in target:- if gid in gap_ids and gid not in seen:- normalized.append(gid)- seen.add(gid)-- # Hard constraint: each task must include at least MIN_GAPS_PER_TASK non-overlapping gaps.- if len(normalized) < MIN_GAPS_PER_TASK:- for gid in ordered_gap_ids:- if gid not in seen:- normalized.append(gid)- seen.add(gid)- if len(normalized) >= MIN_GAPS_PER_TASK:- break-- if len(normalized) < MIN_GAPS_PER_TASK:- logger.warning(- " Task %s has only %d target gaps (<%d), dropping",- task["task_id"],- len(normalized),- MIN_GAPS_PER_TASK,- )- return None-- task["target_gaps"] = normalized- task.pop("gap_pacing_plan", None)- task["primary_gap"] = normalized[0]-- logger.info(f" Task targets gaps: {task['target_gaps']}")- return task---async def generate_tasks_with_partition(- knowledge_scope: dict,- student_profile: dict,- knowledge_gaps: list[dict],- task_index_offset: int = 0,-) -> list[dict]:- """- Generate tasks by iteratively partitioning gaps. Each gap is assigned to- exactly one task: after each task is generated, its target_gaps are removed- from the pool for the next task.-- Args:- knowledge_scope: Knowledge scope dictionary- student_profile: Student profile dictionary- knowledge_gaps: All knowledge gaps for this profile- task_index_offset: Offset for task_id (e.g. when generating multiple batches)-- Returns:- List of task dicts; union of target_gaps equals all gap_ids, no overlap- """- tasks: list[dict] = []- remaining = list(knowledge_gaps)- task_index = task_index_offset-- while len(remaining) >= MIN_GAPS_PER_TASK:- task = await generate_single_task(- knowledge_scope=knowledge_scope,- student_profile=student_profile,- available_gaps=remaining,- task_index=task_index,- )- if not task or len(task.get("target_gaps", [])) < MIN_GAPS_PER_TASK:- break-- tasks.append(task)- assigned_ids = set(task["target_gaps"])- remaining = [g for g in remaining if g.get("gap_id") not in assigned_ids]- task_index += 1-- if remaining:- logger.info(- " Partition complete: %d tasks, %d leftover gaps dropped (<%d required per task)",- len(tasks),- len(remaining),- MIN_GAPS_PER_TASK,- )- else:- logger.info(f" Partition complete: {len(tasks)} tasks, all gaps assigned")- return tasks---def _format_source_for_rejection(page_content: dict[int, str], page_indices: list[int]) -> str:- """Format source content for rejection sampling (only relevant pages)."""- lines = []- for p in sorted(set(page_indices) & set(page_content.keys())):- text = page_content.get(p, "")- if text:- lines.append(f"### Page {p}\n{text[:2500]}{'...' if len(text) > 2500 else ''}")- return "\n\n".join(lines) if lines else "(no content)"---async def batch_rejection_sample_tasks(- tasks: list[dict],- gap_by_id: dict[str, dict],- page_content: dict[int, str],-) -> tuple[list[dict], list[dict]]:- """- Batch rejection sampling: verify each task + gaps align with source content.-- Args:- tasks: List of task dicts with target_gaps- gap_by_id: Mapping gap_id -> gap dict- page_content: page_idx -> text-- Returns:- (accepted_tasks, rejected_tasks)- """- if not tasks or not page_content:- return tasks-- # Collect all source pages used by any task- all_page_indices = []- for task in tasks:- for gid in task.get("target_gaps", []):- gap = gap_by_id.get(gid, {})- all_page_indices.extend(gap.get("source_pages", []))-- source_text = _format_source_for_rejection(page_content, all_page_indices)-- # Build tasks_with_gaps: each task + its full gap objects- tasks_with_gaps_list = []- for task in tasks:- target_gaps = [- gap_by_id.get(gid, {"gap_id": gid})- for gid in task.get("target_gaps", [])- if gid in gap_by_id- ]- tasks_with_gaps_list.append({- "task": task,- "gaps": target_gaps,- })-- tasks_text = json.dumps(tasks_with_gaps_list, ensure_ascii=False, indent=2)-- prompt = load_prompt("reject_task_batch")- user_prompt = prompt["user_template"].format(- source_content=source_text,- tasks_with_gaps=tasks_text,- )-- try:- result = await call_llm_json(- user_prompt=user_prompt,- system_prompt=prompt["system"],- temperature=0.1,- max_tokens=2048,- )- except Exception as e:- logger.warning(f"Rejection sampling failed: {e}, accepting all tasks")- return tasks, []-- results = result.get("results", [])- if not isinstance(results, list):- logger.warning("Rejection result malformed, accepting all tasks")- return tasks, []-- accepted_ids = {r["task_id"] for r in results if r.get("accepted") is True}- accepted = [t for t in tasks if t.get("task_id") in accepted_ids]- rejected = [t for t in tasks if t.get("task_id") not in accepted_ids]- if rejected:- for r in results:- if not r.get("accepted"):- logger.info(f" Rejected task {r.get('task_id')}: {r.get('reason', '?')}")-- return accepted, rejected---async def generate_tasks_with_partition_and_rejection(- knowledge_scope: dict,- student_profile: dict,- knowledge_gaps: list[dict],- page_content: dict[int, str],- max_retries: int = 2,- task_index_offset: int = 0,-) -> list[dict]:- """- Generate tasks with partition, then batch rejection sampling with retry.-- Flow: 10 pages → gaps → tasks (partition). For each task, verify alignment with source.- Rejected tasks are regenerated (same gaps, new task) and re-checked.-- Args:- knowledge_scope: Knowledge scope- student_profile: Student profile- knowledge_gaps: All gaps (with source_pages)- page_content: page_idx -> text for rejection check- max_retries: Max regeneration attempts for rejected tasks-- Returns:- List of accepted tasks only- """- tasks = await generate_tasks_with_partition(- knowledge_scope=knowledge_scope,- student_profile=student_profile,- knowledge_gaps=knowledge_gaps,- task_index_offset=task_index_offset,- )- gap_by_id = {g["gap_id"]: g for g in knowledge_gaps if "gap_id" in g}-- if not page_content:- return tasks-- all_accepted = []- to_process = list(tasks)- retry_count = 0-- while to_process and retry_count <= max_retries:- accepted, rejected = await batch_rejection_sample_tasks(- tasks=to_process,- gap_by_id=gap_by_id,- page_content=page_content,- )- all_accepted.extend(accepted)-- if not rejected:- break-- logger.info(f" Regenerating {len(rejected)} rejected tasks (retry {retry_count + 1})")- to_process = []- for old_task in rejected:- gap_ids = old_task.get("target_gaps", [])- remaining = [gap_by_id[gid] for gid in gap_ids if gid in gap_by_id]- if not remaining:- continue- new_task = await generate_single_task(- knowledge_scope=knowledge_scope,- student_profile=student_profile,- available_gaps=remaining,- task_index=task_index_offset + len(all_accepted) + len(to_process),- )- if new_task:- to_process.append(new_task)-- retry_count += 1-- if to_process and retry_count > max_retries:- logger.warning(f" {len(to_process)} tasks still rejected after {max_retries} retries, accepting them")- all_accepted.extend(to_process)-- return all_accepteddiff --git a/benchmark/evaluation/__init__.py b/benchmark/evaluation/__init__.pydeleted file mode 100644index a186117ce..000000000--- a/benchmark/evaluation/__init__.py+++ /dev/null@@ -1 +0,0 @@-# Benchmark Evaluation - Tutor response and dialog scoringdiff --git a/benchmark/evaluation/evaluator.py b/benchmark/evaluation/evaluator.pydeleted file mode 100644index 9a89008a4..000000000--- a/benchmark/evaluation/evaluator.py+++ /dev/null@@ -1,1071 +0,0 @@-#!/usr/bin/env python-"""-Benchmark Evaluator - Independent metric evaluation (no weighted merge)--Metrics (turn-level):-1) Gap tracking (LLM, per tutor turn): mentioned vs newly resolved gaps-2) Source faithfulness (LLM, per tutor turn): 1-5 score against source text-3) Teaching quality (LLM, per tutor turn): insightfulness + applicability (1-5)-4) Turn count (non-LLM): student/tutor interaction counts--Metrics (practice questions, session-level):-5) Practice question evaluation (LLM):- - gap_coverage (set-level, 1-5)- - difficulty_fit_delta (per-question, -5 to +5)- - groundedness (per-question, 1-5)- - diversity (set-level, 1-5)- - distractor_quality (per-question, 1-5)--Supports:-- Single-session transcript: {"transcript": [...], "entry": {...}}-- Multi-session transcript: {"sessions": [{"transcript": [...], "entry": {...}, ...}, ...]}-"""--import json-import logging-from pathlib import Path--from benchmark.data_generation.llm_utils import call_llm_json, extract_json, load_prompt--logger = logging.getLogger("benchmark.evaluation")--PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent-RECENT_CONTEXT_WINDOW = 8 # messages (student+tutor) to provide around each turn---def _format_profile(profile: dict) -> str:- """Format student profile for prompt."""- parts = []- if profile.get("personality"):- parts.append(f"Personality: {profile['personality']}")- if profile.get("education_background"):- parts.append(f"Background: {profile['education_background']}")- if profile.get("learning_purpose"):- parts.append(f"Purpose: {profile['learning_purpose']}")- ks = profile.get("knowledge_state", {})- if ks.get("known_well"):- parts.append(f"Known well: {', '.join(ks['known_well'][:5])}")- if ks.get("partially_known"):- parts.append(f"Partially known: {', '.join(ks['partially_known'][:5])}")- if ks.get("unknown"):- parts.append(f"Unknown: {', '.join(ks['unknown'][:5])}")- if profile.get("beliefs"):- parts.append(f"Beliefs (may be misconceptions): {profile['beliefs']}")- return "\n".join(parts) if parts else "(no profile)"---def _format_task(task: dict) -> str:- """Format task for prompt."""- parts = []- if task.get("title"):- parts.append(f"Title: {task['title']}")- if task.get("description"):- parts.append(f"Description: {task['description']}")- if task.get("success_criteria"):- parts.append(f"Success criteria: {task['success_criteria']}")- if task.get("target_gaps"):- parts.append(f"Target gaps: {task['target_gaps']}")- return "\n".join(parts) if parts else "(no task)"---def _normalize_source_by_page(source_content: dict | None) -> dict[int, str]:- """Normalize source_content keys to int (JSON may have str page keys)."""- if not source_content:- return {}- out = {}- for k, v in source_content.items():- pk = int(k) if isinstance(k, str) and k.isdigit() else k- if isinstance(pk, int):- out[pk] = v or ""- return out---def _format_transcript(transcript: list[dict]) -> str:- """Format transcript for prompt."""- lines = []- for i, msg in enumerate(transcript, 1):- role = msg.get("role", "?")- content = (msg.get("content", "") or "")[:900]- if len((msg.get("content") or "")) > 900:- content += "..."- lines.append(f"[{i}] {role.upper()}: {content}")- return "\n\n".join(lines) if lines else "(empty)"---def _filter_dialog_messages(transcript: list[dict]) -> list[dict]:- """Keep only student/tutor messages for evaluation scope."""- return [m for m in transcript if m.get("role") in {"student", "tutor"}]---def _extract_turn_pairs(dialog_msgs: list[dict]) -> list[dict]:- """- Build per-turn student->tutor pairs.-- Returns list of:- {- "turn_index": int,- "student_message": str,- "tutor_response": str,- "student_msg_index": int, # index in dialog_msgs- }- """- turns: list[dict] = []- turn_index = 0- for i in range(len(dialog_msgs) - 1):- a, b = dialog_msgs[i], dialog_msgs[i + 1]- if a.get("role") == "student" and b.get("role") == "tutor":- turn_index += 1- turns.append(- {- "turn_index": turn_index,- "student_message": a.get("content", ""),- "tutor_response": b.get("content", ""),- "student_msg_index": i,- }- )- return turns---def _get_recent_context(dialog_msgs: list[dict], student_msg_index: int, window: int = RECENT_CONTEXT_WINDOW) -> str:- """- Return recent context ending at current student message.-- This intentionally provides more than just current turn for metric-1 robustness.- """- start = max(0, student_msg_index - window + 1)- snippet = dialog_msgs[start : student_msg_index + 1]- return _format_transcript(snippet)---def _build_gap_map(gaps: list[dict]) -> dict[str, dict]:- """Build gap_id -> gap dict mapping."""- out = {}- for g in gaps:- gid = str(g.get("gap_id", "")).strip()- if gid:- out[gid] = g- return out---def _format_gap_catalog(gaps: list[dict]) -> str:- """Format full gap catalog for metric-1 prompt."""- if not gaps:- return "(no gaps)"- lines = []- for g in gaps:- gid = g.get("gap_id", "unknown")- concept = g.get("target_concept", "?")- desc = (g.get("description", "") or "")[:350]- mani = (g.get("manifestation", "") or "")[:240]- corr = (g.get("correct_understanding", "") or "")[:320]- lines.append(- f"- gap_id: {gid}\n"- f" concept: {concept}\n"- f" description: {desc}\n"- f" manifestation: {mani}\n"- f" expected_correct_understanding: {corr}"- )- return "\n".join(lines)---def _format_mentioned_gaps_with_source(mentioned_gap_ids: list[str], gap_by_id: dict[str, dict], source_content: dict | None) -> str:- """Format only mentioned gaps and their source excerpts for metric-2."""- if not mentioned_gap_ids:- return "(no mentioned gaps)"-- src_by_page = _normalize_source_by_page(source_content)- lines = []- for gid in mentioned_gap_ids:- gap = gap_by_id.get(gid)- if not gap:- continue- concept = gap.get("target_concept", "?")- desc = (gap.get("description", "") or "")[:260]- lines.append(f"### {gid} - {concept}")- lines.append(f"Description: {desc}")- pages = sorted(set(gap.get("source_pages", [])))- if pages:- lines.append(f"Source pages: {pages}")- for p in pages:- text = src_by_page.get(p, "")- if text:- excerpt = text[:1800] + ("..." if len(text) > 1800 else "")- lines.append(f"Source page {p}:\n{excerpt}")- lines.append("")- return "\n".join(lines).strip() or "(no source excerpt for mentioned gaps)"---async def evaluate_gap_tracking_turn(- *,- entry: dict,- turn_index: int,- student_message: str,- tutor_response: str,- recent_context: str,- previously_mentioned_gap_ids: list[str],- previously_resolved_gap_ids: list[str],- temperature: float,-) -> dict:- """- Metric-1 (LLM): detect mentioned gaps and newly resolved gaps on this tutor turn.-- Strict resolution is enforced in prompt:- - "resolved" requires clear correction + concrete closure evidence, not a casual mention.- """- prompt_cfg = load_prompt("eval_gap_tracking_turn")- profile = entry.get("profile", {})- gaps = entry.get("gaps", [])- task = entry.get("task", {})- gap_by_id = _build_gap_map(gaps)- valid_gap_ids = set(gap_by_id.keys())- unresolved = valid_gap_ids - set(previously_resolved_gap_ids)-- user_prompt = prompt_cfg["user_template"].format(- profile_summary=_format_profile(profile),- task_summary=_format_task(task),- gap_catalog=_format_gap_catalog(gaps),- recent_context=recent_context,- student_message=student_message,- tutor_response=tutor_response,- turn_index=turn_index,- previously_mentioned_gap_ids=sorted(set(previously_mentioned_gap_ids)),- previously_resolved_gap_ids=sorted(set(previously_resolved_gap_ids)),- )-- try:- result = await call_llm_json(- user_prompt=user_prompt,- system_prompt=prompt_cfg["system"],- temperature=temperature,- max_tokens=1024,- )- except (json.JSONDecodeError, Exception) as e:- logger.warning("Gap tracking failed at turn %d: %s", turn_index, e)- return {- "turn_index": turn_index,- "mentioned_gap_ids": [],- "resolved_gap_ids_new": [],- "rationale": f"Evaluation failed: {e}",- "error": str(e),- }-- mentioned = [gid for gid in result.get("mentioned_gap_ids", []) if gid in valid_gap_ids]- mentioned = sorted(set(mentioned))-- resolved_new_raw = [gid for gid in result.get("resolved_gap_ids_new", []) if gid in unresolved]- resolved_new = sorted(set(resolved_new_raw))- # Resolved should be a subset of mentioned on this turn for consistency.- resolved_new = [gid for gid in resolved_new if gid in mentioned]-- return {- "turn_index": turn_index,- "mentioned_gap_ids": mentioned,- "resolved_gap_ids_new": resolved_new,- "rationale": result.get("rationale", ""),- }---async def evaluate_source_faithfulness_turn(- *,- turn_index: int,- student_message: str,- tutor_response: str,- recent_context: str,- mentioned_gap_ids: list[str],- gap_by_id: dict[str, dict],- source_content: dict | None,- temperature: float,-) -> dict:- """- Metric-2 (LLM): faithfulness (1-5) against source text of mentioned gaps only.- """- if not mentioned_gap_ids:- return {- "turn_index": turn_index,- "mentioned_gap_ids": [],- "not_applicable": True,- "reason": "No mentioned gaps on this turn.",- }-- prompt_cfg = load_prompt("eval_source_faithfulness_turn")- source_for_mentioned = _format_mentioned_gaps_with_source(mentioned_gap_ids, gap_by_id, source_content)- if source_for_mentioned.startswith("(no source excerpt"):- return {- "turn_index": turn_index,- "mentioned_gap_ids": mentioned_gap_ids,- "not_applicable": True,- "reason": "Mentioned gaps have no usable source excerpts.",- }-- user_prompt = prompt_cfg["user_template"].format(- turn_index=turn_index,- recent_context=recent_context,- student_message=student_message,- tutor_response=tutor_response,- mentioned_gap_ids=mentioned_gap_ids,- source_content_for_mentioned_gaps=source_for_mentioned,- )-- try:- result = await call_llm_json(- user_prompt=user_prompt,- system_prompt=prompt_cfg["system"],- temperature=temperature,- max_tokens=900,- )- except (json.JSONDecodeError, Exception) as e:- logger.warning("Source faithfulness failed at turn %d: %s", turn_index, e)- return {- "turn_index": turn_index,- "mentioned_gap_ids": mentioned_gap_ids,- "not_applicable": True,- "reason": f"Evaluation failed: {e}",- "error": str(e),- }-- score = result.get("faithfulness_score")- try:- score = int(score)- except (TypeError, ValueError):- score = None- if score is not None:- score = max(1, min(5, score))-- return {- "turn_index": turn_index,- "mentioned_gap_ids": mentioned_gap_ids,- "faithfulness_score": score,- "rationale": result.get("rationale", ""),- "contradictions": result.get("contradictions", result.get("unsupported_claims", [])),- "not_applicable": score is None,- }---def _build_source_faithfulness_summary(per_turn: list[dict]) -> dict:- """Aggregate metric-2 stats: min/max/avg over scored turns only."""- scored = [t["faithfulness_score"] for t in per_turn if not t.get("not_applicable") and t.get("faithfulness_score") is not None]- if not scored:- return {- "scale": "1-5",- "num_scored_turns": 0,- "max_score": None,- "min_score": None,- "avg_score": None,- "per_turn": per_turn,- }- return {- "scale": "1-5",- "num_scored_turns": len(scored),- "max_score": max(scored),- "min_score": min(scored),- "avg_score": round(sum(scored) / len(scored), 2),- "per_turn": per_turn,- }---async def evaluate_teaching_quality_turn(- *,- turn_index: int,- student_message: str,- tutor_response: str,- recent_context: str,- temperature: float,-) -> dict:- """- Metric-3 (LLM): turn-level teaching quality on two dimensions:- - insightfulness (1-5)- - applicability (1-5)- """- prompt_cfg = load_prompt("eval_teaching_quality_turn")- user_prompt = prompt_cfg["user_template"].format(- turn_index=turn_index,- recent_context=recent_context,- student_message=student_message,- tutor_response=tutor_response,- )-- try:- result = await call_llm_json(- user_prompt=user_prompt,- system_prompt=prompt_cfg["system"],- temperature=temperature,- max_tokens=700,- )- except (json.JSONDecodeError, Exception) as e:- logger.warning("Teaching quality failed at turn %d: %s", turn_index, e)- return {- "turn_index": turn_index,- "insightfulness_score": None,- "applicability_score": None,- "rationale": f"Evaluation failed: {e}",- "not_applicable": True,- "error": str(e),- }-- insight = result.get("insightfulness_score")- applicability = result.get("applicability_score")- try:- insight = int(insight) if insight is not None else None- except (TypeError, ValueError):- insight = None- try:- applicability = int(applicability) if applicability is not None else None- except (TypeError, ValueError):- applicability = None-- if insight is not None:- insight = max(1, min(5, insight))- if applicability is not None:- applicability = max(1, min(5, applicability))-- return {- "turn_index": turn_index,- "insightfulness_score": insight,- "applicability_score": applicability,- "rationale": result.get("rationale", ""),- "evidence": result.get("evidence", []),- "not_applicable": insight is None and applicability is None,- }---def _build_teaching_quality_summary(per_turn: list[dict]) -> dict:- """Aggregate metric-3 stats over scored turns only."""- insight_scores = [- t.get("insightfulness_score")- for t in per_turn- if t.get("insightfulness_score") is not None and not t.get("not_applicable")- ]- applicability_scores = [- t.get("applicability_score")- for t in per_turn- if t.get("applicability_score") is not None and not t.get("not_applicable")- ]- return {- "scale": "1-5",- "num_scored_turns_insightfulness": len(insight_scores),- "num_scored_turns_applicability": len(applicability_scores),- "avg_insightfulness": (- round(sum(insight_scores) / len(insight_scores), 2)- if insight_scores- else None- ),- "avg_applicability": (- round(sum(applicability_scores) / len(applicability_scores), 2)- if applicability_scores- else None- ),- "max_insightfulness": max(insight_scores) if insight_scores else None,- "min_insightfulness": min(insight_scores) if insight_scores else None,- "max_applicability": max(applicability_scores) if applicability_scores else None,- "min_applicability": min(applicability_scores) if applicability_scores else None,- "per_turn": per_turn,- }---# ======================================================================-# Practice question evaluation (session-level, 5 metrics)-# ======================================================================--def _format_gaps_with_source_for_pq(gaps: list[dict], source_content: dict | None) -> str:- """Format gaps + their source pages for practice question groundedness evaluation."""- src_by_page = _normalize_source_by_page(source_content)- lines = []- for g in gaps:- gid = g.get("gap_id", "?")- concept = g.get("target_concept", "?")- desc = (g.get("description", "") or "")[:300]- correct = (g.get("correct_understanding", "") or "")[:300]- lines.append(f"### {gid} - {concept}")- lines.append(f"Description: {desc}")- if correct:- lines.append(f"Correct understanding: {correct}")- pages = sorted(set(g.get("source_pages", [])))- for p in pages:- text = src_by_page.get(p, "")- if text:- excerpt = text[:1500] + ("..." if len(text) > 1500 else "")- lines.append(f"Source page {p}:\n{excerpt}")- lines.append("")- return "\n".join(lines).strip() or "(no source content)"---def _clamp_score(raw, lo: int = 1, hi: int = 5) -> int | None:- if raw is None:- return None- try:- v = int(raw)- except (TypeError, ValueError):- return None- return max(lo, min(hi, v))---async def _eval_pq_gap_coverage(- questions_block: str,- gaps: list[dict],- temperature: float,-) -> dict:- """Set-level: how well the full question set covers each gap (1-5)."""- from src.services.llm import factory-- gap_view = [- {"gap_id": g.get("gap_id", ""), "type": g.get("type", ""),- "target_concept": g.get("target_concept", ""), "description": g.get("description", "")}- for g in gaps- ]- prompt = (- "Evaluate the following PRACTICE QUESTION SET as a whole.\n\n"- f"Question set:\n{questions_block}\n\n"- f"Knowledge gaps:\n{json.dumps(gap_view, ensure_ascii=False, indent=2)}\n\n"- "Return strict JSON only:\n"- '{"gap_scores": {"gap_id": 1-5, "...": 1-5}, "rationale": "short reason"}\n\n'- "Scoring guide:\n"- "- For EACH gap, score how well the FULL question set covers that gap.\n"- "- 1 means almost no coverage; 5 means strong and explicit coverage.\n"- )- try:- raw = await factory.complete(prompt=prompt,- system_prompt="You are a strict education evaluator. Output valid JSON only, no markdown.",- temperature=temperature, max_tokens=1000)- parsed = extract_json(raw)- except Exception as e:- logger.warning("Practice gap-coverage eval failed: %s", e)- parsed = {"gap_scores": {g.get("gap_id", f"gap_{i}"): 1 for i, g in enumerate(gaps)},- "rationale": f"fallback: {e}"}-- scores: dict[str, int] = {}- for g in gap_view:- gid = g.get("gap_id", "")- scores[gid] = _clamp_score((parsed.get("gap_scores") or {}).get(gid, 1)) or 1- avg = round(sum(scores.values()) / len(scores), 2) if scores else None- return {"gap_scores": scores, "avg": avg, "rationale": parsed.get("rationale", "")}---async def _eval_pq_per_question(- questions: list[str],- gaps: list[dict],- source_content: dict | None,- profile: dict,- temperature: float,-) -> list[dict]:- """Per-question: difficulty_fit_delta, groundedness, distractor_quality."""- from src.services.llm import factory-- gap_source_block = _format_gaps_with_source_for_pq(gaps, source_content)- profile_view = json.dumps({- "profile_id": profile.get("profile_id", ""),- "learning_purpose": profile.get("learning_purpose", ""),- "knowledge_state": profile.get("knowledge_state", {}),- }, ensure_ascii=False, indent=2)-- results = []- for i, q in enumerate(questions, start=1):- prompt = (- f"Evaluate this multiple-choice practice question (Q{i}) on three dimensions.\n\n"- f"Question:\n{q}\n\n"- f"Student profile:\n{profile_view}\n\n"- f"Knowledge gaps and source content:\n{gap_source_block}\n\n"- "Return strict JSON only:\n"- "{\n"- ' "difficulty_fit_delta": -5_to_5,\n'- ' "groundedness": 1-5,\n'- ' "distractor_quality": 1-5,\n'- ' "rationale": "short reason"\n'- "}\n\n"- "Scoring guide:\n"- "- difficulty_fit_delta: -5 = much too easy for this student, "- "+5 = much too hard, 0 = ideal fit.\n"- "- groundedness (1-5): Are the question's claims, terminology, and "- "correct answer consistent with the source content? "- "Check THREE aspects:\n"- " (a) Factual consistency: do factual claims align with and not "- "contradict the source?\n"- " (b) Terminological consistency: does the question use the same "- "definitions, terminology, and framing as the source? Different "- "textbooks may define concepts differently; the question should follow "- "the source's conventions, not introduce alternative definitions.\n"- " (c) Source grounding: does the question draw on specific details, "- "examples, or structures from the source material? A question that "- "references concrete content from the source (even paraphrased) is "- "better grounded than one based on generic knowledge alone.\n"- "A question that goes beyond the source (e.g. applies concepts to new "- "scenarios) is fine as long as it doesn't distort or contradict the source. "- "5 = all claims are accurate, terminology matches, AND the question "- "clearly draws on specific source content; "- "4 = mostly consistent, some evidence of source grounding, minor "- "imprecision in wording; "- "3 = some claims or definitions deviate from the source, or the question "- "appears largely generic with weak connection to source material; "- "2 = multiple claims contradict the source, or key terms use different "- "definitions, or no evidence of consulting the source; "- "1 = core claims are wrong or hallucinated, or terminology directly "- "conflicts with the source's definitions.\n"- "- distractor_quality (1-5): Quality of wrong answer options. "- "5 = distractors target common misconceptions, are plausible but clearly wrong; "- "1 = distractors are obviously absurd or trivially eliminable. "- "If the question has no options/distractors, score 1.\n"- )- try:- raw = await factory.complete(prompt=prompt,- system_prompt="You are a strict education evaluator. Output valid JSON only.",- temperature=temperature, max_tokens=800)- parsed = extract_json(raw)- except Exception as e:- logger.warning("Practice Q%d per-question eval failed: %s", i, e)- parsed = {"difficulty_fit_delta": 0, "groundedness": 1, "distractor_quality": 1,- "rationale": f"fallback: {e}"}-- diff_delta = _clamp_score(parsed.get("difficulty_fit_delta"), -5, 5) or 0- results.append({- "question_index": i,- "question_preview": q[:200],- "difficulty_fit_delta": diff_delta,- "difficulty_abs": abs(diff_delta),- "groundedness": _clamp_score(parsed.get("groundedness")) or 1,- "distractor_quality": _clamp_score(parsed.get("distractor_quality")) or 1,- "rationale": parsed.get("rationale", ""),- })- return results---async def _eval_pq_diversity(questions_block: str, temperature: float) -> dict:- """Set-level: diversity among questions (1-5)."""- from src.services.llm import factory-- prompt = (- "Evaluate the DIVERSITY of the following practice question set.\n\n"- f"Question set:\n{questions_block}\n\n"- "Return strict JSON only:\n"- '{"diversity_score": 1-5, "rationale": "short reason"}\n\n'- "Scoring guide:\n"- "- 5 = questions cover different knowledge points, cognitive levels "- "(recall, understanding, application, analysis), and problem setups. "- "No redundancy.\n"- "- 1 = questions are near-duplicates or all test the same narrow concept "- "at the same level.\n"- )- try:- raw = await factory.complete(prompt=prompt,- system_prompt="You are a strict education evaluator. Output valid JSON only.",- temperature=temperature, max_tokens=500)- parsed = extract_json(raw)- except Exception as e:- logger.warning("Practice diversity eval failed: %s", e)- parsed = {"diversity_score": 1, "rationale": f"fallback: {e}"}-- return {- "diversity_score": _clamp_score(parsed.get("diversity_score")) or 1,- "rationale": parsed.get("rationale", ""),- }---async def evaluate_practice_questions(- *,- practice_questions: list[str],- entry: dict,- temperature: float,-) -> dict:- """Full practice question evaluation with 5 metrics.-- Returns dict with keys: per_question, gap_coverage, diversity, summary.- """- if not practice_questions:- return {- "per_question": [],- "gap_coverage": None,- "diversity": None,- "summary": {- "num_questions": 0,- "avg_gap_coverage": None,- "avg_difficulty_abs": None,- "avg_groundedness": None,- "avg_distractor_quality": None,- "diversity_score": None,- },- }-- gaps = entry.get("gaps", [])- profile = entry.get("profile", {})- source_content = entry.get("source_content")-- questions_block = "\n\n".join(f"Q{i}. {q}" for i, q in enumerate(practice_questions, 1))-- coverage_result = await _eval_pq_gap_coverage(questions_block, gaps, temperature)- per_question = await _eval_pq_per_question(- practice_questions, gaps, source_content, profile, temperature)- diversity_result = await _eval_pq_diversity(questions_block, temperature)-- diff_abs = [pq["difficulty_abs"] for pq in per_question]- ground_scores = [pq["groundedness"] for pq in per_question]- distractor_scores = [pq["distractor_quality"] for pq in per_question]-- return {- "per_question": per_question,- "gap_coverage": coverage_result,- "diversity": diversity_result,- "summary": {- "num_questions": len(per_question),- "avg_gap_coverage": coverage_result.get("avg"),- "avg_difficulty_abs": round(sum(diff_abs) / len(diff_abs), 2) if diff_abs else None,- "avg_groundedness": round(sum(ground_scores) / len(ground_scores), 2) if ground_scores else None,- "avg_distractor_quality": round(sum(distractor_scores) / len(distractor_scores), 2) if distractor_scores else None,- "diversity_score": diversity_result.get("diversity_score"),- },- }---def _load_entry_by_id(entry_id: str) -> dict | None:- """- Try to load entry by entry_id from generated JSONL files.- Supports nested benchmark_<timestamp>/_all_entries.jsonl layout.- """- generated_dir = PROJECT_ROOT / "benchmark" / "data" / "generated"- candidates = sorted(generated_dir.glob("**/*.jsonl"))- for jsonl_path in candidates:- with open(jsonl_path, encoding="utf-8") as f:- for line in f:- line = line.strip()- if not line:- continue- entry = json.loads(line)- if entry.get("entry_id") == entry_id:- return entry- return None---async def _evaluate_single_session(- *,- transcript: list[dict],- entry: dict,- entry_id: str,- skip_turns: bool,- temperature: float,- practice_questions: list[str] | None = None,-) -> dict:- """Evaluate one session with turn-level + practice-question metrics."""- dialog_msgs = _filter_dialog_messages(transcript)- turns = _extract_turn_pairs(dialog_msgs)- gaps = entry.get("gaps", [])- gap_by_id = _build_gap_map(gaps)- source_content = entry.get("source_content")-- has_pq = bool(practice_questions)- eval_turns = turns- if has_pq and eval_turns:- eval_turns = turns[:-1]- logger.info("Excluding last turn (practice questions) from turn-level evaluation")-- logger.info(- "Metrics: gap_tracking, faithfulness%s, teaching_quality, turn_count | practice_questions=%s",- " [source present]" if source_content else "",- f"{len(practice_questions)} Qs" if has_pq else "none",- )-- student_turns = sum(1 for m in dialog_msgs if m.get("role") == "student")- tutor_turns = sum(1 for m in dialog_msgs if m.get("role") == "tutor")- turn_count_metric = {- "student_turns": student_turns,- "tutor_turns": tutor_turns,- "paired_turns": len(eval_turns),- }-- gap_tracking_per_turn: list[dict] = []- source_faithfulness_per_turn: list[dict] = []- teaching_quality_per_turn: list[dict] = []- mentioned_so_far: set[str] = set()- resolved_so_far: set[str] = set()-- if not skip_turns:- for t in eval_turns:- turn_index = t["turn_index"]- student_message = t["student_message"]- tutor_response = t["tutor_response"]- recent_context = _get_recent_context(dialog_msgs, t["student_msg_index"])-- gap_turn = await evaluate_gap_tracking_turn(- entry=entry,- turn_index=turn_index,- student_message=student_message,- tutor_response=tutor_response,- recent_context=recent_context,- previously_mentioned_gap_ids=sorted(mentioned_so_far),- previously_resolved_gap_ids=sorted(resolved_so_far),- temperature=temperature,- )- mentioned_turn = set(gap_turn.get("mentioned_gap_ids", []))- resolved_turn_new = set(gap_turn.get("resolved_gap_ids_new", []))-- mentioned_so_far |= mentioned_turn- resolved_so_far |= resolved_turn_new-- gap_turn["resolved_gap_ids_total"] = sorted(resolved_so_far)- gap_turn["mentioned_count_turn"] = len(mentioned_turn)- gap_turn["resolved_count_turn_new"] = len(resolved_turn_new)- gap_turn["resolved_count_total"] = len(resolved_so_far)- gap_tracking_per_turn.append(gap_turn)-- faith_turn = await evaluate_source_faithfulness_turn(- turn_index=turn_index,- student_message=student_message,- tutor_response=tutor_response,- recent_context=recent_context,- mentioned_gap_ids=sorted(mentioned_turn),- gap_by_id=gap_by_id,- source_content=source_content,- temperature=temperature,- )- source_faithfulness_per_turn.append(faith_turn)-- quality_turn = await evaluate_teaching_quality_turn(- turn_index=turn_index,- student_message=student_message,- tutor_response=tutor_response,- recent_context=recent_context,- temperature=temperature,- )- teaching_quality_per_turn.append(quality_turn)-- logger.info(- "Turn %d: mentioned=%d, resolved_new=%d, resolved_total=%d, faith=%s, insight=%s, applic=%s",- turn_index, len(mentioned_turn), len(resolved_turn_new), len(resolved_so_far),- faith_turn.get("faithfulness_score", "N/A"),- quality_turn.get("insightfulness_score", "N/A"),- quality_turn.get("applicability_score", "N/A"),- )-- gap_tracking_metric = {- "total_gaps": len(gap_by_id),- "mentioned_gap_ids_final": sorted(mentioned_so_far),- "resolved_gap_ids_final": sorted(resolved_so_far),- "resolved_gaps_final_count": len(resolved_so_far),- "per_turn": gap_tracking_per_turn,- }- source_faithfulness_metric = _build_source_faithfulness_summary(source_faithfulness_per_turn)- teaching_quality_metric = _build_teaching_quality_summary(teaching_quality_per_turn)-- result: dict = {- "entry_id": entry_id,- "actual_turns": len(eval_turns),- "metrics": {- "gap_tracking": gap_tracking_metric,- "source_faithfulness": source_faithfulness_metric,- "teaching_quality": teaching_quality_metric,- "turn_count": turn_count_metric,- },- }-- if has_pq and not skip_turns:- logger.info("Evaluating %d practice questions...", len(practice_questions))- pq_eval = await evaluate_practice_questions(- practice_questions=practice_questions,- entry=entry,- temperature=temperature,- )- result["metrics"]["practice_questions"] = pq_eval- s = pq_eval.get("summary", {})- logger.info(- "Practice Q: gap_cov=%.2f ground=%.2f distractor=%.2f diversity=%s diff_abs=%.2f",- s.get("avg_gap_coverage") or 0, s.get("avg_groundedness") or 0,- s.get("avg_distractor_quality") or 0, s.get("diversity_score", "N/A"),- s.get("avg_difficulty_abs") or 0,- )- elif has_pq and skip_turns:- result["metrics"]["practice_questions"] = {- "num_questions": len(practice_questions),- "note": "skipped (--skip-turns)",- }-- return result---def _safe_avg(vals: list[float]) -> float | None:- return round(sum(vals) / len(vals), 2) if vals else None---def _aggregate_multi_session(session_results: list[dict]) -> dict:- """Build lightweight aggregate view; each session gap stats stay independent."""- if not session_results:- return {}-- total_student_turns = 0- total_tutor_turns = 0- total_paired_turns = 0- faith_scores: list[float] = []- insight_scores: list[float] = []- applicability_scores: list[float] = []- resolved_counts: list[int] = []- total_gaps_counts: list[int] = []-- pq_total_questions = 0- pq_coverage: list[float] = []- pq_diff_abs: list[float] = []- pq_ground: list[float] = []- pq_distractor: list[float] = []- pq_diversity: list[float] = []-- for s in session_results:- tc = s.get("metrics", {}).get("turn_count", {})- total_student_turns += tc.get("student_turns", 0)- total_tutor_turns += tc.get("tutor_turns", 0)- total_paired_turns += tc.get("paired_turns", 0)-- gt = s.get("metrics", {}).get("gap_tracking", {})- resolved_counts.append(gt.get("resolved_gaps_final_count", 0))- total_gaps_counts.append(gt.get("total_gaps", 0))-- sf = s.get("metrics", {}).get("source_faithfulness", {})- for t in sf.get("per_turn", []):- score = t.get("faithfulness_score")- if score is not None and not t.get("not_applicable"):- faith_scores.append(float(score))-- tq = s.get("metrics", {}).get("teaching_quality", {})- for t in tq.get("per_turn", []):- ins = t.get("insightfulness_score")- app = t.get("applicability_score")- if ins is not None and not t.get("not_applicable"):- insight_scores.append(float(ins))- if app is not None and not t.get("not_applicable"):- applicability_scores.append(float(app))-- pq = s.get("metrics", {}).get("practice_questions")- if pq and pq.get("summary"):- sm = pq["summary"]- pq_total_questions += sm.get("num_questions", 0)- for key, lst in [("avg_gap_coverage", pq_coverage), ("avg_difficulty_abs", pq_diff_abs),- ("avg_groundedness", pq_ground), ("avg_distractor_quality", pq_distractor),- ("diversity_score", pq_diversity)]:- v = sm.get(key)- if isinstance(v, (int, float)):- lst.append(float(v))-- total_resolved = sum(resolved_counts)- total_gaps = sum(total_gaps_counts)- gap_resolution_rate = round(total_resolved / total_gaps, 3) if total_gaps else None- gap_efficiency = (- round(total_resolved / total_paired_turns, 3) if total_paired_turns else None- )-- result: dict = {- "turn_count": {- "student_turns_total": total_student_turns,- "tutor_turns_total": total_tutor_turns,- "paired_turns_total": total_paired_turns,- },- "gap_tracking": {- "resolved_gaps_per_session": resolved_counts,- "total_gaps_per_session": total_gaps_counts,- "total_resolved": total_resolved,- "total_gaps": total_gaps,- "gap_resolution_rate": gap_resolution_rate,- "gap_resolution_efficiency": gap_efficiency,- },- "source_faithfulness": {- "scale": "1-5",- "num_scored_turns_total": len(faith_scores),- "max_score_overall": max(faith_scores) if faith_scores else None,- "min_score_overall": min(faith_scores) if faith_scores else None,- "avg_score_overall": _safe_avg(faith_scores),- },- "teaching_quality": {- "scale": "1-5",- "num_scored_turns_insightfulness_total": len(insight_scores),- "num_scored_turns_applicability_total": len(applicability_scores),- "avg_insightfulness_overall": _safe_avg(insight_scores),- "avg_applicability_overall": _safe_avg(applicability_scores),- },- }-- if pq_total_questions > 0:- result["practice_questions"] = {- "total_questions_across_sessions": pq_total_questions,- "avg_gap_coverage": _safe_avg(pq_coverage),- "avg_difficulty_abs": _safe_avg(pq_diff_abs),- "avg_groundedness": _safe_avg(pq_ground),- "avg_distractor_quality": _safe_avg(pq_distractor),- "avg_diversity": _safe_avg(pq_diversity),- }-- return result---async def evaluate_transcript(- transcript_path: str | Path,- skip_turns: bool = False,- temperature: float = 0.2,-) -> dict:- """- Evaluate transcript using independent metrics (no weighted merge).-- Args:- transcript_path: Path to transcript JSON- skip_turns: If True, skip LLM per-turn metrics and keep only turn_count- temperature: LLM temperature for metric-1 and metric-2- """- path = Path(transcript_path)- if not path.exists():- raise FileNotFoundError(f"Transcript not found: {path}")-- with open(path, encoding="utf-8") as f:- data = json.load(f)-- # Multi-session format- if "sessions" in data:- sessions = data["sessions"]- profile_id = data.get("profile_id", "unknown")- session_results = []-- for i, sess in enumerate(sessions):- transcript = sess.get("transcript", [])- entry = sess.get("entry")- entry_id = sess.get("entry_id", f"session_{i+1}")-- if not entry:- entry = _load_entry_by_id(entry_id)- if not entry:- logger.warning(- "Session %s has no entry; skipping (run multi-session again to save entry)",- entry_id,- )- continue-- logger.info("Evaluating session %d/%d: %s", i + 1, len(sessions), entry_id)- sess_result = await _evaluate_single_session(- transcript=transcript,- entry=entry,- entry_id=entry_id,- skip_turns=skip_turns,- temperature=temperature,- practice_questions=sess.get("practice_questions"),- )- session_results.append(sess_result)-- if not session_results:- raise ValueError(- "No sessions could be evaluated (missing 'entry' in each session; "- "re-run multi-session to save entries)"- )-- return {- "profile_id": profile_id,- "transcript_path": str(path),- "num_sessions": len(session_results),- "sessions": session_results,- "aggregate": _aggregate_multi_session(session_results),- }-- # Single-session format- transcript = data.get("transcript", [])- entry = data.get("entry", {})- if not entry:- raise ValueError("Transcript must contain 'entry' (benchmark entry with profile, gaps, task)")-- result = await _evaluate_single_session(- transcript=transcript,- entry=entry,- entry_id=data.get("entry_id", "unknown"),- skip_turns=skip_turns,- temperature=temperature,- practice_questions=data.get("practice_questions"),- )- result["transcript_path"] = str(path)- return resultdiff --git a/benchmark/evaluation/request_eval.py b/benchmark/evaluation/request_eval.pydeleted file mode 100644index b94c2317f..000000000--- a/benchmark/evaluation/request_eval.py+++ /dev/null@@ -1,602 +0,0 @@-#!/usr/bin/env python3-"""-Request-based evaluation runner.--Evaluate request dataset records with:- 1) baseline model (direct LLM completion)- 2) DeepTutor tools (solve_question / generate_questions)--Each record contains:- - solve_request.query- - question_request.query--For each system and each task type (solve/question), this script:- - generates output- - runs LLM-as-judge scoring- - stores detailed per-record result and aggregate summary-"""--from __future__ import annotations--import argparse-import asyncio-import json-import logging-import sys-import time-from datetime import datetime-from pathlib import Path-from typing import Any--# Ensure project root is importable when executed directly.-_THIS_FILE = Path(__file__).resolve()-_PROJECT_ROOT_FOR_IMPORT = _THIS_FILE.parents[2]-if str(_PROJECT_ROOT_FOR_IMPORT) not in sys.path:- sys.path.insert(0, str(_PROJECT_ROOT_FOR_IMPORT))--from benchmark.data_generation.llm_utils import call_llm_json-from src.services.llm import factory--logger = logging.getLogger("benchmark.request_eval")--PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent-DEFAULT_GENERATED_DIR = PROJECT_ROOT / "benchmark" / "data" / "generated"-DEFAULT_EVAL_DIR = PROJECT_ROOT / "benchmark" / "data" / "evaluations"-DEFAULT_WORKSPACE_DIR = PROJECT_ROOT / "benchmark" / "data" / "request_eval_workspaces"---def _normalize_space(text: str) -> str:- return " ".join((text or "").strip().split())---def _discover_latest_dir(prefix: str, base_dir: Path) -> Path:- candidates = [p for p in base_dir.glob(f"{prefix}_*") if p.is_dir()]- if not candidates:- raise FileNotFoundError(f"No {prefix}_* directories found under: {base_dir}")- return max(candidates, key=lambda p: p.stat().st_mtime)---def _load_request_records(requests_dir: Path, limit: int = 0) -> list[dict[str, Any]]:- files = sorted(p for p in requests_dir.glob("*.json") if not p.name.startswith("_"))- if limit > 0:- files = files[:limit]- if not files:- raise ValueError(f"No request records found in: {requests_dir}")-- records: list[dict[str, Any]] = []- for fp in files:- with open(fp, encoding="utf-8") as f:- data = json.load(f)- if isinstance(data, dict) and "solve_request" in data and "question_request" in data:- records.append(data)- else:- logger.warning("Skip invalid request file: %s", fp)- return records---def _load_profile_context_map(benchmark_dir: Path) -> dict[tuple[str, str], dict[str, Any]]:- """- Load minimal profile context from benchmark entries keyed by (kb_name, profile_id).- """- ctx_map: dict[tuple[str, str], dict[str, Any]] = {}- files = sorted(p for p in benchmark_dir.glob("*.json") if not p.name.startswith("_"))- for fp in files:- try:- with open(fp, encoding="utf-8") as f:- entry = json.load(f)- except Exception:- continue-- if not isinstance(entry, dict):- continue- kb_name = str(entry.get("kb_name", ""))- profile = entry.get("profile", {}) or {}- profile_id = str(profile.get("profile_id", ""))- if not kb_name or not profile_id:- continue-- key = (kb_name, profile_id)- task = entry.get("task", {}) or {}- title = _normalize_space(str(task.get("title", "")))- if key not in ctx_map:- ctx_map[key] = {- "profile": profile,- "task_titles": [title] if title else [],- }- elif title and title not in ctx_map[key]["task_titles"]:- ctx_map[key]["task_titles"].append(title)- return ctx_map---def _format_profile_context(profile: dict[str, Any], task_titles: list[str]) -> str:- ks = profile.get("knowledge_state", {}) or {}- parts = [- f"profile_id: {profile.get('profile_id', '')}",- f"learning_purpose: {_normalize_space(str(profile.get('learning_purpose', '')))}",- f"task_topics: {task_titles[:3]}",- f"known_well: {ks.get('known_well', [])[:4]}",- f"partially_known: {ks.get('partially_known', [])[:4]}",- f"unknown: {ks.get('unknown', [])[:4]}",- ]- return "\n".join(parts)---def _format_question_from_deeptutor(result: dict[str, Any]) -> str:- qs = result.get("questions", []) or []- if not qs:- return "(No question generated.)"- q = qs[0] or {}- stem = _normalize_space(str(q.get("question", "")))- options = q.get("options", {})- lines = [stem] if stem else ["(Empty question)"]- if isinstance(options, dict):- for k, v in options.items():- lines.append(f"{k}. {v}")- return "\n".join(lines)---async def _generate_with_baseline(query: str, task_type: str) -> str:- if task_type == "solve":- system_prompt = (- "You are a helpful tutor. Solve the user's requested problem clearly "- "with concise step-by-step reasoning."- )- else:- system_prompt = (- "You are a tutor creating practice problems. Generate exactly one practice question "- "only. Do not include solution or hints."- )- text = await factory.complete(- prompt=query,- system_prompt=system_prompt,- temperature=0.3,- max_tokens=800,- )- return (text or "").strip()---async def _generate_with_deeptutor(- *,- task_type: str,- kb_name: str,- query: str,- workspace: str,- language: str,-) -> str:- from benchmark.iso_solve.core.pipeline import run_solver_pipeline- from benchmark.simulation.tools import generate_questions-- if task_type == "solve":- solve_tools = ["code_execute", "reason"]- result = await run_solver_pipeline(- question=query,- workspace=workspace,- language=language,- tools=solve_tools,- )- return (result.get("final_answer") or "").strip() or "(No answer generated.)"-- # iso_solve-style gating: if rag is disabled for question generation,- # don't pass a KB name to avoid any accidental KB-side initialization.- q_tools = {"rag": False, "web": False}- q_kb_name = kb_name if q_tools["rag"] else ""- q_result = await generate_questions(- workspace=workspace,- kb_name=q_kb_name,- topic=query,- num_questions=1,- language=language,- enable_memory=False,- enable_rag=q_tools["rag"],- enable_web=q_tools["web"],- )- return _format_question_from_deeptutor(q_result)---async def _judge_solve(- *,- query: str,- output_text: str,- profile_context: str,-) -> dict[str, Any]:- system_prompt = (- "You are a strict evaluator. Return valid JSON only."- )- user_prompt = (- "Evaluate the quality of a tutoring solve response.\n\n"- f"Request:\n{query}\n\n"- f"Student context:\n{profile_context}\n\n"- f"System output:\n{output_text}\n\n"- "Return JSON only with keys:\n"- "{\n"- ' "relevance": 1-5,\n'- ' "clarity": 1-5,\n'- ' "helpfulness": 1-5,\n'- ' "overall": 1-5,\n'- ' "rationale": "short reason"\n'- "}"- )- try:- data = await call_llm_json(- user_prompt=user_prompt,- system_prompt=system_prompt,- temperature=0.0,- max_tokens=600,- )- except Exception as e:- return {- "relevance": None,- "clarity": None,- "helpfulness": None,- "overall": None,- "rationale": f"judge_failed: {e}",- "error": str(e),- }-- def _clamp(x: Any) -> int | None:- try:- v = int(x)- return max(1, min(5, v))- except Exception:- return None-- return {- "relevance": _clamp(data.get("relevance")),- "clarity": _clamp(data.get("clarity")),- "helpfulness": _clamp(data.get("helpfulness")),- "overall": _clamp(data.get("overall")),- "rationale": data.get("rationale", ""),- }---async def _judge_question(- *,- query: str,- output_text: str,- profile_context: str,-) -> dict[str, Any]:- system_prompt = "You are a strict evaluator. Return valid JSON only."- user_prompt = (- "Evaluate a generated practice question.\n\n"- f"Request:\n{query}\n\n"- f"Student context:\n{profile_context}\n\n"- f"Generated output:\n{output_text}\n\n"- "Return JSON only with keys:\n"- "{\n"- ' "request_following": 1-5,\n'- ' "topic_relevance": 1-5,\n'- ' "difficulty_fit": 1-5,\n'- ' "clarity": 1-5,\n'- ' "overall": 1-5,\n'- ' "rationale": "short reason"\n'- "}"- )- try:- data = await call_llm_json(- user_prompt=user_prompt,- system_prompt=system_prompt,- temperature=0.0,- max_tokens=600,- )- except Exception as e:- return {- "request_following": None,- "topic_relevance": None,- "difficulty_fit": None,- "clarity": None,- "overall": None,- "rationale": f"judge_failed: {e}",- "error": str(e),- }-- def _clamp(x: Any) -> int | None:- try:- v = int(x)- return max(1, min(5, v))- except Exception:- return None-- return {- "request_following": _clamp(data.get("request_following")),- "topic_relevance": _clamp(data.get("topic_relevance")),- "difficulty_fit": _clamp(data.get("difficulty_fit")),- "clarity": _clamp(data.get("clarity")),- "overall": _clamp(data.get("overall")),- "rationale": data.get("rationale", ""),- }---def _avg(nums: list[float]) -> float | None:- return round(sum(nums) / len(nums), 4) if nums else None---def _build_summary(results: list[dict[str, Any]], systems: list[str]) -> dict[str, Any]:- summary: dict[str, Any] = {}- for system in systems:- solve_scores: list[float] = []- question_scores: list[float] = []- failures = 0- for r in results:- sr = (r.get("systems", {}).get(system, {}).get("solve", {}) or {})- qr = (r.get("systems", {}).get(system, {}).get("question", {}) or {})- s_overall = sr.get("judge", {}).get("overall")- q_overall = qr.get("judge", {}).get("overall")- if isinstance(s_overall, (int, float)):- solve_scores.append(float(s_overall))- if isinstance(q_overall, (int, float)):- question_scores.append(float(q_overall))- if sr.get("error") or qr.get("error"):- failures += 1- combined = [*solve_scores, *question_scores]- summary[system] = {- "num_records": len(results),- "num_failures": failures,- "solve_overall_avg": _avg(solve_scores),- "question_overall_avg": _avg(question_scores),- "combined_overall_avg": _avg(combined),- }- return summary---async def _eval_one_record(- record: dict[str, Any],- systems: list[str],- profile_context_map: dict[tuple[str, str], dict[str, Any]],- deeptutor_language: str,- record_index: int = 0,- total_records: int = 0,-) -> dict[str, Any]:- kb_name = str(record.get("kb_name", ""))- profile_id = str(record.get("profile_id", ""))- profile_entry_id = str(record.get("profile_entry_id", f"{kb_name}_{profile_id}"))-- solve_query = ((record.get("solve_request") or {}).get("query") or "").strip()- question_query = ((record.get("question_request") or {}).get("query") or "").strip()-- ctx = profile_context_map.get((kb_name, profile_id), {})- profile = ctx.get("profile", {}) or {}- task_titles = ctx.get("task_titles", []) or []- profile_context = _format_profile_context(profile, task_titles)-- output = {- "profile_entry_id": profile_entry_id,- "kb_name": kb_name,- "profile_id": profile_id,- "topic": record.get("topic", ""),- "systems": {},- }- prefix = f"[record {record_index}/{total_records} {profile_entry_id}]"- logger.info("%s start", prefix)-- for system in systems:- system_out: dict[str, Any] = {}- logger.info("%s [%s] start", prefix, system)-- # solve- t0 = time.perf_counter()- solve_text = ""- solve_error = None- logger.info("%s [%s] solve.generate start", prefix, system)- try:- if system == "baseline":- solve_text = await _generate_with_baseline(solve_query, "solve")- else:- ws = str(DEFAULT_WORKSPACE_DIR / profile_entry_id / "deeptutor")- solve_text = await _generate_with_deeptutor(- task_type="solve",- kb_name=kb_name,- query=solve_query,- workspace=ws,- language=deeptutor_language,- )- except Exception as e:- solve_error = str(e)- solve_text = ""- logger.info(- "%s [%s] solve.generate done in %.2fs%s",- prefix,- system,- time.perf_counter() - t0,- f" (error: {solve_error})" if solve_error else "",- )- logger.info("%s [%s] solve.judge start", prefix, system)- solve_judge = await _judge_solve(- query=solve_query,- output_text=solve_text,- profile_context=profile_context,- )- logger.info(- "%s [%s] solve.judge done (overall=%s)",- prefix,- system,- solve_judge.get("overall"),- )- system_out["solve"] = {- "query": solve_query,- "output": solve_text,- "judge": solve_judge,- "elapsed_sec": round(time.perf_counter() - t0, 3),- "error": solve_error,- }-- # question- t1 = time.perf_counter()- question_text = ""- question_error = None- logger.info("%s [%s] question.generate start", prefix, system)- try:- if system == "baseline":- question_text = await _generate_with_baseline(question_query, "question")- else:- ws = str(DEFAULT_WORKSPACE_DIR / profile_entry_id / "deeptutor")- question_text = await _generate_with_deeptutor(- task_type="question",- kb_name=kb_name,- query=question_query,- workspace=ws,- language=deeptutor_language,- )- except Exception as e:- question_error = str(e)- question_text = ""- logger.info(- "%s [%s] question.generate done in %.2fs%s",- prefix,- system,- time.perf_counter() - t1,- f" (error: {question_error})" if question_error else "",- )- logger.info("%s [%s] question.judge start", prefix, system)- question_judge = await _judge_question(- query=question_query,- output_text=question_text,- profile_context=profile_context,- )- logger.info(- "%s [%s] question.judge done (overall=%s)",- prefix,- system,- question_judge.get("overall"),- )- system_out["question"] = {- "query": question_query,- "output": question_text,- "judge": question_judge,- "elapsed_sec": round(time.perf_counter() - t1, 3),- "error": question_error,- }-- output["systems"][system] = system_out- logger.info(- "%s [%s] done (solve=%.2fs question=%.2fs)",- prefix,- system,- system_out["solve"]["elapsed_sec"],- system_out["question"]["elapsed_sec"],- )- logger.info("%s complete", prefix)- return output---async def async_main() -> None:- parser = argparse.ArgumentParser(description="Evaluate request dataset with baseline and DeepTutor.")- parser.add_argument(- "--requests-dir",- default=None,- help="Request dataset directory (requests_YYYYMMDD_HHMMSS). Default: latest.",- )- parser.add_argument(- "--benchmark-dir",- default=None,- help="Benchmark entries directory for profile context (benchmark_...). Default: latest.",- )- parser.add_argument(- "--system",- choices=["baseline", "deeptutor", "both"],- default="both",- help="Which system to evaluate (default: both).",- )- parser.add_argument(- "--deeptutor-language",- default="en",- help="Language used by DeepTutor tools (default: en).",- )- parser.add_argument("--limit", type=int, default=0, help="Only evaluate first N records.")- parser.add_argument(- "--max-concurrency",- type=int,- default=2,- help="Max concurrent records to evaluate (default: 2).",- )- parser.add_argument(- "--output",- default=None,- help="Output JSON file path (default: benchmark/data/evaluations/request_eval_<timestamp>.json).",- )- args = parser.parse_args()-- logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )-- if args.requests_dir:- requests_dir = Path(args.requests_dir)- if not requests_dir.is_absolute():- requests_dir = (PROJECT_ROOT / requests_dir).resolve()- else:- requests_dir = _discover_latest_dir("requests", DEFAULT_GENERATED_DIR)-- if args.benchmark_dir:- benchmark_dir = Path(args.benchmark_dir)- if not benchmark_dir.is_absolute():- benchmark_dir = (PROJECT_ROOT / benchmark_dir).resolve()- else:- benchmark_dir = _discover_latest_dir("benchmark", DEFAULT_GENERATED_DIR)-- records = _load_request_records(requests_dir, args.limit)- profile_context_map = _load_profile_context_map(benchmark_dir)- systems = ["baseline", "deeptutor"] if args.system == "both" else [args.system]-- logger.info("Requests dir: %s", requests_dir)- logger.info("Benchmark dir: %s", benchmark_dir)- logger.info("Records: %d | Systems: %s", len(records), systems)-- sem = asyncio.Semaphore(max(1, args.max_concurrency))-- async def _run_with_sem(i: int, rec: dict[str, Any]) -> dict[str, Any]:- async with sem:- t_rec = time.perf_counter()- return await _eval_one_record(- record=rec,- systems=systems,- profile_context_map=profile_context_map,- deeptutor_language=args.deeptutor_language,- record_index=i + 1,- total_records=len(records),- )-- results = await asyncio.gather(*[_run_with_sem(i, r) for i, r in enumerate(records)])- summary = _build_summary(results, systems)-- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- if args.output:- out_path = Path(args.output)- if not out_path.is_absolute():- out_path = (PROJECT_ROOT / out_path).resolve()- else:- DEFAULT_EVAL_DIR.mkdir(parents=True, exist_ok=True)- out_path = DEFAULT_EVAL_DIR / f"request_eval_{timestamp}.json"- out_path.parent.mkdir(parents=True, exist_ok=True)-- payload = {- "timestamp": timestamp,- "requests_dir": str(requests_dir),- "benchmark_dir": str(benchmark_dir),- "systems": systems,- "num_records": len(results),- "summary": summary,- "results": results,- }- with open(out_path, "w", encoding="utf-8") as f:- json.dump(payload, f, ensure_ascii=False, indent=2)-- print("\nDone.")- print(f"Output: {out_path}")- for system in systems:- s = summary.get(system, {})- print(- f"[{system}] solve_avg={s.get('solve_overall_avg')} | "- f"question_avg={s.get('question_overall_avg')} | "- f"combined_avg={s.get('combined_overall_avg')} | "- f"failures={s.get('num_failures')}"- )---def main() -> None:- asyncio.run(async_main())---if __name__ == "__main__":- main()-diff --git a/benchmark/evaluation/run.py b/benchmark/evaluation/run.pydeleted file mode 100644index 03aa279f6..000000000--- a/benchmark/evaluation/run.py+++ /dev/null@@ -1,189 +0,0 @@-#!/usr/bin/env python-"""-CLI for benchmark evaluation.--Current evaluator uses 3 independent metrics:-1) gap_tracking (LLM, per turn)-2) source_faithfulness (LLM, per turn, 1-5)-3) turn_count (non-LLM)-"""--import argparse-import asyncio-import json-import logging-from datetime import datetime-from pathlib import Path--from benchmark.evaluation.evaluator import evaluate_transcript--logger = logging.getLogger("benchmark.evaluation")--PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent-DEFAULT_EVAL_DIR = PROJECT_ROOT / "benchmark" / "data" / "evaluations"---def _setup_logging(verbose: bool) -> None:- level = logging.DEBUG if verbose else logging.INFO- logging.basicConfig(- level=level,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )---async def _run_single(transcript_path: Path, skip_turns: bool, temperature: float) -> dict:- """Evaluate a single transcript."""- return await evaluate_transcript(- transcript_path=transcript_path,- skip_turns=skip_turns,- temperature=temperature,- )---async def main() -> None:- parser = argparse.ArgumentParser(- description="Evaluate tutor transcripts from benchmark conversations"- )- parser.add_argument(- "--transcript",- help="Path to a single transcript JSON file",- )- parser.add_argument(- "--transcript-dir",- help="Path to directory of transcript JSON files (evaluates all)",- )- parser.add_argument(- "--dialog-only",- action="store_true",- help="Skip per-turn LLM metrics (gap_tracking/source_faithfulness), keep turn_count only",- )- parser.add_argument(- "--output",- "-o",- help="Output path for results JSON (default: benchmark/data/evaluations/<stem>_eval_<timestamp>.json)",- )- parser.add_argument(- "--temperature",- type=float,- default=0.2,- help="LLM temperature for evaluation (default: 0.2)",- )- parser.add_argument(- "--verbose",- "-v",- action="store_true",- help="Enable debug logging",- )-- args = parser.parse_args()-- _setup_logging(args.verbose)-- if args.transcript and args.transcript_dir:- parser.error("Use either --transcript or --transcript-dir, not both")- if not args.transcript and not args.transcript_dir:- parser.error("Provide --transcript or --transcript-dir")-- paths: list[Path] = []- if args.transcript:- p = Path(args.transcript)- if not p.exists():- # Try relative to project root (handles /benchmark/... typo)- alt = PROJECT_ROOT / args.transcript.lstrip("/")- if alt.exists():- p = alt- else:- parser.error(f"Transcript not found: {p}")- paths = [p]- else:- d = Path(args.transcript_dir)- if not d.is_dir():- alt = PROJECT_ROOT / args.transcript_dir.lstrip("/")- if alt.is_dir():- d = alt- else:- parser.error(f"Directory not found: {d}")- paths = sorted(d.glob("*.json"))-- if not paths:- parser.error("No transcript files found")-- results = []- for path in paths:- logger.info("Evaluating %s", path)- try:- result = await _run_single(- transcript_path=path,- skip_turns=args.dialog_only,- temperature=args.temperature,- )- results.append(result)-- # Print summary- print(f"\n--- {path.name} ---")- if "error" in result:- print(f"Error: {result['error']}")- elif "sessions" in result:- print(f"Profile: {result.get('profile_id', '?')} ({result.get('num_sessions', 0)} sessions)")- for i, s in enumerate(result.get("sessions", []), 1):- metrics = s.get("metrics", {})- gap = metrics.get("gap_tracking", {})- faith = metrics.get("source_faithfulness", {})- turns = metrics.get("turn_count", {})- print(- f" Session {i} ({s.get('entry_id', '?')}): "- f"paired_turns={turns.get('paired_turns', 0)}, "- f"resolved={gap.get('resolved_gaps_final_count', 0)}/{gap.get('total_gaps', 0)}, "- f"faith_avg={faith.get('avg_score', 'N/A')}"- )- agg = result.get("aggregate", {})- agg_turn = agg.get("turn_count", {})- agg_faith = agg.get("source_faithfulness", {})- print(f"Total paired turns: {agg_turn.get('paired_turns_total', 0)}")- print(f"Faithfulness overall avg: {agg_faith.get('avg_score_overall', 'N/A')}")- else:- print(f"Entry: {result.get('entry_id', '?')}")- metrics = result.get("metrics", {})- gap = metrics.get("gap_tracking", {})- faith = metrics.get("source_faithfulness", {})- turns = metrics.get("turn_count", {})- print(f"Paired turns: {turns.get('paired_turns', 0)}")- print(- "Gap resolution: "- f"{gap.get('resolved_gaps_final_count', 0)}/{gap.get('total_gaps', 0)} "- f"(mentioned={len(gap.get('mentioned_gap_ids_final', []))})"- )- print(- "Source faithfulness (1-5): "- f"avg={faith.get('avg_score', 'N/A')}, "- f"min={faith.get('min_score', 'N/A')}, "- f"max={faith.get('max_score', 'N/A')}, "- f"scored_turns={faith.get('num_scored_turns', 0)}"- )- except Exception as e:- logger.exception("Failed to evaluate %s", path)- results.append({"transcript_path": str(path), "error": str(e)})-- # Single file: result is the first (and only) item- output_data = results[0] if len(results) == 1 else {"evaluations": results}-- # Always save to file; default path when --output not specified- if args.output:- out_path = Path(args.output)- else:- DEFAULT_EVAL_DIR.mkdir(parents=True, exist_ok=True)- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- if len(paths) == 1:- stem = paths[0].stem- out_path = DEFAULT_EVAL_DIR / f"{stem}_eval_{timestamp}.json"- else:- out_path = DEFAULT_EVAL_DIR / f"eval_{timestamp}.json"-- out_path.parent.mkdir(parents=True, exist_ok=True)- with open(out_path, "w", encoding="utf-8") as f:- json.dump(output_data, f, ensure_ascii=False, indent=2)- print(f"\nResults saved → {out_path}")---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/iso_solve/README.md b/benchmark/iso_solve/README.mddeleted file mode 100644index 2ff48328d..000000000--- a/benchmark/iso_solve/README.md+++ /dev/null@@ -1,199 +0,0 @@-# iso_solve--`iso_solve` 用于隔离评估 DeepTutor 解题能力,支持同一套评估主流程在多个 benchmark 上复用:--- `direct`:直接调用 LLM 解题-- `pipeline`:调用 DeepTutor 的 Plan -> ReAct -> Write 解题链路--评估逻辑统一为两步:--1. 基于题目 + 模型输出(`output.md` / `final_answer.md` 内容)使用 LLM 抽取最终答案-2. 基于抽取答案 + GT 使用 LLM 判分(正确/错误)-------## 目录结构--```text-benchmark/iso_solve/-├── run_benchmark.py # 统一 CLI 入口-├── config.yaml # 统一配置-├── core/ # 通用评估框架-│ ├── types.py-│ ├── extractor.py-│ ├── judge.py-│ ├── pipeline.py-│ └── runner.py-├── eval/ # benchmark 适配层-│ ├── base.py-│ ├── math.py-│ ├── gpqa.py-│ ├── aime25.py-│ ├── gaia.py-│ ├── hle.py-│ ├── livebench.py-│ └── scorers/-└── results/ # 所有评估产物-```-------## 核心设计--- `core/runner.py`- - 统一并发调度、结果落盘、report 汇总- - 与 benchmark 无关-- `eval/*.py`- - 只负责数据加载、过滤、prompt/metadata 差异- - 每个 benchmark 通过 adapter 接入-- `core/extractor.py` + `core/judge.py`- - 统一的 LLM 抽取与 LLM 判分能力- - 全局配置由 `config.yaml` 的 `evaluation` 控制-------## 配置说明--全局评估开关(单一真值来源):--```yaml-evaluation:- llm_extract: true- llm_judge: true- extract_model: null- extract_max_tokens: 256- judge_model: null- judge_max_tokens: 128-```--说明:--- `extract_model` / `judge_model` 为 `null` 时使用默认 LLM 配置-- `extract_max_tokens` / `judge_max_tokens` 控制抽取和判分模型的输出长度-- benchmark 子配置不再单独控制 extract/judge 的模型和开关-------## 运行方式--从项目根目录执行:--### MATH(config 默认 500 题,Level 3-5)--```bash-# direct 少量-python -m benchmark.iso_solve.run_benchmark --benchmark math --mode direct --config benchmark/iso_solve/config.yaml --limit 5-# direct 全量-python -m benchmark.iso_solve.run_benchmark --benchmark math --mode direct --config benchmark/iso_solve/config.yaml-# pipeline 少量-python -m benchmark.iso_solve.run_benchmark --benchmark math --mode pipeline --config benchmark/iso_solve/config.yaml --limit 5-# pipeline 全量-python -m benchmark.iso_solve.run_benchmark --benchmark math --mode pipeline --config benchmark/iso_solve/config.yaml-```--### GPQA-Diamond(共 198 题)--```bash-# direct 少量-python -m benchmark.iso_solve.run_benchmark --benchmark gpqa --mode direct --config benchmark/iso_solve/config.yaml --limit 5-# direct 全量-python -m benchmark.iso_solve.run_benchmark --benchmark gpqa --mode direct --config benchmark/iso_solve/config.yaml-# pipeline 少量-python -m benchmark.iso_solve.run_benchmark --benchmark gpqa --mode pipeline --config benchmark/iso_solve/config.yaml --limit 5-# pipeline 全量-python -m benchmark.iso_solve.run_benchmark --benchmark gpqa --mode pipeline --config benchmark/iso_solve/config.yaml-```--### AIME 2025(共 30 题,Part I + II)--```bash-# direct 少量-python -m benchmark.iso_solve.run_benchmark --benchmark aime25 --mode direct --config benchmark/iso_solve/config.yaml --limit 5-# direct 全量-python -m benchmark.iso_solve.run_benchmark --benchmark aime25 --mode direct --config benchmark/iso_solve/config.yaml-# pipeline 少量-python -m benchmark.iso_solve.run_benchmark --benchmark aime25 --mode pipeline --config benchmark/iso_solve/config.yaml --limit 5-# pipeline 全量-python -m benchmark.iso_solve.run_benchmark --benchmark aime25 --mode pipeline --config benchmark/iso_solve/config.yaml-```--### HLE(config 默认 100 题)--```bash-# direct 少量-python -m benchmark.iso_solve.run_benchmark --benchmark hle --mode direct --config benchmark/iso_solve/config.yaml --limit 5-# direct 全量-python -m benchmark.iso_solve.run_benchmark --benchmark hle --mode direct --config benchmark/iso_solve/config.yaml-# pipeline 少量-python -m benchmark.iso_solve.run_benchmark --benchmark hle --mode pipeline --config benchmark/iso_solve/config.yaml --limit 5-# pipeline 全量-python -m benchmark.iso_solve.run_benchmark --benchmark hle --mode pipeline --config benchmark/iso_solve/config.yaml-```--### GAIA(config 默认 10 题,需 `huggingface-cli login`)--```bash-# direct 少量-python -m benchmark.iso_solve.run_benchmark --benchmark gaia --mode direct --config benchmark/iso_solve/config.yaml --limit 3-# direct 全量-python -m benchmark.iso_solve.run_benchmark --benchmark gaia --mode direct --config benchmark/iso_solve/config.yaml-# pipeline 少量-python -m benchmark.iso_solve.run_benchmark --benchmark gaia --mode pipeline --config benchmark/iso_solve/config.yaml --limit 3-# pipeline 全量-python -m benchmark.iso_solve.run_benchmark --benchmark gaia --mode pipeline --config benchmark/iso_solve/config.yaml-```--### LiveBench(共 ~1436 题)--```bash-# direct 少量-python -m benchmark.iso_solve.run_benchmark --benchmark livebench --mode direct --config benchmark/iso_solve/config.yaml --limit 20-# direct 全量-python -m benchmark.iso_solve.run_benchmark --benchmark livebench --mode direct --config benchmark/iso_solve/config.yaml-# pipeline 少量-python -m benchmark.iso_solve.run_benchmark --benchmark livebench --mode pipeline --config benchmark/iso_solve/config.yaml --limit 20-# pipeline 全量-python -m benchmark.iso_solve.run_benchmark --benchmark livebench --mode pipeline --config benchmark/iso_solve/config.yaml-```--### 常见参数--| 参数 | 说明 |-|------|------|-| `--benchmark` | `math \| gpqa \| aime25 \| hle \| gaia \| livebench` |-| `--mode` | `direct \| pipeline` |-| `--limit N` | 限制样本数(覆盖 config.yaml 中的 `filter.limit`) |-| `--seed N` | 采样随机种子 |-| `--output DIR` | 自定义结果根目录(默认 `benchmark/iso_solve/results`) |-| `--dry-run` | 仅验证数据加载与过滤,不触发 LLM 调用 |-| `-v` | 开启 DEBUG 日志 |-------## 结果目录规范--每次实验按 benchmark / mode / run 分层:--```text-results/{benchmark}/{mode}/{model}_{YYYYMMDD_HHMMSS}/-├── report.json-├── summary.txt-└── outputs/- ├── 0000/- │ ├── output.md- │ ├── meta.json- │ ├── scratchpad.json # pipeline 模式由 solver 生成- │ ├── cost_report.json # pipeline 模式由 solver 生成- │ ├── task.log # pipeline 模式由 solver 生成- │ └── code_runs/ # pipeline+code_execute 产生- │ └── exec_*/...- └── 0001/-```-------## 关于 code_execute 产物落盘--`pipeline` 模式下如果调用 `code_execute`,其执行目录会写入当前题目的 solve 输出目录下(`code_runs/exec_*`),而不是全局 `run_code_workspace`。--这使得单次实验目录具备完整可复现性:题目输出、推理轨迹、开销和代码执行产物全部在同一条目录树内。diff --git a/benchmark/iso_solve/__init__.py b/benchmark/iso_solve/__init__.pydeleted file mode 100644index 9107da100..000000000--- a/benchmark/iso_solve/__init__.py+++ /dev/null@@ -1,11 +0,0 @@-from .core import BenchmarkReport, BenchmarkRunner, EvalResult, Problem-from .eval import ADAPTER_REGISTRY, BenchmarkAdapter--__all__ = [- "ADAPTER_REGISTRY",- "BenchmarkAdapter",- "BenchmarkReport",- "BenchmarkRunner",- "EvalResult",- "Problem",-]diff --git a/benchmark/iso_solve/check_folder_names.py b/benchmark/iso_solve/check_folder_names.pydeleted file mode 100644index 504053fb2..000000000--- a/benchmark/iso_solve/check_folder_names.py+++ /dev/null@@ -1,101 +0,0 @@-#!/usr/bin/env python3-"""-Audit pipeline result folders: compare folder-name model vs actual model in cost_reports.-"""--import json-import os-import re-import sys-from collections import defaultdict-from pathlib import Path--RESULTS_ROOT = Path(__file__).parent / "results"---def extract_model_from_folder(folder_name: str) -> str | None:- """Extract model identifier from folder name like 'openai_gpt-5.2_nitro_20260224_014320'."""- m = re.match(r"^(.+?)_(\d{8}_\d{6})(-.*)?$", folder_name)- if m:- return m.group(1)- return folder_name---def collect_models_from_cost_reports(folder: Path) -> set[str]:- """Walk all cost_report.json under a run folder, return the set of models actually used."""- models = set()- for root, _, files in os.walk(folder):- if "cost_report.json" in files:- try:- with open(os.path.join(root, "cost_report.json")) as f:- data = json.load(f)- by_model = data.get("summary", {}).get("by_model", {})- for model_key in by_model:- models.add(model_key)- except (json.JSONDecodeError, KeyError):- pass- return models---def normalize_model(name: str) -> str:- """Normalize model name for comparison: strip provider prefix, colon suffix, replace / and : with _."""- return name.replace("/", "_").replace(":", "_")---def main():- mismatches = []- ok_count = 0- skip_count = 0-- for benchmark_dir in sorted(RESULTS_ROOT.iterdir()):- if not benchmark_dir.is_dir():- continue- pipeline_dir = benchmark_dir / "pipeline"- if not pipeline_dir.is_dir():- continue- for run_dir in sorted(pipeline_dir.iterdir()):- if not run_dir.is_dir():- continue-- folder_model = extract_model_from_folder(run_dir.name)- actual_models = collect_models_from_cost_reports(run_dir)-- if not actual_models:- skip_count += 1- continue-- folder_model_norm = normalize_model(folder_model) if folder_model else ""- actual_norms = {normalize_model(m) for m in actual_models}-- if folder_model_norm in actual_norms or (len(actual_norms) == 1 and folder_model_norm == actual_norms.pop()):- ok_count += 1- else:- mismatches.append({- "path": str(run_dir.relative_to(RESULTS_ROOT)),- "folder_model": folder_model,- "actual_models": sorted(actual_models),- })-- print("=" * 80)- print("Pipeline Folder Name Audit")- print("=" * 80)- print(f" OK (folder matches cost_report): {ok_count}")- print(f" Skipped (no cost_report found): {skip_count}")- print(f" MISMATCH: {len(mismatches)}")- print("=" * 80)-- if mismatches:- print("\nMISMATCHED FOLDERS:\n")- for i, m in enumerate(mismatches, 1):- print(f" [{i}] {m['path']}")- print(f" Folder says: {m['folder_model']}")- print(f" Actually used: {', '.join(m['actual_models'])}")- print()- else:- print("\nAll pipeline folders match their cost reports!")-- return 1 if mismatches else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/benchmark/iso_solve/config.yaml b/benchmark/iso_solve/config.yamldeleted file mode 100644index 582f0a7c8..000000000--- a/benchmark/iso_solve/config.yaml+++ /dev/null@@ -1,400 +0,0 @@-# --- Global evaluation defaults (single source of truth) ----evaluation:- llm_extract: true- llm_judge: true- extract_model: anthropic/claude-sonnet-4.6:nitro- extract_temperature: 0.0- extract_max_tokens: 16384- judge_model: anthropic/claude-sonnet-4.6:nitro- judge_temperature: 0.0- judge_max_tokens: 16384--# ======================================================================-# MATH Benchmark Configuration-# ======================================================================-# python -m benchmark.iso_solve.run_benchmark --mode pipeline \-# --config benchmark/iso_solve/config.yaml --limit 5--# python -m benchmark.iso_solve.run_benchmark --mode direct \-# --config benchmark/iso_solve/config.yaml --limit 5--# --- Dataset ----# First run downloads from HuggingFace and caches locally.-# Override with --dataroot to use a local file.-dataset:- parquet_url: "hf://datasets/qwedsacf/competition_math/data/train-00000-of-00001-7320a6f3aba8ebd2.parquet"--# --- Filtering ----filter:- # subjects: # Uncomment to filter by subject(s):- # - Algebra # Prealgebra, Algebra, Number Theory,- # - Prealgebra # Counting & Probability, Geometry,- # # Intermediate Algebra, Precalculus- levels: # Uncomment to filter by level(s) 1-5:- - 3- - 4- - 5- limit: 500 # Max problems to evaluate (null = all 12498)- seed: 42 # Random seed for sampling--# --- LLM settings (for direct mode) ----llm:- model: null # null = use global LLM config; set to override- temperature: 0.0 # 0.0 = greedy / deterministic- max_tokens: 4096 # Max output tokens per problem--# --- Concurrency (for direct mode) ----concurrency: 10 # Parallel LLM requests--# --- Pipeline mode settings ----pipeline:- model: null # null = use llm.model; set to use a different model for pipeline- max_tokens: null # null = use llm.max_tokens → agents.yaml default- temperature: null # null = use llm.temperature → agents.yaml default- language: en # Prompt language for pipeline agents- tools: # Tools available to the solver agent.- - code_execute # Only code execution; no RAG / web search.- - reason # Deep reasoning without external tools.- # done and replan are always included.- # Set to null or remove to enable all tools.- concurrency: 20 # Parallel pipeline runs (each uses ~10-20 LLM calls,- # keep low to avoid API rate limits)--# --- Output ----output_dir: benchmark/iso_solve/results---# ======================================================================-# HLE (Humanity's Last Exam) Benchmark Configuration-# ======================================================================-# python -m benchmark.iso_solve.run_benchmark --benchmark hle --mode direct \-# --config benchmark/iso_solve/config.yaml --limit 500 --sequential-#-# python -m benchmark.iso_solve.run_benchmark --benchmark hle --mode pipeline \-# --config benchmark/iso_solve/config.yaml --limit 500 --sequential--hle:- # --- Dataset ---- parquet_url: "hf://datasets/cais/hle/data/test-00000-of-00001.parquet"- skip_multimodal: false # true = only evaluate text-only questions-- # --- Filtering ---- filter:- # subjects: [] # Uncomment to filter by subject(s)- limit: null # Max problems to evaluate (null = all ~2500)- seed: 42-- # --- LLM settings (for direct mode) ---- llm:- model: qwen3.5-plus # null = use global LLM config; override for vision model- multimodal: true # true = send images to LLM; false = text-only- temperature: 0.0- max_tokens: 16384 # Official recommendation: >= 8192-- # --- Concurrency (for direct mode) ---- concurrency: 50-- # --- Pipeline mode settings ---- pipeline:- model: qwen3.5-plus # null = use llm.model; set to use a different model for pipeline- max_tokens: 16384 # null = use llm.max_tokens → agents.yaml default- temperature: 0.0 # null = use llm.temperature → agents.yaml default- language: en- tools:- - code_execute- - reason- concurrency: 30---# ======================================================================-# GPQA-Diamond Benchmark Configuration-# ======================================================================-# python -m benchmark.iso_solve.run_benchmark --benchmark gpqa --mode direct \-# --config benchmark/iso_solve/config.yaml --limit 5-#-# python -m benchmark.iso_solve.run_benchmark --benchmark gpqa --mode pipeline \-# --config benchmark/iso_solve/config.yaml --limit 5--gpqa:- # --- Dataset (gated — requires `huggingface-cli login` or HF_TOKEN) ---- dataset_id: "Idavidrein/gpqa"- config_name: "gpqa_diamond" # gpqa_diamond / gpqa_main / gpqa_extended- choice_shuffle_seed: 42 # Seed for shuffling answer choices (A/B/C/D)-- # --- Filtering ---- filter:- # domains: # Uncomment to filter by domain(s):- # - Physics # Physics, Chemistry, Biology- # - Chemistry- limit: null # Max problems to evaluate (null = all 198)- seed: 42 # Random seed for sampling-- # --- LLM settings (for direct mode) ---- llm:- model: # null = use global LLM config; set to override- temperature: 0.0 # 0.0 = greedy / deterministic- max_tokens: 16384 # Max output tokens per problem-- # --- Concurrency (for direct mode) ---- concurrency: 50-- # --- Pipeline mode settings ---- pipeline:- model: # null = use llm.model; set to use a different model for pipeline- max_tokens: 16384 # null = use llm.max_tokens → agents.yaml default- temperature: 0.0 # null = use llm.temperature → agents.yaml default- language: en- tools:- - code_execute- - reason- concurrency: 50--# ======================================================================-# LiveBench Benchmark Configuration-# ======================================================================-# python -m benchmark.iso_solve.run_benchmark --benchmark livebench --mode direct \-# --config benchmark/iso_solve/config.yaml --limit 20-#-# python -m benchmark.iso_solve.run_benchmark --benchmark livebench --mode pipeline \-# --config benchmark/iso_solve/config.yaml --limit 20-#-# Filter by category:-# python -m benchmark.iso_solve.run_benchmark --benchmark livebench --mode direct \-# --config benchmark/iso_solve/config.yaml --livebench-categories math reasoning--livebench:- # --- Categories to evaluate ---- # All 6 categories by default. Uncomment to select specific ones.- categories:- - reasoning # ~200 questions (web_of_lies, zebra_puzzle, spatial, ...)- # - math # ~368 questions (AIME, AMC, AMPS_Hard, olympiad, ...)- # - coding # ~128 questions (LCB_generation, code_generation, ...)- # - data_analysis # ~150 questions (tablereformat, cta, tablejoin, ...)- # - instruction_following # ~400 questions- # - language # ~190 questions (plot_unscrambling, typos, connections)-- # --- Filtering ---- filter:- # tasks: [] # Uncomment to filter by specific task name(s)- limit: null # Max problems to evaluate (null = all ~1436)- seed: 42 # Random seed for sampling-- # --- LLM settings (for direct mode) ---- llm:- model: openai/gpt-5.2:nitro # null = use global LLM config; set to override- temperature: 0.0 # 0.0 = greedy / deterministic- max_tokens: 16384 # Max output tokens per problem-- # --- Concurrency (for direct mode) ---- concurrency: 20-- # --- Pipeline mode settings ---- pipeline:- model: anthropic/claude-sonnet-4.5 # null = use llm.model- max_tokens: 16384 # null = use llm.max_tokens → agents.yaml default- temperature: 0.0 # null = use llm.temperature → agents.yaml default- language: en- tools:- - code_execute- - reason- # - web_search- concurrency: 10--# ======================================================================-# GAIA Benchmark Configuration-# ======================================================================-# python -m benchmark.iso_solve.run_benchmark --benchmark gaia --mode direct \-# --config benchmark/iso_solve/config.yaml --limit 5-#-# python -m benchmark.iso_solve.run_benchmark --benchmark gaia --mode pipeline \-# --config benchmark/iso_solve/config.yaml --limit 5--gaia:- # --- Dataset (gated — requires `huggingface-cli login` or HF_TOKEN) ---- dataset_id: "gaia-benchmark/GAIA"- config_name: "2023_all" # 2023_all / 2023_level1 / 2023_level2 / 2023_level3- split: "validation" # validation (has ground truth) / test (private answers)-- # --- Filtering ---- filter:- # levels: # Uncomment to filter by level(s) 1-3:- # - 1- # - 2- limit: null # Max problems to evaluate (null = all ~165 validation)- seed: 42 # Random seed for sampling-- # --- LLM settings (for direct mode) ---- llm:- model: # null = use global LLM config; set to override- multimodal: true # true = send images to LLM as base64;- # false = text-only (images described as placeholders,- # documents/spreadsheets still injected as text)- temperature: 0.0- max_tokens: 16384-- # --- Concurrency (for direct mode) ---- concurrency: 30-- # --- Pipeline mode settings ---- pipeline:- model: # null = use llm.model; set to use a different model for pipeline- max_tokens: 16384 # null = use llm.max_tokens → agents.yaml default- temperature: 0.0 # null = use llm.temperature → agents.yaml default- language: en- tools: # Tools available to the solver agent.- - code_execute # Code execution.- - web_search- - reason # Web search (GAIA often requires it).- concurrency: 20--# ======================================================================-# AA-LCR (Artificial Analysis Long Context Reasoning) Benchmark-# ======================================================================-# 100 human-crafted questions requiring multi-step reasoning across-# multiple long documents (~100k tokens per question). Text-only.-# https://huggingface.co/datasets/ArtificialAnalysis/AA-LCR-#-# python -m benchmark.iso_solve.run_benchmark --benchmark aalcr --mode direct \-# --config benchmark/iso_solve/config.yaml --limit 5-#-# python -m benchmark.iso_solve.run_benchmark --benchmark aalcr --mode pipeline \-# --config benchmark/iso_solve/config.yaml --limit 5-#-# Filter by category:-# python -m benchmark.iso_solve.run_benchmark --benchmark aalcr --mode direct \-# --config benchmark/iso_solve/config.yaml --aalcr-categories "Company Documents"--aalcr:- # --- Dataset (HuggingFace: ArtificialAnalysis/AA-LCR) ---- dataset_id: "ArtificialAnalysis/AA-LCR"-- # --- Filtering ---- filter:- # categories: # Uncomment to filter by document category:- # - Marketing # Company Documents (63), Industry Reports (8),- # - Legal # Government Consultations (11), Academia (5),- # # Legal (6), Marketing (6), Survey Reports (1)- limit: null # Max problems to evaluate (null = all 100)- seed: 42 # Random seed for sampling-- # --- LLM settings (for direct mode) ---- # NOTE: AA-LCR requires long-context models (~100k+ input tokens per question).- llm:- model: openai/gpt-5-mini:nitro # Must support >=128k context window- temperature: 0.0 # 0.0 = greedy / deterministic- max_tokens: 16384 # Max output tokens per problem-- # --- Concurrency (for direct mode) ---- concurrency: 20 # Keep low due to very large input sizes-- # --- Pipeline mode settings ---- pipeline:- model: openai/gpt-5-mini:nitro # Must support >=128k context window- max_tokens: 16384- temperature: 0.0- language: en- tools:- - code_execute- - reason- concurrency: 25 # Keep low; each call sends ~100k tokens--# ======================================================================-# AIME 2025 Benchmark Configuration-# ======================================================================-# python -m benchmark.iso_solve.run_benchmark --benchmark aime25 --mode direct \-# --config benchmark/iso_solve/config.yaml-#-# python -m benchmark.iso_solve.run_benchmark --benchmark aime25 --mode pipeline \-# --config benchmark/iso_solve/config.yaml-#-# Part I only:-# python -m benchmark.iso_solve.run_benchmark --benchmark aime25 --mode direct \-# --config benchmark/iso_solve/config.yaml --aime-parts 1-#-# Part II only:-# python -m benchmark.iso_solve.run_benchmark --benchmark aime25 --mode direct \-# --config benchmark/iso_solve/config.yaml --aime-parts 2--aime25:- # --- Dataset (HuggingFace: opencompass/AIME2025) ---- # Configs: AIME2025-I (15 problems), AIME2025-II (15 problems)- # All answers are integers in [0, 999].- parts: # Which parts to evaluate:- - 1 # 1 = AIME 2025-I- - 2 # 2 = AIME 2025-II-- # --- Filtering ---- filter:- limit: null # Max problems to evaluate (null = all 30)- seed: 42 # Random seed for sampling-- # --- LLM settings (for direct mode) ---- llm:- model: null # null = use global LLM config; set to override- temperature: 0.0 # 0.0 = greedy / deterministic- max_tokens: 8192 # Max output tokens per problem-- # --- Concurrency (for direct mode) ---- concurrency: 5-- # --- Pipeline mode settings ---- pipeline:- model: null # null = use llm.model- max_tokens: null # null = use llm.max_tokens → agents.yaml default- temperature: null # null = use llm.temperature → agents.yaml default- language: en- tools:- - code_execute- concurrency: 5--# ======================================================================-# SuperGPQA Benchmark Configuration-# ======================================================================-# 26,500 graduate-level multiple-choice questions across 285 disciplines.-# Each question has 4-10 options; difficulty levels: easy, middle, hard.-# https://huggingface.co/datasets/m-a-p/SuperGPQA-#-# python -m benchmark.iso_solve.run_benchmark --benchmark super_gpqa --mode direct \-# --config benchmark/iso_solve/config.yaml --limit 50-#-# python -m benchmark.iso_solve.run_benchmark --benchmark super_gpqa --mode pipeline \-# --config benchmark/iso_solve/config.yaml --limit 50-#-# Filter by difficulty:-# python -m benchmark.iso_solve.run_benchmark --benchmark super_gpqa --mode direct \-# --config benchmark/iso_solve/config.yaml --super-gpqa-difficulties hard--super_gpqa:- # --- Dataset (requires `huggingface-cli login`) ---- dataset_url: "hf://datasets/m-a-p/SuperGPQA/SuperGPQA-all.jsonl"-- # --- Filtering ---- filter:- # disciplines: # Uncomment to filter by discipline(s):- # - Physics # 13 disciplines (e.g. Physics, Chemistry,- # - Computer Science # Biology, Mathematics, Engineering, ...)- # fields: # Uncomment to filter by field(s):- # - Machine Learning # 72 fields- # difficulties: # Uncomment to filter by difficulty:- # - hard # easy, middle, hard- limit: null # Max problems to evaluate (null = all 26500)- seed: 42 # Random seed for sampling-- # --- LLM settings (for direct mode) ---- llm:- model: null # null = use global LLM config; set to override- temperature: 0.0 # 0.0 = greedy / deterministic- max_tokens: 16384 # Max output tokens per problem-- # --- Concurrency (for direct mode) ---- concurrency: 20-- # --- Pipeline mode settings ---- pipeline:- model: null # null = use llm.model- max_tokens: null # null = use llm.max_tokens → agents.yaml default- temperature: null # null = use llm.temperature → agents.yaml default- language: en- tools:- - code_execute- concurrency: 10diff --git a/benchmark/iso_solve/core/__init__.py b/benchmark/iso_solve/core/__init__.pydeleted file mode 100644index 17114732b..000000000--- a/benchmark/iso_solve/core/__init__.py+++ /dev/null@@ -1,16 +0,0 @@-from .extractor import extract_answer-from .judge import judge_answer-from .pipeline import build_tool_registry, run_solver_pipeline-from .runner import BenchmarkRunner-from .types import BenchmarkReport, EvalResult, Problem--__all__ = [- "BenchmarkRunner",- "BenchmarkReport",- "EvalResult",- "Problem",- "build_tool_registry",- "extract_answer",- "judge_answer",- "run_solver_pipeline",-]diff --git a/benchmark/iso_solve/core/extractor.py b/benchmark/iso_solve/core/extractor.pydeleted file mode 100644index 5d44c0ad8..000000000--- a/benchmark/iso_solve/core/extractor.py+++ /dev/null@@ -1,68 +0,0 @@-from __future__ import annotations--import logging--logger = logging.getLogger("iso_solve.extractor")--EXTRACT_SYSTEM = (- "You are a precise answer extractor. "- "Given a problem and a model response, extract only the final answer.\n\n"- "Rules:\n"- "- Output only the answer itself.\n"- "- Do not output explanation or any prefix like 'Answer:'.\n"- "- If no clear final answer exists, output exactly: NONE"-)--EXTRACT_USER = """\-## Problem-{question}--## Model Response-{model_output}--{extract_hint}--Extract the final answer:"""---async def extract_answer(- question: str,- model_output: str,- extract_hint: str = "",- model: str | None = None,- api_key: str | None = None,- base_url: str | None = None,- max_tokens: int = 256,- temperature: float | None = None,-) -> str | None:- from src.services.llm import complete-- prompt = EXTRACT_USER.format(- question=question,- model_output=model_output,- extract_hint=extract_hint or "",- )- kwargs = {- "prompt": prompt,- "system_prompt": EXTRACT_SYSTEM,- "temperature": temperature if temperature is not None else 0.0,- "max_tokens": max_tokens,- }- if model:- kwargs["model"] = model- if api_key:- kwargs["api_key"] = api_key- if base_url:- kwargs["base_url"] = base_url-- try:- response = await complete(**kwargs)- answer = response.strip()- if not answer or answer.upper() == "NONE":- return None- if answer.lower().startswith("answer:"):- answer = answer.split(":", 1)[1].strip()- return answer or None- except Exception as exc:- logger.warning("LLM extraction failed: %s", exc)- return Nonediff --git a/benchmark/iso_solve/core/judge.py b/benchmark/iso_solve/core/judge.pydeleted file mode 100644index a8ca1ef31..000000000--- a/benchmark/iso_solve/core/judge.py+++ /dev/null@@ -1,83 +0,0 @@-from __future__ import annotations--import logging--logger = logging.getLogger("iso_solve.judge")--JUDGE_SYSTEM = (- "You are a rigorous answer grader. "- "Given a problem, a predicted answer, and a ground-truth answer, "- "determine whether they are equivalent.\n\n"- "Ignore superficial formatting differences.\n"- "Output exactly one word: CORRECT or INCORRECT."-)--JUDGE_USER = """\-## Problem-{question}--## Ground-Truth Answer-{ground_truth}--## Predicted Answer-{predicted}--{judge_hint}--Verdict:"""---def _fallback_compare(predicted: str | None, ground_truth: str) -> bool:- if predicted is None:- return False- return predicted.strip().lower() == ground_truth.strip().lower()---async def judge_answer(- question: str,- predicted: str | None,- ground_truth: str,- judge_hint: str = "",- model: str | None = None,- api_key: str | None = None,- base_url: str | None = None,- max_tokens: int = 32,- temperature: float | None = None,-) -> tuple[bool, str]:- if predicted is None:- return False, "No extracted answer"-- from src.services.llm import complete-- prompt = JUDGE_USER.format(- question=question,- predicted=predicted,- ground_truth=ground_truth,- judge_hint=judge_hint or "",- )- kwargs = {- "prompt": prompt,- "system_prompt": JUDGE_SYSTEM,- "temperature": temperature if temperature is not None else 0.0,- "max_tokens": max_tokens,- }- if model:- kwargs["model"] = model- if api_key:- kwargs["api_key"] = api_key- if base_url:- kwargs["base_url"] = base_url-- try:- response = await complete(**kwargs)- verdict = response.strip().upper()- if "CORRECT" in verdict and "INCORRECT" not in verdict:- return True, verdict- if "INCORRECT" in verdict:- return False, verdict- fallback = _fallback_compare(predicted, ground_truth)- return fallback, f"Ambiguous verdict: {verdict}"- except Exception as exc:- logger.warning("LLM judge failed: %s", exc)- fallback = _fallback_compare(predicted, ground_truth)- return fallback, f"Judge failed: {exc}"diff --git a/benchmark/iso_solve/core/pipeline.py b/benchmark/iso_solve/core/pipeline.pydeleted file mode 100644index 44f9b9531..000000000--- a/benchmark/iso_solve/core/pipeline.py+++ /dev/null@@ -1,40 +0,0 @@-from __future__ import annotations--from typing import Any---def build_tool_registry(tools: list[str] | None, language: str):- from src.agents.solve.tools import ToolRegistry-- if tools is None:- return ToolRegistry.create_default(language=language)- return ToolRegistry.create_from_names(tools, language=language)---async def run_solver_pipeline(- question: str,- workspace: str,- language: str = "en",- tools: list[str] | None = None,- model: str | None = None,- image_url: str | None = None,- max_tokens: int | None = None,- temperature: float | None = None,-) -> dict[str, Any]:- from src.agents.solve import MainSolver-- registry = build_tool_registry(tools, language)- has_rag = registry.get("rag_search") is not None-- solver = MainSolver(- kb_name="" if not has_rag else "__benchmark__",- language=language,- output_base_dir=workspace,- tool_registry=registry,- disable_memory=True,- model=model,- max_tokens=max_tokens,- temperature=temperature,- )- await solver.ainit()- return await solver.solve(question, image_url=image_url)diff --git a/benchmark/iso_solve/core/runner.py b/benchmark/iso_solve/core/runner.pydeleted file mode 100644index 74beb0569..000000000--- a/benchmark/iso_solve/core/runner.py+++ /dev/null@@ -1,346 +0,0 @@-from __future__ import annotations--import argparse-import asyncio-from datetime import datetime-import json-import logging-import os-from pathlib import Path-import time-from typing import Any--from .pipeline import run_solver_pipeline-from .types import BenchmarkReport, EvalResult, Problem--logger = logging.getLogger("iso_solve.runner")---class BenchmarkRunner:- def __init__(self, adapter: Any, extractor_fn: Any, judge_fn: Any):- self.adapter = adapter- self.extractor_fn = extractor_fn- self.judge_fn = judge_fn-- def _resolve_bench_cfg(self, cfg: dict[str, Any]) -> dict[str, Any]:- # Backward compatibility: old MATH config lived at root level.- if self.adapter.name == "math" and self.adapter.name not in cfg:- return cfg- return cfg.get(self.adapter.name, {})-- def _resolve_llm_runtime(self, bench_cfg: dict[str, Any]) -> dict[str, Any]:- model_name = bench_cfg.get("llm", {}).get("model")- api_key = None- base_url = None- try:- from src.services.llm.config import get_llm_config-- llm_cfg = get_llm_config()- model_name = model_name or llm_cfg.model or "unknown"- api_key = llm_cfg.api_key- base_url = llm_cfg.base_url- except Exception:- model_name = model_name or os.getenv("LLM_MODEL", "unknown")- return {- "model_name": model_name or "unknown",- "api_key": api_key,- "base_url": base_url,- }-- def _create_output_dir(- self,- global_cfg: dict[str, Any],- mode: str,- model_name: str,- timestamp: str,- args_output: str | None,- ) -> Path:- base = args_output or global_cfg.get("output_dir", "benchmark/iso_solve/results")- model_short = model_name.replace("/", "_").replace(":", "_")- path = Path(base) / self.adapter.name / mode / f"{model_short}_{timestamp}"- path.mkdir(parents=True, exist_ok=True)- return path-- async def _direct_call(- self,- problem: Problem,- bench_cfg: dict[str, Any],- model: str | None,- api_key: str | None,- base_url: str | None,- ) -> str:- from src.services.llm import complete-- llm_cfg = bench_cfg.get("llm", {})- temperature = llm_cfg.get("temperature", 0.0)- max_tokens = llm_cfg.get("max_tokens", 4096)- multimodal = llm_cfg.get("multimodal", True)-- req = self.adapter.build_direct_request(problem, multimodal=multimodal)- kwargs: dict[str, Any] = {- "temperature": temperature,- "max_tokens": max_tokens,- }- if "messages" in req:- kwargs["prompt"] = ""- kwargs["messages"] = req["messages"]- else:- kwargs["prompt"] = req.get("prompt", problem.question)- kwargs["system_prompt"] = req.get("system_prompt", problem.system_prompt)- if model:- kwargs["model"] = model- if api_key:- kwargs["api_key"] = api_key- if base_url:- kwargs["base_url"] = base_url- return await complete(**kwargs)-- async def _pipeline_call(- self,- problem: Problem,- bench_cfg: dict[str, Any],- problem_workspace: str,- model: str | None,- ) -> str:- pipeline_cfg = bench_cfg.get("pipeline", {})- tools = pipeline_cfg.get("tools")- language = pipeline_cfg.get("language", "en")- pipeline_model = pipeline_cfg.get("model") or model- multimodal = bench_cfg.get("llm", {}).get("multimodal", True)-- llm_cfg = bench_cfg.get("llm", {})- max_tokens = pipeline_cfg.get("max_tokens") or llm_cfg.get("max_tokens")- temperature = pipeline_cfg.get("temperature")- if temperature is None:- temperature = llm_cfg.get("temperature")-- req = self.adapter.build_pipeline_request(problem, multimodal=multimodal)- result = await run_solver_pipeline(- question=req.get("prompt", problem.question),- workspace=problem_workspace,- language=language,- tools=tools,- model=pipeline_model,- image_url=req.get("image_url"),- max_tokens=max_tokens,- temperature=temperature,- )- return result.get("final_answer", "")-- def _save_result(- self,- out_dir: Path,- idx: int,- result: EvalResult,- ) -> None:- prob_dir = out_dir / "outputs" / f"{idx:04d}"- prob_dir.mkdir(parents=True, exist_ok=True)-- with open(prob_dir / "output.md", "w", encoding="utf-8") as f:- f.write(result.model_output)-- meta = {- "id": result.problem.id,- "benchmark": result.problem.benchmark,- "question": result.problem.question,- "ground_truth": result.problem.ground_truth,- "metadata": result.problem.metadata,- "extracted_answer": result.extracted_answer,- "correct": result.correct,- "score": result.score,- "confidence": result.confidence,- "judge_reasoning": result.judge_reasoning,- "elapsed_sec": round(result.elapsed_sec, 3),- "error": result.error,- }- with open(prob_dir / "meta.json", "w", encoding="utf-8") as f:- json.dump(meta, f, ensure_ascii=False, indent=2)-- async def run(- self,- args: argparse.Namespace,- cfg: dict[str, Any],- ) -> BenchmarkReport:- bench_cfg = self._resolve_bench_cfg(cfg)- problems = self.adapter.load_dataset(bench_cfg, args)- problems = self.adapter.filter_problems(problems, bench_cfg, args)-- if not problems:- raise ValueError(f"No {self.adapter.name} problems after filtering.")-- runtime = self._resolve_llm_runtime(bench_cfg)- model_name = runtime["model_name"]- api_key = runtime["api_key"]- base_url = runtime["base_url"]-- if args.mode == "pipeline":- pipeline_model = bench_cfg.get("pipeline", {}).get("model")- if pipeline_model:- model_name = pipeline_model-- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- out_dir = self._create_output_dir(cfg, args.mode, model_name, timestamp, args.output)-- report = BenchmarkReport(- benchmark=self.adapter.name,- mode=args.mode,- model=model_name,- timestamp=timestamp,- )-- if args.dry_run:- logger.info("=== %s DRY RUN ===", self.adapter.name.upper())- for i, p in enumerate(problems[: min(10, len(problems))]):- logger.info("[%d] %s", i + 1, self.adapter.preview(p))- return report-- eval_cfg = cfg.get("evaluation", {})- llm_extract = eval_cfg.get("llm_extract", True)- llm_judge = eval_cfg.get("llm_judge", True)- extract_model = eval_cfg.get("extract_model")- extract_temperature = eval_cfg.get("extract_temperature")- extract_max_tokens = eval_cfg.get("extract_max_tokens", 256)- judge_model = eval_cfg.get("judge_model")- judge_temperature = eval_cfg.get("judge_temperature")- judge_max_tokens = eval_cfg.get("judge_max_tokens", 128)-- concurrency = (- bench_cfg.get("pipeline", {}).get("concurrency", 1)- if args.mode == "pipeline"- else bench_cfg.get("concurrency", 1)- )- sem = asyncio.Semaphore(concurrency)- total = len(problems)-- logger.info(- "=== %s | mode=%s | model=%s | %d problems | concurrency=%d ===",- self.adapter.name.upper(),- args.mode,- model_name,- total,- concurrency,- )-- start = time.time()- completed_count = 0- correct_count = 0- error_count = 0- _progress_lock = asyncio.Lock()-- async def _run_one(i: int, prob: Problem) -> EvalResult:- nonlocal completed_count, correct_count, error_count- async with sem:- t0 = time.time()- try:- workspace = str(out_dir / "outputs" / f"{i:04d}")- if args.mode == "direct":- model_output = await self._direct_call(- prob,- bench_cfg=bench_cfg,- model=bench_cfg.get("llm", {}).get("model"),- api_key=api_key,- base_url=base_url,- )- elif args.mode == "pipeline":- model_output = await self._pipeline_call(- prob,- bench_cfg=bench_cfg,- problem_workspace=workspace,- model=bench_cfg.get("llm", {}).get("model"),- )- else:- raise ValueError(f"Unknown mode: {args.mode}")-- if self.adapter.skip_extract:- extracted = model_output- else:- extracted = None- if llm_extract:- extracted = await self.extractor_fn(- question=prob.question,- model_output=model_output,- extract_hint=self.adapter.extract_hint,- model=extract_model,- api_key=api_key,- base_url=base_url,- max_tokens=extract_max_tokens,- temperature=extract_temperature,- )- if extracted is None:- extracted = self.adapter.extract_fallback(model_output)-- if llm_judge:- correct, reasoning = await self.judge_fn(- question=prob.question,- predicted=extracted,- ground_truth=prob.ground_truth,- judge_hint=self.adapter.judge_hint,- model=judge_model,- api_key=api_key,- base_url=base_url,- max_tokens=judge_max_tokens,- temperature=judge_temperature,- )- else:- correct, reasoning = self.adapter.judge_fallback(prob, extracted)-- result = EvalResult(- problem=prob,- model_output=model_output,- extracted_answer=extracted,- correct=correct,- score=1.0 if correct else 0.0,- elapsed_sec=time.time() - t0,- judge_reasoning=reasoning,- )- except Exception as exc:- result = EvalResult(- problem=prob,- model_output="",- extracted_answer=None,- correct=False,- score=0.0,- elapsed_sec=time.time() - t0,- judge_reasoning="",- error=str(exc),- )-- async with _progress_lock:- completed_count += 1- if result.error:- error_count += 1- elif result.correct:- correct_count += 1- elapsed = time.time() - start- acc = correct_count / completed_count * 100 if completed_count else 0- status = "ERR" if result.error else ("OK" if result.correct else "WRONG")- logger.info(- "[%d/%d] #%04d %s | acc=%.1f%% | err=%d | %.1fs | elapsed %.0fs",- completed_count,- total,- i,- status,- acc,- error_count,- result.elapsed_sec,- elapsed,- )-- return result-- results = await asyncio.gather(*[_run_one(i, p) for i, p in enumerate(problems)])- for i, r in enumerate(results):- report.add(r, self.adapter.breakdown_keys)- self._save_result(out_dir, i, r)-- report.elapsed_sec = time.time() - start-- report_path = out_dir / "report.json"- with open(report_path, "w", encoding="utf-8") as f:- json.dump(report.to_dict(), f, ensure_ascii=False, indent=2)-- summary_path = out_dir / "summary.txt"- with open(summary_path, "w", encoding="utf-8") as f:- f.write("\n".join(report.summary_lines()))-- return reportdiff --git a/benchmark/iso_solve/core/types.py b/benchmark/iso_solve/core/types.pydeleted file mode 100644index 26fdfa12b..000000000--- a/benchmark/iso_solve/core/types.py+++ /dev/null@@ -1,144 +0,0 @@-from __future__ import annotations--from dataclasses import dataclass, field-import math-from typing import Any---@dataclass-class Problem:- id: str- question: str- ground_truth: str- benchmark: str- system_prompt: str = ""- metadata: dict[str, Any] = field(default_factory=dict)---@dataclass-class EvalResult:- problem: Problem- model_output: str- extracted_answer: str | None- correct: bool- elapsed_sec: float- score: float = 1.0- confidence: int = 100- judge_reasoning: str = ""- error: str | None = None---@dataclass-class BenchmarkReport:- benchmark: str- mode: str- model: str- timestamp: str- total: int = 0- correct: int = 0- errors: int = 0- elapsed_sec: float = 0.0- results: list[EvalResult] = field(default_factory=list)- breakdowns: dict[str, dict[str, dict[str, int]]] = field(default_factory=dict)-- @property- def accuracy(self) -> float:- return self.correct / self.total if self.total > 0 else 0.0-- @property- def accuracy_pct(self) -> float:- return round(100.0 * self.accuracy, 2)-- @property- def confidence_interval(self) -> float:- if self.total == 0:- return 0.0- acc = self.accuracy_pct- return round(1.96 * math.sqrt(acc * (100 - acc) / self.total), 2)-- def add(self, r: EvalResult, breakdown_keys: list[str]) -> None:- self.results.append(r)- self.total += 1-- if r.error:- self.errors += 1- return-- if r.correct:- self.correct += 1-- for key in breakdown_keys:- if key not in r.problem.metadata:- continue- bucket_name = f"by_{key}"- bucket_value = str(r.problem.metadata.get(key))- bucket = self.breakdowns.setdefault(bucket_name, {})- stats = bucket.setdefault(bucket_value, {"total": 0, "correct": 0})- stats["total"] += 1- if r.correct:- stats["correct"] += 1-- def summary_lines(self) -> list[str]:- lines = [- "=" * 70,- f"{self.benchmark.upper()} Benchmark Report — {self.mode} mode",- f"Model: {self.model}",- f"Time: {self.timestamp}",- "=" * 70,- f"Overall: {self.correct}/{self.total} = {self.accuracy_pct}% "- f"+/- {self.confidence_interval}% (errors={self.errors})",- f"Wall time: {self.elapsed_sec:.1f}s",- ]- for bucket_name in sorted(self.breakdowns):- lines.append("")- lines.append(f"--- {bucket_name} ---")- for k in sorted(self.breakdowns[bucket_name]):- s = self.breakdowns[bucket_name][k]- acc = s["correct"] / s["total"] if s["total"] else 0.0- lines.append(f" {k:30s} {s['correct']:4d}/{s['total']:4d} = {acc:.3f}")- lines.append("=" * 70)- return lines-- def to_dict(self) -> dict[str, Any]:- breakdowns: dict[str, dict[str, Any]] = {}- for bucket_name, bucket in self.breakdowns.items():- breakdowns[bucket_name] = {}- for k, s in bucket.items():- acc = s["correct"] / s["total"] if s["total"] else 0.0- breakdowns[bucket_name][k] = {- **s,- "accuracy": round(acc, 4),- }-- return {- "benchmark": self.benchmark,- "mode": self.mode,- "model": self.model,- "timestamp": self.timestamp,- "overall": {- "total": self.total,- "correct": self.correct,- "accuracy": round(self.accuracy, 4),- "accuracy_pct": self.accuracy_pct,- "confidence_interval": self.confidence_interval,- "errors": self.errors,- "elapsed_sec": round(self.elapsed_sec, 2),- },- "breakdowns": breakdowns,- "results": [- {- "id": r.problem.id,- "question": r.problem.question[:300],- "ground_truth": r.problem.ground_truth,- "extracted_answer": r.extracted_answer,- "correct": r.correct,- "score": r.score,- "confidence": r.confidence,- "judge_reasoning": r.judge_reasoning[:400],- "elapsed_sec": round(r.elapsed_sec, 3),- "error": r.error,- "metadata": r.problem.metadata,- }- for r in self.results- ],- }diff --git a/benchmark/iso_solve/eval/__init__.py b/benchmark/iso_solve/eval/__init__.pydeleted file mode 100644index 899b1381a..000000000--- a/benchmark/iso_solve/eval/__init__.py+++ /dev/null@@ -1,33 +0,0 @@-from .aalcr import AALCRAdapter-from .aime25 import AIME25Adapter-from .base import BenchmarkAdapter-from .gaia import GAIAAdapter-from .gpqa import GPQAAdapter-from .hle import HLEAdapter-from .livebench import LiveBenchAdapter-from .math import MathAdapter-from .super_gpqa import SuperGPQAAdapter--ADAPTER_REGISTRY: dict[str, type[BenchmarkAdapter]] = {- "math": MathAdapter,- "gaia": GAIAAdapter,- "hle": HLEAdapter,- "gpqa": GPQAAdapter,- "aime25": AIME25Adapter,- "livebench": LiveBenchAdapter,- "aalcr": AALCRAdapter,- "super_gpqa": SuperGPQAAdapter,-}--__all__ = [- "AALCRAdapter",- "ADAPTER_REGISTRY",- "AIME25Adapter",- "BenchmarkAdapter",- "GAIAAdapter",- "GPQAAdapter",- "HLEAdapter",- "LiveBenchAdapter",- "MathAdapter",- "SuperGPQAAdapter",-]diff --git a/benchmark/iso_solve/eval/aalcr.py b/benchmark/iso_solve/eval/aalcr.pydeleted file mode 100644index baa8bb734..000000000--- a/benchmark/iso_solve/eval/aalcr.py+++ /dev/null@@ -1,307 +0,0 @@-from __future__ import annotations--import logging-import os-import re-import zipfile-from collections import defaultdict-from pathlib import Path-from typing import Any--from .base import BenchmarkAdapter, apply_limit-from benchmark.iso_solve.core.types import Problem--logger = logging.getLogger("iso_solve.aalcr")--AALCR_SYSTEM_PROMPT = (- "You are an expert analyst. You will be given a set of documents followed by a question. "- "Read all documents carefully, then answer the question using information from the documents. "- "Think step by step, synthesizing information across multiple documents as needed. "- "Finish your response with: FINAL ANSWER: [YOUR ANSWER]"-)--_FINAL_ANSWER_RE = re.compile(r"FINAL\s+ANSWER\s*:\s*(.+)", re.IGNORECASE | re.DOTALL)---def _parse_semicolon_list(value: str) -> list[str]:- """Parse a semicolon-separated field (AA-LCR uses `;` as delimiter)."""- if not value or not value.strip():- return []- return [v.strip() for v in value.split(";") if v.strip()]---def _extract_documents(data_dir: str) -> str:- """Extract the AA-LCR zip and return the root directory containing documents.-- Zip structure: lcr/{Category}/{document_set_id}/{filename}.txt- Returns the path to the 'lcr' directory after extraction.-- Handles encoding: the zip lacks the UTF-8 flag so Python decodes filenames- as CP437, mangling non-ASCII characters. We re-encode via CP437 and decode- as UTF-8 (with NFC normalization) to recover correct filenames.- """- import unicodedata-- zip_path = os.path.join(data_dir, "extracted_text", "AA-LCR_extracted-text.zip")- if not os.path.isfile(zip_path):- raise FileNotFoundError(- f"Document archive not found at {zip_path}. "- "Ensure the full dataset was downloaded."- )-- extract_dir = os.path.join(data_dir, "_extracted")- lcr_dir = os.path.join(extract_dir, "lcr")- if os.path.isdir(lcr_dir):- return lcr_dir-- logger.info("Extracting AA-LCR documents from %s ...", zip_path)- with zipfile.ZipFile(zip_path, "r") as zf:- for info in zf.infolist():- if info.is_dir():- continue- try:- raw_bytes = info.filename.encode("cp437")- correct_name = unicodedata.normalize("NFC", raw_bytes.decode("utf-8"))- except (UnicodeDecodeError, UnicodeEncodeError):- correct_name = info.filename-- out_path = os.path.join(extract_dir, correct_name)- os.makedirs(os.path.dirname(out_path), exist_ok=True)- with zf.open(info) as src, open(out_path, "wb") as dst:- dst.write(src.read())-- logger.info("Extracted to %s", extract_dir)- return lcr_dir---def _build_file_index(lcr_dir: str) -> dict[str, dict[str, str]]:- """Build {document_set_id: {filename: abs_path}} index from extracted docs."""- index: dict[str, dict[str, str]] = defaultdict(dict)- for category_dir in Path(lcr_dir).iterdir():- if not category_dir.is_dir():- continue- for docset_dir in category_dir.iterdir():- if not docset_dir.is_dir():- continue- ds_id = docset_dir.name- for fpath in docset_dir.iterdir():- if fpath.is_file():- index[ds_id][fpath.name] = str(fpath)- return dict(index)---def _resolve_local_paths(- file_index: dict[str, dict[str, str]],- document_set_id: str,- filenames: list[str],-) -> list[str]:- """Resolve filenames to local paths using the pre-built index."""- docset_files = file_index.get(document_set_id, {})- resolved: list[str] = []- for fname in filenames:- path = docset_files.get(fname)- if path:- resolved.append(path)- else:- logger.debug(- "File '%s' not found in document set '%s'", fname, document_set_id- )- return resolved---def _load_document_text(local_paths: list[str]) -> str:- """Read and concatenate document text from local file paths."""- parts: list[str] = []- for path in local_paths:- try:- with open(path, "r", encoding="utf-8", errors="replace") as f:- content = f.read()- doc_name = os.path.basename(path)- parts.append(f"=== Document: {doc_name} ===\n{content}")- except Exception as exc:- logger.warning("Failed to read document %s: %s", path, exc)- return "\n\n".join(parts)---class AALCRAdapter(BenchmarkAdapter):- @property- def name(self) -> str:- return "aalcr"-- @property- def breakdown_keys(self) -> list[str]:- return ["document_category"]-- @property- def skip_extract(self) -> bool:- return True-- @property- def extract_hint(self) -> str:- return "Extract the final answer after 'FINAL ANSWER:'. The answer is typically a short phrase, number, or list."-- @property- def judge_hint(self) -> str:- return (- "IMPORTANT GRADING INSTRUCTIONS:\n"- "1. The candidate response is the FULL model output, not a pre-extracted answer. "- "Read through the entire response and check whether the key factual content "- "from the ground-truth answer is present.\n"- "2. Judge ONLY on substantive content. Abbreviated names, full legal names, and "- "common short-form variants of the same entity are all equivalent.\n"- "3. If the ground-truth lists multiple items, the response is CORRECT as long as "- "it identifies ALL of them, even if surrounded by extra explanation or caveats.\n"- "4. If the question asks for N items but the ground-truth contains fewer than N, "- "the response is CORRECT as long as it identifies all items in the ground-truth, "- "even if it notes that fewer than N exist.\n"- "5. Ignore differences in punctuation, capitalization, word order, formatting, "- "and any additional contextual details the response may include.\n"- "6. When in doubt, lean toward CORRECT if the core factual content matches."- )-- def load_dataset(self, bench_cfg: dict[str, Any], args: Any) -> list[Problem]:- import csv-- from huggingface_hub import snapshot_download-- dataset_id = bench_cfg.get("dataset_id", "ArtificialAnalysis/AA-LCR")- data_dir = snapshot_download(repo_id=dataset_id, repo_type="dataset")-- lcr_dir = _extract_documents(data_dir)- file_index = _build_file_index(lcr_dir)- logger.info(- "Document index: %d document sets, %d total files",- len(file_index),- sum(len(v) for v in file_index.values()),- )-- csv_path = os.path.join(data_dir, "AA-LCR_Dataset.csv")- if not os.path.isfile(csv_path):- csv_candidates = list(Path(data_dir).rglob("*.csv"))- if csv_candidates:- csv_path = str(csv_candidates[0])- else:- raise FileNotFoundError(f"No CSV file found in {data_dir}")-- with open(csv_path, newline="", encoding="utf-8") as f:- rows = list(csv.DictReader(f))-- problems: list[Problem] = []- for row in rows:- question_id = int(row.get("question_id", 0))- document_set_id = row.get("document_set_id", "")- filenames_raw = row.get("data_source_filenames", "")-- filenames = _parse_semicolon_list(filenames_raw)- local_paths = _resolve_local_paths(file_index, document_set_id, filenames)-- if not local_paths:- logger.warning(- "Question %s (set=%s): no documents resolved (filenames=%s)",- question_id,- document_set_id,- filenames_raw[:120],- )- elif len(local_paths) < len(filenames):- logger.warning(- "Question %s (set=%s): only %d/%d documents resolved",- question_id,- document_set_id,- len(local_paths),- len(filenames),- )-- problems.append(- Problem(- id=f"aalcr_{question_id:04d}",- question=row["question"],- ground_truth=str(row.get("answer", "")),- benchmark="aalcr",- system_prompt=AALCR_SYSTEM_PROMPT,- metadata={- "document_category": row.get("document_category", "Unknown"),- "document_set_id": document_set_id,- "question_id": question_id,- "input_tokens": int(row.get("input_tokens", 0)),- "local_paths": local_paths,- },- )- )- return problems-- def filter_problems(- self,- problems: list[Problem],- bench_cfg: dict[str, Any],- args: Any,- ) -> list[Problem]:- filter_cfg = bench_cfg.get("filter", {})- categories = getattr(args, "aalcr_categories", None) or filter_cfg.get("categories")- limit = args.limit or filter_cfg.get("limit")- seed = getattr(args, "seed", filter_cfg.get("seed", 42))- sequential = getattr(args, "sequential", False)-- filtered = problems- if categories:- cat_set = {c.lower() for c in categories}- filtered = [- p for p in filtered- if str(p.metadata.get("document_category", "")).lower() in cat_set- ]- return apply_limit(filtered, limit, seed, sequential)-- def _load_docs_for_problem(self, problem: Problem) -> str:- local_paths = problem.metadata.get("local_paths", [])- if not local_paths:- return ""- return _load_document_text(local_paths)-- def build_direct_request(self, problem: Problem, multimodal: bool = True) -> dict[str, Any]: # noqa: ARG002- doc_text = self._load_docs_for_problem(problem)- if doc_text:- user_content = f"{doc_text}\n\n---\n\nQuestion: {problem.question}"- else:- user_content = problem.question- return {- "messages": [- {"role": "system", "content": problem.system_prompt},- {"role": "user", "content": user_content},- ]- }-- def build_pipeline_request(self, problem: Problem, multimodal: bool = True) -> dict[str, Any]: # noqa: ARG002- doc_text = self._load_docs_for_problem(problem)- if doc_text:- prompt = f"{doc_text}\n\n---\n\nQuestion: {problem.question}"- else:- prompt = problem.question- return {"prompt": prompt, "image_url": None}-- def extract_fallback(self, model_output: str) -> str | None:- matches = _FINAL_ANSWER_RE.findall(model_output)- if matches:- ans = matches[-1].strip()- return ans.split("\n")[0].strip() if ans else None- text = model_output.strip()- return text.splitlines()[-1].strip() if text else None-- def judge_fallback(self, problem: Problem, extracted: str | None) -> tuple[bool, str]:- if extracted is None:- return False, "No extracted answer"- pred = extracted.strip().lower()- gold = problem.ground_truth.strip().lower()- if pred == gold:- return True, "exact match"- if gold in pred or pred in gold:- return True, "substring match fallback"- return False, "no match fallback"-- def preview(self, problem: Problem) -> str:- n_docs = len(problem.metadata.get("local_paths", []))- tokens = problem.metadata.get("input_tokens", "?")- return (- f"id={problem.id} "- f"category={problem.metadata.get('document_category', '?')} "- f"docs={n_docs} tokens={tokens} "- f"question={problem.question[:100]}"- )diff --git a/benchmark/iso_solve/eval/aime25.py b/benchmark/iso_solve/eval/aime25.pydeleted file mode 100644index 7fea8a4b1..000000000--- a/benchmark/iso_solve/eval/aime25.py+++ /dev/null@@ -1,164 +0,0 @@-from __future__ import annotations--import json-from pathlib import Path-import re-from typing import Any--from .base import BenchmarkAdapter, apply_limit-from benchmark.iso_solve.core.types import Problem--AIME_SYSTEM_PROMPT = (- "You are an expert competition mathematics problem solver. "- "Solve the given AIME problem step by step with rigorous reasoning. "- "The answer is an integer from 0 to 999. "- "Put your final answer inside \\boxed{}."-)--_LEADING_INT_RE = re.compile(r"^[-+]?\d+")-_INTEGER_RE = re.compile(r"[-+]?\d+")---class AIME25Adapter(BenchmarkAdapter):- @property- def name(self) -> str:- return "aime25"-- @property- def breakdown_keys(self) -> list[str]:- return ["part"]-- @property- def extract_hint(self) -> str:- return "The final answer must be an integer in [0, 999]."-- @property- def judge_hint(self) -> str:- return "Judge by integer equality."-- def _parse_answer(self, raw: Any) -> int:- if isinstance(raw, (int, float)):- return int(raw)- s = str(raw).strip()- m = _LEADING_INT_RE.match(s)- if not m:- raise ValueError(f"Cannot parse AIME answer: {raw!r}")- return int(m.group(0))-- def _load_part_from_hf(self, config_name: str, part: int) -> list[Problem]:- from datasets import load_dataset-- ds = load_dataset("opencompass/AIME2025", config_name, split="test")- out: list[Problem] = []- for idx, row in enumerate(ds):- answer_int = self._parse_answer(row["answer"])- out.append(- Problem(- id=f"aime25_{'I' if part == 1 else 'II'}_{idx + 1:02d}",- question=row["question"],- ground_truth=str(answer_int),- benchmark="aime25",- system_prompt=AIME_SYSTEM_PROMPT,- metadata={"part": part, "problem_number": idx + 1},- )- )- return out-- def _load_part_from_jsonl(self, path: Path, part: int) -> list[Problem]:- out: list[Problem] = []- with open(path, "r", encoding="utf-8") as f:- for idx, line in enumerate(f):- row = json.loads(line)- answer_int = self._parse_answer(row["answer"])- out.append(- Problem(- id=f"aime25_{'I' if part == 1 else 'II'}_{idx + 1:02d}",- question=row["question"],- ground_truth=str(answer_int),- benchmark="aime25",- system_prompt=AIME_SYSTEM_PROMPT,- metadata={"part": part, "problem_number": idx + 1},- )- )- return out-- def load_dataset(self, bench_cfg: dict[str, Any], args: Any) -> list[Problem]:- parts = getattr(args, "aime_parts", None) or bench_cfg.get("parts") or [1, 2]- cache_dir = Path(__file__).resolve().parents[1] / "data"- cache_map = {- 1: cache_dir / "aime2025_I.jsonl",- 2: cache_dir / "aime2025_II.jsonl",- }- config_map = {1: "AIME2025-I", 2: "AIME2025-II"}-- problems: list[Problem] = []- for part in parts:- cache_file = cache_map[part]- if cache_file.exists():- part_probs = self._load_part_from_jsonl(cache_file, part)- else:- part_probs = self._load_part_from_hf(config_map[part], part)- cache_dir.mkdir(parents=True, exist_ok=True)- with open(cache_file, "w", encoding="utf-8") as f:- for p in part_probs:- json.dump(- {"question": p.question, "answer": p.ground_truth},- f,- ensure_ascii=False,- )- f.write("\n")- problems.extend(part_probs)- return problems-- def filter_problems(- self,- problems: list[Problem],- bench_cfg: dict[str, Any],- args: Any,- ) -> list[Problem]:- filter_cfg = bench_cfg.get("filter", {})- parts = getattr(args, "aime_parts", None) or bench_cfg.get("parts")- limit = args.limit or filter_cfg.get("limit")- seed = getattr(args, "seed", filter_cfg.get("seed", 42))- sequential = getattr(args, "sequential", False)-- filtered = problems- if parts:- part_set = {int(p) for p in parts}- filtered = [p for p in filtered if int(p.metadata.get("part", 0)) in part_set]- return apply_limit(filtered, limit, seed, sequential)-- def build_pipeline_request(- self,- problem: Problem,- multimodal: bool = True, # noqa: ARG002- ) -> dict[str, Any]:- prompt = (- f"{problem.question}\n\n"- "This is an AIME problem. The final answer is an integer from 0 to 999. "- "Put your final answer inside \\boxed{}."- )- return {"prompt": prompt, "image_url": None}-- def extract_fallback(self, model_output: str) -> str | None:- boxed = re.findall(r"\\boxed\{([^{}]+)\}", model_output)- if boxed:- m = _INTEGER_RE.search(boxed[-1])- if m:- return m.group(0)- nums = _INTEGER_RE.findall(model_output)- return nums[-1] if nums else None-- def judge_fallback(self, problem: Problem, extracted: str | None) -> tuple[bool, str]:- if extracted is None:- return False, "No integer extracted"- try:- return int(extracted) == int(problem.ground_truth), "integer match fallback"- except Exception:- return False, "Invalid integer prediction"-- def preview(self, problem: Problem) -> str:- return (- f"id={problem.id} part={problem.metadata.get('part')} "- f"gt={problem.ground_truth} question={problem.question[:90]}"- )diff --git a/benchmark/iso_solve/eval/base.py b/benchmark/iso_solve/eval/base.pydeleted file mode 100644index 808ad0897..000000000--- a/benchmark/iso_solve/eval/base.py+++ /dev/null@@ -1,90 +0,0 @@-from __future__ import annotations--import random-from abc import ABC, abstractmethod-from typing import Any--from benchmark.iso_solve.core.types import Problem---def apply_limit(- problems: list[Problem],- limit: int | None,- seed: int = 42,- sequential: bool = False,-) -> list[Problem]:- """Apply limit to a problem list: sequential slice or seeded random sample."""- if not limit or limit >= len(problems):- return problems- if sequential:- return problems[:limit]- return random.Random(seed).sample(problems, limit)---class BenchmarkAdapter(ABC):- @property- @abstractmethod- def name(self) -> str:- pass-- @property- def breakdown_keys(self) -> list[str]:- return []-- @property- def skip_extract(self) -> bool:- """If True, skip LLM extraction and pass full model output to judge."""- return False-- @property- def extract_hint(self) -> str:- return ""-- @property- def judge_hint(self) -> str:- return ""-- @abstractmethod- def load_dataset(self, bench_cfg: dict[str, Any], args: Any) -> list[Problem]:- pass-- @abstractmethod- def filter_problems(- self,- problems: list[Problem],- bench_cfg: dict[str, Any],- args: Any,- ) -> list[Problem]:- pass-- def build_direct_request(- self,- problem: Problem,- multimodal: bool = True, # noqa: ARG002- ) -> dict[str, Any]:- return {- "messages": [- {"role": "system", "content": problem.system_prompt},- {"role": "user", "content": problem.question},- ]- }-- def build_pipeline_request(- self,- problem: Problem,- multimodal: bool = True, # noqa: ARG002- ) -> dict[str, Any]:- return {"prompt": problem.question, "image_url": None}-- def extract_fallback(self, model_output: str) -> str | None:- text = model_output.strip()- return text if text else None-- def judge_fallback(self, problem: Problem, extracted: str | None) -> tuple[bool, str]:- if extracted is None:- return False, "No extracted answer"- correct = extracted.strip().lower() == problem.ground_truth.strip().lower()- return correct, "string exact match fallback"-- def preview(self, problem: Problem) -> str:- return f"id={problem.id} question={problem.question[:120]}"diff --git a/benchmark/iso_solve/eval/gaia.py b/benchmark/iso_solve/eval/gaia.pydeleted file mode 100644index 5767942e6..000000000--- a/benchmark/iso_solve/eval/gaia.py+++ /dev/null@@ -1,138 +0,0 @@-from __future__ import annotations--import os-import re-from typing import Any--from .base import BenchmarkAdapter, apply_limit-from .scorers import question_scorer-from benchmark.iso_solve.core.types import Problem-from benchmark.iso_solve.multimodal import (- build_messages,- build_multimodal_context,-)--GAIA_SYSTEM_PROMPT = (- "You are a general AI assistant. I will ask you a question. "- "Report your thoughts, and finish your answer with the following template: "- "FINAL ANSWER: [YOUR FINAL ANSWER]."-)--_FINAL_ANSWER_RE = re.compile(r"FINAL\s+ANSWER\s*:\s*(.+)", re.IGNORECASE | re.DOTALL)---class GAIAAdapter(BenchmarkAdapter):- @property- def name(self) -> str:- return "gaia"-- @property- def breakdown_keys(self) -> list[str]:- return ["level"]-- @property- def extract_hint(self) -> str:- return "Extract the final answer after 'FINAL ANSWER:'."-- @property- def judge_hint(self) -> str:- return "Answers may be numbers, short strings, or comma-separated lists."-- def load_dataset(self, bench_cfg: dict[str, Any], args: Any) -> list[Problem]:- from datasets import load_dataset- from huggingface_hub import snapshot_download-- dataset_id = bench_cfg.get("dataset_id", "gaia-benchmark/GAIA")- config_name = getattr(args, "gaia_config_name", None) or bench_cfg.get("config_name", "2023_all")- split = getattr(args, "gaia_split", None) or bench_cfg.get("split", "validation")-- data_dir = snapshot_download(repo_id=dataset_id, repo_type="dataset")- ds = load_dataset(data_dir, config_name, split=split)-- problems: list[Problem] = []- for row in ds:- gt = row.get("Final answer") or row.get("final_answer")- if gt is None:- continue- file_name = row.get("file_name") or ""- file_path_rel = row.get("file_path") or ""- abs_file_path = os.path.join(data_dir, file_path_rel) if file_path_rel else None- problems.append(- Problem(- id=row["task_id"],- question=row["Question"],- ground_truth=str(gt),- benchmark="gaia",- system_prompt=GAIA_SYSTEM_PROMPT,- metadata={- "level": int(row["Level"]),- "file_name": file_name or None,- "file_path": abs_file_path,- },- )- )- return problems-- def filter_problems(- self,- problems: list[Problem],- bench_cfg: dict[str, Any],- args: Any,- ) -> list[Problem]:- filter_cfg = bench_cfg.get("filter", {})- levels = getattr(args, "gaia_levels", None) or filter_cfg.get("levels")- limit = args.limit or filter_cfg.get("limit")- seed = getattr(args, "seed", filter_cfg.get("seed", 42))- sequential = getattr(args, "sequential", False)-- filtered = problems- if levels:- level_set = {int(v) for v in levels}- filtered = [p for p in filtered if int(p.metadata.get("level", 0)) in level_set]- return apply_limit(filtered, limit, seed, sequential)-- def _prepare_multimodal(- self,- problem: Problem,- multimodal: bool,- ) -> tuple[str, list[str]]:- file_path = problem.metadata.get("file_path")- file_name = problem.metadata.get("file_name")- if not file_path or not os.path.exists(file_path):- return problem.question, []- ctx = build_multimodal_context([(file_path, file_name)], multimodal=multimodal)- text_parts = [problem.question]- if ctx.extra_text:- text_parts.append(ctx.extra_text)- return "\n\n".join(text_parts), ctx.image_data_uris-- def build_direct_request(self, problem: Problem, multimodal: bool = True) -> dict[str, Any]:- user_text, image_data_uris = self._prepare_multimodal(problem, multimodal=multimodal)- if image_data_uris:- return {"messages": build_messages(problem.system_prompt, user_text, image_data_uris)}- return {- "messages": [- {"role": "system", "content": problem.system_prompt},- {"role": "user", "content": user_text},- ]- }-- def build_pipeline_request(self, problem: Problem, multimodal: bool = True) -> dict[str, Any]:- user_text, image_data_uris = self._prepare_multimodal(problem, multimodal=multimodal)- return {- "prompt": user_text,- "image_url": image_data_uris[0] if image_data_uris else None,- }-- def extract_fallback(self, model_output: str) -> str | None:- matches = _FINAL_ANSWER_RE.findall(model_output)- if matches:- ans = matches[-1].strip()- return ans.split("\n")[0].strip() if ans else None- text = model_output.strip()- return text.splitlines()[-1].strip() if text else None-- def judge_fallback(self, problem: Problem, extracted: str | None) -> tuple[bool, str]:- if extracted is None:- return False, "No extracted answer"- return question_scorer(extracted, problem.ground_truth), "gaia scorer fallback"diff --git a/benchmark/iso_solve/eval/gpqa.py b/benchmark/iso_solve/eval/gpqa.pydeleted file mode 100644index 4f32baed4..000000000--- a/benchmark/iso_solve/eval/gpqa.py+++ /dev/null@@ -1,130 +0,0 @@-from __future__ import annotations--import random-import re-from typing import Any--from .base import BenchmarkAdapter, apply_limit-from benchmark.iso_solve.core.types import Problem--CHOICE_LABELS = ["A", "B", "C", "D"]--GPQA_SYSTEM_PROMPT = (- "You are an expert scientist answering a multiple-choice question. "- "Think step-by-step, then finish your response with the line:\n"- "Answer: X\n"- "where X is exactly one of A, B, C, or D."-)---class GPQAAdapter(BenchmarkAdapter):- @property- def name(self) -> str:- return "gpqa"-- @property- def breakdown_keys(self) -> list[str]:- return ["domain"]-- @property- def extract_hint(self) -> str:- return "The final answer must be exactly one letter: A, B, C, or D."-- @property- def judge_hint(self) -> str:- return "This is a multiple-choice question. Compare only the final letter answer."-- def _build_choices(self, row: dict[str, Any], seed: int) -> tuple[list[str], int]:- correct_ans = row["Correct Answer"]- incorrect = [- row["Incorrect Answer 1"],- row["Incorrect Answer 2"],- row["Incorrect Answer 3"],- ]- choices = [correct_ans] + incorrect- rng = random.Random(seed)- rng.shuffle(choices)- correct_idx = choices.index(correct_ans)- return choices, correct_idx-- def load_dataset(self, bench_cfg: dict[str, Any], args: Any) -> list[Problem]:- from datasets import load_dataset-- dataset_id = bench_cfg.get("dataset_id", "Idavidrein/gpqa")- config_name = bench_cfg.get("config_name", "gpqa_diamond")- choice_seed = bench_cfg.get("choice_shuffle_seed", 42)- ds = load_dataset(dataset_id, config_name, split="train")-- problems: list[Problem] = []- for idx, row in enumerate(ds):- choices, correct_idx = self._build_choices(row, choice_seed + idx)- formatted = "\n".join(f"{CHOICE_LABELS[i]}. {c}" for i, c in enumerate(choices))- q = f"{row['Question']}\n\n{formatted}"- problems.append(- Problem(- id=row.get("Record ID", f"gpqa_{idx:04d}"),- question=q,- ground_truth=CHOICE_LABELS[correct_idx],- benchmark="gpqa",- system_prompt=GPQA_SYSTEM_PROMPT,- metadata={- "domain": row.get("High-level domain", "Unknown"),- "subdomain": row.get("Subdomain", "Unknown"),- "choices": choices,- "correct_idx": correct_idx,- },- )- )- return problems-- def filter_problems(- self,- problems: list[Problem],- bench_cfg: dict[str, Any],- args: Any,- ) -> list[Problem]:- filter_cfg = bench_cfg.get("filter", {})- domains = getattr(args, "gpqa_domains", None) or filter_cfg.get("domains")- limit = args.limit or filter_cfg.get("limit")- seed = getattr(args, "seed", filter_cfg.get("seed", 42))- sequential = getattr(args, "sequential", False)-- filtered = problems- if domains:- domain_set = {d.lower() for d in domains}- filtered = [p for p in filtered if str(p.metadata.get("domain", "")).lower() in domain_set]-- return apply_limit(filtered, limit, seed, sequential)-- def build_pipeline_request(- self,- problem: Problem,- multimodal: bool = True, # noqa: ARG002- ) -> dict[str, Any]:- prompt = (- f"{problem.question}\n\n"- "Think carefully step-by-step. Your final answer must be exactly one of A, B, C, or D."- )- return {"prompt": prompt, "image_url": None}-- def extract_fallback(self, model_output: str) -> str | None:- for line in reversed(model_output.splitlines()):- m = re.match(r"(?:Answer|answer|ANSWER)\s*[::]\s*([A-Da-d])", line.strip())- if m:- return m.group(1).upper()- m = re.search(r"\b([A-D])\b", model_output[-200:] if len(model_output) > 200 else model_output)- if m:- return m.group(1).upper()- return None-- def judge_fallback(self, problem: Problem, extracted: str | None) -> tuple[bool, str]:- if extracted is None:- return False, "No extracted option letter"- correct = extracted.strip().upper() == problem.ground_truth.strip().upper()- return correct, "letter match fallback"-- def preview(self, problem: Problem) -> str:- return (- f"id={problem.id} domain={problem.metadata.get('domain', 'Unknown')} "- f"gt={problem.ground_truth} question={problem.question[:100]}"- )diff --git a/benchmark/iso_solve/eval/hle.py b/benchmark/iso_solve/eval/hle.pydeleted file mode 100644index 5839e729b..000000000--- a/benchmark/iso_solve/eval/hle.py+++ /dev/null@@ -1,110 +0,0 @@-from __future__ import annotations--from typing import Any-from pathlib import Path--from .base import BenchmarkAdapter, apply_limit-from benchmark.iso_solve.core.types import Problem-from benchmark.iso_solve.multimodal import build_messages--HLE_SYSTEM_PROMPT = (- "Your response should be in the following format:\n"- "Explanation: {your explanation for your answer choice}\n"- "Answer: {your chosen answer}\n"- "Confidence: {your confidence score between 0% and 100% for your answer}"-)--_HF_HLE_PARQUET_URL = "hf://datasets/cais/hle/data/test-00000-of-00001.parquet"---class HLEAdapter(BenchmarkAdapter):- @property- def name(self) -> str:- return "hle"-- @property- def breakdown_keys(self) -> list[str]:- return ["subject", "answer_type"]-- @property- def extract_hint(self) -> str:- return "Extract the final answer from the line starting with 'Answer:'."-- @property- def judge_hint(self) -> str:- return "For numerical answers allow tiny rounding tolerance."-- def load_dataset(self, bench_cfg: dict[str, Any], args: Any) -> list[Problem]:- import pandas as pd-- parquet_url = bench_cfg.get("parquet_url", _HF_HLE_PARQUET_URL)- cache_dir = Path(__file__).resolve().parents[1] / "data"- cache_file = cache_dir / "hle.parquet"- if cache_file.exists():- df = pd.read_parquet(cache_file)- else:- df = pd.read_parquet(parquet_url)- cache_dir.mkdir(parents=True, exist_ok=True)- df.to_parquet(cache_file, index=False)-- out: list[Problem] = []- for _, row in df.iterrows():- image = str(row.get("image", "") or "")- out.append(- Problem(- id=str(row.get("id", "")),- question=str(row.get("question", "")),- ground_truth=str(row.get("answer", "")),- benchmark="hle",- system_prompt=HLE_SYSTEM_PROMPT,- metadata={- "subject": str(row.get("subject", "Unknown") or "Unknown"),- "answer_type": str(row.get("answer_type", "short_answer") or "short_answer"),- "image": image,- "is_multimodal": bool(image),- },- )- )- return out-- def filter_problems(- self,- problems: list[Problem],- bench_cfg: dict[str, Any],- args: Any,- ) -> list[Problem]:- filter_cfg = bench_cfg.get("filter", {})- subjects = getattr(args, "subjects", None) or filter_cfg.get("subjects")- skip_multimodal = bench_cfg.get("skip_multimodal", False)- limit = args.limit or filter_cfg.get("limit")- seed = getattr(args, "seed", filter_cfg.get("seed", 42))- sequential = getattr(args, "sequential", False)-- filtered = problems- if subjects:- subj_set = set(subjects)- filtered = [p for p in filtered if p.metadata.get("subject") in subj_set]- if skip_multimodal:- filtered = [p for p in filtered if not p.metadata.get("is_multimodal")]- return apply_limit(filtered, limit, seed, sequential)-- def build_direct_request(self, problem: Problem, multimodal: bool = True) -> dict[str, Any]:- image = str(problem.metadata.get("image", "") or "")- if multimodal and image:- return {"messages": build_messages(problem.system_prompt, problem.question, [image])}- return super().build_direct_request(problem, multimodal=multimodal)-- def build_pipeline_request(self, problem: Problem, multimodal: bool = True) -> dict[str, Any]:- image = str(problem.metadata.get("image", "") or "")- return {- "prompt": problem.question,- "image_url": image if multimodal and image else None,- }-- def extract_fallback(self, model_output: str) -> str | None:- for line in reversed(model_output.splitlines()):- stripped = line.strip()- if stripped.lower().startswith("answer:"):- return stripped.split(":", 1)[1].strip()- text = model_output.strip()- return text.splitlines()[-1].strip() if text else Nonediff --git a/benchmark/iso_solve/eval/livebench.py b/benchmark/iso_solve/eval/livebench.pydeleted file mode 100644index 7dfd6a330..000000000--- a/benchmark/iso_solve/eval/livebench.py+++ /dev/null@@ -1,130 +0,0 @@-from __future__ import annotations--import re-from typing import Any--from .base import BenchmarkAdapter, apply_limit-from benchmark.iso_solve.core.types import Problem--ALL_CATEGORIES = [- "reasoning",- "math",- "coding",- "data_analysis",- "instruction_following",- "language",-]--_HF_DATASET_MAP = {- "reasoning": "livebench/reasoning",- "math": "livebench/math",- "coding": "livebench/coding",- "data_analysis": "livebench/data_analysis",- "instruction_following": "livebench/instruction_following",- "language": "livebench/language",-}--LIVEBENCH_SYSTEM_PROMPT = (- "You are an expert AI assistant solving a benchmark question. "- "Think step-by-step, then provide your final answer clearly. "- "Follow any output format instructions given in the question exactly."-)---class LiveBenchAdapter(BenchmarkAdapter):- @property- def name(self) -> str:- return "livebench"-- @property- def breakdown_keys(self) -> list[str]:- return ["category", "task"]-- @property- def extract_hint(self) -> str:- return "Extract the model's final answer according to the requested output format."-- @property- def judge_hint(self) -> str:- return "Be strict about correctness and lenient about whitespace/case differences."-- def load_dataset(self, bench_cfg: dict[str, Any], args: Any) -> list[Problem]:- from datasets import load_dataset-- categories = getattr(args, "livebench_categories", None) or bench_cfg.get("categories") or ALL_CATEGORIES- out: list[Problem] = []- for cat in categories:- dataset_id = _HF_DATASET_MAP.get(cat)- if not dataset_id:- continue- try:- ds = load_dataset(dataset_id, split="test")- except Exception:- ds = load_dataset(dataset_id, split="train")- for row in ds:- removal = row.get("livebench_removal_date")- if removal is not None and str(removal).strip():- continue- turns = row.get("turns", [])- question = turns[0] if turns else ""- gt = row.get("ground_truth", "")- if isinstance(gt, list):- gt = ", ".join(str(x) for x in gt)- out.append(- Problem(- id=str(row.get("question_id", f"{cat}_{len(out):04d}")),- question=question,- ground_truth=str(gt),- benchmark="livebench",- system_prompt=LIVEBENCH_SYSTEM_PROMPT,- metadata={- "category": row.get("category", cat),- "task": row.get("task", "unknown"),- },- )- )- return out-- def filter_problems(- self,- problems: list[Problem],- bench_cfg: dict[str, Any],- args: Any,- ) -> list[Problem]:- filter_cfg = bench_cfg.get("filter", {})- categories = getattr(args, "livebench_categories", None) or bench_cfg.get("categories")- tasks = filter_cfg.get("tasks")- limit = args.limit or filter_cfg.get("limit")- seed = getattr(args, "seed", filter_cfg.get("seed", 42))- sequential = getattr(args, "sequential", False)-- filtered = problems- if categories:- cat_set = {str(v).lower() for v in categories}- filtered = [p for p in filtered if str(p.metadata.get("category", "")).lower() in cat_set]- if tasks:- task_set = {str(v).lower() for v in tasks}- filtered = [p for p in filtered if str(p.metadata.get("task", "")).lower() in task_set]- return apply_limit(filtered, limit, seed, sequential)-- def build_pipeline_request(self, problem: Problem, multimodal: bool = True) -> dict[str, Any]:- prompt = (- f"{problem.question}\n\n"- "Think carefully step-by-step. Provide your final answer clearly, "- "following any format instructions exactly."- )- return {"prompt": prompt, "image_url": None}-- def extract_fallback(self, model_output: str) -> str | None:- text = model_output.strip()- if not text:- return None- lines = [line.strip() for line in text.splitlines() if line.strip()]- return lines[-1] if lines else text-- def judge_fallback(self, problem: Problem, extracted: str | None) -> tuple[bool, str]:- if extracted is None:- return False, "No extracted answer"- norm_pred = re.sub(r"\s+", " ", extracted.strip().lower()).strip(".,;!? ")- norm_gt = re.sub(r"\s+", " ", problem.ground_truth.strip().lower()).strip(".,;!? ")- return norm_pred == norm_gt, "normalized exact match fallback"diff --git a/benchmark/iso_solve/eval/math.py b/benchmark/iso_solve/eval/math.pydeleted file mode 100644index f9c4544e3..000000000--- a/benchmark/iso_solve/eval/math.py+++ /dev/null@@ -1,174 +0,0 @@-from __future__ import annotations--import json-from pathlib import Path-import re-from typing import Any--from .base import BenchmarkAdapter, apply_limit-from benchmark.iso_solve.core.types import Problem-from .scorers.math_equivalence import is_equiv--SUBJECTS = [- "Prealgebra",- "Algebra",- "Number Theory",- "Counting & Probability",- "Geometry",- "Intermediate Algebra",- "Precalculus",-]--MATH_SYSTEM_PROMPT = (- "You are a precise mathematics problem solver. "- "Solve step by step and put your final answer inside \\boxed{}."-)--_HF_PARQUET_URL = (- "hf://datasets/qwedsacf/competition_math/data/"- "train-00000-of-00001-7320a6f3aba8ebd2.parquet"-)---class MathAdapter(BenchmarkAdapter):- @property- def name(self) -> str:- return "math"-- @property- def breakdown_keys(self) -> list[str]:- return ["subject", "level"]-- @property- def extract_hint(self) -> str:- return "This is a math problem. Extract the final expression, preferably from \\boxed{}."-- @property- def judge_hint(self) -> str:- return "Judge mathematical equivalence, not formatting."-- def _parse_level(self, level_raw: Any) -> int | None:- if isinstance(level_raw, int):- return level_raw- if isinstance(level_raw, str) and "Level " in level_raw:- try:- return int(level_raw.split("Level ")[1])- except Exception:- return None- return None-- def _df_to_problems(self, df: Any, source: str) -> list[Problem]:- out: list[Problem] = []- for idx, row in df.iterrows():- solution = str(row.get("solution", ""))- gt = self._extract_from_solution(solution)- out.append(- Problem(- id=f"math_{idx:05d}",- question=str(row.get("problem", "")),- ground_truth=gt or "",- benchmark="math",- system_prompt=MATH_SYSTEM_PROMPT,- metadata={- "subject": str(row.get("type", "Unknown")),- "level": self._parse_level(row.get("level", "")),- "source_file": f"{source}#{idx}",- },- )- )- return out-- def _load_from_local(self, dataroot: str) -> list[Problem]:- root = Path(dataroot)- if "*" in dataroot:- import glob as globmod- files = [Path(p) for p in globmod.glob(dataroot)]- else:- files = list(root.rglob("*.json"))- out: list[Problem] = []- for idx, fpath in enumerate(files):- try:- data = json.loads(fpath.read_text(encoding="utf-8"))- solution = str(data.get("solution", ""))- gt = self._extract_from_solution(solution) or ""- out.append(- Problem(- id=f"math_local_{idx:05d}",- question=str(data.get("problem", "")),- ground_truth=gt,- benchmark="math",- system_prompt=MATH_SYSTEM_PROMPT,- metadata={- "subject": str(data.get("type", "Unknown")),- "level": self._parse_level(data.get("level", "")),- "source_file": str(fpath),- },- )- )- except Exception:- continue- return out-- def load_dataset(self, bench_cfg: dict[str, Any], args: Any) -> list[Problem]:- import pandas as pd-- dataroot = getattr(args, "dataroot", None)- if dataroot:- if dataroot.endswith(".parquet"):- df = pd.read_parquet(dataroot)- return self._df_to_problems(df, dataroot)- return self._load_from_local(dataroot)-- dataset_cfg = bench_cfg.get("dataset", {})- parquet_url = dataset_cfg.get("parquet_url", _HF_PARQUET_URL)- cache_dir = Path(__file__).resolve().parents[1] / "data"- cache_file = cache_dir / "competition_math.parquet"- if cache_file.exists():- df = pd.read_parquet(cache_file)- else:- df = pd.read_parquet(parquet_url)- cache_dir.mkdir(parents=True, exist_ok=True)- df.to_parquet(cache_file, index=False)-- df = df[df["level"] != "Level ?"].reset_index(drop=True)- return self._df_to_problems(df, "competition_math")-- def filter_problems(- self,- problems: list[Problem],- bench_cfg: dict[str, Any],- args: Any,- ) -> list[Problem]:- filter_cfg = bench_cfg.get("filter", {})- subjects = getattr(args, "subjects", None) or filter_cfg.get("subjects")- levels = getattr(args, "levels", None) or filter_cfg.get("levels")- limit = args.limit or filter_cfg.get("limit")- seed = getattr(args, "seed", filter_cfg.get("seed", 42))- sequential = getattr(args, "sequential", False)-- filtered = problems- if subjects:- subj_set = set(subjects)- filtered = [p for p in filtered if p.metadata.get("subject") in subj_set]- if levels:- level_set = {int(v) for v in levels}- filtered = [p for p in filtered if p.metadata.get("level") in level_set]- return apply_limit(filtered, limit, seed, sequential)-- def _extract_from_solution(self, text: str) -> str | None:- matches = re.findall(r"\\boxed\{([^{}]+)\}", text, flags=re.DOTALL)- if matches:- return matches[-1].strip()- return None-- def extract_fallback(self, model_output: str) -> str | None:- boxed = self._extract_from_solution(model_output)- if boxed:- return boxed- text = model_output.strip()- return text.splitlines()[-1].strip() if text else None-- def judge_fallback(self, problem: Problem, extracted: str | None) -> tuple[bool, str]:- if not extracted:- return False, "No extracted answer"- return is_equiv(extracted, problem.ground_truth), "math equivalence fallback"diff --git a/benchmark/iso_solve/eval/scorers/__init__.py b/benchmark/iso_solve/eval/scorers/__init__.pydeleted file mode 100644index a593d4d2c..000000000--- a/benchmark/iso_solve/eval/scorers/__init__.py+++ /dev/null@@ -1,3 +0,0 @@-from .gaia_scorer import question_scorer--__all__ = ["question_scorer"]diff --git a/benchmark/iso_solve/eval/scorers/gaia_scorer.py b/benchmark/iso_solve/eval/scorers/gaia_scorer.pydeleted file mode 100644index f10bd7a64..000000000--- a/benchmark/iso_solve/eval/scorers/gaia_scorer.py+++ /dev/null@@ -1,68 +0,0 @@-from __future__ import annotations--import re-import string-import warnings---def normalize_number_str(number_str: str) -> float:- for char in ["$", "%", ","]:- number_str = number_str.replace(char, "")- try:- return float(number_str)- except ValueError:- return float("inf")---def split_string(s: str, char_list: list[str] = [",", ";"]) -> list[str]:- pattern = f"[{''.join(char_list)}]"- return re.split(pattern, s)---def normalize_str(input_str: str, remove_punct: bool = True) -> str:- no_spaces = re.sub(r"\s", "", input_str)- if remove_punct:- translator = str.maketrans("", "", string.punctuation)- return no_spaces.lower().translate(translator)- return no_spaces.lower()---def question_scorer(model_answer: str, ground_truth: str) -> bool:- def _is_float(element: object) -> bool:- try:- float(element)- return True- except (ValueError, TypeError):- return False-- if model_answer is None:- model_answer = "None"-- if _is_float(ground_truth):- normalized_answer = normalize_number_str(model_answer)- return normalized_answer == float(ground_truth)-- if any(char in ground_truth for char in [",", ";"]):- gt_elems = split_string(ground_truth)- ma_elems = split_string(model_answer)-- if len(gt_elems) != len(ma_elems):- warnings.warn(- "Answer lists have different lengths, returning False.",- UserWarning,- stacklevel=2,- )- return False-- comparisons = []- for ma_elem, gt_elem in zip(ma_elems, gt_elems):- if _is_float(gt_elem):- comparisons.append(normalize_number_str(ma_elem) == float(gt_elem))- else:- comparisons.append(- normalize_str(ma_elem, remove_punct=False)- == normalize_str(gt_elem, remove_punct=False)- )- return all(comparisons)-- return normalize_str(model_answer) == normalize_str(ground_truth)diff --git a/benchmark/iso_solve/eval/scorers/math_equivalence/__init__.py b/benchmark/iso_solve/eval/scorers/math_equivalence/__init__.pydeleted file mode 100644index 8d5e4f1e8..000000000--- a/benchmark/iso_solve/eval/scorers/math_equivalence/__init__.py+++ /dev/null@@ -1,13 +0,0 @@-from __future__ import annotations---def is_equiv(a: str | None, b: str | None) -> bool:- """Lightweight fallback equivalence check.-- The old benchmark used an external math_equivalence package. The unified- runner is LLM-first, so this function is only used as a deterministic- fallback when needed.- """- if a is None or b is None:- return False- return a.strip().lower() == b.strip().lower()diff --git a/benchmark/iso_solve/eval/super_gpqa.py b/benchmark/iso_solve/eval/super_gpqa.pydeleted file mode 100644index bd4cae593..000000000--- a/benchmark/iso_solve/eval/super_gpqa.py+++ /dev/null@@ -1,145 +0,0 @@-from __future__ import annotations--import re-from typing import Any--from .base import BenchmarkAdapter, apply_limit-from benchmark.iso_solve.core.types import Problem--CHOICE_LABELS = list("ABCDEFGHIJ")--SUPER_GPQA_SYSTEM_PROMPT = (- "You are an expert answering a graduate-level multiple-choice question. "- "Think step-by-step, then finish your response with the line:\n"- "Answer: X\n"- "where X is exactly one of the option letters (e.g. A, B, C, D, ...)."-)---class SuperGPQAAdapter(BenchmarkAdapter):- @property- def name(self) -> str:- return "super_gpqa"-- @property- def breakdown_keys(self) -> list[str]:- return ["discipline", "field", "difficulty"]-- @property- def extract_hint(self) -> str:- return "The final answer must be exactly one option letter such as A, B, C, D, etc."-- @property- def judge_hint(self) -> str:- return "This is a multiple-choice question. Compare only the final letter answer."-- def load_dataset(self, bench_cfg: dict[str, Any], args: Any) -> list[Problem]:- import polars as pl-- dataset_url = bench_cfg.get(- "dataset_url",- "hf://datasets/m-a-p/SuperGPQA/SuperGPQA-all.jsonl",- )- df = pl.read_ndjson(dataset_url)-- problems: list[Problem] = []- for row in df.iter_rows(named=True):- options: list[str] = row["options"]- formatted = "\n".join(- f"{CHOICE_LABELS[i]}. {opt}" for i, opt in enumerate(options)- )- q = f"{row['question']}\n\n{formatted}"-- answer_letter = row.get("answer_letter", "").strip()-- problems.append(- Problem(- id=row.get("uuid", ""),- question=q,- ground_truth=answer_letter,- benchmark="super_gpqa",- system_prompt=SUPER_GPQA_SYSTEM_PROMPT,- metadata={- "discipline": row.get("discipline", "Unknown"),- "field": row.get("field", "Unknown"),- "subfield": row.get("subfield", "Unknown"),- "difficulty": row.get("difficulty", "Unknown"),- "is_calculation": row.get("is_calculation", False),- "num_options": len(options),- },- )- )- return problems-- def filter_problems(- self,- problems: list[Problem],- bench_cfg: dict[str, Any],- args: Any,- ) -> list[Problem]:- filter_cfg = bench_cfg.get("filter", {})- disciplines = getattr(args, "super_gpqa_disciplines", None) or filter_cfg.get("disciplines")- difficulties = getattr(args, "super_gpqa_difficulties", None) or filter_cfg.get("difficulties")- fields = filter_cfg.get("fields")- limit = args.limit or filter_cfg.get("limit")- seed = getattr(args, "seed", filter_cfg.get("seed", 42))- sequential = getattr(args, "sequential", False)-- filtered = problems- if disciplines:- disc_set = {d.lower() for d in disciplines}- filtered = [- p for p in filtered- if str(p.metadata.get("discipline", "")).lower() in disc_set- ]- if difficulties:- diff_set = {d.lower() for d in difficulties}- filtered = [- p for p in filtered- if str(p.metadata.get("difficulty", "")).lower() in diff_set- ]- if fields:- field_set = {f.lower() for f in fields}- filtered = [- p for p in filtered- if str(p.metadata.get("field", "")).lower() in field_set- ]-- return apply_limit(filtered, limit, seed, sequential)-- def build_pipeline_request(- self,- problem: Problem,- multimodal: bool = True, # noqa: ARG002- ) -> dict[str, Any]:- prompt = (- f"{problem.question}\n\n"- "Think carefully step-by-step. "- "Your final answer must be exactly one of the option letters."- )- return {"prompt": prompt, "image_url": None}-- def extract_fallback(self, model_output: str) -> str | None:- for line in reversed(model_output.splitlines()):- m = re.match(r"(?:Answer|answer|ANSWER)\s*[::]\s*([A-Ja-j])", line.strip())- if m:- return m.group(1).upper()- tail = model_output[-200:] if len(model_output) > 200 else model_output- m = re.search(r"\b([A-J])\b", tail)- if m:- return m.group(1).upper()- return None-- def judge_fallback(self, problem: Problem, extracted: str | None) -> tuple[bool, str]:- if extracted is None:- return False, "No extracted option letter"- correct = extracted.strip().upper() == problem.ground_truth.strip().upper()- return correct, "letter match fallback"-- def preview(self, problem: Problem) -> str:- return (- f"id={problem.id} "- f"discipline={problem.metadata.get('discipline', 'Unknown')} "- f"difficulty={problem.metadata.get('difficulty', 'Unknown')} "- f"gt={problem.ground_truth} question={problem.question[:100]}"- )diff --git a/benchmark/iso_solve/get_llm_score.py b/benchmark/iso_solve/get_llm_score.pydeleted file mode 100644index 390194ef1..000000000--- a/benchmark/iso_solve/get_llm_score.py+++ /dev/null@@ -1,736 +0,0 @@-"""Multi-round LLM scoring for existing benchmark results.--Runs N rounds (default 5) of extract + judge on an existing results folder,-producing a per-round detailed report and an averaged final summary.--For benchmarks with breakdown keys (e.g. GAIA by level), per-group averages-are also reported.--Usage:- # Single directory- python -m benchmark.iso_solve.get_llm_score \- --results-dir benchmark/iso_solve/report_trace/gaia/direct/google_gemini-3-flash-preview_nitro_20260223_235651-- # Batch mode — score all dirs listed in a YAML file- python -m benchmark.iso_solve.get_llm_score \- --jobs benchmark/iso_solve/score_jobs.yaml-- # Custom rounds & concurrency- python -m benchmark.iso_solve.get_llm_score \- --results-dir benchmark/iso_solve/report_trace/hle/direct/anthropic_claude-sonnet-4.5_20260224_133043 \- --rounds 3 --concurrency 30-- # Override judge model- python -m benchmark.iso_solve.get_llm_score \- --results-dir benchmark/iso_solve/report_trace/aalcr/direct/openai_gpt-5-mini_20260223_185720-paper \- --judge-model openai/gpt-5.2:nitro-"""--from __future__ import annotations--import argparse-import asyncio-import json-import logging-import math-import os-import re-import sys-from pathlib import Path-from typing import Any--logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(levelname)-8s] %(message)s",- datefmt="%Y-%m-%d %H:%M:%S",-)-logger = logging.getLogger("get_llm_score")--_PROJECT_ROOT = Path(__file__).resolve().parents[2]-if str(_PROJECT_ROOT) not in sys.path:- sys.path.insert(0, str(_PROJECT_ROOT))--_RESULTS_DIR_MARKERS = ("results", "report_trace")---# ----------------------------------------------------------------------------# Helpers-# -----------------------------------------------------------------------------def _load_cases(results_dir: Path) -> list[dict]:- """Load all cases from outputs/ directory."""- outputs_dir = results_dir / "outputs"- cases = []- for subdir in sorted(outputs_dir.iterdir()):- if not subdir.is_dir():- continue- meta_path = subdir / "meta.json"- if not meta_path.exists():- continue- with open(meta_path, encoding="utf-8") as f:- meta = json.load(f)- output_path = subdir / "output.md"- if output_path.exists():- with open(output_path, encoding="utf-8") as f:- meta["_model_output"] = f.read()- else:- meta["_model_output"] = ""- meta["_subdir"] = subdir.name- cases.append(meta)- return cases---def _get_adapter(benchmark: str):- from benchmark.iso_solve.eval import ADAPTER_REGISTRY-- cls = ADAPTER_REGISTRY.get(benchmark)- if cls is None:- raise ValueError(f"Unknown benchmark: {benchmark}. Available: {list(ADAPTER_REGISTRY)}")- return cls()---def _find_marker_index(parts: tuple[str, ...]) -> int | None:- """Find the index of 'results' or 'report_trace' in path parts."""- for marker in _RESULTS_DIR_MARKERS:- try:- return parts.index(marker)- except ValueError:- continue- return None---def _detect_benchmark_from_path(results_dir: Path) -> str | None:- parts = results_dir.resolve().parts- idx = _find_marker_index(parts)- if idx is not None and idx + 1 < len(parts):- return parts[idx + 1]- return None---def _detect_benchmark_from_cases(cases: list[dict]) -> str | None:- for c in cases:- b = c.get("benchmark")- if b:- return b- return None---def _load_eval_cfg() -> dict[str, Any]:- import yaml-- cfg_path = Path("benchmark/iso_solve/config.yaml")- if cfg_path.exists():- with open(cfg_path) as f:- return yaml.safe_load(f) or {}- return {}---def _resolve_judge_model(cli_model: str | None) -> str:- if cli_model:- return cli_model- try:- cfg = _load_eval_cfg()- m = cfg.get("evaluation", {}).get("judge_model")- if m:- return m- except Exception:- pass- return os.getenv("LLM_MODEL", "qwen3.5-plus")---def _resolve_extract_model() -> str | None:- try:- cfg = _load_eval_cfg()- return cfg.get("evaluation", {}).get("extract_model") or None- except Exception:- return None---def _resolve_extract_max_tokens() -> int:- try:- cfg = _load_eval_cfg()- return cfg.get("evaluation", {}).get("extract_max_tokens", 16384)- except Exception:- return 16384---def _resolve_temperatures() -> tuple[float | None, float | None]:- try:- cfg = _load_eval_cfg()- ev = cfg.get("evaluation", {})- ext = ev.get("extract_temperature")- jdg = ev.get("judge_temperature")- return (float(ext) if ext is not None else None,- float(jdg) if jdg is not None else None)- except Exception:- return None, None---def _infer_report_meta(results_dir: Path, benchmark: str) -> dict:- mode = ""- parts = results_dir.resolve().parts- idx = _find_marker_index(parts)- if idx is not None and idx + 2 < len(parts):- mode = parts[idx + 2]-- model, timestamp = "", ""- m = re.match(r"(.+?)_(\d{8}_\d{6})", results_dir.name)- if m:- model = m.group(1)- timestamp = m.group(2)-- return {- "benchmark": benchmark,- "mode": mode,- "model": model,- "timestamp": timestamp,- }---# ----------------------------------------------------------------------------# Single-round scoring-# -----------------------------------------------------------------------------async def _score_one_case(- case: dict,- *,- skip_extract: bool,- extract_hint: str,- judge_hint: str,- extract_model: str | None,- judge_model: str | None,- extract_max_tokens: int,- judge_max_tokens: int,- extract_temperature: float | None,- judge_temperature: float | None,- adapter: Any,-) -> dict:- """Run extract + judge on a single case. Returns case dict with _new_* fields."""- from benchmark.iso_solve.core.extractor import extract_answer- from benchmark.iso_solve.core.judge import judge_answer-- extracted = case.get("extracted_answer")- if not skip_extract:- extracted = await extract_answer(- question=case["question"],- model_output=case["_model_output"],- extract_hint=extract_hint,- model=extract_model,- max_tokens=extract_max_tokens,- temperature=extract_temperature,- )- if extracted is None:- extracted = adapter.extract_fallback(case["_model_output"])- elif extracted is None:- extracted = case["_model_output"]-- correct, reasoning = await judge_answer(- question=case["question"],- predicted=extracted,- ground_truth=case["ground_truth"],- judge_hint=judge_hint,- model=judge_model,- max_tokens=judge_max_tokens,- temperature=judge_temperature,- )-- return {- **case,- "_new_extracted": extracted,- "_new_correct": correct,- "_new_reasoning": reasoning,- }---async def _run_one_round(- cases: list[dict],- *,- round_num: int,- total_rounds: int,- concurrency: int,- skip_extract: bool,- extract_hint: str,- judge_hint: str,- extract_model: str | None,- judge_model: str | None,- extract_max_tokens: int,- judge_max_tokens: int,- extract_temperature: float | None,- judge_temperature: float | None,- adapter: Any,-) -> list[dict]:- """Run one round of extract+judge on all cases."""- sem = asyncio.Semaphore(concurrency)- completed = 0- total = len(cases)-- async def _run(case: dict) -> dict:- nonlocal completed- async with sem:- result = await _score_one_case(- case,- skip_extract=skip_extract,- extract_hint=extract_hint,- judge_hint=judge_hint,- extract_model=extract_model,- judge_model=judge_model,- extract_max_tokens=extract_max_tokens,- judge_max_tokens=judge_max_tokens,- extract_temperature=extract_temperature,- judge_temperature=judge_temperature,- adapter=adapter,- )- completed += 1- status = "OK" if result["_new_correct"] else "WRONG"- if completed % 50 == 0 or completed == total:- logger.info(- " Round %d/%d [%d/%d] %s %s",- round_num, total_rounds, completed, total,- result.get("_subdir", ""), status,- )- return result-- results = await asyncio.gather(*[_run(c) for c in cases])- return list(results)---# ----------------------------------------------------------------------------# Report building-# -----------------------------------------------------------------------------def _build_round_report(- results: list[dict],- breakdown_keys: list[str],- meta_info: dict,- round_num: int,-) -> dict:- """Build a per-round report dict."""- correct_count = sum(1 for r in results if r["_new_correct"])- errors = sum(1 for r in results if r.get("error"))- total = len(results)-- acc = correct_count / total if total else 0.0- acc_pct = round(100.0 * acc, 2)- ci = round(1.96 * math.sqrt(acc_pct * (100 - acc_pct) / total), 2) if total else 0.0-- breakdowns: dict[str, dict[str, dict]] = {}- for r in results:- if r.get("error"):- continue- rmeta = r.get("metadata", {})- for key in breakdown_keys:- val = str(rmeta.get(key, ""))- if not val:- continue- bucket_name = f"by_{key}"- stats = breakdowns.setdefault(bucket_name, {}).setdefault(- val, {"total": 0, "correct": 0}- )- stats["total"] += 1- if r["_new_correct"]:- stats["correct"] += 1- for bucket in breakdowns.values():- for s in bucket.values():- s["accuracy"] = round(s["correct"] / s["total"], 4) if s["total"] else 0.0-- return {- **meta_info,- "round": round_num,- "overall": {- "total": total,- "correct": correct_count,- "accuracy": round(acc, 4),- "accuracy_pct": acc_pct,- "confidence_interval": ci,- "errors": errors,- },- "breakdowns": breakdowns,- "results": [- {- "id": r.get("id"),- "question": r.get("question", "")[:300],- "ground_truth": r.get("ground_truth", ""),- "extracted_answer": r.get("_new_extracted"),- "correct": r["_new_correct"],- "score": 1.0 if r["_new_correct"] else 0.0,- "judge_reasoning": r["_new_reasoning"][:400],- "error": r.get("error"),- "metadata": r.get("metadata", {}),- }- for r in results- ],- }---def _compute_averages(- round_reports: list[dict],- breakdown_keys: list[str],-) -> dict:- """Compute averaged scores across all rounds."""- n_rounds = len(round_reports)-- overall_accs = [rr["overall"]["accuracy_pct"] for rr in round_reports]- mean_acc = sum(overall_accs) / n_rounds- std_acc = math.sqrt(sum((a - mean_acc) ** 2 for a in overall_accs) / n_rounds) if n_rounds > 1 else 0.0-- avg_correct = sum(rr["overall"]["correct"] for rr in round_reports) / n_rounds- total = round_reports[0]["overall"]["total"]-- breakdown_avgs: dict[str, dict[str, dict]] = {}- for rr in round_reports:- for bucket_name, bucket in rr.get("breakdowns", {}).items():- for val, stats in bucket.items():- entry = breakdown_avgs.setdefault(bucket_name, {}).setdefault(- val, {"total": stats["total"], "accs": []}- )- acc_val = stats["correct"] / stats["total"] * 100 if stats["total"] else 0.0- entry["accs"].append(acc_val)-- breakdown_summary: dict[str, dict[str, dict]] = {}- for bucket_name, bucket in breakdown_avgs.items():- for val, entry in bucket.items():- accs = entry["accs"]- mean = sum(accs) / len(accs) if accs else 0.0- std = math.sqrt(sum((a - mean) ** 2 for a in accs) / len(accs)) if len(accs) > 1 else 0.0- breakdown_summary.setdefault(bucket_name, {})[val] = {- "total": entry["total"],- "mean_accuracy_pct": round(mean, 2),- "std_accuracy_pct": round(std, 2),- "per_round_accuracy_pct": [round(a, 2) for a in accs],- }-- per_question: dict[str, dict] = {}- for rr in round_reports:- for item in rr["results"]:- qid = item["id"]- entry = per_question.setdefault(qid, {- "id": qid,- "question": item["question"],- "ground_truth": item["ground_truth"],- "metadata": item["metadata"],- "rounds": [],- })- entry["rounds"].append({- "round": rr["round"],- "extracted_answer": item["extracted_answer"],- "correct": item["correct"],- "judge_reasoning": item["judge_reasoning"],- })-- for entry in per_question.values():- correct_rounds = sum(1 for rd in entry["rounds"] if rd["correct"])- entry["correct_rate"] = round(correct_rounds / n_rounds, 4)- entry["correct_count"] = correct_rounds-- return {- "n_rounds": n_rounds,- "total_questions": total,- "mean_correct": round(avg_correct, 2),- "mean_accuracy_pct": round(mean_acc, 2),- "std_accuracy_pct": round(std_acc, 2),- "per_round_accuracy_pct": [round(a, 2) for a in overall_accs],- "breakdowns": breakdown_summary,- "per_question": list(per_question.values()),- }---# ----------------------------------------------------------------------------# Output formatting-# -----------------------------------------------------------------------------def _format_summary(meta_info: dict, averages: dict) -> str:- lines = [- "=" * 70,- f"{meta_info['benchmark'].upper()} LLM Score — {averages['n_rounds']}-round average",- f"Model: {meta_info['model']}",- f"Mode: {meta_info['mode']}",- "=" * 70,- "",- f"Overall: {averages['mean_accuracy_pct']}% (+/- std {averages['std_accuracy_pct']}%)",- f" Total questions: {averages['total_questions']}",- f" Mean correct: {averages['mean_correct']}",- "",- "Per-round accuracy:",- ]- for i, acc in enumerate(averages["per_round_accuracy_pct"], 1):- lines.append(f" Round {i}: {acc}%")-- for bucket_name in sorted(averages.get("breakdowns", {})):- lines.append("")- lines.append(f"--- {bucket_name} ---")- bucket = averages["breakdowns"][bucket_name]- for val in sorted(bucket):- s = bucket[val]- lines.append(- f" {val:30s} n={s['total']:4d} "- f"mean={s['mean_accuracy_pct']:6.2f}% std={s['std_accuracy_pct']:5.2f}% "- f"rounds={s['per_round_accuracy_pct']}"- )-- lines.append("")- lines.append("=" * 70)-- unstable = [- q for q in averages["per_question"]- if 0 < q["correct_count"] < averages["n_rounds"]- ]- if unstable:- unstable.sort(key=lambda q: q["correct_rate"])- lines.append("")- lines.append(f"Unstable questions ({len(unstable)} / {averages['total_questions']}):")- lines.append("-" * 70)- for q in unstable:- verdicts = " ".join(- "OK" if rd["correct"] else "XX" for rd in q["rounds"]- )- lines.append(- f" {q['id'][:40]:40s} {q['correct_count']}/{averages['n_rounds']} [{verdicts}]"- )- lines.append("=" * 70)-- return "\n".join(lines)---# ----------------------------------------------------------------------------# Core: score a single results directory-# -----------------------------------------------------------------------------async def score_one_dir(- results_dir: Path,- *,- rounds: int = 5,- concurrency: int = 20,- judge_model_override: str | None = None,- judge_max_tokens: int = 16384,- output_dir: Path | None = None,-) -> dict:- """Score a single results directory. Returns the averages dict."""- cases = _load_cases(results_dir)- if not cases:- logger.error("No cases found in %s/outputs/ — skipping", results_dir)- return {}-- benchmark = (- _detect_benchmark_from_path(results_dir)- or _detect_benchmark_from_cases(cases)- )- if not benchmark:- logger.error("Cannot detect benchmark for %s — skipping", results_dir)- return {}-- adapter = _get_adapter(benchmark)- meta_info = _infer_report_meta(results_dir, benchmark)-- judge_model = _resolve_judge_model(judge_model_override)- extract_model = _resolve_extract_model()- extract_max_tokens = _resolve_extract_max_tokens()- extract_temperature, judge_temperature = _resolve_temperatures()-- label = f"{meta_info['benchmark']}/{meta_info['mode']}/{meta_info['model']}"- logger.info(- "[%s] Cases: %d | Rounds: %d | Judge: %s | Extract: %s | Concurrency: %d",- label, len(cases), rounds, judge_model,- extract_model or "(default)", concurrency,- )-- if output_dir:- out_dir = output_dir- else:- # Default: benchmark/iso_solve/report_trace/{benchmark}/{mode}/{run_name}/llm_score/- trace_base = Path("benchmark/iso_solve/report_trace")- run_name = results_dir.name- if meta_info["benchmark"] and meta_info["mode"]:- out_dir = trace_base / meta_info["benchmark"] / meta_info["mode"] / run_name / "llm_score"- else:- out_dir = results_dir / "llm_score"- out_dir.mkdir(parents=True, exist_ok=True)-- round_reports: list[dict] = []-- for round_num in range(1, rounds + 1):- logger.info("[%s] Round %d / %d", label, round_num, rounds)-- results = await _run_one_round(- cases,- round_num=round_num,- total_rounds=rounds,- concurrency=concurrency,- skip_extract=adapter.skip_extract,- extract_hint=adapter.extract_hint,- judge_hint=adapter.judge_hint,- extract_model=extract_model,- judge_model=judge_model,- extract_max_tokens=extract_max_tokens,- judge_max_tokens=judge_max_tokens,- extract_temperature=extract_temperature,- judge_temperature=judge_temperature,- adapter=adapter,- )-- report = _build_round_report(- results, adapter.breakdown_keys, meta_info, round_num,- )- round_reports.append(report)-- correct = report["overall"]["correct"]- total = report["overall"]["total"]- acc = report["overall"]["accuracy_pct"]- logger.info(- "[%s] Round %d result: %d/%d = %.2f%%", label, round_num, correct, total, acc,- )-- round_path = out_dir / f"round_{round_num}.json"- with open(round_path, "w", encoding="utf-8") as f:- json.dump(report, f, ensure_ascii=False, indent=2)-- averages = _compute_averages(round_reports, adapter.breakdown_keys)-- avg_path = out_dir / "average.json"- with open(avg_path, "w", encoding="utf-8") as f:- json.dump({**meta_info, "averages": averages}, f, ensure_ascii=False, indent=2)-- summary_text = _format_summary(meta_info, averages)-- summary_path = out_dir / "summary.txt"- with open(summary_path, "w", encoding="utf-8") as f:- f.write(summary_text)-- print()- print(summary_text)-- return {**meta_info, "averages": averages}---# ----------------------------------------------------------------------------# Batch mode-# -----------------------------------------------------------------------------def _load_jobs(jobs_path: Path) -> tuple[dict, list[dict]]:- """Load score_jobs.yaml. Returns (defaults, jobs)."""- import yaml-- with open(jobs_path, encoding="utf-8") as f:- data = yaml.safe_load(f) or {}-- defaults = data.get("defaults", {})- jobs = data.get("jobs", [])- if not jobs:- raise ValueError(f"No jobs defined in {jobs_path}")- return defaults, jobs---async def _run_batch(- jobs_path: Path,- *,- cli_rounds: int | None,- cli_concurrency: int | None,- cli_judge_model: str | None,- cli_judge_max_tokens: int,-) -> None:- """Run all jobs from a YAML file sequentially."""- defaults, jobs = _load_jobs(jobs_path)-- total_jobs = len(jobs)- logger.info("Loaded %d jobs from %s", total_jobs, jobs_path)-- all_summaries: list[str] = []-- for i, job in enumerate(jobs, 1):- results_dir = Path(job["results_dir"])- if not results_dir.exists():- logger.error("[%d/%d] Directory not found: %s — skipping", i, total_jobs, results_dir)- continue-- rounds = cli_rounds or job.get("rounds") or defaults.get("rounds", 5)- concurrency = cli_concurrency or job.get("concurrency") or defaults.get("concurrency", 20)- judge_model = cli_judge_model or job.get("judge_model")- judge_max_tokens = job.get("judge_max_tokens", cli_judge_max_tokens)- output_dir = Path(job["output"]) if job.get("output") else None-- logger.info(- "=" * 70 + "\n" +- f" Job {i}/{total_jobs}: {results_dir}\n" +- f" rounds={rounds} concurrency={concurrency}\n" +- "=" * 70,- )-- result = await score_one_dir(- results_dir,- rounds=rounds,- concurrency=concurrency,- judge_model_override=judge_model,- judge_max_tokens=judge_max_tokens,- output_dir=output_dir,- )-- if result and "averages" in result:- avg = result["averages"]- bm = result.get("benchmark", "?")- mode = result.get("mode", "?")- model = result.get("model", "?")- all_summaries.append(- f" {bm:12s} {mode:10s} {model:50s} "- f"{avg['mean_accuracy_pct']:6.2f}% +/- {avg['std_accuracy_pct']:.2f}%"- )-- if all_summaries:- print()- print("=" * 70)- print(" BATCH SUMMARY")- print("=" * 70)- print(f" {'Benchmark':12s} {'Mode':10s} {'Model':50s} {'Score':>14s}")- print("-" * 70)- for line in all_summaries:- print(line)- print("=" * 70)---# ----------------------------------------------------------------------------# Main-# -----------------------------------------------------------------------------async def main():- from dotenv import load_dotenv- load_dotenv(_PROJECT_ROOT / "DeepTutor.env", override=False)- load_dotenv(_PROJECT_ROOT / ".env", override=False)-- parser = argparse.ArgumentParser(- description="Multi-round LLM scoring for existing benchmark results",- )- group = parser.add_mutually_exclusive_group(required=True)- group.add_argument("--results-dir", help="Path to a single results folder")- group.add_argument("--jobs", help="Path to score_jobs.yaml for batch scoring")-- parser.add_argument("--rounds", type=int, default=None, help="Number of extract+judge rounds (default: 5)")- parser.add_argument("--concurrency", type=int, default=None, help="Parallel LLM requests per round")- parser.add_argument("--judge-model", default=None, help="Override judge model")- parser.add_argument("--judge-max-tokens", type=int, default=16384, help="Max tokens for judge")- parser.add_argument("--output", default=None, help="Output directory (default: <results-dir>/llm_score/)")- args = parser.parse_args()-- if args.jobs:- await _run_batch(- Path(args.jobs),- cli_rounds=args.rounds,- cli_concurrency=args.concurrency,- cli_judge_model=args.judge_model,- cli_judge_max_tokens=args.judge_max_tokens,- )- else:- results_dir = Path(args.results_dir)- if not results_dir.exists():- logger.error("Results directory not found: %s", results_dir)- sys.exit(1)-- await score_one_dir(- results_dir,- rounds=args.rounds or 5,- concurrency=args.concurrency or 20,- judge_model_override=args.judge_model,- judge_max_tokens=args.judge_max_tokens,- output_dir=Path(args.output) if args.output else None,- )---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/iso_solve/multimodal.py b/benchmark/iso_solve/multimodal.pydeleted file mode 100644index 6456363aa..000000000--- a/benchmark/iso_solve/multimodal.py+++ /dev/null@@ -1,417 +0,0 @@-# -*- coding: utf-8 -*--"""-Shared multimodal utilities for benchmark evaluation.--Provides a unified pipeline for processing file attachments (images,-documents, spreadsheets, text) and building OpenAI-compatible multimodal-messages. Used by GAIA, HLE, and any future benchmark that may include-multimodal questions.--Design principles:- - If the configured model supports multimodal input, images are encoded- as base64 data URIs and sent via the ``image_url`` content type.- - If the model does NOT support multimodal, images are described as- text placeholders so the run still proceeds (text-only mode).- - Non-image files (xlsx, csv, pdf, docx, txt, py, …) are always read- as text and injected directly into the prompt.- - Every attachment processing step is logged so the user can verify- exactly what was sent to the LLM.-"""--from __future__ import annotations--import base64-import logging-import mimetypes-import os-from dataclasses import dataclass, field-from typing import Any--logger = logging.getLogger("benchmark.multimodal")--# -------------------------------------------------------------------# Supported file categories-# --------------------------------------------------------------------IMAGE_EXTENSIONS = frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"})-TEXT_EXTENSIONS = frozenset({".txt", ".py", ".csv", ".json", ".jsonld", ".md", ".html", ".xml", ".yaml", ".yml"})-SPREADSHEET_EXTENSIONS = frozenset({".xlsx", ".xls"})-DOCUMENT_EXTENSIONS = frozenset({".pdf", ".docx", ".pptx"})--MAX_TEXT_CHARS = 50_000---# -------------------------------------------------------------------# Data structures-# --------------------------------------------------------------------@dataclass-class AttachmentResult:- """Result of processing a single file attachment."""- file_path: str- file_name: str- file_type: str # e.g. "image", "spreadsheet", "document", "text", "audio", "unknown"- extension: str # e.g. ".png"- strategy: str # e.g. "image_multimodal", "image_text_fallback", "text_injected", ...- text_content: str | None = None # text injected into prompt (for non-image files)- image_data_uri: str | None = None # base64 data URI (for images in multimodal mode)- success: bool = True- error: str | None = None-- def to_dict(self) -> dict[str, Any]:- return {- "file_name": self.file_name,- "file_type": self.file_type,- "extension": self.extension,- "strategy": self.strategy,- "has_text_content": self.text_content is not None,- "text_content_length": len(self.text_content) if self.text_content else 0,- "has_image_data": self.image_data_uri is not None,- "success": self.success,- "error": self.error,- }---@dataclass-class MultimodalContext:- """Aggregated multimodal context for a single problem."""- text_parts: list[str] = field(default_factory=list)- image_data_uris: list[str] = field(default_factory=list)- attachments: list[AttachmentResult] = field(default_factory=list)-- @property- def has_images(self) -> bool:- return len(self.image_data_uris) > 0-- @property- def n_images(self) -> int:- return len(self.image_data_uris)-- @property- def extra_text(self) -> str:- """Concatenated text from all attachments (for prompt injection)."""- return "\n\n".join(self.text_parts)-- def summary_label(self) -> str:- """Short human-readable label for logging."""- parts = []- for a in self.attachments:- parts.append(f"{a.file_name}→{a.strategy}")- return ", ".join(parts) if parts else "no_attachments"-- def to_metadata(self) -> list[dict[str, Any]]:- return [a.to_dict() for a in self.attachments]---# -------------------------------------------------------------------# File readers-# --------------------------------------------------------------------def _encode_image_base64(path: str) -> str:- """Read an image file and return a ``data:`` URI with base64 content."""- mime = mimetypes.guess_type(path)[0] or "image/png"- with open(path, "rb") as f:- data = base64.b64encode(f.read()).decode("utf-8")- return f"data:{mime};base64,{data}"---def _read_text_file(path: str, max_chars: int = MAX_TEXT_CHARS) -> str | None:- try:- with open(path, "r", encoding="utf-8", errors="replace") as f:- return f.read(max_chars)- except (IOError, OSError):- return None---def _read_spreadsheet(path: str) -> str | None:- ext = os.path.splitext(path)[1].lower()- try:- if ext == ".csv":- return _read_text_file(path)- import openpyxl- wb = openpyxl.load_workbook(path, read_only=True, data_only=True)- lines: list[str] = []- for sheet_name in wb.sheetnames:- ws = wb[sheet_name]- lines.append(f"=== Sheet: {sheet_name} ===")- row_count = 0- for row in ws.iter_rows(values_only=True):- lines.append("\t".join(str(c) if c is not None else "" for c in row))- row_count += 1- if row_count > 2000:- lines.append("... (truncated)")- break- wb.close()- return "\n".join(lines)- except ImportError:- logger.warning("openpyxl not installed — cannot read .xlsx files; pip install openpyxl")- return None- except Exception as exc:- logger.debug("Failed to read spreadsheet %s: %s", path, exc)- return None---def _read_document(path: str) -> str | None:- ext = os.path.splitext(path)[1].lower()- try:- if ext == ".pdf":- return _read_pdf(path)- if ext == ".docx":- return _read_docx(path)- if ext == ".pptx":- return _read_pptx(path)- except Exception as exc:- logger.debug("Failed to read document %s: %s", path, exc)- return None---def _read_pdf(path: str) -> str | None:- for reader_fn in [_read_pdf_pdfplumber, _read_pdf_pypdf]:- result = reader_fn(path)- if result:- return result- logger.warning("No PDF reader available (install pdfplumber or PyPDF2)")- return None---def _read_pdf_pdfplumber(path: str) -> str | None:- try:- import pdfplumber- with pdfplumber.open(path) as pdf:- pages = [p.extract_text() or "" for p in pdf.pages]- text = "\n\n".join(pages)- return text[:MAX_TEXT_CHARS] if text.strip() else None- except ImportError:- return None---def _read_pdf_pypdf(path: str) -> str | None:- try:- from PyPDF2 import PdfReader- reader = PdfReader(path)- pages = [p.extract_text() or "" for p in reader.pages]- text = "\n\n".join(pages)- return text[:MAX_TEXT_CHARS] if text.strip() else None- except ImportError:- return None---def _read_docx(path: str) -> str | None:- try:- import docx- doc = docx.Document(path)- text = "\n".join(p.text for p in doc.paragraphs)- return text[:MAX_TEXT_CHARS] if text.strip() else None- except ImportError:- logger.warning("python-docx not installed — cannot read .docx files")- return None---def _read_pptx(path: str) -> str | None:- try:- from pptx import Presentation- prs = Presentation(path)- texts: list[str] = []- for slide in prs.slides:- for shape in slide.shapes:- if shape.has_text_frame:- texts.append(shape.text)- text = "\n".join(texts)- return text[:MAX_TEXT_CHARS] if text.strip() else None- except ImportError:- logger.warning("python-pptx not installed — cannot read .pptx files")- return None---# -------------------------------------------------------------------# Core: process a single file attachment-# --------------------------------------------------------------------def process_attachment(- file_path: str,- file_name: str | None = None,- multimodal: bool = True,-) -> AttachmentResult:- """Process one file attachment and return an ``AttachmentResult``.-- Args:- file_path: Absolute path to the file on disk.- file_name: Human-readable file name (defaults to basename).- multimodal: If True and file is an image, encode as base64 data URI.- If False, images produce a text placeholder instead.- """- fname = file_name or os.path.basename(file_path)- ext = os.path.splitext(file_path)[1].lower()-- if not os.path.exists(file_path):- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="missing",- extension=ext, strategy="file_not_found", success=False,- error=f"File does not exist: {file_path}",- )-- # --- Images ---- if ext in IMAGE_EXTENSIONS:- if multimodal:- try:- data_uri = _encode_image_base64(file_path)- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="image",- extension=ext, strategy="image_multimodal",- image_data_uri=data_uri,- )- except Exception as exc:- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="image",- extension=ext, strategy="image_encode_failed",- text_content=f"[Image file: {fname} — failed to encode: {exc}]",- success=False, error=str(exc),- )- else:- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="image",- extension=ext, strategy="image_text_fallback",- text_content=f"[Image file: {fname} — image content not available in text-only mode]",- )-- # --- Text files ---- if ext in TEXT_EXTENSIONS:- content = _read_text_file(file_path)- if content:- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="text",- extension=ext, strategy="text_injected",- text_content=f"[Content of {fname}]:\n{content}",- )- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="text",- extension=ext, strategy="text_read_failed",- text_content=f"[Could not read file: {fname}]",- success=False, error="Read failed",- )-- # --- Spreadsheets ---- if ext in SPREADSHEET_EXTENSIONS or ext == ".csv":- content = _read_spreadsheet(file_path)- if content:- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="spreadsheet",- extension=ext, strategy="spreadsheet_injected",- text_content=f"[Spreadsheet content of {fname}]:\n{content}",- )- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="spreadsheet",- extension=ext, strategy="spreadsheet_read_failed",- text_content=f"[Could not read spreadsheet: {fname}]",- success=False, error="Spreadsheet read failed",- )-- # --- Documents (PDF, DOCX, PPTX) ---- if ext in DOCUMENT_EXTENSIONS:- content = _read_document(file_path)- if content:- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="document",- extension=ext, strategy="document_injected",- text_content=f"[Document content of {fname}]:\n{content}",- )- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="document",- extension=ext, strategy="document_read_failed",- text_content=f"[Could not extract text from: {fname}]",- success=False, error="Document extraction failed",- )-- # --- Unsupported / unknown ---- return AttachmentResult(- file_path=file_path, file_name=fname, file_type="unsupported",- extension=ext, strategy="unsupported_type",- text_content=f"[Attached file: {fname} (type {ext} — content not extracted)]",- )---# -------------------------------------------------------------------# Core: build multimodal context from one or more attachments-# --------------------------------------------------------------------def build_multimodal_context(- file_paths: list[tuple[str, str | None]],- multimodal: bool = True,-) -> MultimodalContext:- """Process a list of ``(file_path, file_name)`` pairs and return a- :class:`MultimodalContext` that aggregates text and image content.-- Args:- file_paths: List of ``(absolute_path, display_name_or_None)`` tuples.- multimodal: Whether images should be encoded as base64 data URIs.- """- ctx = MultimodalContext()- for fpath, fname in file_paths:- result = process_attachment(fpath, fname, multimodal=multimodal)- ctx.attachments.append(result)-- if result.text_content:- ctx.text_parts.append(result.text_content)- if result.image_data_uri:- ctx.image_data_uris.append(result.image_data_uri)-- logger.info(- " Attachment: %s → %s%s",- result.file_name,- result.strategy,- f" (error: {result.error})" if result.error else "",- )-- return ctx---# -------------------------------------------------------------------# Core: build OpenAI-compatible messages-# --------------------------------------------------------------------def build_messages(- system_prompt: str,- user_text: str,- image_data_uris: list[str] | None = None,-) -> list[dict[str, Any]]:- """Build an OpenAI-compatible message array.-- When *image_data_uris* is provided, the user message uses the- ``content`` list format (text + image_url entries). Otherwise a- plain string ``content`` is used.- """- if image_data_uris:- content: list[dict[str, Any]] = [{"type": "text", "text": user_text}]- for uri in image_data_uris:- content.append({"type": "image_url", "image_url": {"url": uri}})- return [- {"role": "system", "content": system_prompt},- {"role": "user", "content": content},- ]-- return [- {"role": "system", "content": system_prompt},- {"role": "user", "content": user_text},- ]---# -------------------------------------------------------------------# Convenience: log a summary of multimodal processing for a problem-# --------------------------------------------------------------------def log_multimodal_summary(- problem_label: str,- ctx: MultimodalContext,- logger_instance: logging.Logger | None = None,-) -> None:- """Log a concise summary of what multimodal content was used."""- log = logger_instance or logger- if not ctx.attachments:- return- for a in ctx.attachments:- tag = "MULTIMODAL" if a.image_data_uri else "TEXT"- status = "OK" if a.success else "FAIL"- log.info(- " [%s] %s | %s | strategy=%s | %s",- problem_label, tag, a.file_name, a.strategy, status,- )diff --git a/benchmark/iso_solve/rejudge.py b/benchmark/iso_solve/rejudge.pydeleted file mode 100644index ac36955d7..000000000--- a/benchmark/iso_solve/rejudge.py+++ /dev/null@@ -1,1014 +0,0 @@-"""Re-judge / re-score existing benchmark results.--Modes:- (default) Dry-run re-judge: show flipped verdicts without writing.- --overwrite Re-judge and overwrite flipped meta.json / report / summary.- --rescore Full re-score with retry:- 1) Detect incomplete cases (no solver output)- 2) Re-run solver for those cases (loop until done or max rounds)- 3) Extract + judge ALL cases- 4) Rebuild report.json + summary.txt from scratch--Usage:- # Default (dry-run comparison)- python -m benchmark.iso_solve.rejudge \- --results-dir benchmark/iso_solve/results/aalcr/pipeline/qwen3.5-plus_20260223_131936-- # Overwrite flipped verdicts in-place- python -m benchmark.iso_solve.rejudge \- --results-dir benchmark/iso_solve/results/aalcr/pipeline/qwen3.5-plus_20260223_131936 \- --overwrite-- # Full re-score with retry (handles incomplete runs)- python -m benchmark.iso_solve.rejudge \- --results-dir benchmark/iso_solve/results/gaia/pipeline/run_20260223 \- --rescore --max-solve-rounds 3-"""--from __future__ import annotations--import argparse-import asyncio-import json-import logging-import math-import os-import re-import sys-from pathlib import Path-from typing import Any--logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(levelname)-8s] %(message)s",- datefmt="%Y-%m-%d %H:%M:%S",-)-logger = logging.getLogger("rejudge")--_PROJECT_ROOT = Path(__file__).resolve().parents[2]-if str(_PROJECT_ROOT) not in sys.path:- sys.path.insert(0, str(_PROJECT_ROOT))---# ----------------------------------------------------------------------------# Helpers-# -----------------------------------------------------------------------------def _load_cases(results_dir: Path) -> list[dict]:- outputs_dir = results_dir / "outputs"- cases = []- for subdir in sorted(outputs_dir.iterdir()):- if not subdir.is_dir():- continue- meta_path = subdir / "meta.json"- if not meta_path.exists():- continue- with open(meta_path, encoding="utf-8") as f:- meta = json.load(f)- output_path = subdir / "output.md"- if output_path.exists():- with open(output_path, encoding="utf-8") as f:- meta["_model_output"] = f.read()- else:- meta["_model_output"] = ""- meta["_subdir"] = subdir.name- cases.append(meta)- return cases---def _get_adapter(benchmark: str):- from benchmark.iso_solve.eval.aalcr import AALCRAdapter- from benchmark.iso_solve.eval.gaia import GAIAAdapter- from benchmark.iso_solve.eval.gpqa import GPQAAdapter- from benchmark.iso_solve.eval.hle import HLEAdapter- from benchmark.iso_solve.eval.math import MathAdapter as MATHAdapter- from benchmark.iso_solve.eval.aime25 import AIME25Adapter- from benchmark.iso_solve.eval.livebench import LiveBenchAdapter- from benchmark.iso_solve.eval.super_gpqa import SuperGPQAAdapter-- adapters = {- "aalcr": AALCRAdapter,- "gaia": GAIAAdapter,- "gpqa": GPQAAdapter,- "hle": HLEAdapter,- "math": MATHAdapter,- "aime25": AIME25Adapter,- "livebench": LiveBenchAdapter,- "super_gpqa": SuperGPQAAdapter,- }- cls = adapters.get(benchmark)- if cls is None:- raise ValueError(f"Unknown benchmark: {benchmark}. Available: {list(adapters)}")- return cls()---def _detect_benchmark(cases: list[dict]) -> str | None:- for c in cases:- b = c.get("benchmark")- if b:- return b- return None---def _detect_benchmark_from_path(results_dir: Path) -> str | None:- """Infer benchmark name from results/{benchmark}/{mode}/..."""- parts = results_dir.resolve().parts- try:- idx = parts.index("results")- if idx + 1 < len(parts):- return parts[idx + 1]- except ValueError:- pass- return None---def _load_eval_cfg() -> dict[str, Any]:- import yaml- cfg_path = Path("benchmark/iso_solve/config.yaml")- if cfg_path.exists():- with open(cfg_path) as f:- return yaml.safe_load(f) or {}- return {}---def _resolve_judge_model(cli_model: str | None) -> str:- if cli_model:- return cli_model- try:- cfg = _load_eval_cfg()- m = cfg.get("evaluation", {}).get("judge_model")- if m:- return m- except Exception:- pass- return os.getenv("LLM_MODEL", "qwen3.5-plus")---def _resolve_extract_model() -> str | None:- try:- cfg = _load_eval_cfg()- return cfg.get("evaluation", {}).get("extract_model") or None- except Exception:- return None---def _resolve_temperatures() -> tuple[float | None, float | None]:- try:- cfg = _load_eval_cfg()- ev = cfg.get("evaluation", {})- ext = ev.get("extract_temperature")- jdg = ev.get("judge_temperature")- return (float(ext) if ext is not None else None,- float(jdg) if jdg is not None else None)- except Exception:- return None, None---async def _rejudge_one(- case: dict,- judge_hint: str,- judge_model: str | None,- api_key: str | None,- base_url: str | None,- judge_max_tokens: int,- judge_temperature: float | None = None,-) -> tuple[bool, str]:- from benchmark.iso_solve.core.judge import judge_answer-- extracted = case.get("extracted_answer") or case.get("_model_output", "")- correct, reasoning = await judge_answer(- question=case["question"],- predicted=extracted,- ground_truth=case["ground_truth"],- judge_hint=judge_hint,- model=judge_model,- api_key=api_key,- base_url=base_url,- max_tokens=judge_max_tokens,- temperature=judge_temperature,- )- return correct, reasoning---def _find_model_output(subdir: Path) -> str | None:- """Find model output from solve_*/final_answer.md or standalone output.md."""- for child in sorted(subdir.iterdir(), reverse=True):- if child.is_dir() and child.name.startswith("solve_"):- fa = child / "final_answer.md"- if fa.exists():- with open(fa, encoding="utf-8") as f:- content = f.read()- if content.strip():- return content- output_md = subdir / "output.md"- if output_md.exists() and not (subdir / "meta.json").exists():- with open(output_md, encoding="utf-8") as f:- content = f.read()- if content.strip():- return content- return None---def _detect_mode_from_path(results_dir: Path) -> str:- parts = results_dir.resolve().parts- try:- idx = parts.index("results")- if idx + 2 < len(parts):- return parts[idx + 2]- except ValueError:- pass- return "pipeline"---def _resolve_llm_runtime(bench_cfg: dict) -> dict[str, Any]:- model_name = bench_cfg.get("llm", {}).get("model")- api_key, base_url = None, None- try:- from src.services.llm.config import get_llm_config- llm_cfg = get_llm_config()- model_name = model_name or llm_cfg.model or "unknown"- api_key = llm_cfg.api_key- base_url = llm_cfg.base_url- except Exception:- model_name = model_name or os.getenv("LLM_MODEL", "unknown")- return {"model_name": model_name or "unknown", "api_key": api_key, "base_url": base_url}---async def _solve_one(- problem: Any,- workspace: str,- adapter: Any,- mode: str,- bench_cfg: dict,- model: str | None,- api_key: str | None,- base_url: str | None,-) -> str:- """Run solver for a single problem. Returns model output text."""- if mode == "pipeline":- from benchmark.iso_solve.core.pipeline import run_solver_pipeline-- pipeline_cfg = bench_cfg.get("pipeline", {})- llm_cfg = bench_cfg.get("llm", {})- pipeline_model = pipeline_cfg.get("model") or model- multimodal = llm_cfg.get("multimodal", True)- max_tokens = pipeline_cfg.get("max_tokens") or llm_cfg.get("max_tokens")- temperature = pipeline_cfg.get("temperature")- if temperature is None:- temperature = llm_cfg.get("temperature")-- req = adapter.build_pipeline_request(problem, multimodal=multimodal)- result = await run_solver_pipeline(- question=req.get("prompt", problem.question),- workspace=workspace,- language=pipeline_cfg.get("language", "en"),- tools=pipeline_cfg.get("tools"),- model=pipeline_model,- image_url=req.get("image_url"),- max_tokens=max_tokens,- temperature=temperature,- )- return result.get("final_answer", "")- else:- from src.services.llm import complete-- llm_cfg = bench_cfg.get("llm", {})- multimodal = llm_cfg.get("multimodal", True)- req = adapter.build_direct_request(problem, multimodal=multimodal)- kwargs: dict[str, Any] = {- "temperature": llm_cfg.get("temperature", 0.0),- "max_tokens": llm_cfg.get("max_tokens", 4096),- }- if "messages" in req:- kwargs["prompt"] = ""- kwargs["messages"] = req["messages"]- else:- kwargs["prompt"] = req.get("prompt", problem.question)- kwargs["system_prompt"] = req.get("system_prompt", problem.system_prompt)- if model:- kwargs["model"] = model- if api_key:- kwargs["api_key"] = api_key- if base_url:- kwargs["base_url"] = base_url- return await complete(**kwargs)---def _find_incomplete_indices(- outputs_dir: Path,- problems_by_index: dict[str, Any],-) -> list[str]:- """Find indices of cases that have no usable solver output or had errors."""- incomplete = []- for idx_str in sorted(problems_by_index.keys()):- subdir = outputs_dir / idx_str- if not subdir.exists():- incomplete.append(idx_str)- continue- meta_path = subdir / "meta.json"- if meta_path.exists():- with open(meta_path, encoding="utf-8") as f:- meta = json.load(f)- if meta.get("error"):- incomplete.append(idx_str)- continue- if _find_model_output(subdir) is not None:- continue- incomplete.append(idx_str)- return incomplete---async def _retry_solve_incomplete(- results_dir: Path,- adapter: Any,- problems_by_index: dict[str, Any],- mode: str,- bench_cfg: dict,- max_rounds: int = 3,-) -> list[str]:- """Retry solving for incomplete cases until all done or max_rounds hit."""- outputs_dir = results_dir / "outputs"- runtime = _resolve_llm_runtime(bench_cfg)- model_name = runtime["model_name"]- api_key = runtime["api_key"]- base_url = runtime["base_url"]-- solve_concurrency = (- bench_cfg.get("pipeline", {}).get("concurrency", 1)- if mode == "pipeline"- else bench_cfg.get("concurrency", 1)- )-- for round_num in range(1, max_rounds + 1):- incomplete = _find_incomplete_indices(outputs_dir, problems_by_index)- if not incomplete:- logger.info("[solve] All %d cases have output", len(problems_by_index))- return []-- logger.info(- "[solve] Round %d/%d: %d incomplete, retrying (concurrency=%d, model=%s)...",- round_num, max_rounds, len(incomplete), solve_concurrency, model_name,- )-- sem = asyncio.Semaphore(solve_concurrency)- solved_count = 0-- async def _run_solve(idx_str: str) -> None:- nonlocal solved_count- prob = problems_by_index[idx_str]- workspace = str(outputs_dir / idx_str)- async with sem:- try:- output = await _solve_one(- prob, workspace, adapter, mode, bench_cfg,- model_name, api_key, base_url,- )- if mode == "direct":- Path(workspace).mkdir(parents=True, exist_ok=True)- with open(Path(workspace) / "output.md", "w", encoding="utf-8") as f:- f.write(output)- solved_count += 1- logger.info("[solve] %s (%s): done", prob.id, idx_str)- except Exception as exc:- logger.error("[solve] %s (%s): %s", prob.id, idx_str, exc)-- await asyncio.gather(*[_run_solve(idx) for idx in incomplete])- logger.info("[solve] Round %d done: solved %d / %d", round_num, solved_count, len(incomplete))-- still_incomplete = _find_incomplete_indices(outputs_dir, problems_by_index)- if still_incomplete:- logger.warning(- "[solve] %d cases still incomplete after %d rounds",- len(still_incomplete), max_rounds,- )- return still_incomplete---def _infer_report_meta(results_dir: Path, benchmark: str) -> dict:- """Infer mode / model / timestamp from directory path and name."""- mode = ""- parts = results_dir.resolve().parts- try:- idx = parts.index("results")- if idx + 2 < len(parts):- mode = parts[idx + 2]- except ValueError:- pass-- model, timestamp = "", ""- m = re.match(r"(.+?)_(\d{8}_\d{6})", results_dir.name)- if m:- model = m.group(1)- timestamp = m.group(2)-- return {- "benchmark": benchmark,- "mode": mode,- "model": model,- "timestamp": timestamp,- }---def _build_report_dict(- meta_info: dict,- results: list[dict],- breakdown_keys: list[str],- incomplete_count: int,-) -> dict:- correct_count = sum(1 for r in results if r["_new_correct"])- errors = sum(1 for r in results if r.get("error"))- total = len(results) + incomplete_count- scored = len(results)-- acc = correct_count / scored if scored else 0.0- acc_pct = round(100.0 * acc, 2)- ci = round(1.96 * math.sqrt(acc_pct * (100 - acc_pct) / scored), 2) if scored else 0.0-- elapsed = sum(r.get("elapsed_sec", 0) or 0 for r in results)-- breakdowns: dict[str, dict[str, dict]] = {}- for r in results:- if r.get("error"):- continue- rmeta = r.get("metadata", {})- for key in breakdown_keys:- val = str(rmeta.get(key, ""))- if not val:- continue- bucket_name = f"by_{key}"- stats = breakdowns.setdefault(bucket_name, {}).setdefault(- val, {"total": 0, "correct": 0}- )- stats["total"] += 1- if r["_new_correct"]:- stats["correct"] += 1- for bucket in breakdowns.values():- for s in bucket.values():- s["accuracy"] = round(s["correct"] / s["total"], 4) if s["total"] else 0.0-- return {- **meta_info,- "overall": {- "total": total,- "scored": scored,- "incomplete": incomplete_count,- "correct": correct_count,- "accuracy": round(acc, 4),- "accuracy_pct": acc_pct,- "confidence_interval": ci,- "errors": errors,- "elapsed_sec": round(elapsed, 2),- },- "breakdowns": breakdowns,- "results": [- {- "id": r.get("id"),- "question": r.get("question", "")[:300],- "ground_truth": r.get("ground_truth", ""),- "extracted_answer": r.get("extracted_answer"),- "correct": r["_new_correct"],- "score": 1.0 if r["_new_correct"] else 0.0,- "judge_reasoning": r["_new_reasoning"][:400],- "elapsed_sec": round(r.get("elapsed_sec", 0) or 0, 3),- "error": r.get("error"),- "metadata": r.get("metadata", {}),- }- for r in results- ],- }---def _write_report_and_summary(results_dir: Path, report: dict) -> None:- with open(results_dir / "report.json", "w", encoding="utf-8") as f:- json.dump(report, f, ensure_ascii=False, indent=2)-- ov = report["overall"]- scored = ov.get("scored", ov["total"])- lines = [- "=" * 70,- f"{report.get('benchmark', '').upper()} Benchmark Report — {report.get('mode', '')} mode",- f"Model: {report.get('model', '')}",- f"Time: {report.get('timestamp', '')}",- "=" * 70,- f"Overall: {ov['correct']}/{scored} = {ov['accuracy_pct']}% "- f"+/- {ov['confidence_interval']}% (errors={ov['errors']})",- f"Wall time: {ov.get('elapsed_sec', 0):.1f}s",- ]- if ov.get("incomplete", 0) > 0:- lines.append(f"Incomplete: {ov['incomplete']} cases (not scored)")-- for bucket_name in sorted(report.get("breakdowns", {})):- lines.append("")- lines.append(f"--- {bucket_name} ---")- for k in sorted(report["breakdowns"][bucket_name]):- s = report["breakdowns"][bucket_name][k]- a = s["correct"] / s["total"] if s["total"] else 0.0- lines.append(f" {k:30s} {s['correct']:4d}/{s['total']:4d} = {a:.3f}")- lines.append("=" * 70)-- with open(results_dir / "summary.txt", "w", encoding="utf-8") as f:- f.write("\n".join(lines))---def _overwrite_meta(results_dir: Path, results: list[dict]) -> int:- """Overwrite meta.json for flipped cases. Returns number of files written."""- outputs_dir = results_dir / "outputs"- written = 0- for r in results:- if r["_new_correct"] == r.get("correct", False):- continue- meta_path = outputs_dir / r["_subdir"] / "meta.json"- with open(meta_path, encoding="utf-8") as f:- meta = json.load(f)- meta["correct"] = r["_new_correct"]- meta["score"] = 1.0 if r["_new_correct"] else 0.0- meta["judge_reasoning"] = r["_new_reasoning"]- with open(meta_path, "w", encoding="utf-8") as f:- json.dump(meta, f, ensure_ascii=False, indent=2)- written += 1- return written---def _rebuild_report(results_dir: Path, results: list[dict]) -> None:- """Rebuild report.json and summary.txt from the current results."""- report_path = results_dir / "report.json"- with open(report_path, encoding="utf-8") as f:- report = json.load(f)-- new_correct_total = 0- new_errors = 0- new_breakdowns: dict[str, dict[str, dict]] = {}-- for r in results:- is_correct = r["_new_correct"]- has_error = bool(r.get("error"))- if has_error:- new_errors += 1- if is_correct:- new_correct_total += 1- meta = r.get("metadata", {})- for bucket_name, bucket in report.get("breakdowns", {}).items():- key_name = bucket_name.removeprefix("by_")- bucket_value = str(meta.get(key_name, ""))- if not bucket_value:- continue- stats = new_breakdowns.setdefault(bucket_name, {}).setdefault(- bucket_value, {"total": 0, "correct": 0}- )- stats["total"] += 1- if is_correct:- stats["correct"] += 1-- total = report["overall"]["total"]- acc = new_correct_total / total if total else 0.0- acc_pct = round(100.0 * acc, 2)- ci = round(1.96 * math.sqrt(acc_pct * (100 - acc_pct) / total), 2) if total else 0.0-- report["overall"]["correct"] = new_correct_total- report["overall"]["accuracy"] = round(acc, 4)- report["overall"]["accuracy_pct"] = acc_pct- report["overall"]["confidence_interval"] = ci- report["overall"]["errors"] = new_errors-- for bucket_name, bucket in new_breakdowns.items():- for k, s in bucket.items():- s["accuracy"] = round(s["correct"] / s["total"], 4) if s["total"] else 0.0- report["breakdowns"] = new_breakdowns-- for item in report.get("results", []):- match = next((r for r in results if r.get("id") == item.get("id")), None)- if match:- item["correct"] = match["_new_correct"]- item["score"] = 1.0 if match["_new_correct"] else 0.0- item["judge_reasoning"] = match["_new_reasoning"][:400]-- with open(report_path, "w", encoding="utf-8") as f:- json.dump(report, f, ensure_ascii=False, indent=2)-- bm = report.get("benchmark", "").upper()- mode = report.get("mode", "")- model = report.get("model", "")- ts = report.get("timestamp", "")- elapsed = report["overall"].get("elapsed_sec", 0.0)-- lines = [- "=" * 70,- f"{bm} Benchmark Report — {mode} mode",- f"Model: {model}",- f"Time: {ts}",- "=" * 70,- f"Overall: {new_correct_total}/{total} = {acc_pct}% "- f"+/- {ci}% (errors={new_errors})",- f"Wall time: {elapsed:.1f}s",- ]- for bucket_name in sorted(new_breakdowns):- lines.append("")- lines.append(f"--- {bucket_name} ---")- for k in sorted(new_breakdowns[bucket_name]):- s = new_breakdowns[bucket_name][k]- a = s["correct"] / s["total"] if s["total"] else 0.0- lines.append(f" {k:30s} {s['correct']:4d}/{s['total']:4d} = {a:.3f}")- lines.append("=" * 70)-- summary_path = results_dir / "summary.txt"- with open(summary_path, "w", encoding="utf-8") as f:- f.write("\n".join(lines))-- logger.info("Overwrote report.json and summary.txt")---def _load_problems_for_rescore(benchmark: str) -> list:- """Load the full problem set for a benchmark (sequential, no limit)."""- import yaml- from benchmark.iso_solve.core.types import Problem # noqa: F401-- cfg = _load_eval_cfg()- bench_cfg = cfg.get(benchmark, {})- adapter = _get_adapter(benchmark)-- class _FakeArgs:- limit = None- seed = 42- sequential = True- # benchmark-specific defaults- gaia_config_name = None- gaia_split = None- gaia_levels = None- gpqa_domains = None- aime_parts = None- livebench_categories = None- aalcr_categories = None- super_gpqa_disciplines = None- super_gpqa_difficulties = None- levels = None- subjects = None- dataroot = None-- args = _FakeArgs()- problems = adapter.load_dataset(bench_cfg, args)- problems = adapter.filter_problems(problems, bench_cfg, args)- return problems---# ----------------------------------------------------------------------------# Rescore mode-# -----------------------------------------------------------------------------async def _rescore(args: argparse.Namespace) -> None:- from dotenv import load_dotenv- load_dotenv(_PROJECT_ROOT / "DeepTutor.env", override=False)- load_dotenv(_PROJECT_ROOT / ".env", override=False)-- results_dir = Path(args.results_dir)- outputs_dir = results_dir / "outputs"-- if not outputs_dir.exists():- logger.error("No outputs directory at %s", outputs_dir)- return-- all_subdirs = sorted([d for d in outputs_dir.iterdir() if d.is_dir()])- if not all_subdirs:- logger.error("No output subdirectories found")- return-- # --- Detect benchmark and mode ---- benchmark = _detect_benchmark_from_path(results_dir)- mode = _detect_mode_from_path(results_dir)-- # Try meta.json for benchmark detection as fallback- if not benchmark:- for subdir in all_subdirs:- mp = subdir / "meta.json"- if mp.exists():- with open(mp, encoding="utf-8") as f:- b = json.load(f).get("benchmark")- if b:- benchmark = b- break- if not benchmark:- raise ValueError(- "Cannot detect benchmark. Directory path does not contain "- "'results/{benchmark}/...' and no meta.json files found."- )-- adapter = _get_adapter(benchmark)- cfg = _load_eval_cfg()- bench_cfg = cfg.get(benchmark, {})-- # --- Phase 0: load dataset and retry incomplete solves ---- logger.info("Loading %s dataset...", benchmark)- problems = _load_problems_for_rescore(benchmark)- problems_by_index: dict[str, Any] = {}- for i, p in enumerate(problems):- problems_by_index[f"{i:04d}"] = p- logger.info("Loaded %d problems from dataset", len(problems))-- existing_indices = {d.name for d in all_subdirs}- problems_by_index = {k: v for k, v in problems_by_index.items() if k in existing_indices}- logger.info("Scoped to %d existing output directories", len(problems_by_index))-- max_rounds = getattr(args, "max_solve_rounds", 3)- pre_incomplete = _find_incomplete_indices(outputs_dir, problems_by_index)-- if pre_incomplete:- logger.info(- "%d cases have no solver output — entering retry-solve phase (mode=%s, max_rounds=%d)",- len(pre_incomplete), mode, max_rounds,- )- still_incomplete = await _retry_solve_incomplete(- results_dir, adapter, problems_by_index, mode, bench_cfg, max_rounds,- )- else:- logger.info("All cases already have solver output, skipping retry-solve phase")- still_incomplete = []-- # --- Phase 1: scan and categorise ---- all_subdirs = sorted([d for d in outputs_dir.iterdir() if d.is_dir()])- meta_cases: list[dict] = []- unscored: list[tuple[str, str]] = []- incomplete: list[str] = []-- for subdir in all_subdirs:- meta_path = subdir / "meta.json"- if meta_path.exists():- with open(meta_path, encoding="utf-8") as f:- meta = json.load(f)- if meta.get("error"):- new_output = _find_model_output(subdir)- if new_output is not None:- unscored.append((subdir.name, new_output))- else:- incomplete.append(subdir.name)- continue- output_path = subdir / "output.md"- if output_path.exists():- with open(output_path, encoding="utf-8") as f:- meta["_model_output"] = f.read()- else:- meta["_model_output"] = ""- meta["_subdir"] = subdir.name- meta_cases.append(meta)- else:- model_output = _find_model_output(subdir)- if model_output is not None:- unscored.append((subdir.name, model_output))- else:- incomplete.append(subdir.name)-- logger.info(- "Scan: %d with meta, %d unscored (have solve output), %d incomplete",- len(meta_cases), len(unscored), len(incomplete),- )-- # --- Phase 2: build unified case list ---- all_cases: list[dict] = list(meta_cases)-- for subdir_name, model_output in unscored:- prob = problems_by_index.get(subdir_name)- if prob is None:- logger.warning(- "No dataset problem for index %s (dataset has %d entries), marking incomplete",- subdir_name, len(problems_by_index),- )- incomplete.append(subdir_name)- continue- all_cases.append({- "id": prob.id,- "benchmark": prob.benchmark,- "question": prob.question,- "ground_truth": prob.ground_truth,- "metadata": prob.metadata,- "_model_output": model_output,- "_subdir": subdir_name,- "_needs_extract": True,- })-- all_cases.sort(key=lambda c: c["_subdir"])-- if not all_cases:- print("No scorable cases found.")- if incomplete:- print(f"\nIncomplete: {len(incomplete)} cases")- return-- # --- Phase 4: resolve models ---- judge_model = _resolve_judge_model(args.judge_model)- extract_model = _resolve_extract_model()- extract_temperature, judge_temperature = _resolve_temperatures()- skip_extract = adapter.skip_extract- extract_hint = adapter.extract_hint- judge_hint = adapter.judge_hint-- logger.info(- "Rescore: %d cases | judge=%s | extract=%s | concurrency=%d",- len(all_cases), judge_model, extract_model or "(default)", args.concurrency,- )-- # --- Phase 5: extract + judge ---- sem = asyncio.Semaphore(args.concurrency)- completed = 0- total = len(all_cases)-- async def _score_one(case: dict) -> dict:- nonlocal completed- async with sem:- if not skip_extract:- from benchmark.iso_solve.core.extractor import extract_answer- extracted = await extract_answer(- question=case["question"],- model_output=case["_model_output"],- extract_hint=extract_hint,- model=extract_model,- max_tokens=16384,- temperature=extract_temperature,- )- if extracted is None:- extracted = adapter.extract_fallback(case["_model_output"])- case["extracted_answer"] = extracted- elif skip_extract and case.get("_needs_extract", False):- case["extracted_answer"] = case["_model_output"]-- correct, reasoning = await _rejudge_one(- case, judge_hint, judge_model, None, None, args.judge_max_tokens,- judge_temperature=judge_temperature,- )-- completed += 1- old_correct = case.get("correct")- tag = ""- if old_correct is not None and correct != old_correct:- tag = " ** FLIPPED **"- elif old_correct is None:- tag = " (new)"- logger.info(- "[%d/%d] %s: %s%s",- completed, total, case.get("id"),- "OK" if correct else "WRONG", tag,- )-- return {**case, "_new_correct": correct, "_new_reasoning": reasoning}-- results = await asyncio.gather(*[_score_one(c) for c in all_cases])-- # --- Phase 6: write ALL meta.json + output.md ---- for r in results:- subdir_path = outputs_dir / r["_subdir"]- subdir_path.mkdir(parents=True, exist_ok=True)-- meta = {- "id": r.get("id"),- "benchmark": r.get("benchmark", benchmark),- "question": r.get("question", ""),- "ground_truth": r.get("ground_truth", ""),- "metadata": r.get("metadata", {}),- "extracted_answer": r.get("extracted_answer"),- "correct": r["_new_correct"],- "score": 1.0 if r["_new_correct"] else 0.0,- "confidence": r.get("confidence", 100),- "judge_reasoning": r["_new_reasoning"],- "elapsed_sec": round(r.get("elapsed_sec", 0) or 0, 3),- "error": r.get("error"),- }- with open(subdir_path / "meta.json", "w", encoding="utf-8") as f:- json.dump(meta, f, ensure_ascii=False, indent=2)-- output_md = subdir_path / "output.md"- if not output_md.exists() and r.get("_model_output"):- with open(output_md, "w", encoding="utf-8") as f:- f.write(r["_model_output"])-- # --- Phase 7: build and write report ---- meta_info = _infer_report_meta(results_dir, benchmark)- report = _build_report_dict(meta_info, results, adapter.breakdown_keys, len(incomplete))- _write_report_and_summary(results_dir, report)-- # --- Phase 8: print summary ---- correct_count = sum(1 for r in results if r["_new_correct"])- scored = len(results)- acc_pct = round(100.0 * correct_count / scored, 1) if scored else 0- ci_val = round(1.96 * math.sqrt(acc_pct * (100 - acc_pct) / scored), 2) if scored else 0-- print()- print("=" * 70)- print(f"Rescored: {correct_count}/{scored} = {acc_pct}% +/- {ci_val}%")- if incomplete:- print(f"Incomplete: {len(incomplete)} cases (not scored)")- print(f"Wrote: {scored} meta.json + report.json + summary.txt")- print("=" * 70)-- if incomplete:- print(f"\nIncomplete cases ({len(incomplete)}):")- for s in sorted(incomplete):- print(f" {s}")---# ----------------------------------------------------------------------------# Default rejudge mode-# -----------------------------------------------------------------------------async def main():- parser = argparse.ArgumentParser(description="Re-judge / re-score benchmark results")- parser.add_argument("--results-dir", required=True)- parser.add_argument("--concurrency", type=int, default=20)- parser.add_argument("--judge-model", default=None)- parser.add_argument("--judge-max-tokens", type=int, default=16384)- parser.add_argument(- "--overwrite", action="store_true",- help="Overwrite meta.json / report.json / summary.txt in-place for flipped cases",- )- parser.add_argument(- "--rescore", action="store_true",- help="Full re-score: retry incomplete solves, extract+judge ALL cases, rebuild report",- )- parser.add_argument(- "--max-solve-rounds", type=int, default=3,- help="(rescore) Max retry rounds for incomplete solver cases (default: 3)",- )- args = parser.parse_args()-- if args.rescore:- await _rescore(args)- return-- results_dir = Path(args.results_dir)- cases = _load_cases(results_dir)- logger.info("Loaded %d cases from %s", len(cases), results_dir)-- benchmark = _detect_benchmark(cases)- if not benchmark:- raise ValueError("Cannot detect benchmark from meta.json files")- adapter = _get_adapter(benchmark)- judge_hint = adapter.judge_hint- logger.info("Benchmark: %s | judge_hint: %s", benchmark, judge_hint[:80])-- judge_model = _resolve_judge_model(args.judge_model)- _, judge_temperature = _resolve_temperatures()-- logger.info("Judge model: %s | concurrency: %d | overwrite: %s",- judge_model, args.concurrency, args.overwrite)-- sem = asyncio.Semaphore(args.concurrency)- completed = 0- total = len(cases)-- async def _run(case: dict) -> dict:- nonlocal completed- async with sem:- new_correct, reasoning = await _rejudge_one(- case, judge_hint, judge_model, None, None, args.judge_max_tokens,- judge_temperature=judge_temperature,- )- completed += 1- old_correct = case.get("correct", False)- if new_correct != old_correct:- logger.info(- "[%d/%d] %s: %s -> %s ** FLIPPED **",- completed, total, case.get("id"),- "OK" if old_correct else "WRONG",- "OK" if new_correct else "WRONG",- )- return {**case, "_new_correct": new_correct, "_new_reasoning": reasoning}-- results = await asyncio.gather(*[_run(c) for c in cases])-- old_correct = sum(1 for r in results if r.get("correct", False))- new_correct = sum(1 for r in results if r["_new_correct"])- flipped = [r for r in results if r["_new_correct"] != r.get("correct", False)]-- acc = lambda c, n: round(c / n * 100, 1) if n else 0- ci = lambda a, n: round(1.96 * math.sqrt(a * (100 - a) / n), 2) if n else 0-- print()- print("=" * 70)- print(f"Old: {old_correct}/{total} = {acc(old_correct, total)}% +/- {ci(acc(old_correct, total), total)}%")- print(f"New: {new_correct}/{total} = {acc(new_correct, total)}% +/- {ci(acc(new_correct, total), total)}%")- print(f"Diff: {new_correct - old_correct:+d}")- print("=" * 70)-- if not flipped:- print("\nNo flipped verdicts.")- if args.overwrite:- print("Nothing to overwrite.")- return-- print(f"\nFlipped verdicts: {len(flipped)}")- print("-" * 70)- for f in flipped:- old = "CORRECT" if f.get("correct") else "INCORRECT"- new = "CORRECT" if f["_new_correct"] else "INCORRECT"- print(f"\n [{f['_subdir']}] {f.get('id')}: {old} -> {new}")- print(f" GT: {f.get('ground_truth', '')[:150]}")- print(f" Reasoning: {f.get('_new_reasoning', '')[:150]}")- extracted = f.get("extracted_answer", "") or ""- print(f" Answer: {extracted[:150]}...")- print("=" * 70)-- if args.overwrite:- written = _overwrite_meta(results_dir, results)- logger.info("Overwrote %d meta.json files", written)- _rebuild_report(results_dir, results)- print(f"\n[overwrite] Updated {written} meta.json + report.json + summary.txt")---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/iso_solve/run_benchmark.py b/benchmark/iso_solve/run_benchmark.pydeleted file mode 100644index da05cd91b..000000000--- a/benchmark/iso_solve/run_benchmark.py+++ /dev/null@@ -1,111 +0,0 @@-# -*- coding: utf-8 -*--"""Unified benchmark entrypoint for iso_solve."""--from __future__ import annotations--import argparse-import asyncio-import logging-import sys-from pathlib import Path--import yaml--_PROJECT_ROOT = Path(__file__).resolve().parents[2]-if str(_PROJECT_ROOT) not in sys.path:- sys.path.insert(0, str(_PROJECT_ROOT))--from dotenv import load_dotenv--load_dotenv(_PROJECT_ROOT / "DeepTutor.env", override=False)-load_dotenv(_PROJECT_ROOT / ".env", override=False)--from benchmark.iso_solve.core import BenchmarkRunner, extract_answer, judge_answer-from benchmark.iso_solve.eval import ADAPTER_REGISTRY--logger = logging.getLogger("benchmark_runner")---def _build_parser() -> argparse.ArgumentParser:- parser = argparse.ArgumentParser(- description="Benchmark Runner — unified iso_solve evaluator",- formatter_class=argparse.RawDescriptionHelpFormatter,- )-- parser.add_argument(- "--benchmark",- choices=["math", "gaia", "hle", "gpqa", "aime25", "livebench", "aalcr", "super_gpqa"],- default="math",- )- parser.add_argument("--mode", choices=["direct", "pipeline"], default="direct")- parser.add_argument("--limit", type=int, default=None)- parser.add_argument("--seed", type=int, default=42)- parser.add_argument("--sequential", action="store_true",- help="Take the first N problems in dataset order instead of random sampling")- parser.add_argument("--output", type=str, default=None)- parser.add_argument("--config", type=str, default=None)- parser.add_argument("--tools", nargs="+", default=None)- parser.add_argument("--dry-run", action="store_true")- parser.add_argument("-v", "--verbose", action="store_true")-- math_group = parser.add_argument_group("MATH")- math_group.add_argument("--dataroot", type=str, default=None)- math_group.add_argument("--subjects", nargs="+", default=None)- math_group.add_argument("--levels", nargs="+", type=int, default=None)-- gaia_group = parser.add_argument_group("GAIA")- gaia_group.add_argument("--gaia-config-name", type=str, default=None)- gaia_group.add_argument("--gaia-split", type=str, default=None)- gaia_group.add_argument("--gaia-levels", nargs="+", type=int, default=None)-- gpqa_group = parser.add_argument_group("GPQA")- gpqa_group.add_argument("--gpqa-domains", nargs="+", default=None)-- aime_group = parser.add_argument_group("AIME")- aime_group.add_argument("--aime-parts", nargs="+", type=int, default=None)-- livebench_group = parser.add_argument_group("LiveBench")- livebench_group.add_argument("--livebench-categories", nargs="+", default=None)-- aalcr_group = parser.add_argument_group("AA-LCR")- aalcr_group.add_argument("--aalcr-categories", nargs="+", default=None)-- super_gpqa_group = parser.add_argument_group("SuperGPQA")- super_gpqa_group.add_argument("--super-gpqa-disciplines", nargs="+", default=None)- super_gpqa_group.add_argument("--super-gpqa-difficulties", nargs="+", default=None)-- return parser---def _load_cfg(path: str | None) -> dict:- if not path:- return {}- p = Path(path)- if not p.exists():- logger.warning("Config file does not exist: %s", path)- return {}- with open(p, "r", encoding="utf-8") as f:- return yaml.safe_load(f) or {}---def main() -> None:- parser = _build_parser()- args = parser.parse_args()-- logging.basicConfig(- level=logging.DEBUG if args.verbose else logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- datefmt="%H:%M:%S",- )-- cfg = _load_cfg(args.config)- adapter_cls = ADAPTER_REGISTRY[args.benchmark]- adapter = adapter_cls()- runner = BenchmarkRunner(adapter, extract_answer, judge_answer)- report = asyncio.run(runner.run(args, cfg))- for line in report.summary_lines():- print(line)---if __name__ == "__main__":- main()diff --git a/benchmark/iso_solve/score_jobs.yaml b/benchmark/iso_solve/score_jobs.yamldeleted file mode 100644index c8aa3650b..000000000--- a/benchmark/iso_solve/score_jobs.yaml+++ /dev/null@@ -1,50 +0,0 @@-# ======================================================================-# LLM Score Batch Jobs-# ======================================================================-# List the results directories to score. Run all jobs with:-#-# python -m benchmark.iso_solve.get_llm_score --jobs benchmark/iso_solve/score_jobs.yaml-#-# Each job inherits global defaults below, but can override per-job.-# ======================================================================--# --- Global defaults (apply to all jobs unless overridden) ----defaults:- rounds: 3- concurrency: 20--# --- Jobs ----jobs:- # -- AALCR --- # - results_dir: benchmark/iso_solve/report_trace/aalcr/direct/anthropic_claude-sonnet-4.5_20260223_223343- # - results_dir: benchmark/iso_solve/report_trace/aalcr/direct/google_gemini-3-flash-preview_nitro_20260224_000404- # - results_dir: benchmark/iso_solve/report_trace/aalcr/direct/openai_gpt-5-mini_20260223_185720-paper- # - results_dir: benchmark/iso_solve/report_trace/aalcr/direct/qwen3.5-plus_20260223_122140-paper-- # # pipeline- # - results_dir: benchmark/iso_solve/report_trace/aalcr/pipeline/qwen3.5-plus_20260223_131936-paper--- # # -- GAIA --- # - results_dir: benchmark/iso_solve/report_trace/gaia/direct/google_gemini-3-flash-preview_nitro_20260223_235651-- # # -- GPQA --- # - results_dir: benchmark/iso_solve/report_trace/gpqa/direct/openai_gpt-5-mini_nitro_20260223_200205-paper-- # # -- HLE --- # - results_dir: benchmark/iso_solve/report_trace/hle/direct/anthropic_claude-sonnet-4.5_20260224_133043-- # -- LiveBench --- - results_dir: benchmark/iso_solve/report_trace/livebench/direct/anthropic_claude-sonnet-4.5_nitro_20260223_225829- - results_dir: benchmark/iso_solve/report_trace/livebench/direct/google_gemini-3-flash-preview_20260223_235455- - results_dir: benchmark/iso_solve/report_trace/livebench/direct/openai_gpt-5-mini_nitro_20260223_194601- - results_dir: benchmark/iso_solve/report_trace/livebench/direct/qwen3.5-plus_20260223_173705-paper- - results_dir: benchmark/iso_solve/report_trace/livebench/pipeline/anthropic_claude-sonnet-4.5_20260224_124453- - results_dir: benchmark/iso_solve/report_trace/livebench/pipeline/google_gemini-3-flash-preview_20260223_235735- - results_dir: benchmark/iso_solve/report_trace/livebench/pipeline/openai_gpt-5-mini_nitro_20260224_014320- - results_dir: benchmark/iso_solve/report_trace/livebench/pipeline/qwen3.5-plus_20260223_174525-- # Per-job overrides example (uncomment to use):- # - results_dir: benchmark/iso_solve/report_trace/gaia/direct/some_run- # rounds: 3 # override rounds for this job only- # concurrency: 10 # override concurrency for this job onlydiff --git a/benchmark/pipeline/__init__.py b/benchmark/pipeline/__init__.pydeleted file mode 100644index b3136f1f4..000000000--- a/benchmark/pipeline/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Three-step benchmark pipeline scripts."""diff --git a/benchmark/pipeline/check_entries.py b/benchmark/pipeline/check_entries.pydeleted file mode 100644index 233a5188a..000000000--- a/benchmark/pipeline/check_entries.py+++ /dev/null@@ -1,710 +0,0 @@-#!/usr/bin/env python3-"""-Check entry health across all KBs in the bench_pipeline output.-With --fix, automatically regenerate unhealthy entries via LLM.--Usage:- python3 -m benchmark.pipeline.check_entries- python3 -m benchmark.pipeline.check_entries --kb-names kb1,kb2- python3 -m benchmark.pipeline.check_entries --fix- python3 -m benchmark.pipeline.check_entries --fix --concurrency 4-"""-from __future__ import annotations--import argparse-import asyncio-import json-import shutil-import sys-from pathlib import Path--import yaml--_THIS_FILE = Path(__file__).resolve()-PROJECT_ROOT = _THIS_FILE.parents[2]-if str(PROJECT_ROOT) not in sys.path:- sys.path.insert(0, str(PROJECT_ROOT))--DEFAULT_CONFIG = PROJECT_ROOT / "benchmark" / "config" / "benchmark_config.yaml"-DEFAULT_OUTPUT_ROOT = PROJECT_ROOT / "benchmark" / "data" / "bench_pipeline"--ANSI_GREEN = "\033[92m"-ANSI_YELLOW = "\033[93m"-ANSI_RED = "\033[91m"-ANSI_DIM = "\033[2m"-ANSI_BOLD = "\033[1m"-ANSI_CYAN = "\033[96m"-ANSI_RESET = "\033[0m"--FIX_RETRY_ATTEMPTS = 3-FIX_RETRY_DELAY_SEC = 3.0-EXPECTED_ENTRIES_PER_PROFILE = 3---def _load_entries_jsonl(path: Path) -> list[dict]:- entries: list[dict] = []- if not path.exists():- return entries- with open(path, encoding="utf-8") as f:- for line in f:- line = line.strip()- if line:- entries.append(json.loads(line))- return entries---def _extract_task_index(entry_id: str) -> int:- marker = "_task_"- if marker not in entry_id:- return 0- try:- return int(entry_id.rsplit(marker, 1)[-1])- except Exception:- return 0---def _next_task_index(entries: list[dict]) -> int:- max_idx = 0- for e in entries:- max_idx = max(max_idx, _extract_task_index(str(e.get("entry_id", ""))))- return max_idx + 1---def _count_jsonl(path: Path) -> int:- count = 0- with open(path, encoding="utf-8") as f:- for line in f:- if line.strip():- count += 1- return count---def _check_entry_quality(entry: dict) -> list[str]:- warnings = []- if not entry.get("gaps"):- warnings.append("no gaps")- if not entry.get("task"):- warnings.append("no task")- task = entry.get("task", {})- if not task.get("target_gaps"):- warnings.append("task has no target_gaps")- if not task.get("title") and not task.get("description"):- warnings.append("task has no title/description")- profile = entry.get("profile", {})- if not profile.get("profile_id"):- warnings.append("no profile_id in entry")- return warnings---def _classify_profile(- profile_dir: Path,-) -> tuple[str, int, list[str]]:- """Classify a profile as ok / warn / empty / missing. Returns (status, n_entries, warnings)."""- entries_jsonl = profile_dir / "entries.jsonl"- if not entries_jsonl.exists():- return "missing", 0, []-- n_entries = _count_jsonl(entries_jsonl)- if n_entries == 0:- return "empty", 0, []-- entry_warnings: list[str] = []- try:- with open(entries_jsonl, encoding="utf-8") as f:- for line in f:- line = line.strip()- if not line:- continue- entry = json.loads(line)- ws = _check_entry_quality(entry)- entry_warnings.extend(- f"{entry.get('entry_id', '?')}: {w}" for w in ws- )- except Exception as e:- entry_warnings.append(f"parse error: {e}")-- if n_entries != EXPECTED_ENTRIES_PER_PROFILE:- entry_warnings.append(- f"entry count mismatch: expected {EXPECTED_ENTRIES_PER_PROFILE}, got {n_entries}"- )-- if entry_warnings:- return "warn", n_entries, entry_warnings- return "ok", n_entries, []---def _save_profile_entries(entries: list[dict], profile_dir: Path) -> None:- entries_dir = profile_dir / "entries"- if entries_dir.exists():- shutil.rmtree(entries_dir)- entries_dir.mkdir(parents=True, exist_ok=True)-- jsonl_path = profile_dir / "entries.jsonl"- with open(jsonl_path, "w", encoding="utf-8") as f:- for entry in entries:- f.write(json.dumps(entry, ensure_ascii=False) + "\n")-- for entry in entries:- entry_id = entry.get("entry_id", "unknown")- out = entries_dir / f"{entry_id}.json"- with open(out, "w", encoding="utf-8") as f:- json.dump(entry, f, ensure_ascii=False, indent=2)---async def _fix_one_profile(- *,- kb_name: str,- profile_id: str,- profile: dict,- scope: dict,- cfg: dict,- kb_base_dir: str,- profile_dir: Path,- semaphore: asyncio.Semaphore,-) -> dict:- from benchmark.simulation.batch_simulation import _generate_entries_for_profile-- async with semaphore:- result = {- "kb_name": kb_name,- "profile_id": profile_id,- "status": "ok",- "num_entries": 0,- "error": None,- }-- entries: list[dict] = []- last_error: str | None = None- entries_jsonl = profile_dir / "entries.jsonl"-- try:- current_entries = _load_entries_jsonl(entries_jsonl)- except Exception:- current_entries = []-- def _sort_entries(xs: list[dict]) -> list[dict]:- return sorted(- xs,- key=lambda e: _extract_task_index(str(e.get("entry_id", ""))),- )-- def _normalize_new_entry(e: dict, task_idx: int) -> dict:- e = dict(e)- e["kb_name"] = kb_name- e["profile"] = profile- e["entry_id"] = f"{kb_name}_{profile_id}_task_{task_idx:03d}"- return e-- # If there are too many entries, keep the first N and rewrite files.- if len(current_entries) > EXPECTED_ENTRIES_PER_PROFILE:- trimmed = _sort_entries(current_entries)[:EXPECTED_ENTRIES_PER_PROFILE]- _save_profile_entries(trimmed, profile_dir)- if not (profile_dir / "profile.json").exists():- with open(profile_dir / "profile.json", "w", encoding="utf-8") as f:- json.dump(profile, f, ensure_ascii=False, indent=2)- result["num_entries"] = len(trimmed)- print(- f" {ANSI_GREEN}✓ fixed: trimmed to {len(trimmed)} entries{ANSI_RESET}"- )- return result-- # If entries exist but are fewer than expected, supplement missing ones.- if 0 < len(current_entries) < EXPECTED_ENTRIES_PER_PROFILE:- merged = _sort_entries(current_entries)- needed = EXPECTED_ENTRIES_PER_PROFILE - len(merged)- print(- f" {ANSI_CYAN}supplementing {needed} missing entries for {profile_id}{ANSI_RESET}"- )- seen_signatures = {- (- str((e.get("task") or {}).get("title", "")).strip().lower(),- str((e.get("task") or {}).get("description", "")).strip().lower(),- )- for e in merged- }- next_idx = _next_task_index(merged)- for attempt in range(1, FIX_RETRY_ATTEMPTS + 1):- try:- candidates = await _generate_entries_for_profile(- kb_name=kb_name,- profile=profile,- knowledge_scope=scope,- cfg=cfg,- kb_base_dir=kb_base_dir,- )- except Exception as e:- last_error = str(e)- print(- f" {ANSI_YELLOW}supplement attempt {attempt}/{FIX_RETRY_ATTEMPTS} "- f"failed: {e}{ANSI_RESET}"- )- if attempt < FIX_RETRY_ATTEMPTS:- await asyncio.sleep(FIX_RETRY_DELAY_SEC * attempt)- continue-- added_this_round = 0- for c in candidates:- sig = (- str((c.get("task") or {}).get("title", "")).strip().lower(),- str((c.get("task") or {}).get("description", "")).strip().lower(),- )- if sig in seen_signatures:- continue- merged.append(_normalize_new_entry(c, next_idx))- seen_signatures.add(sig)- next_idx += 1- added_this_round += 1- if len(merged) >= EXPECTED_ENTRIES_PER_PROFILE:- break-- if len(merged) >= EXPECTED_ENTRIES_PER_PROFILE:- _save_profile_entries(merged[:EXPECTED_ENTRIES_PER_PROFILE], profile_dir)- if not (profile_dir / "profile.json").exists():- with open(profile_dir / "profile.json", "w", encoding="utf-8") as f:- json.dump(profile, f, ensure_ascii=False, indent=2)- result["num_entries"] = EXPECTED_ENTRIES_PER_PROFILE- print(- f" {ANSI_GREEN}✓ fixed: supplemented to {EXPECTED_ENTRIES_PER_PROFILE} entries{ANSI_RESET}"- )- return result-- print(- f" {ANSI_YELLOW}supplement attempt {attempt}/{FIX_RETRY_ATTEMPTS} "- f"added {added_this_round}, still missing "- f"{EXPECTED_ENTRIES_PER_PROFILE - len(merged)}{ANSI_RESET}"- )- if attempt < FIX_RETRY_ATTEMPTS:- await asyncio.sleep(FIX_RETRY_DELAY_SEC * attempt)-- # Full regeneration (for empty/missing or supplement fallback).- for attempt in range(1, FIX_RETRY_ATTEMPTS + 1):- try:- entries = await _generate_entries_for_profile(- kb_name=kb_name,- profile=profile,- knowledge_scope=scope,- cfg=cfg,- kb_base_dir=kb_base_dir,- )- except Exception as e:- last_error = str(e)- print(- f" {ANSI_YELLOW}attempt {attempt}/{FIX_RETRY_ATTEMPTS} "- f"failed: {e}{ANSI_RESET}"- )- if attempt < FIX_RETRY_ATTEMPTS:- await asyncio.sleep(FIX_RETRY_DELAY_SEC * attempt)- continue-- if entries:- break-- print(- f" {ANSI_YELLOW}attempt {attempt}/{FIX_RETRY_ATTEMPTS} "- f"returned 0 entries{ANSI_RESET}"- )- last_error = "0 entries"- if attempt < FIX_RETRY_ATTEMPTS:- await asyncio.sleep(FIX_RETRY_DELAY_SEC * attempt)-- if entries:- entries = _sort_entries(entries)[:EXPECTED_ENTRIES_PER_PROFILE]- _save_profile_entries(entries, profile_dir)- if not (profile_dir / "profile.json").exists():- with open(profile_dir / "profile.json", "w", encoding="utf-8") as f:- json.dump(profile, f, ensure_ascii=False, indent=2)- result["num_entries"] = len(entries)- print(- f" {ANSI_GREEN}✓ fixed: {len(entries)} entries{ANSI_RESET}"- )- else:- result["status"] = "error"- result["error"] = last_error- print(- f" {ANSI_RED}✗ fix failed after {FIX_RETRY_ATTEMPTS} "- f"attempts: {last_error}{ANSI_RESET}"- )-- return result---def _load_profile_data(- kb_name: str, profile_id: str, entries_root: Path-) -> dict | None:- """Load profile dict from profile.json or profiles.json."""- profile_json = entries_root / kb_name / "profiles" / profile_id / "profile.json"- if profile_json.exists():- with open(profile_json, encoding="utf-8") as f:- return json.load(f)-- profiles_json = entries_root / kb_name / "profiles.json"- if profiles_json.exists():- with open(profiles_json, encoding="utf-8") as f:- profiles = json.load(f)- for p in profiles:- if p.get("profile_id") == profile_id:- return p-- return None---def _load_scope(kb_name: str, entries_root: Path) -> dict | None:- scope_path = entries_root / kb_name / "knowledge_scope.json"- if not scope_path.exists():- return None- with open(scope_path, encoding="utf-8") as f:- return json.load(f)---def scan_entries(- entries_root: Path, kb_names: list[str]-) -> tuple[- list[str], list[str], list[str], list[str], list[str],- dict[str, list[str]], int, int-]:- """Scan and classify all profiles.-- Returns (ok, warn, empty, missing, count_mismatch, kb_details, total_profiles, total_entries).- """- ok_profiles: list[str] = []- warn_profiles: list[str] = []- empty_profiles: list[str] = []- missing_profiles: list[str] = []- count_mismatch_profiles: list[str] = []- kb_details: dict[str, list[str]] = {}- total_profiles = 0- total_entries = 0-- for kb_name in kb_names:- kb_dir = entries_root / kb_name- kb_lines: list[str] = []- if not kb_dir.exists():- kb_lines.append(f" {ANSI_RED}directory not found{ANSI_RESET}")- kb_details[kb_name] = kb_lines- continue-- scope_path = kb_dir / "knowledge_scope.json"- if scope_path.exists():- try:- with open(scope_path, encoding="utf-8") as f:- scope = json.load(f)- topic = scope.get("topic", scope.get("title", "?"))- n_concepts = len(scope.get("concepts", []))- kb_lines.append(f" {ANSI_DIM}scope: {topic} ({n_concepts} concepts){ANSI_RESET}")- except Exception:- kb_lines.append(f" {ANSI_YELLOW}scope: parse error{ANSI_RESET}")-- profiles_root = kb_dir / "profiles"- if not profiles_root.exists():- kb_lines.append(f" {ANSI_RED}no profiles/ directory{ANSI_RESET}")- kb_details[kb_name] = kb_lines- continue-- profile_dirs = sorted(p for p in profiles_root.iterdir() if p.is_dir())- for profile_dir in profile_dirs:- total_profiles += 1- profile_id = profile_dir.name- full_id = f"{kb_name}/{profile_id}"- has_profile_json = (profile_dir / "profile.json").exists()-- status, n_entries, warnings = _classify_profile(profile_dir)- total_entries += n_entries-- if status == "missing":- missing_profiles.append(full_id)- kb_lines.append(- f" {ANSI_RED}✗{ANSI_RESET} {profile_id} "- f"{ANSI_RED}entries.jsonl missing{ANSI_RESET}"- )- elif status == "empty":- empty_profiles.append(full_id)- kb_lines.append(- f" {ANSI_RED}✗{ANSI_RESET} {profile_id} "- f"{ANSI_RED}0 entries{ANSI_RESET}"- )- elif status == "warn":- warn_profiles.append(full_id)- if any(w.startswith("entry count mismatch:") for w in warnings):- count_mismatch_profiles.append(full_id)- kb_lines.append(- f" {ANSI_YELLOW}⚠{ANSI_RESET} {profile_id} "- f"{n_entries} entries "- f"{ANSI_YELLOW}{len(warnings)} warnings{ANSI_RESET} "- f"profile.json:{'✓' if has_profile_json else '✗'}"- )- for w in warnings[:5]:- kb_lines.append(f" {ANSI_DIM}└ {w}{ANSI_RESET}")- if len(warnings) > 5:- kb_lines.append(- f" {ANSI_DIM}└ ...and {len(warnings) - 5} more{ANSI_RESET}"- )- else:- ok_profiles.append(full_id)- kb_lines.append(- f" {ANSI_GREEN}✓{ANSI_RESET} {profile_id} "- f"{n_entries} entries "- f"profile.json:{'✓' if has_profile_json else '✗'}"- )-- kb_details[kb_name] = kb_lines-- return (- ok_profiles,- warn_profiles,- empty_profiles,- missing_profiles,- count_mismatch_profiles,- kb_details,- total_profiles,- total_entries,- )---def print_report(- kb_names: list[str],- entries_root: Path,- ok_profiles: list[str],- warn_profiles: list[str],- empty_profiles: list[str],- missing_profiles: list[str],- count_mismatch_profiles: list[str],- kb_details: dict[str, list[str]],- total_profiles: int,- total_entries: int,-) -> None:- print(f"\n{ANSI_BOLD}Entry Health Check{ANSI_RESET}")- print(f"Root: {entries_root}")- print(f"KBs: {len(kb_names)}\n")- print("=" * 80)-- for kb_name in kb_names:- lines = kb_details.get(kb_name, [])- has_error = any(- f.startswith(kb_name + "/") for f in empty_profiles + missing_profiles- )- has_warn = any(f.startswith(kb_name + "/") for f in warn_profiles)- if has_error:- icon = f"{ANSI_RED}✗{ANSI_RESET}"- elif has_warn:- icon = f"{ANSI_YELLOW}⚠{ANSI_RESET}"- else:- icon = f"{ANSI_GREEN}✓{ANSI_RESET}"- print(f"\n{icon} {ANSI_BOLD}{kb_name}{ANSI_RESET}")- for line in lines:- print(line)-- print("\n" + "=" * 80)- print(f"\n{ANSI_BOLD}Summary{ANSI_RESET}")- print(f" KBs: {len(kb_names)}")- print(f" Profiles: {total_profiles}")- print(f" Entries: {total_entries}")-- print(f"\n {ANSI_GREEN}OK{ANSI_RESET}: {len(ok_profiles)}")- for p in ok_profiles:- print(f" {ANSI_DIM}{p}{ANSI_RESET}")-- print(f" {ANSI_YELLOW}WARN{ANSI_RESET}: {len(warn_profiles)}")- for p in warn_profiles:- print(f" {ANSI_DIM}{p}{ANSI_RESET}")-- print(f" {ANSI_RED}EMPTY{ANSI_RESET}: {len(empty_profiles)}")- for p in empty_profiles:- print(f" {ANSI_DIM}{p}{ANSI_RESET}")-- print(f" {ANSI_RED}MISSING{ANSI_RESET}: {len(missing_profiles)}")- for p in missing_profiles:- print(f" {ANSI_DIM}{p}{ANSI_RESET}")-- print(- f" {ANSI_YELLOW}COUNT_MISMATCH{ANSI_RESET}: {len(count_mismatch_profiles)} "- f"(expected {EXPECTED_ENTRIES_PER_PROFILE})"- )- for p in count_mismatch_profiles:- print(f" {ANSI_DIM}{p}{ANSI_RESET}")-- print()---async def run(args: argparse.Namespace) -> None:- output_root = Path(args.output_root)- if not output_root.is_absolute():- output_root = (PROJECT_ROOT / output_root).resolve()- entries_root = output_root / "entries"-- if not entries_root.exists():- print(f"{ANSI_RED}Entries root not found: {entries_root}{ANSI_RESET}")- sys.exit(1)-- if args.kb_names:- kb_names = sorted(set(n.strip() for n in args.kb_names.split(",") if n.strip()))- else:- kb_names = sorted(d.name for d in entries_root.iterdir() if d.is_dir())-- if not kb_names:- print(f"{ANSI_RED}No KBs found in {entries_root}{ANSI_RESET}")- sys.exit(1)-- # --- First pass: scan ---- (- ok,- warn,- empty,- missing,- count_mismatch,- details,- total_profiles,- total_entries,- ) = scan_entries(entries_root, kb_names)- print_report(- kb_names, entries_root, ok, warn, empty, missing, count_mismatch, details,- total_profiles, total_entries,- )-- unhealthy = empty + missing + count_mismatch- if not args.fix or not unhealthy:- if unhealthy:- print(- f"Run with {ANSI_CYAN}--fix{ANSI_RESET} to regenerate/fix unhealthy entries.\n"- )- sys.exit(1)- return-- # --- Fix pass ---- kb_base_dir = Path(args.kb_dir)- if not kb_base_dir.is_absolute():- kb_base_dir = (PROJECT_ROOT / kb_base_dir).resolve()-- cfg_path = Path(args.config)- if not cfg_path.is_absolute():- cfg_path = (PROJECT_ROOT / cfg_path).resolve()- with open(cfg_path, encoding="utf-8") as f:- cfg = yaml.safe_load(f) or {}-- print(f"\n{ANSI_BOLD}Fixing {len(unhealthy)} unhealthy profiles...{ANSI_RESET}\n")-- sem = asyncio.Semaphore(args.concurrency)- fix_tasks = []- skipped: list[str] = []-- for full_id in unhealthy:- kb_name, profile_id = full_id.split("/", 1)-- scope = _load_scope(kb_name, entries_root)- if not scope:- print(- f" {ANSI_RED}✗ {full_id}: no knowledge_scope.json, cannot fix{ANSI_RESET}"- )- skipped.append(full_id)- continue-- profile = _load_profile_data(kb_name, profile_id, entries_root)- if not profile:- print(- f" {ANSI_RED}✗ {full_id}: no profile data found, cannot fix{ANSI_RESET}"- )- skipped.append(full_id)- continue-- profile_dir = entries_root / kb_name / "profiles" / profile_id- profile_dir.mkdir(parents=True, exist_ok=True)-- print(f" {ANSI_CYAN}→ fixing {full_id}...{ANSI_RESET}")- fix_tasks.append(- _fix_one_profile(- kb_name=kb_name,- profile_id=profile_id,- profile=profile,- scope=scope,- cfg=cfg,- kb_base_dir=str(kb_base_dir),- profile_dir=profile_dir,- semaphore=sem,- )- )-- if fix_tasks:- results = await asyncio.gather(*fix_tasks, return_exceptions=True)- fixed = sum(- 1- for r in results- if not isinstance(r, Exception) and r.get("status") == "ok"- )- failed = len(results) - fixed- else:- fixed = 0- failed = 0-- # --- Second pass: re-scan ---- print(f"\n{'=' * 80}")- print(f"{ANSI_BOLD}Post-fix re-scan{ANSI_RESET}")- ok2, warn2, empty2, missing2, count_mismatch2, details2, tp2, te2 = scan_entries(- entries_root, kb_names- )- print_report(- kb_names,- entries_root,- ok2,- warn2,- empty2,- missing2,- count_mismatch2,- details2,- tp2,- te2,- )-- print(f"{ANSI_BOLD}Fix summary{ANSI_RESET}")- print(f" Fixed: {ANSI_GREEN}{fixed}{ANSI_RESET}")- print(f" Failed: {ANSI_RED}{failed}{ANSI_RESET}")- print(f" Skipped: {ANSI_YELLOW}{len(skipped)}{ANSI_RESET}")- if skipped:- for s in skipped:- print(f" {ANSI_DIM}{s}{ANSI_RESET}")- print()-- if empty2 or missing2 or count_mismatch2:- sys.exit(1)---def main() -> None:- parser = argparse.ArgumentParser(description="Check & fix entry health")- parser.add_argument(- "--output-root",- default=str(DEFAULT_OUTPUT_ROOT),- help=f"Pipeline output root (default: {DEFAULT_OUTPUT_ROOT})",- )- parser.add_argument(- "--kb-names",- default=None,- help="Comma-separated KB names to check (default: all)",- )- parser.add_argument(- "--fix",- action="store_true",- help=(- "Fix unhealthy profiles: regenerate empty/missing, "- "supplement <3 entries, trim >3 entries"- ),- )- parser.add_argument(- "--kb-dir",- default="data/knowledge_bases",- help="Knowledge base directory (default: data/knowledge_bases)",- )- parser.add_argument(- "--config",- default=str(DEFAULT_CONFIG),- help=f"Benchmark config path (default: {DEFAULT_CONFIG})",- )- parser.add_argument(- "--concurrency",- type=int,- default=6,- help="Max parallel fix tasks (default: 6)",- )- args = parser.parse_args()- asyncio.run(run(args))---if __name__ == "__main__":- main()diff --git a/benchmark/pipeline/run_step2_multimodel_then_step3_fixed_judge.py b/benchmark/pipeline/run_step2_multimodel_then_step3_fixed_judge.pydeleted file mode 100644index daf85380a..000000000--- a/benchmark/pipeline/run_step2_multimodel_then_step3_fixed_judge.py+++ /dev/null@@ -1,182 +0,0 @@-#!/usr/bin/env python3-"""-Run Step2 with multiple generation models, then Step3 with one fixed judge model.--Example:- python -m benchmark.pipeline.run_step2_multimodel_then_step3_fixed_judge \- --kb-names kb_a,kb_b \- --step2-models qwen3.5-plus,deepseek-v3 \- --judge-model qwen3.5-plus \- --base-output-root benchmark/data/bench_pipeline_multimodel-"""--from __future__ import annotations--import argparse-import json-import os-import re-import subprocess-import sys-from datetime import datetime-from pathlib import Path-from typing import Any--_THIS_FILE = Path(__file__).resolve()-PROJECT_ROOT = _THIS_FILE.parents[2]---def _parse_names(raw: str) -> list[str]:- return [x.strip() for x in raw.split(",") if x.strip()]---def _safe_model_key(model: str) -> str:- return re.sub(r"[^a-zA-Z0-9._-]+", "_", model).strip("_") or "model"---def _run(cmd: list[str], env: dict[str, str]) -> None:- print("$ " + " ".join(cmd))- subprocess.run(cmd, cwd=str(PROJECT_ROOT), env=env, check=True)---def _load_json(path: Path) -> dict[str, Any] | None:- if not path.exists():- return None- try:- with open(path, encoding="utf-8") as f:- return json.load(f)- except Exception:- return None---def main() -> None:- parser = argparse.ArgumentParser(- description="Run step2 (multi models) then step3 (fixed judge model)."- )- parser.add_argument("--kb-names", required=True, help="Comma-separated KB names")- parser.add_argument(- "--step2-models",- required=True,- help="Comma-separated models for step2 generation (e.g. a,b,c)",- )- parser.add_argument(- "--judge-model",- required=True,- help="Model used for all step3 evaluations",- )- parser.add_argument(- "--base-output-root",- default=str(PROJECT_ROOT / "benchmark" / "data" / "bench_pipeline_multimodel"),- help="Base output root; each model writes to a subdir",- )- parser.add_argument("--backends", default="mock,deep_tutor")- parser.add_argument("--step2-concurrency", type=int, default=6)- parser.add_argument("--step2-max-turns", type=int, default=30)- parser.add_argument("--step2-language", default="en")- parser.add_argument("--step2-no-evolve", action="store_true")- parser.add_argument("--step2-verbose", action="store_true")- parser.add_argument("--step3-concurrency", type=int, default=6)- parser.add_argument("--step3-temperature", type=float, default=0.2)- parser.add_argument("--step3-skip-turns", action="store_true")- args = parser.parse_args()-- kb_names = ",".join(_parse_names(args.kb_names))- models = _parse_names(args.step2_models)- if not models:- raise ValueError("No step2 models provided.")-- base_output_root = Path(args.base_output_root)- if not base_output_root.is_absolute():- base_output_root = (PROJECT_ROOT / base_output_root).resolve()- base_output_root.mkdir(parents=True, exist_ok=True)-- runs: list[dict[str, Any]] = []-- for model in models:- model_key = _safe_model_key(model)- output_root = base_output_root / model_key- output_root.mkdir(parents=True, exist_ok=True)-- env_step2 = os.environ.copy()- env_step2["LLM_MODEL"] = model-- step2_cmd = [- sys.executable,- str(PROJECT_ROOT / "benchmark" / "pipeline" / "step2_generate_transcripts.py"),- "--kb-names",- kb_names,- "--output-root",- str(output_root),- "--backends",- args.backends,- "--concurrency",- str(args.step2_concurrency),- "--max-turns",- str(args.step2_max_turns),- "--language",- args.step2_language,- "--model",- model,- ]- if args.step2_no_evolve:- step2_cmd.append("--no-evolve")- if args.step2_verbose:- step2_cmd.append("--verbose")- _run(step2_cmd, env_step2)-- env_step3 = os.environ.copy()- env_step3["LLM_MODEL"] = args.judge_model-- step3_cmd = [- sys.executable,- str(PROJECT_ROOT / "benchmark" / "pipeline" / "step3_evaluate_transcripts.py"),- "--kb-names",- kb_names,- "--output-root",- str(output_root),- "--backends",- args.backends,- "--concurrency",- str(args.step3_concurrency),- "--temperature",- str(args.step3_temperature),- ]- if args.step3_skip_turns:- step3_cmd.append("--skip-turns")- _run(step3_cmd, env_step3)-- runs.append(- {- "step2_model": model,- "step2_model_key": model_key,- "judge_model": args.judge_model,- "output_root": str(output_root),- "step2_manifest": str(output_root / "manifests" / "step2_manifest.json"),- "step3_manifest": str(output_root / "manifests" / "step3_manifest.json"),- "step3_summary": str(output_root / "manifests" / "step3_summary.json"),- "step3_summary_data": _load_json(output_root / "manifests" / "step3_summary.json"),- }- )-- summary = {- "timestamp": datetime.now().isoformat(),- "kb_names": _parse_names(args.kb_names),- "backends": _parse_names(args.backends),- "judge_model": args.judge_model,- "base_output_root": str(base_output_root),- "runs": runs,- }-- manifests_dir = base_output_root / "manifests"- manifests_dir.mkdir(parents=True, exist_ok=True)- out_path = manifests_dir / "multimodel_step2_then_step3_summary.json"- with open(out_path, "w", encoding="utf-8") as f:- json.dump(summary, f, ensure_ascii=False, indent=2)-- print(f"\nSummary: {out_path}")- print("Done.")---if __name__ == "__main__":- main()-diff --git a/benchmark/pipeline/step1_generate_entries.py b/benchmark/pipeline/step1_generate_entries.pydeleted file mode 100644index 0ac8107f2..000000000--- a/benchmark/pipeline/step1_generate_entries.py+++ /dev/null@@ -1,357 +0,0 @@-#!/usr/bin/env python3-"""-Step 1: Generate benchmark entries grouped by KB.--For each KB:-1) Generate knowledge scope-2) Generate profiles-3) For each profile, generate entries (gaps + tasks) in parallel--Output layout (stable, KB-separated):- <output_root>/entries/<kb_name>/knowledge_scope.json- <output_root>/entries/<kb_name>/profiles.json- <output_root>/entries/<kb_name>/profiles/<profile_id>/profile.json- <output_root>/entries/<kb_name>/profiles/<profile_id>/entries.jsonl- <output_root>/entries/<kb_name>/profiles/<profile_id>/entries/<entry_id>.json--Manifest:- <output_root>/manifests/step1_manifest.json-"""--from __future__ import annotations--import argparse-import asyncio-import json-import logging-import shutil-import sys-from datetime import datetime-from pathlib import Path--import yaml--_THIS_FILE = Path(__file__).resolve()-PROJECT_ROOT = _THIS_FILE.parents[2]-if str(PROJECT_ROOT) not in sys.path:- sys.path.insert(0, str(PROJECT_ROOT))--from benchmark.data_generation.profile_generator import generate_profiles_for_kb-from benchmark.data_generation.scope_generator import generate_knowledge_scope-from benchmark.simulation.batch_simulation import _generate_entries_for_profile--logger = logging.getLogger("benchmark.pipeline.step1")--DEFAULT_CONFIG = PROJECT_ROOT / "benchmark" / "config" / "benchmark_config.yaml"-DEFAULT_OUTPUT_ROOT = PROJECT_ROOT / "benchmark" / "data" / "bench_pipeline"---def _parse_kb_names(raw: str) -> list[str]:- names = [n.strip() for n in raw.split(",") if n.strip()]- return sorted(set(names))---def _save_profile_entries(entries: list[dict], profile_dir: Path) -> None:- if profile_dir.exists():- shutil.rmtree(profile_dir)- (profile_dir / "entries").mkdir(parents=True, exist_ok=True)-- jsonl_path = profile_dir / "entries.jsonl"- with open(jsonl_path, "w", encoding="utf-8") as f:- for entry in entries:- f.write(json.dumps(entry, ensure_ascii=False) + "\n")-- for entry in entries:- entry_id = entry.get("entry_id", "unknown")- out = profile_dir / "entries" / f"{entry_id}.json"- with open(out, "w", encoding="utf-8") as f:- json.dump(entry, f, ensure_ascii=False, indent=2)---async def _generate_entries_for_one_profile(- *,- kb_name: str,- profile: dict,- scope: dict,- cfg: dict,- kb_base_dir: str,- kb_entries_dir: Path,- semaphore: asyncio.Semaphore,-) -> dict:- async with semaphore:- profile_id = profile.get("profile_id", "unknown")- profile_dir = kb_entries_dir / "profiles" / profile_id- result = {- "kb_name": kb_name,- "profile_id": profile_id,- "status": "ok",- "num_entries": 0,- "error": None,- "entries_path": str(profile_dir / "entries.jsonl"),- }- try:- entries = await _generate_entries_for_profile(- kb_name=kb_name,- profile=profile,- knowledge_scope=scope,- cfg=cfg,- kb_base_dir=kb_base_dir,- )- _save_profile_entries(entries, profile_dir)- with open(profile_dir / "profile.json", "w", encoding="utf-8") as f:- json.dump(profile, f, ensure_ascii=False, indent=2)- result["num_entries"] = len(entries)- logger.info("[%s] %s -> %d entries", kb_name, profile_id, len(entries))- except Exception as e:- result["status"] = "error"- result["error"] = str(e)- logger.error("[%s] %s failed: %s", kb_name, profile_id, e)- return result---async def _process_one_kb(- *,- kb_name: str,- kb_base_dir: Path,- entries_root: Path,- profile_cfg: dict,- rag_cfg: dict,- cfg: dict,- profile_semaphore: asyncio.Semaphore,- kb_semaphore: asyncio.Semaphore,-) -> tuple[dict, int]:- """Process one KB: scope -> profiles -> entries (profiles in parallel)."""- async with kb_semaphore:- kb_dir = kb_base_dir / kb_name- kb_entry_root = entries_root / kb_name- kb_entry_root.mkdir(parents=True, exist_ok=True)-- kb_record = {- "kb_name": kb_name,- "status": "ok",- "error": None,- "num_profiles": 0,- "profiles": [],- }- profile_errors = 0-- if not kb_dir.exists():- kb_record["status"] = "error"- kb_record["error"] = f"KB directory not found: {kb_dir}"- logger.error("[%s] KB directory not found", kb_name)- return kb_record, profile_errors-- try:- scope = await generate_knowledge_scope(- kb_name=kb_name,- seed_queries=rag_cfg.get("seed_queries"),- mode=rag_cfg.get("mode", "naive"),- kb_base_dir=str(kb_base_dir),- )- kb_entry_root.mkdir(parents=True, exist_ok=True)- with open(kb_entry_root / "knowledge_scope.json", "w", encoding="utf-8") as f:- json.dump(scope, f, ensure_ascii=False, indent=2)- except Exception as e:- kb_record["status"] = "error"- kb_record["error"] = f"knowledge_scope generation failed: {e}"- logger.error("[%s] knowledge_scope failed: %s", kb_name, e)- return kb_record, profile_errors-- try:- profiles = await generate_profiles_for_kb(- knowledge_scope=scope,- background_types=profile_cfg.get(- "background_types", ["beginner", "intermediate", "advanced"]- ),- profiles_per_kb=profile_cfg.get("profiles_per_subtopic", 3),- )- with open(kb_entry_root / "profiles.json", "w", encoding="utf-8") as f:- json.dump(profiles, f, ensure_ascii=False, indent=2)- kb_record["num_profiles"] = len(profiles)- except Exception as e:- kb_record["status"] = "error"- kb_record["error"] = f"profile generation failed: {e}"- logger.error("[%s] profile generation failed: %s", kb_name, e)- return kb_record, profile_errors-- tasks = [- _generate_entries_for_one_profile(- kb_name=kb_name,- profile=p,- scope=scope,- cfg=cfg,- kb_base_dir=str(kb_base_dir),- kb_entries_dir=kb_entry_root,- semaphore=profile_semaphore,- )- for p in profiles- ]- profile_results = await asyncio.gather(*tasks, return_exceptions=True)-- for r in profile_results:- if isinstance(r, Exception):- profile_errors += 1- kb_record["profiles"].append(- {- "status": "error",- "error": str(r),- }- )- continue- kb_record["profiles"].append(r)- if r.get("status") != "ok":- profile_errors += 1-- return kb_record, profile_errors---async def main() -> None:- logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )- parser = argparse.ArgumentParser(- description="Step1: generate profiles + entries for KBs"- )- parser.add_argument(- "--kb-names",- required=True,- help="Comma-separated KB names to process",- )- parser.add_argument(- "--kb-dir",- default="data/knowledge_bases",- help="Knowledge base directory (default: data/knowledge_bases)",- )- parser.add_argument(- "--config",- default=str(DEFAULT_CONFIG),- help=f"Benchmark config path (default: {DEFAULT_CONFIG})",- )- parser.add_argument(- "--output-root",- default=str(DEFAULT_OUTPUT_ROOT),- help=f"Pipeline output root (default: {DEFAULT_OUTPUT_ROOT})",- )- parser.add_argument(- "--concurrency",- type=int,- default=6,- help="Max parallel profile entry-generation tasks (default: 6)",- )- parser.add_argument(- "--kb-concurrency",- type=int,- default=6,- help="Max parallel KB tasks (default: 6)",- )- parser.add_argument(- "--force",- action="store_true",- help="Accepted for compatibility; output is overwritten by default.",- )- args = parser.parse_args()-- kb_names = _parse_kb_names(args.kb_names)- kb_base_dir = Path(args.kb_dir)- if not kb_base_dir.is_absolute():- kb_base_dir = (PROJECT_ROOT / kb_base_dir).resolve()-- cfg_path = Path(args.config)- if not cfg_path.is_absolute():- cfg_path = (PROJECT_ROOT / cfg_path).resolve()- with open(cfg_path, encoding="utf-8") as f:- cfg = yaml.safe_load(f) or {}-- output_root = Path(args.output_root)- if not output_root.is_absolute():- output_root = (PROJECT_ROOT / output_root).resolve()- entries_root = output_root / "entries"- manifests_root = output_root / "manifests"- entries_root.mkdir(parents=True, exist_ok=True)- manifests_root.mkdir(parents=True, exist_ok=True)-- profile_cfg = cfg.get("profile_generation", {})- rag_cfg = cfg.get("rag_query", {})-- kb_parallel = max(1, args.kb_concurrency)- print(- f"KBs: {len(kb_names)} | Concurrency(profile): {args.concurrency} | "- f"Concurrency(kb): {kb_parallel}"- )- print(f"Output root: {output_root}")- for kb in kb_names:- print(f" - {kb}")-- profile_sem = asyncio.Semaphore(args.concurrency)- # Keep KB-level parallelism moderate to avoid overloading RAG/LLM services.- kb_sem = asyncio.Semaphore(kb_parallel)- logger.info(- "Step1 parallelism: kb_concurrency=%d, profile_concurrency=%d",- kb_parallel,- args.concurrency,- )-- kb_tasks = [- _process_one_kb(- kb_name=kb_name,- kb_base_dir=kb_base_dir,- entries_root=entries_root,- profile_cfg=profile_cfg,- rag_cfg=rag_cfg,- cfg=cfg,- profile_semaphore=profile_sem,- kb_semaphore=kb_sem,- )- for kb_name in kb_names- ]- raw_results = await asyncio.gather(*kb_tasks, return_exceptions=True)-- kb_records: list[dict] = []- total_profile_errors = 0- for i, item in enumerate(raw_results):- if isinstance(item, Exception):- kb_name = kb_names[i]- kb_records.append(- {- "kb_name": kb_name,- "status": "error",- "error": str(item),- "num_profiles": 0,- "profiles": [],- }- )- logger.error("[%s] unexpected failure: %s", kb_name, item)- continue- kb_record, profile_errors = item- kb_records.append(kb_record)- total_profile_errors += profile_errors-- manifest = {- "step": "step1_generate_entries",- "timestamp": datetime.now().isoformat(),- "kb_names": kb_names,- "output_root": str(output_root),- "concurrency_profile": args.concurrency,- "concurrency_kb": kb_parallel,- "overwrite": True,- "results": kb_records,- "num_kbs": len(kb_names),- "num_kb_errors": sum(1 for r in kb_records if r.get("status") != "ok"),- "num_profile_errors": total_profile_errors,- }- manifest_path = manifests_root / "step1_manifest.json"- with open(manifest_path, "w", encoding="utf-8") as f:- json.dump(manifest, f, ensure_ascii=False, indent=2)-- print(f"\nManifest: {manifest_path}")- print(- f"Done. KB errors: {manifest['num_kb_errors']} | "- f"Profile errors: {manifest['num_profile_errors']}"- )- if manifest["num_kb_errors"] > 0 or manifest["num_profile_errors"] > 0:- sys.exit(1)---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/pipeline/step2_generate_transcripts.py b/benchmark/pipeline/step2_generate_transcripts.pydeleted file mode 100644index 02eebe1ec..000000000--- a/benchmark/pipeline/step2_generate_transcripts.py+++ /dev/null@@ -1,410 +0,0 @@-#!/usr/bin/env python3-"""-Step 2: Run simulations per profile, backend serially.--Input:- <output_root>/entries/<kb_name>/profiles/<profile_id>/entries.jsonl--Output:- <output_root>/transcripts/<kb_name>/<backend>/<profile_id>.json- <output_root>/workspaces/<kb_name>/<backend>/<profile_id>/--Manifest:- <output_root>/manifests/step2_manifest.json-"""--from __future__ import annotations--import argparse-import asyncio-import contextlib-import io-import json-import logging-import os-import sys-from datetime import datetime-from pathlib import Path-from typing import Literal--_THIS_FILE = Path(__file__).resolve()-PROJECT_ROOT = _THIS_FILE.parents[2]-if str(PROJECT_ROOT) not in sys.path:- sys.path.insert(0, str(PROJECT_ROOT))--from benchmark.simulation.profile_evolver import evolve_profile as evolve_profile_fn--logger = logging.getLogger("benchmark.pipeline.step2")--DEFAULT_OUTPUT_ROOT = PROJECT_ROOT / "benchmark" / "data" / "bench_pipeline"---def _parse_names(raw: str) -> list[str]:- return sorted(set(n.strip() for n in raw.split(",") if n.strip()))---def _load_entries(entries_jsonl: Path) -> list[dict]:- entries: list[dict] = []- with open(entries_jsonl, encoding="utf-8") as f:- for line in f:- line = line.strip()- if line:- entries.append(json.loads(line))- return entries---async def _simulate_profile_backend(- *,- kb_name: str,- profile_id: str,- entries: list[dict],- backend: Literal["deep_tutor", "mock"],- output_root: Path,- max_turns: int,- language: str,- evolve_profile: bool,- verbose: bool,-) -> dict:- from benchmark.simulation.conversation import (- _run_single_session,- _summarize_session,- )-- if not entries:- logger.warning("[%s/%s] %s has 0 entries, skipping", kb_name, backend, profile_id)- return {- "status": "skipped",- "backend": backend,- "profile_id": profile_id,- "kb_name": kb_name,- "num_sessions": 0,- "transcript_path": "",- "error": "0 entries",- }-- workspace = str(output_root / "workspaces" / kb_name / backend / profile_id)- prior_sessions_summary: list[str] = []- current_profile = entries[0].get("profile", {})- sessions_results: list[dict] = []-- for i, base_entry in enumerate(entries):- session_num = i + 1- entry = dict(base_entry)-- if evolve_profile and i > 0:- prev_profile = entries[i - 1].get("profile", {})- resolved = entries[i - 1].get("gaps", [])- current_profile = evolve_profile_fn(prev_profile, resolved)- entry["profile"] = current_profile-- prior_ctx = "\n".join(prior_sessions_summary) if prior_sessions_summary else None- logger.info(- "[%s/%s] %s session %d/%d",- kb_name,- backend,- profile_id,- session_num,- len(entries),- )-- try:- if verbose:- result = await _run_single_session(- entry=entry,- max_turns=max_turns,- auto=True,- use_editor=False,- auto_backend=backend,- deeptutor_workspace=workspace,- deeptutor_language=language,- prior_sessions_summary=prior_ctx,- )- else:- with contextlib.redirect_stdout(io.StringIO()):- result = await _run_single_session(- entry=entry,- max_turns=max_turns,- auto=True,- use_editor=False,- auto_backend=backend,- deeptutor_workspace=workspace,- deeptutor_language=language,- prior_sessions_summary=prior_ctx,- )- except Exception as e:- logger.error(- "[%s/%s] %s session %d failed: %s",- kb_name,- backend,- profile_id,- session_num,- e,- )- result = {- "entry_id": entry.get("entry_id", f"session_{session_num}"),- "transcript": [],- "entry": entry,- "actual_turns": 0,- "practice_questions": [],- "error": str(e),- }-- summary = _summarize_session(result.get("transcript", []), entry.get("task", {}), session_num)- prior_sessions_summary.append(summary)- sessions_results.append(result)-- combined = {- "kb_name": kb_name,- "profile_id": profile_id,- "backend": backend,- "timestamp": datetime.now().isoformat(),- "mode": "auto",- "evolve_profile": evolve_profile,- "num_sessions": len(sessions_results),- "sessions": [- {- "entry_id": r["entry_id"],- "actual_turns": r["actual_turns"],- "transcript": r.get("transcript", []),- "entry": r["entry"],- "practice_questions": r.get("practice_questions", []),- }- for r in sessions_results- ],- }-- transcript_path = output_root / "transcripts" / kb_name / backend / f"{profile_id}.json"- transcript_path.parent.mkdir(parents=True, exist_ok=True)- with open(transcript_path, "w", encoding="utf-8") as f:- json.dump(combined, f, ensure_ascii=False, indent=2)-- return {- "status": "ok",- "backend": backend,- "profile_id": profile_id,- "kb_name": kb_name,- "num_sessions": combined.get("num_sessions", 0),- "transcript_path": str(transcript_path),- "error": None,- }---async def _process_profile(- *,- kb_name: str,- profile_id: str,- entries: list[dict],- backends: list[str],- output_root: Path,- semaphore: asyncio.Semaphore,- max_turns: int,- language: str,- evolve_profile: bool,- verbose: bool,-) -> dict:- async with semaphore:- record = {- "kb_name": kb_name,- "profile_id": profile_id,- "status": "ok",- "num_entries": len(entries),- "backends": {},- "error": None,- }- for backend in backends:- try:- result = await _simulate_profile_backend(- kb_name=kb_name,- profile_id=profile_id,- entries=entries,- backend=backend, # type: ignore[arg-type]- output_root=output_root,- max_turns=max_turns,- language=language,- evolve_profile=evolve_profile,- verbose=verbose,- )- record["backends"][backend] = result- except Exception as e:- record["status"] = "error"- record["backends"][backend] = {- "status": "error",- "error": str(e),- }- logger.error("[%s] %s backend=%s failed: %s", kb_name, profile_id, backend, e)- return record---async def main() -> None:- logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )- parser = argparse.ArgumentParser(description="Step2: run simulations to generate transcripts")- parser.add_argument("--kb-names", required=True, help="Comma-separated KB names to process")- parser.add_argument(- "--output-root",- default=str(DEFAULT_OUTPUT_ROOT),- help=f"Pipeline output root (default: {DEFAULT_OUTPUT_ROOT})",- )- parser.add_argument(- "--backends",- default="mock,deep_tutor",- help="Comma-separated backends (executed serially per profile)",- )- parser.add_argument("--concurrency", type=int, default=6, help="Max parallel profiles")- parser.add_argument("--max-turns", type=int, default=30, help="Max student turns per session")- parser.add_argument("--language", default="en", help="DeepTutor language")- parser.add_argument(- "--model",- default="",- help="Override LLM model for step2 simulation. If set, ignores env LLM_MODEL.",- )- parser.add_argument("--no-evolve", action="store_true", help="Disable profile evolution")- parser.add_argument("--verbose", "-v", action="store_true", help="Show per-turn output")- parser.add_argument(- "--force",- action="store_true",- help="Accepted for compatibility; transcripts are overwritten by default.",- )- args = parser.parse_args()-- if args.model:- # Force model override for this process.- os.environ["LLM_MODEL"] = args.model- try:- from src.services.llm.config import clear_llm_config_cache-- clear_llm_config_cache()- except Exception:- pass-- # Suppress noisy logs from RAG/LLM internals during auto simulation- from benchmark.simulation.conversation import _suppress_noisy_auto_logs-- _suppress_noisy_auto_logs()- logging.getLogger("benchmark.pipeline.step2").setLevel(logging.INFO)- logging.getLogger("benchmark.conversation").setLevel(logging.INFO)-- kb_names = _parse_names(args.kb_names)- backends = _parse_names(args.backends)- output_root = Path(args.output_root)- if not output_root.is_absolute():- output_root = (PROJECT_ROOT / output_root).resolve()- entries_root = output_root / "entries"- manifests_root = output_root / "manifests"- manifests_root.mkdir(parents=True, exist_ok=True)-- print(f"KBs: {len(kb_names)} | Concurrency(profile): {args.concurrency}")- print(f"Backends(serial/profile): {backends}")- print(f"Output root: {output_root}")-- sem = asyncio.Semaphore(args.concurrency)- tasks = []- pre_errors: list[dict] = []- for kb_name in kb_names:- kb_profiles_root = entries_root / kb_name / "profiles"- if not kb_profiles_root.exists():- pre_errors.append(- {- "kb_name": kb_name,- "profile_id": None,- "status": "error",- "error": f"Missing entries directory: {kb_profiles_root}",- }- )- logger.error("[%s] missing entries directory: %s", kb_name, kb_profiles_root)- continue- for profile_dir in sorted(p for p in kb_profiles_root.iterdir() if p.is_dir()):- profile_id = profile_dir.name- entries_path = profile_dir / "entries.jsonl"- if not entries_path.exists():- pre_errors.append(- {- "kb_name": kb_name,- "profile_id": profile_id,- "status": "error",- "error": f"Missing entries.jsonl: {entries_path}",- }- )- logger.error("[%s] %s missing entries.jsonl", kb_name, profile_id)- continue- try:- entries = _load_entries(entries_path)- except Exception as e:- pre_errors.append(- {- "kb_name": kb_name,- "profile_id": profile_id,- "status": "error",- "error": f"Failed to load entries.jsonl: {e}",- }- )- continue- if not entries:- pre_errors.append(- {- "kb_name": kb_name,- "profile_id": profile_id,- "status": "error",- "error": f"entries.jsonl is empty (0 entries): {entries_path}",- }- )- logger.error("[%s] %s has 0 entries, skipping", kb_name, profile_id)- continue- tasks.append(- _process_profile(- kb_name=kb_name,- profile_id=profile_id,- entries=entries,- backends=backends,- output_root=output_root,- semaphore=sem,- max_turns=args.max_turns,- language=args.language,- evolve_profile=not args.no_evolve,- verbose=args.verbose,- )- )-- logger.info("Launching %d profile simulation tasks", len(tasks))- results = await asyncio.gather(*tasks, return_exceptions=True)-- profile_results = []- task_errors = 0- for r in results:- if isinstance(r, Exception):- task_errors += 1- profile_results.append({"status": "error", "error": str(r)})- else:- profile_results.append(r)- if r.get("status") != "ok":- task_errors += 1-- manifest = {- "step": "step2_generate_transcripts",- "timestamp": datetime.now().isoformat(),- "kb_names": kb_names,- "backends": backends,- "model": (args.model or os.getenv("LLM_MODEL", "")),- "output_root": str(output_root),- "concurrency_profile": args.concurrency,- "backend_execution": "serial_per_profile",- "overwrite": True,- "pre_errors": pre_errors,- "results": profile_results,- "num_profiles": len(profile_results),- "num_errors": len(pre_errors) + task_errors,- }- manifest_path = manifests_root / "step2_manifest.json"- with open(manifest_path, "w", encoding="utf-8") as f:- json.dump(manifest, f, ensure_ascii=False, indent=2)-- print(f"\nManifest: {manifest_path}")- print(f"Done. Profile tasks: {len(profile_results)} | Errors: {manifest['num_errors']}")- if manifest["num_errors"] > 0:- sys.exit(1)---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/pipeline/step3_evaluate_transcripts.py b/benchmark/pipeline/step3_evaluate_transcripts.pydeleted file mode 100644index 5c0b159cb..000000000--- a/benchmark/pipeline/step3_evaluate_transcripts.py+++ /dev/null@@ -1,351 +0,0 @@-#!/usr/bin/env python3-"""-Step 3: Evaluate transcripts for specified KBs.--Only evaluates transcripts that belong to input KB names.-Missing transcripts are recorded as errors (continue-on-error).--Input:- Expected profile set from:- <output_root>/entries/<kb_name>/profiles/<profile_id>/entries.jsonl- Transcript:- <output_root>/transcripts/<kb_name>/<backend>/<profile_id>.json--Output:- <output_root>/evaluations/<kb_name>/<backend>/<profile_id>_eval.json--Manifest:- <output_root>/manifests/step3_manifest.json-"""--from __future__ import annotations--import argparse-import asyncio-import json-import logging-import sys-from datetime import datetime-from pathlib import Path-from typing import Any--_THIS_FILE = Path(__file__).resolve()-PROJECT_ROOT = _THIS_FILE.parents[2]-if str(PROJECT_ROOT) not in sys.path:- sys.path.insert(0, str(PROJECT_ROOT))--from benchmark.evaluation.evaluator import evaluate_transcript--logger = logging.getLogger("benchmark.pipeline.step3")--DEFAULT_OUTPUT_ROOT = PROJECT_ROOT / "benchmark" / "data" / "bench_pipeline"---def _parse_names(raw: str) -> list[str]:- return sorted(set(n.strip() for n in raw.split(",") if n.strip()))---async def _evaluate_one_transcript(- *,- kb_name: str,- profile_id: str,- backend: str,- transcript_path: Path,- output_root: Path,- temperature: float,- skip_turns: bool,- semaphore: asyncio.Semaphore,-) -> dict:- async with semaphore:- out_path = output_root / "evaluations" / kb_name / backend / f"{profile_id}_eval.json"- out_path.parent.mkdir(parents=True, exist_ok=True)- record = {- "kb_name": kb_name,- "profile_id": profile_id,- "backend": backend,- "transcript_path": str(transcript_path),- "evaluation_path": str(out_path),- "status": "ok",- "error": None,- }- try:- result = await evaluate_transcript(- transcript_path=transcript_path,- skip_turns=skip_turns,- temperature=temperature,- )- with open(out_path, "w", encoding="utf-8") as f:- json.dump(result, f, ensure_ascii=False, indent=2)- except Exception as e:- record["status"] = "error"- record["error"] = str(e)- logger.error("[%s/%s] %s eval failed: %s", kb_name, backend, profile_id, e)- return record---def _extract_eval_summary(eval_data: dict) -> dict:- agg = eval_data.get("aggregate", {})- summary = {- "turn_count": agg.get("turn_count", {}),- "gap_tracking": agg.get("gap_tracking", {}),- "source_faithfulness": agg.get("source_faithfulness", {}),- "teaching_quality": agg.get("teaching_quality", {}),- }- pq = agg.get("practice_questions")- if pq:- summary["practice_questions"] = pq- return summary---def _safe_avg(vals: list[float]) -> float | None:- return round(sum(vals) / len(vals), 2) if vals else None---def _build_aggregate_summary(results: list[dict], output_root: Path) -> dict:- grouped: dict[str, dict[str, Any]] = {}- for r in results:- if r.get("status") != "ok":- continue- backend = r.get("backend", "unknown")- grouped.setdefault(- backend,- {- "num_profiles": 0,- "paired_turns_total": 0,- "total_resolved": 0,- "total_gaps": 0,- "faithfulness_scores": [],- "insightfulness_scores": [],- "applicability_scores": [],- "pq_total_questions": 0,- "pq_gap_coverage": [],- "pq_difficulty_abs": [],- "pq_groundedness": [],- "pq_distractor_quality": [],- "pq_diversity": [],- },- )- try:- with open(r["evaluation_path"], encoding="utf-8") as f:- eval_data = json.load(f)- except Exception:- continue- s = _extract_eval_summary(eval_data)- g = grouped[backend]- g["num_profiles"] += 1- g["paired_turns_total"] += (- s.get("turn_count", {}).get("paired_turns_total", 0)- )- gt = s.get("gap_tracking", {})- g["total_resolved"] += gt.get("total_resolved", 0)- g["total_gaps"] += gt.get("total_gaps", 0)- faith = s.get("source_faithfulness", {}).get("avg_score_overall")- if isinstance(faith, (int, float)):- g["faithfulness_scores"].append(float(faith))- insight = s.get("teaching_quality", {}).get("avg_insightfulness_overall")- if isinstance(insight, (int, float)):- g["insightfulness_scores"].append(float(insight))- app = s.get("teaching_quality", {}).get("avg_applicability_overall")- if isinstance(app, (int, float)):- g["applicability_scores"].append(float(app))-- pq = s.get("practice_questions", {})- if pq:- g["pq_total_questions"] += pq.get("total_questions_across_sessions", 0)- for key, lst_key in [- ("avg_gap_coverage", "pq_gap_coverage"),- ("avg_difficulty_abs", "pq_difficulty_abs"),- ("avg_groundedness", "pq_groundedness"),- ("avg_distractor_quality", "pq_distractor_quality"),- ("avg_diversity", "pq_diversity"),- ]:- v = pq.get(key)- if isinstance(v, (int, float)):- g[lst_key].append(float(v))-- out: dict[str, dict] = {}- for backend, s in grouped.items():- total_res = s["total_resolved"]- total_gap = s["total_gaps"]- turns = s["paired_turns_total"]- backend_summary: dict[str, Any] = {- "num_profiles": s["num_profiles"],- "paired_turns_total": turns,- "total_resolved_gaps": total_res,- "total_gaps": total_gap,- "gap_resolution_rate": round(total_res / total_gap, 3) if total_gap else None,- "gap_resolution_efficiency": round(total_res / turns, 3) if turns else None,- "avg_faithfulness": _safe_avg(s["faithfulness_scores"]),- "avg_insightfulness": _safe_avg(s["insightfulness_scores"]),- "avg_applicability": _safe_avg(s["applicability_scores"]),- }- if s["pq_total_questions"] > 0:- backend_summary["practice_questions"] = {- "total_questions": s["pq_total_questions"],- "avg_gap_coverage": _safe_avg(s["pq_gap_coverage"]),- "avg_difficulty_abs": _safe_avg(s["pq_difficulty_abs"]),- "avg_groundedness": _safe_avg(s["pq_groundedness"]),- "avg_distractor_quality": _safe_avg(s["pq_distractor_quality"]),- "avg_diversity": _safe_avg(s["pq_diversity"]),- }- out[backend] = backend_summary- return {- "timestamp": datetime.now().isoformat(),- "output_root": str(output_root),- "by_backend": out,- }---async def main() -> None:- logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )- parser = argparse.ArgumentParser(description="Step3: evaluate transcripts")- parser.add_argument("--kb-names", required=True, help="Comma-separated KB names")- parser.add_argument(- "--output-root",- default=str(DEFAULT_OUTPUT_ROOT),- help=f"Pipeline output root (default: {DEFAULT_OUTPUT_ROOT})",- )- parser.add_argument(- "--backends",- default="mock,deep_tutor",- help="Comma-separated backends to evaluate",- )- parser.add_argument(- "--concurrency",- type=int,- default=6,- help="Max parallel transcript evaluations",- )- parser.add_argument(- "--temperature",- type=float,- default=0.2,- help="LLM temperature for evaluation",- )- parser.add_argument(- "--skip-turns",- action="store_true",- help="Skip per-turn LLM metrics and keep only turn_count",- )- parser.add_argument(- "--force",- action="store_true",- help="Accepted for compatibility; evaluations are overwritten by default.",- )- args = parser.parse_args()-- kb_names = _parse_names(args.kb_names)- backends = _parse_names(args.backends)- output_root = Path(args.output_root)- if not output_root.is_absolute():- output_root = (PROJECT_ROOT / output_root).resolve()-- entries_root = output_root / "entries"- transcripts_root = output_root / "transcripts"- manifests_root = output_root / "manifests"- manifests_root.mkdir(parents=True, exist_ok=True)-- print(f"KBs: {len(kb_names)} | Backends: {backends}")- print(f"Concurrency(transcript): {args.concurrency}")- print(f"Output root: {output_root}")-- missing_errors: list[dict] = []- tasks = []- sem = asyncio.Semaphore(args.concurrency)-- for kb_name in kb_names:- profiles_root = entries_root / kb_name / "profiles"- if not profiles_root.exists():- missing_errors.append(- {- "kb_name": kb_name,- "profile_id": None,- "backend": None,- "error": f"Missing entries root for KB: {profiles_root}",- }- )- logger.error("[%s] missing entries root: %s", kb_name, profiles_root)- continue-- profile_ids = sorted(p.name for p in profiles_root.iterdir() if p.is_dir())- for profile_id in profile_ids:- for backend in backends:- transcript_path = transcripts_root / kb_name / backend / f"{profile_id}.json"- if not transcript_path.exists():- missing_errors.append(- {- "kb_name": kb_name,- "profile_id": profile_id,- "backend": backend,- "error": f"Missing transcript: {transcript_path}",- }- )- logger.error(- "[%s/%s] %s missing transcript", kb_name, backend, profile_id- )- continue- tasks.append(- _evaluate_one_transcript(- kb_name=kb_name,- profile_id=profile_id,- backend=backend,- transcript_path=transcript_path,- output_root=output_root,- temperature=args.temperature,- skip_turns=args.skip_turns,- semaphore=sem,- )- )-- logger.info("Launching %d transcript evaluation tasks", len(tasks))- task_results = await asyncio.gather(*tasks, return_exceptions=True)-- eval_results = []- task_errors = 0- for r in task_results:- if isinstance(r, Exception):- task_errors += 1- eval_results.append({"status": "error", "error": str(r)})- else:- eval_results.append(r)- if r.get("status") != "ok":- task_errors += 1-- aggregate = _build_aggregate_summary(eval_results, output_root)- summary_path = manifests_root / "step3_summary.json"- with open(summary_path, "w", encoding="utf-8") as f:- json.dump(aggregate, f, ensure_ascii=False, indent=2)-- manifest = {- "step": "step3_evaluate_transcripts",- "timestamp": datetime.now().isoformat(),- "kb_names": kb_names,- "backends": backends,- "output_root": str(output_root),- "concurrency_transcript": args.concurrency,- "overwrite": True,- "missing_errors": missing_errors,- "results": eval_results,- "num_evaluated": len(eval_results),- "num_errors": len(missing_errors) + task_errors,- "summary_path": str(summary_path),- }- manifest_path = manifests_root / "step3_manifest.json"- with open(manifest_path, "w", encoding="utf-8") as f:- json.dump(manifest, f, ensure_ascii=False, indent=2)-- print(f"\nSummary: {summary_path}")- print(f"Manifest: {manifest_path}")- print(- f"Done. Evaluated: {manifest['num_evaluated']} | "- f"Errors: {manifest['num_errors']}"- )- if manifest["num_errors"] > 0:- sys.exit(1)---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/prompts/__init__.py b/benchmark/prompts/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/benchmark/prompts/eval_dialog.yaml b/benchmark/prompts/eval_dialog.yamldeleted file mode 100644index f9bc58f9c..000000000--- a/benchmark/prompts/eval_dialog.yaml+++ /dev/null@@ -1,74 +0,0 @@-# Evaluation prompt for the entire tutoring dialog-# Used by benchmark.evaluation.evaluator-# Merged dimensions: 50% personalization, 25% quality, 25% knowledge_source_alignment--system: |- You are an expert evaluator for AI tutoring systems. Your task is to score an ENTIRE tutoring- conversation. The student has a specific profile and the tutor should adapt throughout.- Focus on PERSONALIZATION: did the tutor consistently tailor the session to THIS student?-- ## Scoring strictness (CRITICAL)- Be VERY STRICT. Most dialogs should score 2–3. Reserve 5 for rare, exemplary sessions only.- - 5: Exceptional — would be published as a model session. Consistent, visible adaptation throughout; all gaps addressed with evidence.- - 4: Good — clear evidence of sustained adaptation; NOT just "helpful overall." Requires explicit references to profile/gaps across turns.- - 3: Adequate — acceptable but unremarkable. Mostly generic tutoring, or weak gap resolution, scores 3 at most on personalization.- - 2: Below average — weak adaptation, notable flaws, or gaps left unaddressed.- - 1: Poor — little personalization, gaps ignored, or session failed.- Rules: (1) When in doubt, score LOWER. (2) Generic dialogs MUST NOT exceed 3 on personalization. (3) For 4 or 5, cite specific evidence from the transcript. (4) "Generally helpful" without profile-specific adaptation = 3 at most.-- ## Dimensions-- **Personalization (50% of dialog score):**- - adaptation_consistency (1-5): Did the tutor maintain adaptation to the student's profile- throughout (not just at the start)? Did they adjust pacing and depth based on student- reactions (slow down when confused, advance when ready)?- - gap_resolution (1-5): Were all target gaps identified and addressed? Did the tutor follow- a sensible trajectory for exposing and correcting misconceptions (as in expected_gap_exposure)?- - success_criteria_met (1-5): To what extent were the task's success_criteria achieved by the end?-- **Session quality (25% of dialog score):**- - session_quality (1-5): Was the conversation appropriately efficient (not overly long or rushed)?- Was it coherent and focused on the task?- - student_agency (1-5): Did the tutor give the student space to think, ask, and try—rather than- lecturing?-- **Knowledge source alignment (25% of dialog score, when source provided):**- - knowledge_source_alignment (1-5): Across the entire dialog, did the tutor's explanations align- with the knowledge base source? No hallucination, no contradiction. Faithful to the textbook.- Any unsupported claims or deviations = 3 at most.- **When "Not applicable"**: Omit this key.-- Output valid JSON only, no markdown or extra text:- {- "scores": {- "adaptation_consistency": <1-5>,- "gap_resolution": <1-5>,- "success_criteria_met": <1-5>,- "session_quality": <1-5>,- "student_agency": <1-5>,- "knowledge_source_alignment": <1-5>- },- "summary": "<3-5 sentences summarizing the tutoring session quality and key observations>"- }- Include knowledge_source_alignment only when source content is provided.--user_template: |- ## Student Profile- {profile_summary}-- ## Knowledge Gaps (with source content — tutor should align explanations to this)- {gaps_summary}-- ## Task- {task_summary}-- ## Source Content (knowledge base — tutor should align with this)- {source_content_summary}-- ## Full conversation transcript- {transcript}-- ## Your task- Score the ENTIRE dialog on all dimensions (1-5). Include knowledge_source_alignment when source content is provided.- Be VERY strict: 4 or 5 require explicit, cited evidence from the transcript. Default to 3 when the session is merely adequate.- Output JSON only.diff --git a/benchmark/prompts/eval_gap_tracking_turn.yaml b/benchmark/prompts/eval_gap_tracking_turn.yamldeleted file mode 100644index 855db41c8..000000000--- a/benchmark/prompts/eval_gap_tracking_turn.yaml+++ /dev/null@@ -1,57 +0,0 @@-system: |- You evaluate ONE tutor response for gap tracking in tutoring dialogs.- Your task is to identify:- 1) which gaps are mentioned/addressed in this tutor response- 2) which gaps are newly resolved on this turn (strict standard)-- ## Strict definitions- - mentioned/addressed:- The tutor explicitly engages the misconception/knowledge hole (not just adjacent topic chatter).- - newly resolved (STRICT):- The primary criterion is whether the tutor CLEARLY EXPLAINS and CORRECTS the target gap- in a way the student can follow.- Strong resolution signals:- (a) explicit correction of the misconception/gap,- (b) clear explanation of why the old understanding is wrong and what is correct,- (c) stepwise/scaffolded explanation when the concept is non-trivial (e.g., broken-down reasoning,- concrete intermediate steps, or worked logic tied to the student's confusion).- A check/confirmation step is helpful but NOT mandatory if (a)(b)(c) are strong.- Superficial mention or vague correction is NOT resolved.- - Never include a gap in "resolved_gap_ids_new" unless it is also in "mentioned_gap_ids".- - Never include previously resolved gaps in "resolved_gap_ids_new".-- ## Output JSON only- {- "mentioned_gap_ids": ["gap_001", "..."],- "resolved_gap_ids_new": ["gap_001", "..."],- "rationale": "1-3 concise sentences."- }--user_template: |- ## Turn index- {turn_index}-- ## Student profile- {profile_summary}-- ## Task- {task_summary}-- ## All gaps (catalog)- {gap_catalog}-- ## Recent conversation context- {recent_context}-- ## Current student message- {student_message}-- ## Current tutor response (evaluate this)- {tutor_response}-- ## State before this turn- previously_mentioned_gap_ids: {previously_mentioned_gap_ids}- previously_resolved_gap_ids: {previously_resolved_gap_ids}-- ## Your task- Return JSON only with mentioned_gap_ids and resolved_gap_ids_new using strict criteria.diff --git a/benchmark/prompts/eval_source_faithfulness_turn.yaml b/benchmark/prompts/eval_source_faithfulness_turn.yamldeleted file mode 100644index 11b32bb80..000000000--- a/benchmark/prompts/eval_source_faithfulness_turn.yaml+++ /dev/null@@ -1,69 +0,0 @@-system: |- You evaluate source faithfulness for ONE tutor response.-- IMPORTANT distinction:- - A tutor MUST go beyond the source to teach effectively: analogies, examples,- simplified explanations, application scenarios, and follow-up questions are- all legitimate and should NOT be penalized.- - You are checking THREE aspects:- (a) Factual consistency: when the tutor makes factual claims about concepts- that ARE covered in the provided source excerpts, do those claims align- with what the source says? Contradictions or distortions of source- material are penalized; going beyond the source is not.- (b) Terminological consistency: does the tutor use the same definitions,- terminology, and framing as the source? Different textbooks may define- the same concept differently. The tutor should follow the source's- conventions, not introduce alternative definitions that conflict with- how the source presents the material.- (c) Source grounding: does the tutor's response show evidence of drawing- from the actual source material? A response that references specific- details, examples, or structures from the source (even paraphrased)- demonstrates better faithfulness than one that relies entirely on- generic knowledge without any connection to the source.-- Score on 1-5:- - 5: All claims are accurate, terminology matches the source, and the response- clearly draws on specific source content (references details/structures- from the source material).- - 4: Mostly consistent with source; minor imprecision in wording but no- meaningful deviation. Some evidence of source grounding.- - 3: Some claims or definitions deviate from the source's framing, or the- response appears largely generic with weak connection to source material.- - 2: Multiple claims contradict the source, key terms use different definitions,- or the response shows no evidence of consulting the source at all.- - 1: Core claims are wrong or hallucinated, or terminology directly conflicts- with the source's definitions.-- Do NOT penalize:- - Analogies, metaphors, or simplified restatements (unless they misrepresent the source)- - Examples, applications, or extensions not mentioned in the source- - Pedagogical elaboration (follow-up questions, scaffolding, encouragement)-- Output JSON only:- {- "faithfulness_score": 1,- "rationale": "1-3 concise sentences.",- "contradictions": ["only list claims that CONTRADICT or DISTORT the source"]- }--user_template: |- ## Turn index- {turn_index}-- ## Recent conversation context- {recent_context}-- ## Current student message- {student_message}-- ## Current tutor response (evaluate this)- {tutor_response}-- ## Mentioned gaps on this turn- {mentioned_gap_ids}-- ## Source excerpts for mentioned gaps- {source_content_for_mentioned_gaps}-- ## Your task- Score source faithfulness (1-5) for the current tutor response. Output JSON only.diff --git a/benchmark/prompts/eval_teaching_quality_turn.yaml b/benchmark/prompts/eval_teaching_quality_turn.yamldeleted file mode 100644index 506ec6283..000000000--- a/benchmark/prompts/eval_teaching_quality_turn.yaml+++ /dev/null@@ -1,64 +0,0 @@-system: |- You evaluate teaching quality for ONE tutor response in a tutoring dialogue.-- Score two independent dimensions on 1-5:-- 1) Insightfulness:- Does the tutor diagnose the student's specific confusion and build deeper- understanding — or just deliver a generically correct explanation?-- - 5: Precisely identifies the student's specific misconception or confusion- point, reveals the deeper "why" (underlying principles, how concepts- connect), and uses guiding questions or analogies to lead the student- toward understanding rather than just stating the answer.- - 4: Good diagnosis of the student's issue with meaningful conceptual- depth; minor room for improvement in guiding vs. telling.- - 3: Gives a correct explanation, but it is generic — it would be roughly- the same response regardless of what the student specifically said or- where exactly they are confused. Does not clearly diagnose the student's- particular misunderstanding.- - 2: Superficial or formulaic response with little diagnostic effort;- mostly restates facts without revealing structure or reasoning.- - 1: Only states conclusions or mechanical steps with no conceptual- insight or attention to the student's specific situation.-- 2) Applicability:- Does the tutor provide concrete, actionable guidance specific to the- student's question — or give generic advice?-- - 5: Provides specific, actionable steps or concrete examples that- directly address the student's question. Includes verifiable elements- the student can act on (e.g., worked examples, step-by-step procedures,- concrete checks, calculations).- - 4: Good actionable content mostly specific to the student's situation;- minor gaps in concreteness.- - 3: Gives reasonable advice but generic or lacking concrete steps the- student can immediately follow or verify. Could apply to almost any- student asking a similar broad question.- - 2: Mostly abstract, hard for the student to execute or verify.- - 1: Vague, irrelevant, or cannot be acted upon at all.-- Use null when not applicable (e.g., pure greeting / small talk / logistics- with no real teaching content).-- Output JSON only:- {- "insightfulness_score": 1,- "applicability_score": 1,- "rationale": "1-3 concise sentences.",- "evidence": ["optional short quoted spans from tutor response"]- }--user_template: |- Evaluate this tutor turn.-- Turn index: {turn_index}-- Recent context:- {recent_context}-- Current student message:- {student_message}-- Current tutor response:- {tutor_response}diff --git a/benchmark/prompts/eval_turn.yaml b/benchmark/prompts/eval_turn.yamldeleted file mode 100644index 133099dde..000000000--- a/benchmark/prompts/eval_turn.yaml+++ /dev/null@@ -1,77 +0,0 @@-# Evaluation prompt for a single tutor response (turn-level)-# Used by benchmark.evaluation.evaluator-# Merged dimensions: 50% personalization, 25% effectiveness, 25% knowledge_source_alignment--system: |- You are an expert evaluator for AI tutoring systems. Your task is to score a single tutor response- in a multi-turn tutoring conversation. The student has a specific profile (knowledge state, learning- style, misconceptions) and the tutor should adapt to them. Focus on PERSONALIZATION: does the tutor- tailor the response to THIS student, or give generic explanations?-- ## Scoring strictness (CRITICAL)- Be VERY STRICT. Most responses should score 2–3. Reserve 5 for rare, exemplary cases only.- - 5: Exceptional — would be published as a model example. Multiple specific, concrete adaptations visible.- - 4: Good — clear evidence of adaptation; NOT just "helpful" or "correct." Requires explicit references to student's profile/gaps.- - 3: Adequate — acceptable but unremarkable. Generic explanations, or weak adaptation, score 3 at most on personalization.- - 2: Below average — weak adaptation, notable flaws, or mostly generic content.- - 1: Poor — little personalization, incorrect, unresponsive, or ignores student context.- Rules: (1) When in doubt, score LOWER. (2) Generic responses MUST NOT exceed 3 on personalization. (3) For 4 or 5, you must cite specific evidence from the response. (4) Correct but generic explanations = 3 at most.-- ## Dimensions-- **Personalization (50% of turn score):**- - profile_adaptation (1-5): Does the tutor adapt to the student's knowledge state (avoid over-explaining known,- scaffold partially_known, introduce unknown carefully), match learning style (examples, visuals, step-by-step),- match communication style (tone, pacing), and provide appropriate scaffolding (direct vs Socratic)?- - misconception_targeting (1-5): Does the tutor address the student's specific misconceptions (beliefs/gaps)- rather than giving generic corrections?-- **Effectiveness (25% of turn score):**- - response_quality (1-5): Is the content factually correct? Does it directly address the student's question?- Is the explanation clear and well-structured?- - engagement (1-5): Does the tutor encourage participation, ask check-in questions, or invite follow-up?-- **Knowledge source alignment (25% of turn score, when source provided):**- - knowledge_source_alignment (1-5): Does the tutor's explanation align with the knowledge base source?- No hallucination, no contradiction. Faithful to the textbook material. Any unsupported claim or deviation = 3 at most.- **When "Not applicable"**: Omit this key.-- Output valid JSON only, no markdown or extra text:- {- "scores": {- "profile_adaptation": <1-5>,- "misconception_targeting": <1-5>,- "response_quality": <1-5>,- "engagement": <1-5>,- "knowledge_source_alignment": <1-5>- },- "rationale": "<2-4 sentences explaining key strengths and weaknesses>"- }- Include knowledge_source_alignment only when source content is provided.--user_template: |- ## Student Profile- {profile_summary}-- ## Knowledge Gaps (with source content — tutor should align explanations to this)- {gaps_summary}-- ## Task- {task_summary}-- ## Source Content (knowledge base — tutor should align with this)- {source_content_summary}-- ## Conversation so far (up to this turn)- {conversation_context}-- ## Student's latest message- {student_message}-- ## Tutor's response to evaluate- {tutor_response}-- ## Your task- Score the tutor's response on all dimensions (1-5). Include knowledge_source_alignment when source content is provided.- Be VERY strict: 4 or 5 require explicit, cited evidence. Default to 3 when the response is merely adequate.- Output JSON only.diff --git a/benchmark/prompts/generate_gaps.yaml b/benchmark/prompts/generate_gaps.yamldeleted file mode 100644index 21a9ff1f9..000000000--- a/benchmark/prompts/generate_gaps.yaml+++ /dev/null@@ -1,49 +0,0 @@-system: |- You are an educational assessment expert. Given a student profile and a knowledge scope,- design **knowledge gaps** for this student.- Knowledge gaps are deficiencies in the student's understanding of specific knowledge points.- The AI Tutor should be able to detect and help address these gaps during the teaching process.-- ## Gap Types- 1. **misconception**: The student has an incorrect understanding of a concept, e.g., confusing two similar concepts or misremembering a formula- 2. **incomplete**: The student knows the concept but has a partial understanding, missing important conditions or special cases- 3. **missing**: The student has absolutely no knowledge of a particular point-- ## Design Principles- - **Plausibility**: Gaps should be consistent with the student's background level (beginners and advanced students have different types of gaps)- - **Detectability**: Gaps should be naturally revealed in conversation (without needing to directly ask "do you know X?")- - **Remediability**: Gaps should be something a tutor can help fix through instruction- - **Typicality**: Gaps should represent common mistakes or confusions students have with the topic-- ## Output Format- ```json- {- "gaps": [- {- "gap_id": "gap_xxx",- "type": "misconception/incomplete/missing",- "target_concept": "The knowledge point involved",- "description": "Specific description of the gap (what the student incorrectly believes / what understanding they lack)",- "manifestation": "How this gap might manifest in conversation (what the student might say or do)",- "correct_understanding": "What the correct understanding should be",- "severity": "high/medium/low",- "common_trigger": "What kind of question or scenario would expose this gap"- }- ]- }- ```--user_template: |- ## Knowledge Scope- {knowledge_scope}-- ## Student Profile- {student_profile}-- ## Requirements- - Generate {num_gaps} knowledge gaps- - Gap type distribution reference: misconception({misconception_weight}), incomplete({incomplete_weight}), missing({missing_weight})- - Ensure gaps match the student's knowledge level- - Gaps should not overlap too much with each other-- Please generate the knowledge gaps.diff --git a/benchmark/prompts/generate_gaps_page.yaml b/benchmark/prompts/generate_gaps_page.yamldeleted file mode 100644index 13a4e1b21..000000000--- a/benchmark/prompts/generate_gaps_page.yaml+++ /dev/null@@ -1,63 +0,0 @@-# Generate knowledge gaps grounded in specific page content from content_list-# Each gap must reference source_pages (page_idx values)--system: |- You are an educational assessment expert. Given a student profile and **excerpts from a textbook**- (organized by page), design **knowledge gaps** for this student.- Knowledge gaps are deficiencies in the student's understanding of specific knowledge points.- The AI Tutor should be able to detect and help address these gaps during the teaching process.-- ## CRITICAL: Source grounding- - Each gap MUST be grounded in the provided page content. The target_concept and correct_understanding- must come from or be directly supported by the source text.- - Each gap MUST include "source_pages": a list of page indices (integers) where the concept appears.- - Do NOT invent concepts not present in the source. If the pages don't cover a concept, don't create a gap for it.-- ## Gap Types- 1. **misconception**: The student has an incorrect understanding of a concept, e.g., confusing two similar concepts or misremembering a formula- 2. **incomplete**: The student knows the concept but has a partial understanding, missing important conditions or special cases- 3. **missing**: The student has absolutely no knowledge of a particular point-- ## Design Principles- - **Plausibility**: Gaps should be consistent with the student's background level- - **Detectability**: Gaps should be naturally revealed in conversation- - **Remediability**: Gaps should be something a tutor can help fix through instruction- - **Typicality**: Gaps should represent common mistakes or confusions students have with the topic-- ## Output Format- ```json- {- "gaps": [- {- "gap_id": "gap_xxx",- "type": "misconception/incomplete/missing",- "target_concept": "The knowledge point involved (must appear in source pages)",- "description": "Specific description of the gap",- "manifestation": "How this gap might manifest in conversation",- "correct_understanding": "What the correct understanding should be (must align with source text)",- "severity": "high/medium/low",- "common_trigger": "What kind of question or scenario would expose this gap",- "source_pages": [3, 4, 5]- }- ]- }- ```-- **Important**: source_pages must be a list of integers from the page indices in the provided content.--user_template: |- ## Source Content (by page index)- {page_content}-- ## Student Profile- {student_profile}-- ## Requirements- - Generate {num_gaps} knowledge gaps- - Gap type distribution reference: misconception({misconception_weight}), incomplete({incomplete_weight}), missing({missing_weight})- - Each gap MUST have "source_pages" listing the page indices where the concept appears- - correct_understanding must be supported by the source text- - Ensure gaps match the student's knowledge level- - Gaps should not overlap too much with each other-- Please generate the knowledge gaps.diff --git a/benchmark/prompts/generate_knowledge_scope.yaml b/benchmark/prompts/generate_knowledge_scope.yamldeleted file mode 100644index 51e803e52..000000000--- a/benchmark/prompts/generate_knowledge_scope.yaml+++ /dev/null@@ -1,47 +0,0 @@-system: |- You are an educational assessment expert. Given retrieved content from a knowledge base,- generate a **knowledge scope description** for that knowledge base.- This description will be used downstream to generate virtual student profiles and knowledge gaps,- in order to evaluate whether an AI Tutor teaches accurately within the knowledge scope.-- ## Requirements- 1. **Completeness**: Cover all core concepts in the knowledge base- 2. **Hierarchy**: Describe the overall domain first, then list specific knowledge points from macro to micro- 3. **Precision**: Use accurate academic terminology- 4. **Connectivity**: Identify the inherent relationships between knowledge points-- ## Output Format- Output strictly in the following JSON format:- ```json- {- "domain": "The broader field this belongs to",- "subtopic_title": "Subtopic name",- "overview": "A 2-3 sentence overall description",- "core_concepts": [- {- "name": "Concept name",- "description": "Precise definition/description of the concept",- "importance": "high/medium/low",- "related_concepts": ["Related concept 1", "Related concept 2"]- }- ],- "knowledge_hierarchy": {- "foundational": ["Foundational knowledge point 1", "Foundational knowledge point 2"],- "intermediate": ["Intermediate knowledge point 1"],- "advanced": ["Advanced knowledge point 1"]- },- "typical_problems": ["Typical problem type 1", "Typical problem type 2"],- "common_misconceptions": ["Common misconception 1", "Common misconception 2"]- }- ```--user_template: |- ## Knowledge Base Name- {kb_name}-- ## Knowledge Base Content (retrieved via RAG)- Below are core content excerpts from this knowledge base:-- {kb_contents}-- Please generate a complete knowledge scope description based on the above content.diff --git a/benchmark/prompts/generate_profile.yaml b/benchmark/prompts/generate_profile.yamldeleted file mode 100644index a2b14cb16..000000000--- a/benchmark/prompts/generate_profile.yaml+++ /dev/null@@ -1,43 +0,0 @@-system: |- You are an educational assessment expert designing virtual student personas for an AI Tutor evaluation system.- Given a knowledge scope, generate a **realistic student profile**.-- ## Profile Contents- 1. **Education background**: A single sentence describing the student's education level, field, and context- 2. **Learning purpose**: Why the student is learning this topic (1-2 sentences)- 3. **Knowledge foundation**: What the student already knows, partially knows, and doesn't know about this topic- 4. **Personality**: A single paragraph combining learning style, communication habits, strengths, weaknesses, patience, and detail orientation-- ## Design Principles- - **Realism**: The profile should resemble a real student with a plausible knowledge structure (neither completely blank nor omniscient)- - **Consistency**: Background, knowledge level, and personality should be internally coherent- - **Diversity**: Different profiles should have clearly distinct characteristics- - **Testability**: The profile's traits should be observable during conversation-- ## Output Format- ```json- {- "profile_id": "profile_xxx",- "education_background": "A single sentence, e.g. 'First-year undergraduate in Physics'",- "learning_purpose": "Why the student is learning this (1-2 sentences)",- "knowledge_state": {- "known_well": ["Knowledge points already mastered"],- "partially_known": ["Knowledge points partially understood but not solid"],- "unknown": ["Knowledge points completely unknown"]- },- "personality": "A single paragraph describing the student's learning style preferences, communication habits, strengths, weaknesses, patience level, and attention to detail. Write it as a coherent character description, not bullet points."- }- ```--user_template: |- ## Knowledge Scope- {knowledge_scope}-- ## Requirements- - Generate a **{background_type}** level student profile- - Background type descriptions:- - beginner: A novice with almost no background in this domain, but with basic learning ability- - intermediate: Has some foundation, has studied some related content but has knowledge blind spots- - advanced: Has a solid foundation, wants to deepen understanding or tackle specific challenging problems-- Please generate a realistic student profile.diff --git a/benchmark/prompts/generate_task_single.yaml b/benchmark/prompts/generate_task_single.yamldeleted file mode 100644index ac593dc0c..000000000--- a/benchmark/prompts/generate_task_single.yaml+++ /dev/null@@ -1,65 +0,0 @@-# Generate a single task from available (remaining) gaps-# Used when iteratively partitioning gaps across tasks (each gap → exactly one task)--system: |- You are an educational assessment expert. Given a student profile and a list of **available** knowledge gaps- (gaps not yet assigned to any task), design ONE learning task for this student.- The task should naturally guide the conversation while exposing one or more of the provided gaps.-- ## Task Types- 1. **concept_understanding**: The student wants to understand a particular concept or principle- 2. **problem_solving**: The student wants to learn how to solve a certain type of problem- 3. **application**: The student wants to understand real-world applications of the knowledge- 4. **comparison**: The student wants to distinguish between easily confused concepts-- ## Constraints- - Select at least THREE gaps from the **available** list for this task- - Each gap can only belong to one task — the gaps you select will be removed from the pool- - Group related gaps into one task when it makes a natural, coherent learning request- - Each task must have >= 3 target_gaps (hard constraint)- - IMPORTANT: The student should NOT expose all target gaps at once. Design the task so confusion is revealed progressively across turns.- - initial_message should focus on ONE primary confusion first (usually one gap), not list every gap.-- ## Output Format- ```json- {- "task_id": "task_xxx",- "type": "concept_understanding/problem_solving/application/comparison",- "title": "Short task title",- "description": "Detailed task description",- "initial_message": "The first message the student might send (natural language, matching personality)",- "target_gaps": ["gap_001", "gap_002"],- "gap_pacing_plan": [- {"gap_id": "gap_001", "turn_window": "1-2", "trigger": "Reveal first confusion only"},- {"gap_id": "gap_002", "turn_window": "3-4", "trigger": "Reveal after partial clarification"},- {"gap_id": "gap_003", "turn_window": "5-6", "trigger": "Reveal only if conversation continues"}- ],- "expected_gap_exposure": "How the targeted gaps are expected to surface",- "success_criteria": "What constitutes successful teaching for this task",- "difficulty": "easy/medium/hard"- }- ```-- **Important**:- - target_gaps must contain gap_id(s) from the provided available_gaps list only- - target_gaps length must be >= 3- - gap_pacing_plan must include every target gap exactly once with staged turn windows--user_template: |- ## Knowledge Scope- {knowledge_scope}-- ## Student Profile- {student_profile}-- ## Available Knowledge Gaps (select one or more for this task; they will not be reused)- {available_gaps}-- ## Requirements- - Generate exactly ONE learning task- - Select at least THREE gaps from the available list for target_gaps- - Provide a gap_pacing_plan so gaps are revealed gradually (not all in first turn)- - The initial_message should match the student's personality- - The task should support at least 5 rounds of meaningful dialogue-- Please generate the task.diff --git a/benchmark/prompts/generate_tasks.yaml b/benchmark/prompts/generate_tasks.yamldeleted file mode 100644index 557f70776..000000000--- a/benchmark/prompts/generate_tasks.yaml+++ /dev/null@@ -1,60 +0,0 @@-system: |- You are an educational assessment expert. Given a student profile, their knowledge gaps,- and the knowledge scope, design **learning tasks** for this student.- A task is a learning request the student brings to the AI Tutor. It should naturally guide- the conversation while exposing one or more of the student's knowledge gaps.-- ## Task Types- 1. **concept_understanding**: The student wants to understand a particular concept or principle- 2. **problem_solving**: The student wants to learn how to solve a certain type of problem- 3. **application**: The student wants to understand real-world applications of the knowledge- 4. **comparison**: The student wants to distinguish between easily confused concepts-- ## Design Principles- - **Naturalness**: Tasks should sound like questions/requests a real student would ask, not artificially constructed- - **Relevance**: Each task should relate to one or more of the student's knowledge gaps (but not directly state the gap)- - **Coverage**: The generated tasks should collectively cover all gaps; each gap should be targeted by at least one task- - **Expandability**: Tasks should be able to generate multiple rounds of meaningful conversation- - **Specificity**: Tasks should have clear goals, not be too vague- - **Background-appropriate**: Task difficulty and wording should match the student's background level-- ## Output Format- ```json- {- "tasks": [- {- "task_id": "task_xxx",- "type": "concept_understanding/problem_solving/application/comparison",- "title": "Short task title",- "description": "Detailed task description (what the student would say to the tutor, 1-3 sentences)",- "initial_message": "The first message the student might send to start the conversation (natural language, matching the student's personality)",- "target_gaps": ["gap_001", "gap_003"],- "expected_gap_exposure": "How the targeted knowledge gaps are expected to surface during the conversation",- "success_criteria": "What constitutes the tutor successfully completing the teaching for this task",- "difficulty": "easy/medium/hard"- }- ]- }- ```-- **Important**: The `target_gaps` field must contain the gap_id(s) from the provided knowledge gaps list.- Each task may target one or multiple gaps — use your judgment on what makes a natural, coherent task.--user_template: |- ## Knowledge Scope- {knowledge_scope}-- ## Student Profile- {student_profile}-- ## Student's Knowledge Gaps- {knowledge_gaps}-- ## Requirements- - Generate {num_tasks} learning tasks- - Each task should naturally expose one or more of the student's knowledge gaps- - All gaps should be covered by at least one task- - The initial_message should match the student's personality and communication style- - Each task should be able to generate at least 5 rounds of meaningful dialogue-- Please generate the learning tasks.diff --git a/benchmark/prompts/reject_task_batch.yaml b/benchmark/prompts/reject_task_batch.yamldeleted file mode 100644index 456e6bd95..000000000--- a/benchmark/prompts/reject_task_batch.yaml+++ /dev/null@@ -1,44 +0,0 @@-# Batch rejection sampling for tasks: verify gaps and task make sense together--system: |- You are a quality checker for educational benchmark data. Your task is to verify that- each learning task and its associated knowledge gaps **make sense together logically**.-- The 10 pages of source content may span different sections and be somewhat disjoint.- Focus on LOGICAL COHERENCE, not source alignment.-- For each task, check:- 1. **Gap coherence**: Are the gaps in this task logically related? Do they form a coherent- learning topic, or are they too scattered/jumpy? Reject if gaps feel unrelated or- would require the student to jump between disconnected concepts in one conversation.- 2. **Task–gap fit**: Does the task description, initial_message, and success_criteria- naturally connect to the targeted gaps? Would pursuing this task organically expose- these gaps? Reject if the task feels mismatched (e.g., task asks about X but gaps- are about Y).- 3. **No contradiction**: Do any gaps contradict each other or the task? Reject if there- is logical inconsistency.-- Output a JSON object with "results": list of {{ "task_id", "accepted", "reason" }}.- Be strict: when in doubt, reject.--user_template: |- ## Source Content (by page index — for context only; focus on logical coherence)- {source_content}-- ## Tasks to Verify- {tasks_with_gaps}-- ## Your Task- For each task, determine if the gaps and task make sense together logically.- Reject if gaps are too scattered, task doesn't fit the gaps, or there's contradiction.- Output JSON:- ```json- {{- "results": [- {{ "task_id": "...", "accepted": true/false, "reason": "..." }},- ...- ]- }}- ```-- Be strict. Reject any task where the gaps and task do not cohere logically.diff --git a/benchmark/prompts/student_system.yaml b/benchmark/prompts/student_system.yamldeleted file mode 100644index e3c71c0bf..000000000--- a/benchmark/prompts/student_system.yaml+++ /dev/null@@ -1,66 +0,0 @@-system: |- You are role-playing as a student seeking help from an AI tutor.- Stay in character throughout the entire conversation. Never break character.-- # Who You Are- {personality}-- # Your Background- {education_background}-- # Why You Are Here- {learning_purpose}-- # What You Know- You are confident about these topics:- {known_well}-- You have vague or partial understanding of these (you might get details wrong):- {partially_known}-- You have NO knowledge of the following — you have never encountered these concepts:- {unknown}-- # What You Believe (IMPORTANT — these feel true to you)- {beliefs}-- # How Your Confusions Surface- {gap_pacing_plan}-- # Behavioral Rules- 1. NEVER display knowledge listed as "unknown" above. If the tutor asks about something you don't know, say so honestly — "I haven't learned that" or "I'm not sure what that means."- 2. When the tutor corrects one of your beliefs, do NOT immediately accept it. First express confusion or surprise ("Wait, but I thought..."), try to reconcile with your old belief, ask a follow-up question. Only gradually accept after the tutor explains convincingly.- 3. When the tutor teaches something new, try to rephrase it in your own words. It's okay to rephrase imperfectly — this shows you're processing.- 4. If the tutor asks "do you understand?", be honest based on whether the explanation actually addressed your confusion. Don't just say "yes" to be polite.- 5. Keep responses concise: 1-4 sentences typically. You are a student, not giving lectures.- 6. Stay consistent with your personality throughout — your communication style, patience level, and level of detail should match.- 7. You may ask follow-up questions, request examples, or ask the tutor to slow down — whatever feels natural for your character.- 8. If you genuinely start to understand something (because the tutor explained it well), you can show that — say "Oh, I see!" or "So what you're saying is..." But don't understand everything at once.- 9. When you feel you've understood a concept, PREFER asking for a practice problem before ending. Testing yourself with a problem helps solidify understanding — don't rush to end without trying at least one problem.-- # Ending the conversation (ONLY when done)- Use [ACTION: task_complete] ONLY if ALL conditions are true:- - You are explicitly done.- - You have zero remaining questions.- - You are NOT requesting anything else (no new example/problem/sketch/check).- - Your message is a natural closing/goodbye.-- CRITICAL guardrail:- - If your message contains any question, uncertainty, or request for more help, you MUST NOT use [ACTION: task_complete].- - Signals like "?", "could you", "can we", "one more", "next", "help me see", "I'm still stuck", "not sure" mean continue conversation (no action marker).-- For all non-ending messages (questions, clarifications, asking for practice, partial understanding, etc.), write normally and do NOT add any action marker.-- Example (continuing conversation):- Could you walk me through deriving r = ed/(1+e cos θ) from the definition?-- Example (continuing conversation):- I think I've got it. Can you give me a similar problem to try on my own?-- Example (ending):- Thank you — I feel confident now. I don't need anything else.- [ACTION: task_complete]-- Counterexample (NOT ending):- Could we do one more example? I'm still not fully sure about this step.- (No action marker)diff --git a/benchmark/simulation/USE_TOOL.md b/benchmark/simulation/USE_TOOL.mddeleted file mode 100644index 84a8e496e..000000000--- a/benchmark/simulation/USE_TOOL.md+++ /dev/null@@ -1,234 +0,0 @@-# Simulator Tools 使用指南--## 概述--三个异步工具,供学生 Agent 调用,完整覆盖 **解题 → 出题 → 做答** 流程,并自动集成 Memory 系统。--每个学生通过独立的 `workspace` 路径实现数据隔离——所有产出文件(解题记录、出题批次、trace、memory 文档)均保存在该路径下,Memory Agent 也只读取该路径内的历史数据。--## Workspace 目录结构--```-workspace/-├── memory/ # 记忆系统-│ ├── traces/ # trace 森林-│ │ ├── index.json-│ │ ├── embeddings.json-│ │ └── {trace_id}.json-│ ├── logs/ # memory agent 日志-│ ├── memory.md # 学习总结 (SummaryAgent)-│ ├── weakness.md # 薄弱点 (WeaknessAgent)-│ └── reflection.md # 反思 (ReflectionAgent)-├── solve/ # 解题输出-│ └── solve_YYYYMMDD_HHMMSS/-│ ├── scratchpad.json-│ ├── final_answer.md-│ └── cost_report.json-└── question/ # 出题输出- └── batch_YYYYMMDD_HHMMSS/- ├── templates.json- ├── summary.json- └── q_X_result.json-```--## 工具 API--### 1. `solve_question` — 解题--```python-from benchmark.simulation import solve_question--result = await solve_question(- workspace="/path/to/student_001",- kb_name="ai-textbook",- question="什么是拉格朗日乘数法?",- language="zh", # 可选,默认 "en"-)-```--**输入参数**--| 参数 | 类型 | 说明 |-|---|---|---|-| `workspace` | `str` | 学生 workspace 根路径 |-| `kb_name` | `str` | 知识库名称 |-| `question` | `str` | 学生提出的问题 |-| `language` | `str` | 语言(`en` / `zh`),默认 `en` |--**返回值**--```python-{- "question": "什么是拉格朗日乘数法?",- "answer": "拉格朗日乘数法是一种...", # 完整解答- "output_dir": "/path/to/.../solve_20260220_143022",- "steps": 3,- "completed_steps": 3,- "citations": ["source-1", "source-2"],-}-```--**内部流程**: Plan → ReAct → Write → 构建 trace → 注册到 trace forest → 运行三个 Memory Agent 更新 memory.md / weakness.md / reflection.md。-------### 2. `generate_questions` — 出题--```python-from benchmark.simulation import generate_questions--result = await generate_questions(- workspace="/path/to/student_001",- kb_name="ai-textbook",- topic="线性代数中的特征值分解",- preferences="侧重应用和计算", # 可选- num_questions=3, # 可选,默认 3- language="zh", # 可选,默认 "en"-)-```--**输入参数**--| 参数 | 类型 | 说明 |-|---|---|---|-| `workspace` | `str` | 学生 workspace 根路径 |-| `kb_name` | `str` | 知识库名称 |-| `topic` | `str` | 出题主题 |-| `preferences` | `str` | 个人偏好/要求,可为空 |-| `num_questions` | `int` | 题目数量,默认 3 |-| `language` | `str` | 语言,默认 `en` |--**返回值**--```python-{- "batch_id": "batch_20260220_150000",- "batch_dir": "/path/to/.../batch_20260220_150000",- "num_generated": 3,- "questions": [- {- "question_id": "q_1",- "question": "下列关于特征值的说法,正确的是?",- "options": {"A": "...", "B": "...", "C": "...", "D": "..."},- "question_type": "choice",- },- # ...- ],-}-```--> **注意**: 返回的 `questions` 中 **不含正确答案**,防止学生 Agent "作弊"。正确答案存储在 `summary.json` 中,由 `submit_answers` 在判分时读取。-------### 3. `submit_answers` — 做答--```python-from benchmark.simulation import submit_answers--result = await submit_answers(- workspace="/path/to/student_001",- batch_id="batch_20260220_150000", # 来自 generate_questions 的返回- answers=[- {"question_id": "q_1", "answer": "A"},- {"question_id": "q_2", "answer": "C"},- {"question_id": "q_3", "answer": "B"},- ],- language="zh",-)-```--**输入参数**--| 参数 | 类型 | 说明 |-|---|---|---|-| `workspace` | `str` | 学生 workspace 根路径 |-| `batch_id` | `str` | `generate_questions` 返回的 `batch_id` |-| `answers` | `list[dict]` | `[{"question_id": "q_1", "answer": "A"}, ...]` |-| `language` | `str` | 语言,默认 `en` |--**返回值**--```python-{- "results": [- {- "question_id": "q_1",- "user_answer": "A",- "correct_answer": "A",- "judged_result": "correct", # correct / wrong / skipped- "explanation": "因为...",- },- # ...- ],- "score": {- "total": 3,- "correct": 2,- "wrong": 1,- "accuracy": 0.6667,- },-}-```--**内部流程**: 从 `summary.json` 读取正确答案 → 自动判分 → 将答题节点写入 trace → 运行三个 Memory Agent 更新记忆。-------## 典型调用流程--```python-import asyncio-from benchmark.simulation import solve_question, generate_questions, submit_answers--WS = "/data/eval/student_001"-KB = "ai-textbook"--async def main():- # ① 解题(自动带 memory)- solve_result = await solve_question(- workspace=WS, kb_name=KB,- question="什么是梯度下降?", language="zh",- )- print(solve_result["answer"])-- # ② 出题- gen_result = await generate_questions(- workspace=WS, kb_name=KB,- topic="反向传播算法", num_questions=3, language="zh",- )-- # ③ 学生 Agent 思考后做答- answers = []- for q in gen_result["questions"]:- answer = student_agent_think(q) # 你自己的学生 Agent 逻辑- answers.append({"question_id": q["question_id"], "answer": answer})-- # ④ 提交答案(自动判分 + 更新 memory)- ans_result = await submit_answers(- workspace=WS, batch_id=gen_result["batch_id"],- answers=answers, language="zh",- )- print(f"得分: {ans_result['score']['correct']}/{ans_result['score']['total']}")--asyncio.run(main())-```--## 多学生并行模拟--不同学生使用不同的 `workspace` 路径,即可完全隔离。可通过 `asyncio.gather` 并行运行多个学生:--```python-async def simulate_student(student_id: str):- ws = f"/data/eval/student_{student_id}"- # ... 调用 solve_question / generate_questions / submit_answers ...--await asyncio.gather(- simulate_student("001"),- simulate_student("002"),- simulate_student("003"),-)-```--## 依赖--使用前确保项目根目录的 `.env` 或 `DeepTutor.env` 中配置了 LLM API 凭证,且目标知识库已在 `data/knowledge_bases/` 中构建完成。diff --git a/benchmark/simulation/__init__.py b/benchmark/simulation/__init__.pydeleted file mode 100644index d30af9e7b..000000000--- a/benchmark/simulation/__init__.py+++ /dev/null@@ -1,16 +0,0 @@-# Simulation Module - Student Agent, Conversation & Simulator Tools-#-# Modules:-# - student_agent: LLM-based student role-playing agent-# - conversation: Multi-turn conversation runner-# - tools: workspace-isolated solve / question / answer tools--from benchmark.simulation.student_agent import StudentAgent-from benchmark.simulation.tools import generate_questions, solve_question, submit_answers--__all__ = [- "StudentAgent",- "solve_question",- "generate_questions",- "submit_answers",-]diff --git a/benchmark/simulation/batch_simulation.py b/benchmark/simulation/batch_simulation.pydeleted file mode 100644index e21b95cfe..000000000--- a/benchmark/simulation/batch_simulation.py+++ /dev/null@@ -1,915 +0,0 @@-#!/usr/bin/env python3-"""-Batch Simulation & Evaluation — end-to-end pipeline.--Given a profile directory (from batch_profiles.py), for every profile:-1. Generate benchmark entries (gaps + tasks)-2. Run simulation with mock tutor and/or DeepTutor-3. Evaluate both transcripts-4. Output comparison summary--Usage:- python -m benchmark.simulation.batch_simulation \- --profiles-dir benchmark/data/generated/profiles_20260304_161506-- python -m benchmark.simulation.batch_simulation \- --profiles-dir benchmark/data/generated/profiles_20260304_161506 \- --concurrency 6 --max-turns 15 --backends mock,deep_tutor-"""-from __future__ import annotations--import argparse-import asyncio-import contextlib-import io-import json-import logging-import sys-from datetime import datetime-from pathlib import Path-from typing import Any, Literal--# Locks for entry generation to avoid race conditions between backends for the same profile-_entry_gen_locks: dict[str, asyncio.Lock] = {}--_THIS_FILE = Path(__file__).resolve()-PROJECT_ROOT = _THIS_FILE.parents[2]-if str(PROJECT_ROOT) not in sys.path:- sys.path.insert(0, str(PROJECT_ROOT))--from dotenv import load_dotenv--load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)-load_dotenv(PROJECT_ROOT / ".env", override=False)--import yaml--logger = logging.getLogger("benchmark.batch_sim")--DEFAULT_CONFIG = PROJECT_ROOT / "benchmark" / "config" / "benchmark_config.yaml"---# ======================================================================-# Stage 1: Entry generation (gaps + tasks per profile)-# ======================================================================---async def _generate_entries_for_profile(- kb_name: str,- profile: dict,- knowledge_scope: dict,- cfg: dict,- kb_base_dir: str,-) -> list[dict]:- """Generate benchmark entries (gaps + tasks) for a single profile.-- Mirrors pipeline.py stages 4-5 for one profile.- """- from benchmark.data_generation.content_loader import load_page_content_for_profile- from benchmark.data_generation.gap_generator import (- generate_gaps,- generate_gaps_from_pages,- )- from benchmark.data_generation.task_generator import (- MIN_GAPS_PER_TASK,- generate_tasks_with_partition,- )-- gap_cfg = cfg.get("gap_generation", {})- task_cfg = cfg.get("task_generation", {})- profile_id = profile.get("profile_id", "unknown")-- severity_weights: dict[str, float] = {}- for level in gap_cfg.get("severity_levels", []):- severity_weights[level["name"]] = level["weight"]-- min_tasks = task_cfg.get("min_tasks_per_profile", 3)- gaps_per_batch = max(task_cfg.get("gaps_per_batch", 3), MIN_GAPS_PER_TASK)- llm_retry_attempts = max(1, int(task_cfg.get("llm_retry_attempts", 3)))- llm_retry_delay_sec = max(0.0, float(task_cfg.get("llm_retry_delay_sec", 1.5)))-- use_content_list = gap_cfg.get("use_content_list", False)- page_content: dict[int, str] | None = None- if use_content_list:- num_pages = gap_cfg.get("pages_per_profile", 10)- result = load_page_content_for_profile(- kb_base_dir=kb_base_dir,- kb_name=kb_name,- num_pages=num_pages,- profile_id=profile_id,- )- if result:- page_content, _ = result- else:- logger.warning(- " No content_list for %s, falling back to scope-based gaps",- kb_name,- )-- all_gaps: list[dict] = []- all_tasks: list[dict] = []- task_index_offset = 0- max_batches = 10-- async def _run_with_retry(op_name: str, batch_num: int, coro_factory):- last_error: Exception | None = None- for attempt in range(1, llm_retry_attempts + 1):- try:- return await coro_factory()- except Exception as e:- last_error = e- if attempt >= llm_retry_attempts:- raise- wait_sec = llm_retry_delay_sec * attempt- logger.warning(- " %s batch %d %s failed (%d/%d): %s; retrying in %.1fs",- profile_id,- batch_num,- op_name,- attempt,- llm_retry_attempts,- e,- wait_sec,- )- if wait_sec > 0:- await asyncio.sleep(wait_sec)- if last_error is not None:- raise last_error-- for batch_num in range(1, max_batches + 1):- if len(all_tasks) >= min_tasks:- break-- try:- if page_content:- async def _gen_gaps():- return await generate_gaps_from_pages(- page_content=page_content,- student_profile=profile,- num_gaps=gaps_per_batch,- severity_weights=severity_weights or None,- gap_id_offset=len(all_gaps),- )- else:- async def _gen_gaps():- return await generate_gaps(- knowledge_scope=knowledge_scope,- student_profile=profile,- num_gaps=gaps_per_batch,- severity_weights=severity_weights or None,- gap_id_offset=len(all_gaps),- )-- new_gaps = await _run_with_retry("gap_generation", batch_num, _gen_gaps)-- if not new_gaps:- logger.warning(" No new gaps for %s, stopping", profile_id)- break-- async def _gen_tasks():- return await generate_tasks_with_partition(- knowledge_scope=knowledge_scope,- student_profile=profile,- knowledge_gaps=new_gaps,- task_index_offset=task_index_offset,- )-- tasks = await _run_with_retry("task_generation", batch_num, _gen_tasks)-- # Only commit this batch's gaps/tasks after both generation steps succeed.- all_gaps.extend(new_gaps)- all_tasks.extend(tasks)- task_index_offset += len(tasks)-- logger.info(- " %s: batch %d → %d/%d tasks",- profile_id,- batch_num,- len(all_tasks),- min_tasks,- )- except Exception as e:- logger.error(" Entry generation failed for %s batch %d: %s", profile_id, batch_num, e)- continue-- gap_by_id = {g["gap_id"]: g for g in all_gaps if "gap_id" in g}- entries: list[dict] = []- for task in all_tasks:- task_id = task.get("task_id", "unknown")- target_gap_ids = task.get("target_gaps", [])- target_gaps = [gap_by_id[gid] for gid in target_gap_ids if gid in gap_by_id]-- entry = {- "entry_id": f"{kb_name}_{profile_id}_{task_id}",- "kb_name": kb_name,- "profile": profile,- "gaps": target_gaps,- "task": task,- }- if page_content is not None:- entry["source_content"] = page_content- entries.append(entry)-- logger.info(- " %s: generated %d entries (%d gaps, %d tasks)",- profile_id,- len(entries),- len(all_gaps),- len(all_tasks),- )- return entries---def _save_entries(entries: list[dict], entries_dir: Path) -> list[str]:- """Save entries as individual JSON files + JSONL. Returns list of file paths."""- entries_dir.mkdir(parents=True, exist_ok=True)- paths: list[str] = []- for entry in entries:- entry_id = entry.get("entry_id", "unknown")- path = entries_dir / f"{entry_id}.json"- with open(path, "w", encoding="utf-8") as f:- json.dump(entry, f, ensure_ascii=False, indent=2)- paths.append(str(path))-- jsonl_path = entries_dir / "_all_entries.jsonl"- with open(jsonl_path, "w", encoding="utf-8") as f:- for entry in entries:- f.write(json.dumps(entry, ensure_ascii=False) + "\n")-- return paths---def _load_entries(entries_dir: Path) -> list[dict]:- """Load entries from a JSONL file."""- jsonl_path = entries_dir / "_all_entries.jsonl"- entries: list[dict] = []- with open(jsonl_path, encoding="utf-8") as f:- for line in f:- line = line.strip()- if line:- entries.append(json.loads(line))- return entries---# ======================================================================-# Stage 2: Simulation (multi-session per profile per backend)-# ======================================================================---async def _simulate_profile(- profile_id: str,- entries: list[dict],- backend: Literal["deep_tutor", "mock"],- output_dir: Path,- max_turns: int,- language: str,- evolve_profile: bool,- verbose: bool = False,-) -> dict:- """Run multi-session simulation for one profile with one backend.-- Replicates the logic of run_multi_session but saves to our controlled paths.- Returns the combined multi-session result dict.- """- from benchmark.simulation.conversation import (- _run_single_session,- _summarize_session,- )- from benchmark.simulation.profile_evolver import evolve_profile as evolve_profile_fn-- workspace = str(output_dir / "workspaces" / backend / profile_id)-- prior_sessions_summary: list[str] = []- current_profile = entries[0].get("profile", {})- sessions_results: list[dict] = []-- for i, base_entry in enumerate(entries):- session_num = i + 1- entry = dict(base_entry)-- if evolve_profile and i > 0:- prev_profile = entries[i - 1].get("profile", {})- resolved = entries[i - 1].get("gaps", [])- current_profile = evolve_profile_fn(prev_profile, resolved)- entry["profile"] = current_profile-- prior_ctx = "\n".join(prior_sessions_summary) if prior_sessions_summary else None-- logger.info(- "[%s] %s session %d/%d: %s",- backend,- profile_id,- session_num,- len(entries),- entry.get("entry_id", "?"),- )-- try:- if verbose:- result = await _run_single_session(- entry=entry,- max_turns=max_turns,- auto=True,- use_editor=False,- auto_backend=backend,- deeptutor_workspace=workspace,- deeptutor_language=language,- prior_sessions_summary=prior_ctx,- )- else:- with contextlib.redirect_stdout(io.StringIO()):- result = await _run_single_session(- entry=entry,- max_turns=max_turns,- auto=True,- use_editor=False,- auto_backend=backend,- deeptutor_workspace=workspace,- deeptutor_language=language,- prior_sessions_summary=prior_ctx,- )-- logger.info(- " [%s] %s session %d done: %d turns",- backend,- profile_id,- session_num,- result.get("actual_turns", 0),- )- except Exception as e:- logger.error(- " [%s] %s session %d failed: %s",- backend,- profile_id,- session_num,- e,- )- result = {- "entry_id": entry.get("entry_id", f"session_{session_num}"),- "transcript": [],- "entry": entry,- "actual_turns": 0,- "practice_questions": [],- "error": str(e),- }-- task = entry.get("task", {})- summary = _summarize_session(result.get("transcript", []), task, session_num)- prior_sessions_summary.append(summary)- sessions_results.append(result)-- combined = {- "profile_id": profile_id,- "backend": backend,- "timestamp": datetime.now().isoformat(),- "mode": "auto",- "evolve_profile": evolve_profile,- "num_sessions": len(sessions_results),- "sessions": [- {- "entry_id": r["entry_id"],- "actual_turns": r["actual_turns"],- "transcript": r.get("transcript", []),- "entry": r["entry"],- "practice_questions": r.get("practice_questions", []),- }- for r in sessions_results- ],- }-- transcript_dir = output_dir / "transcripts" / backend- transcript_dir.mkdir(parents=True, exist_ok=True)- transcript_path = transcript_dir / f"{profile_id}.json"- with open(transcript_path, "w", encoding="utf-8") as f:- json.dump(combined, f, ensure_ascii=False, indent=2)-- logger.info(" Transcript saved → %s", transcript_path)- return combined---# ======================================================================-# Stage 3: Evaluation-# ======================================================================---async def _evaluate_profile_transcript(- transcript_path: Path,- eval_output_dir: Path,- temperature: float = 0.2,-) -> dict:- """Evaluate a profile's transcript and save results."""- from benchmark.evaluation.evaluator import evaluate_transcript-- eval_output_dir.mkdir(parents=True, exist_ok=True)-- result = await evaluate_transcript(- transcript_path=transcript_path,- temperature=temperature,- )-- eval_path = eval_output_dir / f"{transcript_path.stem}_eval.json"- with open(eval_path, "w", encoding="utf-8") as f:- json.dump(result, f, ensure_ascii=False, indent=2)- logger.info(" Evaluation saved → %s", eval_path)- return result---def _extract_eval_summary(eval_result: dict) -> dict:- """Extract key metrics from full evaluation result for the summary."""- if "error" in eval_result:- return {"error": eval_result["error"]}-- agg = eval_result.get("aggregate", {})- return {- "num_sessions": eval_result.get("num_sessions", 0),- "turn_count": agg.get("turn_count", {}),- "gap_tracking": agg.get("gap_tracking", {}),- "source_faithfulness": agg.get("source_faithfulness", {}),- }---# ======================================================================-# Orchestration: one profile at a time (backends serial)-# ======================================================================---async def _process_one_profile(- kb_name: str,- profile: dict,- scope: dict,- cfg: dict,- kb_base_dir: str,- backends: list[str],- output_dir: Path,- semaphore: asyncio.Semaphore,- max_turns: int,- language: str,- evolve_profile: bool,- eval_temperature: float,- skip_eval: bool,- verbose: bool,-) -> dict:- """Process one profile: generate entries, then run backends serially."""- async with semaphore:- profile_id = profile.get("profile_id", "unknown")- profile_result: dict[str, Any] = {- "profile_id": profile_id,- "kb_name": kb_name,- "num_entries": 0,- "simulations": {},- "evaluations": {},- }-- # ----------------------------------------------------------- # Step 1: Generate entries (shared across backends — lock to avoid race)- # ----------------------------------------------------------- entries_dir = output_dir / "entries" / kb_name / profile_id- lock_key = f"{kb_name}/{profile_id}"- if lock_key not in _entry_gen_locks:- _entry_gen_locks[lock_key] = asyncio.Lock()-- async with _entry_gen_locks[lock_key]:- if (entries_dir / "_all_entries.jsonl").exists():- logger.info("SKIP entry generation (exists): %s", profile_id)- entries = _load_entries(entries_dir)- else:- try:- entries = await _generate_entries_for_profile(- kb_name=kb_name,- profile=profile,- knowledge_scope=scope,- cfg=cfg,- kb_base_dir=kb_base_dir,- )- _save_entries(entries, entries_dir)- except Exception as e:- logger.error(- "Entry generation failed for %s: %s", profile_id, e- )- return profile_result-- if not entries:- logger.warning("No entries for %s, skipping simulation", profile_id)- return profile_result-- profile_result["num_entries"] = len(entries)-- # ----------------------------------------------------------- # Step 2 & 3: Simulate + Evaluate each backend serially- # ----------------------------------------------------------- for backend in backends:- transcript_path = output_dir / "transcripts" / backend / f"{profile_id}.json"-- if transcript_path.exists():- logger.info("SKIP simulation (exists): %s / %s", profile_id, backend)- sim_result = json.loads(transcript_path.read_text("utf-8"))- else:- try:- sim_result = await _simulate_profile(- profile_id=profile_id,- entries=entries,- backend=backend,- output_dir=output_dir,- max_turns=max_turns,- language=language,- evolve_profile=evolve_profile,- verbose=verbose,- )- except Exception as e:- logger.error(- "Simulation failed for %s / %s: %s",- profile_id,- backend,- e,- )- sim_result = {"error": str(e)}-- profile_result["simulations"][backend] = {- "num_sessions": sim_result.get("num_sessions", 0),- "transcript_path": str(transcript_path),- }-- if (- not skip_eval- and transcript_path.exists()- and "error" not in sim_result- ):- eval_dir = output_dir / "evaluations" / backend- eval_path = eval_dir / f"{profile_id}_eval.json"- if eval_path.exists():- logger.info(- "SKIP evaluation (exists): %s / %s", profile_id, backend- )- eval_result = json.loads(eval_path.read_text("utf-8"))- else:- try:- eval_result = await _evaluate_profile_transcript(- transcript_path=transcript_path,- eval_output_dir=eval_dir,- temperature=eval_temperature,- )- except Exception as e:- logger.error(- "Evaluation failed for %s / %s: %s",- profile_id,- backend,- e,- )- eval_result = {"error": str(e)}-- profile_result["evaluations"][backend] = _extract_eval_summary(eval_result)-- return profile_result---# ======================================================================-# Summary-# ======================================================================---def _build_and_print_summary(- all_kb_results: list[dict],- backends: list[str],- output_dir: Path,-) -> dict:- """Build aggregate summary across all KBs and print comparison table."""- summary_by_backend: dict[str, dict[str, Any]] = {}-- for backend in backends:- total_profiles = 0- total_sessions = 0- faith_scores: list[float] = []- resolved_counts: list[int] = []- total_gaps_counts: list[int] = []- total_turns = 0-- for kb_res in all_kb_results:- for profile_res in kb_res.get("profiles", []):- sim = profile_res.get("simulations", {}).get(backend, {})- n_sess = sim.get("num_sessions", 0)- if n_sess == 0:- continue- total_profiles += 1- total_sessions += n_sess-- ev = profile_res.get("evaluations", {}).get(backend, {})- tc = ev.get("turn_count", {})- total_turns += tc.get("paired_turns_total", 0)-- gt = ev.get("gap_tracking", {})- for r in gt.get("resolved_gaps_per_session", []):- resolved_counts.append(r)- for t in gt.get("total_gaps_per_session", []):- total_gaps_counts.append(t)-- sf = ev.get("source_faithfulness", {})- avg = sf.get("avg_score_overall")- if isinstance(avg, (int, float)):- faith_scores.append(float(avg))-- summary_by_backend[backend] = {- "total_profiles": total_profiles,- "total_sessions": total_sessions,- "total_paired_turns": total_turns,- "avg_faithfulness": (- round(sum(faith_scores) / len(faith_scores), 2)- if faith_scores- else None- ),- "avg_resolved_gaps_per_session": (- round(sum(resolved_counts) / len(resolved_counts), 2)- if resolved_counts- else None- ),- "avg_total_gaps_per_session": (- round(sum(total_gaps_counts) / len(total_gaps_counts), 2)- if total_gaps_counts- else None- ),- }-- # Print comparison- print("\n" + "=" * 70)- print("BATCH SIMULATION & EVALUATION SUMMARY")- print("=" * 70)-- for backend, stats in summary_by_backend.items():- print(f"\n--- {backend.upper()} ---")- print(f" Profiles evaluated : {stats['total_profiles']}")- print(f" Total sessions : {stats['total_sessions']}")- print(f" Total paired turns : {stats['total_paired_turns']}")- faith = stats["avg_faithfulness"]- print(f" Avg faithfulness (1-5): {faith if faith is not None else 'N/A'}")- res = stats["avg_resolved_gaps_per_session"]- tot = stats["avg_total_gaps_per_session"]- print(- f" Avg gap resolution : "- f"{res if res is not None else 'N/A'} / "- f"{tot if tot is not None else 'N/A'}"- )-- print("\n" + "=" * 70)-- full_summary = {- "timestamp": datetime.now().isoformat(),- "output_dir": str(output_dir),- "backends": backends,- "aggregate": summary_by_backend,- "per_kb": all_kb_results,- }-- summary_path = output_dir / "_summary.json"- with open(summary_path, "w", encoding="utf-8") as f:- json.dump(full_summary, f, ensure_ascii=False, indent=2)- print(f"\nFull summary → {summary_path}")-- return full_summary---# ======================================================================-# CLI-# ======================================================================---async def main() -> None:- logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )-- parser = argparse.ArgumentParser(- description="Batch simulation & evaluation for all profiles"- )- parser.add_argument(- "--profiles-dir",- required=True,- help="Directory containing profile JSON files (from batch_profiles.py)",- )- parser.add_argument(- "--kb-dir",- default="data/knowledge_bases",- help="Knowledge bases directory (default: data/knowledge_bases)",- )- parser.add_argument(- "--config",- default=str(DEFAULT_CONFIG),- help=f"Benchmark config path (default: {DEFAULT_CONFIG})",- )- parser.add_argument(- "--output-dir",- default=None,- help="Output directory (default: benchmark/data/batch_sim_{timestamp})",- )- parser.add_argument(- "--concurrency",- type=int,- default=6,- help="Max parallel profile tasks (default: 6)",- )- parser.add_argument(- "--max-turns",- type=int,- default=30,- help="Max student turns per session (default: 30)",- )- parser.add_argument(- "--backends",- default="mock,deep_tutor",- help="Comma-separated backends to test (default: mock,deep_tutor)",- )- parser.add_argument(- "--language",- default="en",- help="DeepTutor language (default: en)",- )- parser.add_argument(- "--no-evolve",- action="store_true",- help="Disable profile evolution between sessions",- )- parser.add_argument(- "--skip-eval",- action="store_true",- help="Skip transcript evaluation (simulation only)",- )- parser.add_argument(- "--skip-sim",- action="store_true",- help="Skip simulation (entry generation only)",- )- parser.add_argument(- "--eval-temperature",- type=float,- default=0.2,- help="LLM temperature for evaluation (default: 0.2)",- )- parser.add_argument(- "--verbose",- "-v",- action="store_true",- help="Show per-turn conversation output (noisy with parallel KBs)",- )-- args = parser.parse_args()-- # Suppress noisy logs from RAG/LLM internals during auto simulation- from benchmark.simulation.conversation import _suppress_noisy_auto_logs-- _suppress_noisy_auto_logs()- # Re-enable our own loggers after global suppression- logging.getLogger("benchmark.batch_sim").setLevel(logging.INFO)- logging.getLogger("benchmark.conversation").setLevel(logging.INFO)- logging.getLogger("benchmark.evaluation").setLevel(logging.INFO)- logging.getLogger("benchmark.pipeline").setLevel(logging.INFO)- logging.getLogger("benchmark.gap_generator").setLevel(logging.INFO)- logging.getLogger("benchmark.task_generator").setLevel(logging.INFO)-- # Resolve paths- profiles_dir = Path(args.profiles_dir)- if not profiles_dir.is_absolute():- profiles_dir = (PROJECT_ROOT / profiles_dir).resolve()-- kb_base_dir = Path(args.kb_dir)- if not kb_base_dir.is_absolute():- kb_base_dir = (PROJECT_ROOT / kb_base_dir).resolve()-- cfg_path = Path(args.config)- if not cfg_path.is_absolute():- cfg_path = (PROJECT_ROOT / cfg_path).resolve()- with open(cfg_path, encoding="utf-8") as f:- cfg = yaml.safe_load(f) or {}-- backends = [b.strip() for b in args.backends.split(",") if b.strip()]-- if args.output_dir:- output_dir = Path(args.output_dir)- if not output_dir.is_absolute():- output_dir = (PROJECT_ROOT / output_dir).resolve()- else:- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- output_dir = (- PROJECT_ROOT / "benchmark" / "data" / f"batch_sim_{timestamp}"- )- output_dir.mkdir(parents=True, exist_ok=True)-- # Load profile data- profile_files = sorted(profiles_dir.glob("*.json"))- profile_files = [f for f in profile_files if not f.name.startswith("_")]- if not profile_files:- print(f"No profile files found in {profiles_dir}")- sys.exit(1)-- all_kb_data: list[dict] = []- for pf in profile_files:- try:- with open(pf, encoding="utf-8") as f:- data = json.load(f)- if data.get("profiles") and data.get("knowledge_scope"):- all_kb_data.append(data)- except Exception as e:- logger.warning("Skip %s: %s", pf.name, e)-- if not all_kb_data:- print("No valid profile files found (need 'profiles' and 'knowledge_scope' keys)")- sys.exit(1)-- total_profiles = sum(len(d["profiles"]) for d in all_kb_data)- print(f"KBs: {len(all_kb_data)} | Profiles: {total_profiles} | "- f"Backends: {backends} | Concurrency: {args.concurrency}")- print(f"Output: {output_dir}")- for d in all_kb_data:- print(f" - {d['kb_name']}: {len(d['profiles'])} profiles")- print()-- if args.skip_sim:- backends_for_sim: list[str] = []- logger.info("--skip-sim: will only generate entries, no simulation/evaluation")- else:- backends_for_sim = backends-- semaphore = asyncio.Semaphore(args.concurrency)-- if not backends_for_sim:- # --skip-sim: only generate entries, one task per unique profile- async def _gen_entries_only(kb_data: dict, profile: dict) -> None:- async with semaphore:- kb_name = kb_data["kb_name"]- profile_id = profile.get("profile_id", "unknown")- entries_dir = output_dir / "entries" / kb_name / profile_id- if (entries_dir / "_all_entries.jsonl").exists():- logger.info("SKIP entry generation (exists): %s/%s", kb_name, profile_id)- return- try:- entries = await _generate_entries_for_profile(- kb_name=kb_name,- profile=profile,- knowledge_scope=kb_data["knowledge_scope"],- cfg=cfg,- kb_base_dir=str(kb_base_dir),- )- _save_entries(entries, entries_dir)- except Exception as e:- logger.error("Entry generation failed for %s/%s: %s", kb_name, profile_id, e)-- tasks = [- _gen_entries_only(data, profile)- for data in all_kb_data- for profile in data["profiles"]- ]- logger.info("Launching %d entry-generation tasks (concurrency=%d)", len(tasks), args.concurrency)- await asyncio.gather(*tasks, return_exceptions=True)- logger.info("Entry generation complete. Output: %s", output_dir)- return-- # Build tasks: one per profile (each task runs backends serially)- tasks = []- for data in all_kb_data:- kb_name = data["kb_name"]- scope = data["knowledge_scope"]- for profile in data["profiles"]:- tasks.append(- _process_one_profile(- kb_name=kb_name,- profile=profile,- scope=scope,- cfg=cfg,- kb_base_dir=str(kb_base_dir),- backends=backends_for_sim,- output_dir=output_dir,- semaphore=semaphore,- max_turns=args.max_turns,- language=args.language,- evolve_profile=not args.no_evolve,- eval_temperature=args.eval_temperature,- skip_eval=args.skip_eval,- verbose=args.verbose,- )- )-- total_tasks = len(tasks)- logger.info("Launching %d parallel tasks (concurrency=%d)", total_tasks, args.concurrency)- all_results = await asyncio.gather(*tasks, return_exceptions=True)-- # Collect results (filter out exceptions)- good_results: list[dict] = []- for i, result in enumerate(all_results):- if isinstance(result, Exception):- logger.error("Task %d failed: %s", i, result)- else:- good_results.append(result)-- # Group per-profile results by KB for summary- by_kb: dict[str, list[dict]] = {d["kb_name"]: [] for d in all_kb_data}- for r in good_results:- by_kb.setdefault(r.get("kb_name", "unknown"), []).append(r)- kb_results = [- {"kb_name": d["kb_name"], "profiles": by_kb.get(d["kb_name"], [])}- for d in all_kb_data- ]-- # Summary- _build_and_print_summary(kb_results, backends_for_sim, output_dir)---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/simulation/conversation.py b/benchmark/simulation/conversation.pydeleted file mode 100644index 256b5e41f..000000000--- a/benchmark/simulation/conversation.py+++ /dev/null@@ -1,1110 +0,0 @@-#!/usr/bin/env python-"""-Conversation Runner - Run multi-turn student-tutor conversations--Supports two modes:- 1. Interactive: Human plays the tutor, types responses in terminal- 2. Auto: Tutor backend (deep_tutor or mock)--Usage:- # Interactive mode (editor by default; use --inline for console input):- python -m benchmark.simulation.conversation --entry path/to/entry.json-- # Console input (empty line + Enter to send; paste may truncate long content):- python -m benchmark.simulation.conversation --entry path/to/entry.json --inline-- # Auto mode with DeepTutor backend:- python -m benchmark.simulation.conversation --entry path/to/entry.json --auto --auto-backend deep_tutor-"""--import asyncio-import contextlib-import io-import json-import logging-import os-import re-import subprocess-import tempfile-import textwrap-from datetime import datetime-from pathlib import Path-from typing import Literal--from benchmark.simulation.student_agent import StudentAgent--# Delimiter to separate student context from tutor response in editor-_EDITOR_DELIMITER = "\n\n--- Type your response below this line ---\n\n"--logger = logging.getLogger("benchmark.conversation")--PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent---def _suppress_noisy_auto_logs() -> None:- """Suppress verbose INFO/DEBUG logs from RAG/LLM internals during simulation."""- # Clamp root logger first to suppress generic "INFO: Process ..." style logs.- logging.getLogger().setLevel(logging.WARNING)-- noisy_loggers = [- "CodeExecutor",- "RAGService",- "RAGForward",- "Main",- "LLMClient",- "EmbeddingClient",- "lightrag",- "raganything",- "nano-vectordb",- "multiprocessing",- "openai",- "httpx",- "httpcore",- "src.services.embedding.provider",- "src.services.embedding.adapters.openai_compatible",- "src.services.rag",- "src.services.rag.service",- "src.tools.rag_tool",- ]- for name in noisy_loggers:- logging.getLogger(name).setLevel(logging.WARNING)---def _get_tutor_input_via_editor(student_context: str) -> str | None:- """- Open editor with student's message at top for reference.- Returns tutor response (content below delimiter), or None if aborted.- Avoids terminal paste truncation (4096 bytes on Linux, ~16K on macOS).- """- editor = os.environ.get("EDITOR") or os.environ.get("VISUAL") or "nano"- # Wrap long lines so they fit in editor (72 chars per line)- wrapped_lines = []- for para in student_context.strip().split("\n"):- for wline in textwrap.wrap(para, width=72):- wrapped_lines.append(f"# {wline}")- wrapped_lines.append("#") # blank line between paragraphs- header = "# Student's question (read-only reference):\n#\n"- header += "\n".join(wrapped_lines) + "\n"- header += _EDITOR_DELIMITER-- with tempfile.NamedTemporaryFile(- mode="w",- suffix=".txt",- delete=False,- encoding="utf-8",- ) as f:- f.write(header)- f.flush()- path = f.name-- try:- ret = subprocess.call([editor, path])- if ret != 0:- return None- with open(path, encoding="utf-8") as f:- text = f.read()- if _EDITOR_DELIMITER in text:- result = text.split(_EDITOR_DELIMITER, 1)[1].strip()- else:- result = text.strip()- if not result or result.lower() == "quit":- return None- return result- finally:- try:- os.unlink(path)- except OSError:- pass---# Fixed prompt sent to tutor after student says task_complete-TUTOR_POST_COMPLETE_PROMPT = (- "The student has indicated they are done with this session. "- "Based on this conversation, please create 5 practice problems that reinforce what was covered. "- "Use multiple-choice format where applicable, and ensure distractors are plausible and non-trivial "- "(not obviously wrong at first glance). "- "Give only problem statements (no solutions)."-)-PRACTICE_QUESTION_COUNT = 5---def _build_sim_workspace(profile_id: str | None, entry_id: str, shared_by_profile: bool) -> str:- """Build workspace path for DeepTutor tool-based auto tutor."""- base = PROJECT_ROOT / "benchmark" / "data" / "sim_workspaces"- key = profile_id if (shared_by_profile and profile_id) else entry_id- return str(base / key)---# Simple tutor system prompt for auto mode-MOCK_TUTOR_SYSTEM = (- "You are a helpful and patient tutor."-)---async def mock_tutor_respond(- student_message: str,- history: list[dict[str, str]],- kb_name: str | None = None,-) -> str:- """- Generate a mock tutor response using LLM.-- Args:- student_message: The student's latest message- history: Conversation history from tutor's perspective- (role="user" for student, role="assistant" for tutor)- kb_name: Knowledge base name used for RAG retrieval-- Returns:- Tutor response string- """- from src.services.llm import factory- from src.tools.rag_tool import rag_search-- system = MOCK_TUTOR_SYSTEM-- # Auto mode RAG: use raw student message as query in naive mode.- rag_context = ""- if kb_name:- try:- # Some RAG internals print INFO lines directly to stdout/stderr.- # Silence those noisy streams during retrieval in auto mode.- with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):- rag_result = await rag_search(- query=student_message,- kb_name=kb_name,- mode="naive",- only_need_context=True,- top_k=2,- )- rag_answer = (rag_result.get("answer") or rag_result.get("content") or "").strip()- if rag_answer:- rag_context = (- "## Retrieved context (RAG, naive mode)\n"- f"{rag_answer[:1500]}\n\n"- )- except Exception as e:- logger.warning("RAG retrieval failed for kb=%s: %s", kb_name, e)-- # No action hint; tutor infers intent from message content.- user_content = f"{rag_context}## Student message\n{student_message}"-- # Build messages from tutor's perspective- messages = [{"role": "system", "content": system}]- messages.extend(history)- messages.append({"role": "user", "content": user_content})-- response = await factory.complete(- prompt="",- system_prompt="",- messages=messages,- temperature=0.5,- max_tokens=1024,- )-- return response---_TUTOR_INSTRUCTION_BASE = (- "You are a helpful and patient tutor."-)---def _build_tutor_instruction(student_message: str) -> str:- """Build adaptive tutoring instruction without rule-based matching."""- _ = student_message # Keep signature stable for callers.- return _TUTOR_INSTRUCTION_BASE + "Student says: "---async def deep_tutor_respond(- student_message: str,- kb_name: str,- workspace: str,- language: str = "en",-) -> str:- """- Generate tutor response via DeepTutor solve pipeline.- Wraps the student message with tutoring instructions so the- WriterAgent produces a pedagogical response rather than an essay.- """- from benchmark.simulation.tools import solve_question-- if not kb_name:- return "(DeepTutor unavailable: missing kb_name in entry.)"-- question = _build_tutor_instruction(student_message) + student_message-- result = await solve_question(- workspace=workspace,- kb_name=kb_name,- question=question,- language=language,- enabled_tools=["rag_search", "code_execute", "reason"],- )- answer = (result.get("answer") or "").strip()- return answer or "(No answer generated.)"---def _format_question_block(q: dict) -> str:- """Format one generated question for tutor output."""- title = q.get("question", "").strip()- options = q.get("options", {}) or {}- lines = [title] if title else ["(Empty question)"]- if isinstance(options, dict):- for k, v in options.items():- lines.append(f"{k}. {v}")- elif isinstance(options, list):- for item in options:- lines.append(str(item))- return "\n".join(lines)---async def deep_tutor_generate_practice_problem(- *,- kb_name: str,- workspace: str,- topic: str,- language: str = "en",-) -> str:- """- Generate one practice problem via DeepTutor question pipeline.- """- from benchmark.simulation.tools import generate_questions-- if not kb_name:- return "(Practice problem generation unavailable: missing kb_name in entry.)"-- result = await generate_questions(- workspace=workspace,- kb_name=kb_name,- topic=topic,- num_questions=1,- language=language,- enable_web=False,- )- questions = result.get("questions", []) or []- if not questions:- return "(Practice problem generation failed.)"- return _format_question_block(questions[0])---def _build_practice_preferences(- tutor_history: list[dict[str, str]],-) -> str:- """Build a preferences string from conversation history."""- quality_rules = (- "Question quality requirements:\n"- "- For MCQ, provide 4 options (A-D) with exactly one correct answer.\n"- "- Distractors must be plausible and reflect common misconceptions.\n"- "- Distractors must NOT be obviously wrong at first glance.\n"- "- Keep options balanced in style and length to avoid test-taking shortcuts.\n"- )- if not tutor_history:- return quality_rules- convo_lines = []- for msg in tutor_history[-16:]:- role = "Student" if msg.get("role") == "user" else "Tutor"- text = (msg.get("content", "") or "")[:300]- convo_lines.append(f"[{role}] {text}")- return quality_rules + "\nRecent conversation:\n" + "\n".join(convo_lines)---async def deep_tutor_generate_practice_questions(- *,- kb_name: str,- workspace: str,- topic: str,- language: str = "en",- num_questions: int = PRACTICE_QUESTION_COUNT,- max_retries: int = 2,- tutor_history: list[dict[str, str]] | None = None,-) -> list[str]:- """Generate multiple practice questions via DeepTutor question pipeline.-- If fewer than num_questions are returned, retries with the remaining count.- """- from benchmark.simulation.tools import generate_questions-- if not kb_name:- return ["(Practice question generation unavailable: missing kb_name in entry.)"]-- preferences = _build_practice_preferences(tutor_history or [])- formatted: list[str] = []- remaining = num_questions-- for attempt in range(1 + max_retries):- if remaining <= 0:- break- result = await generate_questions(- workspace=workspace,- kb_name=kb_name,- topic=topic,- preferences=preferences,- num_questions=remaining,- language=language,- enable_web=False,- )- questions = result.get("questions", []) or []- for q in questions:- if q:- formatted.append(_format_question_block(q))- remaining = num_questions - len(formatted)- if remaining <= 0:- break- logger.warning(- "DeepTutor generated %d/%d questions (attempt %d/%d), retrying %d remaining",- len(formatted), num_questions, attempt + 1, 1 + max_retries, remaining,- )-- if not formatted:- return ["(Practice question generation failed.)"]- return formatted[:num_questions]---def _format_practice_questions_block(questions: list[str]) -> str:- """Render practice questions as numbered block."""- lines: list[str] = []- for i, q in enumerate(questions, start=1):- lines.append(f"Q{i}. {q.strip()}")- return "\n\n".join(lines) if lines else "(No practice questions generated.)"---def _split_questions_from_text(text: str) -> list[str]:- """Best-effort split of question list from raw text."""- if not text.strip():- return []- blocks = [b.strip() for b in re.split(r"\n\s*\n", text) if b.strip()]- # Prefer lines/blocks that look like numbered questions.- numbered = [b for b in blocks if re.match(r"^(Q?\d+[\).:]\s+)", b, flags=re.I)]- if numbered:- return numbered[:PRACTICE_QUESTION_COUNT]- return blocks[:PRACTICE_QUESTION_COUNT]---def _normalize_question_text(text: str) -> str:- """Normalize question text for duplicate checks."""- s = text.strip().lower()- s = re.sub(r"\s+", " ", s)- s = re.sub(r"^[qQ]?\d+[\).:]\s*", "", s)- return s---async def mock_tutor_generate_practice_questions(- *,- tutor_history: list[dict[str, str]],- kb_name: str | None,- num_questions: int = PRACTICE_QUESTION_COUNT,-) -> list[str]:- """- Generate MCQ practice questions via mock tutor in iterative rounds.- Each round includes all previously generated questions as context.- """- generated: list[str] = []- generated_norm: set[str] = set()- practice_history = list(tutor_history)-- for i in range(1, num_questions + 1):- prev = "\n\n".join([f"{idx + 1}. {q}" for idx, q in enumerate(generated)]) or "(none yet)"- prompt = (- "The student has finished this session. Generate EXACTLY ONE new "- "multiple-choice question (MCQ) with 4 options (A-D).\n"- f"This is question {i} of {num_questions}.\n\n"- "Requirements:\n"- "- Keep it aligned with this session's covered concepts.\n"- "- Use the exact format:\n"- " <question stem>\n"- " A. <option>\n"- " B. <option>\n"- " C. <option>\n"- " D. <option>\n"- "- Exactly ONE option must be correct. The other three are distractors.\n"- "- Include the correct answer and explanation.\n\n"- f"Previously generated questions:\n{prev}"- )-- chosen = None- for _ in range(3):- candidate = await mock_tutor_respond(- prompt,- practice_history,- kb_name=kb_name,- )- candidate = (candidate or "").strip()- norm = _normalize_question_text(candidate)- if candidate and norm and norm not in generated_norm:- chosen = candidate- generated_norm.add(norm)- break- prompt = (- "Your previous output overlapped with an existing question.\n"- "Generate ONE different MCQ (A-D options), substantially different.\n\n"- f"Existing questions:\n{prev}"- )-- if not chosen:- chosen = "(Failed to generate a unique practice question.)"-- generated.append(chosen)- practice_history.append({"role": "user", "content": prompt})- practice_history.append({"role": "assistant", "content": chosen})-- return generated---def _summarize_session(transcript: list[dict], task: dict, session_index: int) -> str:- """Produce a brief summary of a session for prior_sessions context."""- title = task.get("title", "Unknown task")- lines = [f"Session {session_index}: {title}"]- # First exchange- for i, msg in enumerate(transcript[:4]):- role = msg.get("role", "?")- content = (msg.get("content", "") or "").strip()[:150]- if content:- lines.append(f" {role}: {content}...")- lines.append(f" ({len(transcript)} messages total)")- return "\n".join(lines)---async def _run_single_session(- entry: dict,- max_turns: int,- auto: bool,- use_editor: bool,- auto_backend: Literal["deep_tutor", "mock"] = "deep_tutor",- deeptutor_workspace: str | None = None,- deeptutor_language: str = "en",- prior_sessions_summary: str | None = None,-) -> dict:- """- Run one session (one task). Returns result dict with transcript, entry, etc.- """- agent = StudentAgent.from_entry(- entry,- prior_sessions_context=prior_sessions_summary,- )- entry_id = entry.get("entry_id", "unknown")- kb_name = entry.get("kb_name")- profile_id = entry.get("profile", {}).get("profile_id")- workspace = deeptutor_workspace or _build_sim_workspace(- profile_id=profile_id,- entry_id=entry_id,- shared_by_profile=True,- )- task_title = entry.get("task", {}).get("title", "")-- tutor_history: list[dict[str, str]] = []- student_msg = agent.initial_message()-- print(f"[Student] {student_msg}\n")-- for turn in range(1, max_turns):- if auto:- try:- if auto_backend == "deep_tutor":- tutor_msg = await deep_tutor_respond(- student_message=student_msg,- kb_name=kb_name,- workspace=workspace,- language=deeptutor_language,- )- else:- tutor_msg = await mock_tutor_respond(- student_msg,- tutor_history,- kb_name=kb_name,- )- except Exception as e:- logger.error("Auto tutor failed (%s): %s", auto_backend, e)- print(f"\n[Tutor] Error: {e}")- break- else:- if use_editor:- tutor_msg = _get_tutor_input_via_editor(student_msg)- else:- print("[Tutor] (type response, empty line + Enter to send, 'quit' to end)")- lines = []- quit_typed = False- while True:- try:- line = input()- except EOFError:- break- if line.strip().lower() == "quit":- quit_typed = True- break- if line == "" and lines:- break- lines.append(line)- if quit_typed or not lines:- break- tutor_msg = "\n".join(lines)-- if tutor_msg is None:- break-- tutor_history.append({"role": "user", "content": student_msg})- tutor_history.append({"role": "assistant", "content": tutor_msg})-- print(f"[Tutor] {tutor_msg}\n")-- student_msg, student_action = await agent.respond(tutor_msg)- print(f"[Student] {student_msg}\n")- if student_action == "task_complete":- tutor_history.append({"role": "user", "content": student_msg})- break-- # --- Practice question generation (runs after session ends for any reason) ---- practice_questions: list[str] = []-- if auto:- end_reason = "task_complete" if (student_action if "student_action" in dir() else None) == "task_complete" else "max_turns"- print(f"[System] Session ended ({end_reason}). Generating practice questions...")- try:- if auto_backend == "deep_tutor":- topic = (- f"{task_title}\n"- f"Conversation summary request: {TUTOR_POST_COMPLETE_PROMPT}\n"- f"Generate {PRACTICE_QUESTION_COUNT} practice questions aligned to this session."- )- practice_questions = await deep_tutor_generate_practice_questions(- kb_name=kb_name,- workspace=workspace,- topic=topic,- language=deeptutor_language,- tutor_history=tutor_history,- )- else:- practice_questions = await mock_tutor_generate_practice_questions(- tutor_history=tutor_history,- kb_name=kb_name,- )- except Exception as e:- logger.error("Auto tutor post-complete failed (%s): %s", auto_backend, e)- practice_questions = ["(Practice question generation failed.)"]- elif not auto and tutor_history:- print(f"[Tutor] {TUTOR_POST_COMPLETE_PROMPT}")- print("[Tutor] (type 5 practice questions, separate by blank lines, empty line + Enter to send)")- lines = []- while True:- try:- line = input()- except EOFError:- break- if line == "" and lines:- break- lines.append(line)- practice_questions = _split_questions_from_text("\n".join(lines))- if not practice_questions:- practice_questions = ["(No practice questions provided.)"]-- if practice_questions:- if len(practice_questions) > PRACTICE_QUESTION_COUNT:- practice_questions = practice_questions[:PRACTICE_QUESTION_COUNT]- practice_msg = _format_practice_questions_block(practice_questions)- tutor_history.append({"role": "assistant", "content": practice_msg})- print(f"[Tutor] {practice_msg}\n")- agent.history.append({"role": "user", "content": practice_msg})-- transcript = agent.get_transcript()- return {- "entry_id": entry_id,- "transcript": transcript,- "entry": entry,- "actual_turns": agent.turn_count,- "practice_questions": practice_questions,- }---async def run_conversation(- entry_path: str | Path,- max_turns: int = 20,- auto: bool = False,- auto_backend: Literal["deep_tutor", "mock"] = "deep_tutor",- deeptutor_language: str = "en",- output_dir: str | Path | None = None,- entry_index: int = 0,- use_editor: bool = True,-) -> dict:- """- Run a multi-turn conversation between student agent and tutor.-- Args:- entry_path: Path to benchmark entry JSON file, or JSONL file- max_turns: Maximum number of student turns (including initial message, default: 20)- auto: If True, use mock LLM tutor. If False, interactive (stdin).- output_dir: Directory to save transcript. If None, uses default.- entry_index: When entry_path is JSONL, which entry to use (0-based).- use_editor: If True (default), open $EDITOR. If False, use console input.-- Returns:- Conversation result dict with transcript and metadata- """- entry_path = Path(entry_path)-- # Load entry and create agent- with open(entry_path, encoding="utf-8") as f:- if entry_path.suffix.lower() == ".jsonl":- lines = [ln.strip() for ln in f if ln.strip()]- if not lines:- raise ValueError(f"Empty JSONL file: {entry_path}")- if entry_index >= len(lines):- raise ValueError(- f"entry_index={entry_index} out of range (file has {len(lines)} entries)"- )- entry = json.loads(lines[entry_index])- else:- entry = json.load(f)-- agent = StudentAgent.from_entry(entry)- entry_id = entry.get("entry_id", entry_path.stem)- kb_name = entry.get("kb_name")- profile_id = entry.get("profile", {}).get("profile_id")- workspace = _build_sim_workspace(- profile_id=profile_id,- entry_id=entry_id,- shared_by_profile=False,- )- task_title = entry.get("task", {}).get("title", "")-- print(f"\n{'='*60}")- print(f"Conversation: {entry_id}")- mode_desc = f"auto ({auto_backend})" if auto else "interactive (you are the tutor)"- print(f"Mode: {mode_desc}")- print(f"Max turns: {max_turns}")- print(f"{'='*60}\n")-- # Tutor-side history (from tutor's perspective)- tutor_history: list[dict[str, str]] = []-- # Turn 0: Student's initial message- student_msg = agent.initial_message()- print(f"[Student] {student_msg}\n")-- for turn in range(1, max_turns):- # Get tutor response- if auto:- try:- if auto_backend == "deep_tutor":- tutor_msg = await deep_tutor_respond(- student_message=student_msg,- kb_name=kb_name,- workspace=workspace,- language=deeptutor_language,- )- else:- tutor_msg = await mock_tutor_respond(- student_msg, tutor_history, kb_name=kb_name- )- except Exception as e:- logger.error("Auto tutor failed (%s): %s", auto_backend, e)- print(f"\n[Tutor] Error: {e}")- print("(Conversation stopped. Partial transcript will be saved.)")- break- else:- print("-" * 40)- if use_editor:- print("[Tutor] Opening editor (student's question at top).")- print(" Save & close to send. nano: Ctrl+O then Ctrl+X | vim: :wq | VS Code: Cmd+S then close tab")- tutor_msg = _get_tutor_input_via_editor(student_msg)- if tutor_msg is None:- print("\n[Conversation ended by tutor]")- break- else:- print("[Tutor] (type your response, empty line + Enter to send, 'quit' to end)")- lines = []- quit_typed = False- while True:- try:- line = input()- except EOFError:- break- if line.strip().lower() == "quit":- print("\n[Conversation ended by tutor]")- quit_typed = True- break- if line == "" and lines:- break- lines.append(line)- if quit_typed or not lines:- break- tutor_msg = "\n".join(lines)-- # Record in tutor history- tutor_history.append({"role": "user", "content": student_msg})- tutor_history.append({"role": "assistant", "content": tutor_msg})-- print(f"[Tutor] {tutor_msg}\n")-- # Get student response (task_complete only when ending)- student_msg, student_action = await agent.respond(tutor_msg)- print(f"[Student] {student_msg}\n")- if student_action == "task_complete":- tutor_history.append({"role": "user", "content": student_msg})- break-- # --- Practice question generation (runs after session ends for any reason) ---- practice_questions: list[str] = []-- if auto and tutor_history:- end_reason = "task_complete" if (student_action if "student_action" in dir() else None) == "task_complete" else "max_turns"- print(f"[System] Session ended ({end_reason}). Generating practice questions...")- try:- if auto_backend == "deep_tutor":- topic = (- f"{task_title}\n"- f"Conversation summary request: {TUTOR_POST_COMPLETE_PROMPT}\n"- f"Generate {PRACTICE_QUESTION_COUNT} practice questions aligned to this session."- )- practice_questions = await deep_tutor_generate_practice_questions(- kb_name=kb_name,- workspace=workspace,- topic=topic,- language=deeptutor_language,- tutor_history=tutor_history,- )- else:- practice_questions = await mock_tutor_generate_practice_questions(- tutor_history=tutor_history,- kb_name=kb_name,- )- except Exception as e:- logger.error("Auto tutor post-complete failed (%s): %s", auto_backend, e)- practice_questions = ["(Practice question generation failed.)"]- elif not auto and tutor_history:- print(f"[Tutor] {TUTOR_POST_COMPLETE_PROMPT}")- print("[Tutor] (type 5 practice questions, separate by blank lines, empty line + Enter to send)")- lines = []- while True:- try:- line = input()- except EOFError:- break- if line == "" and lines:- break- lines.append(line)- practice_questions = _split_questions_from_text("\n".join(lines))- if not practice_questions:- practice_questions = ["(No practice questions provided.)"]-- if practice_questions:- if len(practice_questions) > PRACTICE_QUESTION_COUNT:- practice_questions = practice_questions[:PRACTICE_QUESTION_COUNT]- practice_msg = _format_practice_questions_block(practice_questions)- print(f"[Tutor] {practice_msg}\n")- agent.history.append({"role": "user", "content": practice_msg})-- print(f"{'='*60}")- print(f"Conversation complete. {agent.turn_count} student turns.")- print(f"{'='*60}\n")-- # Build result- result = {- "entry_id": entry_id,- "timestamp": datetime.now().isoformat(),- "mode": "auto" if auto else "interactive",- "max_turns": max_turns,- "actual_turns": agent.turn_count,- "transcript": agent.get_transcript(),- "entry": entry,- "practice_questions": practice_questions,- }-- # Save transcript- if output_dir is None:- output_dir = PROJECT_ROOT / "benchmark" / "data" / "transcripts"- output_dir = Path(output_dir)- output_dir.mkdir(parents=True, exist_ok=True)-- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- output_file = output_dir / f"{entry_id}_{timestamp}.json"- with open(output_file, "w", encoding="utf-8") as f:- json.dump(result, f, ensure_ascii=False, indent=2)-- print(f"Transcript saved → {output_file}")- return result---def _load_entries_for_profile(- jsonl_path: Path,- profile_id: str,-) -> list[dict]:- """Load and return entries for a given profile_id, sorted by task_id."""- entries = []- with open(jsonl_path, encoding="utf-8") as f:- for line in f:- line = line.strip()- if not line:- continue- entry = json.loads(line)- if entry.get("profile", {}).get("profile_id") == profile_id:- entries.append(entry)- # Sort by entry_id (contains task_id) for deterministic order- entries.sort(key=lambda e: e.get("entry_id", ""))- return entries---def _load_entries_from_paths(paths: list[str]) -> list[dict]:- """Load entries from explicit JSON paths."""- entries = []- for p in paths:- path = Path(p.strip())- if not path.exists():- raise FileNotFoundError(f"Entry file not found: {path}")- with open(path, encoding="utf-8") as f:- entries.append(json.load(f))- return entries---async def run_multi_session(- entry_path: str | Path | None = None,- profile_id: str | None = None,- entry_paths: list[str] | None = None,- max_turns: int = 20,- auto: bool = False,- auto_backend: Literal["deep_tutor", "mock"] = "deep_tutor",- deeptutor_language: str = "en",- output_dir: str | Path | None = None,- use_editor: bool = True,- evolve_profile: bool = True,-) -> dict:- """- Run multiple sessions for the same student (one task per session).-- Entries are loaded either by:- - profile_id: filter JSONL at entry_path by profile- - entry_paths: explicit list of entry JSON paths-- After each session, prior_sessions_summary is built and injected into- student context for the next session. If evolve_profile is True, the profile is- evolved (resolved gaps → known_well) for the next session.-- Returns:- Dict with sessions list and combined transcript- """- if entry_paths:- entries = _load_entries_from_paths(entry_paths)- elif entry_path and profile_id:- entries = _load_entries_for_profile(Path(entry_path), profile_id)- if not entries:- raise ValueError(- f"No entries found for profile_id={profile_id} in {entry_path}"- )- else:- raise ValueError("Provide either (entry_path + profile_id) or entry_paths")-- if output_dir is None:- output_dir = PROJECT_ROOT / "benchmark" / "data" / "transcripts"- output_dir = Path(output_dir)- output_dir.mkdir(parents=True, exist_ok=True)-- profile_id_display = profile_id or entries[0].get("profile", {}).get("profile_id", "?")- shared_workspace = _build_sim_workspace(- profile_id=profile_id_display,- entry_id=entries[0].get("entry_id", "unknown"),- shared_by_profile=True,- )- print(f"\n{'='*60}")- print(f"Multi-session: {profile_id_display} ({len(entries)} sessions)")- print(f"Mode: {'auto (' + auto_backend + ')' if auto else 'interactive'}")- if auto and auto_backend == "deep_tutor":- print(f"DeepTutor workspace(shared): {shared_workspace}")- print(f"Evolve profile: {evolve_profile}")- print(f"{'='*60}\n")-- prior_sessions_summary: list[str] = []- current_profile = entries[0].get("profile", {})- sessions_results: list[dict] = []-- for i, base_entry in enumerate(entries):- session_num = i + 1- entry_id = base_entry.get("entry_id", f"session_{session_num}")-- # Build entry for this session: evolved profile + prior context- entry = dict(base_entry)- if evolve_profile and i > 0:- prev_entry = entries[i - 1]- resolved = prev_entry.get("gaps", [])- from benchmark.simulation.profile_evolver import evolve_profile as evolve_profile_fn-- current_profile = evolve_profile_fn(prev_entry.get("profile", {}), resolved)- entry["profile"] = current_profile-- prior_ctx = "\n".join(prior_sessions_summary) if prior_sessions_summary else None-- print(f"\n--- Session {session_num}/{len(entries)}: {entry_id} ---\n")-- result = await _run_single_session(- entry=entry,- max_turns=max_turns,- auto=auto,- use_editor=use_editor,- auto_backend=auto_backend,- deeptutor_workspace=shared_workspace,- deeptutor_language=deeptutor_language,- prior_sessions_summary=prior_ctx,- )-- task = entry.get("task", {})- summary = _summarize_session(- result["transcript"],- task,- session_num,- )- prior_sessions_summary.append(summary)-- sessions_results.append(result)- print(f"\n[Session {session_num} complete. {result['actual_turns']} turns.]")-- combined = {- "profile_id": profile_id_display,- "timestamp": datetime.now().isoformat(),- "mode": "auto" if auto else "interactive",- "evolve_profile": evolve_profile,- "num_sessions": len(sessions_results),- "sessions": [- {- "entry_id": r["entry_id"],- "actual_turns": r["actual_turns"],- "transcript": r["transcript"],- "entry": r["entry"],- "practice_questions": r.get("practice_questions", []),- }- for r in sessions_results- ],- }-- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- out_file = output_dir / f"multi_{profile_id_display}_{timestamp}.json"- with open(out_file, "w", encoding="utf-8") as f:- json.dump(combined, f, ensure_ascii=False, indent=2)-- print(f"\n{'='*60}")- print(f"Multi-session complete. Transcript saved → {out_file}")- print(f"{'='*60}\n")-- return combined---async def main():- """CLI entry point."""- import argparse-- logging.basicConfig(- level=logging.INFO,- format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",- )-- parser = argparse.ArgumentParser(- description="Run a student-tutor conversation from a benchmark entry"- )- parser.add_argument(- "--entry",- help="Path to benchmark entry JSON or JSONL file",- )- parser.add_argument(- "--multi-session",- action="store_true",- help="Run multiple sessions for same student (requires --profile or --entries)",- )- parser.add_argument(- "--profile",- help="Profile ID to filter JSONL entries (use with --entry and --multi-session)",- )- parser.add_argument(- "--entries",- help="Comma-separated paths to entry JSON files (use with --multi-session)",- )- parser.add_argument(- "--no-evolve",- action="store_true",- help="Disable profile evolution between sessions (multi-session only)",- )- parser.add_argument(- "--auto",- action="store_true",- help="Use auto tutor backend instead of interactive mode",- )- parser.add_argument(- "--auto-backend",- choices=["deep_tutor", "mock"],- default="deep_tutor",- help="Auto tutor backend (default: deep_tutor)",- )- parser.add_argument(- "--deeptutor-language",- default="en",- help="Language for DeepTutor tools (default: en)",- )- parser.add_argument(- "--max-turns",- type=int,- default=20,- help="Maximum number of student turns (default: 20)",- )- parser.add_argument(- "--output-dir",- default=None,- help="Directory to save transcript (default: benchmark/data/transcripts/)",- )- parser.add_argument(- "--entry-index",- type=int,- default=0,- help="When entry is a JSONL file, which entry to use (0-based, default: 0)",- )- parser.add_argument(- "--inline",- action="store_true",- help="Use console input instead of editor (empty line + Enter to send)",- )-- args = parser.parse_args()- if args.auto:- _suppress_noisy_auto_logs()-- if args.multi_session:- if args.entries:- entry_paths = [p.strip() for p in args.entries.split(",") if p.strip()]- await run_multi_session(- entry_paths=entry_paths,- max_turns=args.max_turns,- auto=args.auto,- auto_backend=args.auto_backend,- deeptutor_language=args.deeptutor_language,- output_dir=args.output_dir,- use_editor=not args.inline,- evolve_profile=not args.no_evolve,- )- elif args.entry and args.profile:- await run_multi_session(- entry_path=args.entry,- profile_id=args.profile,- max_turns=args.max_turns,- auto=args.auto,- auto_backend=args.auto_backend,- deeptutor_language=args.deeptutor_language,- output_dir=args.output_dir,- use_editor=not args.inline,- evolve_profile=not args.no_evolve,- )- else:- parser.error(- "Multi-session requires either --entries or (--entry + --profile)"- )- else:- if not args.entry:- parser.error("Single-session mode requires --entry")- await run_conversation(- entry_path=args.entry,- max_turns=args.max_turns,- auto=args.auto,- auto_backend=args.auto_backend,- deeptutor_language=args.deeptutor_language,- output_dir=args.output_dir,- entry_index=args.entry_index,- use_editor=not args.inline,- )---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/simulation/profile_evolver.py b/benchmark/simulation/profile_evolver.pydeleted file mode 100644index ff0ef8d43..000000000--- a/benchmark/simulation/profile_evolver.py+++ /dev/null@@ -1,102 +0,0 @@-"""-Profile Evolver - Update student profile after a session--When a session completes, the addressed gaps are considered "resolved".-This module updates the profile for the next session:-- Moves resolved concepts from unknown/partially_known to known_well-- Removes resolved gaps from the gaps list (for beliefs)-"""--import copy-import logging-from typing import Any--logger = logging.getLogger("benchmark.profile_evolver")---def evolve_profile(profile: dict, resolved_gaps: list[dict]) -> dict:- """- Create an updated profile after resolving the given gaps.-- For each resolved gap:- - Add target_concept (or correct_understanding summary) to known_well- - Remove from unknown and partially_known if present-- Args:- profile: Original profile dict (will be deep-copied)- resolved_gaps: List of gap dicts that were addressed in the session-- Returns:- New profile dict with updated knowledge_state- """- if not resolved_gaps:- return copy.deepcopy(profile)-- new_profile = copy.deepcopy(profile)- ks = new_profile.get("knowledge_state", {})- known_well = list(ks.get("known_well", []))- partially_known = list(ks.get("partially_known", []))- unknown = list(ks.get("unknown", []))-- for gap in resolved_gaps:- concept = gap.get("target_concept", "")- if not concept:- continue-- # Add to known_well (student learned this)- if concept not in known_well:- known_well.append(concept)-- # Remove from partially_known and unknown- if concept in partially_known:- partially_known.remove(concept)- if concept in unknown:- unknown.remove(concept)-- new_profile["knowledge_state"] = {- "known_well": known_well,- "partially_known": partially_known,- "unknown": unknown,- }-- logger.debug(- "Evolved profile: +%d known_well, resolved %d gaps",- len(known_well) - len(ks.get("known_well", [])),- len(resolved_gaps),- )- return new_profile---def evolve_entry(- entry: dict,- resolved_gaps: list[dict],- prior_sessions_summary: str | None = None,-) -> dict:- """- Create an entry for the next session with evolved profile and remaining gaps.-- Args:- entry: Base entry (from previous session or template)- resolved_gaps: Gaps addressed in the completed session- prior_sessions_summary: Optional summary of prior sessions for context-- Returns:- New entry with evolved profile; gaps exclude resolved ones- """- new_entry = copy.deepcopy(entry)- resolved_ids = {g.get("gap_id") for g in resolved_gaps}-- # Evolve profile- new_entry["profile"] = evolve_profile(- entry.get("profile", {}),- resolved_gaps,- )-- # Remove resolved gaps from entry's gaps list- remaining_gaps = [g for g in entry.get("gaps", []) if g.get("gap_id") not in resolved_ids]- new_entry["gaps"] = remaining_gaps-- if prior_sessions_summary:- new_entry["prior_sessions_summary"] = prior_sessions_summary-- return new_entrydiff --git a/benchmark/simulation/student_agent.py b/benchmark/simulation/student_agent.pydeleted file mode 100644index 6faa70c63..000000000--- a/benchmark/simulation/student_agent.py+++ /dev/null@@ -1,305 +0,0 @@-#!/usr/bin/env python-"""-Student Agent - LLM-based student role-playing for tutor evaluation--Takes a benchmark entry (profile + gaps + task) and role-plays as the student-in a multi-turn conversation with a tutor.--The agent:-- Initiates conversation with task.initial_message-- Responds to tutor messages while staying in character-- Naturally exhibits knowledge gaps (misconceptions, incomplete understanding)-- Gradually learns from good explanations but doesn't accept corrections instantly--Usage:- agent = StudentAgent.from_entry(entry)- first_msg = agent.initial_message()- response, task_complete = await agent.respond(tutor_reply)-"""--import json-import logging-import re-from pathlib import Path-from typing import Any--import yaml--logger = logging.getLogger("benchmark.student_agent")--PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent--# Only task_complete is used; no action required on other messages-TASK_COMPLETE_RE = re.compile(r"\[\s*TASK_COMPLETE\s*\]", re.IGNORECASE)-ACTION_TASK_COMPLETE_RE = re.compile(- r"\[\s*ACTION\s*:\s*task_complete\s*\]",- re.IGNORECASE,-)---def _load_student_prompt_template() -> str:- """Load the student system prompt template."""- path = PROJECT_ROOT / "benchmark" / "prompts" / "student_system.yaml"- with open(path, encoding="utf-8") as f:- data = yaml.safe_load(f)- return data["system"]---def _format_list(items: list[str], bullet: str = "-") -> str:- """Format a list of strings as bullet points."""- if not items:- return "(none)"- return "\n".join(f" {bullet} {item}" for item in items)---def _build_beliefs_text(gaps: list[dict]) -> str:- """- Convert knowledge gaps into first-person belief statements.-- This is the key trick: gaps are encoded as what the student *believes*,- not as what's wrong. This prevents the LLM from being self-aware about errors.- """- if not gaps:- return "(No specific beliefs to note.)"-- beliefs = []- for gap in gaps:- gap_type = gap.get("type", "unknown")- concept = gap.get("target_concept", "")- description = gap.get("description", "")- manifestation = gap.get("manifestation", "")-- if gap_type == "misconception":- beliefs.append(- f"You believe the following about {concept}: {description}\n"- f" This feels obviously correct to you. "- f"In conversation, you would naturally: {manifestation}"- )- elif gap_type == "incomplete":- beliefs.append(- f"Regarding {concept}: {description}\n"- f" You feel you understand this topic reasonably well, "- f"but haven't thought deeply about edge cases. "- f"In conversation, you might: {manifestation}"- )- elif gap_type == "missing":- beliefs.append(- f"You have never encountered {concept}. {description}\n"- f" If this comes up, you would: {manifestation}"- )- else:- beliefs.append(f"About {concept}: {description}")-- return "\n\n".join(f"[Belief {i+1}]\n{b}" for i, b in enumerate(beliefs))---def _build_gap_pacing_text(task: dict, gaps: list[dict]) -> str:- """Build natural gap-exposure guidance — no rigid turn schedule."""- num_gaps = len(gaps)- if num_gaps == 0:- return "You have no specific confusions to reveal."-- lines = [- "You have several confusions/gaps (listed in the Beliefs section above), "- "but you are NOT aware of them as a list. They surface naturally:",- "",- "- Start the conversation with whatever feels most relevant to your question.",- "- Only bring up a confusion when it genuinely connects to what you and the tutor are discussing.",- "- If the tutor's explanation touches on one of your misconceptions, react naturally — ",- " express surprise, push back, or ask a follow-up.",- "- You do NOT need to hold back confusions. If something comes up that you're confused about, bring it up.",- "- There is no limit on how many confusions you can surface across the session.",- "",- "Per-reply guideline: prefer focusing on one confusion at a time for clarity, "- "but if two issues are genuinely entangled you may mention both.",- ]- return "\n".join(lines)---class StudentAgent:- """- An LLM-powered student agent for tutor evaluation.-- Maintains conversation history and generates in-character student responses.- """-- def __init__(- self,- system_prompt: str,- first_message: str,- entry_id: str = "unknown",- temperature: float = 0.7,- max_tokens: int = 1024,- ):- self.system_prompt = system_prompt- self.first_message = first_message- self.entry_id = entry_id- self.temperature = temperature- self.max_tokens = max_tokens-- # Conversation history: list of {"role": "user"/"assistant", "content": "..."}- # From the tutor's perspective: user=student, assistant=tutor- # But from the student LLM's perspective: user=tutor, assistant=student- # We store it from the STUDENT's perspective (student=assistant, tutor=user)- self.history: list[dict[str, str]] = []- self.turn_count: int = 0-- @classmethod- def from_entry(- cls,- entry: dict,- prior_sessions_context: str | None = None,- **kwargs,- ) -> "StudentAgent":- """- Create a StudentAgent from a benchmark entry.-- Args:- entry: Benchmark entry dict with profile, gaps, task- prior_sessions_context: Optional summary of previous sessions (student- "remembers" this). Injected at start of system prompt.- **kwargs: Override temperature, max_tokens, etc.-- Returns:- Configured StudentAgent- """- profile = entry.get("profile", {})- gaps = entry.get("gaps", [])- task = entry.get("task", {})- entry_id = entry.get("entry_id", "unknown")-- # Build system prompt from template- template = _load_student_prompt_template()-- knowledge_state = profile.get("knowledge_state", {})-- system_prompt = template.format(- personality=profile.get("personality", "A typical student."),- education_background=profile.get(- "education_background", "An undergraduate student."- ),- learning_purpose=profile.get(- "learning_purpose", "To learn the material for an upcoming exam."- ),- known_well=_format_list(knowledge_state.get("known_well", [])),- partially_known=_format_list(knowledge_state.get("partially_known", [])),- unknown=_format_list(knowledge_state.get("unknown", [])),- beliefs=_build_beliefs_text(gaps),- gap_pacing_plan=_build_gap_pacing_text(task, gaps),- )-- if prior_sessions_context:- system_prompt = (- "# Prior Sessions (you remember these)\n"- f"{prior_sessions_context}\n\n"- "---\n\n"- + system_prompt- )-- first_message = task.get("initial_message", "Hi, I need help with this topic.")-- return cls(- system_prompt=system_prompt,- first_message=first_message,- entry_id=entry_id,- **kwargs,- )-- @classmethod- def from_file(cls, path: str | Path, **kwargs) -> "StudentAgent":- """- Create a StudentAgent from a benchmark entry JSON file.-- Args:- path: Path to the entry JSON file- **kwargs: Override temperature, max_tokens, etc.-- Returns:- Configured StudentAgent- """- with open(path, encoding="utf-8") as f:- entry = json.load(f)- return cls.from_entry(entry, **kwargs)-- def initial_message(self) -> str:- """- Get the student's first message (from task.initial_message).-- Also records it in history. Initial message implicitly has action "solve".- """- self.history.append({- "role": "assistant",- "content": self.first_message,- "action": "solve",- })- self.turn_count = 1- return self.first_message-- async def respond(self, tutor_message: str) -> tuple[str, str]:- """- Generate a student response to a tutor message (ReAct paradigm).-- Args:- tutor_message: The tutor's latest message-- Returns:- Tuple of (message, action). action is one of: solve, generate_problem, task_complete.- """- # Record tutor message- self.history.append({"role": "user", "content": tutor_message})-- # Build messages array for LLM call- messages = [{"role": "system", "content": self.system_prompt}]- messages.extend(self.history)-- # Call LLM- from src.services.llm import factory-- response = await factory.complete(- prompt="", # Not used when messages is provided- system_prompt="", # Not used when messages is provided- messages=messages,- temperature=self.temperature,- max_tokens=self.max_tokens,- )-- # Parse only task_complete; no action required on other messages- action = "solve" # default (continue conversation)- if ACTION_TASK_COMPLETE_RE.search(response) or TASK_COMPLETE_RE.search(response):- action = "task_complete"-- # Strip task_complete markers from message- cleaned = ACTION_TASK_COMPLETE_RE.sub("", response)- cleaned = TASK_COMPLETE_RE.sub("", cleaned)- cleaned = cleaned.strip()-- # Record in history with action metadata- self.history.append({"role": "assistant", "content": cleaned, "action": action})- self.turn_count += 1-- return (cleaned, action)-- def get_transcript(self) -> list[dict]:- """- Get the full conversation transcript.-- Returns:- List of messages with roles "student"/"tutor". Student messages include- "action" (solve, generate_problem, or task_complete) when available.- """- transcript = []- for msg in self.history:- role = "student" if msg["role"] == "assistant" else "tutor"- entry = {"role": role, "content": msg["content"]}- if role == "student" and msg.get("action") == "task_complete":- entry["action"] = "task_complete"- transcript.append(entry)- return transcript-- def get_metadata(self) -> dict[str, Any]:- """Get agent metadata for saving alongside transcript."""- return {- "entry_id": self.entry_id,- "turn_count": self.turn_count,- "system_prompt_length": len(self.system_prompt),- }diff --git a/benchmark/simulation/test_tools.py b/benchmark/simulation/test_tools.pydeleted file mode 100644index 8b173c0ab..000000000--- a/benchmark/simulation/test_tools.py+++ /dev/null@@ -1,268 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-Quick smoke-test for the three simulator tools.--Usage:- python benchmark/simulation/test_tools.py-"""--from __future__ import annotations--import asyncio-import json-import shutil-import sys-from pathlib import Path--PROJECT_ROOT = Path(__file__).resolve().parents[2]-sys.path.insert(0, str(PROJECT_ROOT))--from dotenv import load_dotenv-load_dotenv(PROJECT_ROOT / ".env", override=False)--# ── Test workspace ─────────────────────────────────────────────────────--TEST_WS = str(PROJECT_ROOT / "data" / "eval_test" / "student_test")-KB = "ai-textbook"-LANG = "en"--GREEN = "\033[92m"-RED = "\033[91m"-CYAN = "\033[96m"-BOLD = "\033[1m"-DIM = "\033[2m"-RESET = "\033[0m"---def section(title: str) -> None:- print(f"\n{'='*60}")- print(f" {BOLD}{CYAN}{title}{RESET}")- print(f"{'='*60}")---def check_path(label: str, path: str | Path) -> bool:- p = Path(path)- ok = p.exists()- icon = f"{GREEN}✓{RESET}" if ok else f"{RED}✗{RESET}"- print(f" {icon} {label}: {DIM}{p}{RESET}")- return ok---def check_key(label: str, d: dict, key: str) -> bool:- val = d.get(key)- ok = val is not None and val != "" and val != []- icon = f"{GREEN}✓{RESET}" if ok else f"{RED}✗{RESET}"- short = str(val)[:120] if val else "(missing)"- print(f" {icon} {label}: {DIM}{short}{RESET}")- return ok---# ── Test 1: solve_question ─────────────────────────────────────────────--async def test_solve():- section("Test 1: solve_question")- from benchmark.simulation import solve_question-- result = await solve_question(- workspace=TEST_WS,- kb_name=KB,- question="What is gradient descent and why is it important in machine learning?",- language=LANG,- )-- print(f"\n {BOLD}Return keys:{RESET} {list(result.keys())}")- check_key("question", result, "question")- check_key("answer", result, "answer")- check_key("output_dir", result, "output_dir")- check_key("steps", result, "steps")-- # Check file paths- print(f"\n {BOLD}File paths:{RESET}")- ws = Path(TEST_WS)- check_path("workspace/memory/", ws / "memory")- check_path("workspace/solve/", ws / "solve")-- out_dir = result.get("output_dir", "")- if out_dir:- check_path("output_dir exists", out_dir)- check_path("scratchpad.json", Path(out_dir) / "scratchpad.json")- check_path("final_answer.md", Path(out_dir) / "final_answer.md")-- # Check trace was registered- traces_dir = ws / "memory" / "traces"- check_path("traces/ dir", traces_dir)- check_path("index.json", traces_dir / "index.json")- if (traces_dir / "index.json").exists():- idx = json.loads((traces_dir / "index.json").read_text())- n_traces = len(idx.get("traces", []))- n_nodes = len(idx.get("nodes", []))- print(f" {GREEN}✓{RESET} index: {n_traces} trace(s), {n_nodes} node(s)")-- # Check memory docs- print(f"\n {BOLD}Memory docs:{RESET}")- for doc in ("memory.md", "weakness.md", "reflection.md"):- p = ws / "memory" / doc- if p.exists():- size = len(p.read_text())- print(f" {GREEN}✓{RESET} {doc}: {size} chars")- else:- print(f" {DIM}○{RESET} {doc}: not yet created (agent may not have written it)")-- return result---# ── Test 2: generate_questions ─────────────────────────────────────────--async def test_generate():- section("Test 2: generate_questions")- from benchmark.simulation import generate_questions-- result = await generate_questions(- workspace=TEST_WS,- kb_name=KB,- topic="gradient descent and optimization",- preferences="focus on intuition and practical applications",- num_questions=2,- language=LANG,- )-- print(f"\n {BOLD}Return keys:{RESET} {list(result.keys())}")- check_key("batch_id", result, "batch_id")- check_key("batch_dir", result, "batch_dir")- check_key("num_generated", result, "num_generated")- check_key("questions", result, "questions")-- questions = result.get("questions", [])- print(f"\n {BOLD}Questions generated: {len(questions)}{RESET}")- for q in questions:- print(f" {CYAN}[{q.get('question_id')}]{RESET} {q.get('question', '')[:80]}...")- opts = q.get("options", {})- if isinstance(opts, dict):- for k, v in opts.items():- print(f" {k}. {v[:60]}")- # Verify no correct answer leaked- assert "correct_answer" not in q, "LEAK: correct_answer in question!"- print(f" {GREEN}✓ no correct_answer leak{RESET}")-- # Check file paths- print(f"\n {BOLD}File paths:{RESET}")- batch_dir = result.get("batch_dir", "")- if batch_dir:- check_path("batch_dir", batch_dir)- check_path("summary.json", Path(batch_dir) / "summary.json")- check_path("templates.json", Path(batch_dir) / "templates.json")-- # Check trace registered (should be in question dir, NOT solve dir)- ws = Path(TEST_WS)- traces_dir = ws / "memory" / "traces"- if (traces_dir / "index.json").exists():- idx = json.loads((traces_dir / "index.json").read_text())- q_traces = [t for t in idx.get("traces", []) if t.get("trace_type") == "question"]- print(f" {GREEN}✓{RESET} question traces in index: {len(q_traces)}")-- return result---# ── Test 3: submit_answers ─────────────────────────────────────────────--async def test_submit(gen_result: dict):- section("Test 3: submit_answers")- from benchmark.simulation import submit_answers-- questions = gen_result.get("questions", [])- if not questions:- print(f" {RED}✗ No questions to answer, skipping{RESET}")- return-- # Simulate student answers (pick "A" for all — naive strategy)- answers = [- {"question_id": q["question_id"], "answer": "A"}- for q in questions- ]- print(f" Submitting {len(answers)} answer(s) (all 'A')...")-- result = await submit_answers(- workspace=TEST_WS,- batch_id=gen_result["batch_id"],- answers=answers,- language=LANG,- )-- print(f"\n {BOLD}Return keys:{RESET} {list(result.keys())}")-- # Per-question results- results = result.get("results", [])- for r in results:- judged = r.get("judged_result", "?")- icon = f"{GREEN}✓{RESET}" if judged == "correct" else f"{RED}✗{RESET}"- print(- f" {icon} {r.get('question_id')}: "- f"user={r.get('user_answer')} correct={r.get('correct_answer')} → {judged}"- )- # Verify explanation is returned- assert "explanation" in r, "Missing explanation in result"-- # Score- score = result.get("score", {})- print(f"\n {BOLD}Score:{RESET} {score.get('correct')}/{score.get('total')} "- f"(accuracy={score.get('accuracy', 0):.2%})")-- # Check trace now has answer nodes- ws = Path(TEST_WS)- traces_dir = ws / "memory" / "traces"- batch_id = gen_result["batch_id"]- trace_file = traces_dir / f"{batch_id}.json"- if trace_file.exists():- tree_data = json.loads(trace_file.read_text())- nodes = tree_data.get("nodes", {})- answer_nodes = {k: v for k, v in nodes.items() if v.get("node_type") == "answer"}- print(f" {GREEN}✓{RESET} trace has {len(answer_nodes)} answer node(s)")- else:- print(f" {RED}✗{RESET} trace file not found: {trace_file}")-- # Check memory docs updated after submit- print(f"\n {BOLD}Memory docs after submit:{RESET}")- for doc in ("memory.md", "weakness.md", "reflection.md"):- p = ws / "memory" / doc- if p.exists():- size = len(p.read_text())- print(f" {GREEN}✓{RESET} {doc}: {size} chars")- else:- print(f" {DIM}○{RESET} {doc}: not created")-- return result---# ── Main ───────────────────────────────────────────────────────────────--async def main():- ws = Path(TEST_WS)- if ws.exists():- print(f" Cleaning previous test workspace: {ws}")- shutil.rmtree(ws)-- try:- await test_solve()- gen_result = await test_generate()- await test_submit(gen_result)- finally:- section("Final workspace tree")- # Print directory tree (first 3 levels)- for p in sorted(ws.rglob("*")):- rel = p.relative_to(ws)- depth = len(rel.parts)- if depth > 3:- continue- indent = " " * depth- if p.is_file():- size = p.stat().st_size- print(f" {indent}{p.name} ({size:,} bytes)")- else:- print(f" {indent}{p.name}/")-- print(f"\n {GREEN}{BOLD}All tests completed.{RESET}\n")---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/simulation/tools.py b/benchmark/simulation/tools.pydeleted file mode 100644index ef41bbddf..000000000--- a/benchmark/simulation/tools.py+++ /dev/null@@ -1,621 +0,0 @@-# -*- coding: utf-8 -*--"""-Simulator Tools — workspace-isolated solve / question / answer tools.--Each tool accepts a ``workspace`` path that determines where all artifacts-(solve outputs, question batches, traces, memory documents) are stored.-Memory agents only see traces inside that workspace.-"""--from __future__ import annotations--import asyncio-import json-import logging-import sys-from pathlib import Path-from typing import Any--# ── Ensure project root is importable ──────────────────────────────────-_PROJECT_ROOT = Path(__file__).resolve().parents[2]-if str(_PROJECT_ROOT) not in sys.path:- sys.path.insert(0, str(_PROJECT_ROOT))--from dotenv import load_dotenv--load_dotenv(_PROJECT_ROOT / "DeepTutor.env", override=False)-load_dotenv(_PROJECT_ROOT / ".env", override=False)--import yaml--from src.personalization.memory_reader import (- MemoryReader,- _workspace_memory_disabled_var,- _workspace_reader_var,-)-from src.personalization.trace_forest import TraceForest-from src.personalization.trace_tree import TraceNode, TraceTree-from src.agents.solve.tools import ToolRegistry--logger = logging.getLogger(__name__)---# ======================================================================-# Workspace session-# ======================================================================--class WorkspaceSession:- """Directory layout manager for one simulated student."""-- def __init__(self, workspace: str) -> None:- self.root = Path(workspace)- self.memory_dir = self.root / "memory"- self.solve_dir = self.root / "solve"- self.question_dir = self.root / "question"- for d in (self.memory_dir, self.solve_dir, self.question_dir):- d.mkdir(parents=True, exist_ok=True)---# ======================================================================-# Tool 1 — solve_question-# ======================================================================--async def solve_question(- workspace: str,- kb_name: str,- question: str,- language: str = "en",- enabled_tools: list[str] | None = None,- enable_memory: bool = True,- enable_planner_retrieve: bool = True,-) -> dict[str, Any]:- """Solve a question with the full Plan → ReAct → Write pipeline.-- All outputs are saved under ``<workspace>/solve/``.- Memory agents update ``<workspace>/memory/``.-- Returns- -------- dict with keys: question, answer, output_dir, steps,- completed_steps, citations.- """- session = WorkspaceSession(workspace)- forest: TraceForest | None = None- token = None- disable_token = None- if enable_memory:- forest = TraceForest(memory_dir=session.memory_dir)- reader = MemoryReader(forest=forest)- token = _workspace_reader_var.set(reader)- else:- disable_token = _workspace_memory_disabled_var.set(True)-- try:- from src.agents.solve import MainSolver-- tool_registry = (- ToolRegistry.create_from_names(enabled_tools, language=language)- if enabled_tools is not None- else None- )-- solver = MainSolver(- kb_name=kb_name,- language=language,- output_base_dir=str(session.solve_dir),- tool_registry=tool_registry,- disable_planner_retrieve=not enable_planner_retrieve,- )- await solver.ainit()- result = await solver.solve(question)-- # Build trace from scratchpad and register- scratchpad_path = Path(result["output_dir"]) / "scratchpad.json"- if enable_memory and forest is not None and scratchpad_path.exists():- scratchpad_data = json.loads(scratchpad_path.read_text("utf-8"))- answer_path = str(Path(result["output_dir"]) / "final_answer.md")- tree = TraceTree.from_scratchpad(- scratchpad_data,- task_id=Path(result["output_dir"]).name,- answer_path=answer_path,- )- await forest.register(tree)- await _run_memory_agents(tree, forest, session.memory_dir, language)-- return {- "question": question,- "answer": result.get("final_answer", ""),- "output_dir": result.get("output_dir", ""),- "steps": result.get("total_steps", 0),- "completed_steps": result.get("completed_steps", 0),- "citations": result.get("citations", []),- }- finally:- if token is not None:- _workspace_reader_var.reset(token)- if disable_token is not None:- _workspace_memory_disabled_var.reset(disable_token)---# ======================================================================-# Tool 2 — generate_questions-# ======================================================================--async def generate_questions(- workspace: str,- kb_name: str,- topic: str,- preferences: str = "",- num_questions: int = 3,- language: str = "en",- enable_memory: bool = True,- enable_rag: bool = True,- enable_web: bool = True,-) -> dict[str, Any]:- """Generate multiple-choice questions with memory.-- All outputs are saved under ``<workspace>/question/``.- Returns questions **without** correct answers so the student- agent cannot peek.-- Returns- -------- dict with keys: batch_id, batch_dir, num_generated,- questions (list of {question_id, question, options, question_type}).- """- session = WorkspaceSession(workspace)- forest: TraceForest | None = None- token = None- disable_token = None- if enable_memory:- forest = TraceForest(memory_dir=session.memory_dir)- reader = MemoryReader(forest=forest)- token = _workspace_reader_var.set(reader)- else:- disable_token = _workspace_memory_disabled_var.set(True)-- try:- from src.agents.question import AgentCoordinator-- coordinator = AgentCoordinator(- kb_name=kb_name,- output_dir=str(session.question_dir),- language=language,- tool_flags_override={- "rag_tool": enable_rag,- "web_search": enable_web,- "write_code": True,- },- enable_idea_rag=enable_rag,- )- summary = await coordinator.generate_from_topic(- user_topic=topic,- preference=preferences,- num_questions=num_questions,- question_type="choice",- )-- batch_dir = summary.get("batch_dir", "")- batch_id = Path(batch_dir).name if batch_dir else ""-- # Register trace (without answers — deferred until submit_answers)- if enable_memory and forest is not None and batch_dir:- summary_path = Path(batch_dir) / "summary.json"- if summary_path.exists():- summary_data = json.loads(summary_path.read_text("utf-8"))- tree = TraceTree.from_question_summary(- summary=summary_data,- user_topic=topic,- task_id=batch_id,- include_answers=False,- answer_path=str(summary_path),- )- await forest.register(tree)-- # Build question list for the student (no correct answers)- questions: list[dict[str, Any]] = []- for r in summary.get("results", []):- if not r.get("success"):- continue- qa = r.get("qa_pair", {})- questions.append({- "question_id": qa.get("question_id", ""),- "question": qa.get("question", ""),- "options": qa.get("options", {}),- "question_type": qa.get("question_type", "choice"),- })-- return {- "batch_id": batch_id,- "batch_dir": batch_dir,- "num_generated": len(questions),- "questions": questions,- }- finally:- if token is not None:- _workspace_reader_var.reset(token)- if disable_token is not None:- _workspace_memory_disabled_var.reset(disable_token)---# ======================================================================-# Tool 3 — submit_answers-# ======================================================================--async def submit_answers(- workspace: str,- batch_id: str,- answers: list[dict[str, str]],- language: str = "en",-) -> dict[str, Any]:- """Submit answers for a previously generated question batch.-- Each entry in *answers* should be ``{"question_id": "q_1", "answer": "A"}``.-- The tool:- 1. Loads the stored correct answers from ``summary.json``.- 2. Auto-judges each answer.- 3. Appends answer nodes to the trace tree.- 4. Runs the three memory agents on the complete trace.-- Returns- -------- dict with keys: results (per-question detail), score.- """- session = WorkspaceSession(workspace)- forest = TraceForest(memory_dir=session.memory_dir)- reader = MemoryReader(forest=forest)-- tree = forest.load_tree(batch_id)- if tree is None:- return {"error": f"Trace '{batch_id}' not found", "results": [], "score": {}}-- # Load correct answers from summary.json- correct_map: dict[str, dict[str, str]] = {}- summary_path = session.question_dir / batch_id / "summary.json"- if summary_path.exists():- summary_data = json.loads(summary_path.read_text("utf-8"))- for r in summary_data.get("results", []):- qa = r.get("qa_pair", {})- qid = qa.get("question_id", "")- if qid:- correct_map[qid] = {- "correct_answer": qa.get("correct_answer", ""),- "question_type": qa.get("question_type", "choice"),- "explanation": qa.get("explanation", ""),- }-- # Judge each answer and attach to trace- results: list[dict[str, Any]] = []- for ans in answers:- qid = ans.get("question_id", "")- user_answer = ans.get("answer", "")- info = correct_map.get(qid, {})- correct_answer = info.get("correct_answer", "")- explanation = info.get("explanation", "")-- judged = _judge_choice(user_answer, correct_answer)-- # Locate the template node and attach an answer node- tmpl_node = _find_template_node(tree, qid)- if tmpl_node is not None:- answer_short = f"{tmpl_node.short_id}.A1"- answer_node = TraceNode(- short_id=answer_short,- level=3,- text=user_answer.strip() or qid,- node_type="answer",- data={- "question_id": qid,- "user_answer": user_answer,- "judged_result": judged,- "question": tmpl_node.data.get("concentration", ""),- },- parent=tmpl_node.short_id,- )- if answer_short not in tree.nodes:- tmpl_node.children.append(answer_short)- tree.nodes[answer_short] = answer_node-- results.append({- "question_id": qid,- "user_answer": user_answer,- "correct_answer": correct_answer,- "judged_result": judged,- "explanation": explanation,- })-- # Re-register trace (now includes answer nodes)- await forest.register(tree)-- # Run memory agents with the complete trace- token = _workspace_reader_var.set(reader)- try:- await _run_memory_agents(tree, forest, session.memory_dir, language)- finally:- _workspace_reader_var.reset(token)-- correct = sum(1 for r in results if r["judged_result"] == "correct")- wrong = sum(1 for r in results if r["judged_result"] == "wrong")- total = len(results)-- return {- "results": results,- "score": {- "total": total,- "correct": correct,- "wrong": wrong,- "accuracy": round(correct / total, 4) if total else 0.0,- },- }---# ======================================================================-# Internal helpers-# ======================================================================--def _judge_choice(user_answer: str, correct_answer: str) -> str:- ua = user_answer.strip().upper().strip("().)( ")- ca = correct_answer.strip().upper().strip("().)( ")- if not ua:- return "skipped"- if ua == ca:- return "correct"- return "wrong"---def _find_template_node(tree: TraceTree, question_id: str) -> TraceNode | None:- q_idx = question_id.replace("q_", "")- short = f"T{q_idx}" if q_idx.isdigit() else f"T{question_id}"- node = tree.nodes.get(short)- if node is not None:- return node- for n in tree.nodes.values():- if n.node_type == "template" and n.data.get("question_id") == question_id:- return n- return None---# ── Memory-agent runner (standalone, no singleton) ─────────────────────--async def _run_memory_agents(- trace: TraceTree,- forest: TraceForest,- memory_dir: Path,- language: str,-) -> None:- """Launch ReflectionAgent, SummaryAgent, WeaknessAgent in parallel."""- from src.personalization.agents import (- ReflectionAgent,- SummaryAgent,- WeaknessAgent,- )- from src.personalization.react_runner import ReActRunner- from src.personalization.trace_tools import TraceToolkit- from src.services.path_service import get_path_service-- config_path = get_path_service().project_root / "config" / "memory.yaml"- config: dict[str, Any] = {}- if config_path.exists():- with open(config_path, "r", encoding="utf-8") as f:- config = yaml.safe_load(f) or {}-- temperature = config.get("llm", {}).get("temperature", 0.5)- max_rounds = config.get("memory", {}).get("max_react_rounds", 6)- agents_cfg = config.get("agents", {})-- toolkit = TraceToolkit(forest, memory_dir)- session_summary = _build_session_summary(trace)- full_context = _build_full_context(trace)-- ctx_base: dict[str, str] = {- "trace_id": trace.trace_id,- "trace_type": trace.trace_type,- "question": trace.root.text,- "answer_path": trace.answer_path,- "session_summary": session_summary,- "full_context": full_context,- }-- log_dir = memory_dir / "logs"- tasks: list[asyncio.Task] = []-- if agents_cfg.get("reflection", {}).get("enabled", True):- agent = ReflectionAgent(language=language, temperature=temperature)- ctx = {**ctx_base, "current_document": _read_md(memory_dir, "reflection.md")}- tasks.append(asyncio.create_task(- _run_single_agent(agent, toolkit, ctx, max_rounds, log_dir),- name="reflection",- ))-- if agents_cfg.get("summary", {}).get("enabled", True):- agent = SummaryAgent(language=language, temperature=temperature)- tasks.append(asyncio.create_task(- _run_single_agent(agent, toolkit, ctx_base, max_rounds, log_dir),- name="summary",- ))-- if agents_cfg.get("weakness", {}).get("enabled", True):- agent = WeaknessAgent(language=language, temperature=temperature)- ctx = {**ctx_base, "current_document": _read_md(memory_dir, "weakness.md")}- tasks.append(asyncio.create_task(- _run_single_agent(agent, toolkit, ctx, max_rounds, log_dir),- name="weakness",- ))-- if tasks:- results = await asyncio.gather(*tasks, return_exceptions=True)- for task, result in zip(tasks, results):- if isinstance(result, Exception):- logger.error("Memory agent '%s' failed: %s", task.get_name(), result)- else:- logger.info("Memory agent '%s' done", task.get_name())---async def _run_single_agent(- agent: Any,- toolkit: Any,- context: dict[str, str],- max_rounds: int,- log_dir: Path | None,-) -> None:- from src.personalization.react_runner import ReActRunner-- system_prompt = agent.get_prompt("system", "")- user_template = agent.get_prompt("user_template", "")- if not system_prompt or not user_template:- return- initial_context = user_template.format(**context)- runner = ReActRunner(- agent=agent,- toolkit=toolkit,- max_rounds=max_rounds,- log_dir=log_dir,- )- await runner.run(system_prompt=system_prompt, initial_context=initial_context)---# ── Context builders (mirrored from PersonalizationService) ────────────--def _read_md(memory_dir: Path, filename: str) -> str:- p = memory_dir / filename- try:- return p.read_text(encoding="utf-8").strip() or "(empty document)"- except FileNotFoundError:- return "(document not found)"---def _build_session_summary(trace: TraceTree) -> str:- if trace.trace_type == "solve":- steps = [n for n in trace.nodes.values() if n.node_type == "step"]- tools = sorted(trace.tools_used) if trace.tools_used else ["none"]- total_rounds = sum(1 for n in trace.nodes.values() if n.node_type == "round")- lines = [- f"Solve summary: {len(steps)} steps, {total_rounds} ReAct rounds, "- f"tools: {', '.join(tools)}",- ]- for step in steps:- n_rounds = len(step.children)- status = step.data.get("status", "?")- goal = step.data.get("step_goal", step.text)- lines.append(f'- {step.short_id} "{goal}" ({n_rounds} rounds) -> {status}')- return "\n".join(lines)-- if trace.trace_type == "question":- templates = [n for n in trace.nodes.values() if n.node_type == "template"]- correct = wrong = skipped = 0- q_lines: list[str] = []- for tmpl in templates:- qtype = tmpl.data.get("question_type", "?")- diff = tmpl.data.get("difficulty", "?")- conc = tmpl.data.get("concentration", tmpl.text)- answer_nodes = [- trace.nodes[cid]- for cid in tmpl.children- if cid in trace.nodes and trace.nodes[cid].node_type == "answer"- ]- if answer_nodes:- res = str(answer_nodes[0].data.get("judged_result", "unknown"))- if res.lower() in ("correct", "true"):- correct += 1- elif res.lower() in ("wrong", "incorrect", "false"):- wrong += 1- else:- skipped += 1- else:- res = "no_answer"- skipped += 1- q_lines.append(f'- {tmpl.short_id} [{qtype}/{diff}] "{conc}" -> {res}')- total = correct + wrong + skipped- header = (- f"Question summary: {total} questions | "- f"correct {correct}, wrong {wrong}, skipped {skipped}"- )- return "\n".join([header] + q_lines)-- return "(unknown trace type)"---def _build_full_context(trace: TraceTree) -> str:- if trace.trace_type == "solve":- if not trace.answer_path:- return "(no final answer available)"- p = Path(trace.answer_path)- if not p.exists():- return "(no final answer available)"- try:- content = p.read_text(encoding="utf-8").strip()- return content if content else "(empty)"- except Exception:- return "(failed to read)"-- if trace.trace_type == "question":- if not trace.answer_path:- return "(no answer data)"- try:- summary_data = json.loads(Path(trace.answer_path).read_text("utf-8"))- except Exception:- return "(no question data)"- if not isinstance(summary_data, dict):- return "(no question data)"-- results = list(summary_data.get("results", []) or [])- if not results:- return "(no results)"-- tmpl_by_qid: dict[str, TraceNode] = {}- for t in trace.nodes.values():- if t.node_type == "template":- qid = t.data.get("question_id", "")- if qid:- tmpl_by_qid[qid] = t-- parts: list[str] = []- for idx, result in enumerate(results, 1):- qa = result.get("qa_pair", {}) or {}- template = result.get("template", {}) or {}-- qid = str(template.get("question_id") or qa.get("question_id") or f"q_{idx}")- qtype = str(template.get("question_type") or qa.get("question_type") or "?")- diff = str(template.get("difficulty") or qa.get("difficulty") or "?")- question_text = str(qa.get("question", "") or "")- correct_answer = str(- qa.get("correct_answer", "") or qa.get("answer", "") or ""- )- explanation = str(qa.get("explanation", "") or "")- options = qa.get("options", None)-- user_answer = ""- judged = "no_answer"- tmpl_node = tmpl_by_qid.get(qid)- if tmpl_node:- for cid in tmpl_node.children:- child = trace.nodes.get(cid)- if child and child.node_type == "answer":- user_answer = str(child.data.get("user_answer", "") or "")- judged = str(- child.data.get("judged_result", "unknown") or "unknown"- )- break-- block = [f"--- Question {idx} [{qtype}/{diff}] ---"]- if question_text:- block.append(f"Question: {question_text}")- if options and isinstance(options, (list, dict)):- if isinstance(options, list):- for opt in options:- block.append(f" {opt}")- elif isinstance(options, dict):- for key, val in options.items():- block.append(f" {key}. {val}")- if correct_answer:- block.append(f"Correct answer: {correct_answer}")- block.append(f"User answer: {user_answer or '(none)'}")- block.append(f"Judged: {judged}")- if explanation:- block.append(f"Explanation: {explanation}")- parts.append("\n".join(block))-- return "\n\n".join(parts)-- return "(unknown)"diff --git a/benchmark/tools/check_kbs.py b/benchmark/tools/check_kbs.pydeleted file mode 100644index aad6af1f2..000000000--- a/benchmark/tools/check_kbs.py+++ /dev/null@@ -1,494 +0,0 @@-#!/usr/bin/env python3-"""-Diagnose health of all knowledge bases.--Usage:- python3 -m benchmark.tools.check_kbs [--kb-dir data/knowledge_bases]-"""-from __future__ import annotations--import argparse-import asyncio-import json-import sys-import time-from pathlib import Path--_PROJECT_ROOT = Path(__file__).resolve().parents[2]-sys.path.insert(0, str(_PROJECT_ROOT))--CRITICAL_RAG_FILES = [- "kv_store_text_chunks.json",- "kv_store_full_docs.json",- "kv_store_full_entities.json",- "kv_store_full_relations.json",- "vdb_chunks.json",- "vdb_entities.json",- "vdb_relationships.json",- "graph_chunk_entity_relation.graphml",-]--OPTIONAL_RAG_FILES = [- "kv_store_doc_status.json",- "kv_store_llm_response_cache.json",- "kv_store_parse_cache.json",-]--ANSI_GREEN = "\033[92m"-ANSI_YELLOW = "\033[93m"-ANSI_RED = "\033[91m"-ANSI_DIM = "\033[2m"-ANSI_RESET = "\033[0m"-ANSI_BOLD = "\033[1m"---def _size_str(path: Path) -> str:- if not path.exists():- return "missing"- size = path.stat().st_size- if size == 0:- return f"{ANSI_RED}0 B (EMPTY){ANSI_RESET}"- for unit in ("B", "KB", "MB", "GB"):- if size < 1024:- return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"- size /= 1024- return f"{size:.1f} TB"---def _load_json(path: Path) -> dict | list | None:- try:- with open(path, encoding="utf-8") as f:- return json.load(f)- except Exception:- return None---def _check_doc_status(rag_dir: Path) -> tuple[int, int, int, list[str]]:- """Return (total, processed, failed, problem_docs)."""- status_file = rag_dir / "kv_store_doc_status.json"- data = _load_json(status_file)- if not data:- return 0, 0, 0, ["doc_status file missing or unreadable"]-- total = processed = failed = 0- problems: list[str] = []- for doc_id, doc in data.items():- if not isinstance(doc, dict):- continue- total += 1- status = doc.get("status")- if status == "processed":- processed += 1- elif status == "failed":- failed += 1- err = doc.get("error", "unknown error")- summary = doc.get("content_summary", doc_id)[:60]- problems.append(f"FAILED: {summary} — {err}")- elif status in ("processing", "pending"):- problems.append(f"{status.upper()}: {doc.get('content_summary', doc_id)[:60]}")- return total, processed, failed, problems---def _count_json_entries(path: Path) -> int | None:- data = _load_json(path)- if isinstance(data, dict):- return len(data)- if isinstance(data, list):- return len(data)- return None---def check_kb(kb_dir: Path, kb_config_entry: dict | None) -> dict:- """Check a single KB and return a report dict."""- report: dict = {"name": kb_dir.name, "issues": [], "warnings": [], "stats": {}}- issues = report["issues"]- warnings = report["warnings"]- stats = report["stats"]-- # --- metadata.json ---- meta_path = kb_dir / "metadata.json"- meta = _load_json(meta_path)- if not meta:- issues.append("metadata.json missing or unreadable")- else:- if not meta.get("rag_provider"):- issues.append("metadata.json: rag_provider is null (processing incomplete)")- if not meta.get("file_hashes"):- warnings.append("metadata.json: no file_hashes recorded")- stats["rag_provider"] = meta.get("rag_provider")- stats["created_at"] = meta.get("created_at")-- # --- kb_config status ---- if kb_config_entry:- cfg_status = kb_config_entry.get("status")- stats["config_status"] = cfg_status- progress = kb_config_entry.get("progress", {})- stats["config_stage"] = progress.get("stage")- if cfg_status == "error":- issues.append(f"kb_config status=error: {progress.get('error', '?')}")- elif cfg_status == "processing":- warnings.append(f"kb_config status=processing (stage={progress.get('stage')})")- else:- warnings.append("not registered in kb_config.json")-- # --- rag_storage directory ---- rag_dir = kb_dir / "rag_storage"- if not rag_dir.is_dir():- issues.append("rag_storage/ directory missing")- return report-- # Critical files- for fname in CRITICAL_RAG_FILES:- fpath = rag_dir / fname- if not fpath.exists():- issues.append(f"rag_storage/{fname} MISSING")- elif fpath.stat().st_size == 0:- issues.append(f"rag_storage/{fname} is EMPTY (0 bytes)")- else:- stats[fname] = _size_str(fpath)-- # doc_status- total, processed, failed, doc_problems = _check_doc_status(rag_dir)- stats["docs_total"] = total- stats["docs_processed"] = processed- stats["docs_failed"] = failed- if failed > 0:- issues.append(f"{failed}/{total} document(s) FAILED")- if total > 0 and processed < total and failed == 0:- pending = total - processed- warnings.append(f"{pending}/{total} document(s) still pending/processing")- for p in doc_problems:- if p.startswith("FAILED"):- issues.append(p)- else:- warnings.append(p)-- # Entity / relation / chunk counts- entities_count = _count_json_entries(rag_dir / "kv_store_full_entities.json")- relations_count = _count_json_entries(rag_dir / "kv_store_full_relations.json")- chunks_count = _count_json_entries(rag_dir / "kv_store_text_chunks.json")- stats["entities"] = entities_count- stats["relations"] = relations_count- stats["chunks"] = chunks_count-- if chunks_count is not None and chunks_count == 0:- issues.append("text_chunks is empty — no searchable content")- if entities_count is not None and entities_count == 0:- warnings.append("no entities extracted (knowledge graph empty)")-- # --- content_list ---- cl_dir = kb_dir / "content_list"- if cl_dir.is_dir():- cl_files = list(cl_dir.glob("*.json"))- stats["content_list_files"] = len(cl_files)- else:- warnings.append("content_list/ directory missing")-- # --- numbered_items ---- ni_path = kb_dir / "numbered_items.json"- if ni_path.exists():- ni_data = _load_json(ni_path)- stats["numbered_items"] = len(ni_data) if isinstance(ni_data, list) else "?"- else:- stats["numbered_items"] = None-- # --- raw documents ---- raw_dir = kb_dir / "raw"- if raw_dir.is_dir():- raw_files = [f for f in raw_dir.iterdir() if f.is_file()]- stats["raw_files"] = len(raw_files)- else:- warnings.append("raw/ directory missing")-- return report---def print_report(report: dict) -> str:- """Print a single KB report. Returns 'ok' | 'warn' | 'error'."""- name = report["name"]- issues = report["issues"]- warnings = report["warnings"]- stats = report["stats"]-- if issues:- icon = f"{ANSI_RED}✗{ANSI_RESET}"- status = "ERROR"- elif warnings:- icon = f"{ANSI_YELLOW}⚠{ANSI_RESET}"- status = "WARN"- else:- icon = f"{ANSI_GREEN}✓{ANSI_RESET}"- status = "OK"-- print(f"\n{icon} {ANSI_BOLD}{name}{ANSI_RESET}")-- # Stats line- parts = []- if stats.get("docs_total") is not None:- parts.append(f"docs={stats['docs_processed']}/{stats['docs_total']}")- if stats.get("chunks") is not None:- parts.append(f"chunks={stats['chunks']}")- if stats.get("entities") is not None:- parts.append(f"entities={stats['entities']}")- if stats.get("relations") is not None:- parts.append(f"relations={stats['relations']}")- if stats.get("numbered_items") is not None:- parts.append(f"numbered_items={stats['numbered_items']}")- elif stats.get("numbered_items") is None:- parts.append(f"numbered_items={ANSI_DIM}N/A{ANSI_RESET}")- if stats.get("config_status"):- parts.append(f"config={stats['config_status']}")- if parts:- print(f" {' | '.join(parts)}")-- # File sizes- rag_files_shown = [f for f in CRITICAL_RAG_FILES if f in stats]- if rag_files_shown:- sizes = [f"{f.replace('kv_store_', '').replace('.json', '').replace('.graphml', '')}={stats[f]}" for f in rag_files_shown]- print(f" {ANSI_DIM}{' | '.join(sizes)}{ANSI_RESET}")-- for w in warnings:- print(f" {ANSI_YELLOW}⚠ {w}{ANSI_RESET}")- for i in issues:- print(f" {ANSI_RED}✗ {i}{ANSI_RESET}")-- return "error" if issues else ("warn" if warnings else "ok")---_RAG_TOOL_SCRIPT = _PROJECT_ROOT / "src" / "tools" / "rag_tool.py"---async def _test_rag_query(kb_name: str, kb_base_dir: str, timeout: float = 60.0) -> tuple[bool, str]:- """Run rag_tool.py as a subprocess to test if a KB is queryable.-- Returns (success, message).- """- cmd = [- sys.executable,- str(_RAG_TOOL_SCRIPT),- "--kb-name", kb_name,- "--kb-base-dir", kb_base_dir,- "--query", "What is the main topic of this document?",- "--mode", "naive",- ]- t0 = time.monotonic()- try:- proc = await asyncio.create_subprocess_exec(- *cmd,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- cwd=str(_PROJECT_ROOT),- )- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)- elapsed = time.monotonic() - t0-- if proc.returncode != 0:- err_line = (stderr or stdout or b"").decode(errors="replace").strip().split("\n")[-1][:120]- return False, f"exit code {proc.returncode} ({elapsed:.1f}s): {err_line}"-- output = stdout.decode(errors="replace")- answer_lines: list[str] = []- capturing = False- for line in output.splitlines():- if line.startswith("Answer:"):- capturing = True- first = line[len("Answer:"):].strip()- if first:- answer_lines.append(first)- elif capturing:- answer_lines.append(line)-- if capturing:- answer = "\n".join(answer_lines).strip()- if not answer:- return False, f"empty answer ({elapsed:.1f}s)"- return True, f"ok ({elapsed:.1f}s)\n{answer}"-- return False, f"no Answer line in output ({elapsed:.1f}s)"- except asyncio.TimeoutError:- proc.kill()- await proc.wait()- return False, f"timeout (>{timeout:.0f}s)"- except Exception as e:- msg = str(e).split("\n")[0][:120]- return False, f"error: {msg}"---async def main():- import logging-- parser = argparse.ArgumentParser(description="Check health of all knowledge bases")- parser.add_argument(- "--kb-dir",- default="data/knowledge_bases",- help="Path to knowledge_bases directory (default: data/knowledge_bases)",- )- parser.add_argument(- "--no-rag",- action="store_true",- help="Skip live RAG query test (only run static checks).",- )- parser.add_argument(- "--rag-timeout",- type=float,- default=60.0,- help="Timeout in seconds for each RAG test query (default: 60).",- )- args = parser.parse_args()-- kb_base = Path(args.kb_dir)- if not kb_base.is_absolute():- kb_base = (_PROJECT_ROOT / kb_base).resolve()-- if not kb_base.is_dir():- print(f"Error: {kb_base} is not a directory", file=sys.stderr)- sys.exit(1)-- # Load kb_config.json- kb_config_path = kb_base / "kb_config.json"- kb_config: dict = {}- if kb_config_path.exists():- data = _load_json(kb_config_path)- if isinstance(data, dict):- kb_config = data.get("knowledge_bases", {})-- # Find all KB directories (has metadata.json OR rag_storage/)- kb_dirs = sorted(- d- for d in kb_base.iterdir()- if d.is_dir()- and (- (d / "metadata.json").exists()- or (d / "rag_storage").is_dir()- or d.name in kb_config- )- )-- if not kb_dirs:- print("No knowledge bases found.")- sys.exit(0)-- print(f"{ANSI_BOLD}Knowledge Base Health Check{ANSI_RESET}")- print(f"Directory: {kb_base}")- print(f"Found {len(kb_dirs)} KB(s), {len(kb_config)} registered in kb_config.json")-- # --- Phase 1: Static checks ---- print(f"\n{'=' * 60}")- print(f"{ANSI_BOLD}Phase 1: Static checks{ANSI_RESET}")- print(f"{'=' * 60}")-- groups: dict[str, list[str]] = {"ok": [], "warn": [], "error": []}- for kb_dir in kb_dirs:- cfg_entry = kb_config.get(kb_dir.name)- report = check_kb(kb_dir, cfg_entry)- result = print_report(report)- groups[result].append(kb_dir.name)-- for cfg_name in kb_config:- if not (kb_base / cfg_name).is_dir():- print(f"\n{ANSI_RED}✗ {ANSI_BOLD}{cfg_name}{ANSI_RESET}")- print(f" {ANSI_RED}✗ registered in kb_config.json but directory missing{ANSI_RESET}")- groups["error"].append(cfg_name)-- print(f"\n{'=' * 60}")- print(- f"Static: "- f"{ANSI_GREEN}{len(groups['ok'])} OK{ANSI_RESET} | "- f"{ANSI_YELLOW}{len(groups['warn'])} WARN{ANSI_RESET} | "- f"{ANSI_RED}{len(groups['error'])} ERROR{ANSI_RESET}"- )-- # --- Phase 2: Live RAG tests (all KBs, parallel) ---- all_kb_names = [d.name for d in kb_dirs]- if args.no_rag or not all_kb_names:- _print_final_summary(groups, rag_results=None)- sys.exit(1 if groups["error"] else 0)-- logging.disable(logging.CRITICAL)-- print(f"\n{'=' * 60}")- print(- f"{ANSI_BOLD}Phase 2: Live RAG query test{ANSI_RESET} "- f"({len(all_kb_names)} KBs, parallel, timeout={args.rag_timeout:.0f}s each)"- )- print(f"{'=' * 60}")-- async def _test_one(kb_name: str) -> tuple[str, bool, str]:- ok, msg = await _test_rag_query(kb_name, str(kb_base), timeout=args.rag_timeout)- return kb_name, ok, msg-- results = await asyncio.gather(*[_test_one(name) for name in all_kb_names])-- rag_pass: list[str] = []- rag_fail: list[str] = []- for kb_name, ok, msg in sorted(results, key=lambda r: r[0]):- if ok:- header, _, body = msg.partition("\n")- print(f" {ANSI_GREEN}✓{ANSI_RESET} {kb_name} {ANSI_DIM}{header}{ANSI_RESET}")- if body:- for line in body.splitlines():- print(f" {ANSI_DIM}{line}{ANSI_RESET}")- rag_pass.append(kb_name)- else:- print(f" {ANSI_RED}✗{ANSI_RESET} {kb_name} {msg}")- rag_fail.append(kb_name)-- logging.disable(logging.NOTSET)-- print(f"\n{'=' * 60}")- print(- f"RAG test: "- f"{ANSI_GREEN}{len(rag_pass)} PASS{ANSI_RESET} | "- f"{ANSI_RED}{len(rag_fail)} FAIL{ANSI_RESET}"- )-- _print_final_summary(groups, rag_results={"pass": rag_pass, "fail": rag_fail})- sys.exit(1 if groups["error"] else 0)---def _print_final_summary(- groups: dict[str, list[str]],- rag_results: dict[str, list[str]] | None,-) -> None:- """Print the combined final summary."""- print(f"\n{'=' * 60}")- total_ok = len(groups["ok"])- total_warn = len(groups["warn"])- total_err = len(groups["error"])- print(- f"{ANSI_BOLD}Final:{ANSI_RESET} "- f"{ANSI_GREEN}{total_ok} OK{ANSI_RESET} | "- f"{ANSI_YELLOW}{total_warn} WARN{ANSI_RESET} | "- f"{ANSI_RED}{total_err} ERROR{ANSI_RESET}"- )-- if rag_results:- rp = sorted(rag_results.get("pass", []))- rf = sorted(rag_results.get("fail", []))- if rp:- print(f"\n{ANSI_GREEN}{ANSI_BOLD}RAG OK ({len(rp)}):{ANSI_RESET}")- for name in rp:- print(f" {ANSI_GREEN}✓{ANSI_RESET} {name}")- if rf:- print(f"\n{ANSI_RED}{ANSI_BOLD}RAG FAIL ({len(rf)}):{ANSI_RESET}")- for name in rf:- print(f" {ANSI_RED}✗{ANSI_RESET} {name}")-- if groups["ok"]:- print(f"\n{ANSI_GREEN}Static OK ({len(groups['ok'])}):{ANSI_RESET}")- for name in sorted(groups["ok"]):- print(f" {ANSI_GREEN}✓{ANSI_RESET} {name}")-- if groups["warn"]:- print(f"\n{ANSI_YELLOW}Static WARN ({len(groups['warn'])}):{ANSI_RESET}")- for name in sorted(groups["warn"]):- print(f" {ANSI_YELLOW}⚠{ANSI_RESET} {name}")-- if groups["error"]:- print(f"\n{ANSI_RED}Static ERROR ({len(groups['error'])}):{ANSI_RESET}")- for name in sorted(groups["error"]):- print(f" {ANSI_RED}✗{ANSI_RESET} {name}")---if __name__ == "__main__":- asyncio.run(main())diff --git a/benchmark/tools/fix_image_paths_in_kb.py b/benchmark/tools/fix_image_paths_in_kb.pydeleted file mode 100644index 83fa4fcb7..000000000--- a/benchmark/tools/fix_image_paths_in_kb.py+++ /dev/null@@ -1,309 +0,0 @@-#!/usr/bin/env python3-"""-Repair stale image paths inside KB JSON artifacts.--Typical issue:- - Old paths point to content_list/.../auto/images/*.jpg (or docling/images)- - Files were migrated to kb/images/*.jpg, old parser dirs were cleaned- - Retrieval/evaluation logs: "Image file not found: .../content_list/.../auto/images/..."--This script rewrites stale image paths in:- - content_list/*.json- - rag_storage/*.json--Usage:- python -m benchmark.tools.fix_image_paths_in_kb --kb-dir data/knowledge_bases --dry-run- python -m benchmark.tools.fix_image_paths_in_kb --kb-dir data/knowledge_bases --kb-name my_kb-"""--from __future__ import annotations--import argparse-import json-import re-import shutil-import sys-import time-from dataclasses import dataclass-from datetime import datetime-from pathlib import Path-from typing import Any--_PROJECT_ROOT = Path(__file__).resolve().parents[2]--ANSI_GREEN = "\033[92m"-ANSI_YELLOW = "\033[93m"-ANSI_RED = "\033[91m"-ANSI_DIM = "\033[2m"-ANSI_RESET = "\033[0m"-ANSI_BOLD = "\033[1m"--TARGET_SUBDIRS = ("auto/images", "docling/images", "content_list")-IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp")-_TARGET_HINTS_LOWER = tuple(x.lower() for x in TARGET_SUBDIRS)-_STALE_IMAGE_PATH_RE = re.compile(- r'([^\s"\'<>]*?(?:content_list|auto/images|docling/images)[^\s"\'<>]*?'- r'(?:\.png|\.jpg|\.jpeg|\.webp|\.gif|\.bmp))',- flags=re.IGNORECASE,-)---@dataclass-class FileFixResult:- path: Path- scanned_strings: int = 0- replaced_strings: int = 0- changed: bool = False- error: str | None = None---def _load_json(path: Path) -> Any:- with open(path, encoding="utf-8") as f:- return json.load(f)---def _dump_json(path: Path, data: Any) -> None:- with open(path, "w", encoding="utf-8") as f:- json.dump(data, f, ensure_ascii=False, indent=2)---def _looks_like_stale_path(value: str) -> bool:- v = value.replace("\\", "/")- return any(token in v for token in TARGET_SUBDIRS)---def _rewrite_embedded_paths(value: str, images_dir: Path, stats: dict[str, int]) -> str:- """- Rewrite stale image paths embedded inside longer strings.-- Example:- "Image Path: /.../content_list/.../auto/images/abc.jpg"- -> "Image Path: /.../knowledge_bases/<kb>/images/abc.jpg"- """- # Fast-path: skip regex for most strings.- lower = value.lower()- if not any(h in lower for h in _TARGET_HINTS_LOWER):- return value-- def _replace(match: re.Match[str]) -> str:- old = match.group(1)- basename = Path(old).name- if not basename:- return old- candidate = images_dir / basename- if candidate.exists():- stats["replaced"] += 1- return str(candidate.resolve())- return old-- return _STALE_IMAGE_PATH_RE.sub(_replace, value)---def _maybe_rewrite_path(value: str, images_dir: Path, stats: dict[str, int]) -> str:- """Return rewritten path if stale and basename exists in kb/images."""- if not isinstance(value, str):- return value-- # 1) Embedded path inside longer text- rewritten = _rewrite_embedded_paths(value, images_dir, stats)- if rewritten != value:- return rewritten-- # 2) Whole-string path rewrite- if _looks_like_stale_path(value):- basename = Path(value).name- if basename:- candidate = images_dir / basename- if candidate.exists():- stats["replaced"] += 1- return str(candidate.resolve())- return value---def _rewrite_obj(obj: Any, images_dir: Path, stats: dict[str, int]) -> Any:- if isinstance(obj, dict):- return {k: _rewrite_obj(v, images_dir, stats) for k, v in obj.items()}- if isinstance(obj, list):- return [_rewrite_obj(x, images_dir, stats) for x in obj]- if isinstance(obj, str):- stats["scanned"] += 1- return _maybe_rewrite_path(obj, images_dir, stats)- return obj---def _backup_file(path: Path) -> Path:- ts = datetime.now().strftime("%Y%m%d_%H%M%S")- backup = path.with_suffix(path.suffix + f".bak.{ts}")- shutil.copy2(path, backup)- return backup---def _fix_one_json(path: Path, images_dir: Path, dry_run: bool, backup: bool) -> FileFixResult:- result = FileFixResult(path=path)- try:- original = _load_json(path)- stats = {"scanned": 0, "replaced": 0}- updated = _rewrite_obj(original, images_dir, stats)- result.scanned_strings = stats["scanned"]- result.replaced_strings = stats["replaced"]- result.changed = stats["replaced"] > 0-- if result.changed and not dry_run:- if backup:- _backup_file(path)- _dump_json(path, updated)- return result- except Exception as e:- result.error = str(e)- return result---def _collect_target_jsons(kb_dir: Path) -> list[Path]:- targets: list[Path] = []- cl_dir = kb_dir / "content_list"- rag_dir = kb_dir / "rag_storage"- if cl_dir.is_dir():- targets.extend(sorted(cl_dir.glob("**/*.json")))- if rag_dir.is_dir():- targets.extend(sorted(rag_dir.glob("**/*.json")))- # Deduplicate while preserving order- seen = set()- unique_targets: list[Path] = []- for p in targets:- sp = str(p.resolve())- if sp in seen:- continue- seen.add(sp)- unique_targets.append(p)- return unique_targets---def _iter_kb_dirs(base: Path, kb_filter: set[str] | None) -> list[Path]:- dirs = [d for d in sorted(base.iterdir()) if d.is_dir() and d.name != "manifests"]- if kb_filter:- dirs = [d for d in dirs if d.name in kb_filter]- return dirs---def main() -> None:- parser = argparse.ArgumentParser(description="Fix stale image paths in KB JSON artifacts.")- parser.add_argument(- "--kb-dir",- default="data/knowledge_bases",- help="Path to knowledge_bases directory (default: data/knowledge_bases)",- )- parser.add_argument(- "--kb-name",- default="",- help="Optional comma-separated KB names to process (default: all).",- )- parser.add_argument("--dry-run", action="store_true", help="Preview changes without writing.")- parser.add_argument(- "--no-backup",- action="store_true",- help="Do not create .bak timestamped backups before writing.",- )- parser.add_argument(- "--clear-llm-cache",- action="store_true",- help="Also clear rag_storage/kv_store_llm_response_cache.json after rewriting.",- )- args = parser.parse_args()-- kb_base = Path(args.kb_dir)- if not kb_base.is_absolute():- kb_base = (_PROJECT_ROOT / kb_base).resolve()- if not kb_base.is_dir():- print(f"{ANSI_RED}Error: {kb_base} is not a directory{ANSI_RESET}", file=sys.stderr)- sys.exit(1)-- kb_filter = {x.strip() for x in args.kb_name.split(",") if x.strip()} or None- kb_dirs = _iter_kb_dirs(kb_base, kb_filter)- if not kb_dirs:- print(f"{ANSI_YELLOW}No KB directories found to process.{ANSI_RESET}")- sys.exit(0)-- print(f"KB dir: {kb_base}")- print(f"Mode: {'DRY-RUN' if args.dry_run else 'WRITE'}")- print(f"Backup: {not args.no_backup}")- print(f"KB count: {len(kb_dirs)}\n")-- total_files = total_changed = total_replaced = total_errors = 0-- for kb_dir in kb_dirs:- images_dir = kb_dir / "images"- targets = _collect_target_jsons(kb_dir)- print(f"{ANSI_BOLD}{kb_dir.name}{ANSI_RESET} ({len(targets)} json files)")- if not images_dir.is_dir():- print(f" {ANSI_YELLOW}⚠ images/ missing, skipping{ANSI_RESET}")- continue-- kb_changed = kb_replaced = kb_errors = 0- for idx, path in enumerate(targets, start=1):- print(f" {ANSI_DIM}→ [{idx}/{len(targets)}] scanning {path.name}{ANSI_RESET}")- started = time.time()- r = _fix_one_json(- path=path,- images_dir=images_dir,- dry_run=args.dry_run,- backup=not args.no_backup,- )- elapsed = time.time() - started- total_files += 1- if r.error:- kb_errors += 1- total_errors += 1- print(f" {ANSI_RED}✗{ANSI_RESET} {path.name}: {r.error} ({elapsed:.1f}s)")- continue- if r.changed:- kb_changed += 1- kb_replaced += r.replaced_strings- total_changed += 1- total_replaced += r.replaced_strings- print(- f" {ANSI_GREEN}✓{ANSI_RESET} {path.name}: replaced {r.replaced_strings}"- f" {ANSI_DIM}(scanned={r.scanned_strings}, {elapsed:.1f}s){ANSI_RESET}"- )- else:- print(f" {ANSI_DIM}- {path.name}: no change ({elapsed:.1f}s){ANSI_RESET}")-- if kb_changed == 0 and kb_errors == 0:- print(f" {ANSI_DIM}- no stale paths rewritten{ANSI_RESET}")- else:- msg = (- f" changed_files={kb_changed}, replaced_paths={kb_replaced}, errors={kb_errors}"- )- print(f" {msg}")-- if args.clear_llm_cache:- cache_path = kb_dir / "rag_storage" / "kv_store_llm_response_cache.json"- if cache_path.exists():- if args.dry_run:- print(f" {ANSI_YELLOW}~{ANSI_RESET} would clear cache: {cache_path.name}")- else:- try:- if not args.no_backup:- _backup_file(cache_path)- _dump_json(cache_path, {})- print(f" {ANSI_GREEN}✓{ANSI_RESET} cleared cache: {cache_path.name}")- except Exception as e:- total_errors += 1- print(f" {ANSI_RED}✗{ANSI_RESET} clear cache failed: {e}")- print()-- print("=" * 72)- print(- f"Scanned files: {total_files} | Changed files: {total_changed} | "- f"Replaced paths: {total_replaced} | Errors: {total_errors}"- )- if args.dry_run:- print(f"{ANSI_YELLOW}[DRY-RUN] No files were modified.{ANSI_RESET}")- elif total_changed > 0:- print(f"{ANSI_GREEN}Done. Rewrites applied.{ANSI_RESET}")- else:- print("Done. Nothing to rewrite.")---if __name__ == "__main__":- main()-diff --git a/benchmark/tools/fix_kb_config.py b/benchmark/tools/fix_kb_config.pydeleted file mode 100644index c1c855368..000000000--- a/benchmark/tools/fix_kb_config.py+++ /dev/null@@ -1,217 +0,0 @@-#!/usr/bin/env python3-"""-Fix kb_config.json status for KBs whose RAG storage is actually complete.--Scans all KB directories, checks if RAG files are intact, and updates-kb_config.json entries from "processing"/"error" to "ready" when appropriate.--Usage:- python3 -m benchmark.tools.fix_kb_config [--kb-dir data/knowledge_bases] [--dry-run]-"""-from __future__ import annotations--import argparse-import json-import sys-from datetime import datetime-from pathlib import Path--_PROJECT_ROOT = Path(__file__).resolve().parents[2]--CRITICAL_RAG_FILES = [- "kv_store_text_chunks.json",- "kv_store_full_docs.json",- "kv_store_full_entities.json",- "kv_store_full_relations.json",- "vdb_chunks.json",- "vdb_entities.json",- "vdb_relationships.json",- "graph_chunk_entity_relation.graphml",-]--ANSI_GREEN = "\033[92m"-ANSI_YELLOW = "\033[93m"-ANSI_RED = "\033[91m"-ANSI_DIM = "\033[2m"-ANSI_RESET = "\033[0m"-ANSI_BOLD = "\033[1m"---def _is_rag_healthy(kb_dir: Path) -> tuple[bool, str]:- """Check if a KB's RAG storage is complete and healthy.-- Returns (healthy, reason).- """- rag_dir = kb_dir / "rag_storage"- if not rag_dir.is_dir():- return False, "rag_storage/ missing"-- for fname in CRITICAL_RAG_FILES:- fpath = rag_dir / fname- if not fpath.exists():- return False, f"{fname} missing"- if fpath.stat().st_size == 0:- return False, f"{fname} empty"-- status_path = rag_dir / "kv_store_doc_status.json"- if status_path.exists():- try:- with open(status_path, encoding="utf-8") as f:- doc_status = json.load(f)- for doc_id, doc in doc_status.items():- if isinstance(doc, dict) and doc.get("status") == "failed":- return False, f"doc '{doc_id[:40]}' status=failed"- except Exception as e:- return False, f"doc_status unreadable: {e}"-- chunks_path = rag_dir / "kv_store_text_chunks.json"- try:- with open(chunks_path, encoding="utf-8") as f:- chunks = json.load(f)- if isinstance(chunks, dict) and len(chunks) == 0:- return False, "text_chunks empty (0 entries)"- except Exception:- return False, "text_chunks unreadable"-- meta_path = kb_dir / "metadata.json"- if meta_path.exists():- try:- with open(meta_path, encoding="utf-8") as f:- meta = json.load(f)- if not meta.get("rag_provider"):- return False, "metadata.json: rag_provider is null"- except Exception:- pass-- return True, "ok"---def main():- parser = argparse.ArgumentParser(- description="Fix kb_config.json status for KBs with healthy RAG storage"- )- parser.add_argument(- "--kb-dir",- default="data/knowledge_bases",- help="Path to knowledge_bases directory (default: data/knowledge_bases)",- )- parser.add_argument(- "--dry-run",- action="store_true",- help="Show what would be fixed without actually writing changes.",- )- args = parser.parse_args()-- kb_base = Path(args.kb_dir)- if not kb_base.is_absolute():- kb_base = (_PROJECT_ROOT / kb_base).resolve()-- if not kb_base.is_dir():- print(f"Error: {kb_base} is not a directory", file=sys.stderr)- sys.exit(1)-- config_path = kb_base / "kb_config.json"- if not config_path.exists():- print(f"Error: {config_path} not found", file=sys.stderr)- sys.exit(1)-- with open(config_path, encoding="utf-8") as f:- config = json.load(f)-- kbs = config.get("knowledge_bases", {})- if not kbs:- print("No knowledge bases in config.")- sys.exit(0)-- kb_dirs = sorted(- d for d in kb_base.iterdir()- if d.is_dir() and (d / "rag_storage").is_dir()- )-- fixed: list[str] = []- skipped_ok: list[str] = []- skipped_bad: list[str] = []- registered: list[str] = []-- for kb_dir in kb_dirs:- name = kb_dir.name- entry = kbs.get(name)- status = entry.get("status") if entry else None-- if status == "ready":- skipped_ok.append(name)- continue-- healthy, reason = _is_rag_healthy(kb_dir)-- if not healthy:- label = f"status={status}" if status else "not in config"- print(f" {ANSI_RED}✗{ANSI_RESET} {name} {ANSI_DIM}({label}, unhealthy: {reason}){ANSI_RESET}")- skipped_bad.append(name)- continue-- if not entry:- now = datetime.now().isoformat()- kbs[name] = {- "path": name,- "description": f"Knowledge base: {name}",- "status": "ready",- "updated_at": now,- "progress": {- "stage": "completed",- "message": "Fixed by fix_kb_config",- "percent": 100,- "current": 1,- "total": 1,- "file_name": "",- "error": None,- "timestamp": now,- },- }- action = "REGISTER + FIX"- registered.append(name)- else:- old_status = entry.get("status", "?")- entry["status"] = "ready"- entry["updated_at"] = datetime.now().isoformat()- entry.setdefault("progress", {})["stage"] = "completed"- entry["progress"]["message"] = f"Fixed by fix_kb_config (was: {old_status})"- entry["progress"]["error"] = None- action = f"{old_status} → ready"-- print(f" {ANSI_GREEN}✓{ANSI_RESET} {name} {ANSI_BOLD}{action}{ANSI_RESET}")- fixed.append(name)-- print(f"\n{'=' * 60}")- print(- f"Result: "- f"{ANSI_GREEN}{len(fixed)} fixed{ANSI_RESET} | "- f"{len(skipped_ok)} already ready | "- f"{ANSI_RED}{len(skipped_bad)} unhealthy (skipped){ANSI_RESET}"- )-- if fixed:- print(f"\n{ANSI_GREEN}{ANSI_BOLD}Fixed ({len(fixed)}):{ANSI_RESET}")- for name in fixed:- print(f" {ANSI_GREEN}✓{ANSI_RESET} {name}")-- if skipped_bad:- print(f"\n{ANSI_RED}Unhealthy — not fixed ({len(skipped_bad)}):{ANSI_RESET}")- for name in skipped_bad:- print(f" {ANSI_RED}✗{ANSI_RESET} {name}")-- if not fixed:- print("\nNothing to fix.")- sys.exit(0)-- if args.dry_run:- print(f"\n{ANSI_YELLOW}[DRY RUN] No changes written.{ANSI_RESET}")- else:- config["knowledge_bases"] = kbs- with open(config_path, "w", encoding="utf-8") as f:- json.dump(config, f, ensure_ascii=False, indent=2)- print(f"\n{ANSI_GREEN}Saved: {config_path}{ANSI_RESET}")---if __name__ == "__main__":- main()diff --git a/tests/iso_solve/__init__.py b/tests/iso_solve/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/tests/iso_solve/test_evaluation.py b/tests/iso_solve/test_evaluation.pydeleted file mode 100644index e5aab056b..000000000--- a/tests/iso_solve/test_evaluation.py+++ /dev/null@@ -1,983 +0,0 @@-"""-Comprehensive tests for the iso_solve benchmark evaluation pipeline.--Covers:- - LLM capabilities (response_format, binding, model overrides) with OpenRouter scenarios- - BaseAgent.call_llm() binding propagation and response_format handling- - BenchmarkRunner: direct mode, pipeline mode, error handling- - Answer extractor: normal, edge cases, LLM failure fallback- - Answer judge: correct, incorrect, ambiguous, fallback- - BenchmarkReport: aggregation, breakdowns, accuracy- - BenchmarkAdapter: request building, extract/judge fallbacks- - Pipeline call: solver integration--Run:- pytest tests/iso_solve/test_evaluation.py -v-"""--from __future__ import annotations--import argparse-import json-from typing import Any-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from benchmark.iso_solve.core.types import BenchmarkReport, EvalResult, Problem--# ----------------------------------------------------------------------------# Fixtures-# -----------------------------------------------------------------------------def _make_problem(**overrides: Any) -> Problem:- defaults = dict(- id="p001",- question="What is 2+2?",- ground_truth="4",- benchmark="test",- system_prompt="You are a math tutor.",- metadata={"level": "easy", "subject": "Algebra"},- )- defaults.update(overrides)- return Problem(**defaults)---def _make_result(correct: bool = True, error: str | None = None, **kw: Any) -> EvalResult:- prob = kw.pop("problem", _make_problem())- return EvalResult(- problem=prob,- model_output=kw.get("model_output", "The answer is 4"),- extracted_answer=kw.get("extracted_answer", "4"),- correct=correct,- score=1.0 if correct else 0.0,- elapsed_sec=kw.get("elapsed_sec", 1.5),- judge_reasoning=kw.get("judge_reasoning", "CORRECT"),- error=error,- )---# ===================================================================-# 1. LLM Capabilities — OpenRouter / proxy model scenarios-# ===================================================================--class TestCapabilitiesOpenRouter:- """Verify response_format and system_in_messages work correctly- for Claude/Anthropic models routed through OpenRouter (binding=openai)."""-- def test_openrouter_claude_supports_response_format(self) -> None:- from src.services.llm.capabilities import supports_response_format-- assert supports_response_format("openai", "anthropic/claude-sonnet-4.5") is True-- def test_openrouter_claude_system_in_messages(self) -> None:- from src.services.llm.capabilities import system_in_messages-- assert system_in_messages("openai", "anthropic/claude-sonnet-4.5") is True-- def test_openrouter_claude_short_name(self) -> None:- from src.services.llm.capabilities import supports_response_format-- assert supports_response_format("openai", "claude-3-5-sonnet-20241022") is True-- def test_native_anthropic_no_response_format(self) -> None:- from src.services.llm.capabilities import supports_response_format-- assert supports_response_format("anthropic", "claude-sonnet-4.5") is False- assert supports_response_format("claude", "claude-3-5-sonnet") is False-- def test_native_anthropic_system_not_in_messages(self) -> None:- from src.services.llm.capabilities import system_in_messages-- assert system_in_messages("anthropic", "claude-sonnet-4.5") is False-- def test_deepseek_via_openai_no_response_format(self) -> None:- from src.services.llm.capabilities import supports_response_format-- assert supports_response_format("openai", "deepseek-reasoner") is False- assert supports_response_format("openai", "deepseek-chat") is False-- def test_openrouter_binding_supports_response_format(self) -> None:- from src.services.llm.capabilities import supports_response_format-- assert supports_response_format("openrouter", "anthropic/claude-sonnet-4.5") is True-- def test_reasoning_model_forced_temperature(self) -> None:- from src.services.llm.capabilities import get_effective_temperature-- assert get_effective_temperature("openai", "gpt-5-mini", 0.5) == 1.0- assert get_effective_temperature("openai", "o3-mini", 0.0) == 1.0- assert get_effective_temperature("openai", "gpt-4o", 0.4) == 0.4-- def test_thinking_tags_deepseek(self) -> None:- from src.services.llm.capabilities import has_thinking_tags-- assert has_thinking_tags("openai", "deepseek-reasoner") is True- assert has_thinking_tags("openai", "qwq-32b") is True- assert has_thinking_tags("openai", "anthropic/claude-sonnet-4.5") is False-- def test_token_limit_kwargs_newer_models(self) -> None:- from src.services.llm.config import get_token_limit_kwargs-- assert get_token_limit_kwargs("gpt-4o", 4096) == {"max_completion_tokens": 4096}- assert get_token_limit_kwargs("o3-mini", 8192) == {"max_completion_tokens": 8192}- assert get_token_limit_kwargs("gpt-5-mini", 4096) == {"max_completion_tokens": 4096}-- def test_token_limit_kwargs_anthropic_model(self) -> None:- from src.services.llm.config import get_token_limit_kwargs-- assert get_token_limit_kwargs("anthropic/claude-sonnet-4.5", 4096) == {"max_tokens": 4096}- assert get_token_limit_kwargs("claude-3-5-sonnet", 8192) == {"max_tokens": 8192}---# ===================================================================-# 2. BaseAgent — binding propagation and response_format-# ===================================================================--class TestBaseAgentCallLLM:- """Test that BaseAgent.call_llm() correctly propagates binding- and handles response_format for various provider configurations."""-- @pytest.mark.asyncio- async def test_call_llm_passes_binding_to_factory(self) -> None:- from src.agents.base_agent import BaseAgent-- class _TestAgent(BaseAgent):- async def process(self, *args: Any, **kwargs: Any) -> Any:- return None-- with patch("src.agents.base_agent.get_llm_config") as mock_cfg, \- patch("src.agents.base_agent.llm_complete", new_callable=AsyncMock) as mock_llm:- mock_cfg.return_value = MagicMock(- api_key="test-key", base_url="https://openrouter.ai/api/v1",- model="anthropic/claude-sonnet-4.5", binding="openai",- api_version=None,- )- mock_llm.return_value = "test response"-- agent = _TestAgent(- module_name="solve", agent_name="test_agent",- api_key="key", base_url="https://openrouter.ai/api/v1",- model="anthropic/claude-sonnet-4.5",- )-- await agent.call_llm(- user_prompt="hello", system_prompt="you are helpful",- )-- call_kwargs = mock_llm.call_args- assert call_kwargs.kwargs.get("binding") == "openai"-- @pytest.mark.asyncio- async def test_call_llm_includes_response_format_for_openrouter_claude(self) -> None:- from src.agents.base_agent import BaseAgent-- class _TestAgent(BaseAgent):- async def process(self, *args: Any, **kwargs: Any) -> Any:- return None-- with patch("src.agents.base_agent.get_llm_config") as mock_cfg, \- patch("src.agents.base_agent.llm_complete", new_callable=AsyncMock) as mock_llm:- mock_cfg.return_value = MagicMock(- api_key="key", base_url="https://openrouter.ai/api/v1",- model="anthropic/claude-sonnet-4.5", binding="openai",- api_version=None,- )- mock_llm.return_value = '{"analysis": "test", "steps": []}'-- agent = _TestAgent(- module_name="solve", agent_name="test_agent",- api_key="key", base_url="https://openrouter.ai/api/v1",- model="anthropic/claude-sonnet-4.5",- )-- await agent.call_llm(- user_prompt="plan this",- system_prompt="you are a planner",- response_format={"type": "json_object"},- )-- call_kwargs = mock_llm.call_args- assert "response_format" in call_kwargs.kwargs- assert call_kwargs.kwargs["response_format"] == {"type": "json_object"}-- @pytest.mark.asyncio- async def test_call_llm_skips_response_format_for_native_anthropic(self) -> None:- from src.agents.base_agent import BaseAgent-- class _TestAgent(BaseAgent):- async def process(self, *args: Any, **kwargs: Any) -> Any:- return None-- with patch("src.agents.base_agent.get_llm_config") as mock_cfg, \- patch("src.agents.base_agent.llm_complete", new_callable=AsyncMock) as mock_llm:- mock_cfg.return_value = MagicMock(- api_key="key", base_url="https://api.anthropic.com/v1",- model="claude-sonnet-4.5", binding="anthropic",- api_version=None,- )- mock_llm.return_value = '{"result": "ok"}'-- agent = _TestAgent(- module_name="solve", agent_name="test_agent",- api_key="key", base_url="https://api.anthropic.com/v1",- model="claude-sonnet-4.5", binding="anthropic",- )-- await agent.call_llm(- user_prompt="plan this",- system_prompt="you are a planner",- response_format={"type": "json_object"},- )-- call_kwargs = mock_llm.call_args- assert "response_format" not in call_kwargs.kwargs---# ===================================================================-# 3. Answer Extractor-# ===================================================================--class TestExtractor:- """extractor.py uses `from src.services.llm import complete` inside the- function body, so we must mock at the source: ``src.services.llm.complete``."""-- _PATCH = "src.services.llm.complete"-- @pytest.mark.asyncio- async def test_extract_clean_answer(self) -> None:- from benchmark.iso_solve.core.extractor import extract_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = "42"- ans = await extract_answer("What is 6*7?", "Let me think... 6*7 = 42.")- assert ans == "42"-- @pytest.mark.asyncio- async def test_extract_strips_answer_prefix(self) -> None:- from benchmark.iso_solve.core.extractor import extract_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = "Answer: 42"- ans = await extract_answer("Q", "output")- assert ans == "42"-- @pytest.mark.asyncio- async def test_extract_multiline_takes_first(self) -> None:- from benchmark.iso_solve.core.extractor import extract_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = "42\nI'm confident about this."- ans = await extract_answer("Q", "output")- assert ans == "42"-- @pytest.mark.asyncio- async def test_extract_none_response(self) -> None:- from benchmark.iso_solve.core.extractor import extract_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = "NONE"- ans = await extract_answer("Q", "I don't know")- assert ans is None-- @pytest.mark.asyncio- async def test_extract_empty_response(self) -> None:- from benchmark.iso_solve.core.extractor import extract_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = " "- ans = await extract_answer("Q", "output")- assert ans is None-- @pytest.mark.asyncio- async def test_extract_llm_failure_returns_none(self) -> None:- from benchmark.iso_solve.core.extractor import extract_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.side_effect = RuntimeError("API timeout")- ans = await extract_answer("Q", "output")- assert ans is None-- @pytest.mark.asyncio- async def test_extract_truncates_long_output(self) -> None:- from benchmark.iso_solve.core.extractor import extract_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = "42"- long_output = "x" * 100_000- await extract_answer("Q", long_output, max_tokens=256)- prompt_arg = mock.call_args.kwargs["prompt"]- assert "...(truncated)" in prompt_arg---# ===================================================================-# 4. Answer Judge-# ===================================================================--class TestJudge:- """judge.py uses `from src.services.llm import complete` inside the- function body, so we must mock at the source."""-- _PATCH = "src.services.llm.complete"-- @pytest.mark.asyncio- async def test_judge_correct(self) -> None:- from benchmark.iso_solve.core.judge import judge_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = "CORRECT"- correct, reasoning = await judge_answer("Q", "4", "4")- assert correct is True- assert "CORRECT" in reasoning-- @pytest.mark.asyncio- async def test_judge_incorrect(self) -> None:- from benchmark.iso_solve.core.judge import judge_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = "INCORRECT"- correct, reasoning = await judge_answer("Q", "5", "4")- assert correct is False-- @pytest.mark.asyncio- async def test_judge_ambiguous_falls_back_to_string_match(self) -> None:- from benchmark.iso_solve.core.judge import judge_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = "I think it might be right?"- correct, reasoning = await judge_answer("Q", "4", "4")- assert correct is True- assert "Ambiguous" in reasoning-- @pytest.mark.asyncio- async def test_judge_ambiguous_no_match(self) -> None:- from benchmark.iso_solve.core.judge import judge_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = "Hmm, unsure"- correct, reasoning = await judge_answer("Q", "5", "4")- assert correct is False-- @pytest.mark.asyncio- async def test_judge_none_predicted(self) -> None:- from benchmark.iso_solve.core.judge import judge_answer-- correct, reasoning = await judge_answer("Q", None, "4")- assert correct is False- assert "No extracted answer" in reasoning-- @pytest.mark.asyncio- async def test_judge_llm_failure_falls_back(self) -> None:- from benchmark.iso_solve.core.judge import judge_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.side_effect = RuntimeError("API error")- correct, reasoning = await judge_answer("Q", "4", "4")- assert correct is True- assert "Judge failed" in reasoning-- @pytest.mark.asyncio- async def test_judge_with_hint(self) -> None:- from benchmark.iso_solve.core.judge import judge_answer-- with patch(self._PATCH, new_callable=AsyncMock) as mock:- mock.return_value = "CORRECT"- await judge_answer("Q", "4", "4", judge_hint="Compare numerically.")- prompt = mock.call_args.kwargs["prompt"]- assert "Compare numerically" in prompt---# ===================================================================-# 5. BenchmarkReport — aggregation, breakdowns, accuracy-# ===================================================================--class TestBenchmarkReport:- def test_empty_report(self) -> None:- r = BenchmarkReport("test", "direct", "model", "20260101")- assert r.total == 0- assert r.accuracy == 0.0- assert r.accuracy_pct == 0.0- assert r.confidence_interval == 0.0-- def test_add_correct_result(self) -> None:- r = BenchmarkReport("test", "direct", "model", "20260101")- r.add(_make_result(correct=True), ["level", "subject"])- assert r.total == 1- assert r.correct == 1- assert r.accuracy_pct == 100.0-- def test_add_incorrect_result(self) -> None:- r = BenchmarkReport("test", "direct", "model", "20260101")- r.add(_make_result(correct=False), [])- assert r.total == 1- assert r.correct == 0- assert r.accuracy_pct == 0.0-- def test_add_error_result_not_counted_as_correct(self) -> None:- r = BenchmarkReport("test", "direct", "model", "20260101")- r.add(_make_result(correct=False, error="timeout"), [])- assert r.total == 1- assert r.errors == 1- assert r.correct == 0-- def test_breakdowns_by_metadata(self) -> None:- r = BenchmarkReport("test", "direct", "model", "20260101")- r.add(_make_result(correct=True), ["level", "subject"])- r.add(- _make_result(- correct=False,- problem=_make_problem(metadata={"level": "hard", "subject": "Geometry"}),- ),- ["level", "subject"],- )-- assert "by_level" in r.breakdowns- assert r.breakdowns["by_level"]["easy"]["total"] == 1- assert r.breakdowns["by_level"]["easy"]["correct"] == 1- assert r.breakdowns["by_level"]["hard"]["total"] == 1- assert r.breakdowns["by_level"]["hard"]["correct"] == 0-- assert "by_subject" in r.breakdowns- assert r.breakdowns["by_subject"]["Algebra"]["correct"] == 1- assert r.breakdowns["by_subject"]["Geometry"]["correct"] == 0-- def test_mixed_results_accuracy(self) -> None:- r = BenchmarkReport("test", "direct", "model", "20260101")- for i in range(10):- r.add(_make_result(correct=(i < 7)), [])- assert r.total == 10- assert r.correct == 7- assert r.accuracy_pct == 70.0-- def test_summary_lines(self) -> None:- r = BenchmarkReport("test", "direct", "model-x", "20260101")- r.add(_make_result(correct=True), ["level"])- lines = r.summary_lines()- text = "\n".join(lines)- assert "model-x" in text- assert "direct" in text- assert "100.0%" in text-- def test_to_dict_structure(self) -> None:- r = BenchmarkReport("test", "pipeline", "model", "20260101")- r.add(_make_result(correct=True), ["level"])- d = r.to_dict()- assert d["benchmark"] == "test"- assert d["mode"] == "pipeline"- assert d["overall"]["total"] == 1- assert d["overall"]["correct"] == 1- assert len(d["results"]) == 1- assert d["results"][0]["correct"] is True-- def test_confidence_interval(self) -> None:- r = BenchmarkReport("test", "direct", "model", "20260101")- for i in range(100):- r.add(_make_result(correct=(i < 70)), [])- ci = r.confidence_interval- assert ci > 0- assert ci < 20---# ===================================================================-# 6. BenchmarkAdapter — request building and fallbacks-# ===================================================================--class TestBenchmarkAdapter:- def _make_adapter(self) -> Any:- from benchmark.iso_solve.eval.base import BenchmarkAdapter-- class _Stub(BenchmarkAdapter):- name = "stub"- def load_dataset(self, *a: Any, **kw: Any) -> list: return []- def filter_problems(self, problems: list, *a: Any, **kw: Any) -> list: return problems-- return _Stub()-- def test_default_build_direct_request(self) -> None:- adapter = self._make_adapter()- prob = _make_problem()- req = adapter.build_direct_request(prob)- assert "messages" in req- assert req["messages"][0]["role"] == "system"- assert req["messages"][1]["role"] == "user"-- def test_default_build_pipeline_request(self) -> None:- adapter = self._make_adapter()- prob = _make_problem()- req = adapter.build_pipeline_request(prob)- assert req["prompt"] == prob.question- assert req["image_url"] is None-- def test_extract_fallback(self) -> None:- adapter = self._make_adapter()- assert adapter.extract_fallback(" 42 ") == "42"- assert adapter.extract_fallback("") is None- assert adapter.extract_fallback(" ") is None-- def test_judge_fallback_exact_match(self) -> None:- adapter = self._make_adapter()- prob = _make_problem(ground_truth="Paris")- assert adapter.judge_fallback(prob, "Paris")[0] is True- assert adapter.judge_fallback(prob, "paris")[0] is True- assert adapter.judge_fallback(prob, "London")[0] is False- assert adapter.judge_fallback(prob, None)[0] is False---# ===================================================================-# 7. BenchmarkRunner — direct mode (mocked LLM)-# ===================================================================--def _make_stub_adapter(problems: list[Problem] | None = None) -> Any:- from benchmark.iso_solve.eval.base import BenchmarkAdapter-- class _StubAdapter(BenchmarkAdapter):- name = "stub"- breakdown_keys = ["level"]-- def load_dataset(self, bench_cfg: dict, args: Any) -> list[Problem]:- if problems is not None:- return list(problems)- return [- _make_problem(id="p1", question="2+2?", ground_truth="4"),- _make_problem(id="p2", question="3+3?", ground_truth="6"),- ]-- def filter_problems(self, probs: list, bench_cfg: dict, args: Any) -> list:- return probs-- return _StubAdapter()---class TestRunnerDirectMode:-- @pytest.mark.asyncio- async def test_direct_mode_full_run(self, tmp_path: Any) -> None:- from benchmark.iso_solve.core.runner import BenchmarkRunner-- mock_extractor = AsyncMock(side_effect=["4", "7"])- mock_judge = AsyncMock(side_effect=[(True, "CORRECT"), (False, "INCORRECT")])- runner = BenchmarkRunner(_make_stub_adapter(), mock_extractor, mock_judge)-- args = argparse.Namespace(- mode="direct", dry_run=False, output=str(tmp_path),- benchmark="stub", config="", limit=None, seed=42,- )- cfg = {- "evaluation": {"llm_extract": True, "llm_judge": True},- "output_dir": str(tmp_path),- "stub": {- "llm": {"model": "test-model", "temperature": 0.0, "max_tokens": 128},- "concurrency": 2,- },- }-- with patch("src.services.llm.config.get_llm_config") as mock_llm_cfg, \- patch.object(BenchmarkRunner, "_direct_call",- new_callable=AsyncMock) as mock_call:- mock_llm_cfg.return_value = MagicMock(- model="test-model", api_key="k", base_url="https://example.com/v1",- )- mock_call.side_effect = ["The answer is 4", "The answer is 7"]-- report = await runner.run(args, cfg)-- assert report.total == 2- assert report.correct == 1- assert report.errors == 0- assert report.accuracy_pct == 50.0-- @pytest.mark.asyncio- async def test_direct_mode_dry_run(self, tmp_path: Any) -> None:- from benchmark.iso_solve.core.runner import BenchmarkRunner-- runner = BenchmarkRunner(_make_stub_adapter(), AsyncMock(), AsyncMock())- args = argparse.Namespace(- mode="direct", dry_run=True, output=str(tmp_path),- benchmark="stub", config="", limit=None, seed=42,- )- cfg = {- "output_dir": str(tmp_path),- "stub": {"llm": {"model": "m"}, "concurrency": 1},- }-- with patch("src.services.llm.config.get_llm_config") as mock_cfg:- mock_cfg.return_value = MagicMock(model="m", api_key="k", base_url="u")- report = await runner.run(args, cfg)-- assert report.total == 0-- @pytest.mark.asyncio- async def test_direct_mode_llm_error_captured(self, tmp_path: Any) -> None:- """Problem 1 errors from _direct_call → extractor/judge are NOT called- for it. Only problem 2 goes through extractor + judge."""- from benchmark.iso_solve.core.runner import BenchmarkRunner-- mock_extractor = AsyncMock(return_value="6")- mock_judge = AsyncMock(return_value=(True, "CORRECT"))- runner = BenchmarkRunner(_make_stub_adapter(), mock_extractor, mock_judge)-- args = argparse.Namespace(- mode="direct", dry_run=False, output=str(tmp_path),- benchmark="stub", config="", limit=None, seed=42,- )- cfg = {- "evaluation": {"llm_extract": True, "llm_judge": True},- "output_dir": str(tmp_path),- "stub": {"llm": {"model": "m", "temperature": 0, "max_tokens": 128}, "concurrency": 2},- }-- with patch("src.services.llm.config.get_llm_config") as mock_llm_cfg, \- patch.object(BenchmarkRunner, "_direct_call",- new_callable=AsyncMock) as mock_call:- mock_llm_cfg.return_value = MagicMock(model="m", api_key="k", base_url="u")- mock_call.side_effect = [RuntimeError("API 500"), "The answer is 6"]-- report = await runner.run(args, cfg)-- assert report.total == 2- assert report.errors == 1- assert report.correct == 1---# ===================================================================-# 8. BenchmarkRunner — pipeline mode (mocked solver)-# ===================================================================--class TestRunnerPipelineMode:-- @pytest.mark.asyncio- async def test_pipeline_mode_calls_solver(self, tmp_path: Any) -> None:- from benchmark.iso_solve.core.runner import BenchmarkRunner- from benchmark.iso_solve.eval.base import BenchmarkAdapter-- class _StubAdapter(BenchmarkAdapter):- name = "stub"- skip_extract = True- breakdown_keys = []-- def load_dataset(self, *a: Any, **kw: Any) -> list[Problem]:- return [_make_problem(id="p1", question="Q1", ground_truth="A1")]-- def filter_problems(self, problems: list, *a: Any, **kw: Any) -> list:- return problems-- mock_judge = AsyncMock(return_value=(True, "CORRECT"))- runner = BenchmarkRunner(_StubAdapter(), AsyncMock(), mock_judge)-- args = argparse.Namespace(- mode="pipeline", dry_run=False, output=str(tmp_path),- benchmark="stub", config="", limit=None, seed=42,- )- cfg = {- "evaluation": {"llm_extract": False, "llm_judge": True},- "output_dir": str(tmp_path),- "stub": {- "llm": {"model": "m", "temperature": 0, "max_tokens": 128},- "pipeline": {- "model": "test-model",- "tools": ["code_execute", "reason"],- "language": "en",- "concurrency": 1,- },- },- }-- with patch("src.services.llm.config.get_llm_config") as mock_llm_cfg, \- patch("benchmark.iso_solve.core.runner.run_solver_pipeline",- new_callable=AsyncMock) as mock_pipeline:- mock_llm_cfg.return_value = MagicMock(model="m", api_key="k", base_url="u")- mock_pipeline.return_value = {"final_answer": "A1"}-- report = await runner.run(args, cfg)-- assert report.total == 1- assert report.correct == 1- mock_pipeline.assert_called_once()- call_kwargs = mock_pipeline.call_args.kwargs- assert call_kwargs["language"] == "en"- assert "code_execute" in call_kwargs["tools"]---# ===================================================================-# 9. Pipeline integration — run_solver_pipeline-# ===================================================================--class TestRunSolverPipeline:- """pipeline.py uses lazy imports: `from src.agents.solve import MainSolver`- and `from src.agents.solve.tools import ToolRegistry`. Mock at source."""-- @pytest.mark.asyncio- async def test_pipeline_creates_solver_and_calls_solve(self) -> None:- from benchmark.iso_solve.core.pipeline import run_solver_pipeline-- mock_solver = MagicMock()- mock_solver.ainit = AsyncMock()- mock_solver.solve = AsyncMock(return_value={- "final_answer": "42",- "output_md": "## Solution\n42",- })-- with patch("src.agents.solve.MainSolver",- return_value=mock_solver) as mock_cls:- result = await run_solver_pipeline(- question="What is 6*7?",- workspace="/tmp/test",- language="en",- tools=["code_execute", "reason"],- model="test-model",- max_tokens=4096,- temperature=0.5,- )-- assert result["final_answer"] == "42"- mock_solver.ainit.assert_called_once()- mock_solver.solve.assert_called_once_with("What is 6*7?", image_url=None)-- init_kwargs = mock_cls.call_args.kwargs- assert init_kwargs["model"] == "test-model"- assert init_kwargs["language"] == "en"- assert init_kwargs["disable_memory"] is True- assert init_kwargs["max_tokens"] == 4096- assert init_kwargs["temperature"] == 0.5-- @pytest.mark.asyncio- async def test_pipeline_with_image_url(self) -> None:- from benchmark.iso_solve.core.pipeline import run_solver_pipeline-- mock_solver = MagicMock()- mock_solver.ainit = AsyncMock()- mock_solver.solve = AsyncMock(return_value={"final_answer": "cat"})-- with patch("src.agents.solve.MainSolver",- return_value=mock_solver):- result = await run_solver_pipeline(- question="What is in this image?",- workspace="/tmp/test",- image_url="https://example.com/image.jpg",- )-- assert result["final_answer"] == "cat"- mock_solver.solve.assert_called_once_with(- "What is in this image?", image_url="https://example.com/image.jpg",- )-- @pytest.mark.asyncio- async def test_pipeline_default_tools(self) -> None:- from benchmark.iso_solve.core.pipeline import build_tool_registry-- with patch("src.agents.solve.tools.ToolRegistry") as mock_tr:- mock_tr.create_default.return_value = MagicMock()- build_tool_registry(None, "en")- mock_tr.create_default.assert_called_once_with(language="en")-- @pytest.mark.asyncio- async def test_pipeline_custom_tools(self) -> None:- from benchmark.iso_solve.core.pipeline import build_tool_registry-- with patch("src.agents.solve.tools.ToolRegistry") as mock_tr:- mock_tr.create_from_names.return_value = MagicMock()- build_tool_registry(["code_execute", "reason"], "en")- mock_tr.create_from_names.assert_called_once_with(- ["code_execute", "reason"], language="en",- )---# ===================================================================-# 10. JSON parsing robustness (planner output parsing)-# ===================================================================--class TestPlannerParsing:-- def test_parse_pure_json(self) -> None:- from src.agents.solve.utils.json_utils import extract_json_from_text-- data = extract_json_from_text('{"analysis": "test", "steps": [{"id": "S1", "goal": "do it"}]}')- assert data is not None- assert data["analysis"] == "test"- assert len(data["steps"]) == 1-- def test_parse_json_in_markdown_block(self) -> None:- from src.agents.solve.utils.json_utils import extract_json_from_text-- text = 'Here is the plan:\n```json\n{"analysis": "x", "steps": []}\n```'- data = extract_json_from_text(text)- assert data is not None- assert data["analysis"] == "x"-- def test_parse_json_with_surrounding_text(self) -> None:- from src.agents.solve.utils.json_utils import extract_json_from_text-- text = 'Let me plan this.\n{"analysis": "ok", "steps": [{"id": "S1", "goal": "step 1"}]}\nDone.'- data = extract_json_from_text(text)- assert data is not None- assert data["steps"][0]["goal"] == "step 1"-- def test_parse_empty_returns_none(self) -> None:- from src.agents.solve.utils.json_utils import extract_json_from_text-- assert extract_json_from_text("") is None- assert extract_json_from_text("no json here") is None-- def test_planner_fallback_on_bad_json(self) -> None:- from src.agents.solve.agents.planner_agent import PlannerAgent-- with patch("src.agents.base_agent.get_llm_config") as mock_cfg:- mock_cfg.return_value = MagicMock(- api_key="k", base_url="u", model="m", binding="openai", api_version=None,- )- agent = PlannerAgent(api_key="k", base_url="u", model="m")-- plan = agent._parse_plan("This is not JSON at all.", None)- assert len(plan.steps) == 1- assert plan.steps[0].id == "S1"- assert "Failed to parse plan" in plan.analysis-- def test_planner_parses_valid_plan(self) -> None:- from src.agents.solve.agents.planner_agent import PlannerAgent-- with patch("src.agents.base_agent.get_llm_config") as mock_cfg:- mock_cfg.return_value = MagicMock(- api_key="k", base_url="u", model="m", binding="openai", api_version=None,- )- agent = PlannerAgent(api_key="k", base_url="u", model="m")-- response = json.dumps({- "analysis": "Multi-step problem",- "steps": [- {"id": "S1", "goal": "Identify the data"},- {"id": "S2", "goal": "Calculate the answer"},- {"id": "S3", "goal": "Verify the result"},- ],- })- plan = agent._parse_plan(response, None)- assert len(plan.steps) == 3- assert plan.analysis == "Multi-step problem"- assert plan.steps[0].goal == "Identify the data"- assert plan.steps[2].id == "S3"---# ===================================================================-# 11. Solver agent decision parsing-# ===================================================================--class TestSolverAgentParsing:-- def _get_agent(self) -> Any:- from src.agents.solve.agents.solver_agent import SolverAgent-- with patch("src.agents.base_agent.get_llm_config") as mock_cfg:- mock_cfg.return_value = MagicMock(- api_key="k", base_url="u", model="m", binding="openai", api_version=None,- )- return SolverAgent(api_key="k", base_url="u", model="m")-- def test_parse_valid_decision(self) -> None:- agent = self._get_agent()- resp = json.dumps({- "thought": "I need to calculate",- "action": "code_execute",- "action_input": "print(2+2)",- "self_note": "Will compute arithmetic",- })- d = agent._parse_decision(resp)- assert d["action"] == "code_execute"- assert d["action_input"] == "print(2+2)"-- def test_parse_done_action(self) -> None:- agent = self._get_agent()- resp = json.dumps({- "thought": "Found the answer",- "action": "done",- "action_input": "The answer is 42",- "self_note": "Confirmed",- })- d = agent._parse_decision(resp)- assert d["action"] == "done"-- def test_parse_invalid_json_defaults_to_done(self) -> None:- agent = self._get_agent()- d = agent._parse_decision("This is not JSON")- assert d["action"] == "done"- assert "Failed to parse" in d["thought"]-- def test_parse_unknown_action_defaults_to_done(self) -> None:- agent = self._get_agent()- resp = json.dumps({- "thought": "hmm",- "action": "unknown_tool",- "action_input": "",- "self_note": "",- })- d = agent._parse_decision(resp)- assert d["action"] == "done"---# ===================================================================-# 12. End-to-end: skip_extract adapter flow-# ===================================================================--class TestSkipExtractFlow:-- @pytest.mark.asyncio- async def test_skip_extract_uses_full_output(self, tmp_path: Any) -> None:- from benchmark.iso_solve.core.runner import BenchmarkRunner- from benchmark.iso_solve.eval.base import BenchmarkAdapter-- class _SkipExtractAdapter(BenchmarkAdapter):- name = "skip_test"- skip_extract = True- breakdown_keys = []-- def load_dataset(self, *a: Any, **kw: Any) -> list[Problem]:- return [_make_problem(id="p1", ground_truth="42")]-- def filter_problems(self, problems: list, *a: Any, **kw: Any) -> list:- return problems-- mock_extractor = AsyncMock()- mock_judge = AsyncMock(return_value=(True, "CORRECT"))- runner = BenchmarkRunner(_SkipExtractAdapter(), mock_extractor, mock_judge)-- args = argparse.Namespace(- mode="direct", dry_run=False, output=str(tmp_path),- benchmark="skip_test", config="", limit=None, seed=42,- )- cfg = {- "evaluation": {"llm_extract": True, "llm_judge": True},- "output_dir": str(tmp_path),- "skip_test": {"llm": {"model": "m"}, "concurrency": 1},- }-- with patch("src.services.llm.config.get_llm_config") as mock_cfg, \- patch.object(BenchmarkRunner, "_direct_call",- new_callable=AsyncMock) as mock_call:- mock_cfg.return_value = MagicMock(model="m", api_key="k", base_url="u")- mock_call.return_value = "Full detailed answer: 42"-- report = await runner.run(args, cfg)-- mock_extractor.assert_not_called()- judge_call = mock_judge.call_args- assert judge_call.kwargs["predicted"] == "Full detailed answer: 42"---# ===================================================================-# 13. Output saving and file structure-# ===================================================================--class TestOutputSaving:- def test_save_result_creates_files(self, tmp_path: Any) -> None:- from benchmark.iso_solve.core.runner import BenchmarkRunner-- runner = BenchmarkRunner(_make_stub_adapter(), AsyncMock(), AsyncMock())- result = _make_result(correct=True)- runner._save_result(tmp_path, 0, result)-- assert (tmp_path / "outputs" / "0000" / "output.md").exists()- assert (tmp_path / "outputs" / "0000" / "meta.json").exists()-- with open(tmp_path / "outputs" / "0000" / "meta.json") as f:- meta = json.load(f)- assert meta["correct"] is True- assert meta["id"] == "p001"- assert meta["extracted_answer"] == "4"