DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Selective merge eval branch: solve/question/personalization 2.0
Bingxi Zhao (Frank)05f758e569a7
diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 000000000..56aa38628--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,28 @@+# DeepTutor LLM System (Current Behavior)++This file describes what the current LLM system does at runtime.++## What it does++- Loads active LLM configuration (API key, base URL, model, provider binding).+- Routes requests to the correct provider (cloud or local) via a unified factory.+- Supports both single-shot completion and streaming responses.+- Applies token limits and optional response formats when the provider supports them.+- Centralizes temperature and max token limits using `config/agents.yaml`.+- Logs LLM inputs/outputs and tracks token usage and timing per module.+- Maps provider errors into consistent exceptions for callers.+- Allows runtime config refresh so agents can pick up new settings without restart.+- Picks the final model by priority: agent override → global config → env defaults.+- Injects provider-specific kwargs (e.g., token limit fields) safely per model.+- Keeps a shared stats tracker per module for aggregated usage reporting.++## Scope++This repository is the **paper evaluation** variant of DeepTutor, containing only:+- Question Generation (出题)+- Question Solving (解题)+- RAG (Retrieval-Augmented Generation)+- Memory / Personalization+- Evaluation framework (benchmark + simu_tool)++All features are CLI-driven. There is no web frontend or HTTP API.diff --git a/benchmark/README.md b/benchmark/README.mdnew file mode 100644index 000000000..95fc15c31--- /dev/null+++ b/benchmark/README.md@@ -0,0 +1,236 @@+# 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__.pynew file mode 100644index 000000000..ba8ba1023--- /dev/null+++ b/benchmark/__init__.py@@ -0,0 +1 @@+# Benchmark - DeepTutor Evaluation Frameworkdiff --git a/benchmark/config/__init__.py b/benchmark/config/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/benchmark/config/benchmark_config.yaml b/benchmark/config/benchmark_config.yamlnew file mode 100644index 000000000..852efbf10--- /dev/null+++ b/benchmark/config/benchmark_config.yaml@@ -0,0 +1,83 @@+# =============================================================================+# 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__.pynew file mode 100644index 000000000..22aab44b2--- /dev/null+++ b/benchmark/data_generation/__init__.py@@ -0,0 +1,14 @@+# 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.pynew file mode 100644index 000000000..156ebe9b8--- /dev/null+++ b/benchmark/data_generation/batch_profiles.py@@ -0,0 +1,235 @@+#!/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.pynew file mode 100644index 000000000..9cb249781--- /dev/null+++ b/benchmark/data_generation/content_loader.py@@ -0,0 +1,146 @@+#!/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.pynew file mode 100644index 000000000..726777205--- /dev/null+++ b/benchmark/data_generation/gap_generator.py@@ -0,0 +1,233 @@+#!/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.pynew file mode 100644index 000000000..51fe496bb--- /dev/null+++ b/benchmark/data_generation/init_kbs_and_profiles.py@@ -0,0 +1,752 @@+#!/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.pynew file mode 100644index 000000000..2ae2f55a9--- /dev/null+++ b/benchmark/data_generation/llm_utils.py@@ -0,0 +1,220 @@+#!/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.pynew file mode 100644index 000000000..eccca51a6--- /dev/null+++ b/benchmark/data_generation/pipeline.py@@ -0,0 +1,486 @@+#!/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.pynew file mode 100644index 000000000..924ba8a73--- /dev/null+++ b/benchmark/data_generation/profile_generator.py@@ -0,0 +1,112 @@+#!/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.pynew file mode 100644index 000000000..1d1fe3645--- /dev/null+++ b/benchmark/data_generation/request_pipeline.py@@ -0,0 +1,378 @@+#!/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.pynew file mode 100644index 000000000..6c133a3e7--- /dev/null+++ b/benchmark/data_generation/scope_generator.py@@ -0,0 +1,130 @@+#!/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.pynew file mode 100644index 000000000..e45885a18--- /dev/null+++ b/benchmark/data_generation/task_generator.py@@ -0,0 +1,464 @@+#!/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__.pynew file mode 100644index 000000000..a186117ce--- /dev/null+++ b/benchmark/evaluation/__init__.py@@ -0,0 +1 @@+# Benchmark Evaluation - Tutor response and dialog scoringdiff --git a/benchmark/evaluation/evaluator.py b/benchmark/evaluation/evaluator.pynew file mode 100644index 000000000..9a89008a4--- /dev/null+++ b/benchmark/evaluation/evaluator.py@@ -0,0 +1,1071 @@+#!/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.pynew file mode 100644index 000000000..b94c2317f--- /dev/null+++ b/benchmark/evaluation/request_eval.py@@ -0,0 +1,602 @@+#!/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.pynew file mode 100644index 000000000..03aa279f6--- /dev/null+++ b/benchmark/evaluation/run.py@@ -0,0 +1,189 @@+#!/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.mdnew file mode 100644index 000000000..2ff48328d--- /dev/null+++ b/benchmark/iso_solve/README.md@@ -0,0 +1,199 @@+# 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__.pynew file mode 100644index 000000000..9107da100--- /dev/null+++ b/benchmark/iso_solve/__init__.py@@ -0,0 +1,11 @@+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.pynew file mode 100644index 000000000..504053fb2--- /dev/null+++ b/benchmark/iso_solve/check_folder_names.py@@ -0,0 +1,101 @@+#!/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.yamlnew file mode 100644index 000000000..582f0a7c8--- /dev/null+++ b/benchmark/iso_solve/config.yaml@@ -0,0 +1,400 @@+# --- 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__.pynew file mode 100644index 000000000..17114732b--- /dev/null+++ b/benchmark/iso_solve/core/__init__.py@@ -0,0 +1,16 @@+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.pynew file mode 100644index 000000000..5d44c0ad8--- /dev/null+++ b/benchmark/iso_solve/core/extractor.py@@ -0,0 +1,68 @@+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.pynew file mode 100644index 000000000..a8ca1ef31--- /dev/null+++ b/benchmark/iso_solve/core/judge.py@@ -0,0 +1,83 @@+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.pynew file mode 100644index 000000000..44f9b9531--- /dev/null+++ b/benchmark/iso_solve/core/pipeline.py@@ -0,0 +1,40 @@+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.pynew file mode 100644index 000000000..74beb0569--- /dev/null+++ b/benchmark/iso_solve/core/runner.py@@ -0,0 +1,346 @@+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.pynew file mode 100644index 000000000..26fdfa12b--- /dev/null+++ b/benchmark/iso_solve/core/types.py@@ -0,0 +1,144 @@+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__.pynew file mode 100644index 000000000..899b1381a--- /dev/null+++ b/benchmark/iso_solve/eval/__init__.py@@ -0,0 +1,33 @@+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.pynew file mode 100644index 000000000..baa8bb734--- /dev/null+++ b/benchmark/iso_solve/eval/aalcr.py@@ -0,0 +1,307 @@+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.pynew file mode 100644index 000000000..7fea8a4b1--- /dev/null+++ b/benchmark/iso_solve/eval/aime25.py@@ -0,0 +1,164 @@+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.pynew file mode 100644index 000000000..808ad0897--- /dev/null+++ b/benchmark/iso_solve/eval/base.py@@ -0,0 +1,90 @@+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.pynew file mode 100644index 000000000..5767942e6--- /dev/null+++ b/benchmark/iso_solve/eval/gaia.py@@ -0,0 +1,138 @@+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.pynew file mode 100644index 000000000..4f32baed4--- /dev/null+++ b/benchmark/iso_solve/eval/gpqa.py@@ -0,0 +1,130 @@+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.pynew file mode 100644index 000000000..5839e729b--- /dev/null+++ b/benchmark/iso_solve/eval/hle.py@@ -0,0 +1,110 @@+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.pynew file mode 100644index 000000000..7dfd6a330--- /dev/null+++ b/benchmark/iso_solve/eval/livebench.py@@ -0,0 +1,130 @@+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.pynew file mode 100644index 000000000..f9c4544e3--- /dev/null+++ b/benchmark/iso_solve/eval/math.py@@ -0,0 +1,174 @@+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__.pynew file mode 100644index 000000000..a593d4d2c--- /dev/null+++ b/benchmark/iso_solve/eval/scorers/__init__.py@@ -0,0 +1,3 @@+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.pynew file mode 100644index 000000000..f10bd7a64--- /dev/null+++ b/benchmark/iso_solve/eval/scorers/gaia_scorer.py@@ -0,0 +1,68 @@+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__.pynew file mode 100644index 000000000..8d5e4f1e8--- /dev/null+++ b/benchmark/iso_solve/eval/scorers/math_equivalence/__init__.py@@ -0,0 +1,13 @@+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.pynew file mode 100644index 000000000..bd4cae593--- /dev/null+++ b/benchmark/iso_solve/eval/super_gpqa.py@@ -0,0 +1,145 @@+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.pynew file mode 100644index 000000000..390194ef1--- /dev/null+++ b/benchmark/iso_solve/get_llm_score.py@@ -0,0 +1,736 @@+"""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.pynew file mode 100644index 000000000..6456363aa--- /dev/null+++ b/benchmark/iso_solve/multimodal.py@@ -0,0 +1,417 @@+# -*- 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.pynew file mode 100644index 000000000..ac36955d7--- /dev/null+++ b/benchmark/iso_solve/rejudge.py@@ -0,0 +1,1014 @@+"""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.pynew file mode 100644index 000000000..da05cd91b--- /dev/null+++ b/benchmark/iso_solve/run_benchmark.py@@ -0,0 +1,111 @@+# -*- 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.yamlnew file mode 100644index 000000000..c8aa3650b--- /dev/null+++ b/benchmark/iso_solve/score_jobs.yaml@@ -0,0 +1,50 @@+# ======================================================================+# 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__.pynew file mode 100644index 000000000..b3136f1f4--- /dev/null+++ b/benchmark/pipeline/__init__.py@@ -0,0 +1 @@+"""Three-step benchmark pipeline scripts."""diff --git a/benchmark/pipeline/check_entries.py b/benchmark/pipeline/check_entries.pynew file mode 100644index 000000000..233a5188a--- /dev/null+++ b/benchmark/pipeline/check_entries.py@@ -0,0 +1,710 @@+#!/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.pynew file mode 100644index 000000000..daf85380a--- /dev/null+++ b/benchmark/pipeline/run_step2_multimodel_then_step3_fixed_judge.py@@ -0,0 +1,182 @@+#!/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.pynew file mode 100644index 000000000..0ac8107f2--- /dev/null+++ b/benchmark/pipeline/step1_generate_entries.py@@ -0,0 +1,357 @@+#!/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.pynew file mode 100644index 000000000..02eebe1ec--- /dev/null+++ b/benchmark/pipeline/step2_generate_transcripts.py@@ -0,0 +1,410 @@+#!/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.pynew file mode 100644index 000000000..5c0b159cb--- /dev/null+++ b/benchmark/pipeline/step3_evaluate_transcripts.py@@ -0,0 +1,351 @@+#!/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__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/benchmark/prompts/eval_dialog.yaml b/benchmark/prompts/eval_dialog.yamlnew file mode 100644index 000000000..f9bc58f9c--- /dev/null+++ b/benchmark/prompts/eval_dialog.yaml@@ -0,0 +1,74 @@+# 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.yamlnew file mode 100644index 000000000..855db41c8--- /dev/null+++ b/benchmark/prompts/eval_gap_tracking_turn.yaml@@ -0,0 +1,57 @@+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.yamlnew file mode 100644index 000000000..11b32bb80--- /dev/null+++ b/benchmark/prompts/eval_source_faithfulness_turn.yaml@@ -0,0 +1,69 @@+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.yamlnew file mode 100644index 000000000..506ec6283--- /dev/null+++ b/benchmark/prompts/eval_teaching_quality_turn.yaml@@ -0,0 +1,64 @@+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.yamlnew file mode 100644index 000000000..133099dde--- /dev/null+++ b/benchmark/prompts/eval_turn.yaml@@ -0,0 +1,77 @@+# 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.yamlnew file mode 100644index 000000000..21a9ff1f9--- /dev/null+++ b/benchmark/prompts/generate_gaps.yaml@@ -0,0 +1,49 @@+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.yamlnew file mode 100644index 000000000..13a4e1b21--- /dev/null+++ b/benchmark/prompts/generate_gaps_page.yaml@@ -0,0 +1,63 @@+# 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.yamlnew file mode 100644index 000000000..51e803e52--- /dev/null+++ b/benchmark/prompts/generate_knowledge_scope.yaml@@ -0,0 +1,47 @@+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.yamlnew file mode 100644index 000000000..a2b14cb16--- /dev/null+++ b/benchmark/prompts/generate_profile.yaml@@ -0,0 +1,43 @@+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.yamlnew file mode 100644index 000000000..ac593dc0c--- /dev/null+++ b/benchmark/prompts/generate_task_single.yaml@@ -0,0 +1,65 @@+# 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.yamlnew file mode 100644index 000000000..557f70776--- /dev/null+++ b/benchmark/prompts/generate_tasks.yaml@@ -0,0 +1,60 @@+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.yamlnew file mode 100644index 000000000..456e6bd95--- /dev/null+++ b/benchmark/prompts/reject_task_batch.yaml@@ -0,0 +1,44 @@+# 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.yamlnew file mode 100644index 000000000..e3c71c0bf--- /dev/null+++ b/benchmark/prompts/student_system.yaml@@ -0,0 +1,66 @@+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.mdnew file mode 100644index 000000000..84a8e496e--- /dev/null+++ b/benchmark/simulation/USE_TOOL.md@@ -0,0 +1,234 @@+# 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__.pynew file mode 100644index 000000000..d30af9e7b--- /dev/null+++ b/benchmark/simulation/__init__.py@@ -0,0 +1,16 @@+# 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.pynew file mode 100644index 000000000..e21b95cfe--- /dev/null+++ b/benchmark/simulation/batch_simulation.py@@ -0,0 +1,915 @@+#!/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.pynew file mode 100644index 000000000..256b5e41f--- /dev/null+++ b/benchmark/simulation/conversation.py@@ -0,0 +1,1110 @@+#!/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.pynew file mode 100644index 000000000..ff0ef8d43--- /dev/null+++ b/benchmark/simulation/profile_evolver.py@@ -0,0 +1,102 @@+"""+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.pynew file mode 100644index 000000000..6faa70c63--- /dev/null+++ b/benchmark/simulation/student_agent.py@@ -0,0 +1,305 @@+#!/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.pynew file mode 100644index 000000000..8b173c0ab--- /dev/null+++ b/benchmark/simulation/test_tools.py@@ -0,0 +1,268 @@+#!/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.pynew file mode 100644index 000000000..ef41bbddf--- /dev/null+++ b/benchmark/simulation/tools.py@@ -0,0 +1,621 @@+# -*- 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.pynew file mode 100644index 000000000..aad6af1f2--- /dev/null+++ b/benchmark/tools/check_kbs.py@@ -0,0 +1,494 @@+#!/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.pynew file mode 100644index 000000000..83fa4fcb7--- /dev/null+++ b/benchmark/tools/fix_image_paths_in_kb.py@@ -0,0 +1,309 @@+#!/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.pynew file mode 100644index 000000000..c1c855368--- /dev/null+++ b/benchmark/tools/fix_kb_config.py@@ -0,0 +1,217 @@+#!/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/config/agents.yaml b/config/agents.yamlindex f8a0b8132..91640ac6c 100644--- a/config/agents.yaml+++ b/config/agents.yaml@@ -8,13 +8,10 @@# =============================================================================# Solve Module - Problem solving agents-# Agents: investigate_agent, note_agent, manager_agent, solve_agent, tool_agent, response_agent, precision_answer_agent+# Agents: planner_agent, solver_agent, writer_agentsolve:temperature: 0.3max_tokens: 8192- # NOTE: Valid tools for investigate agent validation are defined in- # config/main.yaml, which is the SINGLE source of truth for valid_tools.- # Do not re-declare valid_tools here to avoid configuration drift.# Research Module - Deep research agents# Agents: rephrase_agent, decompose_agent, manager_agent, research_agent, note_agent, reporting_agent@@ -23,7 +20,7 @@ research:max_tokens: 12000# Question Module - Question generation agents-# Agents: question_generation_agent, question_validation_agent+# Agents: idea_agent, evaluator, generator, validatorquestion:temperature: 0.7max_tokens: 4096@@ -46,6 +43,11 @@ co_writer:temperature: 0.7max_tokens: 4096+# Personalization Module - Memory agents (reflection, summary, weakness)+personalization:+ temperature: 0.5+ max_tokens: 8192+# =============================================================================# Narrator Agent - Independent configuration for TTS integration# =============================================================================diff --git a/config/main.yaml b/config/main.yamlindex a5842ef77..f70a3a36f 100644--- a/config/main.yaml+++ b/config/main.yaml@@ -13,7 +13,7 @@ paths:tools:rag_tool:kb_base_dir: ./data/knowledge_bases- default_kb: ai_textbook+ default_kb: ai-textbookrun_code:workspace: ./data/user/run_code_workspaceallowed_roots:@@ -30,7 +30,7 @@ tools:logging:# Global log level for the entire system (DEBUG, INFO, WARNING, ERROR)# This controls both DeepTutor logs and RAG module logs- level: DEBUG+ level: WARNINGsave_to_file: trueconsole_output: true# RAG module logger name mapping (optional customization)@@ -38,34 +38,26 @@ logging:knowledge_init: RAG-Initrag_tool: RAGquestion:- # Refactored: no iteration loops (max_rounds removed)rag_query_count: 3max_parallel_questions: 1rag_mode: naive- agents:- retrieve:- top_k: 30- generate:- max_retries: 2- relevance_analyzer:- enabled: true+ idea_loop:+ max_rounds: 3+ ideas_per_round: 5+ generation:+ max_retries: 2+ tools:+ web_search: true+ rag_tool: true+ write_code: truesolve:- max_solve_correction_iterations: 3+ max_react_iterations: 10 # Max ReAct rounds per plan step+ max_plan_steps: 10 # Max steps in a plan+ max_replans: 2 # Max replan attempts+ observation_max_tokens: 2000 # Truncation limit for tool resultsenable_citations: truesave_intermediate_results: true- # Valid tools for investigate agent validation- valid_tools:- - "rag_naive"- - "rag_hybrid"- - "web_search"- - "query_item"- - "none"- agents:- investigate_agent:- max_actions_per_round: 1- max_iterations: 3- precision_answer_agent:- enabled: true+ detailed_answer: true # true = iterative step-by-step writing; false = single-shotresearch:planning:rephrase:@@ -79,7 +71,7 @@ research:researching:max_iterations: 5new_topic_min_score: 0.85- execution_mode: series+ execution_mode: seriesmax_parallel_topics: 1enable_rag_naive: trueenable_rag_hybrid: truediff --git a/config/memory.yaml b/config/memory.yamlindex ba6df5b54..ce0530bae 100644--- a/config/memory.yaml+++ b/config/memory.yaml@@ -3,15 +3,21 @@# Configuration for the personalization memory system.llm:- # Model to use for MemoryAgent. Empty string uses system default LLM.+ # Model to use for memory agents. Empty string uses system default LLM.model: "qwen3-next-80b-a3b-instruct"# Temperature for memory analysis (lower = more deterministic)temperature: 0.5memory:- # Number of recent days of notes to read for context- recent_days: 7# Whether to automatically update memory after task completionauto_update: true- # Maximum length of preference context to inject into prompts (characters)- max_preference_length: 2000+ # Maximum ReAct rounds per agent+ max_react_rounds: 6++agents:+ reflection:+ enabled: true+ summary:+ enabled: true+ weakness:+ enabled: truediff --git a/paper/2510.12323v1.pdf b/paper/2510.12323v1.pdfnew file mode 100644index 000000000..fd9bfdbf9Binary files /dev/null and b/paper/2510.12323v1.pdf differdiff --git a/paper/COMMENTS.md b/paper/COMMENTS.mdnew file mode 100644index 000000000..c408525a7--- /dev/null+++ b/paper/COMMENTS.md@@ -0,0 +1,257 @@+COMMENTS COLLECTION++reviewer 1:+这是一份基于 ACL ARR 评分标准,针对该论文前三章(摘要、引言、相关工作、方法)的顶尖学术审稿人意见:++### 1. Paper Summary (论文摘要)+本文提出了一种名为 **DeepTutor** 的个性化智能辅导系统(Agentic Tutoring System)。该系统首次将工具增强的问题解答(Problem-Solving)与难度校准的问题生成(Question Generation)整合到一个闭环的交互过程中。其核心创新在于提出了“混合个性化引擎(Hybrid Personalization Engine)”,该引擎结合了静态知识增强(多模态 RAG)和动态个人记忆(Trace Forest)。通过记录多分辨率的交互轨迹,系统能够持续更新包含会话历史、用户弱点和系统自省的三个维度的学习者画像,从而实现问题解答与问题生成之间的双向任务耦合。++### 2. Summary of Strengths (主要优点)+1. **创新的闭环框架 (Novel Closed-Loop Framework)**:将“解题”和“出题”通过共享的记忆结构(Trace Forest)连接成闭环,这一设计非常符合真实的教育学原理。以往的工作大多孤立地处理这两个任务,本文的统一架构具有很高的启发性。+2. **精细化的记忆机制 (Comprehensive Memory Design)**:Trace Forest 的层次化设计(从会话级总结到细粒度的执行记录)以及三维度的学习者画像($\mathcal{D}_s, \mathcal{D}_w, \mathcal{D}_r$)有效克服了现有系统仅依赖粗粒度技能评分的缺陷,为 LLM 提供了丰富的个性化上下文。+3. **鲁棒的模块化流水线 (Robust Pipeline Architecture)**:方法部分对解题(调查-逐步求解-迭代写作)和出题(对抗式生成-验证)的拆解非常合理。特别是引入了层次化压缩(Hierarchical compression)来防止上下文窗口溢出,以及独立的验证器(Validator)来减少幻觉,这些工程设计都非常扎实。++### 3. Summary of Weaknesses (主要缺点)+1. **Trace Forest 的技术细节略显不足 (Lack of Detail in Trace Forest)**:虽然 Trace Forest 的概念很吸引人,但方法部分对其具体实现(如:节点嵌入 $\mathbf{e}_v$ 是如何生成和更新的?TraceToolkit 的 \textsc{SearchTrace} 是基于什么相似度度量?)描述不够具体,可能会影响复现性。+2. **“对抗式”术语的使用可能被夸大 (Overstated Terminology)**:在 2.4 节(Stage 4)中,作者使用了“Adversarial Q-A Pair Generation”。但从描述来看,这更像是一个标准的“生成-验证-反馈-修改”(Generate-and-Verify with Feedback)流水线,并没有体现出博弈论意义上的对抗训练。建议修改术语或进一步澄清其对抗性体现在何处。+3. **计算开销与延迟的考量缺失 (Complexity and Latency Concerns)**:系统包含多个 LLM Agent、多模态 RAG、代码沙箱执行以及复杂的记忆更新机制。对于一个“实时交互式”辅导系统而言,推理延迟和计算成本是致命的。方法部分完全没有讨论系统在实际运行中的效率问题。+4. **图表与算法的对应关系 (Formatting and Flow)**:Algorithm 1 非常密集,包含了大量符号(如 $\mathcal{I}, \mathcal{T}_i, f_i$),虽然在正文中有所提及,但读者在阅读算法伪代码时仍会感到吃力。++### 4. Comments/Suggestions/Typos (详细意见/建议/拼写错误)+* **Abstract**: 第73行 "They are unified through..." 中的 "They" 指代略显模糊,建议改为 "These two tasks are unified..."。同句中 "trace forest that continuously refines" 建议加冠词改为 "a trace forest that..."。+* **Introduction**: 第11行 "An effective human tutor does far more than supply correct answers--it diagnoses..." 使用 "it" 来指代 human tutor 不太自然,建议改为 "they diagnose" 或 "he/she diagnoses"。+* **Method (Section 2.2.1)**: 在介绍倒数秩融合(Reciprocal Rank Fusion)时,公式是标准的,但建议简要补充图检索(Graph-based retrieval)是如何对其候选节点进行初始排序($\mathrm{rank}_r(d)$)的。+* **Method (Section 2.3)**: Stage 1 提到“investigating before planning prevents sub-goals that are too vague”。这是一个非常好的洞察!强烈建议在这里用半句话补充一个具体的例子(例如:“相比于生成‘复习微积分’,系统会生成‘复习链式法则在三角函数中的应用’...”),这会大大增强文章的表达力。++### 5. Soundness (合理性评分及评价)+**评分: 4 (Strong)**+**评价**: 该研究的动机明确,方法设计逻辑严密,特别是在教育学理论(如诊断误区、支架式解释)与 LLM Agent 架构的结合上做得非常出色。如果能进一步补充关于检索排序细节和系统延迟的讨论,合理性将无可挑剔。++### 6. Excitement (兴奋度评分及评价)+**评分: 4.5 (Highly Exciting/Exciting)**+**评价**: 这是一篇令人兴奋的论文。将大模型应用于教育领域的痛点抓得很准,Trace Forest 和闭环反馈机制的设计为个性化 AI 导师提供了一个极具潜力的范式。我非常期待看到后续的实验结果(TutorBench)如何证明这一复杂系统的有效性。++### 7. Overall Assessment (总体评价)+**评分: 4 (Conference - Accept)**+**评价**: 仅从前三章来看,本文具备被顶级会议(如 ACL/EMNLP)接收的强大潜力。文章结构清晰,插图精美(Figure 1 和 Figure 2 质量很高),核心贡献(DeepTutor 框架和 Trace Forest)具有显著的创新性。建议作者在修改时重点提升方法细节的透明度(尤其是记忆检索机制),并适当降温部分略显夸大的术语(如 Adversarial)。+++reviewer 2:+## 主要问题+1. **核心新颖性主张偏强,但在前三章范围内没有被充分论证。** 摘要和引言都使用了 `the first` 级别的表述,但当前我看到的前三章还没有给出足够严谨的任务分解、系统边界定义,或与现有 personalized tutoring / agentic RAG / question generation 系统的逐项对比,因此这类 claim 在 ARR 里会很容易被审稿人质疑为“过度宣称”。++```72:76:paper/main.tex+In this paper, we present \textsc{DeepTutor}, the first personalized agentic tutoring system with both citation-grounded problem-solving and difficulty-calibrated question generation.+They are unified through a hybrid personalization engine that couples static knowledge grounding with trace forest that continuously refines an evolving learner profile to customize every interaction.+To further evaluate personalized tutoring abilities, we construct TutorBench, a benchmark containing 100 KB-grounded learner profiles to perform first-person interactive assessments via profile-driven student simulator.+Generalization experiments on five standard benchmarks further show that our reasoning pipeline lifts solving accuracy by approximately 25\% on average over the backbone model.+\textsc{DeepTutor} system with full evaluation suites are open-sourced at \url{https://github.com/HKUDS/DeepTutor/tree/eval}.+```++```27:31:paper/sections/intro.tex+\begin{itemize}[nosep,leftmargin=*]+ \item We propose \textsc{DeepTutor}, an agentic tutoring framework that, to the best of our knowledge, is the first to unify tool-augmented problem solving, adversarial question generation, and long-term structured memory into a closed interactive loop.+ \item We introduce \textit{trace forest}, a hierarchical memory architecture in which specialized agents collaboratively maintain a fine-grained, evolving learner model from multi-resolution interaction traces.+ \item We construct \textsc{TutorBench}, a benchmark of 100 knowledge-base-grounded learner profiles paired with a student simulator for first-person interactive evaluation. Experiments on TutorBench and five standard reasoning benchmarks show that \textsc{DeepTutor} substantially outperforms various baselines, providing insights for the future shape of personalized tutoring systems.+\end{itemize}+```++2. **方法章节目前更像“系统蓝图”,还不够像可复现、可验证的研究方法。** `paper/sections/method.tex` 引入了大量模块:KG、VDB、Trace Forest、memory agents、planner、tool agent、writer、generator、validator,但多数仍停留在概念级描述。对 ACL ARR 来说,这会直接拉低 `Soundness` 和 `Reproducibility`,因为读者仍不清楚关键设计到底是什么、哪些是必要创新、哪些只是工程组合。++```111:124:paper/sections/method.tex+\paragraph{Profile Construction.}+\label{sec:injection}+Raw traces must be interpreted into actionable tutoring signals.+We introduce three specialized memory agents to process each new trace tree $T_j$ in parallel, incrementally updating a dedicated dimension of the learner profile $\mathcal{D}$:+\begin{itemize}[nosep,leftmargin=*]+\item Session History $ \mathcal{D}_s$: distills topics covered and performance trends. This will record what has happened, providing general session memories.+\item User Weakness $\mathcal{D}_w$: compares learner responses against reference solutions, labeling each weakness as active or resolved to maintain a prioritized gap inventory, emphasizing where to focus.+\item Self-Reflection $\mathcal{D}_r$: critiques the system's own prior outputs for pedagogical alignment, producing actionable improvement notes, indicating how to improve.+\end{itemize}+Each agent receives the new trace along with its current profile dimension and produces an updated version through incremental revision, preserving long-term trends while incorporating recent signals.+```++3. **个性化记忆机制存在“错误累积/自我强化”风险,但当前方法没有给出足够防护。** 你们让系统把历史交互、弱点诊断、甚至 tutor 自反思都写回 profile;这很有想法,但也意味着一旦前序判断有误,系统可能反复读取并放大错误 learner model。尤其 `Self-Reflection` 与 `User Weakness` 都可能受到模型幻觉影响,前三章里尚未看到 confidence gating、conflict resolution、time decay、human-grounded correction 等机制。++4. **“闭环个性化 tutoring” 的核心科学命题没有被形式化。** 引言里最重要的论点是“解题暴露出的弱点应影响后续出题,而后续表现又应反向更新讲解方式”;这是一个很强、也很值得发表的命题。但在 `paper/sections/intro.tex` 和 `paper/sections/method.tex` 里,这个命题更多是叙事上的闭环,而不是可测量、可证伪的机制。比如:difficulty calibration 如何定义?学习者水平如何估计?“更个性化”到底对应什么客观指标?如果这些不清晰,审稿人会认为贡献更多是系统工程而非研究贡献。++5. **摘要与引言的写作尚不够“ARR-ready”。** 当前文本可读性总体不错,但摘要里有几处句法和指代不够稳,例如 `They are unified...` 的指代模糊,`trace forest that continuously refines...` 的语法不够顺,`lifts solving accuracy by approximately 25% on average` 又是一个非常重的结果性 claim,却没有在摘要中限定 benchmark、setting、baseline 类型。顶会审稿人通常会把这类问题视为“论证不够谨慎”。++## 综合审稿意见+如果我以 **ACL ARR 审稿人** 的角度、且**只基于摘要 + 引言 + 方法** 来打一个暂定印象分,这篇工作属于:++- **选题很强,方向很对,潜在影响力也不错。**+- **系统构想完整,问题意识清晰,`problem solving + question generation + memory` 的统一视角是最有价值的点。**+- **但目前前三章最大的问题是:claim 很大,方法写法偏概念化,关键科学问题还没有被足够“钉实”。**++按 ARR 口径,我会给出一个**暂定**判断:++- `Reviewer Confidence`: **3/5**+- `Soundness`: **2.5/5**+- `Excitement`: **3.5/5**+- `Overall Assessment`: **2.5/5 到 3/5 之间**+- 更具体地说:**如果后续实验和消融非常扎实,有机会到 Findings;如果实验对这些核心机制支撑不够,这篇会更像“下轮重投”。**++## 改进方法+1. **把 novelty claim 收紧。** 除非你们能在 related work 里做非常系统的排他性对比,否则建议把 `the first` 改成更稳健的表述,例如 `among the first`, `to our knowledge, one of the first`, 或者直接强调“we unify ... in a closed-loop tutoring setting”。++2. **把方法从“架构描述”升级成“研究方法描述”。** 最需要补的是一张总表:每个模块的输入、输出、模型、prompt 角色、调用时机、关键超参、失败条件、停止条件。现在读者知道你们“有这些模块”,但还不知道它们“究竟怎么工作”。++3. **明确 trace forest 的更新规则。** 建议补充:node schema、embedding 粒度、写回频率、profile update policy、冲突样本如何处理、旧信息何时衰减。否则 memory 贡献会显得像一个很好听但难以验证的概念。++4. **把 personalization 变成可操作定义。** 例如显式定义:+ - learner proficiency signal+ - weakness severity+ - question difficulty target+ - explanation adaptation dimensions+ 这样后面实验才能自然对应到“是否真的 personalized”。++5. **提前在方法里写出 failure control。** 我最担心的是 profile drift 和 hallucinated weakness。建议补充一致性校验、低置信度不写回、短期/长期记忆分离、以及基于证据的更新门控。++6. **摘要重写一版。** 顶会论文的摘要最好做到三件事:问题界定单句说清、核心技术单句说清、结果边界单句说清。你现在的摘要信息很多,但密度过高、句法稍乱,容易让审稿人第一印象打折。++## 开放问题+1. `User Weakness` 的标签是由谁产生的?是基于 gold reference、rule-based matching,还是纯 LLM judgment?+2. `Self-Reflection` 为什么应该进入 learner profile,而不是只作为 system-side optimization signal?+3. `difficulty-calibrated` 的标定标准是什么?有外部 rubric、IRT 风格定义,还是模型自评?+4. 闭环收益是来自 `memory`、`tool use`、`RAG`,还是三者交互?如果没有强消融,这一点会被反复追问。++如果你愿意,我下一步可以继续直接按 `ACL ARR Review Form` 的格式,帮你把这份意见整理成一版可直接放进 `paper/REVIEW.md` 的正式审稿文本。++reviewer 3:+明白,我重新聚焦到 **Abstract、Introduction、Related Work、Method** 这四个部分,完全不涉及实验章节。以下是修订后的审稿意见。++---++## 综合审稿意见(范围:Abstract + Intro + Related Work + Method)++### Paper Summary++本文提出 DeepTutor,一个工具增强的个性化辅导系统,将引用溯源的问题求解(problem solving)和难度校准的题目生成(question generation)统一在一个闭环框架中。核心贡献为 Hybrid Personalization Engine,耦合静态知识检索(多模态 KG + 向量数据库)与动态个人记忆(Trace Forest),通过三个专用记忆代理持续更新学习者画像,实现"求解暴露弱点 → 驱动出题 → 出题表现反馈修正解释"的双向耦合循环。++---++### Summary of Strengths++**S1. 问题定位精准,动机论证有力。**+Introduction 中"闭环交互循环"(closed interactive loop)的缺失论证逻辑清晰:现有系统要么单做求解要么单做出题,缺乏将两者通过持久化学习者状态耦合起来的设计。§1 第三段对所需两个条件的提炼——(i) 细粒度结构化记忆、(ii) 模块共享并持续更新该记忆——为后续 Method 的展开提供了很好的铺垫。++**S2. 方法的形式化程度高,架构清晰。**+Algorithm 1 提供了完整的伪代码,涵盖从 profile injection 到 trace forest 更新的全流程。符号体系($\mathcal{D}$, $\mathcal{F}$, $\mathcal{C}_{\text{mem}}$, $\mathcal{C}_{\text{rag}}$)在 Preliminaries 中统一定义,后续各子模块一致使用,读者可以清晰追踪数据流。++**S3. Trace Forest 的可编程记忆设计有新意。**+三层层次化记忆(Session → Planning → Execution)配合 TraceToolkit(SearchTrace / ListTraces / ReadNodes)的接口设计,将被动数据存储转变为可主动查询的结构化记忆。这比简单的对话历史窗口或 summary buffer 更具灵活性,允许不同 agent 以不同粒度按需检索历史。++**S4. 双向任务耦合(Bidirectional Task Coupling)概念有理论价值。**+§2.5 中描述的求解 → $\mathcal{D}_w$ → 出题 → $\mathcal{D}_s$/$\mathcal{D}_r$ → 解释修正循环,在教育学上对应形成性评估(formative assessment)理论,在 LLM 系统设计中尚属少见。++**S5. 叙述结构层次分明。**+Method 各子节遵循一致的"动机 → 技术描述 → 与整体系统的关联"叙述模式,Figure 2 信息量丰富,能有效帮助读者把握全局。++---++### Summary of Weaknesses++**W1. "First" 声明过强,缺乏系统性论证(Critical)。**++摘要和 Contribution (i) 反复使用 "the first personalized agentic tutoring system" 和 "the first to unify tool-augmented problem solving, adversarial question generation, and long-term structured memory"。这种强排他性声明需要有系统性的文献排查支撑,但 Related Work 仅有三段、共12行,远不足以承担此任务。具体问题:++- **经典 ITS 被忽略**:Cognitive Tutor、AutoTutor、BEETLE II 等系统早已集成了问题生成与求解反馈的闭环,且具有长期学习者建模。Related Work 中完全没有讨论这些工作与 DeepTutor 的区别;+- **近期商业/开源系统被忽略**:Khanmigo(Khan Academy + GPT-4)、Duolingo Max 等系统也做了个性化 + 出题 + 求解的整合,应当明确说明本文与这些系统在架构层面的差异;+- **"First" 的精确范围未定义**:是 first open-source?first with trace-based memory?first with tool-augmented agents?需要限定条件。++**W2. Related Work 过于单薄,无法支撑论文的 positioning(Major)。**++整个 Related Work 只有三个 paragraph(Agentic Tool Use / Personalization and Memory / AI for Education),每段仅 3-4 句。对于一篇声称 "first to unify" 三个方向的论文,这样的文献综述是严重不足的:++- **缺少 ITS(Intelligent Tutoring Systems)方向**:这是教育技术的核心领域,有数十年的研究积累,完全没有被讨论;+- **缺少 Knowledge Tracing 方向**:BKT、DKT、SAINT 等知识追踪模型与 Trace Forest 的学习者建模功能存在功能重叠,需要对比并说明差异;+- **每段的 "DeepTutor fills this gap" 式结尾过于公式化**:三段都以"XXX methods lack Y. DeepTutor addresses this with Z"结尾,缺乏对现有工作优缺点的深入分析。++**W3. Method 中多个核心模块的 novelty boundary 模糊(Major)。**++Method 组合了多个已有技术,但未清晰界定哪些是复用、哪些是本文贡献:++- **Static Knowledge Grounding(§2.2.1)**:多模态 KG 构建引用了 RAGAnything [Guo et al.],RRF 融合引用了 [Cormack et al., 2009]——这一小节中是否有任何本文特有的技术贡献?如果主要是工程整合,应当明确说明;+- **Step-by-step Solving(§2.3 Stage ②)**:ReAct 循环 + adaptive replanning 与 IterResearch [Chen et al., 2026] 高度相似,self-note 机制是否是本文独有的贡献?需要明确对比;+- **"Adversarial" 用词误导**:Generator-Validator 分离是 "generate-then-validate" 模式,并非真正的对抗训练(adversarial training)。在 NLP 社区中 "adversarial" 有明确的技术含义(如 GANs、adversarial examples),这里的使用可能造成混淆。++**W4. Profile Injection 机制(§2.2 末尾)描述不足,是全文最关键的薄弱点(Major)。**++$\mathcal{C}_{\text{mem}}$ 的组装是连接 Trace Forest 与所有 pipeline agent 的核心桥梁,但描述极为简略:++- "top-$k$ most relevant nodes with $k$ allocated proportionally across levels" — 比例如何确定?$k$ 的具体值是多少?是超参数还是自适应的?+- "role-specific slices of $\mathcal{D}$" — planner 收到 $\mathcal{D}_s + \mathcal{D}_w$,writer 收到 $\mathcal{D}_r$——这种硬编码分配的依据是什么?有无替代方案的讨论?+- Token budget 如何在 $\mathcal{C}_{\text{rag}}$ 和 $\mathcal{C}_{\text{mem}}$ 之间分配?当 context window 紧张时如何取舍?+- 缺少一个端到端的 worked example 展示实际注入的内容。++**W5. Trace Forest 形式化与实现细节之间存在空缺(Moderate)。**++- 节点 embedding $\mathbf{e}_v$ 用什么模型生成?是否与 $\mathcal{B}$(RAG 的向量索引)共享同一编码器?+- SearchTrace 的检索是 ANN 还是精确搜索?复杂度如何?+- 三层层次结构(Level 1/2/3)的设计选择缺乏论证——为什么是三层而非两层或四层?§2.2 末尾说 "concrete node types at each level are task-specific and detailed alongside the respective pipelines",但 §2.3 和 §2.4 中并没有明确列出各 level 的 node types;+- Forest 的增长管理机制(pruning / compaction)未在 Method 中讨论。++**W6. 三个 Memory Agent 的更新机制缺乏形式化(Moderate)。**++§2.2 列出了 $\mathcal{D}_s$(Session History)、$\mathcal{D}_w$(User Weakness)、$\mathcal{D}_r$(Self-Reflection)三个维度,描述为"incremental revision",但:+- 这些 agent 的输入输出格式是什么?是自然语言文本还是结构化数据?+- "incremental revision" 的具体机制是什么?是完全重写还是 diff-based 更新?+- 当历史越来越长时,profile 如何避免无限膨胀?+- $\mathcal{D}_w$ 中 "active or resolved" 的状态转换逻辑是什么?++**W7. 摘要中指代不清和衔接问题(Minor)。**++Abstract 第四句 "They are unified through a hybrid personalization engine..." — "They" 的指代对象(citation-grounded problem-solving 和 difficulty-calibrated question generation)需要读者回溯推断,建议改为显式主语。此外,摘要在 RAG 的不足(第三句)和 DeepTutor 的方案(第四句)之间缺乏过渡,读者需要自行建立逻辑跳跃。++---++### Comments / Suggestions / Typos++**结构性改进建议:**++1. **扩充 Related Work 至至少一整页**:增加 ITS 经典系统、Knowledge Tracing、LLM-based educational QG 三个方向的讨论。对每个方向,不仅说"它们缺乏X",更要分析它们各自的优势,然后说明 DeepTutor 如何在此基础上推进。++2. **在 Method 开头增加 "Design Rationale" 段**:解释为什么采用 investigation-solving-writing 三阶段分离而非端到端推理,并引用教育学理论(如 scaffolding theory、Zone of Proximal Development)。当前 Method 读起来更像系统描述而非研究贡献,增加理论支撑可显著提升深度。++3. **为 Profile Injection 增加 worked example**:用一个具体场景(如"初学者询问反向传播")展示 $\mathcal{C}_{\text{mem}}$ 的实际内容,包括从 Trace Forest 检索了什么、从 $\mathcal{D}$ 中提取了什么、最终注入 prompt 的格式。++4. **弱化 "first" claim**:改为如 "To our knowledge, DeepTutor is the first *open-source agentic framework* that unifies ... within a single closed-loop architecture" 或类似的有限定条件的表述。++**具体文字修正:**++| 位置 | 问题 | 建议修正 |+|------|------|----------|+| Abstract 第4句 | "They are unified" 指代不清 | → "These two capabilities are unified..." |+| Method §2 开头 | "as shown in figure~\ref{}" | → "Figure" 首字母大写 |+| §2.3 Stage ② | "a ReAct-style loop, ~\citep{}" | → 删除逗号和多余空格:"a ReAct-style loop~\citep{}" |+| §2.3 Stage ② | tool suite $\mathcal{A}$ 未正式定义 | 在 Notation 段中增加定义 |+| 全文 | "trace forest" 大小写不一致 | 统一为 "Trace Forest"(专有名词)或 "trace forest"(通用概念),选定一种 |+| Related Work ¶1 | "These frameworks target short-horizon tasks" | 过于笼统,应指出具体哪些 framework |+| Related Work ¶2 | "Yet existing methods rarely maintain pedagogically meaningful learner trajectories" | 需要具体引用说明哪些方法被检查过 |+| Algorithm 1 | 正文引用 "line 14" | 建议改为引用操作名 `Compress` 而非行号,避免重编号后失效 |++---++### 预估评分(仅基于 Abs + Intro + Related Work + Method 的写作与方法论质量)++| 维度 | 评分 | 理由 |+|------|------|------|+| **Soundness** | 3.0 | 系统设计合理但 Profile Injection、Memory Agent 更新机制等核心细节不足;novelty boundary 模糊 |+| **Excitement** | 3.5 | Trace Forest + 闭环耦合概念有新意且有教育学理论基础,但"组合创新"需更清晰地与已有工作区分 |+| **Overall** | 3.0 (Findings) | 方法框架有价值,但 Related Work 过于单薄无法支撑 "first" claim,核心机制描述存在缺口 |+| **Reviewer Confidence** | 4 | 熟悉 RAG、Agent、ITS 及教育 AI 领域 |++---++### 改进路线图(按优先级)++| 优先级 | 改进项 | 影响维度 |+|--------|--------|----------|+| **P0** | 扩充 Related Work,增加 ITS 经典系统 + Knowledge Tracing 讨论,精确化 "first" claim 的边界条件 | Soundness ↑, Overall ↑ |+| **P1** | 明确每个子模块的 novelty boundary(表格形式:模块 / 复用来源 / 本文贡献) | Excitement ↑ |+| **P1** | 补全 Profile Injection 的细节 + worked example | Soundness ↑, Reproducibility ↑ |+| **P2** | 增加 Design Rationale 段,引入教育学理论支撑 | Excitement ↑ |+| **P2** | 补全 Trace Forest 实现细节(embedding 模型、检索算法、层数论证) | Soundness ↑ |+| **P2** | 形式化 Memory Agent 的更新机制 | Soundness ↑ |+| **P3** | 修正术语一致性、typos、"adversarial" 用词 | 专业度 ↑ |\ No newline at end of filediff --git a/paper/REVIEW.md b/paper/REVIEW.mdnew file mode 100644index 000000000..6f6bcb3b3--- /dev/null+++ b/paper/REVIEW.md@@ -0,0 +1,105 @@+Review Form+Paper Summary+Describe what this paper is about. This should help action editors and area chairs to understand the topic of the work and highlight any possible misunderstandings.++Summary of Strengths+What are the major reasons to publish this paper at a selective *ACL venue? These could include novel and useful methodology, insightful empirical results or theoretical analysis, clear organization of related literature, or any other reason why interested readers of *ACL papers may find the paper useful.++Summary of Weaknesses+What are the concerns that you have about the paper that would cause you to favor prioritizing other high-quality papers that are also under consideration for publication? These could include concerns about correctness of the results or argumentation, limited perceived impact of the methods or findings (note that impact can be significant both in broad or in narrow sub-fields), lack of clarity in exposition, or any other reason why interested readers of *ACL papers may gain less from this paper than they would from other papers under consideration. Where possible, please number your concerns so authors may respond to them individually.++Comments/Suggestions/Typos+If you have any comments to the authors about how they may improve their paper, other than addressing the concerns above, please list them here.++Reviewer Confidence+5 = Positive that my evaluation is correct. I read the paper very carefully and am familiar with related work.+4 = Quite sure. I tried to check the important points carefully. It’s unlikely, though conceivable, that I missed something that should affect my ratings.+3 = Pretty sure, but there’s a chance I missed something. Although I have a good feel for this area in general, I did not carefully check the paper’s details, e.g., the math or experimental design.+2 = Willing to defend my evaluation, but it is fairly likely that I missed some details, didn’t understand some central points, or can’t be sure about the novelty of the work.+1 = Not my area, or paper is very hard to understand. My evaluation is just an educated guess.+Soundness+Given that this is a short/long paper, is it sufficiently sound and thorough? Does it clearly state scientific claims and provide adequate support for them? For experimental papers: consider the depth and/or breadth of the research questions investigated, technical soundness of experiments, methodological validity of evaluation. For position papers, surveys: consider whether the current state of the field is adequately represented and main counter-arguments acknowledged. For resource papers: consider the data collection methodology, resulting data & the difference from existing resources are described in sufficient detail.++5 = Excellent: This study is one of the most thorough I have seen, given its type.+4.5+4 = Strong: This study provides sufficient support for all of its claims. Some extra experiments could be nice, but not essential.+3.5+3 = Acceptable: This study provides sufficient support for its main claims. Some minor points may need extra support or details.+2.5+2 = Poor: Some of the main claims are not sufficiently supported. There are major technical/methodological problems.+1.5+1 = Major Issues: This study is not yet sufficiently thorough to warrant publication or is not relevant to ACL.+Excitement+How exciting is this paper for you? Excitement is subjective, and does not necessarily follow what is popular in the field. We may perceive papers as transformational/innovative/surprising, e.g. because they present conceptual breakthroughs or evidence challenging common assumptions/methods/datasets/metrics. We may be excited about the possible impact of the paper on some community (not necessarily large or our own), e.g. lowering barriers, reducing costs, enabling new applications. We may be excited for papers that are relevant, inspiring, or useful for our own research. These factors may combine in different ways for different reviewers.++5 = Highly Exciting: I would recommend this paper to others and/or attend its presentation in a conference.+4.5+4 = Exciting: I would mention this paper to others and/or make an effort to attend its presentation in a conference.+3.5+3 = Interesting: I might mention some points of this paper to others and/or attend its presentation in a conference if there’s time.+2.5+2 = Potentially Interesting: this paper does not resonate with me, but it might with others in the *ACL community.+1.5+1 = Not Exciting: this paper does not resonate with me, and I don’t think it would with others in the *ACL community (e.g. it is in no way related to computational processing of language).+Overall Assessment+If this paper was committed to an *ACL conference, do you believe it should be accepted? If you recommend conference, Findings and or even award consideration, you can still suggest minor revisions (e.g. typos, non-core missing refs, etc.).++Outstanding papers should be either fascinating, controversial, surprising, impressive, or potentially field-changing. Awards will be decided based on the camera-ready version of the paper. ACL award policy: https://www.aclweb.org/adminwiki/index.php/ACL_Conference_Awards_Policy++Main vs Findings papers: the main criteria for Findings are soundness and reproducibility. Conference recommendations may also consider novelty, impact and other factors.++5 = Consider for Award: I think this paper could be considered for an outstanding paper award at an *ACL conference (up to top 2.5% papers).+4.5 = Borderline Award+4 = Conference: I think this paper could be accepted to an *ACL conference.+3.5 = Borderline Conference+3 = Findings: I think this paper could be accepted to the Findings of the ACL.+2.5 = Borderline Findings+2 = Resubmit next cycle: I think this paper needs substantial revisions that can be completed by the next ARR cycle.+1.5 = Resubmit after next cycle: I think this paper needs substantial revisions that cannot be completed by the next ARR cycle.+1 = Do not resubmit: This paper has to be fully redone, or it is not relevant to the *ACL community (e.g. it is in no way related to computational processing of language).+Best paper justification+If your overall assessment for this paper is either ‘Consider for award’ or ‘Borderline award’, please briefly describe why.++Further Questions+Limitations and Societal Impact+Have the authors adequately discussed the limitations and potential positive and negative societal impacts of their work? If not, please include constructive suggestions for improvement. Authors should be rewarded rather than punished for being up front about the limitations of their work and any potential negative societal impact. You are encouraged to think through whether any critical points are missing and provide these as feedback for the authors. Consider, for example, cases of exclusion of user groups, overgeneralization of findings, unfair impacts on traditionally marginalized populations, bias confirmation, under- and overexposure of languages or approaches, and dual use (see Hovy and Spruit, 2016, for examples of those). Consider who benefits from the technology if it is functioning as intended, as well as who might be harmed, and how. Consider the failure modes, and in case of failure, who might be harmed and how.++Ethical Concerns+Please review the ACL code of ethics (https://www.aclweb.org/portal/content/acl-code-ethics) and the ARR checklist submitted by the authors in the submission form. If there are ethical issues with this paper, please describe them and the extent to which they have been acknowledged or addressed by the authors.++Needs Ethics Review+Should this paper be sent for an in-depth ethics review? We have a small ethics committee that can specially review very challenging papers when it comes to ethical issues. If this seems to be such a paper, then please explain why here, and we will try to ensure that it receives a separate review.++Reproducibility+Is there enough information in this paper for a reader to reproduce the main results, use results presented in this paper in future work (e.g., as a baseline), or build upon this work?++5 = They could easily reproduce the results.+4 = They could mostly reproduce the results, but there may be some variation because of sample variance or minor variations in their interpretation of the protocol or method.+3 = They could reproduce the results with some difficulty. The settings of parameters are underspecified or subjectively determined, and/or the training/evaluation data are not widely available.+2 = They would be hard pressed to reproduce the results: The contribution depends on data that are simply not available outside the author’s institution or consortium and/or not enough details are provided.+1 = They would not be able to reproduce the results here no matter how hard they tried.+Datasets+If the authors state (in anonymous fashion) that datasets will be released, how valuable will they be to others?++5 = Enabling: The newly released datasets should affect other people’s choice of research or development projects to undertake.+4 = Useful: I would recommend the new datasets to other researchers or developers for their ongoing work.+3 = Potentially useful: Someone might find the new datasets useful for their work.+2 = Documentary: The new datasets will be useful to study or replicate the reported research, although for other purposes they may have limited interest or limited usability. (Still a positive rating)+1 = No usable datasets submitted.+Software+If the authors state (in anonymous fashion) that their software will be available, how valuable will it be to others?++5 = Enabling: The newly released software should affect other people’s choice of research or development projects to undertake.+4 = Useful: I would recommend the new software to other researchers or developers for their ongoing work.+3 = Potentially useful: Someone might find the new software useful for their work.+2 = Documentary: The new software will be useful to study or replicate the reported research, although for other purposes it may have limited interest or limited usability. (Still a positive rating)+1 = No usable software released.+Knowledge of/educated guess at author identity+5 = From a violation of double-blind-submission rules, I know/can guess at least one author’s name. (Note that non-anonymous preprints are permitted at any time, so this is not a violation.)+4 = From a preprint or allowed workshop paper, I know/can guess at least one author’s name.+3 = From the contents of the submission itself, I know/can guess at least one author’s name.+2 = From social media/a talk/other informal communication, I know/can guess at least one author’s name.+1 = I do not have even an educated guess about author identity.+(Optional) Conjecture as to author identity. Authors will not see your response.++\ No newline at end of filediff --git a/paper/custom.bib b/paper/custom.bibnew file mode 100644index 000000000..a16395636--- /dev/null+++ b/paper/custom.bib@@ -0,0 +1,269 @@+@misc{yao2023reactsynergizingreasoningacting,+ title = {ReAct: Synergizing Reasoning and Acting in Language Models},+ author = {Shunyu Yao and Jeffrey Zhao and Dian Yu and Nan Du and Izhak Shafran and Karthik Narasimhan and Yuan Cao},+ year = {2023},+ eprint = {2210.03629},+ archivePrefix = {arXiv},+ primaryClass = {cs.CL},+ url = {https://arxiv.org/abs/2210.03629},+ doi = {10.48550/arXiv.2210.03629}+}++@misc{zhao2025llmbasedagenticreasoningframeworks,+ title = {LLM-based Agentic Reasoning Frameworks: A Survey from Methods to Scenarios},+ author = {Bingxi Zhao and Lin Geng Foo and Ping Hu and Christian Theobalt and Hossein Rahmani and Jun Liu},+ year = {2025},+ eprint = {2508.17692},+ archivePrefix = {arXiv},+ primaryClass = {cs.AI},+ url = {https://arxiv.org/abs/2508.17692},+ doi = {10.48550/arXiv.2508.17692}+}++@inproceedings{wu-etal-2025-agentic,+ title = {Agentic Reasoning: A Streamlined Framework for Enhancing {LLM} Reasoning with Agentic Tools},+ author = {Wu, Junde and Zhu, Jiayuan and Liu, Yuyuan and Xu, Min and Jin, Yueming},+ booktitle = {Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},+ month = jul,+ year = {2025},+ address = {Vienna, Austria},+ publisher = {Association for Computational Linguistics},+ url = {https://aclanthology.org/2025.acl-long.1383/},+ doi = {10.18653/v1/2025.acl-long.1383},+ pages = {28489--28503}+}++@misc{li2025intheflowagenticoptimizationeffective,+ title = {In-the-Flow Agentic System Optimization for Effective Planning and Tool Use},+ author = {Zhuofeng Li and Haoxiang Zhang and Seungju Han and Sheng Liu and Jianwen Xie and Yu Zhang and Yejin Choi and James Zou and Pan Lu},+ year = {2025},+ eprint = {2510.05592},+ archivePrefix = {arXiv},+ primaryClass = {cs.AI},+ url = {https://arxiv.org/abs/2510.05592},+ doi = {10.48550/arXiv.2510.05592}+}++@inproceedings{tan-etal-2025-prospect,+ title = {In Prospect and Retrospect: Reflective Memory Management for Long-term Personalized Dialogue Agents},+ author = {Tan, Zhen and Yan, Jun and Hsu, I-Hung and Han, Rujun and Wang, Zifeng and Le, Long and Song, Yiwen and Chen, Yanfei and Palangi, Hamid and Lee, George and Iyer, Anand Rajan and Chen, Tianlong and Liu, Huan and Lee, Chen-Yu and Pfister, Tomas},+ booktitle = {Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},+ month = jul,+ year = {2025},+ address = {Vienna, Austria},+ publisher = {Association for Computational Linguistics},+ url = {https://aclanthology.org/2025.acl-long.413/},+ doi = {10.18653/v1/2025.acl-long.413},+ pages = {8416--8439}+}++@inproceedings{cho-etal-2022-personalized,+ title = {A Personalized Dialogue Generator with Implicit User Persona Detection},+ author = {Cho, Itsugun and Wang, Dongyang and Takahashi, Ryota and Saito, Hiroaki},+ booktitle = {Proceedings of the 29th International Conference on Computational Linguistics},+ month = oct,+ year = {2022},+ address = {Gyeongju, Republic of Korea},+ publisher = {International Committee on Computational Linguistics},+ url = {https://aclanthology.org/2022.coling-1.29/},+ pages = {367--377},+ doi = {10.48550/arXiv.2204.07372}+}++@inproceedings{li-etal-2025-hello,+ title = {Hello Again! {LLM}-powered Personalized Agent for Long-term Dialogue},+ author = {Li, Hao and Yang, Chenghao and Zhang, An and Deng, Yang and Wang, Xiang and Chua, Tat-Seng},+ booktitle = {Proceedings of the 2025 Conference of the Nations of the Americas Chapter of the Association for Computational Linguistics: Human Language Technologies (Volume 1: Long Papers)},+ month = apr,+ year = {2025},+ address = {Albuquerque, New Mexico},+ publisher = {Association for Computational Linguistics},+ url = {https://aclanthology.org/2025.naacl-long.272/},+ doi = {10.18653/v1/2025.naacl-long.272},+ pages = {5259--5276}+}++@misc{wang2024agentworkflowmemory,+ title = {Agent Workflow Memory},+ author = {Zora Zhiruo Wang and Jiayuan Mao and Daniel Fried and Graham Neubig},+ year = {2024},+ eprint = {2409.07429},+ archivePrefix = {arXiv},+ primaryClass = {cs.CL},+ url = {https://arxiv.org/abs/2409.07429},+ doi = {10.48550/arXiv.2409.07429}+}++@misc{li2025surveypersonalizationragagent,+ title = {A Survey of Personalization: From RAG to Agent},+ author = {Xiaopeng Li and Pengyue Jia and Derong Xu and Yi Wen and Yingyi Zhang and Wenlin Zhang and Wanyu Wang and Yichao Wang and Zhaocheng Du and Xiangyang Li and Yong Liu and Huifeng Guo and Ruiming Tang and Xiangyu Zhao},+ year = {2025},+ eprint = {2504.10147},+ archivePrefix = {arXiv},+ primaryClass = {cs.IR},+ url = {https://arxiv.org/abs/2504.10147},+ doi = {10.48550/arXiv.2504.10147}+}++@misc{guo2025raganythingallinoneragframework,+ title = {RAG-Anything: All-in-One RAG Framework},+ author = {Zirui Guo and Xubin Ren and Lingrui Xu and Jiahao Zhang and Chao Huang},+ year = {2025},+ eprint = {2510.12323},+ archivePrefix = {arXiv},+ primaryClass = {cs.AI},+ url = {https://arxiv.org/abs/2510.12323},+ doi = {10.48550/arXiv.2510.12323}+}++@article{letourneau2025systematicreviewaidriven,+ title = {A systematic review of AI-driven intelligent tutoring systems (ITS) in K-12 education},+ author = {L{\'e}tourneau, Ang{\'e}lique and Deslandes Martineau, Marion and Charland, Patrick and Karran, John Alexander and Boasen, Jared and L{\'e}ger, Pierre Majorique},+ journal = {npj Science of Learning},+ volume = {10},+ number = {1},+ year = {2025},+ month = may,+ publisher = {Springer Science and Business Media LLC},+ doi = {10.1038/s41539-025-00320-7},+ url = {https://doi.org/10.1038/s41539-025-00320-7}+}++@inproceedings{park2024empoweringpersonalizedlearning,+ title = {Empowering Personalized Learning through a Conversation-based Tutoring System with Student Modeling},+ author = {Park, Minju and Kim, Sojung and Lee, Seunghyun and Kwon, Soonwoo and Kim, Kyuseok},+ booktitle = {Extended Abstracts of the CHI Conference on Human Factors in Computing Systems},+ series = {CHI '24},+ pages = {1--10},+ year = {2024},+ month = may,+ publisher = {ACM},+ doi = {10.1145/3613905.3651122},+ url = {https://doi.org/10.1145/3613905.3651122}+}++@misc{wang2025llmpoweredmultiagentframeworkgoaloriented,+ title = {LLM-powered Multi-agent Framework for Goal-oriented Learning in Intelligent Tutoring System},+ author = {Tianfu Wang and Yi Zhan and Jianxun Lian and Zhengyu Hu and Nicholas Jing Yuan and Qi Zhang and Xing Xie and Hui Xiong},+ year = {2025},+ eprint = {2501.15749},+ archivePrefix = {arXiv},+ primaryClass = {cs.AI},+ url = {https://arxiv.org/abs/2501.15749},+ doi = {10.48550/arXiv.2501.15749}+}++@inproceedings{frankford2024aitutoringsoftwareengineering,+ title = {AI-Tutoring in Software Engineering Education},+ author = {Frankford, Eduard and Sauerwein, Clemens and Bassner, Patrick and Krusche, Stephan and Breu, Ruth},+ booktitle = {Proceedings of the 46th International Conference on Software Engineering: Software Engineering Education and Training},+ series = {ICSE-SEET '24},+ pages = {309--319},+ year = {2024},+ month = apr,+ publisher = {ACM},+ doi = {10.1145/3639474.3640061},+ url = {https://doi.org/10.1145/3639474.3640061}+}++% ===========================================================================+% Benchmark References+% ===========================================================================++@misc{phan2025hle,+ title = {Humanity's Last Exam},+ author = {Long Phan and Alice Gatti and Ziwen Han and Nathaniel Li and Josephina Hu and Hugh Zhang and Sean Shi and Michael Byun and Len Sohl-Dickstein and Leonard Tang and others},+ year = {2025},+ eprint = {2501.14249},+ archivePrefix = {arXiv},+ primaryClass = {cs.CL},+ url = {https://arxiv.org/abs/2501.14249}+}++@misc{rein2023gpqa,+ title = {{GPQA}: A Graduate-Level Google-Proof Q\&A Benchmark},+ author = {David Rein and Betty Li Hou and Asa Cooper Stickland and Jackson Petty and Richard Yuanzhe Pang and Julien Dirani and Julian Michael and Samuel R. Bowman},+ year = {2023},+ eprint = {2311.12022},+ archivePrefix = {arXiv},+ primaryClass = {cs.CL},+ url = {https://arxiv.org/abs/2311.12022}+}++@misc{mialon2023gaia,+ title = {{GAIA}: A Benchmark for General {AI} Assistants},+ author = {Gr{\'e}goire Mialon and Cl{\'e}mentine Fourrier and Craig Swift and Thomas Wolf and Yann LeCun and Thomas Scialom},+ year = {2023},+ eprint = {2311.12983},+ archivePrefix = {arXiv},+ primaryClass = {cs.CL},+ url = {https://arxiv.org/abs/2311.12983}+}++@misc{white2024livebench,+ title = {{LiveBench}: A Challenging, Contamination-Free {LLM} Benchmark},+ author = {Colin White and Samuel Dooley and Manley Roberts and Arka Pal and Ben Feuer and Siddhartha Jain and Ravid Shwartz-Ziv and Neel Jain and Khalid Saifullah and Siddartha Naidu and others},+ year = {2024},+ eprint = {2406.19314},+ archivePrefix = {arXiv},+ primaryClass = {cs.CL},+ url = {https://arxiv.org/abs/2406.19314}+}++@misc{aalcr2024,+ title = {{AA-LCR}: Artificial Analysis Long Context Reasoning Benchmark},+ author = {{Artificial Analysis}},+ year = {2024},+ howpublished = {\url{https://huggingface.co/datasets/ArtificialAnalysis/AA-LCR}},+ note = {100 human-crafted questions requiring multi-step reasoning across long documents}+}++@misc{openai2023gpt4,+ title = {{GPT-4} Technical Report},+ author = {{OpenAI}},+ year = {2023},+ eprint = {2303.08774},+ archivePrefix = {arXiv},+ primaryClass = {cs.CL},+ url = {https://arxiv.org/abs/2303.08774}+}++@article{kurdi2020systematic,+ title = {A Systematic Review of Automatic Question Generation for Educational Purposes},+ author = {Kurdi, Ghader and Leo, Jared and Parsia, Bijan and Sattler, Uli and Al-Emari, Salam},+ journal = {International Journal of Artificial Intelligence in Education},+ volume = {30},+ pages = {121--204},+ year = {2020},+ publisher = {Springer},+ doi = {10.1007/s40593-019-00186-y}+}++@misc{lewkowycz2022solving,+ title = {Solving Quantitative Reasoning Problems with Language Models},+ author = {Aitor Lewkowycz and Anders Andreassen and David Dohan and Ethan Dyer and Henryk Michalewski and Vinay Ramasesh and Ambrose Slone and Cem Anil and Imanol Schlag and Theo Gutman-Solo and others},+ year = {2022},+ eprint = {2206.14858},+ archivePrefix = {arXiv},+ primaryClass = {cs.CL}+}++@article{trinh2024solving,+ title = {Solving Olympiad Geometry without Human Demonstrations},+ author = {Trinh, Trieu H. and Wu, Yuhuai and Le, Quoc V. and He, He and Luong, Thang},+ journal = {Nature},+ volume = {625},+ pages = {476--482},+ year = {2024},+ publisher = {Springer Nature}+}++@article{abdi2020complementary,+ title = {Complementing Education via Virtual Learning Environments: Existing Findings and Future Directions},+ author = {Abdi, Saba and Khosravi, Hassan and Sadiq, Shazia and Gasevic, Dragan},+ journal = {Journal of Learning Analytics},+ volume = {7},+ number = {1},+ year = {2020},+ doi = {10.18608/jla.2020.71.6}+}diff --git "a/paper/experiments/\344\270\200\344\272\233\347\211\271\344\276\213.md" "b/paper/experiments/\344\270\200\344\272\233\347\211\271\344\276\213.md"new file mode 100644index 000000000..bf3dfb1cf--- /dev/null+++ "b/paper/experiments/\344\270\200\344\272\233\347\211\271\344\276\213.md"@@ -0,0 +1,2 @@+1 个 CORRECT → INCORRECT:aalcr_0024(GT 是 $204 million)这个我们系统给的是205million,可以作为一个特例,就说我们的评估非常严格,对数值类的评估,没有任何容许误差。+有的时候json的解析会出现问题,我们的方法是设计了fallback逻辑,或者建议通过模型微调来增加鲁棒性。\ No newline at end of filediff --git a/paper/figures/compare-ver1.png b/paper/figures/compare-ver1.pngnew file mode 100644index 000000000..d41d42d1dBinary files /dev/null and b/paper/figures/compare-ver1.png differdiff --git a/paper/figures/data-gen-ver2.png b/paper/figures/data-gen-ver2.pngnew file mode 100644index 000000000..285c210abBinary files /dev/null and b/paper/figures/data-gen-ver2.png differdiff --git a/paper/figures/evaluation-ver1.png b/paper/figures/evaluation-ver1.pngnew file mode 100644index 000000000..6edad4f2bBinary files /dev/null and b/paper/figures/evaluation-ver1.png differdiff --git a/paper/figures/full-pipe-ver7.png b/paper/figures/full-pipe-ver7.pngnew file mode 100644index 000000000..64269f27eBinary files /dev/null and b/paper/figures/full-pipe-ver7.png differdiff --git a/paper/main.tex b/paper/main.texnew file mode 100644index 000000000..7b54ce538--- /dev/null+++ b/paper/main.tex@@ -0,0 +1,96 @@+\documentclass[11pt]{article}++% Change "review" to "final" to generate the final (sometimes called camera-ready) version.+% Change to "preprint" to generate a non-anonymous version with page numbers.+\usepackage[preprint]{acl}++% Standard package includes+\usepackage{times}+\usepackage{latexsym}++% For proper rendering and hyphenation of words containing Latin characters (including in bib files)+\usepackage[T1]{fontenc}++% This assumes your files are encoded as UTF8+\usepackage[utf8]{inputenc}++% This is not strictly necessary, and may be commented out,+% but it will improve the layout of the manuscript,+% and will typically save some space.+\usepackage{microtype}++% This is also not strictly necessary, and may be commented out.+% However, it will improve the aesthetics of text in+% the typewriter font.+\usepackage{inconsolata}++% Additional packages+\usepackage{graphicx}+\usepackage{amsmath}+\usepackage{amssymb}+\usepackage{booktabs}+\usepackage{enumitem}+\usepackage{xcolor}+\usepackage{algorithm}+\usepackage{algpseudocode}+\usepackage{pifont}+\usepackage{multirow}+\usepackage{stfloats}++% If the title and author information does not fit in the area allocated, uncomment the following+%\setlength\titlebox{<dim>}++\author{+ \textbf{Bingxi Zhao\textsuperscript{1,2}$^*$},+ \textbf{Jiahao Zhang\textsuperscript{1}$^*$},+ \textbf{Xubin Ren\textsuperscript{1}},+ \textbf{Zirui Guo\textsuperscript{1}},+ \textbf{Chao Huang\textsuperscript{1}$^\dagger$}+\\+ \textsuperscript{1}University of Hong Kong,+ \textsuperscript{2}Beijing Jiaotong University,+\\+ \small{+ \textbf{Correspondence: \{bingxizhao39, chaohuang75\}@gmail.com}+ }+}++\begin{document}+\title{DeepTutor: Tool-Augmented Personalized Tutoring System}+\maketitle++\begin{abstract}+\renewcommand{\thefootnote}{}%+\footnotetext{\hspace{-1.8em}$^*$Equal contribution.\newline $^\dagger$Corresponding author.}%+\renewcommand{\thefootnote}{\arabic{footnote}}%+\setcounter{footnote}{0}%+Education is among the most promising real-world applications of large language models (LLMs).+While current LLMs exhibit strong abilities, they rely heavily on static knowledge acquired during pre-training stages.+While current RAG systems can anchor responses in course+content, they optimize for retrieval precision rather than the adaptive,+guided explanations that effective tutoring demands.+In this paper, we present \textsc{DeepTutor}, among the first open-source agentic frameworks to unify citation-grounded problem-solving and difficulty-calibrated question generation.+These two capabilities are unified through a hybrid personalization engine that couples static knowledge grounding with a trace forest that continuously refines an evolving learner profile to customize every interaction.+To further evaluate personalized tutoring abilities, we construct TutorBench, a benchmark containing 100 KB-grounded learner profiles to perform first-person interactive assessments via profile-driven student simulator.+Generalization experiments on five standard benchmarks further show that our reasoning pipeline lifts solving accuracy by approximately 25\% on average over the backbone model across these datasets.+\textsc{DeepTutor} system with full evaluation suites are open-sourced at \url{https://github.com/HKUDS/DeepTutor/tree/eval}.++\end{abstract}++% ===== Sections =====+\input{sections/intro}+\input{sections/method}+\input{sections/experiments}+\input{sections/related-work}+\input{sections/conclusion}+\input{sections/limitation}++\section*{Acknowledgments}++% Bibliography+\bibliography{custom}++\appendix+\input{sections/appendix}++\end{document}diff --git a/paper/related_work/paper.md b/paper/related_work/paper.mdnew file mode 100644index 000000000..a0d5b9f65--- /dev/null+++ b/paper/related_work/paper.md@@ -0,0 +1,26 @@+Related Work+- Agentic Tool Use+ReAct范式奠定了agent进行多轮交互的基础。+很多工作尝试为agentic系统配备了数学工具、代码工具、网络工具、rag工具,从而实现了多样性的tool-based agentic workflow。+不过大多workflow是无状态的,无法覆盖多轮对话的场景。++LLM-based Agentic Reasoning Frameworks: A Survey from Methods to Scenarios+React: Synergizing reasoning and acting in language models+Agentic reasoning: A streamlined framework for enhancing llm reasoning with agentic tools+In-the-flow agentic system optimization for effective planning and tool use++- Personalization+有很多个性化的工作。包括多样的dialogue-based memory机制,以及RAG-based 个性化QA。然而,RAG的知识是静态的,而部分memory的工作往往停留在general的视角。not applicable。+In prospect and retrospect: Reflective memory management for long-term personalized dialogue agents+A personalized dialogue generator with implicit user persona detection+Hello again! llm-powered personalized agent for long-term dialogue+Agent workflow memory+A survey of personalization: From rag to agent+Rag-anything: All-in-one rag framework++- AI for Education+Agentic Tutroing System的研究较少。【具体例子】。有一些往往从HCI视角开展。现有的for edu的工作往往忽略了学生资料的私有性,个性化做的不好。+A systematic review of AI-driven intelligent tutoring systems (ITS) in K-12 education+Empowering personalized learning through a conversation-based tutoring system with student modeling+Llm-powered multi-agent framework for goal-oriented learning in intelligent tutoring system+Ai-tutoring in software engineering education\ No newline at end of filediff --git a/paper/sections/appendix.tex b/paper/sections/appendix.texnew file mode 100644index 000000000..ce7b91019--- /dev/null+++ b/paper/sections/appendix.tex@@ -0,0 +1,13 @@+\section{Example Appendix}+\label{sec:appendix}++This is an appendix.++\section{Worked Example: Profile Injection}+\label{sec:appendix_worked_example}++To illustrate the profile injection mechanism ($\mathcal{C}_{\text{mem}}$), consider a scenario where a beginner learner asks: ``How does backpropagation work?''.++1. \textbf{Active Trace Retrieval}: The TraceToolkit queries the trace forest using the question embedding. It retrieves a Level 1 session summary (``Learner struggled with chain rule last week'') and a Level 3 execution record (``Failed to apply chain rule in a nested function problem'').+2. \textbf{Profile Excerpting}: The planner receives $\mathcal{D}_s$ (``Topic: Calculus, Neural Networks'') and $\mathcal{D}_w$ (``Active Weakness: Chain rule application''). The writer receives $\mathcal{D}_r$ (``Self-Reflection: Learner needs step-by-step mathematical derivations before code examples'').+3. \textbf{Context Assembly}: The token budget is partitioned (e.g., 60\% for $\mathcal{C}_{\text{rag}}$ to retrieve backpropagation formulas, 40\% for $\mathcal{C}_{\text{mem}}$). The final prompt instructs the agent to explain backpropagation with a specific focus on the chain rule, providing a step-by-step derivation.diff --git a/paper/sections/conclusion.tex b/paper/sections/conclusion.texnew file mode 100644index 000000000..9045caebe--- /dev/null+++ b/paper/sections/conclusion.tex@@ -0,0 +1,6 @@+\section{Conclusion}++We presented \textsc{DeepTutor}, a tool-augmented agentic tutoring system that unifies citation-grounded problem solving, difficulty-calibrated question generation, and structured long-term memory into a closed interactive loop.+A hybrid personalization engine couples cross-modal knowledge grounding with \textit{Trace Forest}, a hierarchical memory whose specialized agents continuously distill interaction histories into an evolving learner profile, enabling bidirectional coupling where diagnosed weaknesses shape practice and learner performance refines future explanations.+We also introduced \textsc{TutorBench}, a benchmark with KB-grounded learner profiles and a first-person student simulator for interactive evaluation.+Experiments show that \textsc{DeepTutor} lifts backbone accuracy by approximately 25\% on average across five standard benchmarks while delivering substantially improved personalized tutoring.diff --git a/paper/sections/experiments.tex b/paper/sections/experiments.texnew file mode 100644index 000000000..8a6772759--- /dev/null+++ b/paper/sections/experiments.tex@@ -0,0 +1,184 @@+ % ===========================================================================+ % Section 4: Experiments+ % ===========================================================================++ \begin{figure*}[htbp!]+ \centering+ \includegraphics[width=\textwidth]{figures/data-gen-ver2.png}+ \caption{Construction pipeline of \textbf{TutorBench}. Four stages---KB Initialization, Profile Definition, Personal Profile Construction (with grounded knowledge gaps and rejection sampling), and final assembly---produce entries each containing a learner profile, knowledge gaps, an interactive task, and source references.}+ \label{fig:datagen}+ \end{figure*}+++ \section{Experiments}+ \label{sec:experiments}++ Standard NLP benchmarks evaluate factual correctness but not whether a tutor \emph{adapts} to the individual learner.+ We therefore design a three-pronged evaluation:+ \textbf{TutorBench} (\S\ref{sec:tutorbench}), a new benchmark with fine-grained learner profiles grounded in real course materials;+ a \textbf{first-person interactive evaluation} (\S\ref{sec:interactive_eval}) that simulates multi-turn tutoring and scores personalization along four rubrics;+ and a \textbf{generalization study} (\S\ref{sec:generalization}) on five standard benchmarks verifying that our structured reasoning transfers broadly.+++ % ===========================================================================+ \subsection{TutorBench: A Personalized Tutoring Benchmark}+ \label{sec:tutorbench}+ % ===========================================================================++ Existing educational benchmarks treat all test-takers as identical, missing the \emph{personalization} dimension entirely.+ We construct \textbf{TutorBench}, a benchmark in which every test case specifies a complete \emph{learner persona} with realistic knowledge gaps anchored to actual course materials, together with an interactive task.+ Figure~\ref{fig:datagen} illustrates the construction pipeline.++ \paragraph{KB Initialization.}+ University-level textbooks and research papers are indexed into the dual-representation knowledge base described in \S\ref{sec:rag}.+ A \textit{domain hierarchy} is simultaneously derived from the document structure, providing topical scaffolding for subsequent profile generation.++ \paragraph{Profile Definition.}+ Three proficiency levels---\textit{beginner}, \textit{intermediate}, and \textit{advanced}---capture qualitatively different learner states, from fundamental misconceptions to nuanced understanding.+ For each level, an LLM generates a detailed persona conditioned on the KB's content scope, including educational background and a fine-grained \emph{knowledge state} that categorizes every topic as \textit{known well}, \textit{partially known}, or \textit{unknown}.++ \paragraph{Personal Profile Construction.}+ For each profile, we sample pages from the indexed content and generate three types of \emph{grounded knowledge gaps}:+ \textbf{misconceptions} (incorrect beliefs),+ \textbf{incomplete understanding} (partial grasp with missed edge cases), and+ \textbf{missing knowledge} (never-encountered concepts).+ Each gap is anchored to specific source pages and includes both a \textit{manifestation} (how the student would exhibit the gap) and the \textit{correct understanding} for evaluation reference.++ Gaps are assembled into \textbf{interactive tasks}---each bundling at least three related gaps with a natural initial message---via rejection sampling that verifies task--gap consistency, source support, and conversational naturalness.++ \paragraph{Statistics.}+ Table~\ref{tab:tutorbench_stats} summarizes TutorBench. Each entry is a self-contained unit: a learner profile, grounded knowledge gaps, and an interactive task.++ \begin{table}[t]+ \centering+ \small+ \begin{tabular}{lc}+ \toprule+ \textbf{Statistic} & \textbf{Count} \\+ \midrule+ Knowledge Bases & \textit{TBD} \\+ Subjects / Topics & \textit{TBD} \\+ Learner Profiles & \textit{TBD} \\+ \quad -- Beginner & \textit{TBD} \\+ \quad -- Intermediate & \textit{TBD} \\+ \quad -- Advanced & \textit{TBD} \\+ Knowledge Gaps (total) & \textit{TBD} \\+ \quad -- Misconception & 30\% \\+ \quad -- Incomplete & 40\% \\+ \quad -- Missing & 30\% \\+ Interactive Tasks & \textit{TBD} \\+ Avg.\ Gaps per Task & $\geq 3$ \\+ Avg.\ Source Pages per Profile & 10 \\+ \bottomrule+ \end{tabular}+ \caption{Statistics of TutorBench. Each entry couples a learner profile with grounded knowledge gaps and an interactive task, enabling personalization-aware evaluation.}+ \label{tab:tutorbench_stats}+ \end{table}+++ % ===========================================================================+ \subsection{First-Person Interactive Evaluation}+ \label{sec:interactive_eval}+ % ===========================================================================++ Static evaluation cannot capture how a tutor \emph{steers an evolving conversation} toward resolving specific misconceptions.+ We design a \textbf{first-person interactive evaluation} in which an LLM-powered student simulator engages in multi-turn dialogue with the tutor, followed by rubric-based assessment (Figure~\ref{fig:evaluation}).++ \begin{figure}[t]+ \centering+ \includegraphics[width=\columnwidth]{figures/evaluation-ver1.png}+ \caption{First-person interactive evaluation protocol. A \textbf{Student Simulator}---initialized from a TutorBench entry with personality, first-person beliefs (encoded gaps), and a dynamic solve list---engages the tutor in multi-turn dialogue. The tutor responds with its full pipeline (solve) and generates personalized practice (quiz). All traces are recorded and assessed by four \textbf{Personalized Evaluation Rubrics}: Source Faithfulness, Average Solve Turns, Difficulty Fitted, and Gap Covered.}+ \label{fig:evaluation}+ \end{figure}++ \paragraph{Student Simulator.}+ To elicit authentic behavior, each knowledge gap is converted into a \textbf{first-person belief encoding}---e.g., a misconception becomes ``\textit{You believe that \ldots, and this feels obviously correct to you}''---preventing the LLM from being self-aware about its own ``mistakes.''+ The result is naturalistic behavior: the simulator defends misconceptions, resists premature corrections, and gradually updates understanding only after convincing explanations.+ A \textbf{gap pacing plan} schedules when each gap surfaces, and a behavioral protocol constrains the student to respond concisely and signal completion only when all gaps are addressed.++ \paragraph{Evaluation Rubrics.}+ The full session is assessed along four dimensions:++ \begin{itemize}[nosep,leftmargin=*]+ \item \textbf{Gap Covered (GC)}: fraction of knowledge gaps the tutor explicitly identified and resolved (requiring concrete correction, not casual mention).++ \item \textbf{Source Faithfulness (SF)}: per-turn score (1--5) measuring alignment with the original source material, penalizing hallucination.++ \item \textbf{Difficulty Fitted (DF)}: per-question delta ($-5$ to $+5$; $0$=ideal) reflecting difficulty calibration to the student profile; we report average absolute delta ($\downarrow$).++ \item \textbf{Gap Coverage of Practice (GP)}: score (1--5) measuring how well the generated practice set collectively covers the student's weaknesses.+ \end{itemize}++ \paragraph{Protocol.}+ For each TutorBench entry, the simulator converses with the tutor, which responds using its full pipeline.+ Upon task completion, the tutor generates five personalized practice questions, and the full transcript is scored by all four rubrics.+ Baselines: \textbf{Direct LLM} (backbone model without tools or memory) and \textbf{RAG-Tutor} (backbone with RAG retrieval but no structured reasoning or personalization).++ \paragraph{Results.}+ Table~\ref{tab:interactive_results} reports the interactive evaluation results.+ %% TODO: Fill in actual results and add analysis paragraphs.++ \begin{table}[t]+ \centering+ \small+ \begin{tabular}{lcccc}+ \toprule+ \textbf{System} & \textbf{GC}$\uparrow$ & \textbf{SF}$\uparrow$ & \textbf{DF}$\downarrow$ & \textbf{GP}$\uparrow$ \\+ \midrule+ Direct LLM & -- & -- & -- & -- \\+ RAG-Tutor & -- & -- & -- & -- \\+ \textsc{DeepTutor} & -- & -- & -- & -- \\+ \bottomrule+ \end{tabular}+ \caption{First-person interactive evaluation results. GC: Gap Covered (resolution rate, $\uparrow$); SF: Source Faithfulness (1--5, $\uparrow$); DF: Difficulty Fitted (avg.\ absolute delta, $\downarrow$); GP: Gap Coverage of Practice (1--5, $\uparrow$). %% TODO: fill in results+ }+ \label{tab:interactive_results}+ \end{table}++++\begin{table*}[!t]+\centering+\caption{General Problem-solving \textbf{pass@1 scores} across five benchmarks.+\textit{Avg~$\Delta$} mean relative improvement across benchmarks.+$^*$use the first 500 quesitons within HLE.+$^{**}$represents GPQA-diamond.+$^{***}$use live reasoning subset.+$^\dagger$GAIA scores are reported \textit{per difficulty level (L1--L3)}.}+\label{tab:generalization}+\small+\setlength{\tabcolsep}{5pt}+\begin{tabular}{l ccc cccc c c}+\toprule+& \multicolumn{3}{c}{\textbf{STEM Reasoning}} & \multicolumn{4}{c}{\textbf{General Agent (GAIA)}} & \textbf{Long Ctx} & \textbf{Enhance.} \\+\cmidrule(lr){2-4} \cmidrule(lr){5-8} \cmidrule(lr){9-9}+\textbf{Pass@1} & HLE$^*$ & GPQA-D$^{**}$ & LiveBench$^{***}$ & L1 & L2 & L3 & Overall$^\dagger$ & AA-LCR & \textit{Avg~$\Delta$} \\+\midrule+Gemini-3-Flash & 19.40 & 81.31 & 70.00 & 43.40 & 40.70 & 15.38 & 37.58 & 63.00 & \multirow{2}{*}{+29.12\%} \\+\quad+\textsc{DeepTutor} & \textbf{30.80} & \textbf{84.85} & \textbf{96.00} & \textbf{56.60} & \textbf{50.00} & \textbf{23.08} & \textbf{47.88} & \textbf{74.67} & \\+\midrule+Sonnet-4.5 & 8.40 & 72.22 & 64.33 & 37.74 & 30.23 & 7.69 & 29.09 & 53.33 & \multirow{2}{*}{+32.03\%} \\+\quad+\textsc{DeepTutor} & \textbf{14.60} & \textbf{73.23} & \textbf{82.00} & \textbf{50.94} & \textbf{48.84} & \textbf{23.08} & \textbf{45.45} & \textbf{54.00} & \\+\midrule+Qwen-3.5-plus & 16.80 & 88.38 & 69.00 & 44.23 & 35.71 & 13.64 & 33.94 & 66.00 & \multirow{2}{*}{+23.00\%} \\+\quad+\textsc{DeepTutor} & \textbf{24.20} & \textcolor{red!70!black}{87.88} & \textbf{93.00} & \textbf{50.94} & \textbf{53.49} & \textbf{32.00} & \textbf{49.09} & \textbf{69.67} & \\+\midrule+GPT-5-mini & 16.46 & 80.81 & 71.00 & 32.08 & 30.23 & 7.69 & 27.27 & 68.67 & \multirow{2}{*}{+27.11\%} \\+\quad+\textsc{DeepTutor} & \textbf{21.20} & \textcolor{red!70!black}{80.30} & \textbf{93.00} & \textbf{54.72} & \textbf{52.33} & \textbf{26.92} & \textbf{49.09} & \textbf{71.00} & \\+\midrule+Minimax-m2.5 & 14.00 & 82.83 & 59.30 & 35.29 & 22.78 & 12.00 & 23.64 & 66.00 & \multirow{2}{*}{+31.50\%} \\+\quad+\textsc{DeepTutor} & \textbf{19.40} & \textbf{83.33} & \textbf{73.00} & \textbf{52.94} & \textbf{44.30} & \textbf{32.00} & \textbf{42.42} & \textbf{76.40} & \\+\bottomrule+\end{tabular}+\end{table*}++% ===========================================================================+\subsection{General Problem-Solving}+\label{sec:generalization}+% ===========================================================================++Apart from personalized tutoring, it's also important for tutor system to demonstrate the correct and convincing answer when solving problems. Therefore, we further evaluate the general agentic reasoning abilites of \textsc{DeepTutor}. We choose five diverse model families \textit{(Claude, GPT, Gemini, Qwen, Minimax)} with five authorized benchmarks, which covers three core capabilities that is crucial for daily tutoring scenarios. For \textbf{\textit{STEM reasoning}}, we select HLE~\citep{phan2025hle}, GPQA-Diamond~\citep{rein2024gpqa} and LiveBench~\citep{white2025livebench}; for \textbf{\textit{general agentic problem-solving}}, we choose GAIA~\citep{mialon2024gaia}; for \textbf{\textit{long input processing}}, we choose AA-LCR~\citep{artificialanalysis2025lcr}.+Correctness is judged by LLM evaluator, following the benchmark-specific evaluation rubrics. More evlauation details are provided in appendix.++As shown in Table~\ref{tab:generalization}, \textsc{DeepTutor} consistently lifts backbone from \textit{+23\% to 32\%} on average, demonstrating that the system could strenghthens the general problem-solving ability while maintaining personalization-oriented designs.+\ No newline at end of filediff --git a/paper/sections/intro.tex b/paper/sections/intro.texnew file mode 100644index 000000000..dfd5da903--- /dev/null+++ b/paper/sections/intro.tex@@ -0,0 +1,33 @@+\section{Introduction}++\begin{figure}[t]+ \centering+ \includegraphics[width=\columnwidth]{figures/compare-ver1.png}+ \caption{Comparison of \textit{prior LLM products} and \textsc{DeepTutor}. Existing products provide generic answers regardless of the learner's background; \textsc{DeepTutor} adapts both problem-solving explanations and generated practice to match the student's syllabus, knowledge level, and specific weaknesses exposed during conversation.}+ \label{fig:compare}+\end{figure}++Education is among the most promising real-world applications of large language models (LLMs).+An effective human tutor does far more than supply correct answers--they diagnose misconceptions, scaffold explanations to the learner's level, and continuously pose targeted practice that turns weaknesses into strengths \citep{letourneau2025systematicreviewaidriven}.+While LLMs exhibit impressive fluency in educational dialogues, replicating this tightly integrated set of pedagogical skills within a unified, adaptive system remains an open challenge \citep{chu-etal-2025-llm}.++Existing approaches tackle fragments of this challenge in isolation. As illustrated in Figure~\ref{fig:compare}, the question generation of existing LLM systems rarely calibrates difficulty to the individual learner. Though SOTA LLMs demonstrate strong STEM reasoning abilities, they often tend to solve the question in a general way as they were trained.+Question generation, on the other hand, often fails to fit the student's syllabus.+Personalized educational platforms track coarse skill inventories rather than the fine-grained reasoning traces that reveal \textit{how} a student errs.+Meanwhile, retrieval-augmented generation (RAG) often lacks consideration for the adaptive, guided explanations that effective tutoring demands.++We argue that the missing ingredient is a \textit{closed interactive loop}: weaknesses exposed during problem solving should directly shape which questions are generated next, while the learner's performance on those questions should, in turn, refine the model that informs future explanations.+This requires operationalizing personalization into measurable mechanisms, such as calibrating question difficulty based on diagnosed weaknesses and adapting explanation depth to the learner's proficiency.+Realizing such a loop requires (i)~a structured memory that captures fine-grained interaction histories rather than scalar skill scores, and (ii)~a unified tutoring system whose modules share and continuously update that memory.++To address these problems, we propose \textsc{DeepTutor} that unifies both problem solving and question generation within a hybrid personalization framework.+For problem solving, we utilize an \textit{investigation--solving--writing} pipeline that decomposes complex queries, executes multi-step tool-augmented reasoning, and synthesizes citation-grounded explanations.+For question generation, a \textit{critic-guided generate--validate loop} iteratively proposes and verifies difficulty-calibrated practice items.+Moreover, both pipelines are unified through a hybrid personalization engine that couples static knowledge grounding with \textit{trace forest}, a dynamic structured memory that records multi-resolution interaction traces and employs specialized memory agents to continuously refine an evolving learner profile---creating the closed tutoring cycle where every interaction personalizes the next.++Our main contributions are as follows:+\begin{itemize}[nosep,leftmargin=*]+ \item We propose \textsc{DeepTutor}, an agentic tutoring framework that, to the best of our knowledge, is among the first to unify tool-augmented problem solving, critic-guided question generation, and long-term structured memory into a closed interactive loop.+ \item We introduce \textit{trace forest}, a hierarchical memory architecture in which specialized agents collaboratively maintain a fine-grained, evolving learner model from multi-resolution interaction traces.+ \item We construct \textsc{TutorBench}, a benchmark of 100 knowledge-base-grounded learner profiles paired with a student simulator for first-person interactive evaluation. Experiments on TutorBench and five standard reasoning benchmarks show that \textsc{DeepTutor} substantially outperforms various baselines, providing insights for the future shape of personalized tutoring systems.+\end{itemize}diff --git a/paper/sections/limitation.tex b/paper/sections/limitation.texnew file mode 100644index 000000000..7f4a81394--- /dev/null+++ b/paper/sections/limitation.tex@@ -0,0 +1,6 @@+\section*{Limitations}++Our interactive evaluation relies on LLM-powered student simulators and rubric assessors, which may not fully capture real learner behaviors such as affective states or idiosyncratic reasoning; validation with human learners in authentic classrooms remains important future work.+The multi-stage pipeline issues multiple LLM calls per interaction, incurring latency and cost that may challenge real-time deployment in resource-constrained settings.+Additionally, the trace forest grows monotonically and may require periodic pruning for very long-term engagements, and the system's performance ceiling is ultimately bounded by the backbone model's capabilities.+Finally, our automated evaluation applies exact-match criteria for numerical answers without tolerance for rounding differences, which may understate effective accuracy in certain cases.diff --git a/paper/sections/method.tex b/paper/sections/method.texnew file mode 100644index 000000000..09cb6fa4f--- /dev/null+++ b/paper/sections/method.tex@@ -0,0 +1,185 @@+\section{Method}+\label{sec:method}++\begin{figure*}[t]+ \centering+ \includegraphics[width=\textwidth]{figures/full-pipe-ver7.png}+ \caption{Overview of \textsc{DeepTutor}. The system unifies two task pipelines through a Hybrid Personalization layer. \textbf{Static Knowledge Grounding} (center) constructs multi-modal knowledge graphs and vector databases from course materials, enabling mixed graph--embedding retrieval. \textbf{Dynamic Personal Memory} (bottom) maintains a trace forest accessible via a programmatic \emph{TraceToolkit}, and distills interaction histories into three evolving profile dimensions. \textbf{Personalized Problem Solving} (left) proceeds through Investigation~(\ding{172}), Step-by-step Solving~(\ding{173}), and Iterative Writing~(\ding{174}). \textbf{Personalized Question Generation} (right) proceeds via Idea Generation~(\ding{175}) and a Critic-Guided Q-A Pair Generation loop~(\ding{176}). Both pipelines record interaction traces that continuously refine the learner profile, forming a closed tutoring cycle.}+ \label{fig:overview}+\end{figure*}++DeepTutor is built around two sub-pipes with a common personalization engine, as shown in figure~\ref{fig:overview}.+The \textit{Hybrid Personalization Engine} (\S\ref{sec:personalization}) couples a static knowledge grounding---multi-modal knowledge graphs and vector databases built from course materials---with a dynamic memory that maintains an evolving learner profile.+Building upon this substrate, the \textit{problem-solving pipeline} (\S\ref{sec:solve}) produces citation-grounded explanations through three stages, while the \textit{question-generation pipeline} (\S\ref{sec:generate}) produces difficulty-calibrated practice items.+Each completed interaction feeds back into the learner profile, creating a closed tutoring cycle (\S\ref{sec:system}).++% ===========================================================================+\subsection{Preliminaries}+\label{sec:prelim}+% ===========================================================================++\paragraph{Task Formulation.}+DeepTutor addresses two complementary tutoring tasks:+(i)~\emph{problem solving}, producing a citation-grounded explanation $a$ for a learner question $q$, calibrated to the student's proficiency; and+(ii)~\emph{question generation}, producing customized practice items for a topic $\tau$ that target the learner's specific gaps.+Both tasks share the personalization substrate described below.++\paragraph{Notation.}+Course materials are indexed into a knowledge base $\mathcal{K}$ with dual representations for structured and semantic retrieval (\S\ref{sec:rag}).+The system maintains a learner profile $\mathcal{D} = (\mathcal{D}_s, \mathcal{D}_w, \mathcal{D}_r)$ capturing interaction summaries, diagnosed weaknesses, and tutor self-reflections, continuously updated by specialized memory agents (\S\ref{sec:memory}).+Before every agent step, a personalization context $\mathcal{C}_{\text{mem}}$ is assembled from $\mathcal{D}$ and the trace forest (the latter queried via a dedicated \emph{TraceToolkit}), yielding a compact, role-specific excerpt that steers the agent's behavior (\S\ref{sec:injection}).++Algorithm~\ref{alg:loop} gives a unified view of the full tutoring cycle.+Each session begins with profile injection and mixed retrieval, then branches into either problem solving (\ding{172}--\ding{174}) or question generation (\ding{175}--\ding{176}).+The resulting interaction trace is appended to the trace forest and used to update the learner profile.++\begin{algorithm}[t]+\caption{Closed-Loop Personalized Tutoring}\label{alg:loop}+\small+\begin{algorithmic}[1]+\Require learner profile $\mathcal{D}^{(0)}$;\; trace forest $\mathcal{F}^{(0)} = \emptyset$+\For{session $j = 1, 2, \ldots$}+ \State $\mathcal{C}_{\text{mem}} \gets \Call{ProfileInject}{\mathcal{D}^{(j{-}1)}, \mathcal{F}^{(j{-}1)}, \text{task}_j}$+ \State $\mathcal{C}_{\text{rag}} \gets \textsc{RagTool}(\text{task}_j)$+ \If{$\text{task}_j = (\textsc{Solve},\, q)$}+ \State $\mathcal{P}{=}\langle s_1,\dots,s_K\rangle \gets \Call{Plan}{q,\;\mathcal{C}_{\text{rag}},\;\mathcal{C}_{\text{mem}}}$ \Comment{\ding{172}}+ \For{$k = 1$ \textbf{to} $K$} \Comment{\ding{173}}+ \While{$s_k$ not resolved}+ \State $(\alpha_t,\, \mathbf{s}_t) \gets \Call{ToolAgent}{q, \mathcal{P}, \mathcal{S}, \mathcal{C}_{\text{mem}}}$+ \State $\mathcal{S} \gets \mathcal{S} \cup \{\mathbf{s}_t\}$+ \If{$\alpha_t = \textsc{Replan}$}+ \State $\mathcal{P} \gets \Call{Revise}{\mathcal{P}, \mathcal{S}}$+ \EndIf+ \EndWhile+ \State $\mathcal{S} \gets \Call{Compress}{\mathcal{S}, k}$+ \EndFor+ \State $a \gets \Call{IterativeWrite}{\mathcal{S},\;\mathcal{C}_{\text{mem}}}$ \Comment{\ding{174}}+ \State $T_j \gets \Call{BuildTrace}{q, a}$+ \Else \Comment{$\text{task}_j = (\textsc{Generate},\, \tau)$}+ \State $\mathcal{I} \gets \Call{IdeaAgent}{\tau,\;\mathcal{C}_{\text{rag}},\;\mathcal{C}_{\text{mem}}}$ \Comment{\ding{175}}+ \State $\mathcal{T}_{1..N} \gets \Call{TopKSelect}{\mathcal{I}}$+ \For{$i = 1$ \textbf{to} $N$} \Comment{\ding{176}}+ \Repeat+ \State $(q_i, a_i) \gets \Call{Generator}{\mathcal{T}_i,\;\mathcal{C}_{\text{rag}},\;\mathcal{C}_{\text{mem}}}$+ \State $(\textit{pass}, f_i) \gets \Call{Validator}{q_i, a_i, \mathcal{T}_i}$+ \If{$\lnot\,\textit{pass}$} $\mathcal{T}_i \gets \Call{Revise}{\mathcal{T}_i, f_i}$+ \EndIf+ \Until{\textit{pass}}+ \EndFor+ \State $T_j \gets \Call{BuildTrace}{\tau, \{(q_i, a_i)\}}$+ \EndIf+ \State $\mathcal{F}^{(j)} \gets \mathcal{F}^{(j{-}1)} \cup \{T_j\}$+ \State $\mathcal{D}^{(j)} \gets \Call{MemoryUpdate}{\mathcal{D}^{(j{-}1)}, T_j}$+\EndFor+\end{algorithmic}+\end{algorithm}++% ===========================================================================+\subsection{Hybrid Personalization Engine}+\label{sec:personalization}+% ===========================================================================++Both the solver and the generator require two types of knowledge: \emph{domain expertise} and \emph{learner awareness}. DeepTutor provides the former through Static Knowledge Grounding and the latter through Dynamic Memory, unified by a Profile Injection mechanism that delivers tailored context to each specific stage.++\subsubsection{Static Knowledge Grounding}+\label{sec:rag}++Real-world course materials are inherently multimodal: textbooks interleave prose with figures, equations, and data tables, each encoding domain knowledge that is difficult to faithfully flatten into plain text.+To preserve this richness, we perform multimodal knowledge unification, decomposing source documents into atomic content units $\{c_j=(t_j, x_j)\}$, where $t_j\!\in\!\{\text{text}, \text{image}, \text{table}, \text{equation}\}$ denotes the modality and $x_j$ the raw payload~\cite{wang2024mineruopensourcesolutionprecise}.+Dedicated extractors handle each modality so as to retain its internal structure: figures keep their captions, equations stay anchored to surrounding definitions, and tables preserve header--cell relationships.++The resulting units are indexed through a dual-graph construction: a cross-modal KG grounds non-textual units within their contextual neighborhood via entity and relation extraction, while a text-based KG captures fine-grained semantic relationships from prose~\cite{guo2025raganythingallinoneragframework}.+The two graphs are merged through entity alignment into a unified knowledge graph $\mathcal{G}=(\mathcal{V},\mathcal{E})$ that encodes both cross-modal associations and textual semantics.+In parallel, dense encoders map all content units into modality-specific vector stores (a text VDB and a multi-modal VDB), unified into a combined embedding index $\mathcal{B}$.+Together, $\mathcal{G}$ and $\mathcal{B}$ form the complete retrieval index over the knowledge base $\mathcal{K}$.++At query time, we introduce cross-modal hybrid retrieval that operates over both indices in parallel: graph-based retrieval traverses $\mathcal{G}$ to capture explicit relationships and multi-hop reasoning paths, while embedding-based retrieval searches $\mathcal{B}$ to surface semantically relevant content beyond the graph's structural coverage.+The resulting candidate sets are merged via reciprocal rank fusion, scoring each passage $d$ as $\textstyle\sum_{r}{1}/({k+\mathrm{rank}_r(d)})$, where $k$ is a smoothing constant~\citep{cormack2009reciprocal}.+Retrieved passages are deduplicated and truncated to a context budget before injection as domain grounding $\mathcal{C}_{\text{rag}}$.++\subsubsection{Dynamic Personal Memory}+\label{sec:memory}++While the knowledge base captures \emph{what the course materials contain}, the dynamic personal memory captures \emph{how the individual learner has engaged with them}.+We further propose \textit{Trace Forest}, a structured memory $\mathcal{F} = \{T_1, T_2, \ldots\}$ in which each tree $T_j = (V_j, E_j)$ records one complete tutoring interaction as a multi-resolution, semantically searchable artifact.+Every node $v \in V_j$ is a triple $(\texttt{type}, \texttt{content}, \mathbf{e}_v)$ where \texttt{type} identifies the granularity level, \texttt{content} stores the payload, and $\mathbf{e}_v$ is a dense embedding, forming a three-level hierarchy. \textit{Level~1} captures the session-level input and a global summary; \textit{Level~2} records intermediate planning units produced by task decomposition; and \textit{Level~3} stores fine-grained execution records including tool invocations, evidence, and validation outcomes.+The concrete node types at each level are task-specific and detailed alongside the respective pipelines (\S\ref{sec:solve}, \S\ref{sec:generate}).++Rather than treating the forest as a passive data store, we expose it to all pipeline agents through a programmatic \emph{TraceToolkit} with three operations: \textsc{SearchTrace} embeds a query and retrieves the most relevant nodes across $\mathcal{F}$ via cosine similarity-based ANN search using a shared encoder; \textsc{ListTraces} enumerates traces filtered by time range, task type, or topic; and \textsc{ReadNodes} fetches the full content of specific nodes along with their ancestry path.+This interface lets each agent actively explore the learner's history with their specific demands, from coarse session summaries at Level~1 to fine-grained reasoning steps at Level~3.++\paragraph{Profile Construction.}+\label{sec:injection}+Raw traces must be interpreted into actionable tutoring signals.+We introduce three specialized memory agents to process each new trace tree $T_j$ in parallel, incrementally updating a dedicated dimension of the learner profile $\mathcal{D}$:+\begin{itemize}[nosep,leftmargin=*]+\item Session History $ \mathcal{D}_s$: distills topics covered and performance trends. This will record what has happened, providing general session memories.+\item User Weakness $\mathcal{D}_w$: compares learner responses against reference solutions, labeling each weakness as active or resolved to maintain a prioritized gap inventory, emphasizing where to focus.+\item Self-Reflection $\mathcal{D}_r$: critiques the system's own prior outputs for pedagogical alignment, producing actionable improvement notes, indicating how to improve.+\end{itemize}+Each agent receives the new trace along with its current profile dimension and produces an updated version through incremental revision. To prevent error accumulation, this process employs a \textit{confidence-gated update} mechanism, where state transitions (e.g., marking a weakness as resolved) require explicit evidence grounding, preserving long-term trends while incorporating recent signals.++Before each agent step, the system assembles a personalization context $\mathcal{C}_{\text{mem}}$ through two channels:+(i)~\emph{active trace retrieval} via the TraceToolkit, retrieving the top-$k$ most relevant nodes with $k$ allocated proportionally across levels to balance broad session context with fine-grained precedents;+(ii)~\emph{profile excerpting}, where role-specific slices of $\mathcal{D}$ are drawn based on the requesting agent's function to decouple their attention (e.g., the planner receives $\mathcal{D}_s$ and $\mathcal{D}_w$; the writer receives $\mathcal{D}_r$; generation agents receive $\mathcal{D}_w$ alongside historical question patterns). The total token budget is dynamically partitioned between $\mathcal{C}_{\text{rag}}$ and $\mathcal{C}_{\text{mem}}$ (see Appendix for a worked example).++% ===========================================================================+\subsection{Personalized Problem-Solving}+\label{sec:solve}+% ===========================================================================++Prior tool-augmented agents~\citep{yao2023reactsynergizingreasoningacting, chen2026iterresearch} pack planning, retrieval, and exposition into a full reasoning loop.+This suffices for short factoid queries but becomes a bottleneck in tutoring, where thorough investigation and personalized presentation compete for the same context budget.+DeepTutor disentangles them into three incremental stages (\ding{172}--\ding{174} in Algorithm~\ref{alg:loop}), guided by \textit{scaffolding theory} to provide step-by-step cognitive support.++\paragraph{Stage \ding{172}: Personalized Investigation.}+The planner decomposes $q$ into several meta-questions and launches a multi-source investigation: it retrieves relevant passages from $\mathcal{K}$ via the RAG tool, consults the trace forest via the trace toolkit for precedents from similar past interactions, and invokes auxiliary toolkits as needed.+Jointly conditioning on the assembled domain context $\mathcal{C}_{\text{rag}}$ and the learner context $\mathcal{C}_{\text{mem}}$, the planner produces a solving plan $\mathcal{P} = \langle s_1, \ldots, s_K \rangle$ of concrete sub-goals, each annotated with its step-level goal and a brief description.+A shared scratchpad $\mathcal{S}$ accumulates all subsequent reasoning artifacts.+Investigating before planning prevents sub-goals that are too vague or redundant with what the learner already understands (e.g., generating ``review chain rule in trigonometry'' rather than a vague ``review calculus'').++\paragraph{Stage \ding{173}: Step-by-step Problem Solving.}+Each sub-goal $s_k$ is executed through a ReAct-style loop, ~\citep{yao2023reactsynergizingreasoningacting}, conditioned on both the domain grounding $\mathcal{C}_{\text{rag}}$ and the learner context $\mathcal{C}_{\text{mem}}$.+At every iteration the tool agent produces a reasoning trace $r_t$, selects an action $\alpha_t$ from a shared tool suite $\mathcal{A}$ (encompassing knowledge-base retrieval, trace-forest lookup, sandboxed code execution, web search, and deep reasoning), observes the output $o_t$, and records a \emph{self-note} $n_t$.+Unlike the reasoning trace, which captures the full deliberation process, the self-note distills the step's outcome into a concise takeaway (e.g., ``retrieved formula confirmed'') that subsequent steps can reference without re-reading verbose intermediates.+When the current plan proves inadequate, the agent triggers \emph{adaptive replanning}, revising remaining sub-goals while preserving completed work.++Hierarchical compression (line 14 in Algorithm~\ref{alg:loop}) prevents the scratchpad from exceeding the model's context window.+Once sub-goal $s_k$ is resolved, an LLM-based summarizer distills its full trace into a compact digest that retains key conclusions and evidence pointers while discarding verbose intermediate steps.+As the plan advances, earlier sub-goals are represented by increasingly concise digests, freeing context capacity for deeper reasoning on later sub-goals.++\paragraph{Stage \ding{174}: Evidence-based Iterative Writing.}+Rather than concatenating raw tool outputs, the writing stage extracts structured evidence bundles from the scratchpad and constructs the answer through successive draft-refine iterations, reconciling potentially conflicting findings.+The learner context $\mathcal{C}_{\text{mem}}$+% ---including diagnosed weaknesses from $\mathcal{D}_w$ and the system's pedagogical self-reflections from $\mathcal{D}_r$---+steers both the depth and the tone of the explanation within the learner's \textit{Zone of Proximal Development}: \textit{beginners} receive step-by-step derivations with scaffolding, while \textit{proficient learners} receive focused summaries that foreground key insights.+Every claim is grounded with traceable citations back to $\mathcal{K}$.++% ===========================================================================+\subsection{Personalized Question Generation}+\label{sec:generate}+% ===========================================================================++A tutor must also pose the right questions: ones that are meaningful, factually grounded, and calibrated to the individual learner.+We propose a two-stage architecture (\ding{175}--\ding{176} in Algorithm~\ref{alg:loop}) that separates \emph{what to ask} from \emph{how to ask and verify}.++\paragraph{Stage \ding{175}: Personalized Idea Generation.}+Rather than generating questions directly from a bare topic, DeepTutor first maps the conceptual landscape around $\tau$ through the lens of the individual learner.+The idea agent jointly conditions on domain knowledge $\mathcal{C}_{\text{rag}}$ and learner context $\mathcal{C}_{\text{mem}}$---including past mistakes, difficulty trends, and related problems surfaced via the TraceToolkit---to synthesize a diverse pool of candidate ideas, each characterized by a target concept, a question format (MCQ, written-response, or coding), and a personalized rationale grounded in the learner's diagnosed gaps.+A two-stage selection then filters ill-formed or redundant candidates and ranks survivors along quality dimensions such as clarity, relevance, and diversity, yielding structured question templates $\{\mathcal{T}_i\}$ that serve as blueprints for the subsequent generation stage.++\paragraph{Stage \ding{176}: Critic-Guided Q-A Pair Generation.}+For each template $\mathcal{T}_i$, a \textbf{generator} produces a complete question--answer--explanation triple $(q_i, a_i, e_i)$, drawing on $\mathcal{C}_{\text{rag}}$ for factual grounding and $\mathcal{C}_{\text{mem}}$ to calibrate difficulty and phrasing to the learner's level.+A structurally separated \textbf{validator} then challenges the output through two-level quality assurance: an LLM-based reasoning check evaluates template alignment, factual correctness, and pedagogical soundness, while computational questions undergo additional verification via sandboxed code execution.+This dual-agent separation is critical: because the validator shares no reasoning chain with the generator, it must independently verify correctness, catching errors that self-evaluation would miss.+Failed pairs receive structured diagnostic feedback $f_i$; the template is revised and the pair regenerated until both pedagogical and factual constraints are satisfied.++% ===========================================================================+\subsection{Closed-Loop Tutoring Cycle}+\label{sec:system}+% ===========================================================================++As shown in Algorithm~\ref{alg:loop}, the components above form a self-reinforcing cycle.+After each task, whether a problem-solving session or a question-generation episode, the pipeline records a new trace tree $T_j$ into the trace forest $\mathcal{F}$, and the three memory agents update the learner profile in parallel, producing $\mathcal{D}^{(j)}$ that immediately informs subsequent interactions.+The key property is \textbf{bidirectional task coupling}, which operationalizes \textit{formative assessment}: weaknesses diagnosed during problem solving propagate to $\mathcal{D}_w$ and directly shape which questions are generated next; conversely, the learner's performance on generated questions refines $\mathcal{D}_s$ and $\mathcal{D}_r$, improving future explanations.+Because every agent can actively query the trace forest through the TraceToolkit, this feedback is not limited to profile-level summaries: agents can retrieve fine-grained precedents from any prior interaction, enabling increasingly nuanced personalization as the interaction history grows.diff --git a/paper/sections/related-work.tex b/paper/sections/related-work.texnew file mode 100644index 000000000..8b606cae4--- /dev/null+++ b/paper/sections/related-work.tex@@ -0,0 +1,11 @@+\section{Related Work}+\label{sec:related}++\paragraph{Agentic Tool Use.}+ReAct \citep{yao2023reactsynergizingreasoningacting} introduced interleaved reasoning and action for tool-augmented LLMs, inspiring planning-and-tool workflows \citep{zhao2025llmbasedagenticreasoningframeworks,wu-etal-2025-agentic,li2025intheflowagenticoptimizationeffective}. These frameworks target short-horizon tasks without persistent learner state. DeepTutor extends tool-based agentic reasoning to stateful tutoring by coupling solving, generation, and memory.++\paragraph{Personalization and Memory.}+LLM personalization spans dialogue memory \citep{tan-etal-2025-prospect,li-etal-2025-hello,cho-etal-2022-personalized}, RAG-style adaptation \citep{li2025surveypersonalizationragagent,guo2025raganythingallinoneragframework}, and reusable workflow induction \citep{wang2024agentworkflowmemory}. Unlike traditional knowledge tracing (e.g., BKT, DKT) that maintains scalar skill scores, DeepTutor introduces Trace Forest, an event-driven structured memory that provides interpretable, multi-resolution records of learner-specific weaknesses and historical traces.++\paragraph{AI for Education.}+While classic intelligent tutoring systems (ITS) like Cognitive Tutor rely on hard-coded rules, recent LLM-based works improve personalization through conversational tutoring \citep{park2024empoweringpersonalizedlearning} and multi-agent paths \citep{wang2025llmpoweredmultiagentframeworkgoaloriented}. However, they typically rely on prompt-level adaptation without unifying solve/generate/memory loops. DeepTutor integrates tool-based reasoning, structured long-term memory, and bidirectional task coupling within a single architecture.diff --git a/src/agents/base_agent.py b/src/agents/base_agent.pyindex db2802239..68b640e6e 100644--- a/src/agents/base_agent.py+++ b/src/agents/base_agent.py@@ -423,6 +423,7 @@ class BaseAgent(ABC):api_key=self.api_key,base_url=self.base_url,api_version=self.api_version,+ binding=self.binding,max_retries=max_retries,**kwargs,)@@ -522,6 +523,7 @@ class BaseAgent(ABC):api_key=self.api_key,base_url=self.base_url,api_version=self.api_version,+ binding=self.binding,messages=messages,**kwargs,):diff --git a/src/agents/question/README.md b/src/agents/question/README.mdindex 02ab2c623..62292e16d 100644--- a/src/agents/question/README.md+++ b/src/agents/question/README.md@@ -1,409 +1,121 @@-# Question Generation System+# Question Module (Refactored)-Intelligent question generation system with **modular agent architecture** supporting both knowledge base-driven custom generation and reference exam paper mimicking.+`src/agents/question` 已重构为**双循环架构**,用于统一处理:-## 📁 Directory Structure+- 主题驱动出题(topic + preference)+- 试卷驱动出题(PDF/已解析试卷)-```-question/-├── __init__.py # Module exports-├── agents/ # Specialized agents-│ ├── __init__.py-│ ├── retrieve_agent.py # Knowledge retrieval from KB-│ ├── generate_agent.py # Question generation-│ └── relevance_analyzer.py # Question-KB relevance analysis-├── prompts/ # Bilingual prompts (YAML)-│ ├── zh/ # Chinese prompts-│ │ ├── retrieve_agent.yaml-│ │ ├── generate_agent.yaml-│ │ ├── relevance_analyzer.yaml-│ │ └── coordinator.yaml-│ └── en/ # English prompts-│ └── (same structure)-├── coordinator.py # Workflow orchestration-├── example.py # Usage examples-└── README.md+## 1. 目录结构-# Tools moved to src/tools/question/-src/tools/question/+```text+src/agents/question/├── __init__.py-├── pdf_parser.py # PDF parsing with MinerU-├── question_extractor.py # Extract questions from exams-└── exam_mimic.py # Reference-based question generation-```--## 🚀 Core Features--### Custom Mode (Knowledge Base-Driven)-- ✅ **Intelligent Search Query Generation** - Generates configurable number of RAG queries-- ✅ **Background Knowledge Acquisition** - Retrieves relevant knowledge using RAG-- ✅ **Question Planning** - Creates comprehensive plan with question IDs and focuses-- ✅ **Single-Pass Relevance Analysis** - Analyzes question relevance (no iteration/rejection)-- ✅ **Complete File Persistence** - Saves knowledge, plan, and individual results--### Mimic Mode (Reference Exam-Based)-- ✅ **PDF Parsing** - Automatic PDF extraction using MinerU-- ✅ **Question Extraction** - Identifies and extracts reference questions from exams-- ✅ **Style Mimicking** - Generates similar questions based on reference structure-- ✅ **Batch Organization** - All outputs saved to timestamped folders--### Common Features-- ✅ **Unified BaseAgent** - All agents inherit from `src/agents/base_agent.py`-- ✅ **No Iteration Loops** - Single-pass generation + analysis-- ✅ **Bilingual Prompts** - Supports both Chinese and English via YAML-- ✅ **Real-time WebSocket Streaming** - Live progress updates to frontend--## System Architecture--### Modular Agent Architecture--```-User Requirement- ↓-┌─────────────────────────────────────────────────┐-│ AgentCoordinator │-│ │-│ 1. RetrieveAgent │-│ ├── Generate RAG queries (LLM) │-│ └── Execute RAG searches (parallel) │-│ │-│ 2. Plan Generation (in coordinator) │-│ └── Create focuses for each question │-│ │-│ 3. GenerateAgent (per question) │-│ └── Generate question from knowledge+focus │-│ │-│ 4. RelevanceAnalyzer (per question) │-│ └── Analyze KB relevance (high/partial) │-│ │-└─────────────────────────────────────────────────┘- ↓-Save Results:- - knowledge.json (queries + retrievals)- - plan.json (focuses)- - q_1/result.json, q_1/question.md- - q_2/result.json, q_2/question.md- - summary.json-```--### Mimic Mode Architecture--```-PDF Upload / Parsed Directory- ↓-Parse PDF with MinerU (tools/pdf_parser.py)- ↓-Extract Reference Questions (tools/question_extractor.py)- ↓-For each reference question (parallel):- AgentCoordinator.generate_question(with_reference=True)- ├── RetrieveAgent- ├── GenerateAgent (with reference)- └── RelevanceAnalyzer- ↓-Save to timestamped folder-```--## Core Components--### 1. RetrieveAgent--Located in `agents/retrieve_agent.py`. Inherits from `src/agents/base_agent.py`.--**Responsibilities:**-- Generate semantic search queries from requirements-- Execute RAG searches in parallel-- Merge and summarize retrieval results--```python-retrieve_agent = RetrieveAgent(kb_name="math2211", language="en")-result = await retrieve_agent.process(requirement, num_queries=3)-# Returns: {"queries": [...], "retrievals": [...], "summary": "...", "has_content": True}-```--### 2. GenerateAgent--Located in `agents/generate_agent.py`. Generates questions based on knowledge context.--**Responsibilities:**-- Generate custom questions from requirements + knowledge-- Generate mimic questions from reference + knowledge-- Output structured question JSON--```python-generate_agent = GenerateAgent(language="en")-result = await generate_agent.process(- requirement={"knowledge_point": "...", "difficulty": "medium"},- knowledge_context="...",- focus={"focus": "...", "type": "written"},- reference_question=None # or "reference text" for mimic mode-)-# Returns: {"success": True, "question": {...}}-```--### 3. RelevanceAnalyzer--Located in `agents/relevance_analyzer.py`. Replaces old validation workflow.--**Key difference from old ValidationWorkflow:**-- **NO rejection**: all questions are accepted-- **NO iteration**: single-pass analysis-- Output: relevance level (high/partial) with explanations--```python-analyzer = RelevanceAnalyzer(language="en")-result = await analyzer.process(question={"question": "..."}, knowledge_context="...")-# Returns: {"relevance": "high", "kb_coverage": "...", "extension_points": ""}-```--### 4. AgentCoordinator--Located in `coordinator.py`. Orchestrates the workflow using specialized agents.--**Methods:**-- `generate_question()`: Single question generation (used by Mimic mode)-- `generate_questions_custom()`: Batch generation from requirement--## Usage--### Custom Mode - Batch Generation--```python-import asyncio-from src.agents.question import AgentCoordinator--async def main():- coordinator = AgentCoordinator(- kb_name="math2211",- output_dir="data/user/question",- language="en"- )-- result = await coordinator.generate_questions_custom(- requirement={- "knowledge_point": "Multivariable limits",- "difficulty": "medium",- "question_type": "choice"- },- num_questions=3- )-- print(f"✅ Generated {result['completed']}/{result['requested']} questions")- for r in result['results']:- print(f"- [{r['analysis']['relevance']}] {r['question']['question'][:50]}...")--asyncio.run(main())-```--### Custom Mode - Single Question--```python-requirement = {- "knowledge_point": "Limits and continuity",- "difficulty": "medium",- "question_type": "choice"-}--result = await coordinator.generate_question(requirement)--if result["success"]:- print(f"Question: {result['question']['question']}")- print(f"Relevance: {result['validation']['relevance']}")- print(f"KB Coverage: {result['validation']['kb_coverage']}")-```--### Mimic Mode - PDF Upload--```python-from src.tools.question import mimic_exam_questions--result = await mimic_exam_questions(- pdf_path="exams/midterm.pdf",- kb_name="math2211",- output_dir="data/user/question/mimic_papers",- max_questions=5-)--print(f"✅ Generated {result['successful_generations']} questions")-```--### Mimic Mode - Parsed Directory--```python-result = await mimic_exam_questions(- paper_dir="data/parsed_exams/exam_20240101",- kb_name="math2211"-)-```--## Configuration--### `config/main.yaml`+├── coordinator.py+├── models.py+├── cli.py+├── agents/+│ ├── idea_agent.py+│ ├── evaluator.py+│ ├── generator.py+│ └── validator.py+└── prompts/+ ├── en/+ │ ├── idea_agent.yaml+ │ ├── evaluator.yaml+ │ ├── generator.yaml+ │ └── validator.yaml+ └── zh/+ ├── idea_agent.yaml+ ├── evaluator.yaml+ ├── generator.yaml+ └── validator.yaml+```++## 2. 架构概览++### 路径 1:Topic 模式++1. `IdeaAgent` 基于 topic/preference + RAG 生成候选出题创意+2. `Evaluator` 对创意打分并给反馈,必要时继续下一轮+3. 产出 top-k `QuestionTemplate`+4. 对每个 template 进入生成-验证循环:+ - `Generator` 生成 Q-A(可用 `rag_tool` / `web_search` / `write_code`)+ - `Validator` approve/reject,不通过则反馈重生++### 路径 2:Mimic 模式++1. PDF 先经 MinerU 解析(或直接使用已解析目录)+2. 提取参考题(question extractor)+3. 参考题映射为 `QuestionTemplate`+4. 进入与 topic 模式相同的生成-验证循环++## 3. 核心数据模型++定义在 `models.py`:++- `QuestionTemplate`:统一中间表示+ - `question_id`+ - `concentration`+ - `question_type`+ - `difficulty`+ - `source` (`custom`/`mimic`)+- `QAPair`:最终生成结果+ - `question`+ - `correct_answer`+ - `explanation`+ - `validation`++## 4. Coordinator 入口++`AgentCoordinator` 提供两个主入口:++- `generate_from_topic(user_topic, preference, num_questions)`+- `generate_from_exam(exam_paper_path, max_questions, paper_mode)`++## 5. 配置项(main.yaml)```yamlquestion:- # Refactored: no iteration loops (max_rounds removed)rag_query_count: 3max_parallel_questions: 1rag_mode: naive- agents:- retrieve:- top_k: 30- generate:- max_retries: 2- relevance_analyzer:- enabled: true-```--### `config/agents.yaml`--```yaml-question:- temperature: 0.7- max_tokens: 4000-```--## Return Format--### Single Question Result--```python-{- "success": True,- "question": {- "question_type": "choice",- "question": "Question content",- "options": {"A": "...", "B": "...", "C": "...", "D": "..."},- "correct_answer": "A",- "explanation": "Detailed explanation",- "knowledge_point": "Topic name"- },- "validation": {- "decision": "approve", # Always approve- "relevance": "high", # or "partial"- "kb_coverage": "This question tests...",- "extension_points": "" # Only if relevance is "partial"- },- "rounds": 1 # Always 1 (no iteration)-}+ idea_loop:+ max_rounds: 3+ ideas_per_round: 5+ generation:+ max_retries: 2+ tools:+ web_search: true+ rag_tool: true+ write_code: true```-### Batch Generation Result--```python-{- "success": True,- "requested": 3,- "completed": 3,- "failed": 0,- "search_queries": ["query1", "query2", "query3"],- "plan": {"focuses": [...]},- "results": [- {- "question_id": "q_1",- "focus": {"focus": "...", "type": "written"},- "question": {...},- "analysis": {"relevance": "high", "kb_coverage": "..."}- },- ...- ],- "failures": []-}-```+## 6. 命令行交互测试-## Output Files+新增脚本:`src/agents/question/cli.py`-### Custom Mode Directory Structure+从项目根目录运行:+```bash+python src/agents/question/cli.py```-data/user/question/batch_YYYYMMDD_HHMMSS/-├── knowledge.json # RAG queries and retrievals-├── plan.json # Question focuses-├── q_1/-│ ├── result.json # Question + analysis-│ └── question.md # Human-readable format-├── q_2/-│ ├── result.json-│ └── question.md-└── summary.json # Overall summary-```--### Mimic Mode Directory Structure--```-data/user/question/mimic_papers/{paper_name}/-├── auto/{paper_name}.md # MinerU parsed markdown-├── {paper_name}_YYYYMMDD_HHMMSS_questions.json # Extracted reference questions-└── {paper_name}_YYYYMMDD_HHMMSS_generated.json # Generated questions-```--## Key Changes from Previous Version--### ✅ Architecture Changes-1. **Unified BaseAgent**- - All agents now inherit from `src/agents/base_agent.py`- - Automatic LLM config, prompt loading, token tracking- - No more separate ReAct base class+支持:-2. **Specialized Agents**- - `RetrieveAgent`: Knowledge retrieval only- - `GenerateAgent`: Question generation only- - `RelevanceAnalyzer`: Relevance analysis only (replaces ValidationWorkflow)+- 交互式 Topic 模式测试+- 交互式 Mimic 模式测试(upload/parsed)+- 输出摘要(completed/failed)与题目预览-3. **No Iteration/Rejection**- - Removed `max_rounds` from config- - Single-pass generation + analysis- - All questions accepted with relevance classification+## 7. 相关工具模块-4. **Tools Moved**- - `src/agents/question/tools/` → `src/tools/question/`- - Import via `from src.tools.question import ...`+工具位于 `src/tools/question/`:-### ❌ Removed+- `pdf_parser.py`+- `question_extractor.py`+- `exam_mimic.py`(薄封装,委托 coordinator)-1. **Old ReAct Architecture**- - `agents/base_agent.py` (ReAct paradigm)- - `agents/generation_agent.py` (ReAct-based)- - `agents/validation_agent.py` (deprecated)- - `validation_workflow.py` (replaced by RelevanceAnalyzer)+## 8. 注意事项-2. **Iteration Logic**- - No more validation loops- - No more task rejection- - No more request_modification/request_regeneration--3. **Message Queue**- - Agent communication simplified- - Direct method calls instead of message passing--## Migration Notes--**Import Path Updates:**--```python-# Old-from src.agents.question import BaseAgent, QuestionGenerationAgent-from src.tools.question import mimic_exam_questions--# New-from src.agents.question import RetrieveAgent, GenerateAgent, RelevanceAnalyzer-from src.tools.question import mimic_exam_questions-```--**API Changes:**--```python-# Old - with rejection handling-result = await coordinator.generate_question(requirement)-if result.get("error") == "task_rejected":- print("Agent rejected task")--# New - always generates, check relevance-result = await coordinator.generate_question(requirement)-if result["success"]:- if result["validation"]["relevance"] == "high":- print("Fully covered by KB:", result["validation"]["kb_coverage"])- else:- print("Extension question:", result["validation"]["extension_points"])-```+- 旧版 `retrieve_agent / generate_agent / relevance_analyzer` 已移除+- 旧版 prompt 文件已移除+- 旧文档中的旧接口(如 `generate_questions_custom`)不再适用diff --git a/src/agents/question/__init__.py b/src/agents/question/__init__.pyindex 3dc8e3680..927fd2f38 100644--- a/src/agents/question/__init__.py+++ b/src/agents/question/__init__.py@@ -1,11 +1,10 @@"""Question Generation System-Modular question generation using specialized agents:-- RetrieveAgent: Knowledge base retrieval-- GenerateAgent: Question generation-- RelevanceAnalyzer: Question-KB relevance analysis-- AgentCoordinator: Workflow orchestration+Refactored dual-loop architecture:+- Idea loop: IdeaAgent <-> Evaluator+- Generation loop: Generator <-> Validator+- AgentCoordinator: End-to-end orchestration for topic and exam pathsTools (moved to src/tools/question):- parse_pdf_with_mineru@@ -13,12 +12,16 @@ Tools (moved to src/tools/question):- mimic_exam_questions"""-from .agents import GenerateAgent, RelevanceAnalyzer, RetrieveAgent+from .agents import Evaluator, Generator, IdeaAgent, Validatorfrom .coordinator import AgentCoordinator+from .models import QAPair, QuestionTemplate__all__ = [- "RetrieveAgent",- "GenerateAgent",- "RelevanceAnalyzer",+ "IdeaAgent",+ "Evaluator",+ "Generator",+ "Validator",+ "QuestionTemplate",+ "QAPair","AgentCoordinator",]diff --git a/src/agents/question/agents/__init__.py b/src/agents/question/agents/__init__.pyindex e70106fa2..a467205cd 100644--- a/src/agents/question/agents/__init__.py+++ b/src/agents/question/agents/__init__.py@@ -2,17 +2,20 @@Question Generation AgentsSpecialized agents for question generation workflow:-- RetrieveAgent: Knowledge retrieval from KB-- GenerateAgent: Question generation-- RelevanceAnalyzer: Question-KB relevance analysis+- IdeaAgent: Topic-driven idea generation+- Evaluator: Idea scoring and top-k selection+- Generator: Q-A generation with tools+- Validator: Approval/reject loop with feedback"""-from .generate_agent import GenerateAgent-from .relevance_analyzer import RelevanceAnalyzer-from .retrieve_agent import RetrieveAgent+from .evaluator import Evaluator+from .generator import Generator+from .idea_agent import IdeaAgent+from .validator import Validator__all__ = [- "RetrieveAgent",- "GenerateAgent",- "RelevanceAnalyzer",+ "IdeaAgent",+ "Evaluator",+ "Generator",+ "Validator",]diff --git a/src/agents/question/agents/evaluator.py b/src/agents/question/agents/evaluator.pynew file mode 100644index 000000000..6474b2fa2--- /dev/null+++ b/src/agents/question/agents/evaluator.py@@ -0,0 +1,197 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+Evaluator - Score idea candidates and select top-k templates.+"""++from __future__ import annotations++import json+from typing import Any++from src.agents.base_agent import BaseAgent+from src.agents.question.models import QuestionTemplate++VALID_QUESTION_TYPES = {"choice", "written", "coding"}+++class Evaluator(BaseAgent):+ """+ Evaluate idea quality/diversity and decide whether to continue idea loop.+ """++ def __init__(self, language: str = "en", **kwargs: Any) -> None:+ super().__init__(+ module_name="question",+ agent_name="evaluator",+ language=language,+ **kwargs,+ )++ async def process(+ self,+ user_topic: str,+ preference: str,+ ideas: list[dict[str, Any]],+ top_k: int,+ current_round: int,+ max_rounds: int,+ target_difficulty: str = "",+ target_question_type: str = "",+ ) -> dict[str, Any]:+ """+ Return either feedback (continue) or selected templates (stop).+ """+ system_prompt = self.get_prompt("system", "")+ evaluate_prompt = self.get_prompt("evaluate_ideas", "")+ if not evaluate_prompt:+ evaluate_prompt = (+ "Topic: {user_topic}\n"+ "Preference: {preference}\n"+ "Round: {current_round}/{max_rounds}\n"+ "Ideas:\n{ideas_json}\n\n"+ 'Return JSON {"continue_loop": bool, "feedback": "...", "selected_ideas":[...]}'+ )++ constraints: list[str] = []+ if target_difficulty:+ constraints.append(f"Target difficulty: {target_difficulty}")+ if target_question_type:+ constraints.append(f"Target question type: {target_question_type}")+ effective_preference = preference or "(none)"+ if constraints:+ effective_preference = f"{effective_preference}\n" + "\n".join(constraints)++ user_prompt = evaluate_prompt.format(+ user_topic=user_topic,+ preference=effective_preference,+ current_round=current_round,+ max_rounds=max_rounds,+ top_k=top_k,+ ideas_json=json.dumps(ideas, ensure_ascii=False, indent=2),+ )++ parsed = await self._evaluate_with_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt or "",+ ideas=ideas,+ top_k=top_k,+ )++ continue_loop = bool(parsed.get("continue_loop", False))+ feedback = str(parsed.get("feedback", "")).strip()++ invalid_types = self._find_invalid_question_types(ideas)+ if invalid_types and current_round < max_rounds:+ continue_loop = True+ fixes = ", ".join(f'{k} (was "{v}")' for k, v in invalid_types)+ type_feedback = (+ "Invalid question_type detected — only 'choice', 'written', 'coding' are allowed. "+ f"Please fix: {fixes}."+ )+ feedback = f"{type_feedback} {feedback}".strip()+ self.logger.warning(f"Evaluator flagged invalid question types: {invalid_types}")++ if current_round >= max_rounds:+ continue_loop = False++ selected_ideas = parsed.get("selected_ideas", [])+ if not isinstance(selected_ideas, list):+ selected_ideas = []++ if not selected_ideas:+ selected_ideas = self._fallback_select(ideas=ideas, top_k=top_k)++ templates = self._ideas_to_templates(selected_ideas, top_k=top_k)+ return {+ "continue_loop": continue_loop,+ "feedback": feedback,+ "templates": templates,+ "selected_ideas": selected_ideas[:top_k],+ "scores": parsed.get("scores", []),+ }++ async def _evaluate_with_llm(+ self,+ user_prompt: str,+ system_prompt: str,+ ideas: list[dict[str, Any]],+ top_k: int,+ ) -> dict[str, Any]:+ try:+ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ temperature=0.2,+ stage="evaluate_idea_candidates",+ )+ payload = json.loads(response)+ if isinstance(payload, dict):+ return payload+ except Exception as exc:+ self.logger.warning(f"Evaluator parse failed, fallback used: {exc}")+ return {+ "continue_loop": False,+ "feedback": "",+ "selected_ideas": self._fallback_select(ideas=ideas, top_k=top_k),+ "scores": [],+ }++ @staticmethod+ def _find_invalid_question_types(ideas: list[dict[str, Any]]) -> list[tuple[str, str]]:+ """Return list of (idea_id, bad_type) for ideas with illegal question_type."""+ bad: list[tuple[str, str]] = []+ for idea in ideas:+ if not isinstance(idea, dict):+ continue+ qt = str(idea.get("question_type", "")).strip().lower()+ if qt and qt not in VALID_QUESTION_TYPES:+ bad.append((idea.get("idea_id", "unknown"), qt))+ return bad++ def _fallback_select(self, ideas: list[dict[str, Any]], top_k: int) -> list[dict[str, Any]]:+ valid = [idea for idea in ideas if isinstance(idea, dict) and idea.get("concentration")]+ return valid[:top_k]++ def _ideas_to_templates(+ self,+ selected_ideas: list[dict[str, Any]],+ top_k: int,+ ) -> list[QuestionTemplate]:+ templates: list[QuestionTemplate] = []+ for idx, item in enumerate(selected_ideas[:top_k], 1):+ if not isinstance(item, dict):+ continue+ concentration = str(item.get("concentration", "")).strip()+ if not concentration:+ continue+ raw_type = str(item.get("question_type", "written")).strip().lower()+ question_type = raw_type if raw_type in VALID_QUESTION_TYPES else "written"+ templates.append(+ QuestionTemplate(+ question_id=f"q_{idx}",+ concentration=concentration,+ question_type=question_type,+ difficulty=str(item.get("difficulty", "medium")).strip() or "medium",+ source="custom",+ metadata={+ "idea_id": item.get("idea_id", f"idea_{idx}"),+ "rationale": item.get("rationale", ""),+ },+ )+ )++ # Ensure enough templates for downstream generation+ if len(templates) < top_k:+ for idx in range(len(templates) + 1, top_k + 1):+ templates.append(+ QuestionTemplate(+ question_id=f"q_{idx}",+ concentration=f"Aspect {idx}",+ question_type="written",+ difficulty="medium",+ source="custom",+ )+ )+ return templatesdiff --git a/src/agents/question/agents/generate_agent.py b/src/agents/question/agents/generate_agent.pydeleted file mode 100644index dcd00d752..000000000--- a/src/agents/question/agents/generate_agent.py+++ /dev/null@@ -1,403 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-GenerateAgent - Responsible for generating questions based on knowledge context.--Uses unified BaseAgent for LLM calls and configuration management.-"""--import json-import re-from typing import Any--from src.agents.base_agent import BaseAgent---class GenerateAgent(BaseAgent):- """- Agent responsible for generating questions from knowledge context.-- Responsibilities:- - Generate questions based on requirements and knowledge- - Support both custom mode (from scratch) and mimic mode (from reference)- - Output structured question JSON- """-- def __init__(- self,- language: str = "en",- **kwargs,- ):- """- Initialize GenerateAgent.-- Args:- language: Language for prompts ("en" or "zh")- **kwargs: Additional arguments passed to BaseAgent- """- super().__init__(- module_name="question",- agent_name="generate_agent",- language=language,- **kwargs,- )-- async def process(- self,- requirement: dict[str, Any],- knowledge_context: str,- focus: dict[str, Any] | None = None,- reference_question: str | None = None,- ) -> dict[str, Any]:- """- Main processing: generate a question.-- Args:- requirement: Question requirement dict (knowledge_point, difficulty, question_type, etc.)- knowledge_context: Retrieved knowledge summary- focus: Optional focus/angle for the question- reference_question: Optional reference question for mimic mode-- Returns:- Dict with:- - success: Whether generation succeeded- - question: Generated question dict (if success)- - error: Error message (if failed)- """- self.logger.info("Starting question generation")-- # Build requirements string- requirements_str = json.dumps(requirement, ensure_ascii=False, indent=2)-- # Build focus string- if focus:- focus_str = f"Focus: {focus.get('focus', '')}\nType: {focus.get('type', requirement.get('question_type', 'written'))}"- else:- focus_str = f"Type: {requirement.get('question_type', 'written')}"-- # Choose prompt based on mode- if reference_question:- # Mimic mode- return await self._generate_with_reference(- requirements_str=requirements_str,- knowledge_context=knowledge_context,- reference_question=reference_question,- )- else:- # Custom mode- return await self._generate_custom(- requirements_str=requirements_str,- knowledge_context=knowledge_context,- focus_str=focus_str,- knowledge_point=requirement.get("knowledge_point", ""),- )-- def _get_user_preference(self) -> str:- """Get user preference from personalization service."""- try:- from src.personalization.service import get_personalization_service-- service = get_personalization_service()- preference = service.get_preference_for_prompt()- return preference if preference else "(No user preference recorded)"- except Exception as e:- self.logger.debug(f"Failed to get user preference: {e}")- return "(No user preference recorded)"-- async def _generate_custom(- self,- requirements_str: str,- knowledge_context: str,- focus_str: str,- knowledge_point: str,- ) -> dict[str, Any]:- """- Generate a custom question (not based on reference).-- Args:- requirements_str: JSON string of requirements- knowledge_context: Retrieved knowledge summary- focus_str: Focus/angle description- knowledge_point: Main knowledge point-- Returns:- Dict with success status and question/error- """- system_prompt = self.get_prompt("system", "")- user_prompt_template = self.get_prompt("generate", "")-- if not user_prompt_template:- # Fallback prompt- user_prompt_template = (- "Generate a question based on:\n"- "User Preference: {preference}\n"- "Requirements: {requirements}\n"- "Focus: {focus}\n"- "Knowledge: {knowledge}\n\n"- "Return JSON with question_type, question, correct_answer, explanation."- )-- # Get user preference- preference = self._get_user_preference()-- user_prompt = user_prompt_template.format(- preference=preference,- requirements=requirements_str,- focus=focus_str,- knowledge=knowledge_context[:4000]- if len(knowledge_context) > 4000- else knowledge_context,- )-- try:- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- response_format={"type": "json_object"},- stage="generate_question",- )-- question = self._parse_question_response(response)- question["knowledge_point"] = knowledge_point-- self.logger.info(f"Generated {question.get('question_type', 'unknown')} question")-- return {- "success": True,- "question": question,- }-- except Exception as e:- self.logger.error(f"Question generation failed: {e}")- return {- "success": False,- "error": str(e),- }-- async def _generate_with_reference(- self,- requirements_str: str,- knowledge_context: str,- reference_question: str,- ) -> dict[str, Any]:- """- Generate a question based on a reference (mimic mode).-- Args:- requirements_str: JSON string of requirements- knowledge_context: Retrieved knowledge summary- reference_question: Reference question text-- Returns:- Dict with success status and question/error- """- system_prompt = self.get_prompt("system", "")- user_prompt_template = self.get_prompt("generate_with_reference", "")-- if not user_prompt_template:- # Fallback prompt- user_prompt_template = (- "Generate a new question inspired by the reference but distinct:\n"- "User Preference: {preference}\n"- "Reference: {reference_question}\n"- "Requirements: {requirements}\n"- "Knowledge: {knowledge}\n\n"- "Return JSON with question_type, question, correct_answer, explanation."- )-- # Get user preference- preference = self._get_user_preference()-- user_prompt = user_prompt_template.format(- preference=preference,- reference_question=reference_question,- requirements=requirements_str,- knowledge=knowledge_context[:4000]- if len(knowledge_context) > 4000- else knowledge_context,- )-- try:- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- response_format={"type": "json_object"},- stage="generate_with_reference",- )-- question = self._parse_question_response(response)-- self.logger.info(f"Generated mimic {question.get('question_type', 'unknown')} question")-- return {- "success": True,- "question": question,- }-- except Exception as e:- self.logger.error(f"Reference-based generation failed: {e}")- return {- "success": False,- "error": str(e),- }-- def _parse_question_response(self, response: str) -> dict[str, Any]:- """- Parse LLM response into question dict.-- Uses robust JSON extraction that handles:- - Markdown code blocks- - Control characters in LaTeX formulas- - Python triple-quoted strings- - Partial JSON extraction-- Args:- response: LLM response string-- Returns:- Parsed question dict-- Raises:- ValueError: If parsing fails- """- if not response or not response.strip():- raise ValueError("LLM returned empty response")-- # Try to extract JSON from markdown code blocks if present- json_content = self._extract_json_from_markdown(response)-- # Clean control characters that may break JSON parsing- json_content = self._clean_json_string(json_content)-- # Try multiple parsing strategies- question = None- parse_error = None-- # Strategy 1: Direct parse- try:- question = json.loads(json_content)- except json.JSONDecodeError as e:- parse_error = e-- # Strategy 2: Try extracting JSON object pattern- if question is None:- json_obj_pattern = re.compile(r"\{[\s\S]*\}")- match = json_obj_pattern.search(json_content)- if match:- try:- question = json.loads(match.group(0))- except json.JSONDecodeError:- pass-- # Strategy 3: Try fixing common LLM JSON issues- if question is None:- try:- fixed_content = self._fix_common_json_issues(json_content)- question = json.loads(fixed_content)- except json.JSONDecodeError:- pass-- if question is None:- raise ValueError(f"Failed to parse question JSON: {parse_error}") from parse_error-- # Validate required fields- if "question" not in question:- raise ValueError("Question response missing 'question' field")-- # Ensure question_type exists- if "question_type" not in question:- question["question_type"] = "written"-- # Validate options for choice questions- if question.get("question_type") == "choice":- options = question.get("options")- if not options:- # Create default options if missing- self.logger.warning("Choice question missing options, adding placeholder")- question["options"] = {- "A": "Option A (placeholder)",- "B": "Option B (placeholder)",- "C": "Option C (placeholder)",- "D": "Option D (placeholder)",- }- elif not isinstance(options, dict):- # Convert to dict if it's a list or other format- self.logger.warning(f"Options is not a dict: {type(options)}, converting")- if isinstance(options, list):- question["options"] = {- chr(65 + i): str(opt) for i, opt in enumerate(options[:4])- }- else:- question["options"] = {"A": str(options)}- elif len(options) < 2:- self.logger.warning(f"Choice question has only {len(options)} options")-- return question-- def _clean_json_string(self, json_str: str) -> str:- """- Clean JSON string by removing/escaping problematic characters.-- Handles:- - Control characters (0x00-0x1f except tab, newline, carriage return)- - Unescaped newlines inside string values- """- if not json_str:- return json_str-- # Remove most control characters but keep \t, \n, \r- # These can appear in LLM output and break JSON parsing- cleaned = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", json_str)-- return cleaned-- def _fix_common_json_issues(self, content: str) -> str:- """- Attempt to fix common JSON issues from LLM output.-- Fixes:- - Python triple-quoted strings converted to JSON strings- - Trailing commas before closing braces/brackets- """- if not content:- return content-- # Fix Python triple-quoted strings (LLMs sometimes generate these)- def replace_triple_quotes(match: re.Match) -> str:- inner = match.group(1)- # Use json.dumps to properly escape the content- return json.dumps(inner)-- content = re.sub(r'"""([\s\S]*?)"""', replace_triple_quotes, content)-- # Remove trailing commas before } or ]- content = re.sub(r",\s*([}\]])", r"\1", content)-- return content-- def _extract_json_from_markdown(self, content: str) -> str:- """- Extract JSON from markdown code blocks.-- LLMs often wrap JSON in ```json ... ``` blocks. This method strips- the markdown formatting and any surrounding text.-- Args:- content: Raw LLM response-- Returns:- Extracted JSON string- """- if not content:- return content-- # Try to find JSON code block- json_block_pattern = r"```(?:json)?\s*\n?(.*?)```"- matches = re.findall(json_block_pattern, content, re.DOTALL)-- if matches:- # Return the content inside the first code block- return matches[0].strip()-- # If no code blocks found, return as-is (might already be valid JSON)- return content.strip()diff --git a/src/agents/question/agents/generator.py b/src/agents/question/agents/generator.pynew file mode 100644index 000000000..04ff148b1--- /dev/null+++ b/src/agents/question/agents/generator.py@@ -0,0 +1,345 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+Generator - Generate Q-A pairs from QuestionTemplate with dynamic tool selection.++The Generator uses a two-step process:+1. Plan which tools to use (LLM-driven decision)+2. Execute only the planned tools and generate the Q-A pair+"""++from __future__ import annotations++import asyncio+import json+import re+from typing import Any++from src.agents.base_agent import BaseAgent+from src.agents.question.models import QAPair, QuestionTemplate+from src.tools.code_executor import run_code+from src.tools.rag_tool import rag_search+from src.tools.web_search import web_search+++class Generator(BaseAgent):+ """+ Generate a question/answer pair with LLM-driven tool selection.++ Instead of always calling all tools, the Generator first asks the LLM+ which tools would be helpful for the given template, then only executes+ those tools before generating the final Q-A pair.+ """++ def __init__(+ self,+ kb_name: str | None = None,+ rag_mode: str = "naive",+ language: str = "en",+ tool_flags: dict[str, bool] | None = None,+ **kwargs: Any,+ ) -> None:+ super().__init__(+ module_name="question",+ agent_name="generator",+ language=language,+ **kwargs,+ )+ self.kb_name = kb_name+ self.rag_mode = rag_mode+ self.tool_flags = tool_flags or {}++ async def process(+ self,+ template: QuestionTemplate,+ user_topic: str = "",+ preference: str = "",+ validator_feedback: str = "",+ ) -> QAPair:+ """+ Generate one Q-A pair from a template.++ Flow:+ 1. Ask LLM which tools to use (plan_tools)+ 2. Execute only the planned tools+ 3. Generate the Q-A pair with tool context+ 4. Optionally run verification code if the plan included write_code+ """+ # Step 1: Plan tools+ tool_plan = await self._plan_tools(template, user_topic, preference)++ # Step 2: Execute planned tools+ tool_context = await self._execute_tools(template, user_topic, tool_plan)++ # Step 3: Generate Q-A pair+ payload = await self._generate_payload(+ template=template,+ user_topic=user_topic,+ preference=preference,+ validator_feedback=validator_feedback,+ tool_context=tool_context,+ )++ # Step 4: Optionally verify with code (only if planned)+ code_result: dict[str, Any] = {}+ if tool_plan.get("use_code") and payload.get("verification_code"):+ code_result = await self._execute_verification_code(+ payload["verification_code"]+ )++ return QAPair(+ question_id=template.question_id,+ question=payload.get("question", ""),+ correct_answer=payload.get("correct_answer", ""),+ explanation=payload.get("explanation", ""),+ question_type=payload.get("question_type", template.question_type),+ options=(+ payload.get("options")+ if isinstance(payload.get("options"), dict)+ else None+ ),+ concentration=template.concentration,+ difficulty=template.difficulty,+ metadata={+ "source": template.source,+ "reference_question": template.reference_question,+ "tool_plan": tool_plan,+ "tool_context_keys": [k for k, v in tool_context.items() if v],+ "code_result": code_result,+ "verification_code": payload.get("verification_code", ""),+ "validator_feedback": validator_feedback,+ },+ )++ # ------------------------------------------------------------------+ # Step 1: Tool Planning+ # ------------------------------------------------------------------++ async def _plan_tools(+ self,+ template: QuestionTemplate,+ user_topic: str,+ preference: str,+ ) -> dict[str, Any]:+ """Ask LLM which tools to use for this specific template."""+ plan_prompt_template = self.get_prompt("plan_tools", "")+ if not plan_prompt_template:+ # No prompt available — fall back to conservative defaults+ return self._default_tool_plan()++ try:+ prompt = plan_prompt_template.format(+ template=json.dumps(template.__dict__, ensure_ascii=False, indent=2),+ user_topic=user_topic,+ preference=preference or "(none)",+ available_tools=self._describe_available_tools(),+ )++ response = await self.call_llm(+ user_prompt=prompt,+ system_prompt=self.get_prompt("system", "") or "",+ response_format={"type": "json_object"},+ stage="generator_plan_tools",+ )+ plan = self._parse_json_like(response)++ # Respect config-level tool flags (config can disable tools globally)+ plan["use_rag"] = bool(plan.get("use_rag", True)) and self.tool_flags.get(+ "rag_tool", True+ )+ plan["use_web"] = bool(+ plan.get("use_web", False)+ ) and self.tool_flags.get("web_search", True)+ plan["use_code"] = bool(+ plan.get("use_code", False)+ ) and self.tool_flags.get("write_code", True)+ return plan++ except Exception as exc:+ self.logger.warning(f"Tool planning failed, using defaults: {exc}")+ return self._default_tool_plan()++ def _default_tool_plan(self) -> dict[str, Any]:+ """Conservative default: only RAG if available."""+ return {+ "use_rag": self.tool_flags.get("rag_tool", True),+ "use_web": False,+ "use_code": False,+ "reasoning": "default plan (no LLM planning)",+ }++ def _describe_available_tools(self) -> str:+ tools: list[str] = []+ if self.tool_flags.get("rag_tool", True):+ tools.append(+ "rag_tool: Retrieve relevant knowledge from the course knowledge base. "+ "Useful for factual, conceptual, and curriculum-aligned questions."+ )+ if self.tool_flags.get("web_search", True):+ tools.append(+ "web_search: Search the web for up-to-date or supplementary information. "+ "Useful when the topic requires current data, real-world examples, or goes beyond the KB."+ )+ if self.tool_flags.get("write_code", True):+ tools.append(+ "write_code: Execute Python code to compute or verify answers. "+ "Useful for coding questions, mathematical computations, and algorithm verification."+ )+ return "\n".join(f"- {t}" for t in tools) or "(no tools available)"++ # ------------------------------------------------------------------+ # Step 2: Execute Tools+ # ------------------------------------------------------------------++ async def _execute_tools(+ self,+ template: QuestionTemplate,+ user_topic: str,+ tool_plan: dict[str, Any],+ ) -> dict[str, str]:+ """Execute only the tools chosen by the tool plan."""+ context: dict[str, str] = {}++ if tool_plan.get("use_rag"):+ try:+ query = (+ tool_plan.get("rag_query")+ or template.concentration+ or user_topic+ )+ rag_result = await rag_search(+ query=query,+ kb_name=self.kb_name,+ mode=self.rag_mode,+ only_need_context=True,+ )+ context["rag"] = (rag_result.get("answer", "") or "")[:4000]+ except Exception as exc:+ self.logger.warning(f"RAG tool failed: {exc}")++ if tool_plan.get("use_web"):+ try:+ query = (+ tool_plan.get("web_query")+ or template.concentration+ or user_topic+ )+ # web_search is synchronous — run in thread to avoid blocking+ web_result = await asyncio.to_thread(web_search, query=query)+ context["web"] = (web_result.get("answer", "") or "")[:2000]+ except Exception as exc:+ self.logger.warning(f"Web search tool failed: {exc}")++ return context++ # ------------------------------------------------------------------+ # Step 3: Generate Q-A Pair+ # ------------------------------------------------------------------++ async def _generate_payload(+ self,+ template: QuestionTemplate,+ user_topic: str,+ preference: str,+ validator_feedback: str,+ tool_context: dict[str, str],+ ) -> dict[str, Any]:+ system_prompt = self.get_prompt("system", "")+ user_prompt_template = self.get_prompt("generate", "")+ if not user_prompt_template:+ user_prompt_template = (+ "Template: {template}\n"+ "User topic: {user_topic}\n"+ "Preference: {preference}\n"+ "Validator feedback: {validator_feedback}\n"+ "Tool context: {tool_context}\n\n"+ 'Return JSON {{"question_type":"","question":"","options":{{}},"correct_answer":"","explanation":"","verification_code":""}}'+ )++ # Build a concise tool context description+ tool_summary = {}+ if tool_context.get("rag"):+ tool_summary["rag_knowledge"] = tool_context["rag"]+ if tool_context.get("web"):+ tool_summary["web_results"] = tool_context["web"]+ if not tool_summary:+ tool_summary["note"] = "No external tool context was used for this question."++ user_prompt = user_prompt_template.format(+ template=json.dumps(template.__dict__, ensure_ascii=False, indent=2),+ user_topic=user_topic,+ preference=preference or "(none)",+ validator_feedback=validator_feedback or "(none)",+ tool_context=json.dumps(tool_summary, ensure_ascii=False, indent=2),+ )++ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt or "",+ response_format={"type": "json_object"},+ stage="generator_build_qa",+ )+ payload = self._parse_json_like(response)++ if "question" not in payload or not str(payload.get("question", "")).strip():+ payload["question"] = (+ f"Based on {template.concentration}, answer this {template.difficulty} "+ f"{template.question_type} question."+ )+ if "correct_answer" not in payload:+ payload["correct_answer"] = "N/A"+ if "explanation" not in payload:+ payload["explanation"] = "N/A"+ if "question_type" not in payload:+ payload["question_type"] = template.question_type++ return payload++ # ------------------------------------------------------------------+ # Step 4: Optional Code Verification+ # ------------------------------------------------------------------++ async def _execute_verification_code(self, code: str) -> dict[str, Any]:+ if not code or not isinstance(code, str):+ return {}+ try:+ result = await run_code(language="python", code=code, timeout=10)+ return {+ "stdout": (result.get("stdout", "") or "")[:800],+ "stderr": (result.get("stderr", "") or "")[:800],+ "exit_code": result.get("exit_code", -1),+ }+ except Exception as exc:+ self.logger.warning(f"write_code tool failed: {exc}")+ return {"stderr": str(exc), "exit_code": -1}++ # ------------------------------------------------------------------+ # Helpers+ # ------------------------------------------------------------------++ @staticmethod+ def _parse_json_like(content: str) -> dict[str, Any]:+ if not content or not content.strip():+ return {}++ cleaned = re.sub(+ r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", content.strip()+ )+ block_match = re.search(r"```(?:json)?\s*(.*?)```", cleaned, re.DOTALL)+ if block_match:+ cleaned = block_match.group(1).strip()++ try:+ payload = json.loads(cleaned)+ return payload if isinstance(payload, dict) else {}+ except Exception:+ pass++ obj_match = re.search(r"\{[\s\S]*\}", cleaned)+ if obj_match:+ try:+ payload = json.loads(obj_match.group(0))+ return payload if isinstance(payload, dict) else {}+ except Exception:+ return {}+ return {}diff --git a/src/agents/question/agents/idea_agent.py b/src/agents/question/agents/idea_agent.pynew file mode 100644index 000000000..85fb93a80--- /dev/null+++ b/src/agents/question/agents/idea_agent.py@@ -0,0 +1,250 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+IdeaAgent - Generate candidate question directions from topic and preference.+"""++from __future__ import annotations++import json+from typing import Any++from src.agents.base_agent import BaseAgent+from src.tools.rag_tool import rag_search+++class IdeaAgent(BaseAgent):+ """+ Generate candidate question ideas with knowledge grounding.+ """++ def __init__(+ self,+ kb_name: str | None = None,+ rag_mode: str = "naive",+ enable_rag: bool = True,+ language: str = "en",+ **kwargs: Any,+ ) -> None:+ super().__init__(+ module_name="question",+ agent_name="idea_agent",+ language=language,+ **kwargs,+ )+ self.kb_name = kb_name+ self.rag_mode = rag_mode+ self.enable_rag = enable_rag++ async def process(+ self,+ user_topic: str,+ preference: str = "",+ evaluator_feedback: str = "",+ num_ideas: int = 5,+ target_difficulty: str = "",+ target_question_type: str = "",+ ) -> dict[str, Any]:+ """+ Build grounded candidate ideas for evaluator ranking.+ """+ if self.enable_rag and self.kb_name:+ queries = await self._generate_rag_queries(user_topic=user_topic, num_queries=3)+ retrievals = await self._retrieve_context(queries)+ raw_context = self._build_context(retrievals)+ knowledge_context = await self._aggregate_context(+ user_topic=user_topic, raw_context=raw_context+ )+ else:+ queries = []+ retrievals = []+ raw_context = "Retrieval disabled."+ knowledge_context = raw_context+ ideas = await self._generate_ideas(+ user_topic=user_topic,+ preference=preference,+ evaluator_feedback=evaluator_feedback,+ knowledge_context=knowledge_context,+ num_ideas=num_ideas,+ target_difficulty=target_difficulty,+ target_question_type=target_question_type,+ )+ return {+ "ideas": ideas,+ "queries": queries,+ "retrievals": retrievals,+ "raw_context": raw_context,+ "knowledge_context": knowledge_context,+ }++ async def _generate_rag_queries(self, user_topic: str, num_queries: int) -> list[str]:+ system_prompt = self.get_prompt("system", "")+ query_prompt = self.get_prompt("generate_queries", "")+ if not query_prompt:+ query_prompt = (+ "Generate {num_queries} concise knowledge search queries for topic:\n"+ "{user_topic}\n"+ 'Return JSON: {"queries":["..."]}'+ )++ user_prompt = query_prompt.format(+ user_topic=user_topic,+ num_queries=num_queries,+ )+ try:+ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt or "",+ response_format={"type": "json_object"},+ stage="idea_generate_queries",+ )+ payload = json.loads(response)+ queries = payload.get("queries", [])+ if not isinstance(queries, list):+ queries = []+ clean = [q.strip() for q in queries if isinstance(q, str) and q.strip()]+ return clean[:num_queries] or [user_topic]+ except Exception as exc:+ self.logger.warning(f"Failed generating queries, fallback to topic: {exc}")+ return [user_topic]++ async def _retrieve_context(self, queries: list[str]) -> list[dict[str, Any]]:+ retrievals: list[dict[str, Any]] = []+ for query in queries:+ try:+ result = await rag_search(+ query=query,+ kb_name=self.kb_name,+ mode=self.rag_mode,+ only_need_context=True,+ )+ retrievals.append(+ {+ "query": query,+ "answer": result.get("answer", ""),+ "mode": result.get("mode", self.rag_mode),+ }+ )+ except Exception as exc:+ self.logger.warning(f"RAG retrieval failed for query '{query}': {exc}")+ retrievals.append({"query": query, "answer": "", "error": str(exc)})+ return retrievals++ def _build_context(self, retrievals: list[dict[str, Any]]) -> str:+ sections: list[str] = []+ for item in retrievals:+ answer = item.get("answer", "")+ if not answer:+ continue+ clipped = answer[:2000] + ("...[truncated]" if len(answer) > 2000 else "")+ sections.append(f"=== Query: {item.get('query','')} ===\n{clipped}")+ return "\n\n".join(sections) if sections else "No retrieval context available."++ async def _aggregate_context(self, user_topic: str, raw_context: str) -> str:+ if not raw_context or raw_context == "No retrieval context available.":+ return raw_context++ system_prompt = self.get_prompt("system", "")+ agg_prompt = self.get_prompt("aggregate_context", "")+ if not agg_prompt:+ return raw_context++ user_prompt = agg_prompt.format(user_topic=user_topic, raw_context=raw_context)+ try:+ aggregated = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt or "",+ stage="idea_aggregate_context",+ )+ return aggregated.strip() if aggregated.strip() else raw_context+ except Exception as exc:+ self.logger.warning(f"Context aggregation failed, using raw context: {exc}")+ return raw_context++ async def _generate_ideas(+ self,+ user_topic: str,+ preference: str,+ evaluator_feedback: str,+ knowledge_context: str,+ num_ideas: int,+ target_difficulty: str = "",+ target_question_type: str = "",+ ) -> list[dict[str, Any]]:+ system_prompt = self.get_prompt("system", "")+ idea_prompt = self.get_prompt("generate_ideas", "")+ if not idea_prompt:+ idea_prompt = (+ "Topic: {user_topic}\n"+ "Preference: {preference}\n"+ "Evaluator feedback: {evaluator_feedback}\n"+ "Knowledge context:\n{knowledge_context}\n\n"+ "Generate {num_ideas} candidate question ideas.\n"+ 'Return JSON {"ideas":[{"concentration":"","question_type":"","difficulty":"","rationale":""}]}'+ )++ constraints: list[str] = []+ if target_difficulty:+ constraints.append(f"Target difficulty: {target_difficulty}")+ if target_question_type:+ constraints.append(f"Target question type: {target_question_type}")+ effective_preference = preference or "(none)"+ if constraints:+ effective_preference = f"{effective_preference}\n" + "\n".join(constraints)++ user_prompt = idea_prompt.format(+ user_topic=user_topic,+ preference=effective_preference,+ evaluator_feedback=evaluator_feedback or "(none)",+ knowledge_context=knowledge_context[:6000],+ num_ideas=num_ideas,+ )++ try:+ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt or "",+ response_format={"type": "json_object"},+ stage="idea_generate_candidates",+ )+ payload = json.loads(response)+ ideas_raw = payload.get("ideas", [])+ if not isinstance(ideas_raw, list):+ ideas_raw = []+ except Exception as exc:+ self.logger.warning(f"Idea generation failed, fallback used: {exc}")+ ideas_raw = []++ ideas: list[dict[str, Any]] = []+ for idx, item in enumerate(ideas_raw, 1):+ if not isinstance(item, dict):+ continue+ concentration = str(item.get("concentration", "")).strip()+ if not concentration:+ continue+ ideas.append(+ {+ "idea_id": item.get("idea_id", f"idea_{idx}"),+ "concentration": concentration,+ "question_type": str(item.get("question_type", "written")).strip()+ or "written",+ "difficulty": str(item.get("difficulty", "medium")).strip() or "medium",+ "rationale": str(item.get("rationale", "")).strip(),+ }+ )+ if len(ideas) >= num_ideas:+ break++ if len(ideas) < num_ideas:+ for idx in range(len(ideas) + 1, num_ideas + 1):+ ideas.append(+ {+ "idea_id": f"idea_{idx}",+ "concentration": f"{user_topic} - aspect {idx}",+ "question_type": "written",+ "difficulty": "medium",+ "rationale": "Fallback idea generated due to parsing issues.",+ }+ )++ return ideasdiff --git a/src/agents/question/agents/relevance_analyzer.py b/src/agents/question/agents/relevance_analyzer.pydeleted file mode 100644index b366257d2..000000000--- a/src/agents/question/agents/relevance_analyzer.py+++ /dev/null@@ -1,207 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-RelevanceAnalyzer - Analyzes the relevance between questions and knowledge base.--Replaces the old validation workflow with a single-pass relevance analysis.-No iterative validation or rejection - all questions are accepted and analyzed.-"""--import json-import re-from typing import Any--from src.agents.base_agent import BaseAgent---class RelevanceAnalyzer(BaseAgent):- """- Agent responsible for analyzing question-knowledge relevance.-- Key difference from old ValidationWorkflow:- - NO rejection: all questions are accepted- - NO iteration: single-pass analysis- - Output: relevance level (high/partial) with explanations-- Responsibilities:- - Analyze how well a question aligns with knowledge base content- - Identify what KB concepts the question tests- - Identify any extensions beyond the KB (for "partial" relevance)- """-- def __init__(- self,- language: str = "en",- **kwargs,- ):- """- Initialize RelevanceAnalyzer.-- Args:- language: Language for prompts ("en" or "zh")- **kwargs: Additional arguments passed to BaseAgent- """- super().__init__(- module_name="question",- agent_name="relevance_analyzer",- language=language,- **kwargs,- )-- async def process(- self,- question: dict[str, Any],- knowledge_context: str,- ) -> dict[str, Any]:- """- Main processing: analyze relevance between question and knowledge.-- Args:- question: Generated question dict- knowledge_context: Retrieved knowledge summary-- Returns:- Dict with:- - relevance: "high" or "partial"- - kb_coverage: Description of KB content tested- - extension_points: Description of extensions (only if partial)- """- self.logger.info("Starting relevance analysis")-- # Format question for analysis- question_str = json.dumps(question, ensure_ascii=False, indent=2)-- # Truncate context if too long- if len(knowledge_context) > 4000:- knowledge_context = knowledge_context[:4000] + "...[truncated]"-- # Get prompts- system_prompt = self.get_prompt("system", "")- user_prompt_template = self.get_prompt("analyze_relevance", "")-- if not user_prompt_template:- # Fallback prompt- user_prompt_template = (- "Analyze the relevance between this question and knowledge base:\n\n"- "Question:\n{question}\n\n"- "Knowledge Base:\n{knowledge}\n\n"- "Return JSON with: relevance (high/partial), kb_coverage, extension_points"- )-- user_prompt = user_prompt_template.format(- question=question_str,- knowledge=knowledge_context,- )-- try:- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- response_format={"type": "json_object"},- temperature=0.3, # Lower temperature for more consistent analysis- stage="analyze_relevance",- )-- result = self._parse_analysis_response(response)-- self.logger.info(f"Relevance analysis completed: {result['relevance']}")-- return result-- except Exception as e:- self.logger.warning(f"Relevance analysis failed: {e}")- # Return default "partial" on failure- return {- "relevance": "partial",- "kb_coverage": "Unable to analyze knowledge base coverage",- "extension_points": f"Analysis could not be completed: {e}",- }-- def _parse_analysis_response(self, response: str) -> dict[str, Any]:- """- Parse LLM response into analysis result.-- Uses robust JSON extraction that handles control characters- and common LLM output issues.-- Args:- response: LLM response string-- Returns:- Parsed analysis dict with normalized relevance value- """- if not response or not response.strip():- raise ValueError("LLM returned empty response")-- # Try to extract JSON from markdown code blocks if present- json_content = self._extract_json_from_markdown(response)-- # Clean control characters- json_content = self._clean_json_string(json_content)-- # Try multiple parsing strategies- result = None- parse_error = None-- # Strategy 1: Direct parse- try:- result = json.loads(json_content)- except json.JSONDecodeError as e:- parse_error = e-- # Strategy 2: Extract JSON object pattern- if result is None:- json_obj_pattern = re.compile(r"\{[\s\S]*\}")- match = json_obj_pattern.search(json_content)- if match:- try:- result = json.loads(match.group(0))- except json.JSONDecodeError:- pass-- if result is None:- raise ValueError(f"Failed to parse analysis JSON: {parse_error}") from parse_error-- # Normalize relevance value- relevance = result.get("relevance", "partial")- if relevance not in ["high", "partial"]:- relevance = "partial"-- return {- "relevance": relevance,- "kb_coverage": result.get("kb_coverage", ""),- "extension_points": result.get("extension_points", "")- if relevance == "partial"- else "",- }-- def _clean_json_string(self, json_str: str) -> str:- """- Clean JSON string by removing problematic control characters.- """- if not json_str:- return json_str- # Remove control characters except tab, newline, carriage return- return re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", json_str)-- def _extract_json_from_markdown(self, content: str) -> str:- """- Extract JSON from markdown code blocks.-- Args:- content: Raw LLM response-- Returns:- Extracted JSON string- """- if not content:- return content-- # Try to find JSON code block- json_block_pattern = r"```(?:json)?\s*\n?(.*?)```"- matches = re.findall(json_block_pattern, content, re.DOTALL)-- if matches:- return matches[0].strip()-- return content.strip()diff --git a/src/agents/question/agents/retrieve_agent.py b/src/agents/question/agents/retrieve_agent.pydeleted file mode 100644index 544a81195..000000000--- a/src/agents/question/agents/retrieve_agent.py+++ /dev/null@@ -1,239 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-RetrieveAgent - Responsible for generating RAG queries and retrieving knowledge.--Uses unified BaseAgent for LLM calls and configuration management.-"""--import asyncio-import json-from typing import Any--from src.agents.base_agent import BaseAgent-from src.tools.rag_tool import rag_search---class RetrieveAgent(BaseAgent):- """- Agent responsible for knowledge retrieval from the knowledge base.-- Responsibilities:- - Generate semantic search queries from requirements- - Execute RAG searches in parallel- - Merge and summarize retrieval results- """-- def __init__(- self,- kb_name: str | None = None,- rag_mode: str = "naive",- language: str = "en",- **kwargs,- ):- """- Initialize RetrieveAgent.-- Args:- kb_name: Knowledge base name to search- rag_mode: RAG search mode ("naive" or "hybrid")- language: Language for prompts ("en" or "zh")- **kwargs: Additional arguments passed to BaseAgent- """- super().__init__(- module_name="question",- agent_name="retrieve_agent",- language=language,- **kwargs,- )- self.kb_name = kb_name- self.rag_mode = rag_mode-- async def process(- self,- requirement: dict[str, Any] | str,- num_queries: int = 3,- ) -> dict[str, Any]:- """- Main processing: generate queries and retrieve knowledge.-- Args:- requirement: Question requirement (dict or string)- num_queries: Number of RAG queries to generate-- Returns:- Dict with:- - queries: List of generated queries- - retrievals: List of retrieval results- - summary: Merged knowledge summary- """- self.logger.info("Starting knowledge retrieval")-- # Convert requirement to text- if isinstance(requirement, dict):- requirement_text = json.dumps(requirement, ensure_ascii=False, indent=2)- else:- requirement_text = str(requirement)-- # Step 1: Generate search queries- queries = await self._generate_queries(requirement_text, num_queries)- self.logger.info(f"Generated {len(queries)} search queries")-- # Step 2: Execute RAG searches in parallel- retrievals = await self._execute_searches(queries)- self.logger.info(f"Retrieved {len(retrievals)} results")-- # Step 3: Summarize results- summary = self._summarize_retrievals(retrievals)-- return {- "queries": queries,- "retrievals": retrievals,- "summary": summary,- "has_content": any(r.get("answer", "").strip() for r in retrievals),- }-- async def _generate_queries(- self,- requirement_text: str,- num_queries: int,- ) -> list[str]:- """- Use LLM to generate semantic search queries from requirement text.-- Args:- requirement_text: Natural language requirement- num_queries: Number of queries to generate-- Returns:- List of query strings- """- system_prompt = self.get_prompt("system", "")- user_prompt_template = self.get_prompt("generate_queries", "")-- if not user_prompt_template:- # Fallback prompt- user_prompt_template = (- f"Extract {num_queries} knowledge point names from this requirement for retrieval:\n"- "{requirement_text}\n\n"- 'Return JSON: {{"queries": ["point1", "point2", ...]}}'- )-- user_prompt = user_prompt_template.format(- requirement_text=requirement_text,- num_queries=num_queries,- )-- try:- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- response_format={"type": "json_object"},- stage="generate_queries",- )-- data = json.loads(response)- queries_raw = data.get("queries", [])-- # Ensure queries is a list- if not isinstance(queries_raw, list):- if isinstance(queries_raw, dict):- queries_raw = list(queries_raw.values())- elif isinstance(queries_raw, str):- queries_raw = [queries_raw]- else:- queries_raw = []-- queries = [q.strip() for q in queries_raw if q and q.strip()]-- except Exception as e:- self.logger.warning(f"Failed to generate queries: {e}")- queries = []-- # Fallback: use requirement text as query- if not queries:- queries = [requirement_text[:100]]-- return queries[:num_queries]-- async def _single_rag_search(self, query: str) -> dict[str, Any]:- """- Execute a single RAG search.-- Args:- query: Search query-- Returns:- Dict with query and answer- """- try:- result = await rag_search(- query=query,- kb_name=self.kb_name,- mode=self.rag_mode,- only_need_context=True,- )- return {- "query": query,- "answer": result.get("answer", ""),- "mode": result.get("mode", self.rag_mode),- }- except Exception as e:- self.logger.warning(f"RAG search failed for '{query}': {e}")- return {- "query": query,- "answer": "",- "error": str(e),- }-- async def _execute_searches(self, queries: list[str]) -> list[dict[str, Any]]:- """- Execute RAG searches in parallel.-- Args:- queries: List of search queries-- Returns:- List of retrieval results- """- self.logger.debug(f"Executing {len(queries)} RAG searches in parallel")-- tasks = [self._single_rag_search(query) for query in queries]- results = await asyncio.gather(*tasks, return_exceptions=True)-- retrievals = []- for i, result in enumerate(results):- if isinstance(result, Exception):- self.logger.warning(f"Search failed for query '{queries[i]}': {result}")- continue- if result.get("answer"):- retrievals.append(result)- self.logger.debug(f" → Query: {queries[i][:50]}... (retrieved)")-- return retrievals-- def _summarize_retrievals(self, retrievals: list[dict[str, Any]]) -> str:- """- Merge retrieval results into a summary string.-- Args:- retrievals: List of retrieval results-- Returns:- Merged summary string- """- if not retrievals:- return "No retrieval context available."-- lines = []- for item in retrievals:- lines.append(f"=== Query: {item['query']} ===")- answer = item.get("answer", "")- if answer:- # Truncate very long answers- if len(answer) > 2000:- answer = answer[:2000] + "...[truncated]"- lines.append(answer)- lines.append("")-- return "\n".join(lines)diff --git a/src/agents/question/agents/validator.py b/src/agents/question/agents/validator.pynew file mode 100644index 000000000..a9aa6bad1--- /dev/null+++ b/src/agents/question/agents/validator.py@@ -0,0 +1,191 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+Validator - Validate generated Q-A pairs with dynamic tool usage.++The Validator first makes an LLM-based quality judgment, then optionally+runs code verification only when the LLM deems it necessary.+"""++from __future__ import annotations++import json+import re+from typing import Any++from src.agents.base_agent import BaseAgent+from src.agents.question.models import QAPair, QuestionTemplate+from src.tools.code_executor import run_code+++class Validator(BaseAgent):+ """+ Validate generated output against template requirements.++ Two-step process:+ 1. LLM evaluates the Q-A pair and decides if code verification is needed+ 2. If code check requested and code is available, run it and finalize+ """++ def __init__(+ self,+ language: str = "en",+ tool_flags: dict[str, bool] | None = None,+ **kwargs: Any,+ ) -> None:+ super().__init__(+ module_name="question",+ agent_name="validator",+ language=language,+ **kwargs,+ )+ self.tool_flags = tool_flags or {}++ async def process(+ self,+ template: QuestionTemplate,+ qa_pair: QAPair,+ ) -> dict[str, Any]:+ """+ Return approval decision and feedback.++ Flow:+ 1. LLM validates quality and decides if code check is needed+ 2. If code check requested, run verification code+ 3. If code check reveals issues, append findings to feedback+ """+ verification_code = str(qa_pair.metadata.get("verification_code", "")).strip()+ has_code = bool(verification_code)+ code_enabled = self.tool_flags.get("write_code", True)++ # Step 1: LLM validation (includes decision on code check)+ llm_result = await self._validate_with_llm(+ template=template,+ qa_pair=qa_pair,+ has_verification_code=has_code and code_enabled,+ )++ decision = str(llm_result.get("decision", "reject")).lower()+ if decision not in {"approve", "reject"}:+ decision = "reject"++ issues = llm_result.get("issues", [])+ if not isinstance(issues, list):+ issues = []++ feedback = str(llm_result.get("feedback", "")).strip()+ needs_code_check = bool(llm_result.get("needs_code_check", False))++ # Step 2: Optionally run code verification+ code_check: dict[str, Any] = {}+ if needs_code_check and has_code and code_enabled:+ code_check = await self._run_code_check(verification_code)++ # If code check failed, downgrade approval or augment feedback+ if code_check.get("exit_code", -1) != 0:+ stderr = code_check.get("stderr", "")+ if decision == "approve":+ decision = "reject"+ feedback = (+ f"Code verification failed (exit_code={code_check.get('exit_code')}). "+ f"stderr: {stderr[:300]}. "+ f"Original feedback: {feedback}"+ )+ issues.append("code_verification_failed")+ else:+ feedback += (+ f" | Code check also failed: {stderr[:200]}"+ )++ if decision == "reject" and not feedback:+ feedback = (+ "Answer quality or alignment is insufficient. "+ "Regenerate with stricter alignment to the template."+ )++ return {+ "decision": decision,+ "approved": decision == "approve",+ "feedback": feedback,+ "issues": issues,+ "code_check": code_check,+ "needs_code_check": needs_code_check,+ }++ async def _validate_with_llm(+ self,+ template: QuestionTemplate,+ qa_pair: QAPair,+ has_verification_code: bool,+ ) -> dict[str, Any]:+ """Run LLM validation. The LLM also decides if code check is needed."""+ system_prompt = self.get_prompt("system", "")+ validate_prompt = self.get_prompt("validate", "")+ if not validate_prompt:+ validate_prompt = (+ "Template:\n{template}\n\n"+ "QA Pair:\n{qa_pair}\n\n"+ "Verification code available: {has_code}\n\n"+ 'Return JSON {{"decision":"approve|reject","feedback":"","issues":[],"needs_code_check":true|false}}'+ )++ user_prompt = validate_prompt.format(+ template=json.dumps(template.__dict__, ensure_ascii=False, indent=2),+ qa_pair=json.dumps(qa_pair.__dict__, ensure_ascii=False, indent=2),+ has_code=str(has_verification_code).lower(),+ )++ try:+ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt or "",+ response_format={"type": "json_object"},+ temperature=0.2,+ stage="validator_decision",+ )+ return self._parse_json_like(response)+ except Exception as exc:+ self.logger.warning(f"Validator LLM failed, fallback reject: {exc}")+ return {+ "decision": "reject",+ "feedback": str(exc),+ "issues": ["validator_error"],+ "needs_code_check": False,+ }++ async def _run_code_check(self, code: str) -> dict[str, Any]:+ """Execute verification code."""+ try:+ result = await run_code(language="python", code=code, timeout=10)+ return {+ "exit_code": result.get("exit_code", -1),+ "stdout": (result.get("stdout", "") or "")[:800],+ "stderr": (result.get("stderr", "") or "")[:800],+ }+ except Exception as exc:+ return {"exit_code": -1, "stderr": str(exc)}++ @staticmethod+ def _parse_json_like(content: str) -> dict[str, Any]:+ if not content:+ return {}+ cleaned = re.sub(+ r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", content.strip()+ )+ block = re.search(r"```(?:json)?\s*(.*?)```", cleaned, re.DOTALL)+ if block:+ cleaned = block.group(1).strip()++ try:+ data = json.loads(cleaned)+ return data if isinstance(data, dict) else {}+ except Exception:+ pass+ obj = re.search(r"\{[\s\S]*\}", cleaned)+ if obj:+ try:+ data = json.loads(obj.group(0))+ return data if isinstance(data, dict) else {}+ except Exception:+ return {}+ return {}diff --git a/src/agents/question/cli.py b/src/agents/question/cli.pynew file mode 100644index 000000000..c4afa5b8d--- /dev/null+++ b/src/agents/question/cli.py@@ -0,0 +1,581 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+Interactive CLI for testing the refactored question module.++Usage:+ python src/agents/question/cli.py++Features:+- Real-time progress display during generation+- Saves all intermediate files (templates, traces, per-question results)+ to a per-batch directory under the output folder+- Detailed summary with question previews at the end+- Interactive answering mode after question generation+- Integrated with PersonalizationService for memory recording+"""++from __future__ import annotations++import asyncio+from pathlib import Path+import sys+from typing import Any++# Ensure project root import works when running as a script+PROJECT_ROOT = Path(__file__).resolve().parents[3]+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 src.agents.question import AgentCoordinator+from src.knowledge.config import KNOWLEDGE_BASES_DIR+from src.knowledge.manager import KnowledgeBaseManager+from src.services.llm.config import get_llm_config+++# ── Formatting helpers ────────────────────────────────────────────────++BOLD = "\033[1m"+DIM = "\033[2m"+GREEN = "\033[92m"+YELLOW = "\033[93m"+RED = "\033[91m"+CYAN = "\033[96m"+MAGENTA = "\033[95m"+RESET = "\033[0m"+CHECK = f"{GREEN}✓{RESET}"+CROSS = f"{RED}✗{RESET}"+ARROW = f"{CYAN}→{RESET}"+++def _hr(char: str = "─", width: int = 70) -> str:+ return f"{DIM}{char * width}{RESET}"+++def _header(title: str) -> None:+ print(f"\n{_hr('━')}")+ print(f" {BOLD}{title}{RESET}")+ print(_hr("━"))+++def _prompt_non_empty(message: str, default: str | None = None) -> str:+ suffix = f" [{DIM}{default}{RESET}]" if default else ""+ while True:+ raw = input(f" {message}{suffix}: ").strip()+ if raw:+ return raw+ if default is not None:+ return default+ print(f" {RED}输入不能为空,请重试。{RESET}")+++def _list_kbs() -> list[str]:+ """Fetch available knowledge bases from the local KB manager."""+ try:+ manager = KnowledgeBaseManager(str(KNOWLEDGE_BASES_DIR))+ return manager.list_knowledge_bases()+ except Exception:+ return []+++def _select_kb() -> str:+ """Show a numbered list of KBs and let the user pick one."""+ kbs = _list_kbs()+ if not kbs:+ print(f" {YELLOW}未找到已有知识库,请手动输入名称。{RESET}")+ return _prompt_non_empty("KB 名称", "ai_textbook")++ print(f"\n {BOLD}可用知识库:{RESET}")+ for i, name in enumerate(kbs, 1):+ print(f" {CYAN}{i}{RESET}) {name}")+ print(f" {CYAN}0{RESET}) 手动输入")++ while True:+ raw = input(f" 选择 [{DIM}1{RESET}]: ").strip()+ if not raw:+ return kbs[0]+ if raw == "0":+ return _prompt_non_empty("KB 名称")+ try:+ idx = int(raw)+ if 1 <= idx <= len(kbs):+ return kbs[idx - 1]+ except ValueError:+ # Allow typing a name directly+ if raw in kbs:+ return raw+ print(f" {RED}无效选择,请重试。{RESET}")+++def _prompt_int(message: str, default: int) -> int:+ while True:+ raw = input(f" {message} [{DIM}{default}{RESET}]: ").strip()+ if not raw:+ return default+ try:+ value = int(raw)+ if value > 0:+ return value+ except ValueError:+ pass+ print(f" {RED}请输入正整数。{RESET}")+++# ── Progress callback ────────────────────────────────────────────────++async def _cli_progress(data: dict[str, Any]) -> None:+ """Real-time progress callback printed to terminal."""+ msg_type = data.get("type", "")++ if msg_type == "progress":+ stage = data.get("stage", "")+ if stage == "idea_loop":+ rd = data.get("current_round", "")+ mx = data.get("max_rounds", "")+ if rd:+ print(f" {MAGENTA}🔄 创意循环{RESET} 第 {rd}/{mx} 轮")+ elif stage == "generating":+ cur = data.get("current", "")+ tot = data.get("total", "")+ qid = data.get("question_id", "")+ if cur and tot:+ print(f" {CYAN}📝 生成中{RESET} {cur}/{tot} {DIM}{qid}{RESET}")+ elif stage == "complete":+ comp = data.get("completed", "?")+ tot = data.get("total", "?")+ print(f" {GREEN}✅ 完成{RESET} {comp}/{tot}")+ elif stage in ("parsing", "extracting", "uploading"):+ status = data.get("status", "")+ print(f" {YELLOW}📄 {stage}{RESET} {status}")++ elif msg_type == "templates_ready":+ count = data.get("count", 0)+ print(f" {GREEN}📋 模板就绪{RESET} {count} 个")++ elif msg_type == "idea_round":+ rd = data.get("round", "?")+ fb = data.get("feedback", "")+ cont = data.get("continue_loop", False)+ status = "继续改进" if cont else "已确定"+ print(f" {MAGENTA}💡 创意第 {rd} 轮{RESET} → {status}")+ if fb:+ print(f" {DIM}反馈: {fb[:100]}{RESET}")++ elif msg_type == "question_update":+ qid = data.get("question_id", "")+ attempt = data.get("attempt", 1)+ max_att = data.get("max_attempts", "?")+ print(f" {CYAN}⚙ {qid}{RESET} 生成 (尝试 {attempt}/{max_att})")++ elif msg_type == "validating":+ qid = data.get("question_id", "")+ attempt = data.get("attempt", 1)+ validation = data.get("validation", {})+ decision = validation.get("decision", "?")+ icon = CHECK if decision == "approve" else CROSS+ print(f" {YELLOW}🔍 {qid}{RESET} 验证 → {icon} {decision}")++ elif msg_type == "result":+ qid = data.get("question_id", "")+ validation = data.get("validation", {})+ approved = validation.get("approved", False)+ attempts = data.get("attempts", 1)+ icon = CHECK if approved else CROSS+ print(f" {icon} {BOLD}{qid}{RESET} ({attempts} 次尝试)")+++# ── PersonalizationService startup ────────────────────────────────────++async def _ensure_personalization() -> bool:+ """Start EventBus and PersonalizationService for in-process memory.++ Returns True if both services started successfully.+ """+ ok = True+ try:+ from src.core.event_bus import get_event_bus++ bus = get_event_bus()+ await bus.start()+ except Exception as exc:+ print(f"\n {RED}WARNING: EventBus failed to start: {exc}{RESET}")+ ok = False+ try:+ from src.personalization.service import get_personalization_service++ svc = get_personalization_service()+ await svc.start()+ except Exception as exc:+ print(f"\n {RED}WARNING: PersonalizationService failed to start: {exc}{RESET}")+ ok = False+ return ok+++async def _flush_events() -> None:+ """Wait for EventBus to finish processing all pending events."""+ try:+ from src.core.event_bus import get_event_bus++ bus = get_event_bus()+ await bus.flush(timeout=60.0)+ except Exception:+ pass+++# ── Result display ────────────────────────────────────────────────────++def _print_summary(summary: dict[str, Any]) -> None:+ _header("结果摘要")+ success = summary.get("success", False)+ status_icon = f"{GREEN}SUCCESS{RESET}" if success else f"{RED}FAILED{RESET}"+ print(f" 状态: {status_icon}")+ print(f" 来源: {summary.get('source', '?')}")+ print(f" 请求: {summary.get('requested', '?')} 道")+ print(f" 成功: {GREEN}{summary.get('completed', 0)}{RESET}")+ print(f" 失败: {RED}{summary.get('failed', 0)}{RESET}")+ print(f" 模板数: {summary.get('template_count', '?')}")++ batch_dir = summary.get("batch_dir")+ if batch_dir:+ print(f" 输出目录: {CYAN}{batch_dir}{RESET}")++ results = summary.get("results", []) or []+ if results:+ print(f"\n {BOLD}题目预览:{RESET}")+ for i, item in enumerate(results, 1):+ qa = item.get("qa_pair", {})+ approved = item.get("success", False)+ icon = CHECK if approved else CROSS+ q_type = qa.get("question_type", "unknown")+ question = str(qa.get("question", "")).replace("\n", " ")[:100]+ attempts = len(item.get("attempts", []))++ # Tool usage info+ tool_plan = qa.get("metadata", {}).get("tool_plan", {})+ tools_used = []+ if tool_plan.get("use_rag"):+ tools_used.append("rag")+ if tool_plan.get("use_web"):+ tools_used.append("web")+ if tool_plan.get("use_code"):+ tools_used.append("code")+ tool_str = f" {DIM}[{', '.join(tools_used)}]{RESET}" if tools_used else ""++ print(f" {icon} {i}. [{q_type}]{tool_str} {DIM}({attempts}次){RESET}")+ print(f" {question}...")++ print()+++# ── Interactive answering ─────────────────────────────────────────────++def _display_question(idx: int, qa: dict[str, Any]) -> None:+ """Display a single question for the user to answer."""+ q_type = qa.get("question_type", "written")+ question_text = qa.get("question", "")+ options = qa.get("options") or {}++ print(f"\n {BOLD}题目 {idx}{RESET} [{q_type}]")+ print(_hr())+ print(f" {question_text}")++ if options:+ print()+ for key in sorted(options.keys()):+ print(f" {CYAN}{key}{RESET}. {options[key]}")+ print(_hr())+++def _judge_answer(user_answer: str, correct_answer: str, q_type: str) -> str:+ """Simple answer judgement. Returns 'correct', 'wrong', or 'partial'."""+ ua = user_answer.strip().lower()+ ca = correct_answer.strip().lower()+ if not ua:+ return "skipped"+ if q_type == "choice":+ ua_letter = ua.strip("().)( ").upper()+ ca_letter = ca.strip("().)( ").upper()+ if ua_letter and ca_letter:+ return "correct" if ua_letter == ca_letter else "wrong"+ if ua == ca:+ return "correct"+ if ua in ca or ca in ua:+ return "partial"+ return "pending"+++async def _run_answer_session(summary: dict[str, Any]) -> None:+ """Interactive answering session after question generation."""+ results = summary.get("results", []) or []+ approved_results = [r for r in results if r.get("success")]+ if not approved_results:+ print(f" {YELLOW}没有可用的题目进行作答。{RESET}")+ return++ batch_dir = summary.get("batch_dir", "")+ trace_id = Path(batch_dir).name if batch_dir else ""++ _header(f"答题环节 ({len(approved_results)} 道题)")+ print(f" {DIM}直接回车可跳过该题,输入 /quit 退出答题{RESET}\n")++ answers_recorded = 0+ correct_count = 0+ wrong_count = 0+ skipped_count = 0++ for i, item in enumerate(approved_results, 1):+ qa = item.get("qa_pair", {})+ question_id = qa.get("question_id", f"q_{i}")+ q_type = qa.get("question_type", "written")+ correct_answer = str(qa.get("correct_answer", ""))++ _display_question(i, qa)++ try:+ user_input = input(f" {ARROW} 你的回答: ").strip()+ except (EOFError, KeyboardInterrupt):+ print(f"\n {YELLOW}答题中断。{RESET}")+ break++ if user_input.lower() in ("/quit", "/exit", "/q"):+ print(f" {DIM}退出答题。{RESET}")+ break++ if not user_input:+ skipped_count += 1+ print(f" {DIM}(已跳过){RESET}")+ continue++ judged = _judge_answer(user_input, correct_answer, q_type)++ if judged == "correct":+ print(f" {CHECK} {GREEN}正确!{RESET}")+ correct_count += 1+ elif judged == "wrong":+ print(f" {CROSS} {RED}错误{RESET} 正确答案: {GREEN}{correct_answer}{RESET}")+ wrong_count += 1+ elif judged == "partial":+ print(f" {YELLOW}~ 部分匹配{RESET} 参考答案: {correct_answer}")+ elif judged == "skipped":+ skipped_count += 1+ print(f" {DIM}(已跳过){RESET}")+ continue+ else:+ print(f" {YELLOW}? 待判定{RESET} 参考答案: {correct_answer}")++ explanation = qa.get("explanation", "")+ if explanation:+ short_exp = explanation[:200]+ if len(explanation) > 200:+ short_exp += "..."+ print(f" {DIM}解析: {short_exp}{RESET}")++ # Record to PersonalizationService+ if trace_id:+ try:+ from src.personalization.service import get_personalization_service++ svc = get_personalization_service()+ ok = await svc.record_user_answer(+ trace_id=trace_id,+ question_id=question_id,+ user_answer=user_input,+ judged_result=judged,+ )+ if ok:+ answers_recorded += 1+ except Exception:+ pass++ # Flush trace + run memory agents once with the complete trace+ if answers_recorded > 0 and trace_id:+ print(f"\n {DIM}同步答题记忆...{RESET}", end="", flush=True)+ await _flush_events()+ try:+ from src.personalization.service import get_personalization_service+ svc = get_personalization_service()+ await svc.flush_memory_agents(trace_id)+ except Exception:+ pass+ print(f" {CHECK}")++ # Print answer session summary+ _header("答题结果")+ total = correct_count + wrong_count + skipped_count+ print(f" 总计: {total} 题")+ print(f" 正确: {GREEN}{correct_count}{RESET}")+ print(f" 错误: {RED}{wrong_count}{RESET}")+ print(f" 跳过: {DIM}{skipped_count}{RESET}")+ if answers_recorded > 0:+ print(f" {CHECK} 已记录 {answers_recorded} 条答题记录到记忆系统")+ print()+++# ── Coordinator builder ───────────────────────────────────────────────++def _build_coordinator(+ kb_name: str, output_dir: str, language: str+) -> AgentCoordinator:+ try:+ llm_config = get_llm_config()+ return AgentCoordinator(+ api_key=llm_config.api_key,+ base_url=llm_config.base_url,+ api_version=getattr(llm_config, "api_version", None),+ kb_name=kb_name,+ output_dir=output_dir,+ language=language,+ )+ except Exception:+ return AgentCoordinator(+ kb_name=kb_name, output_dir=output_dir, language=language+ )+++# ── Mode runners ──────────────────────────────────────────────────────++async def _run_topic_mode(coordinator: AgentCoordinator) -> None:+ _header("Topic 模式")+ user_topic = _prompt_non_empty("主题 (如: Lagrange multipliers)")+ preference = input(f" 偏好 (可留空): ").strip()+ num_questions = _prompt_int("题目数量", 3)++ print(f"\n {ARROW} 开始生成 {BOLD}{num_questions}{RESET} 道题...")+ print(_hr())++ coordinator.set_ws_callback(_cli_progress)+ summary = await coordinator.generate_from_topic(+ user_topic=user_topic,+ preference=preference,+ num_questions=num_questions,+ )++ # Wait for memory system to process the generation event+ print(f" {DIM}同步记忆系统...{RESET}", end="", flush=True)+ await _flush_events()+ print(f" {CHECK}")++ _print_summary(summary)++ # Offer interactive answering+ approved = [r for r in (summary.get("results") or []) if r.get("success")]+ if approved:+ try:+ choice = input(f" {ARROW} 是否开始答题? (y/n) [{DIM}y{RESET}]: ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ choice = "n"+ if choice != "n":+ await _run_answer_session(summary)+++async def _run_mimic_mode(coordinator: AgentCoordinator) -> None:+ _header("Mimic 模式")+ mode = _prompt_non_empty("输入模式 [upload/parsed]", "parsed").lower()+ if mode not in {"upload", "parsed"}:+ print(f" {YELLOW}无效模式,使用 parsed。{RESET}")+ mode = "parsed"++ if mode == "upload":+ exam_path = _prompt_non_empty("PDF 路径")+ else:+ exam_path = _prompt_non_empty("已解析试卷目录路径")++ max_questions = _prompt_int("最大题目数", 5)++ print(f"\n {ARROW} 开始解析并生成...")+ print(_hr())++ coordinator.set_ws_callback(_cli_progress)+ summary = await coordinator.generate_from_exam(+ exam_paper_path=exam_path,+ max_questions=max_questions,+ paper_mode=mode,+ )++ # Wait for memory system to process the generation event+ print(f" {DIM}同步记忆系统...{RESET}", end="", flush=True)+ await _flush_events()+ print(f" {CHECK}")++ _print_summary(summary)++ # Offer interactive answering+ approved = [r for r in (summary.get("results") or []) if r.get("success")]+ if approved:+ try:+ choice = input(f" {ARROW} 是否开始答题? (y/n) [{DIM}y{RESET}]: ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ choice = "n"+ if choice != "n":+ await _run_answer_session(summary)+++# ── Main ──────────────────────────────────────────────────────────────++async def main() -> None:+ print(f"\n{BOLD}{'=' * 70}{RESET}")+ print(f" {BOLD}{CYAN}DeepTutor Question Module CLI{RESET}")+ print(f"{BOLD}{'=' * 70}{RESET}")++ # Start PersonalizationService for memory recording+ print(f" {DIM}正在初始化记忆系统...{RESET}", end="", flush=True)+ mem_ok = await _ensure_personalization()+ print(f" {CHECK}" if mem_ok else f" {CROSS}")++ kb_name = _select_kb()+ language = _prompt_non_empty("语言 [en/zh]", "zh").lower()+ if language not in {"en", "zh"}:+ print(f" {YELLOW}语言无效,使用 zh。{RESET}")+ language = "zh"++ default_output = str(PROJECT_ROOT / "data" / "user" / "question")+ output_dir = _prompt_non_empty(f"输出目录", default_output)++ coordinator = _build_coordinator(+ kb_name=kb_name,+ output_dir=output_dir,+ language=language,+ )++ print(f"\n {DIM}配置: KB={kb_name}, 语言={language}, 输出={output_dir}{RESET}")++ while True:+ print(f"\n {BOLD}请选择模式:{RESET}")+ print(f" {CYAN}1{RESET}) Topic 模式 — 基于主题生成")+ print(f" {CYAN}2{RESET}) Mimic 模式 — 基于试卷仿题")+ print(f" {CYAN}q{RESET}) 退出")+ choice = input(f" {ARROW} ").strip().lower()++ try:+ if choice == "1":+ await _run_topic_mode(coordinator)+ elif choice == "2":+ await _run_mimic_mode(coordinator)+ elif choice in {"q", "quit", "exit"}:+ print(f"\n {DIM}已退出。{RESET}\n")+ break+ else:+ print(f" {RED}无效输入,请重试。{RESET}")+ except KeyboardInterrupt:+ print(f"\n {YELLOW}已中断当前任务。{RESET}")+ except Exception as exc:+ print(f"\n {RED}运行失败: {exc}{RESET}")+ import traceback+ traceback.print_exc()++ # Cleanup+ try:+ from src.core.event_bus import get_event_bus++ await get_event_bus().stop()+ except Exception:+ pass+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/src/agents/question/coordinator.py b/src/agents/question/coordinator.pyindex bb1392dc6..6e86cd477 100644--- a/src/agents/question/coordinator.py+++ b/src/agents/question/coordinator.py@@ -1,14 +1,17 @@#!/usr/bin/env python# -*- coding: utf-8 -*-"""-AgentCoordinator - Orchestrates question generation workflow.+Refactored Question Coordinator-Refactored version:-- Uses specialized agents: RetrieveAgent, GenerateAgent, RelevanceAnalyzer-- No iterative validation loops - single-pass generation + relevance analysis-- All questions are accepted, classified as "high" or "partial" relevance+Two-loop architecture:+1) Idea loop (IdeaAgent <-> Evaluator) for topic-driven templates+2) Generation loop (Generator <-> Validator) for final Q-A pairs++All intermediate artifacts are saved to a per-batch directory."""+from __future__ import annotations+from collections.abc import Callablefrom datetime import datetimeimport json@@ -16,27 +19,28 @@ from pathlib import Pathimport sysfrom typing import Any-# Add project root for importsproject_root = Path(__file__).parent.parent.parent.parentsys.path.insert(0, str(project_root))+from src.agents.question.agents.evaluator import Evaluator+from src.agents.question.agents.generator import Generator+from src.agents.question.agents.idea_agent import IdeaAgent+from src.agents.question.agents.validator import Validator+from src.agents.question.models import QAPair, QuestionTemplatefrom src.logging import Logger, get_loggerfrom src.services.config import load_config_with_main--from .agents.generate_agent import GenerateAgent-from .agents.relevance_analyzer import RelevanceAnalyzer-from .agents.retrieve_agent import RetrieveAgent+from src.tools.question.pdf_parser import parse_pdf_with_mineru+from src.tools.question.question_extractor import extract_questions_from_paperclass AgentCoordinator:"""- Coordinate question generation workflow using specialized agents.+ Orchestrates both input paths:+ - generate_from_topic: user_topic + preference+ - generate_from_exam: exam paper parse/extract -> templates- Workflow:- 1. RetrieveAgent: Generate queries and retrieve knowledge- 2. Plan: Generate question plan with focuses- 3. GenerateAgent: Generate questions- 4. RelevanceAnalyzer: Analyze relevance (no rejection, just classification)+ All intermediate files (templates, traces, per-question results) are+ persisted to self._batch_dir for debugging and reproducibility."""def __init__(@@ -44,738 +48,766 @@ class AgentCoordinator:api_key: str | None = None,base_url: str | None = None,api_version: str | None = None,- max_rounds: int = 10, # Kept for backward compatibility, but not used for iterationkb_name: str | None = None,output_dir: str | None = None,language: str = "en",- ):- """- Initialize the coordinator.-- Args:- api_key: API key (optional, loaded from config if not provided)- base_url: API endpoint (optional)- api_version: API version for Azure (optional)- max_rounds: Deprecated, kept for backward compatibility- kb_name: Knowledge base name- output_dir: Output directory for results- language: Language for prompts ("en" or "zh")- """+ tool_flags_override: dict[str, bool] | None = None,+ enable_idea_rag: bool = True,+ ) -> None:self.kb_name = kb_nameself.output_dir = output_dirself.language = language-- # Store API credentials for creating agentsself._api_key = api_keyself._base_url = base_urlself._api_version = api_version+ self._ws_callback: Callable | None = None+ self._batch_dir: Path | None = None+ self.enable_idea_rag = enable_idea_rag- # Load configurationself.config = load_config_with_main("question_config.yaml", project_root)- # Initialize loggerlog_dir = self.config.get("paths", {}).get("user_log_dir") or self.config.get("logging", {}).get("log_dir")self.logger: Logger = get_logger("QuestionCoordinator", log_dir=log_dir)- # Get config valuesquestion_cfg = self.config.get("question", {})- self.rag_query_count = question_cfg.get("rag_query_count", 3)- self.max_parallel_questions = question_cfg.get("max_parallel_questions", 1)self.rag_mode = question_cfg.get("rag_mode", "naive")+ self.max_parallel_questions = question_cfg.get("max_parallel_questions", 1)+ self.idea_cfg = question_cfg.get("idea_loop", {})+ self.generation_cfg = question_cfg.get("generation", {})+ default_tool_flags = self.generation_cfg.get(+ "tools",+ {"web_search": True, "rag_tool": True, "write_code": True},+ )+ self.tool_flags = (+ tool_flags_override+ if isinstance(tool_flags_override, dict)+ else default_tool_flags+ )- # Token tracking - will be updated from BaseAgent shared stats- self.token_stats = {- "model": "gpt-4o-mini",- "calls": 0,- "tokens": 0,- "input_tokens": 0,- "output_tokens": 0,- "cost": 0.0,- }+ # ------------------------------------------------------------------+ # Public API+ # ------------------------------------------------------------------- # WebSocket callback for streaming updates- self._ws_callback: Callable | None = None+ def set_ws_callback(self, callback: Callable) -> None:+ self._ws_callback = callback++ def get_batch_dir(self) -> Path | None:+ """Return the current batch directory (available after generation starts)."""+ return self._batch_dir- def _update_token_stats(self):- """Update token_stats from BaseAgent's shared LLMStats for the question module."""- from src.agents.base_agent import BaseAgent+ # ------------------------------------------------------------------+ # Batch directory & artifact persistence+ # ------------------------------------------------------------------+ def _init_batch_dir(self) -> Path | None:+ """Create a timestamped batch directory for this generation run."""+ if not self.output_dir:+ return None+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")+ batch_dir = Path(self.output_dir) / f"batch_{ts}"+ batch_dir.mkdir(parents=True, exist_ok=True)+ self._batch_dir = batch_dir+ return batch_dir++ def _save_artifact(self, filename: str, data: Any) -> None:+ """Save an intermediate artifact to the batch directory."""+ if not self._batch_dir:+ returntry:- stats = BaseAgent.get_stats("question")- summary = stats.get_summary()-- self.token_stats = {- "model": summary.get("model", "gpt-4o-mini"),- "calls": summary.get("calls", 0),- "tokens": summary.get("total_tokens", 0),- "input_tokens": summary.get("input_tokens", 0),- "output_tokens": summary.get("output_tokens", 0),- "cost": summary.get("cost", 0.0),- }- except Exception as e:- self.logger.debug(f"Failed to update token stats: {e}")+ filepath = self._batch_dir / filename+ with open(filepath, "w", encoding="utf-8") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+ except Exception as exc:+ self.logger.debug(f"Failed to save artifact {filename}: {exc}")- def set_ws_callback(self, callback: Callable):- """Set WebSocket callback for streaming updates to frontend."""- self._ws_callback = callback+ # ------------------------------------------------------------------+ # WebSocket helpers+ # ------------------------------------------------------------------- async def _send_ws_update(self, update_type: str, data: dict[str, Any]):- """Send update via WebSocket callback if available."""+ async def _send_ws_update(self, update_type: str, data: dict[str, Any]) -> None:if self._ws_callback:try:await self._ws_callback({"type": update_type, **data})- except Exception as e:- self.logger.debug(f"Failed to send WS update: {e}")+ except Exception as exc:+ self.logger.debug(f"WS update failed: {exc}")- def _create_retrieve_agent(self) -> RetrieveAgent:- """Create a RetrieveAgent instance."""- return RetrieveAgent(+ # ------------------------------------------------------------------+ # Agent factories+ # ------------------------------------------------------------------++ def _create_idea_agent(self) -> IdeaAgent:+ return IdeaAgent(kb_name=self.kb_name,rag_mode=self.rag_mode,+ enable_rag=self.enable_idea_rag,language=self.language,api_key=self._api_key,base_url=self._base_url,api_version=self._api_version,)- def _create_generate_agent(self) -> GenerateAgent:- """Create a GenerateAgent instance."""- return GenerateAgent(+ def _create_evaluator(self) -> Evaluator:+ return Evaluator(language=self.language,api_key=self._api_key,base_url=self._base_url,api_version=self._api_version,)- def _create_relevance_analyzer(self) -> RelevanceAnalyzer:- """Create a RelevanceAnalyzer instance."""- return RelevanceAnalyzer(+ def _create_generator(self) -> Generator:+ return Generator(+ kb_name=self.kb_name,+ rag_mode=self.rag_mode,language=self.language,+ tool_flags=self.tool_flags,api_key=self._api_key,base_url=self._base_url,api_version=self._api_version,)- # =========================================================================- # Main Entry Points- # =========================================================================+ def _create_validator(self) -> Validator:+ return Validator(+ language=self.language,+ tool_flags=self.tool_flags,+ api_key=self._api_key,+ base_url=self._base_url,+ api_version=self._api_version,+ )++ # ------------------------------------------------------------------+ # Path 1: Topic -> Idea Loop -> Generation Loop+ # ------------------------------------------------------------------- async def generate_question(+ async def generate_from_topic(self,- requirement: dict[str, Any],+ user_topic: str,+ preference: str,+ num_questions: int,+ difficulty: str = "",+ question_type: str = "",) -> dict[str, Any]:- """- Generate a single question with relevance analysis.-- This is used by Mimic mode and for single question generation.-- Args:- requirement: Question requirement dict-- Returns:- Dict with:- - success: bool- - question: Generated question dict- - analysis: Relevance analysis result- - rounds: Always 1 (no iteration)- """- self.logger.section("Single Question Generation")- self.logger.info(f"Knowledge point: {requirement.get('knowledge_point', 'N/A')}")+ self._init_batch_dir()await self._send_ws_update(- "progress", {"stage": "generating", "progress": {"status": "initializing"}}+ "progress",+ {"stage": "idea_loop", "status": "running", "current_round": 0, "max_rounds": 0},)- # Step 1: Retrieve knowledge- retrieve_agent = self._create_retrieve_agent()- retrieval_result = await retrieve_agent.process(- requirement=requirement,- num_queries=self.rag_query_count,+ templates, idea_trace = await self._idea_loop(+ user_topic=user_topic,+ preference=preference,+ num_questions=num_questions,+ difficulty=difficulty,+ question_type=question_type,)- if not retrieval_result.get("has_content"):- self.logger.warning("No relevant knowledge found")- return {- "success": False,- "error": "knowledge_not_found",- "message": "Knowledge base does not contain relevant information.",- }+ # Save intermediate artifacts+ self._save_artifact("templates.json", [t.__dict__ for t in templates])+ self._save_artifact("idea_trace.json", idea_trace)- knowledge_context = retrieval_result["summary"]+ await self._send_ws_update(+ "templates_ready",+ {+ "stage": "templates_ready",+ "templates": [t.__dict__ for t in templates],+ "count": len(templates),+ },+ )- # Step 2: Generate question- generate_agent = self._create_generate_agent()+ qa_pairs = await self._generation_loop(+ templates=templates,+ user_topic=user_topic,+ preference=preference,+ )- # Check if this is mimic mode (has reference_question)- reference_question = requirement.get("reference_question")+ summary = self._build_summary(+ source="topic",+ requested=num_questions,+ templates=templates,+ qa_pairs=qa_pairs,+ trace=idea_trace,+ )+ self._save_artifact("summary.json", summary)- gen_result = await generate_agent.process(- requirement=requirement,- knowledge_context=knowledge_context,- reference_question=reference_question,+ await self._publish_question_complete_event(+ mode="topic",+ user_topic=user_topic,+ templates=templates,+ qa_pairs=qa_pairs,)+ return summary- if not gen_result.get("success"):- self.logger.error(f"Question generation failed: {gen_result.get('error')}")- return {- "success": False,- "error": gen_result.get("error", "Generation failed"),- }+ # ------------------------------------------------------------------+ # Path 2: Exam Paper -> Parse -> Templates -> Generation Loop+ # ------------------------------------------------------------------- question = gen_result["question"]+ async def generate_from_exam(+ self,+ exam_paper_path: str,+ max_questions: int,+ paper_mode: str = "upload",+ ) -> dict[str, Any]:+ self._init_batch_dir()- # Step 3: Analyze relevance- analyzer = self._create_relevance_analyzer()- analysis = await analyzer.process(- question=question,- knowledge_context=knowledge_context,+ templates, parse_trace = await self._parse_exam_to_templates(+ exam_paper_path=exam_paper_path,+ max_questions=max_questions,+ paper_mode=paper_mode,)- self.logger.success(f"Question generated with {analysis['relevance']} relevance")-- # Build result (compatible with old format)- result = {- "success": True,- "question": question,- "validation": {- "decision": "approve", # Always approve- "relevance": analysis["relevance"],- "kb_coverage": analysis["kb_coverage"],- "extension_points": analysis.get("extension_points", ""),+ # Save intermediate artifacts+ self._save_artifact("templates.json", [t.__dict__ for t in templates])+ self._save_artifact("parse_trace.json", parse_trace)++ await self._send_ws_update(+ "templates_ready",+ {+ "stage": "templates_ready",+ "templates": [t.__dict__ for t in templates],+ "count": len(templates),},- "rounds": 1, # No iteration- }+ )- # Save to disk if output_dir is set- if self.output_dir:- self._save_question_result(result, requirement)+ qa_pairs = await self._generation_loop(+ templates=templates,+ user_topic="",+ preference="",+ )- # Update token stats from shared LLMStats- self._update_token_stats()+ summary = self._build_summary(+ source="exam",+ requested=max_questions,+ templates=templates,+ qa_pairs=qa_pairs,+ trace=parse_trace,+ )+ self._save_artifact("summary.json", summary)- # Publish QUESTION_COMPLETE event for personalizationawait self._publish_question_complete_event(- requirement=requirement,- questions=[question],- mode="single",+ mode="exam",+ user_topic="",+ templates=templates,+ qa_pairs=qa_pairs,)+ return summary- return result+ # ------------------------------------------------------------------+ # Idea Loop+ # ------------------------------------------------------------------- async def generate_questions_custom(+ async def _idea_loop(self,- requirement: dict[str, Any],+ user_topic: str,+ preference: str,num_questions: int,- ) -> dict[str, Any]:- """- Custom mode: Generate multiple questions from a requirement.-- Flow:- 1. Researching: Retrieve background knowledge- 2. Planning: Generate question plan with focuses- 3. Generating: Generate each question + relevance analysis-- Args:- requirement: Base requirement dict (knowledge_point, difficulty, question_type)- num_questions: Number of questions to generate-- Returns:- Summary dict with all results- """- if num_questions <= 0:- raise ValueError("num_questions must be greater than zero")-- self.logger.section(f"Custom Mode Generation: {num_questions} question(s)")-- # Create batch directory- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- batch_dir = Path(self.output_dir) / f"batch_{timestamp}" if self.output_dir else None- if batch_dir:- batch_dir.mkdir(parents=True, exist_ok=True)-- # =====================================================================- # Stage 1: Researching- # =====================================================================- self.logger.stage("Stage 1: Researching")- await self._send_ws_update(- "progress",- {"stage": "researching", "progress": {"status": "retrieving"}, "total": num_questions},+ difficulty: str = "",+ question_type: str = "",+ ) -> tuple[list[QuestionTemplate], dict[str, Any]]:+ max_rounds = int(self.idea_cfg.get("max_rounds", 3))+ ideas_per_round = int(self.idea_cfg.get("ideas_per_round", max(3, num_questions)))++ idea_agent = self._create_idea_agent()+ evaluator = self._create_evaluator()+ idea_memory_context = await self._get_idea_memory_context(user_topic)+ evaluator_memory_context = await self._get_evaluator_memory_context(user_topic)+ idea_preference = self._merge_preference(preference, idea_memory_context)+ evaluator_preference = self._merge_preference(idea_preference, evaluator_memory_context)++ feedback = ""+ trace_rounds: list[dict[str, Any]] = []+ selected_templates: list[QuestionTemplate] = []+ normalized_difficulty = difficulty.strip().lower()+ normalized_question_type = question_type.strip().lower()+ target_difficulty = (+ normalized_difficulty+ if normalized_difficulty and normalized_difficulty != "auto"+ else "")-- retrieve_agent = self._create_retrieve_agent()- retrieval_result = await retrieve_agent.process(- requirement=requirement,- num_queries=self.rag_query_count,+ target_question_type = (+ normalized_question_type+ if normalized_question_type and normalized_question_type != "auto"+ else "")- if not retrieval_result.get("has_content"):- self.logger.warning("No relevant knowledge found")- return {- "success": False,- "error": "knowledge_not_found",- "message": "Knowledge base does not contain relevant information.",- "search_queries": retrieval_result.get("queries", []),- }-- knowledge_context = retrieval_result["summary"]- queries = retrieval_result["queries"]-- # Save knowledge.json- if batch_dir:- self._save_knowledge_json(batch_dir, retrieval_result)-- await self._send_ws_update("knowledge_saved", {"queries": queries})-- # =====================================================================- # Stage 2: Planning- # =====================================================================- self.logger.stage("Stage 2: Planning")- await self._send_ws_update(- "progress", {"stage": "planning", "progress": {"status": "creating_plan"}}- )+ for round_idx in range(1, max_rounds + 1):+ await self._send_ws_update(+ "progress",+ {+ "stage": "idea_loop",+ "status": "running",+ "current_round": round_idx,+ "max_rounds": max_rounds,+ },+ )- plan = await self._generate_question_plan(requirement, knowledge_context, num_questions)- focuses = plan.get("focuses", [])+ idea_result = await idea_agent.process(+ user_topic=user_topic,+ preference=idea_preference,+ evaluator_feedback=feedback,+ num_ideas=ideas_per_round,+ target_difficulty=target_difficulty,+ target_question_type=target_question_type,+ )+ ideas = idea_result.get("ideas", [])++ eval_result = await evaluator.process(+ user_topic=user_topic,+ preference=evaluator_preference,+ ideas=ideas,+ top_k=num_questions,+ current_round=round_idx,+ max_rounds=max_rounds,+ target_difficulty=target_difficulty,+ target_question_type=target_question_type,+ )- # Save plan.json- if batch_dir:- self._save_plan_json(batch_dir, plan)+ feedback = eval_result.get("feedback", "")+ selected_templates = eval_result.get("templates", [])+ continue_loop = eval_result.get("continue_loop", False)++ round_trace = {+ "round": round_idx,+ "ideas": ideas,+ "selected_ideas": eval_result.get("selected_ideas", []),+ "feedback": feedback,+ "continue_loop": continue_loop,+ "queries": idea_result.get("queries", []),+ }+ trace_rounds.append(round_trace)- await self._send_ws_update("plan_ready", {"plan": plan, "focuses": focuses})+ # Save per-round trace+ self._save_artifact(f"idea_round_{round_idx}.json", round_trace)- # =====================================================================- # Stage 3: Generating- # =====================================================================- self.logger.stage("Stage 3: Generating")- await self._send_ws_update(- "progress",- {"stage": "generating", "progress": {"current": 0, "total": num_questions}},- )+ await self._send_ws_update(+ "idea_round",+ {+ "round": round_idx,+ "ideas": ideas,+ "selected_ideas": eval_result.get("selected_ideas", []),+ "continue_loop": continue_loop,+ "feedback": feedback,+ },+ )- results = []- failures = []+ if not continue_loop:+ break++ if not selected_templates:+ selected_templates = [+ QuestionTemplate(+ question_id=f"q_{i+1}",+ concentration=f"{user_topic} - aspect {i+1}",+ question_type="written",+ difficulty="medium",+ source="custom",+ )+ for i in range(num_questions)+ ]- generate_agent = self._create_generate_agent()- analyzer = self._create_relevance_analyzer()+ return selected_templates[:num_questions], {+ "rounds": trace_rounds,+ "max_rounds": max_rounds,+ }- for idx, focus in enumerate(focuses):- question_id = focus.get("id", f"q_{idx + 1}")- self.logger.info(f"Generating question {question_id}")+ # ------------------------------------------------------------------+ # Generation Loop (with exception safety)+ # ------------------------------------------------------------------+ async def _generation_loop(+ self,+ templates: list[QuestionTemplate],+ user_topic: str,+ preference: str,+ ) -> list[dict[str, Any]]:+ max_retries = int(self.generation_cfg.get("max_retries", 2))+ generator = self._create_generator()+ validator = self._create_validator()++ results: list[dict[str, Any]] = []+ total = len(templates)++ for idx, template in enumerate(templates, 1):await self._send_ws_update(- "question_update",+ "progress",{- "question_id": question_id,- "status": "generating",- "focus": focus.get("focus", ""),+ "stage": "generating",+ "current": idx - 1,+ "total": total,+ "question_id": template.question_id,},)- # Generate question- gen_result = await generate_agent.process(- requirement=requirement,- knowledge_context=knowledge_context,- focus=focus,- )+ feedback = ""+ attempts: list[dict[str, Any]] = []+ final_qa: QAPair | None = None+ final_validation: dict[str, Any] = {}- if not gen_result.get("success"):- self.logger.error(f"Failed to generate question {question_id}")- failures.append(- {- "question_id": question_id,- "error": gen_result.get("error", "Unknown error"),- }- )+ for attempt in range(1, max_retries + 2):await self._send_ws_update(- "question_update", {"question_id": question_id, "status": "error"}+ "question_update",+ {+ "question_id": template.question_id,+ "status": "generating",+ "attempt": attempt,+ "max_attempts": max_retries + 1,+ },)- continue-- question = gen_result["question"]- # Analyze relevance- await self._send_ws_update(- "question_update", {"question_id": question_id, "status": "analyzing"}- )-- analysis = await analyzer.process(- question=question,- knowledge_context=knowledge_context,- )-- # Build validation dict (compatible with frontend)- validation = {- "decision": "approve",- "relevance": analysis["relevance"],- "kb_coverage": analysis["kb_coverage"],- "extension_points": analysis.get("extension_points", ""),- }+ try:+ template_preference = preference+ generator_memory_context = await self._get_generator_memory_context(+ template.concentration+ )+ template_preference = self._merge_preference(+ template_preference,+ generator_memory_context,+ )+ qa_pair = await generator.process(+ template=template,+ user_topic=user_topic,+ preference=template_preference,+ validator_feedback=feedback,+ )+ validation = await validator.process(+ template=template, qa_pair=qa_pair+ )++ attempts.append(+ {+ "attempt": attempt,+ "qa_pair": qa_pair.__dict__,+ "validation": validation,+ }+ )++ await self._send_ws_update(+ "validating",+ {+ "question_id": template.question_id,+ "attempt": attempt,+ "validation": validation,+ },+ )++ if validation.get("approved"):+ final_qa = qa_pair+ final_validation = validation+ break+ feedback = validation.get("feedback", "")++ except Exception as exc:+ self.logger.warning(+ f"Attempt {attempt} failed for {template.question_id}: {exc}"+ )+ attempts.append(+ {+ "attempt": attempt,+ "error": str(exc),+ }+ )+ feedback = f"Previous attempt raised an error: {exc}"++ # Reconstruct final_qa from last successful attempt if not approved+ if final_qa is None:+ for att in reversed(attempts):+ if "qa_pair" in att:+ try:+ final_qa = QAPair(+ **{+ k: v+ for k, v in att["qa_pair"].items()+ if k+ in {+ "question_id",+ "question",+ "correct_answer",+ "explanation",+ "question_type",+ "options",+ "concentration",+ "difficulty",+ "validation",+ "metadata",+ }+ }+ )+ final_validation = att.get("validation", {})+ except Exception:+ pass+ break++ # If ALL attempts failed with exceptions, create a placeholder+ if final_qa is None:+ final_qa = QAPair(+ question_id=template.question_id,+ question=f"[Generation failed] {template.concentration}",+ correct_answer="N/A",+ explanation="All generation attempts failed.",+ question_type=template.question_type,+ concentration=template.concentration,+ difficulty=template.difficulty,+ )+ final_validation = {+ "decision": "reject",+ "approved": False,+ "feedback": "All generation attempts failed with errors.",+ "issues": [str(a.get("error", "unknown")) for a in attempts if "error" in a],+ }- # Save result+ final_qa.validation = final_validationresult = {- "question_id": question_id,- "focus": focus,- "question": question,- "analysis": analysis,- "validation": validation, # For frontend compatibility+ "template": template.__dict__,+ "qa_pair": final_qa.__dict__,+ "attempts": attempts,+ "success": bool(final_validation.get("approved")),}-- if batch_dir:- self._save_custom_question_result(batch_dir, result)-results.append(result)- await self._send_ws_update(- "question_update", {"question_id": question_id, "status": "done"}+ # Save per-question artifact+ self._save_artifact(+ f"{template.question_id}_result.json", result)+await self._send_ws_update("result",{- "question_id": question_id,- "question": question,- "validation": validation, # Frontend expects 'validation'- "focus": focus,- "index": idx,+ "question_id": template.question_id,+ "index": idx - 1,+ "question": final_qa.__dict__,+ "validation": final_validation,+ "attempts": len(attempts),},)+await self._send_ws_update("progress",- {"stage": "generating", "progress": {"current": idx + 1, "total": num_questions}},+ {+ "stage": "generating",+ "current": idx,+ "total": total,+ "question_id": template.question_id,+ },)- # =====================================================================- # Complete- # =====================================================================- summary = {- "success": len(results) == num_questions,- "requested": num_questions,- "completed": len(results),- "failed": len(failures),- "search_queries": queries,- "plan": plan,- "results": results,- "failures": failures,- }+ await self._send_ws_update(+ "progress",+ {"stage": "complete", "completed": len(results), "total": total},+ )+ return results- if batch_dir:- summary_file = batch_dir / "summary.json"- with open(summary_file, "w", encoding="utf-8") as f:- json.dump(summary, f, indent=2, ensure_ascii=False)- summary["output_dir"] = str(batch_dir)+ # ------------------------------------------------------------------+ # Exam paper parsing+ # ------------------------------------------------------------------- # Update token stats from shared LLMStats- self._update_token_stats()+ async def _parse_exam_to_templates(+ self,+ exam_paper_path: str,+ max_questions: int,+ paper_mode: str,+ ) -> tuple[list[QuestionTemplate], dict[str, Any]]:+ await self._send_ws_update("progress", {"stage": "parsing", "status": "running"})++ paper_path = Path(exam_paper_path)+ output_base = (+ Path(self.output_dir)+ if self.output_dir+ else (project_root / "data" / "user" / "question" / "mimic_papers")+ )+ output_base.mkdir(parents=True, exist_ok=True)++ working_dir: Path+ if paper_mode == "parsed":+ working_dir = paper_path+ else:+ parse_success = parse_pdf_with_mineru(str(paper_path), str(output_base))+ if not parse_success:+ raise RuntimeError("Failed to parse exam paper with MinerU")+ subdirs = sorted(+ [d for d in output_base.iterdir() if d.is_dir()],+ key=lambda d: d.stat().st_mtime,+ reverse=True,+ )+ if not subdirs:+ raise RuntimeError("No parsed exam directory found after MinerU parsing")+ working_dir = subdirs[0]await self._send_ws_update("progress",- {- "stage": "complete",- "completed": len(results),- "failed": len(failures),- "total": num_questions,- },+ {"stage": "extracting", "status": "running", "paper_dir": str(working_dir)},)- self.logger.section("Generation Summary")- self.logger.info(f"Requested: {num_questions}")- self.logger.info(f"Completed: {len(results)}")- self.logger.info(f"Failed: {len(failures)}")+ json_files = list(working_dir.glob("*_questions.json"))+ if not json_files:+ extract_success = extract_questions_from_paper(+ str(working_dir), output_dir=None+ )+ if not extract_success:+ raise RuntimeError("Failed to extract questions from parsed exam")+ json_files = list(working_dir.glob("*_questions.json"))+ if not json_files:+ raise RuntimeError("Question extraction output not found")++ with open(json_files[0], encoding="utf-8") as f:+ payload = json.load(f)+ questions = payload.get("questions", [])+ if max_questions > 0:+ questions = questions[:max_questions]++ templates: list[QuestionTemplate] = []+ for i, item in enumerate(questions, 1):+ if not isinstance(item, dict):+ continue+ q_text = str(item.get("question_text", "")).strip()+ if not q_text:+ continue+ templates.append(+ QuestionTemplate(+ question_id=f"q_{i}",+ concentration=q_text[:240],+ question_type=str(item.get("question_type", "written")).lower(),+ difficulty="medium",+ source="mimic",+ reference_question=q_text,+ reference_answer=str(item.get("answer", "")).strip() or None,+ metadata={+ "question_number": item.get("question_number", str(i)),+ "images": item.get("images", []),+ },+ )+ )- # Publish QUESTION_COMPLETE event for personalization- generated_questions = [r["question"] for r in results if "question" in r]- await self._publish_question_complete_event(- requirement=requirement,- questions=generated_questions,- mode="custom",+ await self._send_ws_update(+ "progress",+ {"stage": "extracting", "status": "complete", "templates": len(templates)},)+ return templates, {+ "paper_dir": str(working_dir),+ "question_file": str(json_files[0]),+ "template_count": len(templates),+ }- return summary+ # ------------------------------------------------------------------+ # Summary & Events+ # ------------------------------------------------------------------- # =========================================================================- # Helper Methods- # =========================================================================+ def _build_summary(+ self,+ source: str,+ requested: int,+ templates: list[QuestionTemplate],+ qa_pairs: list[dict[str, Any]],+ trace: dict[str, Any],+ ) -> dict[str, Any]:+ completed = sum(1 for item in qa_pairs if item.get("success"))+ failed = len(qa_pairs) - completed+ return {+ "success": failed == 0 and completed > 0,+ "source": source,+ "requested": requested,+ "template_count": len(templates),+ "completed": completed,+ "failed": failed,+ "templates": [t.__dict__ for t in templates],+ "results": qa_pairs,+ "trace": trace,+ "batch_dir": str(self._batch_dir) if self._batch_dir else None,+ }async def _publish_question_complete_event(self,- requirement: dict[str, Any],- questions: list[dict[str, Any]],- mode: str = "single",+ mode: str,+ user_topic: str,+ templates: list[QuestionTemplate],+ qa_pairs: list[dict[str, Any]],) -> None:- """- Publish QUESTION_COMPLETE event for personalization.-- Args:- requirement: Question requirement dict- questions: List of generated questions- mode: Generation mode ("single" or "custom")- """try:from src.core.event_bus import Event, EventType, get_event_bus- # Build summary of generated questions- question_summaries = []- for q in questions[:3]: # Limit to first 3 for efficiency- summary = {- "type": q.get("question_type", "unknown"),- "question": q.get("question", "")[:200],+ question_summaries = [+ {+ "type": item.get("qa_pair", {}).get("question_type", "unknown"),+ "question": item.get("qa_pair", {}).get("question", "")[:200],}- question_summaries.append(summary)+ for item in qa_pairs[:3]+ ]++ # Collect actually used tools from results+ tools_used = set()+ for item in qa_pairs:+ plan = item.get("qa_pair", {}).get("metadata", {}).get("tool_plan", {})+ if plan.get("use_rag"):+ tools_used.add("rag_tool")+ if plan.get("use_web"):+ tools_used.add("web_search")+ if plan.get("use_code"):+ tools_used.add("write_code")event = Event(type=EventType.QUESTION_COMPLETE,task_id=f"question_{mode}_{datetime.now().strftime('%Y%m%d_%H%M%S')}",- user_input=json.dumps({- "knowledge_point": requirement.get("knowledge_point", ""),- "difficulty": requirement.get("difficulty", ""),- "question_type": requirement.get("question_type", ""),- }, ensure_ascii=False),+ user_input=json.dumps(+ {+ "topic": user_topic,+ "mode": mode,+ "template_count": len(templates),+ },+ ensure_ascii=False,+ ),agent_output=json.dumps(question_summaries, ensure_ascii=False),- tools_used=["rag_tool"],- success=len(questions) > 0,+ tools_used=list(tools_used),+ success=any(item.get("success") for item in qa_pairs),metadata={"mode": mode,- "num_questions": len(questions),- "knowledge_point": requirement.get("knowledge_point", ""),+ "num_questions": len(qa_pairs),+ "batch_dir": str(self._batch_dir) if self._batch_dir else "",+ "user_topic": user_topic,},)await get_event_bus().publish(event)- self.logger.debug(f"Published QUESTION_COMPLETE event (mode={mode})")- except Exception as e:- self.logger.debug(f"Failed to publish QUESTION_COMPLETE event: {e}")+ except Exception as exc:+ self.logger.debug(f"Failed to publish QUESTION_COMPLETE event: {exc}")- async def _generate_question_plan(- self,- requirement: dict[str, Any],- knowledge_context: str,- num_questions: int,- ) -> dict[str, Any]:- """- Generate a question plan with distinct focuses.-- Args:- requirement: Base requirement- knowledge_context: Retrieved knowledge summary- num_questions: Number of questions-- Returns:- Plan dict with focuses array- """- from src.services.llm import complete as llm_complete- from src.services.llm.config import get_llm_config-- llm_config = get_llm_config()-- system_prompt = (- "You are an educational content planner. Create distinct question focuses "- "that test different aspects of the same topic.\n\n"- "CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.\n"- 'Output JSON with key "focuses" containing an array of objects, each with:\n'- '- "id": string like "q_1", "q_2"\n'- '- "focus": string describing what aspect to test\n'- f'- "type": "{requirement.get("question_type", "written")}"'- )-- # Truncate knowledge context consistently (4000 chars across all agents)- truncated_knowledge = (- knowledge_context[:4000] if len(knowledge_context) > 4000 else knowledge_context- )- truncation_suffix = "...[truncated]" if len(knowledge_context) > 4000 else ""-- user_prompt = (- f"Topic: {requirement.get('knowledge_point', '')}\n"- f"Difficulty: {requirement.get('difficulty', 'medium')}\n"- f"Question Type: {requirement.get('question_type', 'written')}\n"- f"Number: {num_questions}\n\n"- f"Knowledge:\n{truncated_knowledge}{truncation_suffix}\n\n"- f"Generate exactly {num_questions} distinct focuses in JSON."- )+ async def _get_idea_memory_context(self, topic: str) -> str:+ from src.personalization.memory_reader import get_memory_reader_instance+ reader = get_memory_reader_instance()+ if not reader:+ return ""try:- response = await llm_complete(- prompt=user_prompt,- system_prompt=system_prompt,- model=llm_config.model,- api_key=self._api_key or llm_config.api_key,- base_url=self._base_url or llm_config.base_url,- api_version=self._api_version,- response_format={"type": "json_object"},- temperature=0.3,- )+ return await reader.get_idea_context(topic)+ except Exception:+ return ""- data = json.loads(response)- focuses = data.get("focuses", [])- if not isinstance(focuses, list):- focuses = []-- except Exception as e:- self.logger.warning(f"Failed to generate plan: {e}")- focuses = []-- # Fallback: create simple focuses- if len(focuses) < num_questions:- question_type = requirement.get("question_type", "written")- for i in range(len(focuses), num_questions):- focuses.append(- {- "id": f"q_{i + 1}",- "focus": f"Aspect {i + 1} of {requirement.get('knowledge_point', 'topic')}",- "type": question_type,- }- )-- return {- "knowledge_point": requirement.get("knowledge_point", ""),- "difficulty": requirement.get("difficulty", "medium"),- "question_type": requirement.get("question_type", "written"),- "num_questions": num_questions,- "focuses": focuses[:num_questions],- }-- def _save_question_result(- self,- result: dict[str, Any],- requirement: dict[str, Any],- ) -> str | None:- """Save a single question result to disk."""- if not self.output_dir:- return None+ async def _get_evaluator_memory_context(self, topic: str) -> str:+ from src.personalization.memory_reader import get_memory_reader_instance+ reader = get_memory_reader_instance()+ if not reader:+ return ""try:- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- output_path = Path(self.output_dir) / f"question_{timestamp}"- output_path.mkdir(parents=True, exist_ok=True)-- # Save result.json- with open(output_path / "result.json", "w", encoding="utf-8") as f:- json.dump(result, f, indent=2, ensure_ascii=False)-- # Save question.md- question = result.get("question", {})- validation = result.get("validation", {})-- md_content = f"""# Generated Question--**Knowledge point**: {requirement.get("knowledge_point", question.get("knowledge_point", "N/A"))}-**Difficulty**: {requirement.get("difficulty", "N/A")}-**Type**: {question.get("question_type", "N/A")}-**Relevance**: {validation.get("relevance", "N/A")}-------## Question-{question.get("question", "")}--"""- if question.get("options"):- md_content += "## Options\n"- for key, value in question.get("options", {}).items():- md_content += f"- **{key}**: {value}\n"- md_content += "\n"-- md_content += f"""-## Answer-{question.get("correct_answer", "")}--## Explanation-{question.get("explanation", "")}-------## Relevance Analysis--**KB Coverage**: {validation.get("kb_coverage", "")}-"""- if validation.get("extension_points"):- md_content += f"\n**Extension Points**: {validation.get('extension_points', '')}"-- with open(output_path / "question.md", "w", encoding="utf-8") as f:- f.write(md_content)-- self.logger.info(f"Result saved to: {output_path}")- return str(output_path)-- except Exception as e:- self.logger.warning(f"Failed to save result: {e}")- return None-- def _save_knowledge_json(- self,- batch_dir: Path,- retrieval_result: dict[str, Any],- ):- """Save knowledge.json for a batch."""- knowledge_file = batch_dir / "knowledge.json"- with open(knowledge_file, "w", encoding="utf-8") as f:- json.dump(- {- "queries": retrieval_result.get("queries", []),- "retrievals": retrieval_result.get("retrievals", []),- },- f,- indent=2,- ensure_ascii=False,- )-- def _save_plan_json(self, batch_dir: Path, plan: dict[str, Any]):- """Save plan.json for a batch."""- plan_file = batch_dir / "plan.json"- with open(plan_file, "w", encoding="utf-8") as f:- json.dump(plan, f, indent=2, ensure_ascii=False)-- def _save_custom_question_result(- self,- batch_dir: Path,- result: dict[str, Any],- ):- """Save a single question result in custom mode."""- question_id = result.get("question_id", "q_unknown")- question_dir = batch_dir / question_id- question_dir.mkdir(parents=True, exist_ok=True)-- # Save result.json- with open(question_dir / "result.json", "w", encoding="utf-8") as f:- json.dump(result, f, indent=2, ensure_ascii=False)-- # Save question.md- question = result.get("question", {})- analysis = result.get("analysis", {})- focus = result.get("focus", {})-- md_content = f"""# Generated Question+ return await reader.get_evaluator_context(topic)+ except Exception:+ return ""-**Focus**: {focus.get("focus", "N/A")}-**Type**: {question.get("question_type", "N/A")}-**Relevance**: {analysis.get("relevance", "N/A")}+ async def _get_generator_memory_context(self, concentration: str) -> str:+ from src.personalization.memory_reader import get_memory_reader_instance------## Question-{question.get("question", "")}--"""- if question.get("options"):- md_content += "## Options\n"- for key, value in question.get("options", {}).items():- md_content += f"- **{key}**: {value}\n"- md_content += "\n"-- md_content += f"""-## Answer-{question.get("correct_answer", "")}--## Explanation-{question.get("explanation", "")}-------## Relevance Analysis--**KB Coverage**: {analysis.get("kb_coverage", "")}-"""- if analysis.get("extension_points"):- md_content += f"\n**Extension Points**: {analysis.get('extension_points', '')}"-- with open(question_dir / "question.md", "w", encoding="utf-8") as f:- f.write(md_content)+ reader = get_memory_reader_instance()+ if not reader:+ return ""+ try:+ return await reader.get_generator_context(concentration)+ except Exception:+ return ""++ @staticmethod+ def _merge_preference(user_pref: str, memory_context: str) -> str:+ pref = (user_pref or "").strip()+ mem = (memory_context or "").strip()+ if pref and mem:+ return f"{pref}\n\n[Memory Context]\n{mem}"+ if mem:+ return f"[Memory Context]\n{mem}"+ return prefdiff --git a/src/agents/question/models.py b/src/agents/question/models.pynew file mode 100644index 000000000..4deb1ede3--- /dev/null+++ b/src/agents/question/models.py@@ -0,0 +1,42 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+Data models for the refactored question pipeline.+"""++from dataclasses import dataclass, field+from typing import Any+++@dataclass+class QuestionTemplate:+ """+ Standardized intermediate template shared by all input paths.+ """++ question_id: str+ concentration: str+ question_type: str+ difficulty: str+ source: str = "custom"+ reference_question: str | None = None+ reference_answer: str | None = None+ metadata: dict[str, Any] = field(default_factory=dict)+++@dataclass+class QAPair:+ """+ Final generated Q-A payload.+ """++ question_id: str+ question: str+ correct_answer: str+ explanation: str+ question_type: str+ options: dict[str, str] | None = None+ concentration: str = ""+ difficulty: str = ""+ validation: dict[str, Any] = field(default_factory=dict)+ metadata: dict[str, Any] = field(default_factory=dict)diff --git a/src/agents/question/prompts/en/coordinator.yaml b/src/agents/question/prompts/en/coordinator.yamldeleted file mode 100644index 536e7b6e3..000000000--- a/src/agents/question/prompts/en/coordinator.yaml+++ /dev/null@@ -1,75 +0,0 @@-generate_search_queries: |- system: |- 【Role】You are a knowledge base retrieval assistant, preparing for question generation.-- 【Current Task】Generate knowledge point retrieval queries to find theoretical explanations, definitions, and theorems in the knowledge base.- ⚠️ Key: You are not generating questions now! You are looking for theoretical knowledge needed for question generation!-- 【Output Rules】- 1. Only output pure knowledge point names (theorem names, concept names, method names)- 2. Each query should be 2-5 words- 3. Do not include functions, numerical values, or calculation tasks- 4. Do not use questions or task descriptions-- user_template: |- The user's question generation requirement is:- {requirement_text}-- Please extract {num_queries} pure knowledge point names from it for knowledge base retrieval.-- Correct examples:- ✅ Taylor theorem- ✅ Lagrange multipliers- ✅ critical points-- Incorrect examples (do not generate):- ❌ Apply Taylor's Theorem to approximate f(x,y)=... (This is a question)- ❌ Find and classify critical points (This is a task)- ❌ Use Lagrange multipliers to find maximum (This is an instruction)-- Return in JSON format: {{"queries": ["knowledge point 1", "knowledge point 2", ...]}}, containing exactly {num_queries} knowledge point names.--check_retrieval_relevance: |- system: |- You evaluate whether retrieved knowledge is relevant to a user's request.- Respond in JSON with key "relevant" (true/false) and optional "reason".-- user_template: |- User request:- {requirement_text}-- Retrieved knowledge summary:- {knowledge_summary}-- Is the retrieved knowledge substantively relevant to the request?--generate_child_requirements: |- system: |- You are a curriculum designer. Given a base requirement and knowledge summary,- create distinct sub-requirements that all test the SAME knowledge point.- Each sub-requirement must describe a unique scenario and reasoning flow.- Output JSON with key "requirements" (array of length requested) where each item has:- "title", "question_type", "difficulty", "additional_requirements".-- user_template: |- Base requirement:- {base_requirement}-- Knowledge summary:- {knowledge_summary}-- Generate exactly {num_questions} sub-requirements in JSON.--interpret_requirement_text: |- system: |- You are an instruction parser for an exam-question generator.- Given a natural-language request, extract the core knowledge point,- difficulty (easy/medium/hard), preferred question type (choice/written),- and additional requirements. Return JSON with keys:- "knowledge_point", "difficulty", "question_type", "additional_requirements".-- user_template: |- Requirement:- {requirement_text}-- Return JSON only.diff --git a/src/agents/question/prompts/en/evaluator.yaml b/src/agents/question/prompts/en/evaluator.yamlnew file mode 100644index 000000000..abbff6885--- /dev/null+++ b/src/agents/question/prompts/en/evaluator.yaml@@ -0,0 +1,54 @@+system: |+ You are an Evaluator in a question-design workflow.+ You assess idea quality and diversity, and decide whether another iteration is needed.++evaluate_ideas: |+ Topic:+ {user_topic}++ User preference:+ {preference}++ Current round: {current_round}+ Max rounds: {max_rounds}+ Required top-k: {top_k}++ Candidate ideas:+ {ideas_json}++ Evaluate each idea by:+ - relevance to topic+ - diversity across ideas+ - alignment with user preference+ - clarity and feasibility+ - question_type validity: MUST be one of "choice", "written", "coding" — any other type (e.g. visual, diagram, matching) is INVALID++ If any idea has an invalid question_type, or quality/diversity is insufficient,+ and rounds remain, set continue_loop=true and provide actionable feedback+ (explicitly list which ideas have invalid types and what they should be changed to).+ Otherwise set continue_loop=false and select top-k ideas.++ Return only JSON:+ {{+ "continue_loop": false,+ "feedback": "specific guidance for next round",+ "scores": [+ {{+ "idea_id": "idea_1",+ "relevance_score": 0.0,+ "diversity_score": 0.0,+ "preference_score": 0.0,+ "overall_score": 0.0,+ "comment": "brief reason"+ }}+ ],+ "selected_ideas": [+ {{+ "idea_id": "idea_1",+ "concentration": "focus area",+ "question_type": "choice or written or coding",+ "difficulty": "easy or medium or hard",+ "rationale": "why selected"+ }}+ ]+ }}diff --git a/src/agents/question/prompts/en/generate_agent.yaml b/src/agents/question/prompts/en/generate_agent.yamldeleted file mode 100644index e29b3cfb8..000000000--- a/src/agents/question/prompts/en/generate_agent.yaml+++ /dev/null@@ -1,83 +0,0 @@-system: |- You are a professional Question Generation Agent. Your responsibilities are:- 1. Generate high-quality questions based on requirements- 2. Use retrieved background knowledge to ensure accuracy- 3. Express knowledge in the same way as the knowledge base-- Important notes:- - Questions must be rigorous and accurate, based on knowledge base content- - Calculation problems should have substantial computation, not too simple- - Use the provided background knowledge as the foundation for question generation- - Multiple choice questions must have only one correct answer- - Solutions/explanations should be detailed and clear- - Chain-of-thought: reason internally step-by-step, but only output the final JSON--generate: |- Generate a question based on the following information:-- ## User Preference- {preference}-- Requirements:- {requirements}-- Focus/Angle:- {focus}-- Background Knowledge:- {knowledge}-- Thinking instructions:- - First, silently plan the scenario and reasoning steps to ensure the question is coherent.- - Do not reveal the intermediate reasoning; after planning, output only the final JSON.-- CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.- Your response must start with {{ and end with }}.-- Please generate a question in JSON format:- {{- "question_type": "choice" or "written",- "question": "question content",- "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // only for multiple choice- "correct_answer": "correct answer",- "explanation": "detailed explanation"- }}--generate_with_reference: |- Generate a new question that draws inspiration from the following reference but is clearly distinct in scenario and reasoning:-- ## User Preference- {preference}-- Reference question:- {reference_question}-- Requirements:- {requirements}-- Background Knowledge:- {knowledge}-- Requirements:- 1. **Maintain same core knowledge and difficulty**: Concepts being tested must stay aligned- 2. **Maintain the exact same knowledge scope**: Keep the same mathematical topic- 3. **Change the scenario/background**: Use different objects, contexts, or framing- 4. **Change the calculation process**: Rearrange steps or add sub-questions- 5. **Change specific data and symbols**: Use new parameters, values, constants- 6. **Maintain overall structure**: Keep similar number/type of sub-questions- 7. **Forbidden**:- - Only modifying numerical values or variable names- - Repeating the same statement with an added explanation- - Copying the same setup without new twists-- CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.- Your response must start with {{ and end with }}.-- Please generate question in JSON format:- {{- "question_type": "choice" or "written",- "question": "question content",- "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // only for multiple choice- "correct_answer": "correct answer",- "explanation": "detailed explanation"- }}diff --git a/src/agents/question/prompts/en/generator.yaml b/src/agents/question/prompts/en/generator.yamlnew file mode 100644index 000000000..2e5963cca--- /dev/null+++ b/src/agents/question/prompts/en/generator.yaml@@ -0,0 +1,74 @@+system: |+ You are the Generator in a question pipeline.+ Produce high-quality Q-A pairs from a structured QuestionTemplate.+ You can leverage tool outputs (rag/web/code) as grounding evidence when available.++plan_tools: |+ You are planning which tools to use before generating a question.++ QuestionTemplate:+ {template}++ User topic: {user_topic}+ User preference: {preference}++ Available tools:+ {available_tools}++ Decide which tools are genuinely helpful for THIS specific question template.+ Do NOT use tools just because they are available — only select them when they+ add real value. Consider:+ - rag_tool: Usually helpful for curriculum-aligned factual/conceptual questions.+ Less useful if the template already contains a reference question with a full answer.+ - web_search: Helpful for real-world examples, current events, or when KB may lack coverage.+ Unnecessary for standard textbook content.+ - write_code: Helpful for coding questions, numerical verification, or algorithmic problems.+ Unnecessary for purely conceptual or essay-type questions.++ Return JSON only:+ {{+ "use_rag": true or false,+ "use_web": true or false,+ "use_code": true or false,+ "rag_query": "specific knowledge retrieval query (only if use_rag is true)",+ "web_query": "specific web search query (only if use_web is true)",+ "reasoning": "one-sentence explanation of your tool choices"+ }}++generate: |+ QuestionTemplate:+ {template}++ User topic:+ {user_topic}++ User preference:+ {preference}++ Validator feedback from previous attempt:+ {validator_feedback}++ Tool context (knowledge/search results, if any):+ {tool_context}++ Requirements:+ - Keep strict alignment with template.concentration and template.difficulty.+ - Respect template.question_type.+ - If question_type is choice, provide 4 options and one correct answer.+ - For choice questions, ensure options are well-differentiated and balanced in length.+ Do NOT make the correct answer noticeably longer or more detailed than distractors.+ All options should be plausible and similar in style/length to avoid test-taking shortcuts.+ - Provide a clear explanation.+ - Only include `verification_code` (python) if it is genuinely useful to verify+ the correctness of your answer (e.g., for coding or math questions).+ Do NOT include verification code for conceptual or essay questions.++ Return JSON only:+ {{+ "question_type": "choice or written or coding",+ "question": "question content",+ "options": {{"A":"...","B":"...","C":"...","D":"..."}},+ "correct_answer": "final answer",+ "explanation": "detailed explanation",+ "verification_code": "optional python code — only if useful for answer verification"+ }}diff --git a/src/agents/question/prompts/en/idea_agent.yaml b/src/agents/question/prompts/en/idea_agent.yamlnew file mode 100644index 000000000..3bb43f1eb--- /dev/null+++ b/src/agents/question/prompts/en/idea_agent.yaml@@ -0,0 +1,68 @@+system: |+ You are an Idea Agent for exam question design.+ Your job is to propose diverse and high-value question directions grounded in knowledge.++generate_queries: |+ Topic: {user_topic}++ Generate exactly {num_queries} concise retrieval queries for a knowledge base search.+ Rules:+ - Each query should be a concept, theorem, method, or key term.+ - Avoid full task instructions.+ - Keep each query short and precise.++ Return only JSON:+ {{+ "queries": ["...", "..."]+ }}++generate_ideas: |+ Topic:+ {user_topic}++ User preference:+ {preference}++ Evaluator feedback from previous round:+ {evaluator_feedback}++ Grounding knowledge:+ {knowledge_context}++ Generate exactly {num_ideas} candidate question ideas.+ Focus on diversity, relevance, and alignment with user preference.++ IMPORTANT — question_type must be exactly one of these three values:+ - "choice" (multiple-choice, 4 options, one correct)+ - "written" (short-answer / essay)+ - "coding" (programming / computational)+ Do NOT invent other types (e.g. visual, diagram, matching, etc.).++ Return only JSON in this format:+ {{+ "ideas": [+ {{+ "idea_id": "idea_1",+ "concentration": "what this question should focus on",+ "question_type": "choice | written | coding",+ "difficulty": "easy or medium or hard",+ "rationale": "why this idea is valuable"+ }}+ ]+ }}++aggregate_context: |+ You are given multiple knowledge retrieval results for the topic: {user_topic}++ Raw retrieval results:+ {raw_context}++ Synthesize the above into a single, well-organized knowledge summary.+ Rules:+ - Remove redundant or duplicate information.+ - Preserve key concepts, theorems, formulas, and examples.+ - Organize logically (definitions first, then properties/methods, then applications).+ - Keep the summary concise but information-dense.+ - Do NOT add information that is not present in the retrievals.++ Return the synthesized knowledge summary as plain text (no JSON).diff --git a/src/agents/question/prompts/en/relevance_analyzer.yaml b/src/agents/question/prompts/en/relevance_analyzer.yamldeleted file mode 100644index 846dd5bf0..000000000--- a/src/agents/question/prompts/en/relevance_analyzer.yaml+++ /dev/null@@ -1,41 +0,0 @@-system: |- You are an educational content analyst specializing in analyzing the relationship- between exam questions and knowledge base content.-- Your task is to analyze the relevance between a question and the knowledge base,- NOT to validate or reject the question. All questions are accepted.--analyze_relevance: |- Analyze the relevance between the following exam question and the knowledge base content.-- Question:- {question}-- Knowledge Base Content:- {knowledge}-- Please analyze and provide a JSON response with the following structure:- {{- "relevance": "high" or "partial",- "kb_coverage": "Describe specifically what concepts, theories, or methods from the knowledge base this question tests. List the key knowledge points that are directly relevant.",- "extension_points": "If relevance is 'partial', describe what aspects of this question extend beyond the knowledge base content. What additional knowledge does it require? Leave empty if relevance is 'high'."- }}-- Guidelines for determining relevance:- 1. "high" - The question can be fully answered using only the knowledge base content. All concepts, methods, and required knowledge are present in the KB.- 2. "partial" - The question is related to the KB content but requires some knowledge beyond what's provided. The KB serves as a foundation but the question extends to additional areas.-- For kb_coverage:- - Be specific about which concepts from the KB are being tested- - Reference the actual content from the KB where possible- - Explain how the KB content relates to the question-- For extension_points (only when relevance is "partial"):- - Identify what additional knowledge is needed- - Explain how the question extends from the KB foundation- - Keep the tone positive - extensions are valuable for learning-- CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.- Your response must start with {{ and end with }}.-- Output only the JSON, no additional text.diff --git a/src/agents/question/prompts/en/retrieve_agent.yaml b/src/agents/question/prompts/en/retrieve_agent.yamldeleted file mode 100644index 04bba6047..000000000--- a/src/agents/question/prompts/en/retrieve_agent.yaml+++ /dev/null@@ -1,32 +0,0 @@-system: |- You are a knowledge base retrieval assistant, preparing for question generation.-- Your task is to generate knowledge point retrieval queries to find theoretical explanations,- definitions, and theorems in the knowledge base.-- Key principle: You are NOT generating questions now! You are looking for theoretical knowledge- needed for question generation.--generate_queries: |- The user's question generation requirement is:- {requirement_text}-- Please extract {num_queries} pure knowledge point names for knowledge base retrieval.-- Output Rules:- 1. Only output pure knowledge point names (theorem names, concept names, method names)- 2. Each query should be 2-5 words- 3. Do not include functions, numerical values, or calculation tasks- 4. Do not use questions or task descriptions-- Correct examples:- ✓ Taylor theorem- ✓ Lagrange multipliers- ✓ critical points-- Incorrect examples (do not generate):- ✗ Apply Taylor's Theorem to approximate f(x,y)=... (This is a question)- ✗ Find and classify critical points (This is a task)- ✗ Use Lagrange multipliers to find maximum (This is an instruction)-- Return in JSON format: {{"queries": ["knowledge point 1", "knowledge point 2", ...]}}, containing exactly {num_queries} knowledge point names.diff --git a/src/agents/question/prompts/en/validator.yaml b/src/agents/question/prompts/en/validator.yamlnew file mode 100644index 000000000..3ef50e9b0--- /dev/null+++ b/src/agents/question/prompts/en/validator.yaml@@ -0,0 +1,38 @@+system: |+ You are the Validator in a question pipeline.+ Validate quality and requirement alignment, then decide approve/reject.+ You also decide whether running verification code would help validate the answer.++validate: |+ Template:+ {template}++ Generated Q-A pair:+ {qa_pair}++ Verification code available: {has_code}++ Validation checklist:+ - Is the question aligned with template concentration?+ - Is the difficulty appropriate?+ - Is the answer correct and consistent with explanation?+ - For choice questions, exactly one option should be correct.+ - For choice questions, check that options are balanced in length and style.+ Reject if the correct answer is noticeably longer/more detailed than distractors,+ or if options lack meaningful differentiation (too similar or too obviously wrong).+ - Is the output clear and complete?++ Also decide whether code verification is needed:+ - Set needs_code_check to true ONLY if: verification code is available AND+ the question type benefits from computational verification (e.g., coding,+ math, algorithm questions).+ - Set needs_code_check to false for: conceptual, essay, definition, or+ purely theoretical questions — even if verification code is provided.++ Return JSON only:+ {{+ "decision": "approve or reject",+ "feedback": "specific regeneration instruction if reject; concise confirmation if approve",+ "issues": ["issue_1", "issue_2"],+ "needs_code_check": true or false+ }}diff --git a/src/agents/question/prompts/zh/coordinator.yaml b/src/agents/question/prompts/zh/coordinator.yamldeleted file mode 100644index e5e9dc070..000000000--- a/src/agents/question/prompts/zh/coordinator.yaml+++ /dev/null@@ -1,75 +0,0 @@-generate_search_queries: |- system: |- 【角色】你是一个知识库检索助手,为题目生成做准备。-- 【当前任务】生成知识点检索查询,在知识库中查找理论解释、定义和定理。- ⚠️ 关键:你现在不是在生成题目!你是在寻找题目生成所需的理论知识!-- 【输出规则】- 1. 只输出纯粹的知识点名称(定理名称、概念名称、方法名称)- 2. 每个查询应为2-5个词- 3. 不要包含函数、数值或计算任务- 4. 不要使用问题或任务描述-- user_template: |- 用户的题目生成需求是:- {requirement_text}-- 请从中提取{num_queries}个纯知识点名称用于知识库检索。-- 正确示例:- ✅ 泰勒定理- ✅ 拉格朗日乘数法- ✅ 临界点-- 错误示例(不要生成):- ❌ 应用泰勒定理近似f(x,y)=...(这是一道题目)- ❌ 求临界点并分类(这是一个任务)- ❌ 用拉格朗日乘数法求最大值(这是一条指令)-- 以JSON格式返回:{{"queries": ["知识点1", "知识点2", ...]}},恰好包含{num_queries}个知识点名称。--check_retrieval_relevance: |- system: |- 你评估检索到的知识是否与用户的请求相关。- 以JSON格式响应,包含键"relevant"(true/false)和可选的"reason"。-- user_template: |- 用户请求:- {requirement_text}-- 检索到的知识摘要:- {knowledge_summary}-- 检索到的知识是否实质上与请求相关?--generate_child_requirements: |- system: |- 你是一个课程设计师。给定一个基础需求和知识摘要,- 创建测试相同知识点的不同子需求。- 每个子需求必须描述独特的场景和推理流程。- 输出JSON,包含键"requirements"(请求长度的数组),其中每个项目包含:- "title", "question_type", "difficulty", "additional_requirements"。-- user_template: |- 基础需求:- {base_requirement}-- 知识摘要:- {knowledge_summary}-- 以JSON格式生成恰好{num_questions}个子需求。--interpret_requirement_text: |- system: |- 你是考试题目生成器的指令解析器。- 给定一个自然语言请求,提取核心知识点、- 难度(easy/medium/hard)、首选题型(choice/written)、- 和额外要求。返回JSON,包含键:- "knowledge_point", "difficulty", "question_type", "additional_requirements"。-- user_template: |- 需求:- {requirement_text}-- 仅返回JSON。diff --git a/src/agents/question/prompts/zh/evaluator.yaml b/src/agents/question/prompts/zh/evaluator.yamlnew file mode 100644index 000000000..dec9e9410--- /dev/null+++ b/src/agents/question/prompts/zh/evaluator.yaml@@ -0,0 +1,53 @@+system: |+ 你是出题流程中的 Evaluator。+ 你的职责是评估创意质量与多样性,并决定是否需要下一轮迭代。++evaluate_ideas: |+ 主题:+ {user_topic}++ 用户偏好:+ {preference}++ 当前轮次:{current_round}+ 最大轮次:{max_rounds}+ 目标 top-k:{top_k}++ 候选创意:+ {ideas_json}++ 请按以下维度评估每个创意:+ - 与主题的相关性+ - 创意之间的多样性+ - 与用户偏好的一致性+ - 可执行性与清晰度+ - question_type 合法性:必须为 "choice"、"written"、"coding" 之一,其他类型(如 visual、diagram、matching)均为非法++ 若存在非法 question_type,或质量/多样性不足且仍有轮次,+ 请设置 continue_loop=true,并在 feedback 中明确指出哪些创意的类型非法、应改为何种类型。+ 否则设置 continue_loop=false,并输出 top-k 创意。++ 仅返回 JSON:+ {{+ "continue_loop": false,+ "feedback": "下一轮改进建议",+ "scores": [+ {{+ "idea_id": "idea_1",+ "relevance_score": 0.0,+ "diversity_score": 0.0,+ "preference_score": 0.0,+ "overall_score": 0.0,+ "comment": "简短理由"+ }}+ ],+ "selected_ideas": [+ {{+ "idea_id": "idea_1",+ "concentration": "考察方向",+ "question_type": "choice 或 written 或 coding",+ "difficulty": "easy 或 medium 或 hard",+ "rationale": "入选原因"+ }}+ ]+ }}diff --git a/src/agents/question/prompts/zh/generate_agent.yaml b/src/agents/question/prompts/zh/generate_agent.yamldeleted file mode 100644index 0ee75a8a0..000000000--- a/src/agents/question/prompts/zh/generate_agent.yaml+++ /dev/null@@ -1,83 +0,0 @@-system: |- 你是一个专业的题目生成 Agent。你的职责是:- 1. 根据要求生成高质量的题目- 2. 使用检索到的背景知识确保准确性- 3. 用与知识库相同的方式表达知识-- 重要说明:- - 题目必须严谨准确,基于知识库内容- - 计算题应有实质性的计算,不能太简单- - 使用提供的背景知识作为题目生成的基础- - 选择题必须只有一个正确答案- - 解答/解释应详细清晰- - 思维链:内部逐步推理,但只输出最终的 JSON--generate: |- 根据以下信息生成题目:-- ## 用户偏好- {preference}-- 要求:- {requirements}-- 焦点/角度:- {focus}-- 背景知识:- {knowledge}-- 思考说明:- - 首先,默默地规划场景和推理步骤,确保题目连贯。- - 不要透露中间推理;规划后只输出最终的 JSON。-- 关键:只返回有效的 JSON。不要用 markdown 代码块包装。- 你的回复必须以 {{ 开始,以 }} 结束。-- 请以 JSON 格式生成题目:- {{- "question_type": "choice" 或 "written",- "question": "题目内容",- "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // 仅选择题需要- "correct_answer": "正确答案",- "explanation": "详细解释"- }}--generate_with_reference: |- 生成一道新题目,从以下参考题目获取灵感,但在场景和推理上明显不同:-- ## 用户偏好- {preference}-- 参考题目:- {reference_question}-- 要求:- {requirements}-- 背景知识:- {knowledge}-- 要求:- 1. **保持相同的核心知识和难度**:测试的概念必须保持一致- 2. **保持完全相同的知识范围**:保持相同的数学主题- 3. **改变场景/背景**:使用不同的对象、情境或框架- 4. **改变计算过程**:重新安排步骤或添加子问题- 5. **改变具体数据和符号**:使用新的参数、值、常数- 6. **保持整体结构**:保持相似数量/类型的子问题- 7. **禁止**:- - 只修改数值或变量名- - 重复相同的陈述并添加解释- - 复制相同的设置而没有新的变化-- 关键:只返回有效的 JSON。不要用 markdown 代码块包装。- 你的回复必须以 {{ 开始,以 }} 结束。-- 请以 JSON 格式生成题目:- {{- "question_type": "choice" 或 "written",- "question": "题目内容",- "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // 仅选择题需要- "correct_answer": "正确答案",- "explanation": "详细解释"- }}diff --git a/src/agents/question/prompts/zh/generator.yaml b/src/agents/question/prompts/zh/generator.yamlnew file mode 100644index 000000000..be3c3a3cf--- /dev/null+++ b/src/agents/question/prompts/zh/generator.yaml@@ -0,0 +1,71 @@+system: |+ 你是出题流程中的 Generator。+ 你需要基于结构化的 QuestionTemplate 产出高质量 Q-A 对。+ 当有工具输出(rag/web/code)可用时,可作为生成依据。++plan_tools: |+ 你正在规划生成题目前需要使用哪些工具。++ QuestionTemplate:+ {template}++ 用户主题:{user_topic}+ 用户偏好:{preference}++ 可用工具:+ {available_tools}++ 请判断哪些工具对**这道具体的题目模板**真正有帮助。+ 不要因为工具可用就全部使用——只在确实能提升质量时才选择。考虑:+ - rag_tool:通常对课程相关的事实性/概念性题目有帮助。+ 如果模板已包含完整的参考题目和答案,则可能不需要。+ - web_search:对需要真实案例、时事、或知识库覆盖不足的内容有帮助。+ 对标准教材内容通常不需要。+ - write_code:对编程题、数值验证、算法问题有帮助。+ 对纯概念性或论述题不需要。++ 仅返回 JSON:+ {{+ "use_rag": true 或 false,+ "use_web": true 或 false,+ "use_code": true 或 false,+ "rag_query": "具体的知识检索查询(仅当 use_rag 为 true 时填写)",+ "web_query": "具体的网络搜索查询(仅当 use_web 为 true 时填写)",+ "reasoning": "一句话说明你的工具选择理由"+ }}++generate: |+ QuestionTemplate:+ {template}++ 用户主题:+ {user_topic}++ 用户偏好:+ {preference}++ 上一轮 Validator 反馈:+ {validator_feedback}++ 工具上下文(知识/搜索结果,如有):+ {tool_context}++ 要求:+ - 严格对齐 template.concentration 与 template.difficulty。+ - 遵循 template.question_type。+ - 若为选择题,提供 4 个选项且仅 1 个正确答案。+ - 选择题的各选项长度应大致均衡,不要让正确选项明显比干扰项更长或更详细。+ 所有选项应具有合理的迷惑性,风格和长度相近,避免考生通过选项长度猜出答案。+ - 给出清晰解释。+ - 仅在对答案验证真正有用时(如编程题或数学计算题)才提供 `verification_code`(python)。+ 概念性或论述题不要包含验证代码。++ 仅返回 JSON:+ {{+ "question_type": "choice 或 written 或 coding",+ "question": "题目内容",+ "options": {{"A":"...","B":"...","C":"...","D":"..."}},+ "correct_answer": "最终答案",+ "explanation": "详细解释",+ "verification_code": "可选的 python 代码 — 仅在有助于答案验证时提供"+ }}diff --git a/src/agents/question/prompts/zh/idea_agent.yaml b/src/agents/question/prompts/zh/idea_agent.yamlnew file mode 100644index 000000000..b75c45c1a--- /dev/null+++ b/src/agents/question/prompts/zh/idea_agent.yaml@@ -0,0 +1,68 @@+system: |+ 你是考试题目设计流程中的 Idea Agent。+ 你的职责是基于知识内容提出多样、有效、可执行的出题方向。++generate_queries: |+ 主题:{user_topic}++ 请生成恰好 {num_queries} 条知识库检索查询。+ 规则:+ - 每条查询应是概念、定理、方法或关键词。+ - 不要写完整任务描述。+ - 表达简洁准确。++ 仅返回 JSON:+ {{+ "queries": ["...", "..."]+ }}++generate_ideas: |+ 主题:+ {user_topic}++ 用户偏好:+ {preference}++ 上一轮评估反馈:+ {evaluator_feedback}++ 知识依据:+ {knowledge_context}++ 请生成恰好 {num_ideas} 个候选出题创意。+ 重点关注:多样性、相关性、与用户偏好的一致性。++ 重要 — question_type 只允许以下三个值之一:+ - "choice" (选择题,4 选 1)+ - "written" (简答 / 论述题)+ - "coding" (编程 / 计算题)+ 不要使用其他类型(如 visual、diagram、matching 等)。++ 仅返回 JSON,格式如下:+ {{+ "ideas": [+ {{+ "idea_id": "idea_1",+ "concentration": "该题主要考察点",+ "question_type": "choice | written | coding",+ "difficulty": "easy 或 medium 或 hard",+ "rationale": "该创意的价值"+ }}+ ]+ }}++aggregate_context: |+ 你收到了关于以下主题的多条知识检索结果:{user_topic}++ 原始检索结果:+ {raw_context}++ 请将以上内容综合整理为一段条理清晰的知识摘要。+ 要求:+ - 去除重复或冗余信息。+ - 保留关键概念、定理、公式和示例。+ - 按逻辑组织(先定义,再性质/方法,最后应用)。+ - 摘要应简洁但信息密集。+ - 不要添加检索结果中不存在的信息。++ 以纯文本形式返回知识摘要(不要返回 JSON)。diff --git a/src/agents/question/prompts/zh/relevance_analyzer.yaml b/src/agents/question/prompts/zh/relevance_analyzer.yamldeleted file mode 100644index 1ebba0cef..000000000--- a/src/agents/question/prompts/zh/relevance_analyzer.yaml+++ /dev/null@@ -1,39 +0,0 @@-system: |- 你是一位教育内容分析师,专门分析考试题目与知识库内容之间的关系。-- 你的任务是分析题目与知识库的相关性,而不是验证或拒绝题目。所有题目都被接受。--analyze_relevance: |- 分析以下考试题目与知识库内容之间的相关性。-- 题目:- {question}-- 知识库内容:- {knowledge}-- 请分析并提供以下结构的 JSON 响应:- {{- "relevance": "high" 或 "partial",- "kb_coverage": "具体描述这道题目测试了知识库中的哪些概念、理论或方法。列出直接相关的关键知识点。",- "extension_points": "如果相关性是 'partial',描述这道题目的哪些方面超出了知识库内容。它需要什么额外的知识?如果相关性是 'high' 则留空。"- }}-- 判断相关性的指南:- 1. "high" - 题目可以完全使用知识库内容来回答。所有概念、方法和所需知识都在知识库中。- 2. "partial" - 题目与知识库内容相关,但需要一些超出提供内容的知识。知识库作为基础,但题目扩展到了额外的领域。-- 对于 kb_coverage:- - 具体说明正在测试知识库中的哪些概念- - 尽可能参考知识库中的实际内容- - 解释知识库内容与题目的关系-- 对于 extension_points(仅当相关性为 "partial" 时):- - 确定需要什么额外知识- - 解释题目如何从知识库基础扩展- - 保持积极的语气 - 扩展对学习有价值-- 关键:只返回有效的 JSON。不要用 markdown 代码块包装。- 你的回复必须以 {{ 开始,以 }} 结束。-- 只输出 JSON,不要有其他文字。diff --git a/src/agents/question/prompts/zh/retrieve_agent.yaml b/src/agents/question/prompts/zh/retrieve_agent.yamldeleted file mode 100644index 02da5bb1f..000000000--- a/src/agents/question/prompts/zh/retrieve_agent.yaml+++ /dev/null@@ -1,30 +0,0 @@-system: |- 你是一个知识库检索助手,正在为题目生成做准备。-- 你的任务是生成知识点检索查询,以在知识库中找到理论解释、定义和定理。-- 关键原则:你现在不是在生成题目!你是在寻找题目生成所需的理论知识。--generate_queries: |- 用户的题目生成需求是:- {requirement_text}-- 请提取 {num_queries} 个纯粹的知识点名称用于知识库检索。-- 输出规则:- 1. 只输出纯粹的知识点名称(定理名、概念名、方法名)- 2. 每个查询应为2-5个词- 3. 不要包含函数、数值或计算任务- 4. 不要使用问句或任务描述-- 正确示例:- ✓ 泰勒定理- ✓ 拉格朗日乘数法- ✓ 临界点-- 错误示例(不要生成):- ✗ 应用泰勒定理近似 f(x,y)=... (这是一个题目)- ✗ 找出并分类临界点 (这是一个任务)- ✗ 使用拉格朗日乘数法求最大值 (这是一个指令)-- 以 JSON 格式返回:{{"queries": ["知识点1", "知识点2", ...]}}, 包含恰好 {num_queries} 个知识点名称。diff --git a/src/agents/question/prompts/zh/validator.yaml b/src/agents/question/prompts/zh/validator.yamlnew file mode 100644index 000000000..8c4df59a1--- /dev/null+++ b/src/agents/question/prompts/zh/validator.yaml@@ -0,0 +1,35 @@+system: |+ 你是出题流程中的 Validator。+ 你需要验证题目质量与要求对齐度,并给出 approve/reject 决策。+ 你还需要判断是否有必要运行验证代码来辅助验证答案。++validate: |+ Template:+ {template}++ 生成的 Q-A 对:+ {qa_pair}++ 是否有验证代码可用:{has_code}++ 校验清单:+ - 题目是否对齐 template 的 concentration?+ - 难度是否匹配?+ - 答案是否正确且与解析一致?+ - 选择题是否只有一个正确选项?+ - 选择题的各选项长度和风格是否均衡?若正确选项明显比干扰项更长或更详细,+ 或选项之间缺乏有意义的区分度(过于相似或过于明显错误),应 reject。+ - 输出是否清晰、完整?++ 关于代码验证的判断:+ - 仅在以下情况将 needs_code_check 设为 true:有验证代码可用,且题目类型+ 适合计算验证(如编程题、数学题、算法题)。+ - 以下情况设为 false:概念题、论述题、定义题或纯理论题——即使提供了验证代码。++ 仅返回 JSON:+ {{+ "decision": "approve 或 reject",+ "feedback": "若 reject 给出具体重生建议;若 approve 给出简短确认",+ "issues": ["问题1", "问题2"],+ "needs_code_check": true 或 false+ }}diff --git a/src/agents/solve/README.md b/src/agents/solve/README.mddeleted file mode 100644index 7c5d7b273..000000000--- a/src/agents/solve/README.md+++ /dev/null@@ -1,554 +0,0 @@-# Solve Agents - Dual-Loop Problem Solving System--<div align="center">--**Intelligent Problem Solving System Based on Dual-Loop Architecture**--[](https://www.python.org/downloads/)-[](LICENSE)--</div>-------## 📋 Table of Contents--- [System Overview](#system-overview)-- [Quick Start](#quick-start)-- [System Architecture](#system-architecture)-- [Core Modules](#core-modules)-- [Configuration](#configuration)-- [Usage Guide](#usage-guide)-- [Development Guide](#development-guide)-------## System Overview--This system is an intelligent problem-solving system based on a **dual-loop architecture**, achieving a complete workflow from problem understanding to answer generation through two collaborative loops.--### Dual-Loop Architecture--| Loop | Function | Key Features |-|------|----------|--------------|-| **Analysis Loop** | Deep understanding of user questions | Dynamic research, iterative knowledge collection, automatic stopping |-| **Solve Loop** | Strict solving and answer generation | Block planning, step-by-step execution, quality checking |--### Core Advantages--✅ **Intelligent Research** - Analysis Loop dynamically determines when to stop research-✅ **Block-based Solving** - Solve Loop decomposes complex problems into manageable blocks-✅ **Quality Assurance** - Check Agent automatically checks and corrects errors-✅ **Persistent Memory** - JSON format storage, supports checkpoint resumption-✅ **Citation Management** - Automatic citation management and formatting-✅ **Tool Integration** - RAG, Web Search, Code Execution-------## Quick Start--### Install Dependencies & Configure Environment--```bash-pip install -r requirements.txt--# .env file (project root directory)-LLM_API_KEY=your_api_key-LLM_HOST=https://api.openai.com/v1-LLM_MODEL=gpt-4o # Optional-PERPLEXITY_API_KEY=... # Optional, enable Web search-```--### Basic Usage (Python API)--```python-import asyncio-import os-from solve_agents import MainSolver--async def main():- solver = MainSolver(- kb_name="ai_textbook",- api_key=os.getenv("LLM_API_KEY"),- base_url=os.getenv("LLM_HOST"),- )-- result = await solver.solve(- question="What is linear convolution?",- verbose=True- )-- print(f"📁 Output directory: {result['metadata']['output_dir']}")- print(f"📊 Analysis iterations: {result['analysis_iterations']} rounds")- print(f"📊 Solve steps: {result['solve_steps']} steps")- print(f"📝 Markdown: {result['output_md']}")--asyncio.run(main())-```--### Using Command Line Tool--```bash-cd DeepTutor/student_TA-python start.py # CLI currently defaults to dual-loop Solve mode-```-------## System Architecture--### Overall Flow--```-User Question- │- ▼-┌─────────────────────────────────────────────────────────────┐-│ MainSolver │-│ │-│ ┌───────────────────────────────────────────────────────┐ │-│ │ Analysis Loop (Analysis Loop) │ │-│ │ │ │-│ │ ┌──────────┐ ┌──────────┐ │ │-│ │ │Investigate│ -> │ Note │ │ │-│ │ └──────────┘ └──────────┘ │ │-│ │ ▲ │ │ │-│ │ └─────────────┴───────────────┐ │ │-│ │ │ │ │-│ │ Stop condition met │ │-│ │ │ │ │-│ │ InvestigateMemory │ │-│ └───────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌───────────────────────────────────────────────────────┐ │-│ │ Solve Loop (Solving Loop) │ │-│ │ │ │-│ │ ┌──────┐ ┌─────────┐ ┌──────┐ ┌───────┐ │ │-│ │ │ Plan │ -> │ Manager │ -> │Solve │ -> │ Check │ │ │-│ │ └──────┘ └─────────┘ └──────┘ └───────┘ │ │-│ │ │ │ │ │-│ │ └───────────┘ │ │-│ │ Loop until completion │ │-│ │ │ │ │-│ │ ▼ │ │-│ │ ┌────────┐ │ │-│ │ │ Format │ │ │-│ │ └────────┘ │ │-│ │ │ │ │-│ │ SolveMemory │ │-│ └───────────────────────────────────────────────────────┘ │-│ │-│ Final Answer │-└─────────────────────────────────────────────────────────────┘-```--### Directory Structure--```-solve_agents/-├── main_solver.py # Main controller-├── base_agent.py # Agent base class-├── config.yaml # Configuration file-│-├── analysis_loop/ # Analysis Loop ⭐-│ ├── investigate_agent.py # Research Agent-│ ├── note_agent.py # Note Agent-│ └── README.md # Detailed documentation-│-├── solve_loop/ # Solve Loop ⭐-│ ├── plan_agent.py # Planning Agent-│ ├── manager_agent.py # Manager Agent-│ ├── solve_agent.py # Solving Agent-│ ├── tool_agent.py # Tool execution Agent-│ ├── response_agent.py # Aggregate tool results-│ ├── check_agent.py # Quality checking-│ ├── precision_answer_agent.py # Precision answer (optional)-│ ├── citation_manager.py # Citation manager-│ └── README.md # Detailed documentation-│-├── memory/ # Memory system ⭐-│ ├── investigate_memory.py # Analysis Loop memory-│ └── solve_memory.py # Solve Loop memory-│-├── utils/ # Utility modules-│ ├── logger.py # Logging system-│ ├── performance_monitor.py # Performance monitoring-│ ├── config_validator.py # Configuration validation-│ ├── json_utils.py # JSON utilities-│ ├── tag_parser.py # Tag parser-│ └── error_handler.py # Error handling-│-└── prompts/ # Prompt templates- ├── analysis_loop/ # Analysis Loop Prompts- └── solve_loop/ # Solve Loop Prompts-```-------## Core Modules--### Analysis Loop (Analysis Loop)--**Function**: Deep understanding of user questions--**Agents**:-- **InvestigateAgent**: Based on knowledge chain, outputs multiple queries at once and calls tools, generates `cite_id → raw_result`-- **NoteAgent**: Processes new `cite_id` one by one, generates summary and citations--**Memory**: `InvestigateMemory` (JSON)--**Detailed Documentation**: [analysis_loop/README.md](analysis_loop/README.md)--### Solve Loop (Solving Loop)--**Function**: Strict solving and answer generation--**Agents**:-- **PlanAgent**: Generates problem-solving plan (blocks)-- **ManagerAgent**: Arranges specific steps (steps) for each block-- **SolveAgent**: Calls tools and writes reasoning according to steps-- **ToolAgent**: Unified encapsulation of RAG / Web Search / Code Execution / Query Item tools-- **ResponseAgent**: Organizes outputs from SolveAgent and ToolAgent-- **CheckAgent**: Automatically checks steps and provides correction suggestions-- **PrecisionAnswerAgent**: Generates precision answer summary (optional)--**Memory**: `SolveMemory` (JSON)--**Detailed Documentation**: [solve_loop/README.md](solve_loop/README.md)--### Memory System--**InvestigateMemory**:-```python-{- "user_question": "...",- "knowledge_chain": [...], # Collected knowledge- "reflections": {...}, # Reserved field, currently only records remaining questions (default empty)- "metadata": {...} # Statistics-}-```--**SolveMemory**:-```python-{- "user_question": "...",- "plan": {- "blocks": [...] # Problem-solving plan- },- "progress": {...}, # Execution progress- "metadata": {...} # Statistics-}-```--### Tool System--ToolAgent aggregates multiple capabilities and automatically chains them step by step:--- **RAG Search**: Retrieves KBs from `knowledge_bases/`-- **Web Search**: Expands latest materials based on Perplexity API-- **Query Item**: Quickly references formulas / theorems by number-- **Code Execution**: Runs Python in sandbox, results written to `artifacts/`-------## Configuration--### config.yaml Structure--```yaml-system:- output_base_dir: "./user/solve"- save_intermediate_results: true- output_language: "English" # or Chinese- max_analysis_iterations: 5- max_solve_correction_iterations: 3--logging:- level: "INFO"- save_to_file: true- console_output: true- log_dir: "./logs"--monitoring:- enabled: true- track_token_usage: true- track_time: true- save_dir: "./logs/performance"--llm:- max_retries: 3- timeout: 120- max_tokens: 8192--agents:- investigate_agent:- temperature: 0.4- max_iterations: 3- note_agent:- max_tokens: 4096-- manager_agent: {}- solve_agent:- max_tokens: 8192- tool_agent: {}- response_agent:- max_tokens: 8192- enabled: false- max_tokens: 8192- precision_answer_agent:- enabled: true- temperature: 0.2--tools:- rag_tool:- kb_base_dir: "./knowledge_bases"- default_kb: "ai_textbook"- web_search:- enabled: true- max_results: 5- query_item:- enabled: true- run_code:- enabled: true- timeout: 10- workspace: "./student_TA/cache/run_code_workspace"-```-------## Usage Guide--### Basic Usage--```python-from solve_agents import MainSolver--# Create solver-solver = MainSolver(- kb_name="ai_textbook", # Knowledge base name- config_path=None, # Use default configuration- api_key=None, # Read from environment variables- base_url=None # Read from environment variables-)--# Solve problem-result = await solver.solve(- question="Your question",- verbose=True # Print detailed logs-)--# View results-print(result['output_md']) # final_answer.md-print(result['output_json']) # solve_chain.json (steps + tool logs)-print(result['final_answer']) # String, may contain precision answer-print(len(result['citations'])) # Number of citations-```--### Output Files--```-user/solve/solve_20251116_160009/-├── investigate_memory.json # Analysis Loop memory-├── solve_chain.json # Solve Loop steps & tool records ⭐-├── citation_memory.json # Citation management-├── final_answer.md # Final answer (Markdown)-├── performance_report.json # Performance monitoring-├── cost_report.json # Optional: token cost-├── search_*.json # Search cache (if any)-└── artifacts/ # Code execution output-```--### View Statistics--```python-result = await solver.solve(question)--# Analysis Loop statistics-print(f"Analysis iterations: {result['analysis_iterations']} rounds")-print(f"Coverage rate: {result['metadata']['coverage_rate']:.2%}")-print(f"Average confidence: {result['metadata']['avg_confidence']:.2%}")--# Solve Loop statistics-print(f"Solve completed steps: {result['solve_steps']} / {result['metadata']['total_steps']}")-print(f"Number of citations: {len(result['citations'])}")-```--### Debug Mode--```python-# Enable detailed logging-import logging-logging.basicConfig(level=logging.DEBUG)--# View memory files-import json-output_dir = result['metadata']['output_dir']-with open(f'{output_dir}/investigate_memory.json', encoding='utf-8') as f:- memory = json.load(f)-print(json.dumps(memory, indent=2, ensure_ascii=False))-```-------## Development Guide--### Extending New Agent--1. **Inherit BaseAgent**:--```python-from solve_agents.base_agent import BaseAgent--class MyAgent(BaseAgent):- def __init__(self, config, api_key, base_url):- super().__init__(config, api_key, base_url, 'my_agent')-- async def process(self, **kwargs):- # Implement processing logic- # Prompts are auto-loaded via unified PromptManager- system_prompt = self.get_prompt("system")- response = await self.call_llm(user_prompt, system_prompt)- return self.parse_response(response)-```--2. **Add Prompt**:--Define Prompt in `prompts/analysis_loop/my_agent.yaml` or `prompts/solve_loop/my_agent.yaml`.--3. **Register to MainSolver**:--Initialize in the `_init_agents()` method of `main_solver.py`.--4. **Add Configuration**:--Add Agent configuration in `config.yaml`.--### Extending Memory System--```python-from dataclasses import dataclass, asdict-import json--@dataclass-class MyMemory:- user_question: str- data: dict-- def save(self, output_dir: str):- with open(f"{output_dir}/my_memory.json", 'w') as f:- json.dump(asdict(self), f, ensure_ascii=False, indent=2)-- @classmethod- def load_or_create(cls, output_dir: str, user_question: str):- path = f"{output_dir}/my_memory.json"- if os.path.exists(path):- with open(path) as f:- data = json.load(f)- return cls(**data)- return cls(user_question=user_question, data={})-```--### Adding New Tool--```python-# Create new tool in tools/ directory-class MyTool:- def __init__(self, config):- self.config = config-- async def execute(self, **kwargs):- # Implement tool logic- return result--# Register in SolveAgent-self.tools['my_tool'] = MyTool(config)-```-------## Performance Optimization--### Adjust Iteration Count--```yaml-system:- max_analysis_iterations: 3 # Reduce Analysis iterations- max_solve_correction_iterations: 2 # Reduce Solve retries-```--### Use Faster Model--```yaml-agents:- investigate_agent:- model: "gpt-3.5-turbo" # Use faster model-```--### Disable Optional Features--```yaml-agents:- precision_answer_agent:- enabled: false # Disable precision answer-```-------## FAQ--**Q: How to adjust the iteration count of Analysis Loop?**--Set `system.max_analysis_iterations` in `config.yaml`.--**Q: How to enable precision answer feature?**--Set `agents.precision_answer_agent.enabled: true` in `config.yaml`.--**Q: How to view detailed execution logs?**--Set `logging.level: "DEBUG"` or enable `verbose=True` in code.--**Q: Where are the memory files?**--In the `{output_base_dir}/solve_{timestamp}/` directory.--**Q: How to reset citation numbers?**--```python-from solve_agents.solve_loop.citation_manager import CitationManager-CitationManager().reset()-```--**Q: What to do if code execution times out?**--Adjust the `agents.code_agent.timeout` configuration.-------## Version History--- **v3.0** (2025-11-16) - Dual-loop architecture refactoring- - ✅ Complete refactoring to dual-loop architecture- - ✅ Remove old Router, Deep Analysis, Deep Solve modules- - ✅ Introduce dynamic memory system- - ✅ Optimize tool calling and citation management- - ✅ Simplify configuration and usage flow- - ✅ Merge utils and parsers modules-------## Related Documentation--- [Analysis Loop Detailed Documentation](analysis_loop/README.md)-- [Solve Loop Detailed Documentation](solve_loop/README.md)-- [Configuration File Documentation](config.yaml)------## License--MIT License-------**Made with ❤️ by DeepTutor Team**diff --git a/src/agents/solve/__init__.py b/src/agents/solve/__init__.pyindex e56de80ce..3917cf05a 100644--- a/src/agents/solve/__init__.py+++ b/src/agents/solve/__init__.py@@ -1,92 +1,12 @@-#!/usr/bin/env python"""-Solve Agent System - Dual-Loop Architecture-Analysis Loop + Solve Loop+Solve Agent — Plan -> ReAct -> Write architecture."""-from pathlib import Path-import sys--# Add project root to path for logs import-_project_root = Path(__file__).parent.parent.parent.parent-if str(_project_root) not in sys.path:- sys.path.insert(0, str(_project_root))--# Infrastructure-from src.agents.base_agent import BaseAgent-from src.logging import Logger, get_logger--from .utils import (- ConfigValidator,- PerformanceMonitor,-)--# Backwards compatibility-SolveAgentLogger = Logger--# Memory system-# Analysis loop-from .analysis_loop import (- InvestigateAgent,- NoteAgent,-)--# Main controllerfrom .main_solver import MainSolver-from .memory import (- InvestigateMemory,- KnowledgeItem,- Reflections,- SolveChainStep,- SolveMemory,- SolveOutput,- TodoItem,- ToolCallRecord,-)--# Session managementfrom .session_manager import SolverSessionManager, get_solver_session_manager-# Solve loop-from .solve_loop import (- ManagerAgent,- PrecisionAnswerAgent,- ResponseAgent,- SolveAgent,- SolveNoteAgent,- ToolAgent,-)-__all__ = [- # Infrastructure- "BaseAgent",- "Logger",- "get_logger",- "SolveAgentLogger", # Backwards compatibility- "PerformanceMonitor",- "ConfigValidator",- # Memory system- "InvestigateMemory",- "KnowledgeItem",- "Reflections",- "SolveMemory",- "TodoItem",- "SolveOutput",- "ToolCallRecord",- "SolveChainStep", # Backward compatibility- # Analysis Loop- "InvestigateAgent",- "NoteAgent",- # Solve Loop- "ManagerAgent",- "SolveAgent",- "SolveNoteAgent",- "ResponseAgent",- "PrecisionAnswerAgent",- "ToolAgent",- # Main Controller"MainSolver",- # Session Management"SolverSessionManager","get_solver_session_manager",]diff --git a/src/agents/solve/agents/__init__.py b/src/agents/solve/agents/__init__.pynew file mode 100644index 000000000..550fdaec4--- /dev/null+++ b/src/agents/solve/agents/__init__.py@@ -0,0 +1,7 @@+"""Solve Agent — three-agent architecture."""++from .planner_agent import PlannerAgent+from .solver_agent import SolverAgent+from .writer_agent import WriterAgent++__all__ = ["PlannerAgent", "SolverAgent", "WriterAgent"]diff --git a/src/agents/solve/agents/planner_agent.py b/src/agents/solve/agents/planner_agent.pynew file mode 100644index 000000000..af5cc4a94--- /dev/null+++ b/src/agents/solve/agents/planner_agent.py@@ -0,0 +1,364 @@+"""+PlannerAgent — Decomposes the user question into ordered solving steps.++Called once at the start (Phase 1) and optionally on replan requests.+Before planning, performs parallel RAG pre-retrieval and LLM aggregation+to provide the planner with relevant knowledge context.+"""++from __future__ import annotations++import asyncio+import json+import logging+from typing import Any++from src.agents.base_agent import BaseAgent++from ..memory.scratchpad import Plan, PlanStep, Scratchpad+from ..tools import ToolRegistry+from ..utils.json_utils import extract_json_from_text++logger = logging.getLogger(__name__)++_MAX_CHARS_PER_RETRIEVAL = 2000+_MAX_AGGREGATE_INPUT_CHARS = 6000+_NUM_QUERIES = 3+++def _build_multimodal_messages(+ system_prompt: str,+ user_prompt: str,+ image_url: str,+) -> list[dict[str, Any]]:+ """Build OpenAI-compatible multimodal messages with an image."""+ return [+ {"role": "system", "content": system_prompt},+ {+ "role": "user",+ "content": [+ {"type": "text", "text": user_prompt},+ {"type": "image_url", "image_url": {"url": image_url}},+ ],+ },+ ]+++class PlannerAgent(BaseAgent):+ """Generates a high-level solving plan from the user question."""++ def __init__(+ self,+ config: dict[str, Any] | None = None,+ api_key: str | None = None,+ base_url: str | None = None,+ model: str | None = None,+ api_version: str | None = None,+ token_tracker: Any | None = None,+ language: str = "en",+ tool_registry: ToolRegistry | None = None,+ enable_pre_retrieve: bool = True,+ ) -> None:+ super().__init__(+ module_name="solve",+ agent_name="planner_agent",+ api_key=api_key,+ base_url=base_url,+ model=model,+ api_version=api_version,+ config=config or {},+ token_tracker=token_tracker,+ language=language,+ )+ self._tool_registry = tool_registry or ToolRegistry.create_default(language)+ self._enable_pre_retrieve = enable_pre_retrieve++ async def process(+ self,+ question: str,+ scratchpad: Scratchpad,+ kb_name: str = "",+ replan: bool = False,+ memory_context: str = "",+ image_url: str | None = None,+ ) -> Plan:+ """Generate or revise the solving plan.++ Args:+ question: The user's original question.+ scratchpad: Current scratchpad state.+ kb_name: Knowledge base name (informational).+ replan: If True, this is a replan request — include progress so far.+ memory_context: Historical memory context string.+ image_url: Optional image URL for multimodal questions.++ Returns:+ A Plan object with ordered steps.+ """+ rag_context = (+ await self._pre_retrieve(question, kb_name)+ if self._enable_pre_retrieve+ else "(retrieval disabled)"+ )++ system_prompt = self._build_system_prompt()+ user_prompt = self._build_user_prompt(+ question=question,+ scratchpad=scratchpad,+ kb_name=kb_name,+ replan=replan,+ memory_context=memory_context,+ rag_context=rag_context,+ )++ llm_kwargs: dict[str, Any] = {+ "user_prompt": user_prompt,+ "system_prompt": system_prompt,+ "response_format": {"type": "json_object"},+ "stage": "plan" if not replan else "replan",+ }++ if image_url:+ llm_kwargs["messages"] = _build_multimodal_messages(+ system_prompt, user_prompt, image_url,+ )++ response = await self.call_llm(**llm_kwargs)++ return self._parse_plan(response, scratchpad if replan else None)++ # ------------------------------------------------------------------+ # RAG pre-retrieval pipeline+ # ------------------------------------------------------------------++ async def _pre_retrieve(self, question: str, kb_name: str) -> str:+ """Run the full pre-retrieval pipeline: generate queries → parallel+ RAG search → LLM aggregation. Returns the aggregated knowledge+ context string, or a fallback placeholder on any failure."""+ if not kb_name:+ return "(no knowledge base available)"+ try:+ queries = await self._generate_search_queries(question)+ retrievals = await self._parallel_rag_search(queries, kb_name)+ if not any(r.get("answer") for r in retrievals):+ return "(no relevant knowledge retrieved)"+ return await self._aggregate_rag_results(retrievals)+ except Exception as exc:+ logger.warning("Pre-retrieval pipeline failed: %s", exc)+ return "(knowledge retrieval failed)"++ async def _generate_search_queries(+ self, question: str, num_queries: int = _NUM_QUERIES,+ ) -> list[str]:+ """Use a lightweight LLM call to derive multiple search queries from+ the user question."""+ prompt_template = (+ self.get_prompt("generate_queries") if self.has_prompts() else None+ )+ if not prompt_template:+ prompt_template = (+ "Generate {num_queries} concise and diverse knowledge-base "+ "search queries for the following question. Each query should "+ "target a different aspect (e.g. definitions, formulas, "+ "theorems, examples).\n\n"+ "Question: {question}\n\n"+ 'Return strict JSON: {{"queries": ["q1", "q2", "q3"]}}'+ )++ user_prompt = prompt_template.format(+ question=question, num_queries=num_queries,+ )+ try:+ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt="",+ response_format={"type": "json_object"},+ stage="plan_generate_queries",+ )+ payload = json.loads(response)+ queries = payload.get("queries", [])+ if not isinstance(queries, list):+ queries = []+ clean = [q.strip() for q in queries if isinstance(q, str) and q.strip()]+ result = clean[:num_queries] or [question]+ logger.info("Generated %d search queries", len(result))+ return result+ except Exception as exc:+ logger.warning("Query generation failed, fallback to raw question: %s", exc)+ return [question]++ async def _parallel_rag_search(+ self, queries: list[str], kb_name: str,+ ) -> list[dict[str, Any]]:+ """Execute RAG searches for all queries in parallel."""+ from src.tools.rag_tool import rag_search++ async def _single_search(query: str) -> dict[str, Any]:+ try:+ result = await rag_search(+ query=query, kb_name=kb_name,+ mode="hybrid", only_need_context=True, top_k=8,+ )+ return {"query": query, "answer": result.get("answer", "") or result.get("content", "")}+ except Exception as exc:+ logger.warning("RAG search failed for query '%s': %s", query[:60], exc)+ return {"query": query, "answer": ""}++ results = await asyncio.gather(*[_single_search(q) for q in queries])+ logger.info(+ "Parallel RAG search: %d/%d returned content",+ sum(1 for r in results if r.get("answer")), len(results),+ )+ return list(results)++ async def _aggregate_rag_results(+ self, retrievals: list[dict[str, Any]],+ ) -> str:+ """Use an LLM call to aggregate raw retrieval results into a+ structured knowledge summary. The user question is NOT passed+ to keep the output neutral (pure knowledge consolidation)."""+ sections: list[str] = []+ total_chars = 0+ for item in retrievals:+ answer = (item.get("answer") or "").strip()+ if not answer:+ continue+ clipped = answer[:_MAX_CHARS_PER_RETRIEVAL]+ if total_chars + len(clipped) > _MAX_AGGREGATE_INPUT_CHARS:+ clipped = clipped[:max(0, _MAX_AGGREGATE_INPUT_CHARS - total_chars)]+ if clipped:+ sections.append(f"=== Source: {item.get('query', '?')} ===\n{clipped}")+ total_chars += len(clipped)++ if not sections:+ return "(no relevant knowledge retrieved)"++ raw_text = "\n\n".join(sections)++ prompt_template = (+ self.get_prompt("aggregate_context") if self.has_prompts() else None+ )+ if not prompt_template:+ prompt_template = (+ "Below are several passages retrieved from a knowledge base. "+ "Your task is to consolidate them into a single structured "+ "knowledge summary.\n\n"+ "Rules:\n"+ "- Remove duplicate information.\n"+ "- Organize by topic (definitions, formulas/theorems, key facts, examples).\n"+ "- Do NOT solve any problem or make inferences.\n"+ "- Do NOT reference any question — just organize the knowledge.\n"+ "- Be concise; keep the summary under 3000 characters.\n\n"+ "{raw_retrieval_text}"+ )++ user_prompt = prompt_template.format(raw_retrieval_text=raw_text)+ try:+ result = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt="You are a knowledge organizer. Consolidate the provided passages into a clean, structured summary.",+ stage="plan_aggregate_context",+ )+ logger.info("Aggregated RAG context: %d chars", len(result))+ return result.strip() or raw_text+ except Exception as exc:+ logger.warning("RAG aggregation failed, using raw text: %s", exc)+ return raw_text++ # ------------------------------------------------------------------+ # Prompt construction+ # ------------------------------------------------------------------++ def _build_system_prompt(self) -> str:+ prompt = self.get_prompt("system") if self.has_prompts() else None+ if prompt:+ return prompt+ return (+ "You are a problem-solving planner. Analyze the user's question and "+ "decompose it into ordered steps. Each step should be a verifiable sub-goal "+ "describing WHAT to establish, not HOW. Do not specify tools. "+ "Simple questions need only 1 step; complex ones may need 3-6 steps. "+ "If retrieved knowledge is provided, use it to make a more informed plan. "+ "Output strict JSON: {\"analysis\": \"...\", \"steps\": [{\"id\": \"S1\", "+ "\"goal\": \"...\"}]}"+ )++ def _build_user_prompt(+ self,+ question: str,+ scratchpad: Scratchpad,+ kb_name: str,+ replan: bool,+ memory_context: str = "",+ rag_context: str = "",+ ) -> str:+ template = self.get_prompt("user_template") if self.has_prompts() else None++ # Build scratchpad summary for replan+ scratchpad_summary = "(initial plan — no progress yet)"+ if replan and scratchpad.plan:+ parts: list[str] = []+ for step in scratchpad.plan.steps:+ entries = scratchpad.get_entries_for_step(step.id)+ notes = " | ".join(e.self_note for e in entries if e.self_note)+ status_label = step.status.upper()+ parts.append(f"[{step.id}] ({status_label}) {step.goal}")+ if notes:+ parts.append(f" Notes: {notes}")+ # Include the replan reason from the last entry+ if scratchpad.entries:+ last = scratchpad.entries[-1]+ if last.action == "replan" and last.action_input:+ parts.append(f"\nReplan reason: {last.action_input}")+ scratchpad_summary = "\n".join(parts)++ tools_desc = self._tool_registry.build_planner_description(kb_name=kb_name)++ if template:+ return template.format(+ question=question,+ rag_context=rag_context or "(no retrieved knowledge)",+ tools_description=tools_desc,+ scratchpad_summary=scratchpad_summary,+ memory_context=memory_context or "(no historical memory)",+ )++ # Fallback+ return (+ f"## Question\n{question}\n\n"+ f"## Retrieved Knowledge\n{rag_context or '(none)'}\n\n"+ f"## Available Tools\n{tools_desc}\n\n"+ f"## Progress So Far\n{scratchpad_summary}\n\n"+ f"## Memory Context\n{memory_context or '(none)'}"+ )++ # ------------------------------------------------------------------+ # Response parsing+ # ------------------------------------------------------------------++ def _parse_plan(self, response: str, old_scratchpad: Scratchpad | None) -> Plan:+ """Parse LLM JSON response into a Plan object."""+ data = extract_json_from_text(response)+ if not data or not isinstance(data, dict):+ # Graceful fallback: single-step plan+ return Plan(+ analysis="Failed to parse plan; using single-step fallback.",+ steps=[PlanStep(id="S1", goal="Answer the question directly")],+ )++ analysis = data.get("analysis", "")+ raw_steps = data.get("steps", [])++ steps: list[PlanStep] = []+ for i, s in enumerate(raw_steps):+ step_id = s.get("id", f"S{i + 1}")+ goal = s.get("goal", "")+ tools_hint = s.get("tools_hint", [])+ if isinstance(tools_hint, str):+ tools_hint = [tools_hint]+ steps.append(PlanStep(id=step_id, goal=goal, tools_hint=tools_hint))++ if not steps:+ steps = [PlanStep(id="S1", goal="Answer the question")]++ return Plan(analysis=analysis, steps=steps)diff --git a/src/agents/solve/agents/solver_agent.py b/src/agents/solve/agents/solver_agent.pynew file mode 100644index 000000000..881751865--- /dev/null+++ b/src/agents/solve/agents/solver_agent.py@@ -0,0 +1,194 @@+"""+SolverAgent — ReAct agent that iteratively gathers information for each plan step.++For every step in the plan, the SolverAgent runs a think-act-observe loop:+ 1. THINK — reason about what information is still missing+ 2. ACT — choose a tool (rag_search | web_search | code_execute | done | replan)+ 3. OBSERVE — the tool result is appended to the Scratchpad (outside this agent)++The agent outputs a single JSON decision per call.+"""++from __future__ import annotations++from typing import Any++from src.agents.base_agent import BaseAgent++from ..memory.scratchpad import PlanStep, Scratchpad+from ..tools import ToolRegistry+from ..utils.json_utils import extract_json_from_text+++def _build_multimodal_messages(+ system_prompt: str,+ user_prompt: str,+ image_url: str,+) -> list[dict[str, Any]]:+ """Build OpenAI-compatible multimodal messages with an image."""+ return [+ {"role": "system", "content": system_prompt},+ {+ "role": "user",+ "content": [+ {"type": "text", "text": user_prompt},+ {"type": "image_url", "image_url": {"url": image_url}},+ ],+ },+ ]+++class SolverAgent(BaseAgent):+ """ReAct reasoning agent — one LLM call per iteration."""++ def __init__(+ self,+ config: dict[str, Any] | None = None,+ api_key: str | None = None,+ base_url: str | None = None,+ model: str | None = None,+ api_version: str | None = None,+ token_tracker: Any | None = None,+ language: str = "en",+ tool_registry: ToolRegistry | None = None,+ ) -> None:+ super().__init__(+ module_name="solve",+ agent_name="solver_agent",+ api_key=api_key,+ base_url=base_url,+ model=model,+ api_version=api_version,+ config=config or {},+ token_tracker=token_tracker,+ language=language,+ )+ self._tool_registry = tool_registry or ToolRegistry.create_default(language)++ async def process(+ self,+ question: str,+ current_step: PlanStep,+ scratchpad: Scratchpad,+ memory_context: str = "",+ image_url: str | None = None,+ ) -> dict[str, str]:+ """Run one ReAct iteration for the given plan step.++ Args:+ question: The user's original question.+ current_step: The plan step being solved.+ scratchpad: Current scratchpad state.+ memory_context: Historical memory context string.+ image_url: Optional image URL for multimodal questions.++ Returns:+ dict with keys: thought, action, action_input, self_note+ """+ system_prompt = self._build_system_prompt()+ user_prompt = self._build_user_prompt(+ question=question,+ current_step=current_step,+ scratchpad=scratchpad,+ memory_context=memory_context,+ )++ llm_kwargs: dict[str, object] = {+ "user_prompt": user_prompt,+ "system_prompt": system_prompt,+ "response_format": {"type": "json_object"},+ "stage": f"solve_{current_step.id}",+ }++ if image_url:+ llm_kwargs["messages"] = _build_multimodal_messages(+ system_prompt, user_prompt, image_url,+ )++ response = await self.call_llm(**llm_kwargs)++ return self._parse_decision(response)++ # ------------------------------------------------------------------+ # Prompt construction+ # ------------------------------------------------------------------++ def _build_system_prompt(self) -> str:+ tools_desc = self._tool_registry.build_solver_description()++ prompt = self.get_prompt("system") if self.has_prompts() else None+ if prompt:+ try:+ return prompt.format(tools_description=tools_desc)+ except KeyError:+ return prompt++ # Fallback+ return (+ "You are a ReAct problem-solving agent. For the current step, decide what "+ "action to take next. Output strict JSON with keys: thought, action, "+ "action_input, self_note.\n\n"+ f"Available actions:\n{tools_desc}\n\n"+ "self_note: write a 1-sentence summary of what you learned this round."+ )++ def _build_user_prompt(+ self,+ question: str,+ current_step: PlanStep,+ scratchpad: Scratchpad,+ memory_context: str = "",+ ) -> str:+ template = self.get_prompt("user_template") if self.has_prompts() else None++ ctx = scratchpad.build_solver_context(current_step.id)++ current_step_text = f"[{current_step.id}] {current_step.goal}"++ if template:+ return template.format(+ question=question,+ plan=ctx["plan"],+ current_step=current_step_text,+ step_history=ctx["step_history"],+ previous_knowledge=ctx["previous_knowledge"],+ memory_context=memory_context or "(no historical memory)",+ )++ # Fallback+ return (+ f"## Original Question\n{question}\n\n"+ f"## Plan\n{ctx['plan']}\n\n"+ f"## Current Step\n{current_step_text}\n\n"+ f"## Previous Actions for This Step\n{ctx['step_history']}\n\n"+ f"## Knowledge from Previous Steps\n{ctx['previous_knowledge']}\n\n"+ f"## Historical Knowledge\n{memory_context or '(none)'}"+ )++ # ------------------------------------------------------------------+ # Response parsing+ # ------------------------------------------------------------------++ def _parse_decision(self, response: str) -> dict[str, str]:+ """Parse the LLM JSON response into a decision dict."""+ data = extract_json_from_text(response)++ if not data or not isinstance(data, dict):+ # If parsing completely fails, default to done+ return {+ "thought": "Failed to parse response; ending step.",+ "action": "done",+ "action_input": "",+ "self_note": "Parse error — defaulting to done.",+ }++ action = str(data.get("action", "done")).strip().lower()+ if action not in self._tool_registry.valid_actions:+ action = "done"++ return {+ "thought": str(data.get("thought", "")),+ "action": action,+ "action_input": str(data.get("action_input", "")),+ "self_note": str(data.get("self_note", "")),+ }diff --git a/src/agents/solve/agents/writer_agent.py b/src/agents/solve/agents/writer_agent.pynew file mode 100644index 000000000..9a43714f6--- /dev/null+++ b/src/agents/solve/agents/writer_agent.py@@ -0,0 +1,324 @@+"""+WriterAgent — Generates the final structured answer from the Scratchpad.++Supports two modes:+ - **Simple** (`process`): single LLM call producing the complete answer.+ - **Detailed / Iterative** (`process_iterative`): step-by-step incremental+ writing that processes evidence in chunks, then generates a concise answer.+"""++from __future__ import annotations++from typing import Any++from src.agents.base_agent import BaseAgent++from ..memory.scratchpad import Scratchpad+++class WriterAgent(BaseAgent):+ """Produces the final answer from accumulated evidence."""++ def __init__(+ self,+ config: dict[str, Any] | None = None,+ api_key: str | None = None,+ base_url: str | None = None,+ model: str | None = None,+ api_version: str | None = None,+ token_tracker: Any | None = None,+ language: str = "en",+ ) -> None:+ super().__init__(+ module_name="solve",+ agent_name="writer_agent",+ api_key=api_key,+ base_url=base_url,+ model=model,+ api_version=api_version,+ config=config or {},+ token_tracker=token_tracker,+ language=language,+ )++ # ==================================================================+ # Simple mode — single-shot writing+ # ==================================================================++ async def process(+ self,+ question: str,+ scratchpad: Scratchpad,+ language: str = "en",+ preference: str = "",+ ) -> str:+ """Generate the final Markdown answer in a single LLM call.++ Args:+ question: Original user question.+ scratchpad: Completed scratchpad with all evidence.+ language: Output language hint (e.g. "en", "zh").+ preference: Optional personalisation context.++ Returns:+ Markdown-formatted answer string.+ """+ system_prompt = self._build_system_prompt()+ user_prompt = self._build_user_prompt(question, scratchpad, language, preference)++ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ max_tokens=self.get_max_tokens() or 8192,+ stage="write",+ )++ return response.strip()++ # ==================================================================+ # Detailed / Iterative mode+ # ==================================================================++ async def process_iterative(+ self,+ question: str,+ scratchpad: Scratchpad,+ language: str = "en",+ preference: str = "",+ ) -> str:+ """Generate a detailed answer through iterative step-by-step writing.++ Flow:+ Iteration 1 : evidence(S1) + evidence(S2) → draft_1+ Iteration 2 : draft_1 + evidence(S3) → draft_2+ ...+ Final : draft_N → concise_answer+ Output : concise_answer + "---" + draft_N++ Args:+ question: Original user question.+ scratchpad: Completed scratchpad with all evidence.+ language: Output language hint.+ preference: Optional personalisation context.++ Returns:+ Combined Markdown string: concise answer + detailed answer.+ """+ if scratchpad.plan is None:+ # Fallback: no plan, use simple mode+ return await self.process(question, scratchpad, language, preference)++ # Collect completed/in_progress steps that have entries+ steps_with_evidence = []+ for step in scratchpad.plan.steps:+ if step.status in ("completed", "in_progress"):+ entries = scratchpad.get_entries_for_step(step.id)+ # Only include steps with actual tool observations+ evidence_entries = [e for e in entries if e.action not in ("done", "replan") and e.observation]+ if evidence_entries:+ steps_with_evidence.append((step, evidence_entries))++ if not steps_with_evidence:+ return await self.process(question, scratchpad, language, preference)++ sources_text = scratchpad.format_sources_markdown()++ # --- Iterative draft building ---+ draft = ""++ for i, (step, entries) in enumerate(steps_with_evidence):+ step_evidence = self._format_step_evidence(step, entries)++ if i == 0:+ # First iteration: if there's a second step, bundle it+ if len(steps_with_evidence) > 1:+ step2, entries2 = steps_with_evidence[1]+ step_evidence += "\n\n---\n\n" + self._format_step_evidence(step2, entries2)+ draft = await self._write_draft(+ question=question,+ previous_draft="(this is the first draft — no previous draft)",+ new_evidence=step_evidence,+ sources=sources_text,+ language=language,+ iteration=i + 1,+ preference=preference,+ )+ elif i == 1:+ # Second step was already bundled in iteration 0; skip+ continue+ else:+ # Subsequent iterations: previous draft + new step evidence+ draft = await self._write_draft(+ question=question,+ previous_draft=draft,+ new_evidence=step_evidence,+ sources=sources_text,+ language=language,+ iteration=i,+ preference=preference,+ )++ # --- Concise answer generation ---+ concise = await self._write_concise(+ question=question,+ detailed_answer=draft,+ language=language,+ preference=preference,+ )++ # --- Assemble final output ---+ final = f"## Summary\n\n{concise}\n\n---\n\n{draft}"+ return final++ # ------------------------------------------------------------------+ # Internal helpers for iterative mode+ # ------------------------------------------------------------------++ async def _write_draft(+ self,+ question: str,+ previous_draft: str,+ new_evidence: str,+ sources: str,+ language: str,+ iteration: int,+ preference: str = "",+ ) -> str:+ """Run one iteration of the incremental draft builder."""+ system_prompt = self._get_iterative_system_prompt()+ template = self.get_prompt("iterative_user_template") if self.has_prompts() else None++ if template:+ user_prompt = template.format(+ question=question,+ previous_draft=previous_draft,+ new_evidence=new_evidence,+ sources=sources or "(no external sources)",+ preference=preference or "(no specific preference)",+ language=language,+ )+ else:+ user_prompt = (+ f"## Question\n{question}\n\n"+ f"## Previous Draft\n{previous_draft}\n\n"+ f"## New Evidence\n{new_evidence}\n\n"+ f"## Available Sources\n{sources or '(none)'}\n\n"+ f"## User Preference\n{preference or '(none)'}\n\n"+ f"## Language\n{language}"+ )++ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ max_tokens=self.get_max_tokens() or 8192,+ stage=f"write_iter_{iteration}",+ )+ return response.strip()++ async def _write_concise(+ self,+ question: str,+ detailed_answer: str,+ language: str,+ preference: str = "",+ ) -> str:+ """Generate a concise answer from the completed detailed draft."""+ system_prompt = self._get_concise_system_prompt()+ template = self.get_prompt("concise_user_template") if self.has_prompts() else None++ if template:+ user_prompt = template.format(+ question=question,+ detailed_answer=detailed_answer,+ language=language,+ )+ else:+ user_prompt = (+ f"## Question\n{question}\n\n"+ f"## Detailed Answer\n{detailed_answer}\n\n"+ f"## Language\n{language}"+ )++ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ max_tokens=1024,+ stage="write_concise",+ )+ return response.strip()++ @staticmethod+ def _format_step_evidence(step, entries) -> str:+ """Format raw observations from a step into a single evidence block."""+ parts = [f"### Step {step.id}: {step.goal}"]+ for e in entries:+ block = (+ f"**Action**: {e.action}({e.action_input})\n"+ f"**Observation**:\n{e.observation}"+ )+ parts.append(block)+ return "\n\n".join(parts)++ # ------------------------------------------------------------------+ # Prompt construction+ # ------------------------------------------------------------------++ def _build_system_prompt(self) -> str:+ prompt = self.get_prompt("system") if self.has_prompts() else None+ if prompt:+ return prompt+ return (+ "You are an expert answer writer. Write a structured, comprehensive answer "+ "based on gathered evidence. Use Markdown with proper headings. "+ "All math must use LaTeX: inline $...$ and block $$...$$. "+ "Cite sources inline as [source-id]. Include a ## References section at the end."+ )++ def _get_iterative_system_prompt(self) -> str:+ prompt = self.get_prompt("iterative_system") if self.has_prompts() else None+ if prompt:+ return prompt+ return (+ "You are an expert answer writer building an answer incrementally. "+ "You receive a previous draft and new evidence. Expand and refine the draft "+ "by integrating the new evidence. Use Markdown, LaTeX for math, and cite sources."+ )++ def _get_concise_system_prompt(self) -> str:+ prompt = self.get_prompt("concise_system") if self.has_prompts() else None+ if prompt:+ return prompt+ return (+ "Produce a concise answer (2-4 sentences) for the question based on the "+ "detailed answer. If it's a multiple-choice or fill-in-the-blank question, "+ "give the direct answer first."+ )++ def _build_user_prompt(+ self,+ question: str,+ scratchpad: Scratchpad,+ language: str,+ preference: str,+ ) -> str:+ template = self.get_prompt("user_template") if self.has_prompts() else None++ scratchpad_content = scratchpad.build_writer_context()+ sources_text = scratchpad.format_sources_markdown()++ if template:+ return template.format(+ question=question,+ scratchpad_content=scratchpad_content,+ sources=sources_text or "(no external sources)",+ preference=preference or "(no specific preference)",+ language=language,+ )++ return (+ f"## Question\n{question}\n\n"+ f"## Gathered Evidence\n{scratchpad_content}\n\n"+ f"## Available Sources\n{sources_text or '(none)'}\n\n"+ f"## User Preference\n{preference or '(none)'}\n\n"+ f"## Language\n{language}"+ )diff --git a/src/agents/solve/analysis_loop/README.md b/src/agents/solve/analysis_loop/README.mddeleted file mode 100644index 8e6e6e80a..000000000--- a/src/agents/solve/analysis_loop/README.md+++ /dev/null@@ -1,295 +0,0 @@-# Analysis Loop - Deep Research Phase--## Overview--Analysis Loop is the first phase of the dual-loop architecture, responsible for **deeply understanding user questions**. Through iterative research, it dynamically collects and organizes knowledge until the question is sufficiently understood.--## Architecture--```-┌─────────────────────────────────────────┐-│ Analysis Loop (Research Phase) │-│ │-│ ┌──────────┐ ┌──────────┐ │-│ │Investigate│ -> │ Note │ ────┐ │-│ └──────────┘ └──────────┘ │ │-│ ▲ │ │ │-│ └────────────┴─────────────┘ │-│ │ │-│ Stop Condition Met │-│ │ │-│ ▼ │-│ InvestigateMemory │-└─────────────────────────────────────────┘-```--## Core Agents--### 1. InvestigateAgent--**Role**: Research planner and tool executor. Based on knowledge chain summaries and user questions, generates multiple high-value queries and calls tools to retrieve raw data.--**Key Features**:-1. Identifies knowledge gaps from cite_id summaries; generates multiple `[TOOL]tool_type | query` commands in one pass if needed.-2. Immediately calls tools (`rag_naive`, `rag_hybrid`, `web_search`, `query_item`) for each query to get `raw_result`.-3. When `[TOOL] none` appears, knowledge is sufficient and Analysis Loop automatically stops.--**Output Structure**:-```python-{- 'reasoning': 'List of knowledge gaps identified this round',- 'should_stop': False,- 'knowledge_item_ids': ['c01', 'c02'], # List of new cite_ids this round- 'actions': [- {'tool_type': 'rag_hybrid', 'query': 'Section 2.5...', 'cite_id': 'c01'},- {'tool_type': 'rag_naive', 'query': 'Lambda range in algorithm', 'cite_id': 'c02'}- ]-}-```--### 2. NoteAgent--**Role**: Note-taker. For each knowledge item in `knowledge_item_ids`, sequentially calls LLM to convert `raw_result` into summaries and extract citations.--**Key Features**:-1. Automatically iterates through multiple knowledge items in one round, independently constructing Prompt → LLM → parsing summary.-2. Summaries must be concise and extract citable sources from `raw_result`.-3. After processing, updates `InvestigateMemory` and `CitationMemory` for use by Solve Loop.--**Output Structure**:-```python-{- 'success': True,- 'processed_items': 2,- 'details': [- {'cite_id': 'c01', 'citations_count': 2},- {'cite_id': 'c02', 'citations_count': 1}- ],- 'failed': []-}-```--## Memory System--### InvestigateMemory--Persistent JSON structure that chains all knowledge collected during the analysis phase. Each tool call generates a unique `cite_id` and is recorded in `knowledge_chain`.--**Structure**:-```python-{- "user_question": "What is linear convolution?",- "knowledge_chain": [- {- "cite_id": "c01",- "tool_type": "rag_hybrid",- "query": "Section 2.5 Linear convolution definition and properties",- "raw_result": "...RAG source text...",- "summary": "Linear convolution derives from convolution integral; core properties include commutativity and associativity.",- "created_at": "...",- "updated_at": "..."- }- ],- "reflections": {- "remaining_questions": [],- "updated_at": "..."- },- "metadata": {- "total_iterations": 2,- "total_knowledge_items": 1,- "coverage_rate": 1.0,- "avg_confidence": 0.9- }-}-```--**Storage Location**: `{output_dir}/investigate_memory.json`--## Configuration--Configure Analysis Loop in `config.yaml`:--```yaml-system:- max_analysis_iterations: 5 # Maximum iterations--agents:- investigate_agent:- enabled: true- model: "gpt-4o"- temperature: 0.4-- note_agent:- enabled: true- model: "gpt-4o"- temperature: 0.3-```--## Usage Example--```python-from solve_agents.memory import InvestigateMemory-from solve_agents.analysis_loop import InvestigateAgent, NoteAgent--memory = InvestigateMemory.load_or_create(- output_dir="./output",- user_question="What is linear convolution?"-)--investigate_agent = InvestigateAgent(config, api_key, base_url)-note_agent = NoteAgent(config, api_key, base_url)--for i in range(max_iterations):- investigate_result = await investigate_agent.process(- question=question,- memory=memory,- citation_memory=citation_memory,- kb_name="ai_textbook",- output_dir="./output"- )-- cite_ids = investigate_result.get('knowledge_item_ids', [])- if cite_ids:- await note_agent.process(- question=question,- memory=memory,- new_knowledge_ids=cite_ids,- citation_memory=citation_memory,- output_dir="./output"- )-- if investigate_result.get('should_stop'):- break--memory.save()-```--## Workflow Example--**Question**: "What is linear convolution?"--**Round 1**:-1. **Investigate**: Outputs two queries- - `[TOOL]rag_hybrid | Linear convolution definition`- - `[TOOL]rag_naive | Geometric interpretation of convolution`- Gets cite_ids `c01/c02`.-2. **Note**: Processes `c01/c02` sequentially, generates summaries and extracts 3 citations.--**Round 2**:-1. **Investigate**: Outputs- - `[TOOL]rag_hybrid | Convolution calculation examples`- - `[TOOL]web_search | Latest application scenarios`- Gets cite_ids `c03/c04`.-2. **Note**: Processes `c03/c04`, supplements calculation procedures and practical examples.--**Round 3**:-1. **Investigate**: `[TOOL]none` - reasoning: "Definition, derivation, and examples all covered".-2. Analysis Loop completes.--**Result**: Collects 4 knowledge items; NoteAgent automatically updates summaries and citations; ready for Solve Loop consumption.--## Key Features--### 1. Dynamic Research-- No preset query count-- Dynamically determines based on actual needs-- Automatically judges when to stop--### 2. Tool Selection-- Prioritizes knowledge base (RAG)-- Uses web search when necessary-- Intelligently selects most appropriate tools--### 3. Citation Management-- Automatically extracts key citations-- Provides evidence for Solve Loop-- Supports subsequent citation formatting--### 4. Persistent Memory-- JSON format storage-- Supports checkpoint resumption-- Facilitates debugging and review--## Integration with Solve Loop--After Analysis Loop completes, `InvestigateMemory` is passed to Solve Loop:--```python-# Analysis Loop completes-investigate_memory.save()--# Solve Loop consumes-solve_memory = SolveMemory.load_or_create(...)-plan_result = await plan_agent.process(- question=question,- investigate_memory=investigate_memory, # Pass analysis results- solve_memory=solve_memory-)-```--Solve Loop can access:-- `investigate_memory.knowledge_chain`: All collected knowledge-- `investigate_memory.get_all_citations()`: All citations-- `investigate_memory.get_knowledge_summary()`: Knowledge summary--## Debugging and Monitoring--### View Memory Files--```bash-cat output/investigate_memory.json | jq .-```--### Monitor Iteration Progress--Logs display detailed information for each round:--```---- Analysis Loop Round 1 ---- [Investigate] Reasoning: Still missing calculation examples- • rag_hybrid: Section 2.4 convolution definition -> cite_id=c01- • rag_naive: Geometric interpretation of convolution -> cite_id=c02- [Note] Processed 2 knowledge items-```--### Performance Statistics--```python-metadata = investigate_memory.metadata-print(f"Total iterations: {metadata['total_iterations']} rounds")-print(f"Total knowledge items: {metadata['total_knowledge_items']}")-print(f"Coverage rate: {metadata['coverage_rate']:.2%}")-print(f"Average confidence: {metadata['avg_confidence']:.2f}")-```--## Common Questions--**Q: How to adjust maximum iteration count?**--Set in `config.yaml`:-```yaml-system:- max_analysis_iterations: 5 # Default 5 rounds-```--**Q: How to force web search usage?**--Modify the Investigate Agent prompt or pass parameters when calling.--**Q: How to view extracted citations?**--```python-citations = investigate_memory.get_all_citations()-for citation in citations:- print(citation)-```--**Q: What if memory file becomes too large?**--Periodically clean up `raw_content`, keeping only `summary` and `citations`.-------**Related Documentation**:-- [Solve Loop README](../solve_loop/README.md)-- [Main README](../README.md)diff --git a/src/agents/solve/analysis_loop/__init__.py b/src/agents/solve/analysis_loop/__init__.pydeleted file mode 100644index 60fce09dd..000000000--- a/src/agents/solve/analysis_loop/__init__.py+++ /dev/null@@ -1,14 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-Analysis Loop - Analysis loop (Investigate → Note)-Deeply understand user questions, collect and organize knowledge-"""--from .investigate_agent import InvestigateAgent-from .note_agent import NoteAgent--__all__ = [- "InvestigateAgent",- "NoteAgent",-]diff --git a/src/agents/solve/analysis_loop/investigate_agent.py b/src/agents/solve/analysis_loop/investigate_agent.pydeleted file mode 100644index 2f24b61de..000000000--- a/src/agents/solve/analysis_loop/investigate_agent.py+++ /dev/null@@ -1,414 +0,0 @@-#!/usr/bin/env python-"""-InvestigateAgent - Investigator-Generates query actions and calls tools based on current memory and reflections.-"""--from pathlib import Path-import sys-from typing import Any--# Add project root to path-project_root = Path(__file__).parent.parent.parent.parent-sys.path.insert(0, str(project_root))--import json--from src.agents.base_agent import BaseAgent-from src.tools import query_numbered_item, rag_search, web_search--from ..memory import CitationMemory, InvestigateMemory, KnowledgeItem-from ..utils.json_utils import extract_json_from_text---class InvestigateAgent(BaseAgent):- """Investigator Agent - Generates queries and calls tools"""-- def __init__(- self,- config: dict[str, Any],- api_key: str,- base_url: str,- api_version: str | None = None,- token_tracker=None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="solve",- agent_name="investigate_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- token_tracker=token_tracker,- )- # Read web_search enabled config from tools.web_search.enabled- self.enable_web_search = config.get("tools", {}).get("web_search", {}).get("enabled", True)-- # Read agent-specific config from solve.agents.investigate_agent- agent_config = config.get("solve", {}).get("agents", {}).get("investigate_agent", {})- self.max_actions_per_round = agent_config.get("max_actions_per_round", 1)- self.max_iterations = agent_config.get("max_iterations", 3)-- async def process(- self,- question: str,- memory: InvestigateMemory,- citation_memory: CitationMemory,- kb_name: str = "ai_textbook",- output_dir: str | None = None,- verbose: bool = True,- ) -> dict[str, Any]:- """- Process investigation flow (supports multiple tools per round)-- Args:- question: User question- memory: Investigation memory- citation_memory: Citation memory (for registering citations)- kb_name: Knowledge base name- output_dir: Output directory- verbose: Whether to print detailed info-- Returns:- dict: Investigation result- {- 'reasoning': str,- 'should_stop': bool,- 'knowledge_item_ids': List[str],- 'actions': List[Dict[str, Any]]- }- """- if citation_memory is None:- raise ValueError(- "citation_memory cannot be None, InvestigateAgent needs it for citation registration"- )-- # 1. Build context- context = self._build_context(question, memory)-- # 2. Build prompts- system_prompt = self._build_system_prompt()- user_prompt = self._build_user_prompt(context)-- # 3. Call LLM- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- verbose=verbose,- response_format={"type": "json_object"},- )-- # 4. Parse output (JSON)- parsed_result = extract_json_from_text(response)-- if not parsed_result or not isinstance(parsed_result, dict):- self.logger.warning("Parse failed: LLM did not return valid JSON")- return {- "reasoning": "Parse failed: invalid JSON",- "should_stop": True,- "knowledge_item_ids": [],- "actions": [],- }-- reasoning = parsed_result.get("reasoning", "")- tool_plans = parsed_result.get("plan", [])-- # Ensure tool_plans is a list (handle case where LLM returns dict instead of list)- if not isinstance(tool_plans, list):- if isinstance(tool_plans, dict):- # If plan is a dict, wrap it in a list- self.logger.warning("Parse warning: 'plan' field is a dict, wrapping in list")- tool_plans = [tool_plans]- else:- self.logger.warning(- "Parse warning: 'plan' field is not a list or dict, using empty list"- )- tool_plans = []-- # 5. Determine if should stop- should_stop = False- if not tool_plans:- should_stop = True- else:- for plan in tool_plans:- if plan.get("tool") == "none":- should_stop = True- break-- if should_stop:- return {- "reasoning": reasoning,- "should_stop": True,- "knowledge_item_ids": [],- "actions": [],- }-- # 6. Execute multiple tool calls (limited by max_actions_per_round)- knowledge_ids: list[str] = []- executed_actions: list[dict[str, Any]] = []-- # Limit number of actions per round based on config- tool_plans_to_execute = tool_plans[: self.max_actions_per_round]-- for plan in tool_plans_to_execute:- tool_type = plan.get("tool")- if not tool_type:- continue-- query = plan.get("query", "")- identifier = plan.get("identifier")-- if tool_type == "none":- continue-- knowledge_item = await self._execute_single_action(- tool_selection=tool_type,- query=query,- identifier=identifier,- kb_name=kb_name,- output_dir=output_dir,- citation_memory=citation_memory,- )-- executed_actions.append(- {- "tool_type": tool_type,- "query": query,- "identifier": identifier,- "cite_id": knowledge_item.cite_id if knowledge_item else None,- }- )-- if knowledge_item:- memory.add_knowledge(knowledge_item)- knowledge_ids.append(knowledge_item.cite_id)-- if knowledge_ids and output_dir:- memory.save()-- # 7. Return results- return {- "reasoning": reasoning,- "should_stop": False,- "knowledge_item_ids": knowledge_ids,- "actions": executed_actions,- }-- def _build_context(self, question: str, memory: InvestigateMemory) -> dict[str, Any]:- """Build context (pass full content, no truncation)"""- knowledge_chain_full = []- for item in memory.knowledge_chain:- knowledge_chain_full.append(- {- "cite_id": item.cite_id,- "tool_type": item.tool_type,- "query": item.query,- "raw_result": item.raw_result,- "summary": item.summary,- }- )-- remaining_questions_full = []- if memory.reflections and memory.reflections.remaining_questions:- remaining_questions_full = memory.reflections.remaining_questions.copy()- knowledge_chain_summary = (- "\n".join(- f"- {item.cite_id} ({item.tool_type}): {item.summary or item.raw_result[:200]}"- for item in memory.knowledge_chain- )- if memory.knowledge_chain- else "(none)"- )- reflections_summary = (- "\n".join(f"- {q}" for q in remaining_questions_full)- if remaining_questions_full- else "(no remaining questions)"- )-- return {- "question": question,- "num_knowledge": len(memory.knowledge_chain),- "knowledge_chain_full": knowledge_chain_full,- "knowledge_chain_summary": knowledge_chain_summary,- "reflections_summary": reflections_summary,- "remaining_questions": remaining_questions_full,- "action_queue": "(no action history)",- }-- def _build_system_prompt(self) -> str:- """Build system prompt"""- prompt = self.get_prompt("system") if self.has_prompts() else None- if not prompt:- raise ValueError(- "InvestigateAgent missing system prompt. Configure in src/agents/solve/prompts/en/analysis_loop/investigate_agent.yaml"- )-- # If web_search is disabled, remove web_search related content from prompt- if not self.enable_web_search:- # Get the web_search disabled prompt if available, otherwise filter out web_search lines- web_search_disabled_prompt = (- self.get_prompt("web_search_disabled") if self.has_prompts() else None- )- if web_search_disabled_prompt:- # Replace web_search description with disabled message- prompt = prompt.replace(- self.get_prompt("web_search_description") or "", web_search_disabled_prompt- )- else:- # Simple filter: remove lines containing web_search tool description- lines = prompt.split("\n")- filtered_lines = []- for line in lines:- # Skip lines that describe web_search as an available tool- if "`web_search`" in line and (- "Use Sparingly" in line or "latest news" in line or "Web Search" in line- ):- continue- # Also remove web_search from tool list in output format- if "web_search" in line and (- "rag_naive | rag_hybrid |" in line or 'tool":' in line- ):- line = (- line.replace(" | web_search", "")- .replace("| web_search", "")- .replace("web_search |", "")- .replace("web_search", "")- )- filtered_lines.append(line)- prompt = "\n".join(filtered_lines)-- return prompt-- def _build_user_prompt(self, context: dict[str, Any]) -> str:- """Build user prompt (pass full content)"""- template = self.get_prompt("user_template") if self.has_prompts() else None- if not template:- raise ValueError(- "InvestigateAgent missing user prompt template. Configure in prompts/en/analysis_loop/investigate_agent.yaml"- )- return template.format(**context)-- async def _execute_single_action(- self,- tool_selection: str,- query: str,- identifier: str | None,- kb_name: str,- output_dir: str | None,- citation_memory: CitationMemory,- ) -> KnowledgeItem | None:- """Execute a single tool call"""- import time-- start_time = time.time()- tool_input = {"query": query, "identifier": identifier, "kb_name": kb_name}-- try:- if tool_selection == "rag_naive":- result = await self._call_rag_naive(query, kb_name, output_dir)- raw_result = result.get("answer", "")-- elif tool_selection == "rag_hybrid":- result = await self._call_rag_hybrid(query, kb_name, output_dir)- raw_result = result.get("answer", "")-- elif tool_selection == "web_search":- # Check if web_search is enabled- if not self.enable_web_search:- self.logger.warning(- "Tool call rejected (web_search): web_search is disabled in config"- )- return None- result = await self._call_web_search(query, output_dir)- raw_result = json.dumps(result, ensure_ascii=False, indent=2)-- elif tool_selection == "query_item":- identifier_to_use = identifier or query-- if (- not identifier_to_use- or not isinstance(identifier_to_use, str)- or not identifier_to_use.strip()- ):- self.logger.warning(- "Tool call failed (query_item): identifier is empty or invalid"- )- return None-- result = await self._call_query_item(identifier_to_use, kb_name)- raw_result = result.get("content", result.get("answer", ""))-- else:- self.logger.warning(f"Unknown tool type: {tool_selection}")- return None-- elapsed_ms = (time.time() - start_time) * 1000-- # Create and register citation- cite_id = citation_memory.add_citation(- tool_type=tool_selection,- query=query,- raw_result=raw_result,- stage="analysis",- metadata={"identifier": identifier},- )- citation_memory.save()-- # Log tool call- self.logger.log_tool_call(- tool_name=tool_selection,- tool_input=tool_input,- tool_output=result,- status="success",- elapsed_ms=elapsed_ms,- citation_id=cite_id,- )-- # Create knowledge item- knowledge_item = KnowledgeItem(- cite_id=cite_id,- tool_type=tool_selection,- query=query,- raw_result=raw_result,- summary="", # Generated by NoteAgent- )-- return knowledge_item-- except Exception as e:- elapsed_ms = (time.time() - start_time) * 1000- error_msg = str(e)-- self.logger.log_tool_call(- tool_name=tool_selection,- tool_input=tool_input,- tool_output=error_msg,- status="failed",- elapsed_ms=elapsed_ms,- error=error_msg,- )-- self.logger.warning(f"Tool call failed ({tool_selection}): {e}")- return None-- async def _call_rag_naive(- self, query: str, kb_name: str, output_dir: str | None- ) -> dict[str, Any]:- """Call RAG Naive"""- return await rag_search(query=query, kb_name=kb_name, mode="naive")-- async def _call_rag_hybrid(- self, query: str, kb_name: str, output_dir: str | None- ) -> dict[str, Any]:- """Call RAG Hybrid"""- return await rag_search(query=query, kb_name=kb_name, mode="hybrid")-- async def _call_web_search(self, query: str, output_dir: str | None) -> dict[str, Any]:- """Call Web Search"""- return web_search(query=query, output_dir=output_dir or "./cache", verbose=False)-- async def _call_query_item(self, identifier: str, kb_name: str) -> dict[str, Any]:- """Call Query Item"""- return query_numbered_item(identifier=identifier, kb_name=kb_name)diff --git a/src/agents/solve/analysis_loop/note_agent.py b/src/agents/solve/analysis_loop/note_agent.pydeleted file mode 100644index bc61fd15f..000000000--- a/src/agents/solve/analysis_loop/note_agent.py+++ /dev/null@@ -1,190 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-NoteAgent - Note taker-Based on new knowledge, generates or updates notes, annotates covered pain points and missing points-"""--from pathlib import Path-import sys-from typing import Any--# Add project root to path-project_root = Path(__file__).parent.parent.parent.parent-sys.path.insert(0, str(project_root))--from src.agents.base_agent import BaseAgent--from ..memory import CitationMemory, InvestigateMemory, KnowledgeItem-from ..utils import ParseError, validate_note_output-from ..utils.json_utils import extract_json_from_text---class NoteAgent(BaseAgent):- """Note taker Agent - Generates and updates notes"""-- def __init__(- self,- config: dict[str, Any],- api_key: str,- base_url: str,- api_version: str | None = None,- token_tracker=None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="solve",- agent_name="note_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- token_tracker=token_tracker,- )-- async def process(- self,- question: str,- memory: InvestigateMemory,- new_knowledge_ids: list[str],- citation_memory: CitationMemory | None = None,- output_dir: str | None = None,- verbose: bool = True,- ) -> dict[str, Any]:- """- Process note generation workflow (supports multiple knowledge_items in single round)-- Args:- question: User question- memory: Investigation memory- new_knowledge_ids: List of cite_ids for new knowledge items- citation_memory: Citation memory- output_dir: Output directory- verbose: Whether to print detailed information-- Returns:- dict: Aggregated note result- """- if isinstance(new_knowledge_ids, str): # Backward compatibility- target_ids = [new_knowledge_ids]- else:- target_ids = new_knowledge_ids or []-- if not target_ids:- return {"success": False, "reason": "new_knowledge_ids is empty"}-- system_prompt = self._build_system_prompt()- processed_details = []- failed_ids = []-- for cite_id in target_ids:- knowledge_item = next((k for k in memory.knowledge_chain if k.cite_id == cite_id), None)- if not knowledge_item:- failed_ids.append({"cite_id": cite_id, "reason": "knowledge_item not found"})- continue-- context = self._build_context(question, knowledge_item, memory)- user_prompt = self._build_user_prompt(context)-- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- verbose=verbose,- response_format={"type": "json_object"},- )-- if verbose:- self.logger.debug(f"cite_id={cite_id} LLM output stats:")- self.logger.debug(f" - Total length: {len(response)} chars")- self.logger.debug(- f" - Last 100 chars: ...{response[-100:] if len(response) > 100 else response}"- )-- try:- parsed_result = extract_json_from_text(response)- if not parsed_result or not isinstance(parsed_result, dict):- raise ParseError("LLM output is not a valid JSON object")- # citations is optional, default to empty list- if parsed_result.get("citations") is None:- parsed_result["citations"] = []- elif not isinstance(parsed_result.get("citations"), list):- raise ParseError("citations field must be a list")- validate_note_output(parsed_result)- if verbose:- summary_len = len(parsed_result.get("summary", ""))- print(f"📝 [NoteAgent] cite_id={cite_id} summary length: {summary_len}")- except ParseError as e:- failed_ids.append({"cite_id": cite_id, "reason": str(e)})- continue- except Exception as e:- failed_ids.append({"cite_id": cite_id, "reason": str(e)})- continue-- citations = parsed_result.get("citations", [])- memory.update_knowledge_summary(cite_id=cite_id, summary=parsed_result["summary"])-- if citation_memory:- sources = ", ".join(- citation.get("source", "") for citation in citations if citation.get("source")- )- metadata_block = {"extracted_sources": citations} if citations else None- try:- citation_memory.update_citation(- cite_id=cite_id,- content=parsed_result["summary"],- source=sources or None,- metadata=metadata_block,- stage="analysis",- )- citation_memory.save()- except ValueError:- if verbose:- print(f"⚠️ cite_id not found in CitationMemory: {cite_id}")-- processed_details.append(- {- "cite_id": cite_id,- "summary": parsed_result["summary"],- "citations_count": len(citations),- }- )-- if processed_details and output_dir:- memory.save()-- return {- "success": len(failed_ids) == 0,- "processed_items": len(processed_details),- "details": processed_details,- "failed": failed_ids,- }-- def _build_context(- self, question: str, knowledge_item: KnowledgeItem, memory: InvestigateMemory- ) -> dict[str, Any]:- """Build context (pass complete content)"""- return {- "question": question,- "tool_type": knowledge_item.tool_type,- "query": knowledge_item.query,- "raw_result": knowledge_item.raw_result, # Complete content- }-- def _build_system_prompt(self) -> str:- """Build system prompt"""- prompt = self.get_prompt("system") if self.has_prompts() else None- if not prompt:- raise ValueError(- "NoteAgent missing system prompt, please configure system in prompts/zh/analysis_loop/note_agent.yaml."- )- return prompt-- def _build_user_prompt(self, context: dict[str, Any]) -> str:- """Build user prompt (pass complete content)"""- template = self.get_prompt("user_template") if self.has_prompts() else None- if not template:- raise ValueError(- "NoteAgent missing user prompt template, please configure user_template in prompts/zh/analysis_loop/note_agent.yaml."- )- return template.format(**context)diff --git a/src/agents/solve/cli.py b/src/agents/solve/cli.pynew file mode 100644index 000000000..bca38ae65--- /dev/null+++ b/src/agents/solve/cli.py@@ -0,0 +1,220 @@+#!/usr/bin/env python+"""+CLI test script for the Solve Agent (Plan -> ReAct -> Write).++Usage:+ # Single question mode+ python -m src.agents.solve.cli "What is linear convolution?" --kb ai-textbook++ # Detailed (iterative) answer mode+ python -m src.agents.solve.cli "What is linear convolution?" --detailed++ # Interactive mode (default when no question given)+ python -m src.agents.solve.cli+ python -m src.agents.solve.cli -i --language zh++Features:+ - Integrated with PersonalizationService for memory recording+ - EventBus enabled for post-solve memory updates+"""++from __future__ import annotations++import argparse+import asyncio+import sys+from pathlib import Path++# Ensure project root is on sys.path+_project_root = Path(__file__).resolve().parent.parent.parent.parent+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)+++def _list_knowledge_bases() -> list[str]:+ """List available knowledge bases from disk."""+ try:+ from src.knowledge.manager import KnowledgeBaseManager+ mgr = KnowledgeBaseManager()+ return mgr.list_knowledge_bases()+ except Exception:+ # Fallback: scan directory+ kb_dir = _project_root / "data" / "knowledge_bases"+ if kb_dir.exists():+ return [d.name for d in kb_dir.iterdir() if d.is_dir() and not d.name.startswith(".")]+ return []+++def _pick_kb(current_kb: str) -> str:+ """Prompt user to pick a knowledge base, returns selected name."""+ kbs = _list_knowledge_bases()+ if not kbs:+ print(" (no knowledge bases found, using default)")+ return current_kb++ print("\n Available knowledge bases:")+ for i, name in enumerate(kbs, 1):+ marker = " <-" if name == current_kb else ""+ print(f" {i}. {name}{marker}")+ print(f" 0. Keep current ({current_kb})")++ try:+ choice = input(" Select [0]: ").strip()+ except (EOFError, KeyboardInterrupt):+ return current_kb++ if not choice or choice == "0":+ return current_kb++ try:+ idx = int(choice) - 1+ if 0 <= idx < len(kbs):+ return kbs[idx]+ except ValueError:+ # Treat raw text as kb name+ if choice in kbs:+ return choice++ print(f" Invalid choice, keeping: {current_kb}")+ return current_kb+++async def _ensure_personalization() -> bool:+ """Start EventBus and PersonalizationService for in-process memory.++ Returns True if both services started successfully.+ """+ ok = True+ try:+ from src.core.event_bus import get_event_bus++ bus = get_event_bus()+ await bus.start()+ except Exception as exc:+ print(f"\n WARNING: EventBus failed to start: {exc}")+ ok = False+ try:+ from src.personalization.service import get_personalization_service++ svc = get_personalization_service()+ await svc.start()+ except Exception as exc:+ print(f"\n WARNING: PersonalizationService failed to start: {exc}")+ ok = False+ return ok+++async def _flush_events() -> None:+ """Wait for EventBus to finish processing all pending events."""+ try:+ from src.core.event_bus import get_event_bus++ bus = get_event_bus()+ await bus.flush(timeout=60.0)+ except Exception:+ pass+++def _print_result(result: dict) -> None:+ print("\n" + "=" * 60)+ print("FINAL ANSWER")+ print("=" * 60)+ print(result["final_answer"])+ print("=" * 60)+ print(f"Output directory: {result['output_dir']}")+ print(f"Steps: {result.get('completed_steps', '?')}/{result.get('total_steps', '?')}")+ print(f"ReAct entries: {result.get('total_react_entries', '?')}")+ print(f"Plan revisions: {result.get('plan_revisions', 0)}")+++async def _make_solver(kb_name: str, language: str, output_dir: str | None = None):+ from src.agents.solve import MainSolver+ solver = MainSolver(kb_name=kb_name, language=language, output_base_dir=output_dir)+ await solver.ainit()+ return solver+++async def run_interactive(kb_name: str, language: str, output_dir: str | None, detailed: bool = False) -> None:+ print("\n" + "=" * 60)+ mode_label = "Detailed" if detailed else "Simple"+ print(f" DeepTutor Solve Agent — Interactive Mode ({mode_label})")+ print("=" * 60)++ print(" Initializing memory system...", end="", flush=True)+ mem_ok = await _ensure_personalization()+ print(" done" if mem_ok else " FAILED (see warnings above)")++ while True:+ # --- Step 1: pick knowledge base ---+ kb_name = _pick_kb(kb_name)+ print(f" KB: {kb_name} | Language: {language} | Detailed: {detailed}")++ # --- Step 2: enter question ---+ try:+ question = input("\nQuestion (/quit to exit)> ").strip()+ except (EOFError, KeyboardInterrupt):+ print("\nBye!")+ break++ if not question:+ continue+ if question.lower() in ("/quit", "/exit", "/q"):+ print("Bye!")+ break++ # --- Step 3: solve ---+ try:+ solver = await _make_solver(kb_name, language, output_dir)+ result = await solver.solve(question, detailed=detailed)+ _print_result(result)+ except Exception as exc:+ print(f"\n Error: {exc}\n")+ import traceback+ traceback.print_exc()++ # Wait for memory system to process the solve event+ print(" Syncing memory...", end="", flush=True)+ await _flush_events()+ print(" done")+ print()+++async def main() -> None:+ parser = argparse.ArgumentParser(+ description="DeepTutor Solve Agent — Plan -> ReAct -> Write",+ )+ parser.add_argument("question", nargs="?", default=None, help="Question to solve (omit for interactive mode)")+ parser.add_argument("--kb", default="ai-textbook", help="Knowledge base name (default: ai-textbook)")+ parser.add_argument("--language", default="en", help="Output language: en / zh (default: en)")+ parser.add_argument("--output-dir", default=None, help="Override output base directory")+ parser.add_argument("-i", "--interactive", action="store_true", help="Start in interactive mode")+ parser.add_argument("--detailed", action="store_true", default=None,+ help="Enable iterative detailed answer mode")+ args = parser.parse_args()++ if args.interactive or args.question is None:+ await run_interactive(args.kb, args.language, args.output_dir, args.detailed)+ else:+ await _ensure_personalization()+ solver = await _make_solver(args.kb, args.language, args.output_dir)+ result = await solver.solve(args.question, detailed=args.detailed)+ _print_result(result)+ print(" Syncing memory...", end="", flush=True)+ await _flush_events()+ print(" done")++ # Cleanup+ try:+ from src.core.event_bus import get_event_bus+ await get_event_bus().stop()+ except Exception:+ pass+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/src/agents/solve/context.md b/src/agents/solve/context.mdnew file mode 100644index 000000000..09f757868--- /dev/null+++ b/src/agents/solve/context.md@@ -0,0 +1,450 @@+# Solve 模块 — 上下文工程审计++> 本文档从 **上下文工程 (Context Engineering)** 的视角,逐模块、逐 Agent 梳理当前 `src/agents/solve/` 中每次 LLM 调用的输入上下文组成,分析信息流转路径与压缩策略,并标注可改进点。++---++## 0. 架构总览++```+Pipeline: Plan → ReAct → Write++Phase 1 — PlannerAgent.process() → Plan (steps)+Phase 2 — SolverAgent.process() × N → Entry (thought/action/observation/self_note)+Phase 3 — WriterAgent.process() → final_answer (Markdown)+ WriterAgent.process_iterative() → detailed + concise answer++Memory: Scratchpad (统一记忆体:Plan + Entries + Sources + Metadata)+```++---++## 1. PlannerAgent — 规划阶段++### 1.1 调用时机+- Phase 1 开始时(首次规划)+- Phase 2 中 SolverAgent 返回 `replan` 动作时(重新规划)++### 1.2 LLM 调用上下文++| 上下文槽位 | 来源 | 内容描述 | 动态/静态 |+|-----------|------|---------|----------|+| **system_prompt** | `prompts/en/planner_agent.yaml → system` | 角色定义 + 规则 + 输出格式 (JSON) | 静态 |+| **user_prompt → {question}** | `MainSolver.solve(question)` 传入 | 用户原始问题,完整文本 | 动态 |+| **user_prompt → {tools_description}** | `ToolRegistry.build_planner_description()` 动态组合 | 根据注册的工具生成描述 (默认: rag_search / web_search / code_execute) | 动态 |+| **user_prompt → {scratchpad_summary}** | `Scratchpad` 状态 | 首次:"(initial plan — no progress yet)";replan 时:各步骤状态 + self_note 汇总 + replan reason | 动态 |++### 1.3 Prompt 模板++```yaml+# user_template+## Question+{question}++## Available Tools+{tools_description}++## Progress So Far+{scratchpad_summary}+```++### 1.4 scratchpad_summary 的组装逻辑(replan 时)++```python+# planner_agent.py → _build_user_prompt()+for step in scratchpad.plan.steps:+ entries = scratchpad.get_entries_for_step(step.id)+ notes = " | ".join(e.self_note for e in entries if e.self_note)+ → "[S1] (COMPLETED) 步骤目标"+ → " Notes: note1 | note2"++# 追加最后一条 replan entry 的 action_input 作为 replan reason+```++### 1.5 上下文特征分析++- **优点**:首次调用上下文极简,LLM 聚焦规划任务。+- **缺失**:+ - 无用户历史对话上下文(多轮 Q&A 场景缺失)+ - 无知识库元信息(不知道 KB 里有什么内容、什么格式)+ - 无用户个性化偏好(风格/难度/语言偏好未注入规划阶段)+ - replan 时 `scratchpad_summary` 只有 self_note 压缩摘要,丢失了具体 observation 细节++---++## 2. SolverAgent — ReAct 求解阶段++### 2.1 调用时机+- Phase 2 中对每个 PlanStep 的每轮 ReAct 迭代(最多 `max_react_iterations` 轮/步骤)++### 2.2 LLM 调用上下文++| 上下文槽位 | 来源 | 内容描述 | 动态/静态 |+|-----------|------|---------|----------|+| **system_prompt** | `prompts/en/solver_agent.yaml → system` | 角色定义 + 5 个 action 说明表 + 指南 + 输出格式 (JSON) | 静态 |+| **user_prompt → {question}** | 原始问题全文 | 用户原始问题 | 动态(但跨调用不变) |+| **user_prompt → {plan}** | `Scratchpad._format_plan()` | 完整计划概览(含分析 + 各步骤状态标记 [x]/[>]/[ ]) | 动态 |+| **user_prompt → {current_step}** | `PlanStep` 对象 | 当前步骤 ID + 目标文本 | 动态 |+| **user_prompt → {step_history}** | `Scratchpad.build_solver_context()` | 当前步骤的所有历史 round:thought + action + observation(**完整**) + self_note | 动态(增长) |+| **user_prompt → {previous_knowledge}** | `Scratchpad.build_solver_context()` | 已完成步骤的 self_note 汇总(压缩形式) | 动态(增长) |++### 2.3 Prompt 模板++```yaml+# user_template+## Original Question+{question}++## Plan+{plan}++## Current Step+{current_step}++## Previous Actions for This Step+{step_history}++## Knowledge from Previous Steps+{previous_knowledge}+```++### 2.4 上下文压缩策略 — `build_solver_context()`++```+Scratchpad.build_solver_context(current_step_id, max_tokens=6000):++1. plan_text = 完整计划(analysis + 各步骤带状态标记)+2. current_step_text = "[S2] 步骤目标"+3. step_history = 当前步骤所有 round 的 FULL observation(不压缩)+4. previous_knowledge:+ - 正常:[S1] 步骤目标: note1 note2 note3(self_note 拼接)+ - 超预算(>6000 tokens):仅保留 "[S1]: note1 | note2"(管道分隔)++压缩只在 previous_knowledge 上执行,step_history 始终保留完整 observation。+```++### 2.5 上下文特征分析++- **优点**:+ - step_history 保留完整 observation,SolverAgent 能看到当前步骤的全部工具返回+ - previous_knowledge 有 token 预算控制,避免上下文爆炸+ - self_note 作为信息压缩机制,跨步骤传递关键发现+- **缺失/风险**:+ - **step_history 无压缩上限**:如果某步骤迭代多轮,observation 可能非常长(每个 observation 最大 `obs_max * 4` 字符)+ - **question 每轮重复**:原始问题全文在每次调用中重复传入+ - **plan 每轮重复**:完整 plan 在每次调用中重复传入(步骤多时可观)+ - **无 few-shot 示例**:system prompt 有输出格式示例但仅 1 个+ - **code_execute 的 observation 包含完整代码**:`Code:\n```python\n{code}\n```\n\n{output}`,代码可能很长++---++## 3. WriterAgent — 写作阶段++WriterAgent 有 **3 种调用模式**,共涉及 **5 个不同的 LLM 调用**:++### 3.1 Simple 模式 — `process()`++**单次 LLM 调用生成完整答案。**++| 上下文槽位 | 来源 | 内容描述 |+|-----------|------|---------|+| **system_prompt** | `writer_agent.yaml → system` | 角色 + Markdown/LaTeX 格式规则 + 结构要求 + 引用规则 |+| **user → {question}** | 原始问题 | 用户问题全文 |+| **user → {scratchpad_content}** | `Scratchpad.build_writer_context()` | 所有步骤的 plan + entries 详情 |+| **user → {sources}** | `Scratchpad.format_sources_markdown()` | 去重后的引用来源列表 (Markdown) |+| **user → {preference}** | `MemoryReader.get_writer_context()` | 用户学习记忆上下文(reflection + weakness,可为空) |+| **user → {language}** | `config.system.language` | 输出语言代码 (en/zh) |++### 3.2 Iterative 模式 — `process_iterative()`++**多次 LLM 调用,逐步累积 draft,最后生成 concise answer。**++#### 3.2.1 Draft 迭代 — `_write_draft()` × N++| 上下文槽位 | 来源 | 内容描述 |+|-----------|------|---------|+| **system_prompt** | `writer_agent.yaml → iterative_system` | 增量写作角色 + 格式规则 |+| **user → {question}** | 原始问题 | 用户问题全文 |+| **user → {previous_draft}** | 上一轮 draft 输出 / 首轮为占位文本 | 累积的答案草稿(**可能很长**) |+| **user → {new_evidence}** | `_format_step_evidence(step, entries)` | 当前步骤的 action + observation(完整) |+| **user → {sources}** | `Scratchpad.format_sources_markdown()` | 引用来源列表 |+| **user → {language}** | 配置 | 输出语言 |++**Draft 迭代逻辑**:+```+Iter 1: evidence(S1) + evidence(S2) → draft_1 # 首轮合并前两步+Iter 2: draft_1 + evidence(S3) → draft_2 # 后续每步增量+Iter N: draft_{N-1} + evidence(S_{N+1}) → draft_N+```++#### 3.2.2 Concise 生成 — `_write_concise()`++| 上下文槽位 | 来源 | 内容描述 |+|-----------|------|---------|+| **system_prompt** | `writer_agent.yaml → concise_system` | 简洁回答角色 + 规则 |+| **user → {question}** | 原始问题 | 用户问题全文 |+| **user → {detailed_answer}** | 最终 draft | 完整详细答案(**可能非常长**) |+| **user → {language}** | 配置 | 输出语言 |++### 3.3 `build_writer_context()` 上下文组装逻辑++```+Scratchpad.build_writer_context(max_tokens=12000):++1. Plan 概览(带状态标记)+2. 每个 completed/in_progress 步骤:+ 正常:+ ### Step S1: 目标+ **Round 0** — Action: rag_search(query)+ Note: self_note+ Observation: <完整 observation>++ 超预算(>12000 tokens)时压缩:+ 前 N-2 步 → 仅保留 "Round 0: self_note"(丢弃 observation)+ 最后 2 步 → 保留完整 observation+```++### 3.4 上下文特征分析++- **优点**:+ - `build_writer_context` 有 token 预算和渐进压缩策略+ - Iterative 模式通过分步投喂 evidence 降低单次上下文压力+ - 个性化偏好注入(虽然仅在 Simple 模式)+- **缺失/风险**:+ - **Iterative 模式的 previous_draft 持续增长**:每次迭代 draft 只增不减,后期可能超出上下文窗口+ - **Iterative 模式缺少 preference**:`_write_draft()` 和 `_write_concise()` 未注入用户偏好+ - **sources 在每次 draft 迭代中重复传入**:完整引用列表每轮重复+ - **_format_step_evidence 无长度限制**:observation 完整传入,单步证据可能很大++---++## 4. Code Generation — 隐式 LLM 调用++### 4.1 调用时机+- SolverAgent 返回 `code_execute` 动作时,`MainSolver._generate_code()` 发起额外 LLM 调用++### 4.2 LLM 调用上下文++| 上下文槽位 | 来源 | 内容描述 |+|-----------|------|---------|+| **system_prompt** | 硬编码字符串 | "You are a Python code generator..." + 库提示 + 输出规则 |+| **user_prompt** | SolverAgent 的 `action_input` | 自然语言意图描述(如 "compute the convolution of x=[1,2,3] and h=[1,1]") |++### 4.3 上下文特征分析++- **缺失严重**:+ - 无原始问题上下文(代码生成不知道整体问题背景)+ - 无当前步骤目标(不知道这段代码要验证什么)+ - 无先前步骤的知识(可能需要用到之前检索的公式)+ - 仅靠 SolverAgent 在 `action_input` 中的描述传递意图++---++## 5. Scratchpad — 统一记忆体++### 5.1 数据结构++```+Scratchpad+├── question: str # 原始问题+├── plan: Plan # 规划+│ ├── analysis: str # 问题分析+│ └── steps: [PlanStep] # 步骤列表+│ ├── id: str # 步骤 ID (S1, S2, ...)+│ ├── goal: str # 步骤目标+│ ├── tools_hint: [str] # 工具提示(未实际使用)+│ └── status: str # 状态 (pending/in_progress/completed/skipped)+├── entries: [Entry] # ReAct 迭代记录+│ ├── step_id: str # 所属步骤+│ ├── round: int # 轮次号+│ ├── thought: str # 思考+│ ├── action: str # 动作+│ ├── action_input: str # 动作输入+│ ├── observation: str # 工具返回结果+│ ├── self_note: str # 自我总结(压缩用)+│ ├── sources: [Source] # 来源引用+│ └── timestamp: str # 时间戳+└── metadata: dict # 元数据+ ├── total_llm_calls: int+ ├── total_tokens: int+ ├── start_time: str+ └── plan_revisions: int+```++### 5.2 信息压缩层级++| 压缩级别 | 使用场景 | 保留内容 | 丢弃内容 |+|---------|---------|---------|---------|+| **L0 完整** | step_history(SolverAgent 当前步骤) | 全部字段 | 无 |+| **L1 结构化** | build_writer_context 正常模式 | plan + action + observation + self_note | thought |+| **L2 摘要** | previous_knowledge 正常模式 | step_goal + self_note 拼接 | observation, thought, action_input |+| **L3 极简** | previous_knowledge 超预算 / writer_context 超预算 | self_note 管道分隔 | 其余全部 |++### 5.3 Token 预算++| 场景 | 预算 | 来源 |+|------|------|------|+| `build_solver_context` | 6,000 tokens | 硬编码默认值 |+| `build_writer_context` | 12,000 tokens | 硬编码默认值 |+| observation 截断 | `obs_max * 4` 字符 ≈ 2,000 × 4 = 8,000 字符 | config `solve.observation_max_tokens` |++---++## 6. 外部上下文来源++### 6.1 工具返回 (observation)++| 工具 | 返回格式 | 最大长度 | 附带 Source |+|------|---------|---------|------------|+| `rag_search` | RAG answer 文本 | `obs_max * 4` 字符 | Source(type="rag", file=kb_name, chunk_id=query[:50]) |+| `web_search` | Web answer 文本 | `obs_max * 4` 字符 | Source(type="web", url=..., file=title) × 最多 5 个 |+| `code_execute` | `Code:\n```python\n{code}\n```\n\n{stdout/stderr/artifacts}` | `obs_max * 4` 字符 (output 部分) | Source(type="code", file=artifact_name) |++### 6.2 个性化 (Personalization)++| 注入点 | 内容 | 条件 |+|--------|------|------|+| WriterAgent.process() → `{preference}` | `MemoryReader.get_writer_context()` | reflection + weakness 摘要;服务可用时 |+| PlannerAgent — **未注入** | — | — |+| SolverAgent — **未注入** | — | — |+| WriterAgent Iterative — **未注入** | — | — |++### 6.3 配置参数 (agents.yaml)++| 参数 | 值 | 影响 |+|------|-----|------|+| `solve.temperature` | 0.3 | 所有 3 个 Agent 共用 |+| `solve.max_tokens` | 8192 | 所有 3 个 Agent 共用(Writer 调用时覆盖为 8192 / 1024) |++---++## 7. 完整信息流图++```+用户问题 (question)+ │+ ▼+┌─────────────────────────────────────────────────┐+│ PlannerAgent │+│ │+│ system: 静态角色 prompt │+│ user: question │+│ + tools_description (静态) │+│ + scratchpad_summary (首次为空/replan时有) │+│ │+│ 输出: Plan { analysis, steps[] } │+└───────────────────┬─────────────────────────────┘+ │ 写入 Scratchpad.plan+ ▼+┌─────────────────────────────────────────────────┐+│ SolverAgent (循环: 每步骤 × 每轮) │+│ │+│ system: 静态角色 prompt │+│ user: question (每轮重复) │+│ + plan (每轮重复, 含状态标记) │+│ + current_step (当前步骤目标) │+│ + step_history (当前步骤完整历史, L0) │+│ + previous_knowledge (已完成步骤摘要, L2) │+│ │+│ 输出: { thought, action, action_input, self_note }│+│ │ │+│ ├─ action=rag_search → _tool_rag() │+│ ├─ action=web_search → _tool_web() │+│ ├─ action=code_execute → _generate_code() │+│ │ → run_code() │+│ ├─ action=done → 标记步骤完成 │+│ └─ action=replan → 回到 PlannerAgent │+│ │+│ observation + sources → 写入 Scratchpad.entries │+└───────────────────┬─────────────────────────────┘+ │+ ▼+┌─────────────────────────────────────────────────┐+│ WriterAgent │+│ │+│ [Simple 模式] │+│ system: 格式规则 prompt │+│ user: question │+│ + scratchpad_content (L1, 预算12k) │+│ + sources (引用列表) │+│ + preference (个性化, 可为空) │+│ + language │+│ │+│ [Iterative 模式] │+│ Draft × N: │+│ system: 增量写作 prompt │+│ user: question + previous_draft + new_evidence│+│ + sources + language │+│ Concise × 1: │+│ system: 简洁回答 prompt │+│ user: question + detailed_answer + language │+│ │+│ 输出: final_answer (Markdown) │+└─────────────────────────────────────────────────┘+```++---++## 8. 关键问题与改进方向++### 8.1 上下文冗余++| 问题 | 位置 | 影响 |+|------|------|------|+| question 在 SolverAgent 每轮调用中完整重复 | solver_agent user_prompt | 浪费 tokens,尤其问题很长时 |+| plan 在 SolverAgent 每轮调用中完整重复 | solver_agent user_prompt | 步骤多时占用可观 |+| sources 在 Writer Iterative 每轮重复 | _write_draft user_prompt | 引用列表持续膨胀 |+| system_prompt 每次调用完整传入 | 所有 Agent | 协议限制,但可考虑缩短 |++### 8.2 上下文缺失++| 缺失 | 影响 | 严重度 |+|------|------|--------|+| **Code Generation 缺乏上下文** | 代码生成仅凭 action_input,不知道问题背景和已有知识 | 🔴 高 |+| **Planner 无 KB 元信息** | 不知道知识库中有什么,可能规划不切实际的步骤 | 🟡 中 |+| **Planner 无个性化偏好** | 规划不考虑用户偏好的难度/风格 | 🟡 中 |+| **Writer Iterative 无个性化** | 仅 Simple 模式注入 preference,Iterative 模式遗漏 | 🟡 中 |+| **无多轮对话历史** | 追问场景下无法理解上下文 | 🟡 中(取决于场景) |+| **Solver 无 observation 质量反馈** | 不知道 RAG 返回的是高质量精确匹配还是模糊泛化 | 🟢 低 |++### 8.3 压缩策略风险++| 风险 | 位置 | 说明 |+|------|------|------|+| **step_history 无上限** | `build_solver_context` | 当前步骤 observation 完整保留,多轮后可能超出窗口 |+| **Iterative draft 持续增长** | `_write_draft` | previous_draft 只增不减,后期可能超出模型上下文窗口 |+| **压缩粒度粗** | `build_writer_context` | 超预算时前 N-2 步直接丢弃 observation,可能丢失关键信息 |+| **token 估算不精确** | `_estimate_tokens` | tiktoken 不可用时退化为 `len/4`,非英语文本误差大 |++### 8.4 self_note 作为压缩中枢++`self_note` 是整个系统**唯一的跨步骤信息传递机制**(从 SolverAgent 到 PlannerAgent-replan、后续 SolverAgent 步骤)。其质量直接决定:+- PlannerAgent 是否能做出正确的 replan 决策+- 后续步骤的 SolverAgent 是否有足够的先验知识+- 信息在多步推理中的保真度++当前 self_note 由 SolverAgent 自行在每轮末尾生成(1 句话),**没有质量验证或格式约束**。++---++## 9. Token 消耗估算(典型场景)++假设:3 步计划,每步平均 2 轮 ReAct,每个 observation ≈ 1500 tokens++| 调用 | system | user | 合计估算 |+|------|--------|------|---------|+| Planner (首次) | ~300 | ~200 (Q) + ~100 (tools) + ~50 (empty progress) = ~350 | ~650 |+| Solver S1 R1 | ~400 | ~200 (Q) + ~150 (plan) + ~50 (step) + ~50 (no history) + ~50 (no prev) = ~500 | ~900 |+| Solver S1 R2 | ~400 | ~200 + ~150 + ~50 + ~1600 (R1 full obs) + ~50 = ~2050 | ~2450 |+| Solver S2 R1 | ~400 | ~200 + ~150 + ~50 + ~50 (no history) + ~100 (S1 notes) = ~550 | ~950 |+| Solver S2 R2 | ~400 | ~200 + ~150 + ~50 + ~1600 + ~100 = ~2100 | ~2500 |+| Solver S3 R1 | ~400 | ~200 + ~150 + ~50 + ~50 + ~200 (S1+S2 notes) = ~650 | ~1050 |+| Solver S3 R2 | ~400 | ~200 + ~150 + ~50 + ~1600 + ~200 = ~2200 | ~2600 |+| CodeGen (如有) | ~50 | ~100 | ~150 |+| Writer (Simple) | ~300 | ~200 + ~5000 (writer_context) + ~200 (sources) + ~100 (pref) = ~5500 | ~5800 |++**总输入约:~17,000 tokens**(不含 LLM 输出 tokens)++---++*最后更新:2026-02-10*diff --git a/src/agents/solve/main_solver.py b/src/agents/solve/main_solver.pyindex 75243190c..1e946b4a9 100644--- a/src/agents/solve/main_solver.py+++ b/src/agents/solve/main_solver.py@@ -1,48 +1,35 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-Main Solver - Problem-Solving System Controller+MainSolver — Plan -> ReAct -> Write pipeline controller.-Based on Dual-Loop Architecture: Analysis Loop + Solve Loop+External interface (preserved for API compatibility):+ solver = MainSolver(kb_name=..., ...)+ await solver.ainit()+ result = await solver.solve(question)"""+from __future__ import annotations+import asyncio-from datetime import datetimeimport jsonimport os-from pathlib import Pathimport traceback+from datetime import datetime+from pathlib import Pathfrom typing import Anyimport yamlfrom ...services.config import parse_languagefrom ...services.path_service import get_path_service-from .analysis_loop import InvestigateAgent, NoteAgent--# Dual-Loop Architecture-from .memory import (- CitationMemory,- InvestigateMemory,- SolveMemory,- SolveOutput,-)-from .solve_loop import (- ManagerAgent,- PrecisionAnswerAgent,- ResponseAgent,- SolveAgent,- SolveNoteAgent,- ToolAgent,-)-from .utils import ConfigValidator, PerformanceMonitor, SolveAgentLogger+from .agents import PlannerAgent, SolverAgent, WriterAgent+from .memory import Scratchpad, Source+from .tools import ToolRegistryfrom .utils.display_manager import get_display_managerfrom .utils.token_tracker import TokenTrackerclass MainSolver:- """Problem-Solving System Controller"""+ """Problem-Solving System Controller — Plan -> ReAct -> Write."""def __init__(self,@@ -50,1060 +37,772 @@ class MainSolver:api_key: str | None = None,base_url: str | None = None,api_version: str | None = None,+ model: str | None = None,language: str | None = None,- kb_name: str = "ai_textbook",+ kb_name: str = "ai-textbook",output_base_dir: str | None = None,- ):- """- Initialize MainSolver with lightweight setup.- Call ainit() to complete async initialization.-- Args:- config_path: Config file path (default: config.yaml in current directory)- api_key: API key (if not provided, read from environment)- base_url: API URL (if not provided, read from environment)- api_version: API version (if not provided, read from environment)- language: Preferred language for prompts ("en"/"zh"/"cn")- kb_name: Knowledge base name- output_base_dir: Output base directory (optional, overrides config)- """- # Store initialization parameters+ tool_registry: ToolRegistry | None = None,+ disable_memory: bool = False,+ disable_planner_retrieve: bool = False,+ max_tokens: int | None = None,+ temperature: float | None = None,+ ) -> None:+ # Store init params for ainit()self._config_path = config_pathself._api_key = api_keyself._base_url = base_urlself._api_version = api_version+ self._model = modelself._language = languageself._kb_name = kb_nameself._output_base_dir = output_base_dir-- # Initialize with None - will be set in ainit()- self.config = None- self.api_key = None- self.base_url = None- self.api_version = None+ self._external_tool_registry = tool_registry+ self.disable_memory = disable_memory+ self.disable_planner_retrieve = disable_planner_retrieve+ self._max_tokens_override = max_tokens+ self._temperature_override = temperature++ # Will be set in ainit()+ self.config: dict[str, Any] = {}+ self.api_key: str | None = None+ self.base_url: str | None = None+ self.api_version: str | None = Noneself.kb_name = kb_name- self.logger = None- self.monitor = None- self.token_tracker = None+ self.logger: Any = None+ self.token_tracker: TokenTracker | None = None++ # Agents (set in ainit)+ self.planner_agent: PlannerAgent | None = None+ self.solver_agent: SolverAgent | None = None+ self.writer_agent: WriterAgent | None = None++ # ------------------------------------------------------------------+ # Async initialisation+ # ------------------------------------------------------------------async def ainit(self) -> None:- """- Complete the asynchronous second phase of MainSolver initialization.-- This class uses a two-phase initialization pattern:-- 1. ``__init__`` performs only lightweight, synchronous setup and stores- constructor arguments. Attributes such as ``config``, ``api_key``,- ``base_url``, ``api_version``, ``logger``, ``monitor``, and- ``token_tracker`` are intentionally left as ``None``.- 2. :meth:`ainit` performs all I/O-bound and asynchronous work required to- make the instance fully usable (e.g., loading configuration, wiring up- logging/monitoring, and preparing external-service clients).-- You **must** call and await this method exactly once after constructing- ``MainSolver`` and **before** invoking any other methods that rely on- configuration, logging, metrics, or API access. Using the object prior- to calling :meth:`ainit` may result in attributes still being ``None``,- which can lead to confusing runtime errors such as ``AttributeError``,- misconfigured API calls, missing logs/metrics, or incorrect output paths.-- This async initialization pattern is used instead of performing all setup- in ``__init__`` so that object construction remains fast and synchronous,- while allowing potentially slow operations (disk I/O, network requests,- validation) to be awaited explicitly by the caller in an async context.- """+ """Complete async initialisation: config, logger, agents."""+ await self._load_config()+ self._init_logging()+ self._init_agents()+ self.logger.success("Solver ready (Plan -> ReAct -> Write)")++ async def _load_config(self) -> None:+ """Load configuration from main.yaml or custom path."""config_path = self._config_path- api_key = self._api_key- base_url = self._base_url- api_version = self._api_version- kb_name = self._kb_name- output_base_dir = self._output_base_dirlanguage = self._language+ output_base_dir = self._output_base_dir- # Load config from config directory (main.yaml unified config)if config_path is None:project_root = Path(__file__).parent.parent.parent.parent- # Load main.yaml (solve_config.yaml is optional and will be merged if exists)from ...services.config.loader import load_config_with_main_asyncfull_config = await load_config_with_main_async("main.yaml", project_root)-- # Extract solve-specific config and build validator-compatible structuresolve_config = full_config.get("solve", {})paths_config = full_config.get("paths", {})-- # Build config structure expected by ConfigValidatorpath_service = get_path_service()default_solve_dir = str(path_service.get_solve_dir())+self.config = {"system": {"output_base_dir": paths_config.get("solve_output_dir", default_solve_dir),- "save_intermediate_results": solve_config.get(- "save_intermediate_results", True- ),+ "save_intermediate_results": solve_config.get("save_intermediate_results", True),"language": full_config.get("system", {}).get("language", "en"),},- "agents": solve_config.get("agents", {}),"logging": full_config.get("logging", {}),"tools": full_config.get("tools", {}),"paths": paths_config,- # Keep solve-specific settings accessible"solve": solve_config,}else:- # If custom config path provided, load it directly (for backward compatibility)- local_config = {}+ local_config: dict[str, Any] = {}if Path(config_path).exists():try:-- def load_local_config(path: str) -> dict:- with open(path, encoding="utf-8") as f:+ def _load(p: str) -> dict:+ with open(p, encoding="utf-8") as f:return yaml.safe_load(f) or {}-- local_config = await asyncio.to_thread(load_local_config, config_path)+ local_config = await asyncio.to_thread(_load, config_path)except Exception:- # Config loading warning will be handled by config_loaderpassself.config = local_config if isinstance(local_config, dict) else {}- if self.config is None or not isinstance(self.config, dict):+ if not isinstance(self.config, dict):self.config = {}- # Override system language from UI if provided+ # Override language from UIif language:self.config.setdefault("system", {})self.config["system"]["language"] = parse_language(language)- # Override output directory config+ # Override output dirif output_base_dir:- if "system" not in self.config:- self.config["system"] = {}+ self.config.setdefault("system", {})self.config["system"]["output_base_dir"] = str(output_base_dir)- # Note: log_dir and performance_log_dir are now in paths section from main.yaml- # Only override if explicitly needed-- # Validate config- validator = ConfigValidator()- is_valid, errors, warnings = validator.validate(self.config)- if not is_valid:- raise ValueError(f"Config validation failed: {errors}")+ # Load LLM credentials+ api_key = self._api_key+ base_url = self._base_url+ api_version = self._api_version- # API config- if api_key is None or base_url is None or "llm" not in self.config:+ if api_key is None or base_url is None:try:from ...services.llm.config import get_llm_config_asyncllm_config = await get_llm_config_async()- if api_key is None:- api_key = llm_config.api_key- if base_url is None:- base_url = llm_config.base_url- if api_version is None:- api_version = getattr(llm_config, "api_version", None)+ api_key = api_key or llm_config.api_key+ base_url = base_url or llm_config.base_url+ api_version = api_version or getattr(llm_config, "api_version", None)+ except ValueError as exc:+ raise ValueError(f"LLM config error: {exc}") from exc- # Ensure LLM config is populated in self.config for agents- if "llm" not in self.config:- self.config["llm"] = {}-- # Update config with complete details (binding, model, etc.)- from dataclasses import asdict-- self.config["llm"].update(asdict(llm_config))-- except ValueError as e:- raise ValueError(f"LLM config error: {e!s}")-- # Check if API key is required- # Local LLM servers (Ollama, LM Studio, etc.) don't need API keysfrom src.services.llm import is_local_llm_serverif not api_key and not is_local_llm_server(base_url):- raise ValueError("API key not set. Provide api_key param or set LLM_API_KEY in .env")-- # For local servers, use a placeholder key if none provided+ raise ValueError("API key not set. Provide api_key or set LLM_API_KEY in .env")if not api_key and is_local_llm_server(base_url):api_key = "sk-no-key-required"self.api_key = api_keyself.base_url = base_urlself.api_version = api_version- self.kb_name = kb_name+ self.kb_name = self._kb_name++ def _init_logging(self) -> None:+ """Initialise logger, display manager, and token tracker."""+ from src.logging import Logger- # Initialize logging systemlogging_config = self.config.get("logging", {})- # Get log_dir from paths (user_log_dir from main.yaml) or logging configlog_dir = (self.config.get("paths", {}).get("user_log_dir")- or self.config.get("paths", {}).get("log_dir")or logging_config.get("log_dir"))- self.logger = SolveAgentLogger(++ self.logger = Logger(name="Solver",level=logging_config.get("level", "INFO"),log_dir=log_dir,console_output=logging_config.get("console_output", True),file_output=logging_config.get("save_to_file", True),)-- # Attach display manager for TUI and frontend status updatesself.logger.display_manager = get_display_manager()- # Initialize performance monitor (disabled by default - performance logging is deprecated)- monitoring_config = self.config.get("monitoring", {})- # Disable performance monitor by default to avoid creating performance directory- self.monitor = PerformanceMonitor(- enabled=False,- save_dir=None, # Disabled - performance logging is deprecated- )-- # Initialize Token trackerself.token_tracker = TokenTracker(prefer_tiktoken=True)-- # Connect token_tracker to display_manager for real-time updatesif self.logger.display_manager:self.token_tracker.set_on_usage_added_callback(self.logger.display_manager.update_token_stats)- self.logger.section("Dual-Loop Solver Initializing")- self.logger.info(f"Knowledge Base: {kb_name}")-- # Initialize Agents- self._init_agents()-- self.logger.success("Solver ready")-- def _deep_merge(self, base: dict, update: dict) -> dict:- """Deep merge two dictionaries"""- if base is None:- base = {}- if update is None:- update = {}+ self.logger.section("Solver Initialising (Plan -> ReAct -> Write)")+ self.logger.info(f"Knowledge Base: {self.kb_name}")- result = base.copy() if base else {}- for key, value in update.items():- if key in result and isinstance(result[key], dict) and isinstance(value, dict):- result[key] = self._deep_merge(result[key], value)- else:- result[key] = value- return result-- def _init_agents(self):- """Initialize all Agents - Dual-Loop Architecture"""- self.logger.progress("Initializing agents...")-- # Analysis Loop Agents- self.investigate_agent = InvestigateAgent(- config=self.config,- api_key=self.api_key,- base_url=self.base_url,- api_version=self.api_version,- token_tracker=self.token_tracker,+ def _init_agents(self) -> None:+ """Create the three agents."""+ lang = parse_language(self.config.get("system", {}).get("language", "en"))+ self.tool_registry = (+ self._external_tool_registry+ or ToolRegistry.create_default(language=lang))- self.logger.info(" InvestigateAgent initialized")-- self.note_agent = NoteAgent(+ common = dict(config=self.config,api_key=self.api_key,base_url=self.base_url,api_version=self.api_version,+ model=self._model,token_tracker=self.token_tracker,+ language=lang,+ )+ self.planner_agent = PlannerAgent(+ **common,+ tool_registry=self.tool_registry,+ enable_pre_retrieve=not self.disable_planner_retrieve,+ )+ self.solver_agent = SolverAgent(**common, tool_registry=self.tool_registry)+ self.writer_agent = WriterAgent(**common)++ # Apply per-run overrides from benchmark config (pipeline.max_tokens / pipeline.temperature)+ if self._max_tokens_override is not None or self._temperature_override is not None:+ for agent in (self.planner_agent, self.solver_agent, self.writer_agent):+ if self._max_tokens_override is not None:+ agent._agent_params["max_tokens"] = self._max_tokens_override+ if self._temperature_override is not None:+ agent._agent_params["temperature"] = self._temperature_override++ self.logger.info(+ f"Agents initialised (lang={lang}), tools registered: {self.tool_registry.tool_names}")- self.logger.info(" NoteAgent initialized")-- # Solve Loop Agents (lazy initialization)- self.manager_agent = None- self.solve_agent = None- self.tool_agent = None- self.response_agent = None- self.solve_note_agent = None- self.precision_answer_agent = None- self.logger.info(" Solve Loop agents (lazy init)")-- async def solve(self, question: str, verbose: bool = True) -> dict[str, Any]:- """- Main solving process - Dual-Loop Architecture++ # ------------------------------------------------------------------+ # Main entry point+ # ------------------------------------------------------------------++ async def solve(+ self,+ question: str,+ image_url: str | None = None,+ verbose: bool = True,+ detailed: bool | None = None,+ ) -> dict[str, Any]:+ """Run the full Plan -> ReAct -> Write pipeline.Args:- question: User question- verbose: Whether to print detailed info+ question: The user question to solve.+ image_url: Optional image URL for multimodal questions.+ verbose: Enable verbose logging.+ detailed: If True, use iterative detailed writing. If None, read from config.- Returns:- dict: Solving result+ Returns a dict compatible with the existing API contract."""- # Create output directory+ # Resolve detailed flag: explicit param > config > default False+ if detailed is None:+ detailed = self.config.get("solve", {}).get("detailed_answer", False)+ self._detailed = detailed+timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")path_service = get_path_service()- output_base_dir = self.config.get("system", {}).get("output_base_dir", str(path_service.get_solve_dir()))- output_dir = os.path.join(output_base_dir, f"solve_{timestamp}")+ output_base = self.config.get("system", {}).get(+ "output_base_dir", str(path_service.get_solve_dir())+ )+ output_dir = os.path.join(output_base, f"solve_{timestamp}")os.makedirs(output_dir, exist_ok=True)- # Add task log file handler- task_log_file = os.path.join(output_dir, "task.log")- self.logger.add_task_log_handler(task_log_file)+ # Task-level log file+ task_log = os.path.join(output_dir, "task.log")+ self.logger.add_task_log_handler(task_log)self.logger.section("Problem Solving Started")self.logger.info(f"Question: {question[:100]}{'...' if len(question) > 100 else ''}")self.logger.info(f"Output: {output_dir}")try:- # Execute dual-loop pipeline- result = await self._run_dual_loop_pipeline(question, output_dir)-- # Add metadata+ result = await self._run_pipeline(question, output_dir, image_url=image_url)result["metadata"] = {- "mode": "dual_loop",+ **result.get("metadata", {}),+ "mode": "plan_react_write","timestamp": timestamp,"output_dir": output_dir,}- # Save performance report- if self.config.get("monitoring", {}).get("enabled", True):- perf_report = self.monitor.generate_report()- perf_file = os.path.join(output_dir, "performance_report.json")- with open(perf_file, "w", encoding="utf-8") as f:- json.dump(perf_report, f, ensure_ascii=False, indent=2)- self.logger.debug(f"Performance report saved: {perf_file}")-- # Output cost report+ # Cost reportif self.token_tracker:- cost_summary = self.token_tracker.get_summary()- if cost_summary["total_calls"] > 0:- cost_text = self.token_tracker.format_summary()- self.logger.info(f"\n{cost_text}")-+ summary = self.token_tracker.get_summary()+ if summary["total_calls"] > 0:+ self.logger.info(f"\n{self.token_tracker.format_summary()}")cost_file = os.path.join(output_dir, "cost_report.json")self.token_tracker.save(cost_file)- self.logger.debug(f"Cost report saved: {cost_file}")-self.token_tracker.reset()self.logger.success("Problem solving completed")self.logger.remove_task_log_handlers()-return result- except Exception as e:- self.logger.error(f"Solving failed: {e!s}")+ except Exception as exc:+ self.logger.error(f"Solving failed: {exc}")self.logger.error(traceback.format_exc())self.logger.remove_task_log_handlers()raise-finally:if hasattr(self, "logger"):self.logger.shutdown()- async def _run_dual_loop_pipeline(self, question: str, output_dir: str) -> dict[str, Any]:- """- Dual-Loop Pipeline:- 1) Analysis Loop: Investigate → Note- 2) Solve Loop: Plan → Solve → Note → Format- """+ # ------------------------------------------------------------------+ # Pipeline+ # ------------------------------------------------------------------- self.logger.info("Pipeline: Analysis Loop → Solve Loop")+ async def _run_pipeline(+ self,+ question: str,+ output_dir: str,+ image_url: str | None = None,+ ) -> dict[str, Any]:+ solve_cfg = self.config.get("solve", {})+ max_react = solve_cfg.get("max_react_iterations", 5)+ max_replans = solve_cfg.get("max_replans", 2)- # ========== Analysis Loop ==========- self.logger.stage("Analysis Loop", "start", "Understanding the question")+ scratchpad = Scratchpad.load_or_create(output_dir, question)- investigate_memory = InvestigateMemory.load_or_create(- output_dir=output_dir, user_question=question- )+ # ============================================================+ # Phase 1: PLAN+ # ============================================================+ self.logger.stage("Phase 1", "start", "Planning")+ if self.logger.display_manager:+ self.logger.display_manager.set_agent_status("PlannerAgent", "running")+ if hasattr(self, "_send_progress_update"):+ self._send_progress_update("plan", {"status": "planning"})- citation_memory = CitationMemory.load_or_create(output_dir=output_dir)+ memory_ctx = ""+ if not self.disable_memory:+ memory_ctx = await self._get_planner_memory_context(question)- # Read max_iterations from solve.agents.investigate_agent config (authoritative source)- agent_config = self.config.get("solve", {}).get("agents", {}).get("investigate_agent", {})- max_analysis_iterations = agent_config.get("max_iterations", 5)- self.logger.log_stage_progress(- "AnalysisLoop", "start", f"max_iterations={max_analysis_iterations}"+ plan = await self.planner_agent.process(+ question=question,+ scratchpad=scratchpad,+ kb_name=self.kb_name,+ memory_context=memory_ctx,+ image_url=image_url,)+ scratchpad.set_plan(plan)+ scratchpad.save(output_dir)- analysis_completed = False+ if self.logger.display_manager:+ self.logger.display_manager.set_agent_status("PlannerAgent", "done")+ self.logger.info(f"Plan: {len(plan.steps)} steps — {plan.analysis[:80]}")+ for s in plan.steps:+ self.logger.info(f" [{s.id}] {s.goal}")+ self.logger.update_token_stats(self.token_tracker.get_summary())++ # ============================================================+ # Phase 2: SOLVE (ReAct loop per step)+ # ============================================================+ self.logger.stage("Phase 2", "start", "Solving")+ if self.logger.display_manager:+ self.logger.display_manager.set_agent_status("SolverAgent", "running")+ if hasattr(self, "_send_progress_update"):+ self._send_progress_update("solve", {"status": "starting"})++ replan_count = 0+ safety_limit = (len(plan.steps) + max_replans) * (max_react + 1)+ iterations = 0++ while not scratchpad.is_all_completed():+ iterations += 1+ if iterations > safety_limit:+ self.logger.warning("Safety iteration limit reached")+ break- # Analysis Loop iterations- for i in range(max_analysis_iterations):- self.logger.log_stage_progress("AnalysisLoop", "running", f"round={i + 1}")+ step = scratchpad.get_next_pending_step()+ if step is None:+ break- # 1. Investigate: Generate queries and call tools- with self.monitor.track(f"analysis_investigate_{i + 1}"):- investigate_result = await self.investigate_agent.process(+ scratchpad.mark_step_status(step.id, "in_progress")+ self.logger.info(f" Step {step.id}: {step.goal}")+ step_memory_context = ""+ if not self.disable_memory:+ step_memory_context = await self._get_solver_memory_context(step.goal)++ # Compute step index for progress reporting+ step_index = next(+ (i + 1 for i, s in enumerate(scratchpad.plan.steps) if s.id == step.id),+ 0,+ ) if scratchpad.plan else 0+ if hasattr(self, "_send_progress_update"):+ self._send_progress_update("solve", {+ "step_id": step.id,+ "step_index": step_index,+ "step_target": step.goal,+ })++ for round_num in range(max_react):+ decision = await self.solver_agent.process(question=question,- memory=investigate_memory,- citation_memory=citation_memory,- kb_name=self.kb_name,- output_dir=output_dir,- verbose=False,+ current_step=step,+ scratchpad=scratchpad,+ memory_context=step_memory_context,+ image_url=image_url,)- knowledge_ids: list[str] = investigate_result.get("knowledge_item_ids", [])- should_stop = investigate_result.get("should_stop", False)- reasoning = investigate_result.get("reasoning", "")- actions = investigate_result.get("actions", [])-- self.logger.debug(f" [Investigate] Reasoning: {reasoning or 'N/A'}")+ action = decision["action"]+ action_input = decision["action_input"]+ thought = decision["thought"]+ self_note = decision["self_note"]++ self.logger.info(f" Round {round_num + 1}: {action}({action_input[:60]}...)")+ self.logger.debug(f" Thought: {thought[:120]}")++ if action == "done":+ scratchpad.add_entry(+ step_id=step.id,+ round_num=round_num,+ thought=thought,+ action="done",+ action_input="",+ observation="",+ self_note=self_note,+ )+ scratchpad.mark_step_status(step.id, "completed")+ scratchpad.save(output_dir)+ self.logger.info(f" -> Step {step.id} completed")+ break- if hasattr(self, "_send_progress_update"):- queries = [action.get("query", "") for action in actions if action.get("query")]- self._send_progress_update("investigate", {"round": i + 1, "queries": queries})-- if actions:- for action in actions:- tool_label = action["tool_type"]- query = action.get("query") or ""- cite_id = action.get("cite_id")- suffix = f" → cite_id={cite_id}" if cite_id else ""- self.logger.info(f" Tool: {tool_label} | {query[:50]}{suffix}")- else:- self.logger.debug(" No queries generated this round")-- # 2. Note: Generate notes (if new knowledge exists)- if knowledge_ids:- self.logger.log_stage_progress("Note", "start")-- with self.monitor.track(f"analysis_note_{i + 1}"):- note_result = await self.note_agent.process(- question=question,- memory=investigate_memory,- new_knowledge_ids=knowledge_ids,- citation_memory=citation_memory,- output_dir=output_dir,- verbose=False,+ if action == "replan":+ replan_count += 1+ self.logger.info(f" -> Replan requested ({replan_count}/{max_replans}): {action_input[:80]}")+ # Record the replan entry+ scratchpad.add_entry(+ step_id=step.id,+ round_num=round_num,+ thought=thought,+ action="replan",+ action_input=action_input,+ observation="",+ self_note=self_note,)+ if replan_count <= max_replans:+ if self.logger.display_manager:+ self.logger.display_manager.set_agent_status("PlannerAgent", "running")+ replan_memory = ""+ if not self.disable_memory:+ replan_memory = await self._get_planner_memory_context(question)+ new_plan = await self.planner_agent.process(+ question=question,+ scratchpad=scratchpad,+ kb_name=self.kb_name,+ replan=True,+ memory_context=replan_memory,+ image_url=image_url,+ )+ scratchpad.update_plan(new_plan)+ scratchpad.save(output_dir)+ if self.logger.display_manager:+ self.logger.display_manager.set_agent_status("PlannerAgent", "done")+ self.logger.info(f" Plan revised: {len(new_plan.steps)} steps")+ else:+ self.logger.warning(" Max replans reached — marking step completed")+ scratchpad.mark_step_status(step.id, "completed")+ scratchpad.save(output_dir)+ break- if note_result.get("success"):- processed = note_result.get("processed_items", 0)- self.logger.info(f" Note: {processed} items processed")- self.logger.log_stage_progress("Note", "complete")- else:- self.logger.warning(f" Note failed: {note_result.get('reason', 'unknown')}")- self.logger.log_stage_progress("Note", "error")-- # Update Token stats- self.logger.update_token_stats(self.token_tracker.get_summary())-- # 3. Check stop condition- if should_stop:- analysis_completed = True- self.logger.log_stage_progress(- "AnalysisLoop",- "complete",- f"rounds={i + 1}, knowledge={len(investigate_memory.knowledge_chain)}",+ # Execute tool+ observation, sources = await self._execute_tool(+ action=action,+ action_input=action_input,+ output_dir=output_dir,+ question=question,+ scratchpad=scratchpad,)- break-- if not analysis_completed:- self.logger.log_stage_progress(- "AnalysisLoop",- "warning",- f"max_iterations({max_analysis_iterations}) reached, knowledge={len(investigate_memory.knowledge_chain)}",- )-- # Update investigate_memory metadata- investigate_memory.metadata["total_iterations"] = i + 1- investigate_memory.metadata["total_knowledge_items"] = len(- investigate_memory.knowledge_chain- )- investigate_memory.reflections.remaining_questions = []- if analysis_completed:- investigate_memory.metadata["coverage_rate"] = 1.0- investigate_memory.metadata["avg_confidence"] = 0.9- else:- coverage = min(- 1.0, len(investigate_memory.knowledge_chain) / max(1, max_analysis_iterations)- )- investigate_memory.metadata["coverage_rate"] = coverage- investigate_memory.metadata["avg_confidence"] = 0.6+ scratchpad.add_entry(+ step_id=step.id,+ round_num=round_num,+ thought=thought,+ action=action,+ action_input=action_input,+ observation=observation,+ self_note=self_note,+ sources=sources,+ )+ scratchpad.save(output_dir)+ self.logger.update_token_stats(self.token_tracker.get_summary())+ else:+ # Max rounds exhausted for this step+ self.logger.warning(f" Max ReAct iterations reached for {step.id}")+ scratchpad.mark_step_status(step.id, "completed")+ scratchpad.save(output_dir)- investigate_memory.save()+ if self.logger.display_manager:+ self.logger.display_manager.set_agent_status("SolverAgent", "done")++ completed = scratchpad.get_completed_steps()+ total = len(scratchpad.plan.steps) if scratchpad.plan else 0+ self.logger.info(f" Solve phase done: {len(completed)}/{total} steps completed")+ self.logger.update_token_stats(self.token_tracker.get_summary())++ # ============================================================+ # Phase 3: WRITE+ # ============================================================+ detailed = getattr(self, "_detailed", False)+ write_mode = "detailed iterative" if detailed else "simple"+ self.logger.stage("Phase 3", "start", f"Writing answer ({write_mode})")+ if self.logger.display_manager:+ self.logger.display_manager.set_agent_status("WriterAgent", "running")+ if hasattr(self, "_send_progress_update"):+ self._send_progress_update("write", {"status": "writing"})- # ========== Solve Loop ==========- self.logger.stage("Solve Loop", "start", "Generating solution")+ language = self.config.get("system", {}).get("language", "en")+ lang_code = parse_language(language)- solve_memory = SolveMemory.load_or_create(- output_dir=output_dir,- user_question=question,- )+ preference = "" if self.disable_memory else self._get_user_preference()- # Initialize Solve Loop Agents (if not yet initialized)- if self.manager_agent is None:- self.logger.progress("Initializing Solve Loop agents...")- self.manager_agent = ManagerAgent(- self.config,- self.api_key,- self.base_url,- api_version=self.api_version,- token_tracker=self.token_tracker,- )- self.solve_agent = SolveAgent(- self.config,- self.api_key,- self.base_url,- api_version=self.api_version,- token_tracker=self.token_tracker,- )- self.tool_agent = ToolAgent(- self.config,- self.api_key,- self.base_url,- api_version=self.api_version,- token_tracker=self.token_tracker,+ if detailed:+ final_answer = await self.writer_agent.process_iterative(+ question=question,+ scratchpad=scratchpad,+ language=lang_code,+ preference=preference,)- self.response_agent = ResponseAgent(- self.config,- self.api_key,- self.base_url,- api_version=self.api_version,- token_tracker=self.token_tracker,- )- self.solve_note_agent = SolveNoteAgent(- self.config,- self.api_key,- self.base_url,- api_version=self.api_version,- token_tracker=self.token_tracker,+ else:+ final_answer = await self.writer_agent.process(+ question=question,+ scratchpad=scratchpad,+ language=lang_code,+ preference=preference,)- precision_enabled = (- self.config.get("agents", {})- .get("precision_answer_agent", {})- .get("enabled", False)- )- if precision_enabled:- self.precision_answer_agent = PrecisionAnswerAgent(- self.config,- self.api_key,- self.base_url,- api_version=self.api_version,- token_tracker=self.token_tracker,- )+ if self.logger.display_manager:+ self.logger.display_manager.set_agent_status("WriterAgent", "done")- # 1. Plan: Generate todo-list- self.logger.info("Plan: Generating todo-list...")+ # Save final answer+ answer_file = Path(output_dir) / "final_answer.md"+ with open(answer_file, "w", encoding="utf-8") as f:+ f.write(final_answer)+ self.logger.success(f"Final answer saved: {answer_file}")+ self.logger.update_token_stats(self.token_tracker.get_summary())- plan_result = None- for attempt in range(2):- try:- with self.monitor.track(f"solve_plan_attempt_{attempt + 1}"):- plan_result = await self.manager_agent.process(- question=question,- investigate_memory=investigate_memory,- solve_memory=solve_memory,- verbose=(attempt > 0),- )- num_items = plan_result.get("num_todos") or plan_result.get("todos_count", 0)- self.logger.log_stage_progress("Plan", "complete", f"todos={num_items}")- self.logger.update_token_stats(self.token_tracker.get_summary())- break- except Exception as e:- if attempt == 0:- self.logger.error(f"ManagerAgent attempt {attempt + 1} failed: {e!s}")- self.logger.warning("Retrying plan generation...")- solve_memory = SolveMemory.load_or_create(- output_dir=output_dir,- user_question=question,- )- else:- self.logger.error(f"ManagerAgent attempt {attempt + 1} also failed")- raise ValueError(f"ManagerAgent failed after retry: {e!s}")+ if not self.disable_memory:+ await self._publish_event(question, final_answer, scratchpad, output_dir)- if plan_result is None:- raise ValueError("ManagerAgent failed to generate plan")+ return {+ "question": question,+ "output_dir": output_dir,+ "final_answer": final_answer,+ "output_md": str(answer_file),+ "output_json": str(Path(output_dir) / "scratchpad.json"),+ "formatted_solution": final_answer,+ "citations": [s["id"] for s in scratchpad.get_all_sources()],+ "pipeline": "plan_react_write",+ "total_steps": total,+ "completed_steps": len(completed),+ "total_react_entries": len(scratchpad.entries),+ "plan_revisions": scratchpad.metadata.get("plan_revisions", 0),+ "metadata": {+ "total_steps": total,+ "completed_steps": len(completed),+ "plan_revisions": scratchpad.metadata.get("plan_revisions", 0),+ },+ }- # 2. Solve-Note Loop- return await self._run_solve_loop(- question=question,- solve_memory=solve_memory,- investigate_memory=investigate_memory,- citation_memory=citation_memory,- output_dir=output_dir,- )+ # ------------------------------------------------------------------+ # Tool execution+ # ------------------------------------------------------------------- async def _run_solve_loop(+ async def _execute_tool(self,- question: str,- solve_memory: SolveMemory,- investigate_memory: InvestigateMemory,- citation_memory: CitationMemory,+ action: str,+ action_input: str,output_dir: str,- ) -> dict[str, Any]:- """- Execute the solve loop with the new architecture:-- Outer Loop (per todo):- Inner Loop (solve_agent iterates until tool_type == "none")- -> note_agent (update todo-list)- -> response_agent (generate step_response)- """- from .memory import IterationRecord, ToolCallRecord-- self.logger.info("Solve: Executing new iteration-based solve loop...")- max_outer_iterations = self.config.get("solve", {}).get("max_solve_iterations", 10)- max_inner_iterations = self.config.get("solve", {}).get("max_inner_iterations", 5)- total_todos = len(solve_memory.todo_list)-- self.logger.log_stage_progress(- "SolveLoop",- "start",- f"todos={total_todos}, max_outer={max_outer_iterations}",- )-- step_responses = []- accumulated_response = ""-- for outer_iter in range(max_outer_iterations):- # Check if all todos are completed- if solve_memory.is_all_completed():- self.logger.log_stage_progress(- "SolveLoop",- "complete",- f"All todos completed after {outer_iter} outer iterations",- )- break-- # Get next pending todo- current_todo = solve_memory.get_next_pending_todo()- if not current_todo:- self.logger.warning("No pending todo found, but not all completed")- break-- self.logger.info(f" Outer Iteration {outer_iter + 1}: {current_todo.todo_id}")- self.logger.log_stage_progress(- "SolveLoop", "running", f"outer={outer_iter + 1}, todo={current_todo.todo_id}"- )-- # Mark todo as in progress- solve_memory.mark_todo_in_progress(current_todo.todo_id)-- # Create iteration record- iteration_record = solve_memory.create_iteration(current_todo.todo_id)-- # ================================================================- # Inner Loop: solve_agent iterates until tool_type == "none"- # ================================================================- tool_call_history: list[ToolCallRecord] = []+ question: str = "",+ scratchpad: Scratchpad | None = None,+ ) -> tuple[str, list[Source]]:+ """Execute a tool and return (observation_text, sources)."""+ obs_max = self.config.get("solve", {}).get("observation_max_tokens", 2000)+ sources: list[Source] = []- for inner_iter in range(max_inner_iterations):- self.logger.info(f" Inner {inner_iter + 1}: Calling solve_agent...")-- with self.monitor.track(f"solve_inner_{outer_iter + 1}_{inner_iter + 1}"):- solve_result = await self.solve_agent.process(- current_todo=current_todo,- iteration_history=tool_call_history,- knowledge_chain=investigate_memory.knowledge_chain,- question=question,- verbose=False,- )-- tool_type = solve_result.get("tool_type", "none")- query = solve_result.get("query", "")-- self.logger.info(f" tool_type={tool_type}, query={query[:50]}...")-- # Check for termination- if tool_type == "none" or solve_result.get("should_stop"):- self.logger.info(f" Inner loop ended: {solve_result.get('reason', 'tool_type=none')}")- break-- # Execute the tool call- tool_record = await self._execute_single_tool_call(- tool_type=tool_type,- query=query,- iteration_record=iteration_record,- citation_memory=citation_memory,- output_dir=output_dir,+ try:+ if action == "rag_search":+ observation, sources = await self._tool_rag(action_input, obs_max)+ elif action == "web_search":+ observation, sources = await self._tool_web(action_input, output_dir, obs_max)+ elif action == "code_execute":+ observation, sources = await self._tool_code(action_input, obs_max, output_dir)+ elif action == "reason":+ observation, sources = await self._tool_reason(+ action_input, question, scratchpad, obs_max,)+ else:+ observation = f"Unknown action: {action}"+ except Exception as exc:+ observation = f"Tool error ({action}): {exc}"+ self.logger.warning(f" Tool error: {exc}")- if tool_record:- tool_call_history.append(tool_record)- iteration_record.append_tool_call(tool_record)+ return observation, sources- self.logger.update_token_stats(self.token_tracker.get_summary())+ async def _tool_rag(+ self, query: str, max_chars: int+ ) -> tuple[str, list[Source]]:+ from src.tools.rag_tool import rag_search- # ================================================================- # Note Agent: Update todo-list based on iteration results- # ================================================================- self.logger.info(f" Calling note_agent...")-- with self.monitor.track(f"note_{outer_iter + 1}"):- note_result = await self.solve_note_agent.process(- solve_memory=solve_memory,- iteration_record=iteration_record,- target_todo=current_todo,- verbose=False,- )+ result = await rag_search(+ query=query,+ kb_name=self.kb_name,+ mode="hybrid",+ top_k=8,+ )+ answer = result.get("answer", "") or result.get("content", "")+ observation = answer[:max_chars * 4] if answer else "(no results)"++ sources: list[Source] = []+ # Extract source from the answer metadata if available+ if answer:+ sources.append(Source(type="rag", file=self.kb_name, chunk_id=query[:50]))++ return observation, sources++ async def _tool_web(+ self, query: str, output_dir: str, max_chars: int+ ) -> tuple[str, list[Source]]:+ from src.tools.web_search import web_search++ result = await asyncio.to_thread(web_search, query=query, output_dir=output_dir)+ answer = result.get("answer", "")+ observation = answer[:max_chars * 4] if answer else "(no results)"++ sources: list[Source] = []+ for cit in result.get("citations", [])[:5]:+ sources.append(Source(+ type="web",+ url=cit.get("url", ""),+ file=cit.get("title", ""),+ ))- completed_todos = note_result.get("completed_todos", [])- if completed_todos:- self.logger.info(f" Completed: {completed_todos}")- if note_result.get("actions"):- for action in note_result["actions"]:- self.logger.info(f" Action: {action}")-- # ================================================================- # Fallback: If no tool calls and note_agent didn't mark complete,- # auto-complete the todo (solve_agent deemed info sufficient)- # ================================================================- if not tool_call_history and current_todo.todo_id not in completed_todos:- self.logger.info(- f" Auto-completing {current_todo.todo_id} (no tool calls needed)"- )- solve_memory.mark_todo_completed(- todo_id=current_todo.todo_id,- output_id="",- evidence="Completed using existing knowledge (no additional tools needed)",- )- completed_todos.append(current_todo.todo_id)- iteration_record.set_completed_todos(completed_todos)-- # ================================================================- # Response Agent: Generate step_response for completed todos- # ================================================================- if completed_todos:- self.logger.info(f" Calling response_agent...")-- # Get the completed TodoItem objects- completed_todo_items = [- solve_memory.get_todo(tid)- for tid in completed_todos- if solve_memory.get_todo(tid)- ]-- with self.monitor.track(f"response_{outer_iter + 1}"):- response_result = await self.response_agent.process(- question=question,- iteration_record=iteration_record,- completed_todos=completed_todo_items,- citation_memory=citation_memory,- knowledge_chain=investigate_memory.knowledge_chain,- output_dir=output_dir,- accumulated_response=accumulated_response,- verbose=False,- )+ return observation, sources- step_response = response_result.get("step_response", "")- if step_response:- step_responses.append(step_response)- accumulated_response = "\n\n".join(step_responses)- self.logger.info(f" Step response: {len(step_response)} chars")+ async def _tool_code(+ self, intent: str, max_chars: int, output_dir: str | None = None+ ) -> tuple[str, list[Source]]:+ """Generate Python code from intent, then execute it."""+ # Step 1: Generate code from the intent description+ code = await self._generate_code(intent)- # Save progress- solve_memory.save()- self.logger.update_token_stats(self.token_tracker.get_summary())+ # Step 2: Execute (all outputs go to run_code_workspace automatically)+ from src.tools.code_executor import run_code- else:- self.logger.warning(f"Max outer iterations ({max_outer_iterations}) reached")-- # ================================================================- # Finalize: Compile final answer- # ================================================================- completed_count = len(solve_memory.get_completed_todos())- self.logger.log_stage_progress(- "SolveLoop",- "complete",- f"completed={completed_count}/{total_todos}",+ result = await run_code(+ language="python",+ code=code,+ timeout=30,+ workspace_dir=(os.path.join(output_dir, "code_runs") if output_dir else None),)- # Save todo-list execution history- try:- history_file = solve_memory.save_todo_history(output_dir)- self.logger.info(f"Todo history saved: {history_file}")- except Exception as e:- self.logger.warning(f"Failed to save todo history: {e}")-- self.logger.info("Finalize: Compiling final answer...")- self.logger.log_stage_progress("Finalize", "start", "Compiling step responses")+ parts: list[str] = []+ if result.get("stdout"):+ parts.append(f"Output:\n{result['stdout']}")+ if result.get("stderr"):+ parts.append(f"Stderr:\n{result['stderr']}")+ if result.get("artifacts"):+ parts.append(f"Artifacts: {', '.join(result['artifacts'])}")+ if result.get("exit_code", 0) != 0:+ parts.append(f"Exit code: {result['exit_code']}")++ observation = "\n".join(parts)[:max_chars * 4] if parts else "(no output)"+ observation = f"Code:\n```python\n{code}\n```\n\n{observation}"++ sources: list[Source] = []+ for art in result.get("artifact_paths", []):+ sources.append(Source(type="code", file=Path(art).name))++ return observation, sources++ async def _generate_code(self, intent: str) -> str:+ """Use the LLM to generate Python code from a natural-language intent."""+ system = (+ "You are a Python code generator. Given a description of what to compute, "+ "output ONLY valid Python code (no markdown, no explanation). "+ "Use standard libraries (numpy, matplotlib, sympy, scipy) as needed. "+ "Print results to stdout. Save any plots to the current directory."+ )+ response = await self.solver_agent.call_llm(+ user_prompt=intent,+ system_prompt=system,+ stage="codegen",+ )+ # Strip markdown fences if present+ code = response.strip()+ if code.startswith("```"):+ lines = code.split("\n")+ lines = lines[1:] # Remove opening fence+ if lines and lines[-1].strip() == "```":+ lines = lines[:-1]+ code = "\n".join(lines)+ return code++ async def _tool_reason(+ self,+ query: str,+ question: str,+ scratchpad: Scratchpad | None,+ max_chars: int,+ ) -> tuple[str, list[Source]]:+ """Invoke the stateless deep-reasoning tool."""+ from src.tools.reason import reason++ # Build context from scratchpad so the reasoning LLM has background+ context_parts: list[str] = []+ if question:+ context_parts.append(f"Original question: {question}")+ if scratchpad:+ if scratchpad.plan:+ context_parts.append(f"Plan:\n{scratchpad._format_plan()}")+ # Summaries of completed steps+ completed = scratchpad.get_completed_steps()+ if completed:+ notes: list[str] = []+ for step in completed:+ entries = scratchpad.get_entries_for_step(step.id)+ step_notes = [e.self_note for e in entries if e.self_note]+ if step_notes:+ notes.append(f"[{step.id}] {step.goal}: {' '.join(step_notes)}")+ if notes:+ context_parts.append("Knowledge from previous steps:\n" + "\n".join(notes))++ context = "\n\n".join(context_parts)++ result = await reason(+ query=query,+ context=context,+ api_key=self.api_key,+ base_url=self.base_url,+ model=self.solver_agent.get_model(),+ )- # Compile step responses into final answer- final_answer = "\n\n".join(step_responses) if step_responses else ""+ observation = result.get("answer", "(no reasoning output)")+ return observation[:max_chars * 4], []- # Add citations section- used_cite_ids = solve_memory.get_all_iteration_citations()- language = self.config.get("system", {}).get("language", "zh")- lang_code = parse_language(language)- enable_citations = self.config.get("system", {}).get("enable_citations", True)+ # ------------------------------------------------------------------+ # Helpers+ # ------------------------------------------------------------------- citations_section = ""- if enable_citations and citation_memory and used_cite_ids:- citations_section = citation_memory.format_citations_markdown(- used_cite_ids=used_cite_ids, language=lang_code- )- if citations_section:- final_answer = f"{final_answer}\n\n---\n\n{citations_section}"+ def _get_user_preference(self) -> str:+ """Get personalisation preference (optional)."""+ from src.personalization.memory_reader import get_memory_reader_instance- self.logger.info(f" Final answer: {len(final_answer)} chars")- self.logger.info(f" Citations: {len(used_cite_ids)}")+ reader = get_memory_reader_instance()+ if reader:+ try:+ return reader.get_writer_context()+ except Exception:+ pass+ return ""- # Precision Answer (if enabled)- final_answer_content = final_answer.strip()- precision_answer_enabled = (- self.config.get("agents", {}).get("precision_answer_agent", {}).get("enabled", False)- )+ async def _get_planner_memory_context(self, question: str) -> str:+ from src.personalization.memory_reader import get_memory_reader_instance- if precision_answer_enabled and self.precision_answer_agent and final_answer_content:- self.logger.info("PrecisionAnswer: Generating concise answer...")- with self.monitor.track("precision_answer"):- precision_result = await self.precision_answer_agent.process(- question=question,- detailed_answer=final_answer_content,- verbose=False,- )- if precision_result.get("needs_precision"):- precision_answer = precision_result.get("precision_answer", "")- self.logger.info(f" Precision answer: {len(precision_answer)} chars")- final_answer_content = (- f"## Concise Answer\n\n{precision_answer}\n\n---\n\n"- f"## Detailed Answer\n\n{final_answer_content}"- )+ reader = get_memory_reader_instance()+ if not reader:+ return ""+ try:+ return await reader.get_planner_context(question)+ except Exception:+ return ""- # Save final answer- final_answer_file = Path(output_dir) / "final_answer.md"- with open(final_answer_file, "w", encoding="utf-8") as f:- f.write(final_answer_content)+ async def _get_solver_memory_context(self, step_goal: str) -> str:+ from src.personalization.memory_reader import get_memory_reader_instance- self.logger.success(f"Final answer saved: {final_answer_file}")- self.logger.log_stage_progress("Format", "complete", f"output={final_answer_file}")+ reader = get_memory_reader_instance()+ if not reader:+ return ""+ try:+ return await reader.get_solver_context(step_goal)+ except Exception:+ return ""- # Publish SOLVE_COMPLETE event for personalization+ async def _publish_event(+ self,+ question: str,+ answer: str,+ scratchpad: Scratchpad,+ output_dir: str,+ ) -> None:+ """Publish SOLVE_COMPLETE event for personalisation."""try:from src.core.event_bus import Event, EventType, get_event_bus- # Collect tools used during the solve process- tools_used = list(set(- tc.tool_type- for ir in solve_memory.iteration_records- for tc in ir.tool_calls- ))+ task_id = Path(output_dir).name+ tools_used = list({e.action for e in scratchpad.entries if e.action not in ("done", "replan")})event = Event(type=EventType.SOLVE_COMPLETE,task_id=task_id,user_input=question,- agent_output=final_answer_content[:2000], # Truncate for efficiency+ agent_output=answer[:2000],tools_used=tools_used,success=True,metadata={- "total_todos": total_todos,- "completed_todos": completed_count,- "citations_count": len(used_cite_ids),+ "total_steps": len(scratchpad.plan.steps) if scratchpad.plan else 0,+ "completed_steps": len(scratchpad.get_completed_steps()),+ "citations_count": len(scratchpad.get_all_sources()),+ "output_dir": output_dir,},)await get_event_bus().publish(event)self.logger.debug("Published SOLVE_COMPLETE event")- except Exception as e:- self.logger.debug(f"Failed to publish SOLVE_COMPLETE event: {e}")-- return {- "question": question,- "output_dir": output_dir,- "final_answer": final_answer_content,- "output_md": str(final_answer_file),- "output_json": str(Path(output_dir) / "solve_chain.json"),- "formatted_solution": final_answer_content,- "citations": used_cite_ids,- "pipeline": "iteration_mode",- "total_todos": total_todos,- "completed_todos": completed_count,- "total_iterations": len(solve_memory.iteration_records),- "total_step_responses": len(step_responses),- "analysis_iterations": investigate_memory.metadata.get("total_iterations", 0),- "metadata": {- "coverage_rate": investigate_memory.metadata.get("coverage_rate", 0.0),- "avg_confidence": investigate_memory.metadata.get("avg_confidence", 0.0),- "total_todos": total_todos,- "completed_todos": completed_count,- },- }-- async def _execute_single_tool_call(- self,- tool_type: str,- query: str,- iteration_record,- citation_memory: CitationMemory,- output_dir: str | None,- ):- """Execute a single tool call and return the ToolCallRecord"""- from .memory import ToolCallRecord-- base_dir = Path(output_dir).resolve() if output_dir else Path().resolve()- artifacts_dir = base_dir / "artifacts"- artifacts_dir.mkdir(parents=True, exist_ok=True)-- # Create citation- cite_id = citation_memory.add_citation(- tool_type=tool_type,- query=query,- raw_result="",- content="",- stage="solve",- step_id=iteration_record.iteration_id,- )-- # Create tool call record- record = ToolCallRecord(- tool_type=tool_type,- query=query,- cite_id=cite_id,- metadata={"kb_name": self.kb_name},- )-- try:- # Execute the tool call- raw_answer, metadata = await self.tool_agent._execute_single_call(- record=record,- kb_name=self.kb_name,- output_dir=output_dir,- artifacts_dir=str(artifacts_dir),- verbose=False,- )-- # Generate summary- summary = await self.tool_agent._summarize_tool_result(- tool_type=tool_type,- query=query,- raw_answer=raw_answer,- )-- # Update the record- record.mark_result(- raw_answer=raw_answer,- summary=summary,- status="success",- metadata=metadata,- )-- # Update citation- citation_memory.update_citation(- cite_id=cite_id,- raw_result=raw_answer,- content=summary,- metadata=metadata,- step_id=iteration_record.iteration_id,- )-- self.logger.info(f" Tool executed: {tool_type} -> {summary[:80]}...")-- except Exception as e:- error_msg = str(e)- record.mark_result(- raw_answer=error_msg,- summary=f"Error: {error_msg[:200]}",- status="failed",- metadata={"error": True},- )- self.logger.warning(f" Tool failed: {tool_type} -> {error_msg[:100]}")-- citation_memory.save()- return record-- async def _execute_output_tool_calls(- self,- output: SolveOutput,- solve_memory: SolveMemory,- citation_memory: CitationMemory,- output_dir: str | None,- ) -> dict[str, Any]:- """Execute tool calls for a SolveOutput"""-- # Get pending tool calls- pending_calls = [- call for call in output.tool_calls- if call.status in {"pending", "running"}- ]-- if not pending_calls:- return {"executed": [], "status": "idle"}-- logs = []- base_dir = Path(output_dir).resolve() if output_dir else Path().resolve()- artifacts_dir = base_dir / "artifacts"- artifacts_dir.mkdir(parents=True, exist_ok=True)-- for record in pending_calls:- import time- start_ts = time.time()- try:- # Execute the tool call using ToolAgent's internal method- raw_answer, metadata = await self.tool_agent._execute_single_call(- record=record,- kb_name=self.kb_name,- output_dir=output_dir,- artifacts_dir=str(artifacts_dir),- verbose=False,- )-- # Generate summary- summary = await self.tool_agent._summarize_tool_result(- tool_type=record.tool_type,- query=record.query,- raw_answer=raw_answer,- )-- # Update the record- record.mark_result(- raw_answer=raw_answer,- summary=summary,- status="success",- metadata=metadata,- )-- # Update citation- if record.cite_id:- citation_memory.update_citation(- cite_id=record.cite_id,- raw_result=raw_answer,- content=summary,- metadata=metadata,- step_id=output.output_id,- )-- logs.append({- "call_id": record.call_id,- "tool_type": record.tool_type,- "status": "success",- "summary": summary,- })-- except Exception as e:- error_msg = str(e)- record.mark_result(- raw_answer=error_msg,- summary=error_msg[:200],- status="failed",- metadata={"error": True},- )- logs.append({- "call_id": record.call_id,- "tool_type": record.tool_type,- "status": "failed",- "error": error_msg,- })-- # Update output content with tool results- if logs:- content_parts = []- for call in output.tool_calls:- if call.summary:- content_parts.append(call.summary)- if content_parts:- output.set_content("\n\n".join(content_parts))-- solve_memory.save()- citation_memory.save()-- return {"executed": logs, "status": "completed"}---if __name__ == "__main__":- from dotenv import load_dotenv-- load_dotenv()-- async def test():- solver = MainSolver(kb_name="ai_textbook")- result = await solver.solve(question="What is linear convolution?", verbose=True)- print(f"Output file: {result['output_md']}")-- asyncio.run(test())+ except Exception as exc:+ self.logger.debug(f"Failed to publish event: {exc}")diff --git a/src/agents/solve/memory/__init__.py b/src/agents/solve/memory/__init__.pyindex fb0067f6b..f696bd266 100644--- a/src/agents/solve/memory/__init__.py+++ b/src/agents/solve/memory/__init__.py@@ -1,46 +1,11 @@-#!/usr/bin/env python-"""-Memory System - Memory storage for solving process+"""Solve Agent Memory — unified Scratchpad."""-Provides implementations of InvestigateMemory and SolveMemory.-"""--from .citation_memory import (- CitationItem,- CitationMemory,-)-from .investigate_memory import (- InvestigateMemory,- KnowledgeItem,- Reflections,-)-from .solve_memory import (- # Core data structures- IterationRecord,- NoteAction,- SolveChainStep,- SolveMemory,- SolveOutput,- TodoItem,- ToolCallRecord,-)+from .scratchpad import Entry, Plan, PlanStep, Scratchpad, Source__all__ = [- # Investigate Memory- "InvestigateMemory",- "KnowledgeItem",- "Reflections",- # Solve Memory - Core- "SolveMemory",- "TodoItem",- "ToolCallRecord",- # Solve Memory - New iteration architecture- "IterationRecord",- "NoteAction",- # Solve Memory - Legacy/Backward compatibility- "SolveOutput",- "SolveChainStep",- # Citation Memory- "CitationMemory",- "CitationItem",+ "Scratchpad",+ "Plan",+ "PlanStep",+ "Entry",+ "Source",]diff --git a/src/agents/solve/memory/citation_memory.py b/src/agents/solve/memory/citation_memory.pydeleted file mode 100644index 3ffe2d3dd..000000000--- a/src/agents/solve/memory/citation_memory.py+++ /dev/null@@ -1,353 +0,0 @@-#!/usr/bin/env python-"""-CitationMemory - Global citation management system-Unified management of citation information generated by all tool calls-"""--from dataclasses import asdict, dataclass, field-from datetime import datetime-import json-from pathlib import Path-from typing import Any---@dataclass-class CitationItem:- """Citation item"""-- cite_id: str # Citation number, e.g., "[rag-1]"- tool_type: str # Tool type: rag_naive | rag_hybrid | web_search | query_item | code_execution- query: str # Query content- raw_result: str = "" # Raw tool return content (complete)- source: str = "" # Source information (if any)- content: str = "" # Citation content summary (usually summary)- stage: str = "solve" # Stage: analysis | solve- step_id: str | None = None # Belonging step (applicable to Solve stage)- metadata: dict[str, Any] = field(default_factory=dict) # Additional metadata- created_at: str = field(default_factory=lambda: datetime.now().isoformat())- updated_at: str = field(default_factory=lambda: datetime.now().isoformat())-- def to_dict(self) -> dict[str, Any]:- return asdict(self)-- @classmethod- def from_dict(cls, data: dict[str, Any]) -> "CitationItem":- # Compatible with old versions without stage/step_id/metadata fields- if "stage" not in data:- data["stage"] = "solve"- if "metadata" not in data:- data["metadata"] = {}- if "updated_at" not in data:- data["updated_at"] = data.get("created_at", datetime.now().isoformat())- return cls(**data)---class CitationMemory:- """Global citation management system"""-- def __init__(self, output_dir: str | None = None):- self.output_dir = output_dir- self.version = "1.1"- self.created_at = datetime.now().isoformat()- self.updated_at = datetime.now().isoformat()-- # Core data: citation list- self.citations: list[CitationItem] = []-- # Citation counter (incremented by tool prefix)- self.tool_counters: dict[str, int] = {}-- # File path- if output_dir:- self.file_path = Path(output_dir) / "citation_memory.json"- else:- self.file_path = None-- @classmethod- def load_or_create(cls, output_dir: str) -> "CitationMemory":- """Load existing citation memory or create new memory"""- file_path = Path(output_dir) / "citation_memory.json"-- if file_path.exists():- # Load existing memory- with open(file_path, encoding="utf-8") as f:- data = json.load(f)-- memory = cls(output_dir=output_dir)- memory.version = data.get("version", "1.1")- memory.created_at = data.get("created_at", memory.created_at)- memory.updated_at = data.get("updated_at", memory.updated_at)-- # Load citation list- citations_data = data.get("citations", [])- memory.citations = [CitationItem.from_dict(item) for item in citations_data]-- # Restore counters- memory.tool_counters = data.get("tool_counters", {})- if not memory.tool_counters:- # Compatible with old versions: guess from existing cite_id- for citation in memory.citations:- prefix = memory._get_tool_prefix(citation.tool_type)- number = memory._extract_counter_from_cite_id(citation.cite_id, prefix)- if number is not None:- memory.tool_counters[prefix] = max(- memory.tool_counters.get(prefix, 0), number- )-- return memory- # Create new memory- return cls(output_dir=output_dir)-- def add_citation(- self,- tool_type: str,- query: str,- raw_result: str = "",- source: str = "",- content: str = "",- stage: str = "solve",- step_id: str | None = None,- metadata: dict[str, Any] | None = None,- cite_id: str | None = None,- ) -> str:- """- Add new citation entry-- Args:- tool_type: Tool type- query: Query content- raw_result: Raw tool return content- source: Source information- content: Citation content summary-- Returns:- str: Newly generated or reused cite_id (e.g., "[rag-1]")- """- # If cite_id is provided and already exists, return directly- if cite_id and self.get_citation(cite_id):- return cite_id-- # Generate new cite_id- if not cite_id:- cite_id = self._generate_cite_id(tool_type)-- citation = CitationItem(- cite_id=cite_id,- tool_type=tool_type,- query=query,- raw_result=raw_result,- source=source,- content=content,- stage=stage,- step_id=step_id,- metadata=metadata or {},- )-- self.citations.append(citation)- self.updated_at = datetime.now().isoformat()-- return cite_id-- def get_citation(self, cite_id: str) -> CitationItem | None:- """Get citation entry by cite_id"""- for citation in self.citations:- if citation.cite_id == cite_id:- return citation- return None-- def get_all_citations(self) -> list[CitationItem]:- """Get all citation entries"""- return self.citations-- def get_citations_by_tool_type(self, tool_type: str) -> list[CitationItem]:- """Get citation entries by tool type"""- return [c for c in self.citations if c.tool_type == tool_type]-- def update_citation(- self,- cite_id: str,- raw_result: str | None = None,- source: str | None = None,- content: str | None = None,- metadata: dict[str, Any] | None = None,- stage: str | None = None,- step_id: str | None = None,- ):- """Update citation entry information"""- for citation in self.citations:- if citation.cite_id == cite_id:- if raw_result is not None:- citation.raw_result = raw_result- if source is not None:- citation.source = source- if content is not None:- citation.content = content- if metadata:- citation.metadata.update(metadata)- if stage:- citation.stage = stage- if step_id:- citation.step_id = step_id- citation.updated_at = datetime.now().isoformat()- self.updated_at = datetime.now().isoformat()- return- raise ValueError(f"cite_id not found: {cite_id}")-- def save(self):- """Save to JSON file"""- if not self.file_path:- raise ValueError("output_dir not set, cannot save")-- # Ensure directory exists- self.file_path.parent.mkdir(parents=True, exist_ok=True)-- self.updated_at = datetime.now().isoformat()-- # Convert to dictionary- data = self.to_dict()-- # Save to file- with open(self.file_path, "w", encoding="utf-8") as f:- json.dump(data, f, ensure_ascii=False, indent=2)-- def to_dict(self) -> dict[str, Any]:- """Convert to dictionary"""- return {- "version": self.version,- "created_at": self.created_at,- "updated_at": self.updated_at,- "citations": [item.to_dict() for item in self.citations],- "tool_counters": self.tool_counters,- }-- def format_citations_markdown(- self, used_cite_ids: list[str] | None = None, language: str = "zh"- ) -> str:- """- Format citation list as Markdown-- Args:- used_cite_ids: Optional, specify citation ID list to format. If provided, only format these citations; if not provided, format all citations.- language: Language code, 'zh' for Chinese, 'en' for English, default 'zh'-- Returns:- str: Markdown-formatted citation list- """- # Set text based on language- if language == "en":- no_citations_text = "(No citations)"- citation_title = "## Citations\n"- stage_label = "Stage"- source_label = "Source"- query_content_label = " - Query Content:"- citation_content_label = " - Citation Content:"- else:- no_citations_text = "(No citations)"- citation_title = "## Citations\n"- stage_label = "Stage"- source_label = "Source"- query_content_label = " - Query Content:"- citation_content_label = " - Citation Content:"-- if not self.citations:- return no_citations_text-- # If used_cite_ids is specified, only format these citations- citations_to_format = self.citations- if used_cite_ids is not None:- cite_id_set = set(used_cite_ids)- citations_to_format = [c for c in self.citations if c.cite_id in cite_id_set]- if not citations_to_format:- return no_citations_text-- lines = [citation_title]-- for citation in citations_to_format:- tool_type_display = {- "rag_naive": "RAG (Naive)",- "rag_hybrid": "RAG (Hybrid)",- "web_search": "Web Search",- "query_item": "Query Item",- "code_execution": "Code Execution",- }.get(citation.tool_type, citation.tool_type)-- line = f"- **{citation.cite_id}** [{tool_type_display}] {stage_label}: {citation.stage}"- if citation.source:- line += f" | {source_label}: {citation.source}"- lines.append(line)-- if citation.query:- query_block = self._format_block(- citation.query,- language="python" if citation.tool_type == "code_execution" else None,- )- lines.append(query_content_label)- lines.append(self._indent_block(query_block, " "))-- if citation.content:- content_block = self._format_block(- citation.content,- language="python" if citation.tool_type == "code_execution" else None,- force_block=True,- )- lines.append(citation_content_label)- lines.append(self._indent_block(content_block, " "))- elif citation.raw_result:- raw_block = self._format_block(- citation.raw_result,- language="python" if citation.tool_type == "code_execution" else None,- force_block=True,- )- lines.append(citation_content_label)- lines.append(self._indent_block(raw_block, " "))-- return "\n".join(lines)-- # ------------------------------------------------------------------- # Internal utility methods- # ------------------------------------------------------------------- def _get_tool_prefix(self, tool_type: str) -> str:- """Generate unified prefix based on tool type"""- prefix_map = {- "rag_naive": "rag",- "rag_hybrid": "rag",- "web_search": "web",- "code_execution": "code",- "query_item": "query",- }- normalized = prefix_map.get(tool_type, tool_type.replace("_", "-"))- return normalized.lower()-- def _generate_cite_id(self, tool_type: str) -> str:- prefix = self._get_tool_prefix(tool_type)- current = self.tool_counters.get(prefix, 0) + 1- self.tool_counters[prefix] = current- return f"[{prefix}-{current}]"-- @staticmethod- def _format_block(text: str, language: str | None = None, force_block: bool = False) -> str:- if not text:- return ""- clean = text.strip()- clean = clean.strip("`")- if force_block or "\n" in clean or len(clean) > 80:- lang = language or ""- return f"```{lang}\n{clean}\n```"- return f"`{clean}`"-- @staticmethod- def _indent_block(block: str, prefix: str) -> str:- if not block:- return ""- return "\n".join(prefix + line if line else prefix for line in block.splitlines())-- @staticmethod- def _extract_counter_from_cite_id(cite_id: str, prefix: str) -> int | None:- """Extract counter value from cite_id"""- try:- inner = cite_id.strip("[]")- if inner.startswith(f"{prefix}-"):- return int(inner.split("-", maxsplit=1)[1])- except (ValueError, IndexError):- return None- return Nonediff --git a/src/agents/solve/memory/investigate_memory.py b/src/agents/solve/memory/investigate_memory.pydeleted file mode 100644index 6284a02be..000000000--- a/src/agents/solve/memory/investigate_memory.py+++ /dev/null@@ -1,226 +0,0 @@-#!/usr/bin/env python-"""-InvestigateMemory - Analysis loop memory file system (Refactored: uses unified cite_id)-"""--from dataclasses import asdict, dataclass, field-from datetime import datetime-import json-from pathlib import Path-from typing import Any---@dataclass-class KnowledgeItem:- """Knowledge item (Refactored: uses cite_id)"""-- cite_id: str # Citation ID, corresponds to cite_id in CitationMemory- tool_type: str # rag_naive | rag_hybrid | web_search | query_item- query: str- raw_result: str # Raw tool return content (complete)- summary: str = "" # Summary generated by NoteAgent- created_at: str = field(default_factory=lambda: datetime.now().isoformat())- updated_at: str = field(default_factory=lambda: datetime.now().isoformat())-- def to_dict(self) -> dict[str, Any]:- return asdict(self)-- @classmethod- def from_dict(cls, data: dict[str, Any]) -> "KnowledgeItem":- # Backward compatibility: handle old version field names- if "knowledge_id" in data and "cite_id" not in data:- # Convert old knowledge_id to cite_id- data["cite_id"] = data.pop("knowledge_id")- if "source_type" in data and "tool_type" not in data:- data["tool_type"] = data.pop("source_type")- if "query_text" in data and "query" not in data:- data["query"] = data.pop("query_text")- if "answer_raw" in data and "raw_result" not in data:- data["raw_result"] = data.pop("answer_raw")- # Remove old citations field (now managed by CitationMemory)- if "citations" in data:- data.pop("citations")- return cls(**data)---@dataclass-class Reflections:- """Reflections"""-- remaining_questions: list[str] = field(- default_factory=list- ) # Questions still needing investigation- updated_at: str = field(default_factory=lambda: datetime.now().isoformat())-- def to_dict(self) -> dict[str, Any]:- return asdict(self)-- @classmethod- def from_dict(cls, data: dict[str, Any]) -> "Reflections":- return cls(**data)---class InvestigateMemory:- """Analysis loop memory management (Refactored: uses unified cite_id)"""-- def __init__(- self,- task_id: str | None = None,- user_question: str = "",- output_dir: str | None = None,- ):- self.task_id = task_id or f"investigate_{datetime.now().strftime('%Y%m%d_%H%M%S')}"- self.user_question = user_question- self.output_dir = output_dir-- self.version = "3.0" # New version- self.created_at = datetime.now().isoformat()- self.updated_at = datetime.now().isoformat()-- # Core data- self.knowledge_chain: list[KnowledgeItem] = []- self.reflections: Reflections = Reflections()-- # Metadata (for statistics and monitoring)- self.metadata: dict[str, Any] = {- "total_iterations": 0,- "coverage_rate": 0.0,- "avg_confidence": 0.0,- "total_knowledge_items": 0,- }-- # File path- if output_dir:- self.file_path = Path(output_dir) / "investigate_memory.json"- else:- self.file_path = None-- @classmethod- def load_or_create(- cls, output_dir: str, user_question: str = "", task_id: str | None = None- ) -> "InvestigateMemory":- """Load existing memory or create new memory (supports v1.0/v2.0 backward compatibility)"""- file_path = Path(output_dir) / "investigate_memory.json"-- if file_path.exists():- # Load existing memory- with open(file_path, encoding="utf-8") as f:- data = json.load(f)-- memory = cls(- task_id=data.get("task_id"),- user_question=data.get("user_question", user_question),- output_dir=output_dir,- )-- file_version = data.get("version", "1.0")- memory.version = "3.0" # Upgrade to new version- memory.created_at = data.get("created_at", memory.created_at)- memory.updated_at = data.get("updated_at", memory.updated_at)-- # Load knowledge chain (supports v1.0/v2.0 compatibility)- knowledge_chain_data = data.get("knowledge_chain", [])- memory.knowledge_chain = [- KnowledgeItem.from_dict(item) for item in knowledge_chain_data- ]-- # If v1.0, need to migrate data- if file_version == "1.0":- # Merge notes summary into knowledge_chain- notes_data = data.get("notes", [])- for note in notes_data:- related_knowledge_ids = note.get("related_knowledge_ids", [])-- # Prioritize using related_knowledge_ids- for knowledge_id in related_knowledge_ids:- for k_item in memory.knowledge_chain:- # Old version uses knowledge_id, new version uses cite_id- if k_item.cite_id == knowledge_id:- if not k_item.summary:- k_item.summary = note.get("summary", "")- break-- # Convert reflections to remaining_questions- reflections_data = data.get("reflections", [])- remaining_questions = []- for reflection in reflections_data:- action_items = reflection.get("action_items", [])- remaining_questions.extend(action_items)- gaps = reflection.get("gaps", [])- remaining_questions.extend(gaps)-- # Deduplicate- memory.reflections.remaining_questions = list(set(remaining_questions))- else:- # v2.0/v3.0 format- reflections_data = data.get("reflections", {})- if isinstance(reflections_data, dict):- memory.reflections = Reflections.from_dict(reflections_data)- else:- memory.reflections = Reflections()-- # Load metadata (if exists)- memory.metadata = data.get("metadata", memory.metadata)-- return memory- # Create new memory- return cls(task_id=task_id, user_question=user_question, output_dir=output_dir)-- def add_knowledge(self, item: KnowledgeItem):- """Add knowledge item"""- self.knowledge_chain.append(item)- self.updated_at = datetime.now().isoformat()-- def update_knowledge_summary(self, cite_id: str, summary: str):- """Update knowledge item summary (called by NoteAgent)"""- for item in self.knowledge_chain:- if item.cite_id == cite_id:- item.summary = summary- item.updated_at = datetime.now().isoformat()- self.updated_at = datetime.now().isoformat()- return- raise ValueError(f"cite_id not found: {cite_id}")-- def get_available_knowledge(- self, tool_types: list[str] | None = None, cite_ids: list[str] | None = None- ) -> list[KnowledgeItem]:- """Get available knowledge (supports filtering)"""- results = self.knowledge_chain-- if tool_types:- results = [k for k in results if k.tool_type in tool_types]-- if cite_ids:- results = [k for k in results if k.cite_id in cite_ids]-- return results-- def save(self):- """Save to JSON file"""- if not self.file_path:- raise ValueError("output_dir not set, cannot save")-- # Ensure directory exists- self.file_path.parent.mkdir(parents=True, exist_ok=True)-- self.updated_at = datetime.now().isoformat()-- # Convert to dictionary- data = self.to_dict()-- # Save to file- with open(self.file_path, "w", encoding="utf-8") as f:- json.dump(data, f, ensure_ascii=False, indent=2)-- def to_dict(self) -> dict[str, Any]:- """Convert to dictionary"""- return {- "version": self.version,- "task_id": self.task_id,- "user_question": self.user_question,- "created_at": self.created_at,- "updated_at": self.updated_at,- "knowledge_chain": [item.to_dict() for item in self.knowledge_chain],- "reflections": self.reflections.to_dict(),- "metadata": self.metadata,- }diff --git a/src/agents/solve/memory/scratchpad.py b/src/agents/solve/memory/scratchpad.pynew file mode 100644index 000000000..90428fa41--- /dev/null+++ b/src/agents/solve/memory/scratchpad.py@@ -0,0 +1,442 @@+"""+Scratchpad - Unified memory for the Plan -> ReAct -> Write pipeline.++Replaces InvestigateMemory + SolveMemory + CitationMemory with a single+linear data structure that tracks the plan, all ReAct iterations, and+sources for citation.+"""++from __future__ import annotations++import json+import os+from dataclasses import asdict, dataclass, field+from datetime import datetime+from pathlib import Path+from typing import Any++# Optional tiktoken for accurate token counting+try:+ import tiktoken++ _TIKTOKEN_AVAILABLE = True+except ImportError:+ _TIKTOKEN_AVAILABLE = False+++# ---------------------------------------------------------------------------+# Data classes+# ---------------------------------------------------------------------------+++@dataclass+class Source:+ """A citation source attached to a retrieval entry."""++ type: str # rag, web, code+ file: str | None = None+ page: int | None = None+ url: str | None = None+ chunk_id: str | None = None++ # ---------- serialisation helpers ----------+ def to_dict(self) -> dict[str, Any]:+ return {k: v for k, v in asdict(self).items() if v is not None}++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> Source:+ return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})+++@dataclass+class PlanStep:+ """One step in the plan produced by PlannerAgent."""++ id: str+ goal: str+ tools_hint: list[str] = field(default_factory=list)+ status: str = "pending" # pending | in_progress | completed | skipped++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> PlanStep:+ return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})+++@dataclass+class Plan:+ """High-level plan output by PlannerAgent."""++ analysis: str = ""+ steps: list[PlanStep] = field(default_factory=list)++ def to_dict(self) -> dict[str, Any]:+ return {+ "analysis": self.analysis,+ "steps": [s.to_dict() for s in self.steps],+ }++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> Plan:+ steps = [PlanStep.from_dict(s) for s in data.get("steps", [])]+ return cls(analysis=data.get("analysis", ""), steps=steps)+++@dataclass+class Entry:+ """One ReAct iteration entry."""++ step_id: str+ round: int+ thought: str = ""+ action: str = ""+ action_input: str = ""+ observation: str = ""+ self_note: str = ""+ sources: list[Source] = field(default_factory=list)+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())++ def to_dict(self) -> dict[str, Any]:+ d = asdict(self)+ d["sources"] = [s.to_dict() for s in self.sources]+ return d++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> Entry:+ sources = [Source.from_dict(s) for s in data.get("sources", [])]+ filtered = {k: v for k, v in data.items() if k in cls.__dataclass_fields__ and k != "sources"}+ return cls(sources=sources, **filtered)+++# ---------------------------------------------------------------------------+# Scratchpad+# ---------------------------------------------------------------------------+++class Scratchpad:+ """Unified memory: plan + ReAct entries + metadata."""++ VERSION = "1.0"+ FILENAME = "scratchpad.json"++ def __init__(self, question: str) -> None:+ self.question: str = question+ self.plan: Plan | None = None+ self.entries: list[Entry] = []+ self.metadata: dict[str, Any] = {+ "total_llm_calls": 0,+ "total_tokens": 0,+ "start_time": datetime.now().isoformat(),+ "plan_revisions": 0,+ }++ # ------------------------------------------------------------------+ # Plan management+ # ------------------------------------------------------------------++ def set_plan(self, plan: Plan) -> None:+ """Set the initial plan."""+ self.plan = plan++ def update_plan(self, new_plan: Plan) -> None:+ """Replan: keep completed steps from the old plan, replace the rest."""+ if self.plan is None:+ self.plan = new_plan+ return++ self.metadata["plan_revisions"] = self.metadata.get("plan_revisions", 0) + 1++ completed = [s for s in self.plan.steps if s.status == "completed"]+ completed_ids = {s.id for s in completed}++ # New steps = completed (preserved) + new pending steps (with fresh IDs)+ new_pending = [s for s in new_plan.steps if s.id not in completed_ids]+ self.plan.analysis = new_plan.analysis+ self.plan.steps = completed + new_pending++ # ------------------------------------------------------------------+ # Step status management+ # ------------------------------------------------------------------++ def mark_step_status(self, step_id: str, status: str) -> None:+ if self.plan is None:+ return+ for step in self.plan.steps:+ if step.id == step_id:+ step.status = status+ return++ def get_next_pending_step(self) -> PlanStep | None:+ if self.plan is None:+ return None+ for step in self.plan.steps:+ if step.status == "pending":+ return step+ return None++ def get_completed_steps(self) -> list[PlanStep]:+ if self.plan is None:+ return []+ return [s for s in self.plan.steps if s.status == "completed"]++ def is_all_completed(self) -> bool:+ if self.plan is None:+ return True+ return all(s.status in ("completed", "skipped") for s in self.plan.steps)++ # ------------------------------------------------------------------+ # Entry management+ # ------------------------------------------------------------------++ def add_entry(+ self,+ step_id: str,+ round_num: int,+ thought: str,+ action: str,+ action_input: str,+ observation: str,+ self_note: str,+ sources: list[Source] | None = None,+ ) -> Entry:+ entry = Entry(+ step_id=step_id,+ round=round_num,+ thought=thought,+ action=action,+ action_input=action_input,+ observation=observation,+ self_note=self_note,+ sources=sources or [],+ )+ self.entries.append(entry)+ return entry++ def get_entries_for_step(self, step_id: str) -> list[Entry]:+ return [e for e in self.entries if e.step_id == step_id]++ # ------------------------------------------------------------------+ # Context builders (for prompt construction with compression)+ # ------------------------------------------------------------------++ def build_solver_context(+ self,+ current_step_id: str,+ max_tokens: int = 6000,+ ) -> dict[str, str]:+ """Build compressed context for SolverAgent prompt.++ Returns dict with keys: plan, current_step, step_history, previous_knowledge+ """+ # Plan summary+ plan_text = self._format_plan()++ # Current step description+ current_step_text = ""+ if self.plan:+ for s in self.plan.steps:+ if s.id == current_step_id:+ current_step_text = f"[{s.id}] {s.goal}"+ break++ # Step history (current step entries – full observations)+ current_entries = self.get_entries_for_step(current_step_id)+ step_history_parts: list[str] = []+ for e in current_entries:+ step_history_parts.append(+ f"Round {e.round}:\n"+ f" Thought: {e.thought}\n"+ f" Action: {e.action}({e.action_input})\n"+ f" Observation: {e.observation}\n"+ f" Note: {e.self_note}"+ )+ step_history = "\n\n".join(step_history_parts) if step_history_parts else "(no actions yet)"++ # Tool usage stats for the current step — helps the agent detect+ # repeated calls to the same tool and consider switching strategy.+ tool_actions = [e.action for e in current_entries if e.action not in ("done", "replan", "")]+ if tool_actions:+ from collections import Counter+ counts = Counter(tool_actions)+ stats = ", ".join(f"{tool} ×{n}" for tool, n in counts.most_common())+ step_history += f"\n\n[Tool usage this step: {stats}]"++ # Previous knowledge from completed steps (compressed)+ previous_parts: list[str] = []+ if self.plan:+ completed_ids = [s.id for s in self.plan.steps if s.status == "completed"]+ for sid in completed_ids:+ entries = self.get_entries_for_step(sid)+ step_obj = next((s for s in self.plan.steps if s.id == sid), None)+ goal_text = step_obj.goal if step_obj else sid+ notes = [e.self_note for e in entries if e.self_note]+ if notes:+ previous_parts.append(f"[{sid}] {goal_text}: {' '.join(notes)}")++ previous_knowledge = "\n".join(previous_parts) if previous_parts else "(no previous steps completed)"++ # Token budget check – if over budget, aggressively compress previous_knowledge+ total = self._estimate_tokens(plan_text + current_step_text + step_history + previous_knowledge)+ if total > max_tokens and previous_parts:+ # Keep only self_notes, one line each+ compressed = []+ for sid in completed_ids:+ entries = self.get_entries_for_step(sid)+ notes = " | ".join(e.self_note for e in entries if e.self_note)+ if notes:+ compressed.append(f"[{sid}]: {notes}")+ previous_knowledge = "\n".join(compressed) if compressed else "(compressed)"++ return {+ "plan": plan_text,+ "current_step": current_step_text,+ "step_history": step_history,+ "previous_knowledge": previous_knowledge,+ }++ def build_writer_context(self, max_tokens: int = 12000) -> str:+ """Build context for WriterAgent – preserves more detail."""+ parts: list[str] = []++ if self.plan:+ parts.append("## Plan\n" + self._format_plan())++ if not self.plan:+ return "\n\n".join(parts) or "(no evidence gathered)"++ for step in self.plan.steps:+ if step.status not in ("completed", "in_progress"):+ continue+ entries = self.get_entries_for_step(step.id)+ if not entries:+ continue++ step_parts = [f"### Step {step.id}: {step.goal}"]+ for e in entries:+ entry_text = (+ f"**Round {e.round}** — Action: {e.action}({e.action_input})\n"+ f"Note: {e.self_note}\n"+ f"Observation:\n{e.observation}"+ )+ step_parts.append(entry_text)+ parts.append("\n\n".join(step_parts))++ full = "\n\n---\n\n".join(parts)++ # If over budget, drop observations from early steps+ if self._estimate_tokens(full) > max_tokens and self.plan:+ parts_compressed: list[str] = []+ step_list = [s for s in self.plan.steps if s.status in ("completed", "in_progress")]+ n = len(step_list)+ for i, step in enumerate(step_list):+ entries = self.get_entries_for_step(step.id)+ if not entries:+ continue+ step_parts_c = [f"### Step {step.id}: {step.goal}"]+ for e in entries:+ if i < n - 2:+ # Early steps: notes only+ step_parts_c.append(f"Round {e.round}: {e.self_note}")+ else:+ # Recent steps: full observation+ step_parts_c.append(+ f"**Round {e.round}** — Action: {e.action}({e.action_input})\n"+ f"Note: {e.self_note}\n"+ f"Observation:\n{e.observation}"+ )+ parts_compressed.append("\n".join(step_parts_c))+ full = "\n\n---\n\n".join(parts_compressed)++ return full or "(no evidence gathered)"++ # ------------------------------------------------------------------+ # Sources+ # ------------------------------------------------------------------++ def get_all_sources(self) -> list[dict[str, Any]]:+ """Return deduplicated list of all sources with IDs."""+ seen: set[str] = set()+ result: list[dict[str, Any]] = []+ counter: dict[str, int] = {}+ for entry in self.entries:+ for src in entry.sources:+ key = f"{src.type}:{src.file or src.url or src.chunk_id}"+ if key not in seen:+ seen.add(key)+ prefix = src.type if src.type in ("rag", "web", "code") else "src"+ counter[prefix] = counter.get(prefix, 0) + 1+ source_id = f"{prefix}-{counter[prefix]}"+ d = src.to_dict()+ d["id"] = source_id+ result.append(d)+ return result++ def format_sources_markdown(self) -> str:+ """Format sources as a Markdown references section."""+ sources = self.get_all_sources()+ if not sources:+ return ""+ lines = ["## References\n"]+ for s in sources:+ label = s.get("file") or s.get("url") or s.get("chunk_id") or "unknown"+ lines.append(f"- **[{s['id']}]** {label}")+ return "\n".join(lines)++ # ------------------------------------------------------------------+ # Persistence+ # ------------------------------------------------------------------++ def save(self, output_dir: str) -> str:+ path = os.path.join(output_dir, self.FILENAME)+ data = {+ "version": self.VERSION,+ "question": self.question,+ "plan": self.plan.to_dict() if self.plan else None,+ "entries": [e.to_dict() for e in self.entries],+ "metadata": self.metadata,+ }+ with open(path, "w", encoding="utf-8") as f:+ json.dump(data, f, ensure_ascii=False, indent=2)+ return path++ @classmethod+ def load_or_create(cls, output_dir: str, question: str) -> Scratchpad:+ path = os.path.join(output_dir, cls.FILENAME)+ if os.path.exists(path):+ with open(path, encoding="utf-8") as f:+ data = json.load(f)+ pad = cls(question=data.get("question", question))+ if data.get("plan"):+ pad.plan = Plan.from_dict(data["plan"])+ pad.entries = [Entry.from_dict(e) for e in data.get("entries", [])]+ pad.metadata = data.get("metadata", pad.metadata)+ return pad+ return cls(question=question)++ # ------------------------------------------------------------------+ # Internal helpers+ # ------------------------------------------------------------------++ def _format_plan(self) -> str:+ if self.plan is None:+ return "(no plan yet)"+ lines = [f"Analysis: {self.plan.analysis}"]+ for s in self.plan.steps:+ status_mark = {"completed": "[x]", "in_progress": "[>]", "skipped": "[-]"}.get(+ s.status, "[ ]"+ )+ lines.append(f" {status_mark} {s.id}: {s.goal}")+ return "\n".join(lines)++ @staticmethod+ def _estimate_tokens(text: str) -> int:+ """Estimate token count. Uses tiktoken if available, else chars/4."""+ if _TIKTOKEN_AVAILABLE:+ try:+ enc = tiktoken.get_encoding("cl100k_base")+ return len(enc.encode(text))+ except Exception:+ pass+ return len(text) // 4diff --git a/src/agents/solve/memory/solve_memory.py b/src/agents/solve/memory/solve_memory.pydeleted file mode 100644index fb1829a7a..000000000--- a/src/agents/solve/memory/solve_memory.py+++ /dev/null@@ -1,996 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-SolveMemory - Todo-list based solving memory system--Manages the todo-list milestones and solve outputs for the problem-solving process.-"""--from __future__ import annotations--from dataclasses import asdict, dataclass, field-from datetime import datetime-import json-from pathlib import Path-from typing import Any, Dict, List, Optional-import uuid---def _now() -> str:- return datetime.utcnow().isoformat()---# ========================================================================== #-# Data Structures-# ========================================================================== #---@dataclass-class TodoItem:- """Single item in the todo-list (milestone)"""-- todo_id: str # e.g., "T1", "T2"- description: str # Milestone description- status: str = "pending" # pending | in_progress | completed | skipped- completed_at: Optional[str] = None- completed_by_output_id: Optional[str] = None # Which output completed this todo- completed_by_iteration_id: Optional[str] = None # Which iteration completed this todo- evidence: Optional[str] = None # Evidence for completion- parent_id: Optional[str] = None # Parent todo ID if this was split from another- iteration_evidence: List[str] = field(default_factory=list) # cite_ids that support completion- created_at: str = field(default_factory=_now)- updated_at: str = field(default_factory=_now)-- def to_dict(self) -> Dict[str, Any]:- return asdict(self)-- @classmethod- def from_dict(cls, data: Dict[str, Any]) -> "TodoItem":- data.setdefault("status", "pending")- data.setdefault("completed_at", None)- data.setdefault("completed_by_output_id", None)- data.setdefault("completed_by_iteration_id", None)- data.setdefault("evidence", None)- data.setdefault("parent_id", None)- data.setdefault("iteration_evidence", [])- data.setdefault("created_at", _now())- data.setdefault("updated_at", data["created_at"])- return cls(**data)-- def mark_completed(- self,- output_id: str = "",- evidence: str = "",- iteration_id: str = "",- cite_ids: Optional[List[str]] = None,- ):- self.status = "completed"- self.completed_at = _now()- self.completed_by_output_id = output_id- self.completed_by_iteration_id = iteration_id- self.evidence = evidence- if cite_ids:- self.iteration_evidence = cite_ids- self.updated_at = _now()-- def mark_in_progress(self):- self.status = "in_progress"- self.updated_at = _now()-- def mark_skipped(self, reason: str = ""):- self.status = "skipped"- self.evidence = reason- self.updated_at = _now()---@dataclass-class NoteAction:- """Single action from note_agent to edit todo-list"""-- pre_id: int # Position reference: 0 means before T1, 1 means after T1, etc.- action: str # done | edit | add | delete- content: Optional[str] = None # Required for edit/add, null for done/delete- target_todo_id: Optional[str] = None # Resolved todo_id after processing-- def to_dict(self) -> Dict[str, Any]:- return asdict(self)-- @classmethod- def from_dict(cls, data: Dict[str, Any]) -> "NoteAction":- data.setdefault("content", None)- data.setdefault("target_todo_id", None)- return cls(**data)---@dataclass-class IterationRecord:- """Record of a single solve iteration (inner loop)"""-- iteration_id: str # e.g., "iter_1", "iter_2"- target_todo_id: str # The todo being worked on- tool_calls: List[ToolCallRecord] = field(default_factory=list)- note_actions: List[NoteAction] = field(default_factory=list)- completed_todos: List[str] = field(default_factory=list) # todo_ids completed this iteration- step_response: Optional[str] = None # Response generated for this iteration- used_citations: List[str] = field(default_factory=list)- status: str = "in_progress" # in_progress | completed | failed- created_at: str = field(default_factory=_now)- updated_at: str = field(default_factory=_now)-- def to_dict(self) -> Dict[str, Any]:- data = asdict(self)- data["tool_calls"] = [tc.to_dict() for tc in self.tool_calls]- data["note_actions"] = [na.to_dict() for na in self.note_actions]- return data-- @classmethod- def from_dict(cls, data: Dict[str, Any]) -> "IterationRecord":- tool_calls = [ToolCallRecord.from_dict(tc) for tc in data.get("tool_calls", [])]- note_actions = [NoteAction.from_dict(na) for na in data.get("note_actions", [])]- data.setdefault("completed_todos", [])- data.setdefault("step_response", None)- data.setdefault("used_citations", [])- data.setdefault("status", "in_progress")- data.setdefault("created_at", _now())- data.setdefault("updated_at", data["created_at"])- return cls(- iteration_id=data["iteration_id"],- target_todo_id=data["target_todo_id"],- tool_calls=tool_calls,- note_actions=note_actions,- completed_todos=data["completed_todos"],- step_response=data["step_response"],- used_citations=data["used_citations"],- status=data["status"],- created_at=data["created_at"],- updated_at=data["updated_at"],- )-- def append_tool_call(self, tool_call: ToolCallRecord):- """Add a tool call to this iteration"""- self.tool_calls.append(tool_call)- self.updated_at = _now()-- def set_note_actions(self, actions: List[NoteAction]):- """Set the note actions from note_agent"""- self.note_actions = actions- self.updated_at = _now()-- def set_completed_todos(self, todo_ids: List[str]):- """Set the list of completed todos"""- self.completed_todos = todo_ids- self.updated_at = _now()-- def set_step_response(self, response: str, used_citations: Optional[List[str]] = None):- """Set the step response and mark iteration as completed"""- self.step_response = response- self.used_citations = used_citations or []- self.status = "completed"- self.updated_at = _now()-- def get_all_cite_ids(self) -> List[str]:- """Get all cite_ids from tool calls"""- return [tc.cite_id for tc in self.tool_calls if tc.cite_id]-- def format_tool_call_chain(self) -> str:- """Format tool call chain for context"""- if not self.tool_calls:- return "(No tool calls)"- lines = []- for tc in self.tool_calls:- summary = tc.summary or tc.raw_answer[:200] if tc.raw_answer else "(pending)"- lines.append(- f"- [{tc.tool_type}] {tc.query}\n"- f" cite_id: {tc.cite_id or 'N/A'}\n"- f" summary: {summary}"- )- return "\n".join(lines)---@dataclass-class ToolCallRecord:- """Single tool call record"""-- tool_type: str- query: str- cite_id: Optional[str] = None- raw_answer: Optional[str] = None- summary: Optional[str] = None- status: str = "pending" # pending | running | success | failed | none | finish- metadata: Dict[str, Any] = field(default_factory=dict)- created_at: str = field(default_factory=_now)- updated_at: str = field(default_factory=_now)- call_id: str = field(default_factory=lambda: f"tc_{uuid.uuid4().hex[:8]}")-- def to_dict(self) -> Dict[str, Any]:- return asdict(self)-- @classmethod- def from_dict(cls, data: Dict[str, Any]) -> "ToolCallRecord":- data.setdefault("metadata", {})- data.setdefault("status", "pending")- data.setdefault("created_at", _now())- data.setdefault("updated_at", data["created_at"])- data.setdefault("call_id", f"tc_{uuid.uuid4().hex[:8]}")- return cls(**data)-- def mark_running(self):- self.status = "running"- self.updated_at = _now()-- def mark_result(- self,- raw_answer: str,- summary: str,- status: str = "success",- metadata: Optional[Dict[str, Any]] = None,- ):- self.raw_answer = raw_answer- self.summary = summary- self.status = status- if metadata:- self.metadata.update(metadata)- self.updated_at = _now()---@dataclass-class SolveOutput:- """Single output from a solve iteration"""-- output_id: str # e.g., "O1", "O2"- selected_todo_id: str # Which todo item was selected- reasoning: str # Why this todo was selected- action_type: str # tool_call | direct_answer | skip- content: str = "" # The actual content/answer generated- tool_calls: List[ToolCallRecord] = field(default_factory=list)- used_citations: List[str] = field(default_factory=list)- created_at: str = field(default_factory=_now)- updated_at: str = field(default_factory=_now)-- def to_dict(self) -> Dict[str, Any]:- data = asdict(self)- data["tool_calls"] = [tc.to_dict() for tc in self.tool_calls]- return data-- @classmethod- def from_dict(cls, data: Dict[str, Any]) -> "SolveOutput":- tool_calls = [ToolCallRecord.from_dict(tc) for tc in data.get("tool_calls", [])]- data.setdefault("content", "")- data.setdefault("used_citations", [])- data.setdefault("created_at", _now())- data.setdefault("updated_at", data["created_at"])- return cls(- output_id=data["output_id"],- selected_todo_id=data["selected_todo_id"],- reasoning=data.get("reasoning", ""),- action_type=data.get("action_type", "direct_answer"),- content=data["content"],- tool_calls=tool_calls,- used_citations=data["used_citations"],- created_at=data["created_at"],- updated_at=data["updated_at"],- )-- def append_tool_call(self, tool_call: ToolCallRecord):- self.tool_calls.append(tool_call)- self.updated_at = _now()-- def set_content(self, content: str, used_citations: Optional[List[str]] = None):- self.content = content- if used_citations:- self.used_citations = used_citations- self.updated_at = _now()---# ========================================================================== #-# SolveChainStep (kept for backward compatibility with ResponseAgent)-# ========================================================================== #---@dataclass-class SolveChainStep:- """Single step structure in solve-chain (kept for backward compatibility)"""-- step_id: str- step_target: str- available_cite: List[str] = field(default_factory=list)- tool_calls: List[ToolCallRecord] = field(default_factory=list)- step_response: Optional[str] = None- status: str = "undone" # undone | in_progress | waiting_response | done | failed- used_citations: List[str] = field(default_factory=list)- created_at: str = field(default_factory=_now)- updated_at: str = field(default_factory=_now)-- def to_dict(self) -> Dict[str, Any]:- data = asdict(self)- data["tool_calls"] = [tc.to_dict() for tc in self.tool_calls]- return data-- @classmethod- def from_dict(cls, data: Dict[str, Any]) -> "SolveChainStep":- tool_calls = [ToolCallRecord.from_dict(tc) for tc in data.get("tool_calls", [])]- data.setdefault("available_cite", [])- data.setdefault("used_citations", [])- data.setdefault("status", "undone")- data.setdefault("step_response", None)- data.setdefault("created_at", _now())- data.setdefault("updated_at", data["created_at"])- return cls(- step_id=data["step_id"],- step_target=data.get("step_target", data.get("plan", "")),- available_cite=data["available_cite"],- tool_calls=tool_calls,- step_response=data.get("step_response", data.get("content")),- status=data["status"],- used_citations=data.get("used_citations", []),- created_at=data["created_at"],- updated_at=data["updated_at"],- )-- def append_tool_call(self, tool_call: ToolCallRecord):- self.tool_calls.append(tool_call)- self.updated_at = _now()- if self.status == "undone":- self.status = "in_progress"-- def update_response(self, response: str, used_citations: Optional[List[str]] = None):- self.step_response = response- self.status = "done"- self.used_citations = used_citations or []- self.updated_at = _now()-- def mark_waiting_response(self):- self.status = "waiting_response"- self.updated_at = _now()---# ========================================================================== #-# SolveMemory-# ========================================================================== #---class SolveMemory:- """Todo-list based solving memory storage"""-- def __init__(- self,- task_id: Optional[str] = None,- user_question: str = "",- output_dir: Optional[str] = None,- ):- self.task_id = task_id or f"solve_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"- self.user_question = user_question- self.output_dir = output_dir-- self.version = "solve_chain_v2" # Updated version for new architecture- self.created_at = _now()- self.updated_at = _now()-- # Todo-list based solving- self.todo_list: List[TodoItem] = []- self.solve_outputs: List[SolveOutput] = [] # Kept for backward compatibility- self.iteration_records: List[IterationRecord] = [] # New: iteration-based tracking-- self.metadata: Dict[str, Any] = {- "total_todos": 0,- "completed_todos": 0,- "total_outputs": 0,- "total_tool_calls": 0,- "total_iterations": 0,- }-- self.file_path = Path(output_dir) / "solve_chain.json" if output_dir else None- self.iteration_file_path = (- Path(output_dir) / "iteration_records.json" if output_dir else None- )-- # ------------------------------------------------------------------ #- # Load/Save- # ------------------------------------------------------------------ #- @classmethod- def load_or_create(- cls,- output_dir: str,- user_question: str = "",- task_id: Optional[str] = None,- ) -> "SolveMemory":- file_path = Path(output_dir) / "solve_chain.json"- if not file_path.exists():- return cls(- task_id=task_id,- user_question=user_question,- output_dir=output_dir,- )-- with open(file_path, "r", encoding="utf-8") as f:- data = json.load(f)-- memory = cls(- task_id=data.get("task_id", task_id),- user_question=data.get("user_question", user_question),- output_dir=output_dir,- )-- memory.version = data.get("version", "solve_chain_v2")- memory.created_at = data.get("created_at", memory.created_at)- memory.updated_at = data.get("updated_at", memory.updated_at)- memory.metadata = data.get("metadata", memory.metadata)-- # Load todo-list data- memory.todo_list = [- TodoItem.from_dict(todo) for todo in data.get("todo_list", [])- ]- memory.solve_outputs = [- SolveOutput.from_dict(output) for output in data.get("solve_outputs", [])- ]-- # Load iteration records (from separate file or inline)- iteration_file_path = Path(output_dir) / "iteration_records.json"- if iteration_file_path.exists():- with open(iteration_file_path, "r", encoding="utf-8") as f:- iter_data = json.load(f)- memory.iteration_records = [- IterationRecord.from_dict(rec) for rec in iter_data.get("iterations", [])- ]- else:- # Try loading from inline data (backward compatibility)- memory.iteration_records = [- IterationRecord.from_dict(rec)- for rec in data.get("iteration_records", [])- ]-- return memory-- def save(self):- if not self.file_path:- raise ValueError("output_dir not set, cannot save solve-chain")- self.file_path.parent.mkdir(parents=True, exist_ok=True)- self.updated_at = _now()- payload = self.to_dict()- with open(self.file_path, "w", encoding="utf-8") as f:- json.dump(payload, f, ensure_ascii=False, indent=2)-- # Also save iteration records to separate file- self.save_iteration_records()-- def save_iteration_records(self):- """Save iteration records to a separate JSON file"""- if not self.iteration_file_path:- return- self.iteration_file_path.parent.mkdir(parents=True, exist_ok=True)- payload = {- "task_id": self.task_id,- "created_at": self.created_at,- "updated_at": _now(),- "iterations": [rec.to_dict() for rec in self.iteration_records],- }- with open(self.iteration_file_path, "w", encoding="utf-8") as f:- json.dump(payload, f, ensure_ascii=False, indent=2)-- def to_dict(self) -> Dict[str, Any]:- return {- "version": self.version,- "task_id": self.task_id,- "user_question": self.user_question,- "created_at": self.created_at,- "updated_at": self.updated_at,- "metadata": self.metadata,- "todo_list": [todo.to_dict() for todo in self.todo_list],- "solve_outputs": [output.to_dict() for output in self.solve_outputs],- # iteration_records saved to separate file, but keep reference- "iteration_records_file": "iteration_records.json",- }-- # ------------------------------------------------------------------ #- # Todo-list Management- # ------------------------------------------------------------------ #- def create_todo_list(self, todos: List[TodoItem]):- """Initialize the todo-list"""- self.todo_list = todos- self.metadata["total_todos"] = len(todos)- self.metadata["completed_todos"] = sum(1 for t in todos if t.status == "completed")- self.updated_at = _now()-- def get_todo(self, todo_id: str) -> Optional[TodoItem]:- """Get a todo item by ID"""- return next((todo for todo in self.todo_list if todo.todo_id == todo_id), None)-- def get_pending_todos(self) -> List[TodoItem]:- """Get all pending todo items"""- return [todo for todo in self.todo_list if todo.status in {"pending", "in_progress"}]-- def get_completed_todos(self) -> List[TodoItem]:- """Get all completed todo items"""- return [todo for todo in self.todo_list if todo.status == "completed"]-- def is_all_completed(self) -> bool:- """Check if all required todos are completed (completed or skipped)"""- if not self.todo_list:- return False- return all(todo.status in {"completed", "skipped"} for todo in self.todo_list)-- def mark_todo_completed(self, todo_id: str, output_id: str, evidence: str = ""):- """Mark a todo item as completed"""- todo = self.get_todo(todo_id)- if not todo:- raise ValueError(f"Todo {todo_id} not found")- todo.mark_completed(output_id=output_id, evidence=evidence)- self.metadata["completed_todos"] = sum(1 for t in self.todo_list if t.status == "completed")- self.updated_at = _now()-- def mark_todo_in_progress(self, todo_id: str):- """Mark a todo item as in progress"""- todo = self.get_todo(todo_id)- if not todo:- raise ValueError(f"Todo {todo_id} not found")- todo.mark_in_progress()- self.updated_at = _now()-- def mark_todo_skipped(self, todo_id: str, reason: str = ""):- """Mark a todo item as skipped"""- todo = self.get_todo(todo_id)- if not todo:- raise ValueError(f"Todo {todo_id} not found")- todo.mark_skipped(reason=reason)- self.updated_at = _now()-- def get_todo_list_with_status(self) -> str:- """Get formatted todo-list with status markers"""- lines = []- for todo in self.todo_list:- status_marker = {- "pending": "[ ]",- "in_progress": "[~]",- "completed": "[x]",- "skipped": "[-]",- }.get(todo.status, "[ ]")- lines.append(f"{status_marker} {todo.todo_id}: {todo.description}")- return "\n".join(lines)-- def get_next_pending_todo(self) -> Optional[TodoItem]:- """Get the first pending todo item"""- for todo in self.todo_list:- if todo.status == "pending":- return todo- return None-- # ------------------------------------------------------------------ #- # Todo-list Editing (for NoteAgent)- # ------------------------------------------------------------------ #- def insert_todo_after(- self,- pre_id: int,- content: str,- parent_id: Optional[str] = None,- ) -> TodoItem:- """- Insert a new todo after the specified position.-- Args:- pre_id: Position reference (0 = before first, 1 = after first, etc.)- content: Description of the new todo- parent_id: Optional parent todo ID if this is a split-- Returns:- The newly created TodoItem- """- # Create new todo with temporary ID- new_todo = TodoItem(- todo_id=f"T{pre_id + 1}_new", # Temporary, will be renumbered- description=content,- status="pending",- parent_id=parent_id,- )-- # Insert at the correct position- insert_pos = min(pre_id, len(self.todo_list))- self.todo_list.insert(insert_pos, new_todo)-- # Renumber all todos- self._renumber_todos()-- self.metadata["total_todos"] = len(self.todo_list)- self.updated_at = _now()- return new_todo-- def edit_todo(self, todo_id: str, new_content: str) -> TodoItem:- """- Edit the content of a todo item.-- Args:- todo_id: ID of the todo to edit- new_content: New description-- Returns:- The updated TodoItem- """- todo = self.get_todo(todo_id)- if not todo:- raise ValueError(f"Todo {todo_id} not found")-- todo.description = new_content- todo.updated_at = _now()- self.updated_at = _now()- return todo-- def delete_todo(self, todo_id: str) -> bool:- """- Delete a todo item.-- Args:- todo_id: ID of the todo to delete-- Returns:- True if deleted, False if not found- """- todo = self.get_todo(todo_id)- if not todo:- return False-- self.todo_list.remove(todo)- self._renumber_todos()-- self.metadata["total_todos"] = len(self.todo_list)- self.updated_at = _now()- return True-- def _renumber_todos(self):- """Renumber all todos to ensure sequential IDs (T1, T2, T3, ...)"""- for idx, todo in enumerate(self.todo_list, 1):- todo.todo_id = f"T{idx}"-- def apply_note_actions(- self,- actions: List[NoteAction],- iteration_id: str = "",- cite_ids: Optional[List[str]] = None,- ) -> List[str]:- """- Apply a list of note actions to modify the todo-list.-- Args:- actions: List of NoteAction objects- iteration_id: Current iteration ID for tracking- cite_ids: Citation IDs from this iteration-- Returns:- List of todo_ids that were marked as completed- """- completed_todos: List[str] = []-- # Sort actions by pre_id in reverse order for insertions- # This ensures earlier insertions don't affect later positions- sorted_actions = sorted(actions, key=lambda a: a.pre_id, reverse=True)-- for action in sorted_actions:- pre_id = action.pre_id- action_type = action.action.lower()-- if action_type == "done":- # Mark the todo at position pre_id as completed- if 0 < pre_id <= len(self.todo_list):- todo = self.todo_list[pre_id - 1]- todo.mark_completed(- output_id="",- evidence=action.content or "",- iteration_id=iteration_id,- cite_ids=cite_ids,- )- completed_todos.append(todo.todo_id)- action.target_todo_id = todo.todo_id-- elif action_type == "edit":- if action.content and 0 < pre_id <= len(self.todo_list):- todo = self.todo_list[pre_id - 1]- todo.description = action.content- todo.updated_at = _now()- action.target_todo_id = todo.todo_id-- elif action_type == "add":- if action.content:- # Determine parent_id from the previous todo- parent_id = None- if 0 < pre_id <= len(self.todo_list):- parent_id = self.todo_list[pre_id - 1].todo_id-- new_todo = TodoItem(- todo_id=f"T_new_{pre_id}",- description=action.content,- status="pending",- parent_id=parent_id,- )- # Insert after pre_id position- insert_pos = min(pre_id, len(self.todo_list))- self.todo_list.insert(insert_pos, new_todo)- action.target_todo_id = new_todo.todo_id-- elif action_type == "delete":- if 0 < pre_id <= len(self.todo_list):- todo = self.todo_list[pre_id - 1]- action.target_todo_id = todo.todo_id- self.todo_list.remove(todo)-- # Renumber todos after all actions- self._renumber_todos()-- # Update metadata- self.metadata["total_todos"] = len(self.todo_list)- self.metadata["completed_todos"] = sum(- 1 for t in self.todo_list if t.status == "completed"- )- self.updated_at = _now()-- return completed_todos-- def get_todo_by_position(self, position: int) -> Optional[TodoItem]:- """Get todo by 1-based position"""- if 0 < position <= len(self.todo_list):- return self.todo_list[position - 1]- return None-- # ------------------------------------------------------------------ #- # Iteration Management- # ------------------------------------------------------------------ #- def create_iteration(self, target_todo_id: str) -> IterationRecord:- """- Create a new iteration record.-- Args:- target_todo_id: The todo being worked on-- Returns:- New IterationRecord- """- iteration_id = f"iter_{len(self.iteration_records) + 1}"- record = IterationRecord(- iteration_id=iteration_id,- target_todo_id=target_todo_id,- )- self.iteration_records.append(record)- self.metadata["total_iterations"] = len(self.iteration_records)- self.updated_at = _now()- return record-- def get_iteration(self, iteration_id: str) -> Optional[IterationRecord]:- """Get an iteration record by ID"""- return next(- (rec for rec in self.iteration_records if rec.iteration_id == iteration_id),- None,- )-- def get_current_iteration(self) -> Optional[IterationRecord]:- """Get the most recent iteration record"""- return self.iteration_records[-1] if self.iteration_records else None-- def get_current_iteration_id(self) -> str:- """Get the current iteration ID or generate new one"""- if self.iteration_records:- return self.iteration_records[-1].iteration_id- return f"iter_{len(self.iteration_records) + 1}"-- def get_all_step_responses(self) -> List[str]:- """Get all step responses from completed iterations"""- return [- rec.step_response- for rec in self.iteration_records- if rec.step_response and rec.status == "completed"- ]-- def get_all_iteration_citations(self) -> List[str]:- """Get all unique citations from all iterations"""- citations = []- for rec in self.iteration_records:- for cite in rec.used_citations:- if cite not in citations:- citations.append(cite)- return citations-- # ------------------------------------------------------------------ #- # Solve Output Management- # ------------------------------------------------------------------ #- def append_solve_output(self, output: SolveOutput):- """Add a new solve output"""- self.solve_outputs.append(output)- self.metadata["total_outputs"] = len(self.solve_outputs)- self.metadata["total_tool_calls"] = sum(- len(o.tool_calls) for o in self.solve_outputs- )- self.updated_at = _now()-- def get_solve_output(self, output_id: str) -> Optional[SolveOutput]:- """Get a solve output by ID"""- return next((o for o in self.solve_outputs if o.output_id == output_id), None)-- def get_latest_output(self) -> Optional[SolveOutput]:- """Get the most recent solve output"""- return self.solve_outputs[-1] if self.solve_outputs else None-- def get_next_output_id(self) -> str:- """Generate the next output ID"""- return f"O{len(self.solve_outputs) + 1}"-- def get_all_output_contents(self) -> List[str]:- """Get all output contents for final answer compilation"""- return [o.content for o in self.solve_outputs if o.content]-- def get_all_used_citations(self) -> List[str]:- """Get all unique citations used across all outputs"""- citations = []- for output in self.solve_outputs:- for cite in output.used_citations:- if cite not in citations:- citations.append(cite)- return citations-- def update_output_content(- self,- output_id: str,- content: str,- used_citations: Optional[List[str]] = None,- ):- """Update the content of a solve output"""- output = self.get_solve_output(output_id)- if not output:- raise ValueError(f"Output {output_id} not found")- output.set_content(content=content, used_citations=used_citations)- self.updated_at = _now()-- def append_tool_call_to_output(- self,- output_id: str,- tool_type: str,- query: str,- cite_id: Optional[str] = None,- metadata: Optional[Dict[str, Any]] = None,- ) -> ToolCallRecord:- """Append a tool call to a solve output"""- output = self.get_solve_output(output_id)- if not output:- raise ValueError(f"Output {output_id} not found")- record = ToolCallRecord(- tool_type=tool_type,- query=query,- cite_id=cite_id,- metadata=metadata or {},- )- output.append_tool_call(record)- self.metadata["total_tool_calls"] = sum(- len(o.tool_calls) for o in self.solve_outputs- )- self.updated_at = _now()- return record-- def update_tool_call_in_output(- self,- output_id: str,- call_id: str,- raw_answer: str,- summary: str,- status: str = "success",- metadata: Optional[Dict[str, Any]] = None,- ):- """Update a tool call result in a solve output"""- output = self.get_solve_output(output_id)- if not output:- raise ValueError(f"Output {output_id} not found")- record = next((tc for tc in output.tool_calls if tc.call_id == call_id), None)- if not record:- raise ValueError(f"Tool call {call_id} not found in output {output_id}")- record.mark_result(raw_answer=raw_answer, summary=summary, status=status, metadata=metadata)- self.updated_at = _now()-- # ------------------------------------------------------------------ #- # Summary and History- # ------------------------------------------------------------------ #- def get_summary(self) -> str:- """Get a summary of the current state"""- lines = [- f"Task ID: {self.task_id}",- f"Question: {self.user_question}",- f"Total Todos: {self.metadata.get('total_todos', len(self.todo_list))}",- f"Completed Todos: {self.metadata.get('completed_todos', 0)}",- f"Total Outputs: {len(self.solve_outputs)}",- ]- for todo in self.todo_list:- status_icon = {- "pending": "[ ]",- "in_progress": "[~]",- "completed": "[x]",- "skipped": "[-]",- }.get(todo.status, "[ ]")- lines.append(f"{status_icon} {todo.todo_id}: {todo.description[:60]}...")- return "\n".join(lines)-- def format_todo_list_for_log(self) -> str:- """Format todo-list for logging output"""- if not self.todo_list:- return "(No todo-list generated)"-- lines = [- "=" * 60,- "Generated Todo-list:",- "-" * 60,- ]- for todo in self.todo_list:- status_icon = {- "pending": "[ ]",- "in_progress": "[~]",- "completed": "[x]",- "skipped": "[-]",- }.get(todo.status, "[ ]")- lines.append(f" {status_icon} {todo.todo_id}: {todo.description}")- lines.append("=" * 60)- return "\n".join(lines)-- def save_todo_history(self, output_dir: str) -> Path:- """- Save todo-list execution history to a markdown file.-- Args:- output_dir: Output directory path-- Returns:- Path to the saved history file- """- history_file = Path(output_dir) / "todo_history.md"-- with open(history_file, "w", encoding="utf-8") as f:- f.write("# Todo-list Execution History\n\n")- f.write(f"**Question:** {self.user_question}\n\n")- f.write(f"**Task ID:** {self.task_id}\n\n")- f.write(f"**Created:** {self.created_at}\n\n")-- # Write todo-list section- f.write("## Todo-list\n\n")- f.write("| Status | ID | Description | Completed By |\n")- f.write("|--------|----|-----------|--------------|\n")- for todo in self.todo_list:- status_icon = {- "pending": "⬜",- "in_progress": "🔄",- "completed": "✅",- "skipped": "⏭️",- }.get(todo.status, "⬜")- completed_by = todo.completed_by_output_id or "-"- # Escape pipe characters in description- desc = todo.description.replace("|", "\\|")- f.write(f"| {status_icon} | {todo.todo_id} | {desc} | {completed_by} |\n")-- # Write execution outputs section- if self.solve_outputs:- f.write("\n## Execution Outputs\n\n")- for output in self.solve_outputs:- f.write(f"### {output.output_id} → {output.selected_todo_id}\n\n")- f.write(f"- **Action Type:** {output.action_type}\n")- f.write(f"- **Reasoning:** {output.reasoning}\n")-- if output.tool_calls:- f.write(f"- **Tool Calls:** {len(output.tool_calls)}\n")- for tc in output.tool_calls:- f.write(f" - `{tc.tool_type}`: {tc.query[:80]}...\n")-- if output.content:- # Truncate long content- content_preview = output.content[:500]- if len(output.content) > 500:- content_preview += "..."- f.write(f"\n**Content:**\n\n{content_preview}\n")-- f.write("\n---\n\n")-- # Write completion evidence section- completed_todos = [t for t in self.todo_list if t.status == "completed" and t.evidence]- if completed_todos:- f.write("## Completion Evidence\n\n")- for todo in completed_todos:- f.write(f"### {todo.todo_id}\n\n")- f.write(f"{todo.evidence}\n\n")-- # Write summary- f.write("## Summary\n\n")- f.write(f"- **Total Todos:** {len(self.todo_list)}\n")- f.write(f"- **Completed:** {len([t for t in self.todo_list if t.status == 'completed'])}\n")- f.write(f"- **Skipped:** {len([t for t in self.todo_list if t.status == 'skipped'])}\n")- f.write(f"- **Total Outputs:** {len(self.solve_outputs)}\n")-- return history_filediff --git a/src/agents/solve/new-structure.md b/src/agents/solve/new-structure.mdnew file mode 100644index 000000000..07cb09023--- /dev/null+++ b/src/agents/solve/new-structure.md@@ -0,0 +1,266 @@+# Solve Agent 重构:Plan → ReAct → Write++## 设计原则++- **一条流水线**:不分路由、不分路径,所有问题走同一个流程+- **宏观 Plan**:先规划解题步骤,给 Agent 全局视野(解决纯 ReAct 局部最优问题)+- **微观 ReAct**:每个步骤内通过 think→act→observe 迭代获取信息+- **Plan 自适应**:简单问题自然产生 1 步计划,复杂问题产生多步计划——复杂度由 LLM 判断,不由系统硬编码+- **去中间摘要**:Agent 直接看原始检索结果,不经过独立的摘要 Agent++---++## 总体流程++```+用户问题+ │+ ▼+┌─────────────────────────────────────────────┐+│ Phase 1: PLAN │+│ PlannerAgent 分析问题,生成有序步骤列表 │+│ [S1, S2, S3, ...] │+└─────────────────┬───────────────────────────┘+ │+ ▼+┌─────────────────────────────────────────────┐+│ Phase 2: SOLVE │+│ │+│ for each step Si: │+│ SolverAgent (ReAct Loop): │+│ THINK → 当前步骤还缺什么信息? │+│ ACT → rag / web / code / done │+│ OBSERVE → 工具返回结果写入 Scratchpad │+│ ... 重复直到 done ... │+│ │+│ (可选) 步骤间 replan: │+│ 如果新信息表明原计划需调整, │+│ SolverAgent 可输出 replan 信号, │+│ 触发 PlannerAgent 修订剩余步骤 │+└─────────────────┬───────────────────────────┘+ │+ ▼+┌─────────────────────────────────────────────┐+│ Phase 3: WRITE │+│ WriterAgent 基于完整 Scratchpad 生成答案 │+│ 结构化 Markdown + LaTeX + 内联引用 │+└─────────────────────────────────────────────┘+```++---++## Agent 定义(共 3 个)++### PlannerAgent++职责:将用户问题分解为有序解题步骤。++输入:+- 用户问题+- 知识库元信息(可选,帮助判断可用资源)+- 已有 Scratchpad 内容(replan 场景下非空)++输出:+```+{+ "analysis": "对问题的简要分析",+ "steps": [+ { "id": "S1", "goal": "明确线性卷积的数学定义", "tools_hint": ["rag"] },+ { "id": "S2", "goal": "推导卷积的计算过程", "tools_hint": ["rag", "code"] },+ { "id": "S3", "goal": "举例验证", "tools_hint": ["code"] }+ ]+}+```++设计要点:+- 步骤粒度为"一个可验证的子目标",不是"一个工具调用"+- `tools_hint` 仅为提示,SolverAgent 可自行决定实际用什么工具+- 简单问题(如"X 的定义是什么")自然只产生 1 个步骤+- 复杂问题自然产生 3-6 个步骤+- 不需要 Router——Plan 本身就是自适应机制++### SolverAgent++职责:针对当前步骤,通过 ReAct 迭代获取和验证所需信息。++每轮迭代输出:+```+{+ "thought": "当前步骤需要卷积定义,我先在教材中检索...",+ "action": "rag_search", // rag_search | web_search | code_execute | done | replan+ "action_input": "线性卷积 定义 公式",+ "self_note": "找到了精确定义和公式,信息充足" // 简短自注,用于后续上下文压缩+}+```++设计要点:+- 一个 Agent 兼具检索决策、查询改写、信息评估能力+- `done` 表示当前步骤信息已充足,推进到下一步+- `replan` 表示发现原计划有问题(如发现问题理解有误、知识库缺少关键信息),触发 PlannerAgent 修订+- `self_note` 是 Agent 对本轮结果的一句话总结,服务于上下文压缩(不是独立的摘要 Agent)+- 工具执行本身是纯函数调用,不消耗 LLM+- 原始检索结果直接截断写入 Scratchpad 的 observation 字段,不做 LLM 摘要++### WriterAgent++职责:基于完整 Scratchpad 生成最终答案。++输入:+- 用户问题+- 完整 Scratchpad(含 plan + 所有 ReAct 条目)+- 用户偏好(语言、详细程度等)++输出:+- 结构化 Markdown 答案+- 内联引用(直接映射 Scratchpad 条目中的 sources)++设计要点:+- 融合原 ResponseAgent + PrecisionAnswerAgent 的能力+- 可以回溯任意 observation 的原始内容来确保公式/数据准确+- 引用不需要独立系统,直接从 Scratchpad entries 的 sources 提取++---++## 统一记忆:Scratchpad++一个数据结构,替代原来的 InvestigateMemory + SolveMemory + CitationMemory。++```+Scratchpad+│+├── question: str # 用户原始问题+│+├── plan: { # PlannerAgent 输出+│ analysis: str,+│ steps: [ { id, goal, tools_hint, status } ]+│ }+│+├── entries: [ # ReAct 循环所有条目(按时间顺序)+│ {+│ step_id: "S1", # 属于哪个 plan step+│ round: 1, # 该 step 内的第几轮+│ thought: str,+│ action: str,+│ action_input: str,+│ observation: str, # 原始工具返回(截断,不做 LLM 摘要)+│ self_note: str, # Agent 自注(1 句话)+│ sources: [ { type, file, page, url, chunk_id } ],+│ timestamp: str+│ }+│ ]+│+└── metadata: {+ total_llm_calls: int,+ total_tokens: int,+ start_time: str,+ plan_revisions: int # replan 次数+ }+```++### Scratchpad 的上下文管理++ReAct 迭代多了之后 Scratchpad 会膨胀,需要主动管理(借鉴 MemoBrain 思想):++**分层压缩策略:**++```+┌─────────────────────────────────────────────┐+│ 当前步骤的条目:完整保留 │+│ thought + action + observation(原始) │+├─────────────────────────────────────────────┤+│ 已完成步骤的条目:压缩为精要 │+│ thought + action + self_note(替代 obs) │+├─────────────────────────────────────────────┤+│ 更早的步骤:极度压缩 │+│ 仅保留 self_note 拼接为 1 段摘要 │+└─────────────────────────────────────────────┘+```++- 触发时机:传入 SolverAgent 的上下文 token 超过窗口 60%+- 原始 observation 始终完整保存在磁盘 JSON 中(WriterAgent 可按需回溯)+- 压缩在构建 prompt 时动态进行,不修改 Scratchpad 本体++---++## Replan 机制++不是每次都 replan,仅在 SolverAgent 主动判断需要时触发:++```+SolverAgent 输出 action = "replan"+ │+ ▼+PlannerAgent 接收:+ - 原始问题+ - 当前 Scratchpad(已执行的步骤和结果)+ - SolverAgent 的 replan 理由+ │+ ▼+输出修订后的 steps(可增删改剩余步骤)+ │+ ▼+继续 Solve Phase+```++典型触发场景:+- 检索发现问题前提有误,需要重新理解问题+- 发现知识库中缺少关键信息,需要转向 web_search+- 已完成的步骤覆盖了后续步骤的目标,可以合并/删除++---++## 工具层++纯执行函数,不涉及 LLM 调用。SolverAgent 通过 `action` + `action_input` 调度:++| action | 功能 | 返回 |+|--------|------|------|+| `rag_search` | 知识库检索 | 检索片段 + 来源元信息 |+| `web_search` | 网络搜索 | 搜索结果 + URL |+| `code_execute` | 沙箱执行 Python | 执行结果 + 产物路径 |+| `done` | 当前步骤完成 | — |+| `replan` | 请求修订计划 | — |++工具返回结果直接截断到合理长度(如 2000 token),写入 observation 字段。++---++## 与现有架构的映射++| 原架构 | 新架构 | 变化 |+|--------|--------|------|+| InvestigateAgent | SolverAgent | 合并 |+| NoteAgent | 删除 | self_note 替代 |+| ManagerAgent | PlannerAgent | 简化 |+| SolveAgent | SolverAgent | 合并 |+| ToolAgent(LLM 摘要) | 删除 | Agent 直接看原始结果 |+| SolveNoteAgent | 删除 | replan 机制替代 |+| ResponseAgent | WriterAgent | 简化 |+| PrecisionAnswerAgent | WriterAgent | 合并 |+| InvestigateMemory | Scratchpad | 统一 |+| SolveMemory | Scratchpad | 统一 |+| CitationMemory | Scratchpad.sources | 内嵌 |+| CitationManager | 删除 | 不需要独立管理 |++LLM 调用估算对比(中等复杂度问题):++| | 原架构 | 新架构 |+|--|--------|--------|+| 规划 | 1 次 ManagerAgent | 1 次 PlannerAgent |+| 检索决策 | ~5 次 InvestigateAgent + ~5 次 SolveAgent | ~6 次 SolverAgent |+| 中间摘要 | ~5 次 NoteAgent + ~5 次 ToolAgent | 0 |+| Todo 管理 | ~3 次 SolveNoteAgent | 0(偶尔 1 次 replan) |+| 答案生成 | ~3 次 ResponseAgent | 1 次 WriterAgent |+| **总计** | **~27 次** | **~8 次** |++---++## 附加建议++**流式输出**:SolverAgent 每轮的 thought 可实时推送前端,用户可看到推理过程。WriterAgent 支持流式生成答案。++**与 Research Agent 复用**:PlannerAgent + SolverAgent + WriterAgent 的三段式结构可复用于 research 模块,仅需切换 prompt 和可用工具。++**Query Rewriting 内置**:SolverAgent 在 thought 步骤中自然包含查询改写推理,不需要独立模块。++**观测截断策略**:RAG 返回多个片段时,按相关性分数排序后截断到 top-K 片段(如 top-3),保留最相关内容在有限 token 预算内。diff --git a/src/agents/solve/prompts/en/analysis_loop/investigate_agent.yaml b/src/agents/solve/prompts/en/analysis_loop/investigate_agent.yamldeleted file mode 100644index 1eefd1cab..000000000--- a/src/agents/solve/prompts/en/analysis_loop/investigate_agent.yaml+++ /dev/null@@ -1,55 +0,0 @@-system: |- # Role Definition- You are the **Investigator** in the analysis phase. Your core responsibility is to scrutinize the user's question and existing knowledge base to precisely identify **critical knowledge gaps** required for solving the problem, and to design efficient query plans. You are not the solver, but the logistics officer providing "ammunition" for the solver.-- # Core Principle: Minimal but Sufficient- Your goal is to reach a state of "Information Sufficiency" with the minimum number of queries.-- 1. **Deduction > Search**: If a piece of information can be derived from common sense, logic, or existing knowledge, **searching is strictly prohibited**.- 2. **Precision Sniper**: Queries must target specific definitions, theorem formulas, specific constants, or data. Reject broad queries like "How to solve...".- 3. **Strict De-duplication**: Before issuing a query, you must carefully check the `Existing Knowledge Context`. Semantic duplicates or subset queries are considered invalid.- 4. **Focus on Core**: Focus only on the "hard knowledge" (definitions, formulas, theorems) necessary for solving the problem. Unless explicitly requested by the user, do not query for application cases or background stories.-- # Tool Usage Guide- - `query_item`: **Priority for Numbered Items**. **ALWAYS use this first** when the user's question explicitly mentions a specific numbered item (e.g., "formula 2.1.2", "Theorem 3.1", "Figure 1.2", "Equation (2.1.2)"). Extract the identifier from the question (formats: "(X.X.X)" for equations, "Figure X.X" for figures, "Theorem X.X" for theorems). This is the most direct and accurate way to retrieve numbered content.- - `rag_naive`: **First Choice for General Queries**. Used for querying clear term definitions, core formulas, or verifying if a concept exists. Fast.- - `rag_hybrid`: Used for scenarios requiring synthesis of multiple concepts, exploring complex entity relationships, or deep principles.- - `web_search`: **Use Sparingly**. Only use when information is likely outside the scope of textbooks (e.g., latest news, specific technical parameters, usage of open-source libraries).- - `none`: Return this state when existing information is sufficient to support solving, or when the gap cannot be filled by retrieval (e.g., requires user input).-- # Thinking Path- 1. **Identify Numbered Items**: **First, scan the user's question for explicit numbered references** (e.g., "formula 2.1.2", "Theorem 3.1", "Figure 1.2", "Equation (2.1.2)"). If found, extract the identifier and use `query_item` immediately. Numbered items take priority over semantic search.- 2. **Analyze Needs**: What is truly missing for the solution? Is it the definition of a variable? The formula for a theorem? Or the value of a constant?- 3. **Check Inventory**: Review `Existing Knowledge Context`. Is the answer already there? Or is it implied in known information?- 4. **Construct Queries**: If gaps definitely exist, build atomic, non-overlapping query requests.- 5. **Judge Termination**: If core definitions and formulas are all present, stop immediately.- 6. **⚠️ CRITICAL - Know When to Cut Losses**: If the first round of queries for a topic returns no useful information (empty results, irrelevant, or low quality), it likely means the knowledge base doesn't contain relevant content. **You MUST abandon that topic immediately**, switch to other topics, or proceed directly to the next phase. **DO NOT repeatedly query the same topic** - this wastes resources and delays the solution.-- # Output Format- Directly output a JSON object (no Markdown formatting):- {- "reasoning": "Concise explanation of why a query is needed (pointing out specific missing points), or why stopping (explaining information is sufficient).",- "plan": [- {- "tool": "rag_naive | rag_hybrid | web_search | query_item",- "query": "Specific search query, or specific ID",- "identifier": "Optional, only for query_item"- }- ]- }--user_template: |- ## User Question- {question}-- ## Existing Knowledge Context ({num_knowledge} items)- {knowledge_chain_summary}-- ## Task- Analyze if there are knowledge gaps hindering the solution.- - **Priority: Numbered Items**: If the question mentions a specific numbered item (formula, theorem, figure, equation with numbers like "2.1.2", "3.1", etc.), **immediately use `query_item`** with the extracted identifier (e.g., "(2.1.2)" for equations, "Figure 2.1" for figures).- - Check for duplicates: New queries must not overlap with existing content.- - Flexible decision: If a previous tool query failed, consider using other tools to achieve the same goal.- - Know when to cut losses: If the first round of queries for a topic returns no useful information, do not repeatedly query that topic. Switch to other topics or proceed to the next phase.- - Judge stop: If existing info is sufficient to start solving (even if not perfect), return `none`.- - Output: Pure JSON format.diff --git a/src/agents/solve/prompts/en/analysis_loop/note_agent.yaml b/src/agents/solve/prompts/en/analysis_loop/note_agent.yamldeleted file mode 100644index 611e73634..000000000--- a/src/agents/solve/prompts/en/analysis_loop/note_agent.yaml+++ /dev/null@@ -1,54 +0,0 @@-system: |- # Role Definition- You are the **Knowledge Stenographer**. Your duty is to organize the raw information found (Raw Result) into well-structured, easy-to-cite knowledge notes.-- # Core Principles- 1. **Clean Noise**: Remove web ads, irrelevant navigation bars, and repetitive nonsense. Retain only hard-core knowledge relevant to the user's question.- 2. **Structuring**: Convert unstructured text into a concise Summary.- 3. **Citation Extraction**: Keenly identify information sources and build standard Citation objects.- 4. **Multi-Item Selection**: When `query_item` tool returns multiple items (indicated by `[identifier]` markers), **select only the most relevant item(s)** that directly answer the user's question. Do not include all items if they are not all relevant.-- # Format Constraints (Critical)- - **Summary Plain Text**: The Summary field is mainly for quick browsing. It is **strictly prohibited** to include LaTeX formulas (e.g., `$$...$$`, `\(...\)`).- - *Handling Method*: Describe formulas in natural language (e.g., "square of x" instead of "$x^2$").- - **JSON Output**: Must directly output a valid JSON object.-- # Multi-Item Handling (for query_item tool)- When the Raw Result contains multiple items separated by `[identifier]` markers:- - **Identify the primary item** that best matches the user's question- - **Focus the summary** on the selected item(s), not all items- - **Extract citations** only from the selected item(s)- - If multiple items are equally relevant, you may include 2-3 items, but prioritize quality over quantity-- # Output Structure- ```json- {- "summary": "Plain text summary, NO LaTeX allowed. Focus on the most relevant item(s) from the query result. E.g.: By definition, the output of an LTI system is the convolution of the input and the impulse response.",- "citations": [- {- "reference_id": "[1]",- "source": "Source filename or URL",- "content": "Optional, excerpt of key sentences from original text"- }- ]- }- ```--user_template: |- ## User Question- {question}-- ## Tool Type- {tool_type}-- ## Query Content- {query}-- ## Raw Search Result- {raw_result}-- ## Task- Organize the raw result into a JSON note.- 1. Summary must be plain text, no LaTeX.- 2. Extract all available citation sources.- 3. **If the result contains multiple items (marked with `[identifier]`), select only the most relevant one(s) for the user's question.**diff --git a/src/agents/solve/prompts/en/planner_agent.yaml b/src/agents/solve/prompts/en/planner_agent.yamlnew file mode 100644index 000000000..a385fee08--- /dev/null+++ b/src/agents/solve/prompts/en/planner_agent.yaml@@ -0,0 +1,65 @@+system: |+ # Role+ You are a **Problem-Solving Planner**. Your job is to analyse the user's question and produce an ordered list of solving steps.++ # Rules+ 1. Each step must be a **verifiable sub-goal** — describe **what** needs to be established or answered, NOT **how** (no tool names, no action instructions).+ - Good: "Establish the mathematical definition of linear convolution"+ - Bad: "Search for convolution" or "Use rag_search to find convolution definition"+ 2. Keep the plan **minimal but sufficient**.+ - A simple factual question → **1 step**.+ - A multi-part analytical question → **2–4 steps**.+ - A complex derivation / multi-hop problem → **3–6 steps**.+ 3. Do NOT specify which tools to use. The solving agent will independently decide the best approach for each step.+ 4. Step IDs must follow the pattern S1, S2, S3, …+ 5. If this is a **replan** request (progress is shown below), preserve all completed steps unchanged and only revise or add pending steps.+ 6. If memory context is provided, use it as historical reference, but do not copy old plans directly.+ 7. If **Retrieved Knowledge** is provided, use it to make a more precise and informed plan. It may reveal what knowledge is available, what concepts are involved, and what sub-problems exist.++ # Output Format+ Output **strict JSON** with no extra text:+ ```json+ {+ "analysis": "Brief analysis of the question and what is needed to solve it",+ "steps": [+ {"id": "S1", "goal": "..."},+ {"id": "S2", "goal": "..."}+ ]+ }+ ```++generate_queries: |+ Generate {num_queries} concise and diverse knowledge-base search queries for the following question. Each query should target a different aspect of the problem (e.g. core definitions, relevant formulas or theorems, related examples or techniques).++ Question: {question}++ Return strict JSON:+ {{"queries": ["query1", "query2", "query3"]}}++aggregate_context: |+ Below are several passages retrieved from a knowledge base. Your task is to consolidate them into a single structured knowledge summary.++ Rules:+ - Remove duplicate information across passages.+ - Organize by topic: definitions, formulas/theorems, key facts, examples.+ - Do NOT solve any problem or make inferences beyond what the passages state.+ - Do NOT reference any question — just organize the raw knowledge.+ - Be concise; keep the summary under 3000 characters.++ {raw_retrieval_text}++user_template: |+ ## Question+ {question}++ ## Retrieved Knowledge+ {rag_context}++ ## Available Tools+ {tools_description}++ ## Progress So Far+ {scratchpad_summary}++ ## Memory Context+ {memory_context}diff --git a/src/agents/solve/prompts/en/solve_loop/manager_agent.yaml b/src/agents/solve/prompts/en/solve_loop/manager_agent.yamldeleted file mode 100644index 10d3bccc9..000000000--- a/src/agents/solve/prompts/en/solve_loop/manager_agent.yaml+++ /dev/null@@ -1,69 +0,0 @@-system: |- # Role Definition- You are the **Milestone Planner** for problem-solving. Your task is to create a **Todo-list** of high-level milestones that need to be achieved to solve the user's question.-- # Planning Principles- 1. **Milestone Granularity**: Each todo item should be a verifiable milestone, NOT a detailed action step. Think "what needs to be achieved" rather than "how to do it".- 2. **Independence**: Each milestone should be independently verifiable - you can tell if it's done without looking at other milestones.- 3. **Coverage**: The todo-list should cover all aspects needed to fully answer the question.- 4. **Simplicity**: Aim for 3-6 milestones. Simple questions may need only 2-3; complex questions may need up to 6.- 5. **No Redundancy**: Don't add milestones just to pad the list. Each must provide unique value.-- # Example Milestones- Good milestones:- - "Clarify the core concepts and given conditions"- - "Establish the mathematical model or approach"- - "Execute the core calculation or derivation"- - "Verify the result and summarize the answer"-- Bad milestones (too detailed):- - "Define variable x"- - "Substitute x into formula"- - "Simplify the expression"-- # Output Format- Output a JSON object with a "todos" array:- ```json- {- "todos": [- {- "todo_id": "T1",- "description": "Clarify the problem's core concepts and identify key information"- },- {- "todo_id": "T2",- "description": "Determine the solution approach or mathematical model"- },- {- "todo_id": "T3",- "description": "Execute the main calculation or reasoning"- },- {- "todo_id": "T4",- "description": "Verify results and compile the final answer"- }- ]- }- ```-- **Field Descriptions**:- - `todo_id`: Todo ID, format as "T1", "T2", "T3", etc.- - `description`: Clear description of what milestone needs to be achieved--user_template: |- ## User Question- {question}-- ## Available Knowledge Chain- {knowledge_chain_summary}-- ## Previous Reflection (If any)- {reflections_summary}-- ## Task- Create a todo-list of milestones to solve this problem.- 1. Focus on WHAT needs to be achieved, not HOW to do it.- 2. Each milestone should be independently verifiable.- 3. Cover all aspects of the question.- 4. Keep it concise: 3-6 milestones is usually enough.- 5. Output the todo-list directly in JSON format.diff --git a/src/agents/solve/prompts/en/solve_loop/precision_answer_agent.yaml b/src/agents/solve/prompts/en/solve_loop/precision_answer_agent.yamldeleted file mode 100644index fccb6aaf7..000000000--- a/src/agents/solve/prompts/en/solve_loop/precision_answer_agent.yaml+++ /dev/null@@ -1,62 +0,0 @@-system: ""-user_template: ""--decision_system: |- # Role Definition- You are the **Question Type Judge**. Your sole task is to judge whether the user's question requires a **precise, short** final answer.-- # Judgement Criteria- - **YES (Precise Answer Needed)**:- - Multiple Choice- - Fill-in-the-blank- - Calculation questions- - True/False questions- - When the user's question contains a question that can be clearly answered by a word, a sentence, or a formula.-- - **NO (Precise Answer Not Needed)**:- - If none of the YES situations occur, judge as NO.-- # Output Format- Output only `YES` or `NO`.--decision_user_template: |- ## User Question- {question}-- ## Task- Judge whether a precise short final answer is needed.- - Output only `YES` or `NO`.--precision_system: |- # Role Definition- You are the **Answer Extractor**. Your task is to precisely extract the "final result" that the user cares about most from the long complete solution.-- # Extraction Strategy- - **Multiple Choice**: Extract only option letter (e.g., "A").- - **Calculation/Fill-in-the-blank**: Extract only final value or expression.- - **Short Answer**: Extract the most core 1-2 sentences of conclusion.- - If the user's question contains a question that can be clearly answered by a word, a sentence, or a formula, you need to extract this answer.-- # Core Principle- **Trim the Fat**: No explanation of process, no nonsense, just the result.-- # LaTeX Format Requirements (Important)- - **All mathematical expressions must be wrapped with `$...$`**- - Examples: `$y = \frac{1}{3}x^3 + C$`, `$x = 2$`, `$\pi$`- - **Strictly Prohibited**: Bare mathematical symbols (e.g., writing y = 2x + 1 directly)-- # Output Format- Directly output the answer string (mathematical formulas must use LaTeX format).--precision_user_template: |- ## User Question- {question}-- ## Detailed Solution- {detailed_answer}-- ## Task- Extract precise answer.- 1. If multiple choice, return letter only.- 2. If numerical, return value only.- 3. Strictly no nonsense.diff --git a/src/agents/solve/prompts/en/solve_loop/response_agent.yaml b/src/agents/solve/prompts/en/solve_loop/response_agent.yamldeleted file mode 100644index 6143ee145..000000000--- a/src/agents/solve/prompts/en/solve_loop/response_agent.yaml+++ /dev/null@@ -1,100 +0,0 @@-# Citation and image instruction templates-citation_instruction_disabled: |-- **Important: Citation Feature Disabled**- The citation feature is currently disabled. You should NOT use citation format (e.g., [rag-1], [code-2]) in your response.- Simply provide the answer without citation markers.--image_instruction: |-- **Important: Image Citation Requirements**- The following image files are detected in this iteration, you **must** insert them all into the answer:- {image_list}-- Insertion rules:- 1. Use standard Markdown image syntax: ``- 2. **Image path must be copied directly from the list above**, modification is strictly prohibited (e.g., if the list shows `artifacts/plot.png`, you must write `(artifacts/plot.png)`).- 3. Images should be accompanied by text explanations describing the meaning of the charts.--system: |- # Role Definition- You are a senior teaching assistant. Your task is to generate a high-quality response for the completed todos based on the tool call results from this iteration.- You need to write content that follows seamlessly from any previous steps, maintaining coherence in both substance and logic.-- # Core Principles- 1. **Continuity**: Your answer must follow directly after `previous_context`, maintaining smooth language flow. Do not repeat previous content unless for emphasis or summary.- 2. **Target Alignment**: Your answer must address ALL completed todos listed. Each todo should be adequately covered.- 3. **Evidence is King**: Any conclusion must be based on the provided tool call results and knowledge chain. Do not fabricate data.- 4. **Professional Format**: The answer must be well-formatted and logically arranged, allowing users to understand the solution approach.-- # Key Norms-- ### 1. Citation- - All definitions, formulas, and fact sources must be cited with ID.- - Format: `[cite_id]` (e.g., `[rag-1]`, `[code-2]`).- - Position: Immediately following the cited sentence or formula.-- ### 2. Mathematical Formulas (LaTeX)- - **All mathematical variables and expressions** must use LaTeX format:- - Single variables: `$x$`, `$y$`, `$n$`- - Constants and symbols: `$\pi$`, `$\alpha$`, `$\infty$`- - Expressions: `$x = 0$`, `$2\pi$`, `$n \to \infty$`- - Inline formula: Use `$ ... $`.- - Block formula:- ```latex- $$- E = mc^2- $$- ```- - **Strictly Prohibited**: Use of `\( ... \)` or `\[ ... \]`.- - **Strictly Prohibited**: Bare mathematical variables in text (e.g., writing x, y, π directly). Must wrap with `$...$`.-- ### 3. Multimodal Fusion- - **Image Insertion Mandatory**: If tool call results include generated images, or if the images list shows `artifacts/...` paths, you must insert these images.- - Syntax: ``, where all image paths are 'artifacts/file_name'- - Image placement should be adjacent to related content, followed by an explanation.- - If the same image appeared in previous steps, do not repeat it.- - **Code Presentation**: Do not paste large chunks of code. Only show core logic or key parameters; focus on explaining the **results** and **significance**.- - **Tables**: Use proper markdown table syntax when presenting tabular data.-- # Output Structure (Textbook Quality)- Please emulate the response style of a professional teaching assistant:- - **Subheading**: Use Markdown headings (`##` or `###`) to organize the response by completed todo- - **Concept Explanation**: For new concepts, provide rigorous definitions with citations- - **Logical Derivation**: Show derivation steps in detail, not just results- - **Multimodal Elements**: Insert and explain images where relevant- - **Summary**: Briefly summarize what was covered in this iteration--user_template: |- ## User Preference- {preference}-- ## User Question- {question}-- ## Previous Context (Completed Steps)- {previous_context}-- ## Completed Todos This Iteration ({completed_todos_count} items)- {completed_todos}-- ## Available Materials-- ### 1. Tool Call Results (This Iteration)- {tool_materials}-- ### 2. Prior Knowledge (from Investigation Phase)- {knowledge_chain}-- ### 3. Citation Details- {citation_details}-- ### 4. Images to Insert- {image_materials}-- ## Task- Write a professional response that addresses ALL the completed todos listed above.- - Use evidence from tool call results- - Include proper citations where applicable- - Insert and explain any generated images- - Follow the formatting guidelinesdiff --git a/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml b/src/agents/solve/prompts/en/solve_loop/solve_agent.yamldeleted file mode 100644index ab939a639..000000000--- a/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml+++ /dev/null@@ -1,56 +0,0 @@-system: |- # Role Definition- You are the **Solve Agent**, responsible for gathering information to complete the current todo.-- ## Your Task- For each call, decide what tool to use next to collect information.- You will be called multiple times in an iteration loop.- Output ONE tool call decision per response.-- ## Output Format (STRICT JSON)- ```json- {- "tool_type": "rag_naive | rag_hybrid | web_search | code_execution | none",- "query": "Your query or intent description"- }- ```-- ## Tool Types- - `rag_naive`: Precise definition/formula lookup from knowledge base- - `rag_hybrid`: Conceptual understanding, comparison, or broader semantic search- - `web_search`: External information, latest news, or resources not in the knowledge base- - `code_execution`: Calculations, mathematical derivations, plotting, data processing- - `none`: No more information needed - END this iteration-- ## Decision Guidelines- 1. **Review iteration_history**: Check what information has already been gathered- 2. **Assess sufficiency**: If existing info can answer the todo, output `none`- 3. **Choose appropriate tool**: Match the tool type to the information need- 4. **Write clear queries**: The query should be specific and actionable-- ## Rules- - Output exactly ONE tool call per response- - Use `none` when you have sufficient information to complete the todo- - Do NOT generate answer content - only decide what information to gather- - The query field describes WHAT you want, not HOW to get it- - For code_execution, describe the computation intent, not actual code--user_template: |- ## User Question- {question}-- ## Current Todo- {current_todo}-- ## Prior Knowledge (from investigation phase)- {knowledge_chain}-- ## This Iteration's Tool Calls ({iteration_count}/{max_iterations})- {iteration_history}-- ## Task- Based on the current todo and available information:- 1. If sufficient information exists, output `tool_type: "none"`- 2. If more information is needed, specify the appropriate tool and query-- Output valid JSON only - no explanation needed.diff --git a/src/agents/solve/prompts/en/solve_loop/solve_note_agent.yaml b/src/agents/solve/prompts/en/solve_loop/solve_note_agent.yamldeleted file mode 100644index a6d9d6f58..000000000--- a/src/agents/solve/prompts/en/solve_loop/solve_note_agent.yaml+++ /dev/null@@ -1,76 +0,0 @@-system: |- # Role Definition- You are the **Todo Manager** for a problem-solving system.-- Your task is to review the iteration results (tool call history) and update the todo-list accordingly.-- ## Capabilities- You can perform these actions on the todo-list:- - `done`: Mark a todo as completed- - `edit`: Change the content/description of a todo- - `add`: Insert a new todo at a specific position- - `delete`: Remove a todo from the list-- ## Output Format (STRICT JSON)- ```json- {- "actions": [- {- "pre_id": 1,- "action": "done",- "content": null- },- {- "pre_id": 1,- "action": "add",- "content": "New subtask that needs investigation"- }- ]- }- ```-- ## pre_id Explanation- - `pre_id` indicates the position number of the todo to operate on- - `pre_id=1` means the first todo (position 1)- - `pre_id=2` means the second todo (position 2)- - For `add` action: new item is inserted AFTER the specified position-- ## Action Details- - `done`: Mark the todo at position pre_id as completed- - content: optional evidence string, or null- - `edit`: Replace the description of todo at position pre_id- - content: new description (REQUIRED)- - `add`: Insert a new todo AFTER position pre_id- - content: description of new todo (REQUIRED)- - `delete`: Remove the todo at position pre_id- - content: null-- ## Guidelines- 1. **Primary goal**: Evaluate if the target todo can be marked as done based on iteration results- 2. **Partial completion**: If a todo is only partially answered:- - Edit the original to reflect the completed portion- - Mark the edited version as done- - Add a new todo for the remaining uncovered part- 3. **Cross-coverage**: If iteration results also answer other pending todos, mark them too- 4. **Conservative judgment**: Only mark as done if tool call summaries provide clear evidence- 5. **Avoid redundancy**: Delete todos that are fully covered by others or no longer needed--user_template: |- ## Current Todo-list- {todo_list}-- ## Target Todo (being worked on)- {target_todo}-- ## This Iteration's Tool Call Results- {tool_call_history}-- ## Task- Based on the tool call results from this iteration:- 1. Determine if the target todo ({target_todo_id}) can be marked as done- 2. Check if the results also complete or affect other pending todos- 3. If a todo is only partially complete, split it into completed + remaining parts-- Output a JSON object with an "actions" array.- Each action must have: pre_id (position number), action (done/edit/add/delete), content (if applicable).- If no changes are needed, return: {{"actions": []}}diff --git a/src/agents/solve/prompts/en/solve_loop/tool_agent.yaml b/src/agents/solve/prompts/en/solve_loop/tool_agent.yamldeleted file mode 100644index c3f92e108..000000000--- a/src/agents/solve/prompts/en/solve_loop/tool_agent.yaml+++ /dev/null@@ -1,38 +0,0 @@-system: |- # Role Definition- You are the **Lab Recorder**. Your duty is to objectively and clearly record the execution results of tools (code or search engine), providing material for subsequent report writing.-- # Core Task- Convert the execution results of tools into a "Structured Summary".- The execution may have been based on internally generated code or external queries.-- # Recording Principles- 1. **Objective & Truthful**: Faithfully record data, errors, or text returned by the tool; add no subjective speculation.- 2. **Highlight Key Points**:- - If code calculation, record key input parameters and output values.- - If search, record core facts and sources.- 3. **Concise**: Control length within 4-6 sentences, high information density.-- # Image Interpretation (Crucial)- If tool execution generates an image file (Artifacts contains .png/.jpg):- - You **MUST** dedicate a paragraph in the summary to describe that image.- - **Content**:- - *Intent*: What is this image intended to show? (e.g., "Plotted the spectrum of a sine wave")- - *Features*: What is seen on the graph? (e.g., "A distinct peak at 50Hz")- - *Conclusion*: What does this image imply? (e.g., "Verified the effectiveness of the filter")--user_template: |- ## Tool Type- {tool_type}-- ## Execution Intent- {query}-- ## Raw Return Result- {raw_answer}-- ## Task- Write a summary of this tool execution.- - Write in English.- - Must include image interpretation (if image generated).- - Objective, concise.diff --git a/src/agents/solve/prompts/en/solver_agent.yaml b/src/agents/solve/prompts/en/solver_agent.yamlnew file mode 100644index 000000000..ef0174d70--- /dev/null+++ b/src/agents/solve/prompts/en/solver_agent.yaml@@ -0,0 +1,43 @@+system: |+ # Role+ You are a **ReAct Problem-Solving Agent**. You operate in a think → act → observe loop to gather the information needed for the current step.++ # Available Actions+ {tools_description}++ # Guidelines+ - **One action per response.** Choose the single best next action.+ - Before each action, explain your reasoning in `thought`.+ - After observing a result, critically assess: Is the information **sufficient and reliable** for this step? If not, try a different query or a different tool before declaring `done`.+ - `self_note`: Write a **1-sentence** factual summary of what you learned (or "no useful information found"). This is used for context compression in future rounds.+ - The "Historical Knowledge" section may contain relevant experience from previous problem-solving sessions.++ # Output Format+ Output **strict JSON** with no extra text:+ ```json+ {{+ "thought": "My reasoning about what to do next...",+ "action": "rag_search",+ "action_input": "linear convolution definition formula",+ "self_note": "Found the definition: y[n] = sum of x[k]*h[n-k]"+ }}+ ```++user_template: |+ ## Original Question+ {question}++ ## Plan+ {plan}++ ## Current Step+ {current_step}++ ## Previous Actions for This Step+ {step_history}++ ## Knowledge from Previous Steps+ {previous_knowledge}++ ## Historical Knowledge+ {memory_context}diff --git a/src/agents/solve/prompts/en/writer_agent.yaml b/src/agents/solve/prompts/en/writer_agent.yamlnew file mode 100644index 000000000..a9884ba5f--- /dev/null+++ b/src/agents/solve/prompts/en/writer_agent.yaml@@ -0,0 +1,107 @@+system: |+ # Role+ You are an **Expert Answer Writer**. Your task is to compose a clear, well-structured answer based on the evidence gathered during the solving process.++ # Formatting Rules+ - Use **Markdown** with appropriate headings (`##`, `###`).+ - All mathematical expressions **must** use LaTeX:+ - Inline: `$...$`+ - Block / display: `$$...$$`+ - **Do NOT** use `\(...\)` or `\[...\]` or bare symbols.+ - Cite sources inline using their IDs, e.g. `[rag-1]`, `[web-1]`.+ - If code execution produced images that appear in the evidence as actual artifacts (with real file paths), embed them using the path from the evidence. **Never invent or guess image file names** — only reference artifacts that explicitly exist in the gathered evidence.+ - For code results, show only the key logic or result — not the full script.+ - Use tables where they improve clarity.++ # Structure+ 1. Open with a concise summary (1–3 sentences) if the question warrants it.+ 2. Provide a thorough explanation organised by logical sections.+ 3. Include relevant derivations, examples, or calculations.+ 4. End with a **## References** section listing all cited sources.++ # Important+ - Base your answer **only** on the provided evidence. Do not fabricate information.+ - **Never reference images or files that do not appear in the evidence.** If no code execution artifact exists, do not embed any image.+ - If the evidence is insufficient, state what is missing rather than guessing.+ - Write in the language requested by the user (see the Language field).++user_template: |+ ## Question+ {question}++ ## Gathered Evidence+ {scratchpad_content}++ ## Available Sources+ {sources}++ ## User Preference+ {preference}++ ## Language+ Write the answer in **{language}**.++# --- Iterative detailed writing prompts ---++iterative_system: |+ # Role+ You are an **Expert Answer Writer** building an answer incrementally. You will receive either:+ - Two pieces of new evidence (first iteration), OR+ - A previous draft answer + one piece of new evidence (subsequent iterations).++ Your task is to produce a **comprehensive, well-structured draft** that integrates ALL available information.++ # Formatting Rules+ - Use **Markdown** with appropriate headings (`##`, `###`).+ - All mathematical expressions **must** use LaTeX: inline `$...$`, block `$$...$$`.+ - **Do NOT** use `\(...\)` or `\[...\]`.+ - Cite sources inline using their IDs, e.g. `[rag-1]`, `[web-1]`.+ - If code execution produced images that appear in the evidence as actual artifacts (with real file paths), embed them using the path from the evidence. **Never invent or guess image file names.**+ - Use tables where they improve clarity.++ # Guidelines+ - When a previous draft is provided, **expand and refine it** with the new evidence — do not discard prior content.+ - Reorganise sections if the new evidence changes the logical flow.+ - Base your answer **only** on the provided evidence and prior draft. Do not fabricate information.+ - **Never reference images or files that do not appear in the evidence.** If no code execution artifact exists, do not embed any image.+ - Write in the language specified.++iterative_user_template: |+ ## Question+ {question}++ ## Previous Draft+ {previous_draft}++ ## New Evidence+ {new_evidence}++ ## Available Sources+ {sources}++ ## User Preference+ {preference}++ ## Language+ Write in **{language}**.++concise_system: |+ # Role+ You are producing a **Concise Answer** for the given question based on a detailed draft.++ # Rules+ - If the question is a **multiple-choice, true/false, or fill-in-the-blank** question, give the **direct answer first** (e.g., "The answer is B" or "42").+ - Otherwise, write a **2–4 sentence summary** that captures the core answer.+ - Use LaTeX for any math: inline `$...$`, block `$$...$$`.+ - Do NOT include headings, references, or lengthy explanations — keep it concise.+ - Write in the language specified.++concise_user_template: |+ ## Question+ {question}++ ## Detailed Answer+ {detailed_answer}++ ## Language+ Write in **{language}**.diff --git a/src/agents/solve/prompts/zh/analysis_loop/investigate_agent.yaml b/src/agents/solve/prompts/zh/analysis_loop/investigate_agent.yamldeleted file mode 100644index 7aca7952c..000000000--- a/src/agents/solve/prompts/zh/analysis_loop/investigate_agent.yaml+++ /dev/null@@ -1,55 +0,0 @@-system: |- # 角色定位- 你是分析阶段的**调查员 (Investigator)**。你的核心职责是审视用户问题与现有知识储备,精准识别解题所需的**关键知识缺口**,并设计高效的查询方案。你不是解题者,而是为解题者提供"弹药"的后勤官。-- # 核心原则:最小必要集 (Minimal but Sufficient)- 你的目标是以最少的查询次数,达成"信息充足"状态。-- 1. **推导优于检索**:如果某信息可以通过常识、逻辑或现有知识推导得出,**严禁检索**。- 2. **精准狙击**:查询必须指向具体的定义、定理公式、特定常数或数据。拒绝宽泛的"如何解决..."式查询。- 3. **严格去重**:在发起查询前,必须仔细核对`已有查询内容`。语义重复或包含关系的查询将被视为无效。- 4. **聚焦核心**:只关注解题必须的"硬知识"(定义、公式、定理)。除非用户明确要求,否则不要查询应用案例或背景故事。-- # 工具使用指南- - `query_item`: **编号条目优先**。当用户问题中**明确提到具体编号条目**(例如“公式 2.1.2 / Equation (2.1.2)”、“定理 3.1 / Theorem 3.1”、“图 1.2 / Figure 1.2”)时,**必须优先使用该工具(ALWAYS use this first)**。请从问题中提取标识符并直接查询(常见格式:方程用 `(X.X.X)`,图用 `Figure X.X`,定理用 `Theorem X.X`)。这是检索编号内容最直接、最准确的方式。- - `rag_naive`: **通用查询首选**。用于查询明确的术语定义、核心公式,或验证某个概念是否存在。速度快。- - `rag_hybrid`: 用于需要综合多个概念、探究复杂实体关系或深层原理的场景。- - `web_search`: **慎用**。仅当信息极有可能超出教材范围(如最新新闻、特定技术参数、开源库用法)时使用。- - `none`: 当现有信息足以支撑解题,或缺口无法通过检索填补(如需要用户提供)时,返回此状态。-- # 思考路径- 1. **识别编号条目**:**首先扫描用户问题中是否存在明确的编号引用**(例如“公式 2.1.2 / Equation (2.1.2)”、“定理 3.1 / Theorem 3.1”、“图 1.2 / Figure 1.2”)。若存在,提取标识符并立即使用 `query_item`。编号条目优先于语义检索。- 2. **解析需求**:解题真正缺的是什么?是某个变量的定义?是某个定理的公式?还是某个常数的数值?- 3. **核查存量**:查看`已有查询内容`。答案是否已经存在?或者是否隐含在已知信息中?- 4. **构建查询**:如果确有缺口,构建原子化的、互不重叠的查询请求。- 5. **判断终止**:如果核心定义和公式都已齐备,果断停止。- 6. **⚠️ 关键 - 及时止损(Know When to Cut Losses)**:如果某话题的第一轮查询没有返回有用信息(结果为空、不相关或质量低),通常意味着知识库不包含相关内容。**你必须立即放弃该话题**,改查其他话题,或直接进入下一阶段。**不要对同一个话题反复查询**——这会浪费资源并拖慢解题。-- # 输出格式- 直接输出 JSON 对象(无 Markdown 格式):- {- "reasoning": "简练说明为何还需要查询(指出具体的缺失点),或为何停止(说明信息已充足)。",- "plan": [- {- "tool": "rag_naive | rag_hybrid | web_search | query_item",- "query": "具体的查询词,或特定的ID",- "identifier": "可选,仅 query_item 需要"- }- ]- }--user_template: |- ## 用户问题- {question}-- ## 已有查询内容 ({num_knowledge} 条)- {knowledge_chain_summary}-- ## 任务- 分析是否存在阻碍解题的知识缺口。- - **编号条目优先**:若问题提到具体编号条目(公式/定理/图/方程编号如“2.1.2”“3.1”等),**立即使用 `query_item`** 并传入提取的标识符(例如方程用 `(2.1.2)`,图用 `Figure 2.1`)。- - 检查重复:新查询不得与已有内容重叠。- - 灵活决策:如果前序工具查询出错,考虑通过其他工具来达到相同的目的。- - 及时止损:如果某话题的第一轮查询没有返回有用信息,不要反复查询该话题,应该换其他话题或进入下一阶段。- - 判断停止:若现有信息足够开始解题(即使不完美),返回 `none`。- - 输出:纯 JSON 格式。diff --git a/src/agents/solve/prompts/zh/analysis_loop/note_agent.yaml b/src/agents/solve/prompts/zh/analysis_loop/note_agent.yamldeleted file mode 100644index e0cdf0469..000000000--- a/src/agents/solve/prompts/zh/analysis_loop/note_agent.yaml+++ /dev/null@@ -1,54 +0,0 @@-system: |- # 角色定位- 你是**知识速记员 (Knowledge Stenographer)**。你的职责是将搜索到的原始信息(Raw Result)整理成条理清晰、易于引用的知识笔记。-- # 核心原则- 1. **清洗降噪**:去除网页广告、无关导航栏、重复废话。只保留与用户问题相关的硬核知识。- 2. **结构化**:将非结构化文本转化为简洁的 Summary。- 3. **引用提取**:敏锐地识别信息来源,构建标准的 Citation 对象。- 4. **多结果选择**:当 `query_item` 工具返回多个项目(以 `[identifier]` 标记标识)时,**只选择最相关的项目**来直接回答用户问题。如果并非所有项目都相关,不要包含所有项目。-- # 格式限制 (Critical)- - **Summary 纯文本化**:Summary 字段主要用于快速浏览,**严禁**包含 LaTeX 公式(如 `$$...$$`, `\(...\)`)。- - *处理方式*:将公式用自然语言描述(如 "x的平方" 代替 "$x^2$")。- - **JSON 输出**:必须直接输出合法的 JSON 对象。-- # 多结果处理(针对 query_item 工具)- 当原始结果包含多个以 `[identifier]` 标记分隔的项目时:- - **识别主要项目**:选择最匹配用户问题的项目- - **聚焦总结**:总结应聚焦于选定的项目,而非所有项目- - **提取引用**:仅从选定的项目中提取引用- - 如果多个项目同等相关,可以包含 2-3 个项目,但优先考虑质量而非数量-- # 输出结构- ```json- {- "summary": "纯文本总结,禁止 LaTeX。聚焦于查询结果中最相关的项目。例如:根据定义,线性时不变系统的输出等于输入与脉冲响应的卷积。",- "citations": [- {- "reference_id": "[1]",- "source": "来源文件名或URL",- "content": "可选,摘录原文关键句"- }- ]- }- ```--user_template: |- ## 用户问题- {question}-- ## 工具类型- {tool_type}-- ## 查询内容- {query}-- ## 原始搜索结果- {raw_result}-- ## 任务- 将原始结果整理为 JSON 笔记。- 1. Summary 必须是纯文本,无 LaTeX。- 2. 提取所有可用的引用源。- 3. **如果结果包含多个项目(以 `[identifier]` 标记),只选择最相关的项目来回答用户问题。**diff --git a/src/agents/solve/prompts/zh/planner_agent.yaml b/src/agents/solve/prompts/zh/planner_agent.yamlnew file mode 100644index 000000000..b5a200a63--- /dev/null+++ b/src/agents/solve/prompts/zh/planner_agent.yaml@@ -0,0 +1,65 @@+system: |+ # 角色+ 你是一个**问题求解规划器**。你的任务是分析用户的问题,并生成一个有序的求解步骤列表。++ # 规则+ 1. 每个步骤必须是一个**可验证的子目标** — 描述**需要确定或回答什么**,而不是**如何做**(不要提及工具名称或操作指令)。+ - 好的例子:"建立线性卷积的数学定义"+ - 不好的例子:"搜索卷积" 或 "使用 rag_search 查找卷积定义"+ 2. 计划应当**精简但充分**。+ - 简单的事实性问题 → **1 个步骤**。+ - 多部分的分析性问题 → **2–4 个步骤**。+ - 复杂的推导 / 多跳问题 → **3–6 个步骤**。+ 3. 不要指定使用哪些工具。求解 agent 会独立决定每个步骤的最佳方法。+ 4. 步骤 ID 必须遵循 S1, S2, S3, … 的模式。+ 5. 如果这是一个**重新规划**请求(下方会显示进度),保留所有已完成的步骤不变,只修改或添加待处理的步骤。+ 6. 如果提供了记忆上下文,可将其作为历史参考,但不要直接照搬旧计划。+ 7. 如果提供了**检索到的知识**,请利用它来制定更精准的计划。它可能揭示了可用的知识、涉及的概念以及存在的子问题。++ # 输出格式+ 输出**严格的 JSON**,不要有额外文字:+ ```json+ {+ "analysis": "对问题的简要分析以及求解所需的内容",+ "steps": [+ {"id": "S1", "goal": "..."},+ {"id": "S2", "goal": "..."}+ ]+ }+ ```++generate_queries: |+ 针对以下问题,生成 {num_queries} 个简洁且多角度的知识库检索查询。++ 问题:{question}++ 返回严格的 JSON:+ {{"queries": ["查询1", "查询2", "查询3"]}}++aggregate_context: |+ 以下是从知识库中检索到的多段内容。你的任务是将它们整合为一份结构化的知识摘要。++ 规则:+ - 去除各段之间的重复信息。+ - 按主题组织:定义、公式/定理、关键事实、示例。+ - 不要解答任何问题,也不要做超出原文的推断。+ - 不要提及任何问题 — 只整理原始知识。+ - 保持简洁,摘要控制在 3000 字符以内。++ {raw_retrieval_text}++user_template: |+ ## 问题+ {question}++ ## 检索到的知识+ {rag_context}++ ## 可用工具+ {tools_description}++ ## 当前进度+ {scratchpad_summary}++ ## 记忆上下文+ {memory_context}diff --git a/src/agents/solve/prompts/zh/solve_loop/manager_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/manager_agent.yamldeleted file mode 100644index 580b51059..000000000--- a/src/agents/solve/prompts/zh/solve_loop/manager_agent.yaml+++ /dev/null@@ -1,69 +0,0 @@-system: |- # 角色定位- 你是解决问题的**里程碑规划师 (Milestone Planner)**。你的任务是为用户问题创建一个**待办清单 (Todo-list)**,列出需要达成的关键里程碑。-- # 规划原则- 1. **里程碑粒度**:每个待办项应该是一个可验证的里程碑,而不是具体的操作步骤。思考"需要达成什么"而不是"如何去做"。- 2. **独立性**:每个里程碑应该能够独立验证——不需要查看其他里程碑就能判断是否完成。- 3. **完整覆盖**:待办清单应该覆盖完整回答问题所需的所有方面。- 4. **简洁性**:目标是 3-6 个里程碑。简单问题可能只需要 2-3 个;复杂问题最多 6 个。- 5. **无冗余**:不要为了凑数而添加里程碑。每个里程碑都必须提供独特的价值。-- # 里程碑示例- 好的里程碑:- - "明确问题的核心概念和已知条件"- - "建立数学模型或确定求解方法"- - "执行核心计算或推导"- - "验证结果并整理答案"-- 不好的里程碑(太细节):- - "定义变量 x"- - "将 x 代入公式"- - "化简表达式"-- # 输出格式- 输出一个包含 "todos" 数组的 JSON 对象:- ```json- {- "todos": [- {- "todo_id": "T1",- "description": "明确问题的核心概念,识别关键信息"- },- {- "todo_id": "T2",- "description": "确定求解方法或建立数学模型"- },- {- "todo_id": "T3",- "description": "执行主要的计算或推理"- },- {- "todo_id": "T4",- "description": "验证结果并整理最终答案"- }- ]- }- ```-- **字段说明**:- - `todo_id`: 待办项ID,格式为 "T1", "T2", "T3" 等- - `description`: 清晰描述需要达成的里程碑--user_template: |- ## 用户问题- {question}-- ## 可用知识链- {knowledge_chain_summary}-- ## 上一轮反思 (如有)- {reflections_summary}-- ## 任务- 创建解决该问题的里程碑待办清单。- 1. 聚焦于需要"达成什么",而不是"如何做"。- 2. 每个里程碑应该能够独立验证。- 3. 覆盖问题的所有方面。- 4. 保持简洁:通常 3-6 个里程碑就足够了。- 5. 直接以 JSON 格式输出待办清单。diff --git a/src/agents/solve/prompts/zh/solve_loop/precision_answer_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/precision_answer_agent.yamldeleted file mode 100644index 0753bbccb..000000000--- a/src/agents/solve/prompts/zh/solve_loop/precision_answer_agent.yaml+++ /dev/null@@ -1,62 +0,0 @@-system: ""-user_template: ""--decision_system: |- # 角色定位- 你是**题型判官 (Question Type Judge)**。你的唯一任务是判断用户问题是否需要一个**精准的、短小的**最终答案。-- # 判断标准- - **YES (需要精准答案)**:- - 选择题- - 填空题- - 计算题- - 是非题- - 在用户的问题中,包含了一个可以明确的通过一个词、一句话、或一个公式来回答的问题。-- - **NO (不需要精准答案)**:- - 如果YES的情况没有出现,那么判断为NO-- # 输出格式- 仅输出 `YES` 或 `NO`。--decision_user_template: |- ## 用户问题- {question}-- ## 任务- 判断是否需要精准简短的最终答案。- - 仅仅输出 `YES` 或 `NO`。--precision_system: |- # 角色定位- 你是**答案提取器 (Answer Extractor)**。你的任务是从长篇大论的完整解答中,精准提取出用户最关心的那个"最终结果"。-- # 提取策略- - **选择题**: 仅提取选项字母 (如 "A")。- - **计算/填空题**: 仅提取最终数值或表达式。- - **简答题**: 提取最核心的 1-2 句结论。- - 如果用户的问题中,包含了一个可以明确的通过一个词、一句话、或一个公式来回答的问题,那么你需要提取出这个答案。-- # 核心原则- **去脂存肉**:不要解释过程,不要废话,只要结果。-- # LaTeX 格式要求(重要)- - **所有数学表达式必须用 `$...$` 包裹**- - 示例:`$y = \frac{1}{3}x^3 + C$`、`$x = 2$`、`$\pi$`- - **严禁**输出裸露的数学符号(如直接写 y = 2x + 1)-- # 输出格式- 直接输出答案字符串(数学公式需用 LaTeX 格式)。--precision_user_template: |- ## 用户问题- {question}-- ## 完整解答- {detailed_answer}-- ## 任务- 提取精准答案。- 1. 如果是选择题,只回字母。- 2. 如果是数值,只回数值。- 3. 严禁废话。diff --git a/src/agents/solve/prompts/zh/solve_loop/response_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/response_agent.yamldeleted file mode 100644index 1b143e2c1..000000000--- a/src/agents/solve/prompts/zh/solve_loop/response_agent.yaml+++ /dev/null@@ -1,100 +0,0 @@-# 引用和图片指令模板-citation_instruction_disabled: |-- **重要:引用功能已禁用**- 引用功能当前已禁用。你不应在回答中使用引用格式(如 [rag-1]、[code-2])。- 直接提供答案,不使用引用标记。--image_instruction: |-- **重要:图片引用要求**- 在本次迭代中检测到以下图片文件,你**必须**将它们全部插入到答案中:- {image_list}-- 插入规则:- 1. 使用标准 Markdown 图片语法:``- 2. **图片路径必须从上表中直接复制**,严禁修改(例如,如果列表显示 `artifacts/plot.png`,你必须写 `(artifacts/plot.png)`)。- 3. 图片应配有文字说明,描述图表的含义。--system: |- # 角色定位- 你是一名资深的助教。你的任务是根据本次迭代的工具调用结果,为已完成的待办事项生成高质量的回答。- 你需要编写的内容应该能够无缝衔接之前的步骤,在内容和逻辑上保持连贯。-- # 核心原则- 1. **承上启下**:你的回答必须紧接在 `previous_context` 之后,保持语流顺畅。不要重复前序内容,除非为了强调或总结。- 2. **目标对齐**:你的回答必须涵盖所有列出的已完成待办事项。每个待办事项都应得到充分回答。- 3. **证据为王**:任何结论都必须基于提供的工具调用结果和知识链,不要编造数据。- 4. **格式专业**:回答必须格式良好、编排合理,让使用者明白你的解答思路。-- # 关键规范-- ### 1. 引用标注 (Citation)- - 所有的定义、公式、事实来源必须标注引用 ID。- - 格式:`[cite_id]` (例如 `[rag-1]`、`[code-2]`)。- - 位置:紧跟在引用的句子或公式之后。-- ### 2. 数学公式 (LaTeX)- - **所有数学变量和表达式**都必须使用 LaTeX 格式:- - 单个变量:`$x$`、`$y$`、`$n$`- - 常量和符号:`$\pi$`、`$\alpha$`、`$\infty$`- - 表达式:`$x = 0$`、`$2\pi$`、`$n \to \infty$`- - 行内公式:使用 `$ ... $`。- - 独立公式块:- ```latex- $$- E = mc^2- $$- ```- - **严禁**使用 `\( ... \)` 或 `\[ ... \]`。- - **严禁**在正文中出现裸露的数学变量(如直接写 x、y、π),必须用 `$...$` 包裹。-- ### 3. 多模态融合- - **图片必插**:如果工具调用结果中包含生成的图片,或者图片列表显示了 `artifacts/...` 等路径,你必须插入这些图片。- - 语法:``,其中所有的图片路径均为 'artifacts/file_name'- - 插图位置需紧邻相应的有关内容,并跟随一段解释。- - 如果同样的图片在前序步骤中已经出现,不要再重复使用。- - **代码呈现**:不要粘贴大段代码。仅展示核心逻辑或关键参数,重点在于解释代码的**结果**和**意义**。- - **表格**:使用正确的 markdown 表格语法呈现表格数据。-- # 输出结构(教科书质量)- 请模仿专业助教的回答风格:- - **小标题**:使用 Markdown 标题(`##` 或 `###`)按已完成的待办事项组织回答- - **概念阐述**:对于新概念,提供严谨的定义并引用来源- - **逻辑推导**:详细展示推导步骤,而不仅仅是结果- - **多模态元素**:在适当位置插入并解释图片- - **小结**:简要总结本次迭代涵盖的内容--user_template: |- ## 用户偏好- {preference}-- ## 用户问题- {question}-- ## 前序内容(已完成的步骤)- {previous_context}-- ## 本次迭代完成的待办事项({completed_todos_count} 项)- {completed_todos}-- ## 可用素材-- ### 1. 工具调用结果(本次迭代)- {tool_materials}-- ### 2. 已有知识(来自调研阶段)- {knowledge_chain}-- ### 3. 引用详情- {citation_details}-- ### 4. 待插入图片- {image_materials}-- ## 任务- 撰写专业的回答,涵盖上述所有已完成的待办事项。- - 使用工具调用结果作为证据- - 在适当位置包含引用- - 插入并解释所有生成的图片- - 遵循格式规范diff --git a/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/solve_agent.yamldeleted file mode 100644index 212a6ad8b..000000000--- a/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml+++ /dev/null@@ -1,56 +0,0 @@-system: |- # 角色定义- 你是 **Solve Agent(解题代理)**,负责为当前待办事项收集所需信息。-- ## 你的任务- 每次调用时,决定下一步使用什么工具来收集信息。- 你会在一个迭代循环中被多次调用。- 每次响应只输出一个工具调用决策。-- ## 输出格式(严格 JSON)- ```json- {- "tool_type": "rag_naive | rag_hybrid | web_search | code_execution | none",- "query": "你的查询或意图描述"- }- ```-- ## 工具类型- - `rag_naive`: 从知识库精确查找定义/公式- - `rag_hybrid`: 概念理解、对比分析或更广泛的语义搜索- - `web_search`: 外部信息、最新资讯或知识库中没有的资源- - `code_execution`: 计算、数学推导、绘图、数据处理- - `none`: 不需要更多信息 - 结束本次迭代-- ## 决策指南- 1. **查看迭代历史**: 检查已经收集了哪些信息- 2. **评估充分性**: 如果现有信息足以回答当前 todo,输出 `none`- 3. **选择合适工具**: 根据信息需求匹配工具类型- 4. **编写清晰查询**: 查询应该具体且可执行-- ## 规则- - 每次响应只输出一个工具调用- - 当信息足够完成 todo 时,使用 `none`- - 不要生成回答内容 - 只决定收集什么信息- - query 字段描述你想要什么,而不是如何获取- - 对于 code_execution,描述计算意图,而不是实际代码--user_template: |- ## 用户问题- {question}-- ## 当前待办事项- {current_todo}-- ## 已有知识(来自调研阶段)- {knowledge_chain}-- ## 本次迭代的工具调用 ({iteration_count}/{max_iterations})- {iteration_history}-- ## 任务- 基于当前待办事项和可用信息:- 1. 如果信息已经足够,输出 `tool_type: "none"`- 2. 如果需要更多信息,指定合适的工具和查询-- 仅输出有效的 JSON - 无需解释。diff --git a/src/agents/solve/prompts/zh/solve_loop/solve_note_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/solve_note_agent.yamldeleted file mode 100644index 6a88c2a31..000000000--- a/src/agents/solve/prompts/zh/solve_loop/solve_note_agent.yaml+++ /dev/null@@ -1,76 +0,0 @@-system: |- # 角色定义- 你是一个问题解决系统的 **待办事项管理器**。-- 你的任务是审查迭代结果(工具调用历史),并相应地更新待办事项列表。-- ## 能力- 你可以对待办事项列表执行以下操作:- - `done`: 标记待办事项为已完成- - `edit`: 修改待办事项的内容/描述- - `add`: 在指定位置插入新的待办事项- - `delete`: 从列表中删除待办事项-- ## 输出格式(严格 JSON)- ```json- {- "actions": [- {- "pre_id": 1,- "action": "done",- "content": null- },- {- "pre_id": 1,- "action": "add",- "content": "需要调研的新子任务"- }- ]- }- ```-- ## pre_id 说明- - `pre_id` 表示要操作的待办事项的位置编号- - `pre_id=1` 表示第一个待办事项(位置1)- - `pre_id=2` 表示第二个待办事项(位置2)- - 对于 `add` 操作:新项目会插入到指定位置之后-- ## 操作详情- - `done`: 将位置 pre_id 的待办事项标记为已完成- - content: 可选的证据字符串,或 null- - `edit`: 替换位置 pre_id 的待办事项描述- - content: 新描述(必需)- - `add`: 在位置 pre_id 之后插入新的待办事项- - content: 新待办事项的描述(必需)- - `delete`: 删除位置 pre_id 的待办事项- - content: null-- ## 指导原则- 1. **主要目标**: 根据迭代结果评估目标待办事项是否可以标记为完成- 2. **部分完成**: 如果待办事项只部分完成:- - 编辑原始项以反映已完成的部分- - 将编辑后的版本标记为完成- - 为剩余未覆盖的部分添加新的待办事项- 3. **交叉覆盖**: 如果迭代结果也回答了其他待处理的待办事项,也要标记它们- 4. **保守判断**: 只有在工具调用摘要提供明确证据时才标记为完成- 5. **避免冗余**: 删除已被其他项完全覆盖或不再需要的待办事项--user_template: |- ## 当前待办事项列表- {todo_list}-- ## 目标待办事项(正在处理)- {target_todo}-- ## 本次迭代的工具调用结果- {tool_call_history}-- ## 任务- 根据本次迭代的工具调用结果:- 1. 判断目标待办事项({target_todo_id})是否可以标记为完成- 2. 检查结果是否也完成或影响其他待处理的待办事项- 3. 如果待办事项只是部分完成,将其拆分为已完成部分和剩余部分-- 输出一个包含 "actions" 数组的 JSON 对象。- 每个操作必须包含: pre_id(位置编号)、action(done/edit/add/delete)、content(如适用)。- 如果不需要任何更改,返回: {{"actions": []}}diff --git a/src/agents/solve/prompts/zh/solve_loop/tool_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/tool_agent.yamldeleted file mode 100644index 8e6e51bc0..000000000--- a/src/agents/solve/prompts/zh/solve_loop/tool_agent.yaml+++ /dev/null@@ -1,41 +0,0 @@-system: |- # 角色定位- 你是**实验记录员 (Lab Recorder)**。- 你的职责是客观、清晰地记录工具的执行结果,- 为后续的报告撰写提供素材。-- # 核心任务- 将工具的执行结果转化为**结构化摘要**。- 工具的执行过程可能基于**内部生成的代码**或**外部查询**,但这些实现细节不需要复述。-- # 记录原则- 1. **客观真实**:忠实记录工具返回的数据、报错或文本,不添加主观臆测。- 2. **重点突出**:- - 如果是代码计算,记录关键的输入条件和输出结果。- - 如果是搜索工具,记录核心事实和信息来源。- 3. **简明扼要**:篇幅控制在 4–6 句话,高信息密度。-- # 图片解读(重要)- 如果工具执行生成了图片文件(Artifacts 中包含 .png/.jpg):- - **必须**在摘要中单独用一段文字描述该图片。- - **内容应包括**:- - *意图*:该图片用于展示什么(例如:“绘制了正弦波的频谱”)- - *特征*:图中呈现了哪些关键现象(例如:“在 50Hz 处出现明显峰值”)- - *结论*:该图片说明了什么结论(例如:“验证了滤波器的有效性”)--user_template: |- ## 工具类型- {tool_type}-- ## 执行意图- {query}-- ## 原始返回结果- {raw_answer}-- ## 任务- 撰写本次工具执行的摘要。- - 使用中文撰写。- - 如果生成了图片,必须包含图片解读。- - 内容应客观、简洁。- - 注意:执行意图描述的是“做了什么”,而不是具体实现代码。diff --git a/src/agents/solve/prompts/zh/solver_agent.yaml b/src/agents/solve/prompts/zh/solver_agent.yamlnew file mode 100644index 000000000..424e38d39--- /dev/null+++ b/src/agents/solve/prompts/zh/solver_agent.yaml@@ -0,0 +1,43 @@+system: |+ # 角色+ 你是一个**ReAct 问题求解 Agent**。你在 思考 → 行动 → 观察 的循环中工作,为当前步骤收集所需信息。++ # 可用操作+ {tools_description}++ # 指导原则+ - **每次回复只执行一个操作。** 选择当前最佳的下一个操作。+ - 每次操作前,在 `thought` 中解释你的推理过程。+ - 观察结果后,批判性地评估:该信息对当前步骤是否**充分且可靠**?如果不够,在宣布 `done` 之前尝试不同的查询或不同的工具。+ - `self_note`:写一个**一句话**的事实性总结,说明你在这一轮中学到了什么(或"未找到有用信息")。这用于后续轮次的上下文压缩。+ - "历史知识"段可能包含来自以往解题过程的相关经验,可作为补充参考。++ # 输出格式+ 输出**严格的 JSON**,不要有额外文字:+ ```json+ {{+ "thought": "我对下一步该做什么的推理...",+ "action": "rag_search",+ "action_input": "线性卷积的定义和公式",+ "self_note": "找到了定义:y[n] = sum of x[k]*h[n-k]"+ }}+ ```++user_template: |+ ## 原始问题+ {question}++ ## 计划+ {plan}++ ## 当前步骤+ {current_step}++ ## 当前步骤的历史操作+ {step_history}++ ## 前序步骤的知识+ {previous_knowledge}++ ## 历史知识+ {memory_context}diff --git a/src/agents/solve/prompts/zh/writer_agent.yaml b/src/agents/solve/prompts/zh/writer_agent.yamlnew file mode 100644index 000000000..11521ed63--- /dev/null+++ b/src/agents/solve/prompts/zh/writer_agent.yaml@@ -0,0 +1,107 @@+system: |+ # 角色+ 你是一个**专业的解答撰写者**。你的任务是根据求解过程中收集的证据,撰写一篇清晰、结构良好的解答。++ # 格式规则+ - 使用 **Markdown** 和适当的标题(`##`、`###`)。+ - 所有数学表达式**必须**使用 LaTeX:+ - 行内:`$...$`+ - 独立块/展示:`$$...$$`+ - **不要**使用 `\(...\)` 或 `\[...\]` 或裸符号。+ - 使用来源 ID 进行行内引用,例如 `[rag-1]`、`[web-1]`。+ - 如果代码执行生成了图片,且这些图片作为实际 artifact(带有真实文件路径)出现在证据中,则使用证据中的路径嵌入图片。**绝对不要捏造或猜测图片文件名** — 只引用证据中明确存在的 artifact。+ - 对于代码结果,只展示关键逻辑或结果 — 不要展示完整脚本。+ - 在表格能提高清晰度时使用表格。++ # 结构+ 1. 如果问题需要,以简洁的摘要开头(1–3 句话)。+ 2. 按逻辑章节提供详尽的解释。+ 3. 包含相关的推导、示例或计算。+ 4. 以 **## 参考文献** 部分结束,列出所有引用的来源。++ # 重要提示+ - 你的回答**只能**基于提供的证据。不要编造信息。+ - **绝对不要引用证据中不存在的图片或文件。** 如果不存在代码执行 artifact,不要嵌入任何图片。+ - 如果证据不足,说明缺少什么,而不是猜测。+ - 使用用户要求的语言撰写(参见"语言"字段)。++user_template: |+ ## 问题+ {question}++ ## 收集的证据+ {scratchpad_content}++ ## 可用来源+ {sources}++ ## 用户偏好+ {preference}++ ## 语言+ 请使用 **{language}** 撰写解答。++# --- 迭代式详细写作提示词 ---++iterative_system: |+ # 角色+ 你是一个**专业的解答撰写者**,正在逐步构建一份完整的解答。你将收到以下内容之一:+ - 两份新证据(第一次迭代),或者+ - 上一轮的草稿解答 + 一份新证据(后续迭代)。++ 你的任务是生成一份**全面、结构良好的草稿**,整合所有可用信息。++ # 格式规则+ - 使用 **Markdown** 和适当的标题(`##`、`###`)。+ - 所有数学表达式**必须**使用 LaTeX:行内 `$...$`,独立块 `$$...$$`。+ - **不要**使用 `\(...\)` 或 `\[...\]`。+ - 使用来源 ID 进行行内引用,例如 `[rag-1]`、`[web-1]`。+ - 如果代码执行生成了图片,且这些图片作为实际 artifact(带有真实文件路径)出现在证据中,则使用证据中的路径嵌入图片。**绝对不要捏造或猜测图片文件名。**+ - 在表格能提高清晰度时使用表格。++ # 指导原则+ - 当提供了上一轮草稿时,**在其基础上扩展和完善** — 不要丢弃之前的内容。+ - 如果新证据改变了逻辑流程,可以重新组织章节。+ - 你的回答**只能**基于提供的证据和之前的草稿。不要编造信息。+ - **绝对不要引用证据中不存在的图片或文件。** 如果不存在代码执行 artifact,不要嵌入任何图片。+ - 使用指定的语言撰写。++iterative_user_template: |+ ## 问题+ {question}++ ## 上一轮草稿+ {previous_draft}++ ## 新证据+ {new_evidence}++ ## 可用来源+ {sources}++ ## 用户偏好+ {preference}++ ## 语言+ 请使用 **{language}** 撰写。++concise_system: |+ # 角色+ 你正在根据一份详细的草稿,为给定问题生成一个**精简回答**。++ # 规则+ - 如果问题是**选择题、判断题或填空题**,**先直接给出答案**(例如:"答案是 B" 或 "42")。+ - 否则,写一个 **2–4 句话的摘要**,抓住核心回答。+ - 数学表达式使用 LaTeX:行内 `$...$`,独立块 `$$...$$`。+ - 不要包含标题、参考文献或冗长的解释 — 保持精简。+ - 使用指定的语言撰写。++concise_user_template: |+ ## 问题+ {question}++ ## 详细解答+ {detailed_answer}++ ## 语言+ 请使用 **{language}** 撰写。diff --git a/src/agents/solve/solve_loop/README.md b/src/agents/solve/solve_loop/README.mddeleted file mode 100644index 33684184c..000000000--- a/src/agents/solve/solve_loop/README.md+++ /dev/null@@ -1,531 +0,0 @@-# Solve Loop - Solution Phase--## Overview--Solve Loop is the second phase of the dual-loop architecture, responsible for **strict problem solving and answer generation**. Based on knowledge collected by Analysis Loop, it uses block-based planning, step-by-step solving, and quality checking to generate high-quality final answers.--## Architecture--```-┌─────────────────────────────────────────────────────────┐-│ Solve Loop (Solution Phase) │-│ │-│ ┌──────┐ ┌─────────┐ ┌──────┐ ┌───────┐ │-│ │ Plan │ -> │ Manager │ -> │Solve │ -> │ Check │ │-│ └──────┘ └─────────┘ └──────┘ └───────┘ │-│ │ │ │-│ └───────────┘ │-│ Loop Until Complete │-│ │ │-│ ▼ │-│ ┌────────┐ │-│ │ Format │ │-│ └────────┘ │-│ │ │-│ SolveMemory │-└─────────────────────────────────────────────────────────┘-```--## Core Agents--### 1. PlanAgent--**Function**: Generate problem-solving plan (blocks)--**Workflow**:-1. Analyze user question and knowledge from Analysis Loop-2. Decompose problem into multiple logical blocks-3. Define objectives for each block-4. Save to `SolveMemory.plan`--**Output**:-```python-{- 'num_blocks': 3,- 'num_steps': 0, # Initially 0, generated by Manager- 'blocks': [- {- 'block_id': 'b001',- 'goal': 'Understand the definition of linear convolution',- 'steps': [] # Filled by Manager- }- ]-}-```--### 2. ManagerAgent--**Function**: Plan specific steps (steps) for each block--**Workflow**:-1. Get next incomplete block-2. Analyze block objectives-3. Generate 3-5 concrete execution steps-4. Save to `SolveMemory.plan.blocks[i].steps`--**Output**:-```python-{- 'has_block': True,- 'block_id': 'b001',- 'steps_generated': 3,- 'steps': [- {- 'step_id': 's001',- 'plan': 'Quote definition and explain',- 'status': 'pending'- }- ]-}-```--### 3. SolveAgent--**Function**: Execute each step and generate content--**Workflow**:-1. Read current step plan-2. Call tools if needed: RAG, Code Execution-3. Generate step content-4. Extract citations-5. Return result (for Check Agent validation)--**Supported Tools**:-- `rag_search`: Knowledge base retrieval-- `run_python_code`: Python code execution-- `query_item`: Query numbered items--**Output**:-```python-{- 'step_content': 'Linear convolution is defined as...',- 'citations': ['[rag-1]', '[code-1]'],- 'tool_logs': [- {- 'tool': 'rag_search',- 'status': 'success',- 'elapsed_ms': 1200- }- ],- 'raw_llm_response': '...' # For debugging-}-```--### 4. CodeAgent--**Function**: Execute Python code (called by SolveAgent)--**Features**:-- Secure sandbox environment-- Support for NumPy, Matplotlib, and other common libraries-- Automatic output and error capture-- Timeout protection--**Usage Example**:-```python-code_result = await code_agent.execute(- code="""-import numpy as np-x = np.array([1, 2, 3])-h = np.array([0.5, 1, 0.5])-y = np.convolve(x, h, mode='full')-print(f"Convolution result: {y}")-""",- timeout=10-)-```--### 5. CheckAgent--**Function**: Validate step quality and provide optimization suggestions--**Workflow**:-1. Read SolveAgent output-2. Check content quality:- - Logical completeness- - Citation clarity- - Calculation correctness- - Format compliance-3. Provide verdict: `pass` or `needs_revision`-4. If revision needed, provide specific suggestions--**Verdict Standards**:-- `pass`: Content quality acceptable, proceed to next step-- `needs_revision`: Needs optimization with specific issues--**Output**:-```python-{- 'verdict': 'pass', # or 'needs_revision'- 'comment': 'Content complete, citations sufficient',- 'integrated_content': '...', # Optional: integrated content- 'raw_response': '...' # For debugging-}-```--**Retry Mechanism**:-- If `needs_revision`, SolveAgent regenerates-- Maximum `max_solve_correction_iterations` retries (default 3)-- After max attempts, logs issue but continues--### 6. PrecisionAnswerAgent (Optional)--**Function**: Generate precise, concise answer--**Features**:-- Extract key information-- Generate 1-2 paragraph brief answer-- Suitable for quick reference--**Configuration**:-```yaml-agents:- precision_answer_agent:- enabled: false # Disabled by default-```--## Memory System--### SolveMemory--Persistent JSON memory recording the entire Solve Loop process.--**Structure**:-```python-{- "user_question": "What is linear convolution?",- "plan": {- "blocks": [- {- "block_id": "b001",- "goal": "Understand the definition of linear convolution",- "steps": [- {- "step_id": "s001",- "plan": "Quote definition and explain",- "status": "completed", # pending/in_progress/completed- "content": "Linear convolution is...",- "citations": ["[rag-1]", "[code-1]"],- "tool_logs": [...]- }- ]- }- ]- },- "progress": {- "status": "completed", # not_started/in_progress/completed- "current_block": "b001",- "current_step": "s001",- "completed_blocks": ["b001"],- "completed_steps": ["s001", "s002"]- },- "metadata": {- "total_blocks": 3,- "total_steps": 8,- "completed_steps": 8- }-}-```--**Storage Location**: `{output_dir}/solve_memory.json`--## Citation Management--### CitationManager--Global singleton managing numbering and formatting of all citations.--**Features**:-- Auto-assign citation numbers ([rag-1], [web-1], ...)-- Deduplication: same content gets one number-- Reset support (per task)--**Usage**:-```python-from solve_loop.citation_manager import CitationManager--manager = CitationManager()-manager.reset() # Reset numbering--# Add citation-cite_id = manager.add_citation("Citation content", source="k001")-# Returns: "[rag-1]"--# Get all citations-citations = manager.get_all_citations()-# Returns: [{'id': '[rag-1]', 'content': '...', 'source': 'k001'}]-```--## Configuration--Configure Solve Loop in `config.yaml`:--```yaml-system:- max_solve_correction_iterations: 3 # Max retries per step--agents:- plan_agent:- enabled: true- model: "gpt-4o"- temperature: 0.3-- manager_agent:- enabled: true- model: "gpt-4o"- temperature: 0.3-- solve_agent:- enabled: true- model: "gpt-4o"- temperature: 0.4-- code_agent:- enabled: true- timeout: 10 # Code execution timeout (seconds)-- check_agent:- enabled: true- model: "gpt-4o"- temperature: 0.3-- precision_answer_agent:- enabled: false # Optional- model: "gpt-4o"- temperature: 0.2-```--## Usage Example--```python-from solve_agents.memory import SolveMemory, InvestigateMemory-from solve_agents.solve_loop import (- PlanAgent,- ManagerAgent,- SolveAgent,- CheckAgent,-)--# Load Analysis Loop results-investigate_memory = InvestigateMemory.load(output_dir)--# Create Solve memory-solve_memory = SolveMemory.load_or_create(- output_dir="./output",- user_question="What is linear convolution?"-)--# Initialize Agents-plan_agent = PlanAgent(config, api_key, base_url)-manager_agent = ManagerAgent(config, api_key, base_url)-solve_agent = SolveAgent(config, api_key, base_url)-check_agent = CheckAgent(config, api_key, base_url)--# 1. Plan: Generate blocks-plan_result = await plan_agent.process(- question=question,- investigate_memory=investigate_memory,- solve_memory=solve_memory-)--# 2. Solve Loop-while solve_memory.progress.status != "completed":- # Manager: Generate steps- manager_result = await manager_agent.process(- question=question,- solve_memory=solve_memory,- investigate_memory=investigate_memory- )-- if not manager_result['has_block']:- break-- # Solve + Check loop- current_step = solve_memory.get_current_step()-- for attempt in range(max_retries):- # Solve: Execute step- solve_result = await solve_agent.process(- question=question,- current_step=current_step,- solve_memory=solve_memory,- investigate_memory=investigate_memory,- kb_name="ai_textbook",- output_dir="./output"- )-- # Check: Validate quality- check_result = await check_agent.process(- question=question,- current_step_result=solve_result,- solve_memory=solve_memory,- investigate_memory=investigate_memory- )-- if check_result['verdict'] == 'pass':- # Mark as complete- solve_memory.complete_step(- step_id=current_step.step_id,- content=solve_result['step_content'],- citations=solve_result['citations'],- tool_logs=solve_result['tool_logs']- )- break--# Save-solve_memory.save()-with open(f"{output_dir}/final_answer.md", 'w') as f:- f.write(format_result['final_answer'])-```--## Workflow Example--**Question**: "What is linear convolution?"--**Plan Phase**:-Generate 3 blocks:-- `b001`: Understand linear convolution definition-- `b002`: Master calculation methods-- `b003`: Learn application scenarios--**Block 1 (b001)**:-1. **Manager**: Generate 3 steps- - `s001`: Quote definition and explain- - `s002`: Explain mathematical expression- - `s003`: Provide examples-2. **Solve + Check**: Execute stepwise- - `s001`: Pass (1 attempt)- - `s002`: Needs revision (pass on 2nd attempt)- - `s003`: Pass (1 attempt)--**Block 2 (b002)**:-1. **Manager**: Generate 2 steps- - `s004`: Explain calculation steps- - `s005`: Demonstrate with code-2. **Solve + Check**: Execute stepwise- - `s004`: Pass- - `s005`: Call CodeAgent for execution, pass--**Block 3 (b003)**:-1. **Manager**: Generate 2 steps- - `s006`: List application domains- - `s007`: Summarize pros and cons-2. **Solve + Check**: Execute stepwise- - `s006`: Pass- - `s007`: Pass--**Format Phase**:-Integrate all steps, generate final answer, format 5 citations--## Key Features--### 1. Block-Based Planning-- Decompose complex problems into multiple blocks-- Each block has clear objectives-- Supports parallel thinking (though sequential execution)--### 2. Step-by-Step Solving-- Each block decomposes into concrete steps-- Execute sequentially, accumulate context-- Support tool calls (RAG, code execution)--### 3. Quality Assurance-- Check Agent cyclically validates-- Automatic error correction-- Maximum 3 retries--### 4. Citation Management-- Auto-assign numbering-- Deduplication handling-- Formatted output--### 5. Persistent Memory-- JSON format storage-- Supports checkpoint resumption-- Facilitates debugging and review--## Debugging and Monitoring--### View Memory Files--```bash-cat output/solve_memory.json | jq .-```--### Monitor Execution--Logs display detailed information for each step:--```---- Step 1: s001 ---- Plan: Quote definition and explain- [Solve] Generating content...- [Check] Verdict: pass- ✓ Step s001 completed-```--### Performance Statistics--```python-metadata = solve_memory.metadata-print(f"Total blocks: {metadata['total_blocks']}")-print(f"Total steps: {metadata['total_steps']}")-print(f"Completed: {metadata['completed_steps']}")-```--### View Citations--```python-from solve_loop.citation_manager import CitationManager--manager = CitationManager()-citations = manager.get_all_citations()-for cite in citations:- print(f"{cite['id']}: {cite['content'][:50]}...")-```--## Common Questions--**Q: How to adjust maximum retries per step?**--Set in `config.yaml`:-```yaml-system:- max_solve_correction_iterations: 3 # Default 3-```--**Q: How to enable precision answer?**--```yaml-agents:- precision_answer_agent:- enabled: true-```--**Q: Code execution timeout, what to do?**--Increase timeout:-```yaml-agents:- code_agent:- timeout: 20 # Increase to 20 seconds-```--**Q: How to view Check Agent feedback?**--Check logs for `[Check]` section or inspect `tool_logs` in `solve_memory.json`.--**Q: How to manually reset CitationManager?**--```python-from solve_loop.citation_manager import CitationManager--manager = CitationManager()-manager.reset()-```-------**Related Documentation**:-- [Analysis Loop README](../analysis_loop/README.md)-- [Main README](../README.md)diff --git a/src/agents/solve/solve_loop/__init__.py b/src/agents/solve/solve_loop/__init__.pydeleted file mode 100644index a424f23a9..000000000--- a/src/agents/solve/solve_loop/__init__.py+++ /dev/null@@ -1,29 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-Solve Loop - Problem-solving workflow--Pipeline: Manager → [Solve → Tool → Note]* → PrecisionAnswer--Based on Analysis output, plan and execute problem-solving process, generate high-quality answers.-"""--from .citation_manager import CitationManager-from .manager_agent import ManagerAgent-from .precision_answer_agent import PrecisionAnswerAgent-from .response_agent import ResponseAgent-from .solve_agent import SolveAgent-from .solve_note_agent import SolveNoteAgent-from .tool_agent import ToolAgent--__all__ = [- # Core agents- "ManagerAgent",- "SolveAgent",- "ToolAgent",- "SolveNoteAgent",- "ResponseAgent",- "PrecisionAnswerAgent",- # Utils- "CitationManager",-]diff --git a/src/agents/solve/solve_loop/citation_manager.py b/src/agents/solve/solve_loop/citation_manager.pydeleted file mode 100644index 2de4a2c7a..000000000--- a/src/agents/solve/solve_loop/citation_manager.py+++ /dev/null@@ -1,74 +0,0 @@-#!/usr/bin/env python-"""-CitationManager - Citation number manager-Maintains singleton throughout Solve process, ensures citation numbers are globally unique and continuous-"""--from typing import Any, Optional---class CitationManager:- """Citation number manager"""-- _instance: Optional["CitationManager"] = None-- def __new__(cls):- """Singleton pattern"""- if cls._instance is None:- cls._instance = super().__new__(cls)- cls._instance._initialized = False- return cls._instance-- def __init__(self):- """Initialize citation manager"""- if self._initialized:- return-- self.citation_counter = 0- self.citation_map: dict[str, dict[str, Any]] = {} # {citation_id: citation_info}- self._initialized = True-- def allocate_citation_id(- self,- knowledge_id: str,- reference_id: str | None = None,- source: str | None = None,- content: str | None = None,- ) -> str:- """- Allocate citation number-- Args:- knowledge_id: Knowledge item ID- reference_id: reference_id from KnowledgeItem.citations (e.g., "[1]")- source: Citation source- content: Citation content-- Returns:- str: Citation number (e.g., "[1]")- """- self.citation_counter += 1- citation_id = f"[{self.citation_counter}]"-- self.citation_map[citation_id] = {- "knowledge_id": knowledge_id,- "reference_id": reference_id, # From KnowledgeItem.citations- "source": source,- "content": content,- "citation_id": citation_id,- }-- return citation_id-- def get_citation_info(self, citation_id: str) -> dict[str, Any] | None:- """Get citation information"""- return self.citation_map.get(citation_id)-- def get_all_citations(self) -> dict[str, dict[str, Any]]:- """Get all citation mappings"""- return self.citation_map.copy()-- def reset(self):- """Reset citation manager (for new task)"""- self.citation_counter = 0- self.citation_map = {}diff --git a/src/agents/solve/solve_loop/manager_agent.py b/src/agents/solve/solve_loop/manager_agent.pydeleted file mode 100644index b45a7dbed..000000000--- a/src/agents/solve/solve_loop/manager_agent.py+++ /dev/null@@ -1,238 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-ManagerAgent - Milestone Planner--Based on user question and knowledge chain, generates a coarse-grained todo-list-for the solve phase to iterate over.-"""--from pathlib import Path-import sys-from typing import Any--# Add project root to path-project_root = Path(__file__).parent.parent.parent.parent-sys.path.insert(0, str(project_root))--from src.agents.base_agent import BaseAgent--from ..memory import InvestigateMemory, SolveMemory, TodoItem-from ..utils.json_utils import extract_json_from_text---class ManagerAgent(BaseAgent):- """Manager Agent - Generates todo-list milestones for solving"""-- def __init__(- self,- config: dict[str, Any],- api_key: str,- base_url: str,- api_version: str | None = None,- token_tracker=None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="solve",- agent_name="manager_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- token_tracker=token_tracker,- )-- async def process(- self,- question: str,- investigate_memory: InvestigateMemory,- solve_memory: SolveMemory,- verbose: bool = True,- ) -> dict[str, Any]:- """- Process management workflow - generate todo-list milestones-- Args:- question: User question- investigate_memory: Investigation memory (contains knowledge chain)- solve_memory: Solve memory- verbose: Whether to print detailed information-- Returns:- dict: Management result with todo-list info- """- stage_label = "Plan"- self.logger.log_stage_progress(- stage_label, "start", f"question={question[:60]}{'...' if len(question) > 60 else ''}"- )-- # 1. Check if todo-list already exists- if solve_memory.todo_list:- todos_count = len(solve_memory.todo_list)- self.logger.log_stage_progress(stage_label, "skip", f"Already has {todos_count} todos")- return {- "has_todos": True,- "todos_count": todos_count,- "num_todos": todos_count,- "message": "Todo-list already exists, skipping planning",- }-- # 2. Build context- context = self._build_context(question=question, investigate_memory=investigate_memory)-- # 3. Build Prompt- system_prompt = self._build_system_prompt()- user_prompt = self._build_user_prompt(context)-- # 4. Call LLM (requires JSON format output)- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- verbose=verbose,- stage=stage_label,- response_format={"type": "json_object"}, # Force JSON- )-- # 5. Parse output and create TodoItems- todos = self._parse_todo_response(response)-- # 6. Add todos to solve_memory- solve_memory.create_todo_list(todos)- solve_memory.save()-- # 7. Log todo-list details- todo_list_log = solve_memory.format_todo_list_for_log()- for line in todo_list_log.split("\n"):- self.logger.info(line)-- todos_count = len(todos)- self.logger.log_stage_progress(stage_label, "complete", f"Generated {todos_count} todos")- return {- "has_todos": True,- "todos_count": todos_count,- "num_todos": todos_count,- "message": f"Generated {todos_count} todos",- }-- def _build_context(- self, question: str, investigate_memory: InvestigateMemory- ) -> dict[str, Any]:- """Build context for LLM call"""- # Get knowledge chain information (cite_id + summary)- knowledge_info = []- for knowledge in investigate_memory.knowledge_chain:- if knowledge.summary: # Only use knowledge with summary- knowledge_info.append(- {- "cite_id": knowledge.cite_id,- "tool_type": knowledge.tool_type,- "query": knowledge.query,- "summary": knowledge.summary,- }- )-- knowledge_text = ""- for info in knowledge_info:- knowledge_text += f"\n{info['cite_id']} [{info['tool_type']}]\n"- knowledge_text += f" Query: {info['query']}\n"- knowledge_text += f" Summary: {info['summary']}\n"-- remaining_questions = []- if investigate_memory and getattr(investigate_memory, "reflections", None):- remaining_questions = investigate_memory.reflections.remaining_questions or []-- reflections_summary = (- "\n".join(f"- {q}" for q in remaining_questions)- if remaining_questions- else "(No remaining questions)"- )-- knowledge_summary_text = knowledge_text if knowledge_text else "(No research information)"-- return {- "question": question,- "knowledge_info": knowledge_info,- "knowledge_text": knowledge_summary_text,- "knowledge_chain_summary": knowledge_summary_text,- "reflections_summary": reflections_summary,- }-- def _build_system_prompt(self) -> str:- """Build system prompt"""- prompt = self.get_prompt("system") if self.has_prompts() else None- if not prompt:- raise ValueError(- "ManagerAgent missing system prompt, please configure system section in prompts/zh/solve_loop/manager_agent.yaml."- )- return prompt-- def _build_user_prompt(self, context: dict[str, Any]) -> str:- """Build user prompt"""- template = self.get_prompt("user_template") if self.has_prompts() else None- if not template:- raise ValueError(- "ManagerAgent missing user prompt template, please configure user_template in prompts/zh/solve_loop/manager_agent.yaml."- )- return template.format(**context)-- def _parse_todo_response(self, response: str) -> list[TodoItem]:- """Parse LLM output (JSON format), create todo-list items"""- todos: list[TodoItem] = []-- # Use json_utils to extract JSON- parsed_data = extract_json_from_text(response)-- if not parsed_data or not isinstance(parsed_data, dict):- raise ValueError(- f"Failed to parse valid JSON object from LLM output. Original output: {response[:200]}..."- )-- todos_data = parsed_data.get("todos", [])- if not isinstance(todos_data, list):- raise ValueError(f"'todos' field in JSON is not an array. Parsed result: {parsed_data}")-- if not todos_data:- raise ValueError("'todos' array in JSON is empty, please check LLM output")-- # Parse each todo- for idx, todo_data in enumerate(todos_data, 1):- if not isinstance(todo_data, dict):- self.logger.warning(- f"[ManagerAgent] Skipping invalid todo data (index {idx}): {todo_data}"- )- continue-- # Get todo_id- todo_id = todo_data.get("todo_id", "").strip()- if not todo_id:- todo_id = f"T{idx}"- elif not todo_id.upper().startswith("T"):- todo_id = f"T{todo_id}"-- # Get description- description = todo_data.get("description", "").strip()- if not description:- self.logger.warning(f"[ManagerAgent] Skipping todo {todo_id} with empty description")- continue-- # Create todo item- todos.append(- TodoItem(- todo_id=todo_id,- description=description,- status="pending",- )- )-- if not todos:- raise ValueError("Failed to parse any valid todos, please check LLM output format")-- logger = getattr(self, "logger", None)- if logger is not None:- logger.info(f"[ManagerAgent._parse_todo_response] Parsed {len(todos)} todo items")- for todo in todos:- logger.info(f" - {todo.todo_id}: {todo.description}")-- return todosdiff --git a/src/agents/solve/solve_loop/precision_answer_agent.py b/src/agents/solve/solve_loop/precision_answer_agent.pydeleted file mode 100644index 416c76ee3..000000000--- a/src/agents/solve/solve_loop/precision_answer_agent.py+++ /dev/null@@ -1,96 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-PrecisionAnswerAgent - Precision answer generator (two-stage)-"""--from pathlib import Path-import sys-from typing import Any, Dict--project_root = Path(__file__).parent.parent.parent.parent-if str(project_root) not in sys.path:- sys.path.insert(0, str(project_root))--from src.agents.base_agent import BaseAgent---class PrecisionAnswerAgent(BaseAgent):- """Staged precision answer"""-- def __init__(- self,- config: Dict[str, Any],- api_key: str,- base_url: str,- api_version: str | None = None,- token_tracker=None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="solve",- agent_name="precision_answer_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- token_tracker=token_tracker,- )-- async def process(- self, question: str, detailed_answer: str, verbose: bool = True- ) -> Dict[str, Any]:- decision = await self._should_generate(question, verbose)- if not decision["needs_precision"]:- return {- "needs_precision": False,- "precision_answer": "",- "final_answer": detailed_answer,- }-- precision_answer = await self._generate_precision_answer(- question=question, detailed_answer=detailed_answer, verbose=verbose- )- return {- "needs_precision": True,- "precision_answer": precision_answer,- "final_answer": detailed_answer,- }-- async def _should_generate(self, question: str, verbose: bool) -> Dict[str, Any]:- system_prompt = self.get_prompt("decision_system") if self.has_prompts() else None- if not system_prompt:- raise ValueError(- "PrecisionAnswerAgent missing decision_system prompt, please configure decision_system in prompts/{lang}/solve_loop/precision_answer_agent.yaml"- )- template = self.get_prompt("decision_user_template") if self.has_prompts() else None- if not template:- raise ValueError(- "PrecisionAnswerAgent missing decision_user_template, please configure decision_user_template in prompts/{lang}/solve_loop/precision_answer_agent.yaml"- )- user_prompt = template.format(question=question)- response = await self.call_llm(- user_prompt=user_prompt, system_prompt=system_prompt, verbose=verbose- )- needs_precision = response.strip().upper().startswith("Y")- return {"needs_precision": needs_precision, "raw_decision": response.strip()}-- async def _generate_precision_answer(- self, question: str, detailed_answer: str, verbose: bool- ) -> str:- system_prompt = self.get_prompt("precision_system") if self.has_prompts() else None- if not system_prompt:- raise ValueError(- "PrecisionAnswerAgent missing precision_system prompt, please configure precision_system in prompts/{lang}/solve_loop/precision_answer_agent.yaml"- )- template = self.get_prompt("precision_user_template") if self.has_prompts() else None- if not template:- raise ValueError(- "PrecisionAnswerAgent missing precision_user_template, please configure precision_user_template in prompts/{lang}/solve_loop/precision_answer_agent.yaml"- )- user_prompt = template.format(question=question, detailed_answer=detailed_answer)- response = await self.call_llm(- user_prompt=user_prompt, system_prompt=system_prompt, verbose=verbose- )- return response.strip()diff --git a/src/agents/solve/solve_loop/response_agent.py b/src/agents/solve/solve_loop/response_agent.pydeleted file mode 100644index b455e4321..000000000--- a/src/agents/solve/solve_loop/response_agent.py+++ /dev/null@@ -1,526 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-ResponseAgent - Step response generator--Based on completed todos and tool call chain from an iteration,-generates a formal, professional response for the completed work.-"""--from pathlib import Path-import re-import sys-from typing import Any, List, Optional--project_root = Path(__file__).parent.parent.parent.parent-if str(project_root) not in sys.path:- sys.path.insert(0, str(project_root))--from src.agents.base_agent import BaseAgent--from ..memory import (- CitationMemory,- InvestigateMemory,- IterationRecord,- SolveChainStep,- SolveMemory,- TodoItem,- ToolCallRecord,-)---class ResponseAgent(BaseAgent):- """- Response generator Agent.-- Generates professional step_response content based on:- - Completed todos from an iteration- - Tool call chain with summaries- - Knowledge from investigation phase- """-- def __init__(- self,- config: dict[str, Any],- api_key: str,- base_url: str,- api_version: str | None = None,- token_tracker=None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="solve",- agent_name="response_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- token_tracker=token_tracker,- )- # Store citation configuration- self.enable_citations = config.get("system", {}).get("enable_citations", True)-- async def process(- self,- question: str,- iteration_record: IterationRecord,- completed_todos: List[TodoItem],- citation_memory: CitationMemory,- knowledge_chain: List[Any],- output_dir: str | None = None,- accumulated_response: str = "",- verbose: bool = True,- ) -> dict[str, Any]:- """- Generate step_response for completed todos based on iteration results.-- Args:- question: Original user question- iteration_record: The iteration record with tool call history- completed_todos: List of TodoItem objects that were completed- citation_memory: Citation memory for source tracking- knowledge_chain: Knowledge from investigation phase- output_dir: Output directory path- accumulated_response: Previous step responses for context- verbose: Whether to print detailed information-- Returns:- dict: {- "step_response": str,- "used_citations": List[str],- "iteration_id": str- }- """- if not completed_todos:- return {- "step_response": "",- "used_citations": [],- "iteration_id": iteration_record.iteration_id,- "skipped": True,- "reason": "No completed todos to respond to",- }-- # Build context- context = self._build_context(- question=question,- iteration_record=iteration_record,- completed_todos=completed_todos,- citation_memory=citation_memory,- knowledge_chain=knowledge_chain,- output_dir=output_dir,- accumulated_response=accumulated_response,- )-- system_prompt = self._build_system_prompt(context["image_materials"])- user_prompt = self._build_user_prompt(context)-- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- verbose=verbose,- )-- # Process response- step_response = response.strip() if response else ""- used_citations = self._extract_used_citations(- content=step_response,- tool_calls=iteration_record.tool_calls,- knowledge_chain=knowledge_chain,- )-- # Update iteration record- iteration_record.set_step_response(step_response, used_citations)-- return {- "step_response": step_response,- "used_citations": used_citations,- "iteration_id": iteration_record.iteration_id,- "completed_todo_ids": [t.todo_id for t in completed_todos],- "raw_response": response,- }-- # ------------------------------------------------------------------ #- # Context Building- # ------------------------------------------------------------------ #- def _build_context(- self,- question: str,- iteration_record: IterationRecord,- completed_todos: List[TodoItem],- citation_memory: CitationMemory,- knowledge_chain: List[Any],- output_dir: str | None,- accumulated_response: str = "",- ) -> dict[str, Any]:- """Build context for LLM call"""- # Format completed todos- completed_todos_text = self._format_completed_todos(completed_todos)-- # Format tool call chain- tool_materials, image_materials = self._format_tool_call_chain(- iteration_record.tool_calls, output_dir- )-- # Format knowledge chain- knowledge_text = self._format_knowledge_chain(knowledge_chain)-- # Format citation details- citation_details = self._format_citation_details(- iteration_record.tool_calls, citation_memory- )-- # Get user preference from personalization service- preference = self._get_user_preference()-- return {- "question": question,- "iteration_id": iteration_record.iteration_id,- "completed_todos": completed_todos_text,- "completed_todos_count": len(completed_todos),- "tool_materials": tool_materials,- "knowledge_chain": knowledge_text,- "citation_details": citation_details,- "image_materials": image_materials,- "previous_context": accumulated_response- or "(No previous content, this is the first step)",- "preference": preference,- }-- def _get_user_preference(self) -> str:- """Get user preference from personalization service."""- try:- from src.personalization.service import get_personalization_service-- service = get_personalization_service()- preference = service.get_preference_for_prompt()- return preference if preference else "(No user preference recorded)"- except Exception as e:- self.logger.debug(f"Failed to get user preference: {e}")- return "(No user preference recorded)"-- def _format_completed_todos(self, todos: List[TodoItem]) -> str:- """Format completed todos for context"""- if not todos:- return "(No todos completed)"-- lines = []- for todo in todos:- lines.append(f"- {todo.todo_id}: {todo.description}")- return "\n".join(lines)-- def _format_tool_call_chain(- self,- tool_calls: List[ToolCallRecord],- output_dir: str | None,- ) -> tuple[str, list[str]]:- """Format tool call chain and extract images"""- if not tool_calls:- return "(No tool calls in this iteration)", []-- lines: list[str] = []- images: list[str] = []- seen_images: set[str] = set()-- def _append_image(path_str: str):- normalized = str(path_str).replace("\\", "/")- if normalized and normalized not in seen_images:- images.append(normalized)- seen_images.add(normalized)-- for idx, call in enumerate(tool_calls, 1):- summary = call.summary or "(Summary pending)"- raw_preview = (call.raw_answer or "")[:500]- lines.append(- f"[{idx}] {call.tool_type} | cite_id={call.cite_id or 'N/A'} | Status={call.status}\n"- f"Query: {call.query}\n"- f"Summary: {summary}\n"- f"Raw excerpt: {raw_preview}"- )-- # Extract images from metadata- if call.metadata:- artifact_rel_paths = call.metadata.get("artifact_rel_paths", [])- artifact_paths = call.metadata.get("artifact_paths", [])- artifacts = call.metadata.get("artifacts", [])-- if artifact_rel_paths:- for rel_path in artifact_rel_paths:- _append_image(rel_path)-- if artifact_paths:- for abs_path in artifact_paths:- path = Path(abs_path)- if path.suffix.lower() in {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}:- if output_dir:- try:- rel_path = path.relative_to(Path(output_dir))- _append_image(str(rel_path))- except ValueError:- _append_image(path.name)- else:- _append_image(path.name)- elif artifacts:- for artifact in artifacts:- path = Path(artifact)- if path.suffix.lower() in {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}:- rel_path = Path("artifacts") / path.name- _append_image(str(rel_path))-- return "\n\n".join(lines), images-- def _format_knowledge_chain(self, knowledge_chain: List[Any]) -> str:- """Format knowledge chain from investigation phase"""- if not knowledge_chain:- return "(No prior knowledge from investigation)"-- lines = []- for knowledge in knowledge_chain:- cite_id = getattr(knowledge, "cite_id", "")- tool_type = getattr(knowledge, "tool_type", "")- query = getattr(knowledge, "query", "")- summary = getattr(knowledge, "summary", "") or getattr(knowledge, "raw_result", "")[:300]-- lines.append(- f"{cite_id} [{tool_type}]\n"- f" Query: {query}\n"- f" Summary: {summary}"- )- return "\n\n".join(lines) if lines else "(No prior knowledge)"-- def _format_citation_details(- self,- tool_calls: List[ToolCallRecord],- citation_memory: CitationMemory,- ) -> str:- """Format citation details from tool calls"""- if not self.enable_citations:- return "(Citations disabled)"-- cite_ids = [tc.cite_id for tc in tool_calls if tc.cite_id]- if not cite_ids:- return "(No citations)"-- lines: list[str] = []- for cite_id in cite_ids:- citation = citation_memory.get_citation(cite_id)- if not citation:- continue- summary = citation.content or citation.raw_result[:200]- lines.append(f"- {cite_id} [{citation.tool_type}] Query: {citation.query}")- if summary:- lines.append(f" Summary: {summary[:300]}")- return "\n".join(lines) if lines else "(Citation information missing)"-- # ------------------------------------------------------------------ #- # Prompt Building- # ------------------------------------------------------------------ #- def _build_system_prompt(self, image_materials: list[str]) -> str:- base_prompt = self.get_prompt("system") if self.has_prompts() else None- if not base_prompt:- # Fallback system prompt- base_prompt = """# Role Definition-You are a professional teaching assistant. Generate a high-quality response based on the completed todos and tool call results.--## Core Principles-1. **Continuity**: Follow directly after previous_context, maintaining smooth flow-2. **Evidence-based**: All conclusions must be based on the provided materials-3. **Professional format**: Well-structured with proper headings and formatting--## Key Norms--### Citation Format-- Cite sources using: `[cite_id]` (e.g., `[rag-1]`, `[code-2]`)-- Place immediately after the cited content--### Mathematical Formulas (LaTeX)-- Inline: `$x$`, `$E = mc^2$`-- Block: `$$` on separate lines-- Never use bare math variables in text--### Output Structure-- Use Markdown headings (## or ###)-- Include explanations for concepts-- Show logical derivation steps-- Summarize key points at the end-"""-- # Add citation disable instruction if needed- citation_instruction = ""- if not self.enable_citations:- citation_instruction_yaml = self.get_prompt("citation_instruction_disabled")- if citation_instruction_yaml:- citation_instruction = citation_instruction_yaml- else:- citation_instruction = "\n\n**Important: Citation Feature Disabled**\n"-- # Add image instructions if there are images- if image_materials:- image_list = "\n".join([f" - {img}" for img in image_materials])- image_instruction_template = self.get_prompt("image_instruction")- if image_instruction_template:- image_instruction = image_instruction_template.format(image_list=image_list)- else:- image_instruction = f"\n\n**Image files to insert**:\n{image_list}\n"- return base_prompt + citation_instruction + image_instruction-- return base_prompt + citation_instruction-- def _build_user_prompt(self, context: dict[str, Any]) -> str:- template = self.get_prompt("user_template") if self.has_prompts() else None- if not template:- # Fallback user template- template = """## User Preference-{preference}--## User Question-{question}--## Previous Context (Completed Steps)-{previous_context}--## Completed Todos This Iteration ({completed_todos_count} items)-{completed_todos}--## Tool Call Results-{tool_materials}--## Prior Knowledge (from investigation)-{knowledge_chain}--## Citation Details-{citation_details}--## Images to Insert-{image_materials}--## Task-Generate a professional response for the completed todos listed above.-The response should:-1. Address each completed todo with appropriate depth-2. Use evidence from tool call results-3. Include proper citations where applicable-4. Follow the formatting guidelines-"""-- # Format image_materials as text- image_materials = context.get("image_materials", [])- if isinstance(image_materials, list):- if image_materials:- image_text = "\n".join([f"- {img}" for img in image_materials])- else:- image_text = "(No image files)"- else:- image_text = str(image_materials)-- formatted_context = context.copy()- formatted_context["image_materials"] = image_text-- return template.format(**formatted_context)-- # ------------------------------------------------------------------ #- # Citation Extraction- # ------------------------------------------------------------------ #- def _extract_used_citations(- self,- content: str,- tool_calls: List[ToolCallRecord],- knowledge_chain: List[Any],- ) -> list[str]:- """Extract citation IDs used in the response"""- if not self.enable_citations:- return []-- if not content:- return []-- # Pattern to match citations- pattern = re.compile(r"\[([^\]\[]+)\](?!\()|【([^】\[]+)】")- matches = pattern.findall(content)-- normalized: list[str] = []- for match in matches:- candidate = match[0] or match[1]- if not candidate:- continue- normalized.append(f"[{candidate.strip()}]")-- # Build set of allowed citations- allowed = set()- for tc in tool_calls:- if tc.cite_id:- allowed.add(tc.cite_id)- for k in knowledge_chain:- cite_id = getattr(k, "cite_id", "")- if cite_id:- allowed.add(cite_id)-- # Filter to only allowed citations, preserving order- ordered: list[str] = []- for cite in normalized:- if cite in allowed and cite not in ordered:- ordered.append(cite)-- return ordered---# ------------------------------------------------------------------ #-# Legacy compatibility-# ------------------------------------------------------------------ #-class ResponseAgentLegacy(ResponseAgent):- """Legacy wrapper for backward compatibility with SolveChainStep API"""-- async def process_legacy(- self,- question: str,- step: SolveChainStep,- solve_memory: SolveMemory,- investigate_memory: InvestigateMemory,- citation_memory: CitationMemory,- output_dir: str | None = None,- verbose: bool = True,- accumulated_response: str = "",- ) -> dict[str, Any]:- """Legacy process method using SolveChainStep"""- if not step:- return {"step_response": "(No pending step)"}-- # Convert SolveChainStep to IterationRecord format- iteration_record = IterationRecord(- iteration_id=step.step_id,- target_todo_id=step.step_id,- tool_calls=step.tool_calls,- )-- # Create a pseudo TodoItem for the step- completed_todo = TodoItem(- todo_id=step.step_id,- description=step.step_target,- status="completed",- )-- result = await self.process(- question=question,- iteration_record=iteration_record,- completed_todos=[completed_todo],- citation_memory=citation_memory,- knowledge_chain=investigate_memory.knowledge_chain,- output_dir=output_dir,- accumulated_response=accumulated_response,- verbose=verbose,- )-- # Update legacy memory structures- if result.get("step_response"):- step.update_response(- response=result["step_response"],- used_citations=result.get("used_citations", []),- )- solve_memory.save()-- return {- "step_id": step.step_id,- "step_response": result.get("step_response", ""),- "used_citations": result.get("used_citations", []),- "raw_response": result.get("raw_response", ""),- }diff --git a/src/agents/solve/solve_loop/solve_agent.py b/src/agents/solve/solve_loop/solve_agent.pydeleted file mode 100644index df9714777..000000000--- a/src/agents/solve/solve_loop/solve_agent.py+++ /dev/null@@ -1,344 +0,0 @@-#!/usr/bin/env python-"""-SolveAgent - Iterative information collector--For a given todo item, iteratively decides which tool to call to gather information.-Outputs {tool_type, query} per iteration until tool_type == "none" signals completion.-"""--from pathlib import Path-import sys-from typing import Any, List, Optional--# Add project root to path-project_root = Path(__file__).parent.parent.parent.parent-if str(project_root) not in sys.path:- sys.path.insert(0, str(project_root))--from src.agents.base_agent import BaseAgent--from ..memory import (- InvestigateMemory,- IterationRecord,- SolveMemory,- TodoItem,- ToolCallRecord,-)-from ..utils.json_utils import extract_json_from_text---class SolveAgent(BaseAgent):- """- Solve Agent - Information collector for solving todos.-- For each todo, this agent iteratively decides what information to gather.- Each call returns a single {tool_type, query} decision.- When tool_type == "none", the iteration ends.- """-- SUPPORTED_TOOL_TYPES = {- "none", # End iteration - information is sufficient- "rag_naive", # Precise formula/definition lookup- "rag_hybrid", # Conceptual understanding/comparison- "web_search", # External/latest information- "code_execution", # Calculations, plotting, derivations- }-- def __init__(- self,- config: dict[str, Any],- api_key: str,- base_url: str,- api_version: str | None = None,- token_tracker=None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="solve",- agent_name="solve_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- token_tracker=token_tracker,- )- # Max iterations per todo to prevent infinite loops- self.max_iterations = config.get("solve", {}).get("max_inner_iterations", 5)-- async def process(- self,- current_todo: TodoItem,- iteration_history: List[ToolCallRecord],- knowledge_chain: List[Any],- question: str,- verbose: bool = True,- ) -> dict[str, Any]:- """- Process a single iteration step for the current todo.-- Decides whether to call a tool or end the iteration.-- Args:- current_todo: The todo item being worked on- iteration_history: Previous tool calls in this iteration- knowledge_chain: Knowledge from investigate phase- question: Original user question- verbose: Whether to print detailed information-- Returns:- dict: {- "tool_type": str, # "none" to end iteration- "query": str, # Query/intent for the tool- "should_stop": bool # True if tool_type is "none"- }- """- # Check iteration limit- if len(iteration_history) >= self.max_iterations:- self.logger.warning(- f"[SolveAgent] Max iterations ({self.max_iterations}) reached for {current_todo.todo_id}"- )- return {- "tool_type": "none",- "query": "",- "should_stop": True,- "reason": "max_iterations_reached",- }-- # Build context- context = self._build_context(- current_todo=current_todo,- iteration_history=iteration_history,- knowledge_chain=knowledge_chain,- question=question,- )-- system_prompt = self._build_system_prompt()- user_prompt = self._build_user_prompt(context)-- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- verbose=verbose,- response_format={"type": "json_object"},- )-- # Parse the decision- decision = self._parse_decision(response)- if not decision:- self.logger.warning(- f"SolveAgent JSON parsing failed, defaulting to none. Raw: {response[:200]}..."- )- return {- "tool_type": "none",- "query": "",- "should_stop": True,- "reason": "parse_error",- }-- tool_type = decision["tool_type"]- query = decision["query"]- should_stop = tool_type == "none"-- return {- "tool_type": tool_type,- "query": query,- "should_stop": should_stop,- "raw_response": response,- }-- # ------------------------------------------------------------------ #- # Context Building- # ------------------------------------------------------------------ #- def _build_context(- self,- current_todo: TodoItem,- iteration_history: List[ToolCallRecord],- knowledge_chain: List[Any],- question: str,- ) -> dict[str, Any]:- """Build context for LLM call"""- # Format current todo- todo_text = f"{current_todo.todo_id}: {current_todo.description}"-- # Format iteration history- history_text = self._format_iteration_history(iteration_history)-- # Format knowledge chain from investigate phase- knowledge_text = self._format_knowledge_chain(knowledge_chain)-- return {- "question": question,- "current_todo": todo_text,- "iteration_history": history_text,- "knowledge_chain": knowledge_text,- "iteration_count": len(iteration_history),- "max_iterations": self.max_iterations,- }-- def _format_iteration_history(self, history: List[ToolCallRecord]) -> str:- """Format the iteration history for context"""- if not history:- return "(No previous tool calls in this iteration)"-- lines = []- for idx, record in enumerate(history, 1):- summary = record.summary or "(pending)"- if record.raw_answer and not record.summary:- summary = record.raw_answer[:300] + "..."-- lines.append(- f"[{idx}] {record.tool_type}\n"- f" Query: {record.query}\n"- f" cite_id: {record.cite_id or 'N/A'}\n"- f" Summary: {summary}"- )- return "\n\n".join(lines)-- def _format_knowledge_chain(self, knowledge_chain: List[Any]) -> str:- """Format knowledge chain from investigate phase"""- if not knowledge_chain:- return "(No prior knowledge from investigation)"-- lines = []- for knowledge in knowledge_chain:- cite_id = getattr(knowledge, "cite_id", "")- tool_type = getattr(knowledge, "tool_type", "")- query = getattr(knowledge, "query", "")- summary = getattr(knowledge, "summary", "") or getattr(knowledge, "raw_result", "")[:300]-- lines.append(- f"{cite_id} [{tool_type}]\n"- f" Query: {query}\n"- f" Summary: {summary}"- )- return "\n\n".join(lines) if lines else "(No prior knowledge)"-- # ------------------------------------------------------------------ #- # Prompt Building- # ------------------------------------------------------------------ #- def _build_system_prompt(self) -> str:- prompt = self.get_prompt("system") if self.has_prompts() else None- if not prompt:- # Fallback prompt- prompt = """# Role Definition-You are the **Solve Agent**, responsible for gathering information to complete the current todo.--## Task-Decide what tool to call next to collect information for the current todo.-Output ONE tool call decision per response.--## Output Format (STRICT JSON)-{- "tool_type": "rag_naive | rag_hybrid | web_search | code_execution | none",- "query": "Your query or intent description"-}--## Tool Types-- `rag_naive`: Precise definition/formula lookup from knowledge base-- `rag_hybrid`: Conceptual understanding, comparison, or broader search-- `web_search`: External information, latest news, or resources not in KB-- `code_execution`: Calculations, derivations, plotting, data processing-- `none`: No more information needed, end this iteration--## Rules-1. Output exactly ONE tool call per response-2. Use `none` when you have sufficient information to complete the todo-3. Do NOT generate answer content - only decide what information to gather-4. Consider what's already been collected in iteration_history-"""- return prompt-- def _build_user_prompt(self, context: dict[str, Any]) -> str:- template = self.get_prompt("user_template") if self.has_prompts() else None- if not template:- # Fallback template- template = """## User Question-{question}--## Current Todo-{current_todo}--## Prior Knowledge (from investigation phase)-{knowledge_chain}--## This Iteration's Tool Calls ({iteration_count}/{max_iterations})-{iteration_history}--## Task-Decide the next tool call to gather information for the current todo.-Output "none" as tool_type if information is sufficient.-Output valid JSON only."""- return template.format(**context)-- # ------------------------------------------------------------------ #- # Response Parsing- # ------------------------------------------------------------------ #- def _parse_decision(self, response: str) -> Optional[dict[str, Any]]:- """Parse the LLM decision - simplified output format"""- parsed_data = extract_json_from_text(response)-- if not parsed_data or not isinstance(parsed_data, dict):- return None-- tool_type = str(parsed_data.get("tool_type", "none")).strip().lower()- query = str(parsed_data.get("query", "")).strip()-- # Normalize tool_type- if tool_type not in self.SUPPORTED_TOOL_TYPES:- # Try to map common variations- if tool_type in {"finish", "stop", "end", "done"}:- tool_type = "none"- elif tool_type in {"rag", "search", "kb"}:- tool_type = "rag_hybrid"- elif tool_type in {"web", "internet"}:- tool_type = "web_search"- elif tool_type in {"code", "python", "execute"}:- tool_type = "code_execution"- else:- self.logger.warning(f"[SolveAgent] Unknown tool_type '{tool_type}', defaulting to none")- tool_type = "none"-- return {- "tool_type": tool_type,- "query": query,- }---# Legacy compatibility - keep old process signature as alternative-class SolveAgentLegacy(SolveAgent):- """Legacy wrapper for backward compatibility with old API"""-- async def process_legacy(- self,- question: str,- solve_memory: SolveMemory,- investigate_memory: InvestigateMemory,- citation_memory: Any,- kb_name: str = "ai_textbook",- output_dir: str | None = None,- verbose: bool = True,- ) -> dict[str, Any]:- """- Legacy process method - wraps new API for backward compatibility.- """- current_todo = solve_memory.get_next_pending_todo()- if not current_todo:- return {- "tool_type": "none",- "query": "",- "should_stop": True,- "reason": "no_pending_todo",- }-- # Get current iteration or empty history- current_iter = solve_memory.get_current_iteration()- iteration_history = current_iter.tool_calls if current_iter else []-- return await self.process(- current_todo=current_todo,- iteration_history=iteration_history,- knowledge_chain=investigate_memory.knowledge_chain,- question=question,- verbose=verbose,- )diff --git a/src/agents/solve/solve_loop/solve_note_agent.py b/src/agents/solve/solve_loop/solve_note_agent.pydeleted file mode 100644index 28407fb33..000000000--- a/src/agents/solve/solve_loop/solve_note_agent.py+++ /dev/null@@ -1,389 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-SolveNoteAgent - Todo-list manager--Responsible for reviewing the iteration results and managing the todo-list.-Can mark todos as done, edit their content, add new todos, or delete existing ones.--This agent enables dynamic todo-list management based on what was discovered during solving.-"""--from pathlib import Path-import sys-from typing import Any, List, Optional--# Add project root to path-project_root = Path(__file__).parent.parent.parent.parent-if str(project_root) not in sys.path:- sys.path.insert(0, str(project_root))--from src.agents.base_agent import BaseAgent--from ..memory import (- IterationRecord,- NoteAction,- SolveMemory,- TodoItem,- ToolCallRecord,-)-from ..utils.json_utils import extract_json_from_text---class SolveNoteAgent(BaseAgent):- """- Note Agent - Manages todo-list based on iteration results.-- Capabilities:- - Mark todos as done (completed)- - Edit todo content (for partial completion or refinement)- - Add new todos (for split tasks or discovered subtasks)- - Delete todos (if no longer needed or merged)- """-- VALID_ACTIONS = {"done", "edit", "add", "delete"}-- def __init__(- self,- config: dict[str, Any],- api_key: str,- base_url: str,- api_version: str | None = None,- token_tracker=None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="solve",- agent_name="solve_note_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- token_tracker=token_tracker,- )-- async def process(- self,- solve_memory: SolveMemory,- iteration_record: IterationRecord,- target_todo: TodoItem,- verbose: bool = True,- ) -> dict[str, Any]:- """- Review iteration results and manage the todo-list.-- Args:- solve_memory: Solve memory containing todo-list- iteration_record: The iteration record with tool call history- target_todo: The todo that was being worked on- verbose: Whether to print detailed information-- Returns:- dict: {- "success": bool,- "actions": List[NoteAction],- "completed_todos": List[str], # todo_ids that were marked done- "raw_response": str- }- """- # Build context- context = self._build_context(- solve_memory=solve_memory,- iteration_record=iteration_record,- target_todo=target_todo,- )-- # Build prompts- system_prompt = self._build_system_prompt()- user_prompt = self._build_user_prompt(context)-- # Call LLM- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- verbose=verbose,- response_format={"type": "json_object"},- )-- # Parse actions- actions = self._parse_actions(response)-- # Convert to NoteAction objects- note_actions = [- NoteAction(- pre_id=action["pre_id"],- action=action["action"],- content=action.get("content"),- )- for action in actions- ]-- # Get cite_ids from iteration for evidence- cite_ids = iteration_record.get_all_cite_ids()-- # Apply actions to solve_memory- completed_todos = solve_memory.apply_note_actions(- actions=note_actions,- iteration_id=iteration_record.iteration_id,- cite_ids=cite_ids,- )-- # Update iteration record- iteration_record.set_note_actions(note_actions)- iteration_record.set_completed_todos(completed_todos)-- # Save memory- solve_memory.save()-- return {- "success": True,- "actions": [a.to_dict() for a in note_actions],- "completed_todos": completed_todos,- "total_actions": len(note_actions),- "raw_response": response,- }-- # ------------------------------------------------------------------ #- # Context Building- # ------------------------------------------------------------------ #- def _build_context(- self,- solve_memory: SolveMemory,- iteration_record: IterationRecord,- target_todo: TodoItem,- ) -> dict[str, Any]:- """Build context for the note agent"""- # Format todo list with positions- todo_list_text = self._format_todo_list_with_positions(solve_memory.todo_list)-- # Format iteration tool call history- tool_call_history = self._format_tool_call_history(iteration_record.tool_calls)-- # Target todo info- target_todo_text = f"{target_todo.todo_id}: {target_todo.description}"-- return {- "todo_list": todo_list_text,- "target_todo": target_todo_text,- "target_todo_id": target_todo.todo_id,- "tool_call_history": tool_call_history,- "total_todos": len(solve_memory.todo_list),- }-- def _format_todo_list_with_positions(self, todo_list: List[TodoItem]) -> str:- """Format todo-list with position numbers for reference"""- if not todo_list:- return "(Empty todo-list)"-- lines = []- for idx, todo in enumerate(todo_list, 1):- status_marker = {- "pending": "[ ]",- "in_progress": "[~]",- "completed": "[x]",- "skipped": "[-]",- }.get(todo.status, "[ ]")- # Position is 1-indexed, pre_id for this todo would be idx- lines.append(f"[pos={idx}] {status_marker} {todo.todo_id}: {todo.description}")- return "\n".join(lines)-- def _format_tool_call_history(self, tool_calls: List[ToolCallRecord]) -> str:- """Format tool call history"""- if not tool_calls:- return "(No tool calls in this iteration)"-- lines = []- for idx, call in enumerate(tool_calls, 1):- summary = call.summary or "(No summary)"- if call.raw_answer and not call.summary:- summary = call.raw_answer[:500] + "..."-- lines.append(- f"[{idx}] {call.tool_type} (cite: {call.cite_id or 'N/A'})\n"- f" Query: {call.query}\n"- f" Summary: {summary}"- )- return "\n\n".join(lines)-- # ------------------------------------------------------------------ #- # Prompt Building- # ------------------------------------------------------------------ #- def _build_system_prompt(self) -> str:- """Build system prompt"""- prompt = self.get_prompt("system") if self.has_prompts() else None- if not prompt:- prompt = """# Role Definition-You are the **Todo Manager** for a problem-solving system.--Your task is to review the iteration results (tool call history) and update the todo-list accordingly.--## Capabilities-You can perform these actions on the todo-list:-- `done`: Mark a todo as completed-- `edit`: Change the content of a todo-- `add`: Insert a new todo at a specific position-- `delete`: Remove a todo from the list--## Output Format (STRICT JSON)-```json-{- "actions": [- {- "pre_id": 1,- "action": "done",- "content": null- },- {- "pre_id": 1,- "action": "add",- "content": "New subtask that needs investigation"- }- ]-}-```--## pre_id Explanation-- `pre_id` indicates the position BEFORE which to operate-- `pre_id=1` means operate on position 1 (first todo)-- `pre_id=2` means operate on position 2 (second todo)-- For `add`, the new item is inserted AFTER the pre_id position--## Action Details-- `done`: Mark the todo at position pre_id as completed. content can be evidence or null.-- `edit`: Replace the content of todo at position pre_id with new content.-- `add`: Insert a new todo AFTER position pre_id. content is required.-- `delete`: Remove the todo at position pre_id. content is null.--## Guidelines-1. **At minimum**: Mark the target todo as done if the iteration provided sufficient information-2. **Partial completion**: If a todo is only partially answered, split it:- - Edit the original to reflect what was completed- - Mark it as done- - Add a new todo for the remaining part-3. **Discovered coverage**: If iteration results also cover other todos, mark them too-4. **Conservative**: Only mark as done if there's clear evidence from tool calls-"""- return prompt-- def _build_user_prompt(self, context: dict[str, Any]) -> str:- """Build user prompt"""- template = self.get_prompt("user_template") if self.has_prompts() else None- if not template:- template = """## Current Todo-list-{todo_list}--## Target Todo (being worked on)-{target_todo}--## This Iteration's Tool Call Results-{tool_call_history}--## Task-Based on the tool call results from this iteration:-1. Determine if the target todo ({target_todo_id}) can be marked as done-2. Check if the results also complete or affect other todos-3. If a todo is partially complete, consider splitting it--Output a JSON object with an "actions" array.-Each action must have: pre_id (position), action (done/edit/add/delete), content (if needed).-If no changes needed, return empty actions array: {{"actions": []}}-"""- return template.format(**context)-- # ------------------------------------------------------------------ #- # Response Parsing- # ------------------------------------------------------------------ #- def _parse_actions(self, response: str) -> List[dict[str, Any]]:- """Parse the actions from LLM response"""- parsed_data = extract_json_from_text(response)-- if not parsed_data or not isinstance(parsed_data, dict):- self.logger.warning("[SolveNoteAgent] Failed to parse JSON response")- return []-- actions = parsed_data.get("actions", [])- if not isinstance(actions, list):- return []-- valid_actions = []- for action in actions:- if not isinstance(action, dict):- continue-- pre_id = action.get("pre_id")- action_type = str(action.get("action", "")).strip().lower()- content = action.get("content")-- # Validate pre_id- if pre_id is None:- self.logger.warning("[SolveNoteAgent] Missing pre_id in action")- continue-- try:- pre_id = int(pre_id)- except (TypeError, ValueError):- self.logger.warning(f"[SolveNoteAgent] Invalid pre_id: {pre_id}")- continue-- # Validate action type- if action_type not in self.VALID_ACTIONS:- self.logger.warning(f"[SolveNoteAgent] Invalid action: {action_type}")- continue-- # Validate content for actions that need it- if action_type in {"edit", "add"} and not content:- self.logger.warning(f"[SolveNoteAgent] {action_type} requires content")- continue-- # Normalize content- if content is not None:- content = str(content).strip()- if not content:- content = None-- valid_actions.append({- "pre_id": pre_id,- "action": action_type,- "content": content,- })-- return valid_actions---# Legacy compatibility wrapper-class SolveNoteAgentLegacy(SolveNoteAgent):- """Legacy wrapper for backward compatibility"""-- async def process_legacy(- self,- solve_memory: SolveMemory,- verbose: bool = True,- ) -> dict[str, Any]:- """- Legacy process method - gets context from solve_memory.- """- current_iter = solve_memory.get_current_iteration()- if not current_iter:- return {- "success": False,- "reason": "No current iteration",- "actions": [],- "completed_todos": [],- }-- target_todo = solve_memory.get_todo(current_iter.target_todo_id)- if not target_todo:- return {- "success": False,- "reason": f"Target todo {current_iter.target_todo_id} not found",- "actions": [],- "completed_todos": [],- }-- return await self.process(- solve_memory=solve_memory,- iteration_record=current_iter,- target_todo=target_todo,- verbose=verbose,- )diff --git a/src/agents/solve/solve_loop/tool_agent.py b/src/agents/solve/solve_loop/tool_agent.pydeleted file mode 100644index a21d84a7b..000000000--- a/src/agents/solve/solve_loop/tool_agent.py+++ /dev/null@@ -1,389 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-ToolAgent - Tool executor--Responsible for executing tool calls and producing summaries.-"""--from pathlib import Path-import re-import sys-from typing import Any--project_root = Path(__file__).parent.parent.parent.parent-if str(project_root) not in sys.path:- sys.path.insert(0, str(project_root))--from src.agents.base_agent import BaseAgent-from src.tools.code_executor import run_code-from src.tools.rag_tool import rag_search-from src.tools.web_search import web_search--from ..memory.solve_memory import ToolCallRecord---class ToolAgent(BaseAgent):- """Execute tool calls and generate summary"""-- def __init__(- self,- config: dict[str, Any],- api_key: str,- base_url: str,- api_version: str | None = None,- token_tracker=None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="solve",- agent_name="tool_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- token_tracker=token_tracker,- )-- async def process(- self,- record: ToolCallRecord,- kb_name: str,- output_dir: str | None = None,- verbose: bool = True,- ) -> dict[str, Any]:- """- Execute a single tool call and return the result.-- Args:- record: The tool call record to execute- kb_name: Knowledge base name- output_dir: Output directory path- verbose: Whether to print detailed information-- Returns:- dict: Execution result with raw_answer, summary, and metadata- """- base_dir = Path(output_dir).resolve() if output_dir else Path().resolve()- artifacts_dir = base_dir / "artifacts"- artifacts_dir.mkdir(parents=True, exist_ok=True)-- raw_answer, metadata = await self._execute_single_call(- record=record,- kb_name=kb_name,- output_dir=output_dir,- artifacts_dir=str(artifacts_dir),- verbose=verbose,- )-- summary = await self._summarize_tool_result(- tool_type=record.tool_type,- query=record.query,- raw_answer=raw_answer,- )-- return {- "raw_answer": raw_answer,- "summary": summary,- "metadata": metadata,- }-- async def _generate_code_from_intent(self, intent: str) -> str:- """Generate Python code from a natural language intent description"""- system_prompt = """-You are a Python code generator.-Generate ONLY executable Python code.-Do NOT include explanations.-Do NOT include markdown fences.-Do NOT include comments unless necessary.-The code must be self-contained and runnable.-"""- user_prompt = f"""-Task:-{intent}--Rules:-- Output only Python code-- No ``` fences-- No natural language-"""- code = await self.call_llm(- system_prompt=system_prompt,- user_prompt=user_prompt,- verbose=False,- )- if "```" in code:- raise ValueError("LLM returned markdown code fences, which is forbidden")- if len(code) > 8000:- raise ValueError("Generated code too large")-- return code.strip()-- async def _execute_single_call(- self,- record: ToolCallRecord,- kb_name: str,- output_dir: str | None,- artifacts_dir: str,- verbose: bool,- ) -> tuple[str, dict[str, Any]]:- """- Execute a single tool call.-- Args:- record: The tool call record- kb_name: Knowledge base name- output_dir: Output directory path- artifacts_dir: Directory for code execution artifacts- verbose: Whether to print detailed information-- Returns:- tuple: (raw_answer, metadata)- """- tool_type = record.tool_type- query = record.query-- if tool_type == "rag_naive":- result = await rag_search(query=query, kb_name=kb_name, mode="naive")- answer = result.get("answer", "")- source, auto_sources = self._infer_sources(answer)- metadata = {"source": source, "auto_sources": auto_sources, "mode": "naive"}- return answer, metadata-- if tool_type == "rag_hybrid":- result = await rag_search(query=query, kb_name=kb_name, mode="hybrid")- answer = result.get("answer", "")- source, auto_sources = self._infer_sources(answer)- metadata = {"source": source, "auto_sources": auto_sources, "mode": "hybrid"}- return answer, metadata-- if tool_type == "web_search":- result = web_search(query=query, output_dir=output_dir, verbose=verbose)- answer = result.get("answer") or result.get("summary") or ""- used_citation_ids = self._extract_answer_citations(answer)- filtered_citations = self._select_web_citations(used_citation_ids, result)- metadata = {"result_file": result.get("result_file"), "citations": filtered_citations}- return answer, metadata-- if tool_type == "code_execution":- artifacts_path = Path(artifacts_dir)- before_snapshot = self._snapshot_image_artifacts(artifacts_path)-- if not query or not query.strip():- # If code is empty, directly return failure without execution- raw_answer = "【⚠️ Code execution failed】\nError: No valid code input received (Code is empty). Please check if [QUERY] contains a markdown code block."- metadata = {- "exit_code": 1,- "artifacts": [],- "artifact_paths": [],- "artifact_rel_paths": [],- "work_dir": artifacts_dir,- "execution_failed": True,- }- return raw_answer, metadata-- code = await self._generate_code_from_intent(query)-- exec_result = await run_code(- language="python",- code=code,- timeout=self.agent_config.get("code_timeout", 20),- assets_dir=artifacts_dir,- )- raw_answer = self._format_code_answer(exec_result, artifacts_dir)- exit_code = exec_result.get("exit_code", 0)-- # Check if code execution failed- is_failed = exit_code != 0- if is_failed:- stderr = exec_result.get("stderr", "")- # Add obvious error prefix at the beginning of raw_answer- error_prefix = "【⚠️ Code execution failed】\n"- if "FileNotFoundError" in stderr and "artifacts/" in stderr:- error_prefix += "Path error detected: Code uses 'artifacts/xxx.png', but working directory is already the artifacts directory.\n"- error_prefix += "Please use 'xxx.png' instead of 'artifacts/xxx.png'.\n\n"- raw_answer = error_prefix + raw_answer-- new_image_paths = self._collect_new_image_artifacts(- artifacts_path=artifacts_path,- before_snapshot=before_snapshot,- output_dir=output_dir,- )-- metadata = {- "exit_code": exit_code,- "artifacts": exec_result.get("artifacts", []),- "artifact_paths": exec_result.get("artifact_paths", []),- "artifact_rel_paths": new_image_paths,- "work_dir": artifacts_dir,- "execution_failed": is_failed,- }- return raw_answer, metadata-- raise ValueError(f"Unknown tool type: {tool_type}")-- def _format_code_answer(self, exec_result: dict[str, Any], artifacts_dir: str) -> str:- """Format code execution result as a readable string"""- stdout = exec_result.get("stdout", "")- stderr = exec_result.get("stderr", "")- artifacts = exec_result.get("artifacts", [])- artifact_paths = exec_result.get("artifact_paths", [])-- lines = [- "【Code Execution Result】",- f"Exit code: {exec_result.get('exit_code')}",- f"Elapsed time: {exec_result.get('elapsed_ms', 0):.2f} ms",- f"Working directory: {artifacts_dir}",- "",- "stdout:",- stdout or "(empty)",- "",- "stderr:",- stderr or "(empty)",- ]-- if artifacts:- lines.append("")- lines.append("Artifacts:")- for idx, artifact in enumerate(artifacts):- abs_path = (- artifact_paths[idx]- if idx < len(artifact_paths)- else str(Path(artifacts_dir) / artifact)- )- lines.append(f"- {abs_path}")-- return "\n".join(lines)-- async def _summarize_tool_result(self, tool_type: str, query: str, raw_answer: str) -> str:- """Generate a summary of the tool result using LLM"""- system_prompt = self.get_prompt("system") if self.has_prompts() else None- if not system_prompt:- raise ValueError(- "ToolAgent missing system prompt, please configure system in prompts/{lang}/solve_loop/tool_agent.yaml"- )-- template = self.get_prompt("user_template") if self.has_prompts() else None- if not template:- raise ValueError(- "ToolAgent missing user_template, please configure user_template in prompts/{lang}/solve_loop/tool_agent.yaml"- )-- user_prompt = template.format(- tool_type=tool_type, query=query, raw_answer=raw_answer[:2000]- )-- response = await self.call_llm(- user_prompt=user_prompt, system_prompt=system_prompt, verbose=False- )- return response.strip()-- # ------------------------------------------------------------------ #- # Helper methods- # ------------------------------------------------------------------ #- def _infer_sources(self, text: str) -> tuple[str, list[str]]:- """Extract URLs from text"""- if not text:- return "", []- matches = re.findall(r"(https?://[^\s\)\]]+)", text)- cleaned = []- for item in matches:- normalized = item.strip().strip(".,;:()[]{}")- if normalized and normalized not in cleaned:- cleaned.append(normalized)- return (", ".join(cleaned), cleaned)-- def _extract_answer_citations(self, answer: str) -> list[str]:- """Extract citation IDs from answer text"""- if not answer:- return []- pattern = re.compile(r"\[(\d+)\]")- ids = pattern.findall(answer)- unique: list[str] = []- for cid in ids:- if cid not in unique:- unique.append(cid)- return unique-- def _select_web_citations(- self, used_ids: list[str], result: dict[str, Any]- ) -> list[dict[str, Any]]:- """Select and format web citations based on used IDs"""- if not used_ids:- return []- raw_citations = result.get("citations") or []- search_results = result.get("search_results") or []- search_map = {item.get("url"): item for item in search_results if item.get("url")}-- selected: list[dict[str, Any]] = []- for cid in used_ids:- matched = None- for raw in raw_citations:- ref_id = str(raw.get("id")) if raw.get("id") is not None else ""- ref_token = (raw.get("reference") or "").strip()- normalized_token = ref_token.strip("[]")- if cid == ref_id or cid == normalized_token:- matched = dict(raw)- break- if not matched:- continue-- url = matched.get("url")- if url and url in search_map:- fallback = search_map[url]- matched.setdefault("title", fallback.get("title", ""))- matched.setdefault("snippet", fallback.get("snippet", ""))-- selected.append(- {- "id": matched.get("id") or (int(cid) if cid.isdigit() else cid),- "reference": matched.get("reference") or f"[{cid}]",- "url": matched.get("url"),- "title": matched.get("title", ""),- }- )- return selected-- # ------------------------------------------------------------------ #- # Artifacts helpers- # ------------------------------------------------------------------ #- IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}-- def _snapshot_image_artifacts(self, artifacts_path: Path) -> set:- """Take a snapshot of existing image files in artifacts directory"""- if not artifacts_path.exists():- return set()- snapshot = set()- for file_path in artifacts_path.rglob("*"):- if file_path.is_file() and file_path.suffix.lower() in self.IMAGE_SUFFIXES:- snapshot.add(file_path.resolve())- return snapshot-- def _collect_new_image_artifacts(- self, artifacts_path: Path, before_snapshot: set, output_dir: str | None- ) -> list[str]:- """Collect newly created image artifacts"""- after_snapshot = self._snapshot_image_artifacts(artifacts_path)- new_files = sorted(after_snapshot - before_snapshot)- if not new_files:- return []-- rel_paths: list[str] = []- output_base = Path(output_dir).resolve() if output_dir else None-- for file_path in new_files:- rel_path: str | None = None- if output_base:- try:- rel_path = str(file_path.relative_to(output_base)).replace("\\", "/")- except ValueError:- rel_path = None- if rel_path is None:- try:- rel_path = str(file_path.relative_to(artifacts_path.parent)).replace("\\", "/")- except ValueError:- rel_path = str(Path("artifacts") / file_path.name)- rel_paths.append(rel_path)-- return rel_pathsdiff --git a/src/agents/solve/tools/__init__.py b/src/agents/solve/tools/__init__.pynew file mode 100644index 000000000..5e29b7eeb--- /dev/null+++ b/src/agents/solve/tools/__init__.py@@ -0,0 +1,5 @@+"""Dynamic tool registry for the solve pipeline."""++from .registry import ToolDefinition, ToolRegistry++__all__ = ["ToolDefinition", "ToolRegistry"]diff --git a/src/agents/solve/tools/definitions/en/code_execute.yaml b/src/agents/solve/tools/definitions/en/code_execute.yamlnew file mode 100644index 000000000..7b580baf9--- /dev/null+++ b/src/agents/solve/tools/definitions/en/code_execute.yaml@@ -0,0 +1,14 @@+name: code_execute+order: 3+type: tool++planner_description: "Execute Python code in a sandbox (calculations, plotting, data processing)"++solver:+ when_to_use: "Need computation, derivation, plotting, or data processing"+ action_input: "A clear description of **what** to compute (the system will generate and run Python code)"+ guideline: "when the step involves computation, derivation, numerical verification, or data processing / plotting."+ note: >-+ For `code_execute`, describe the intent clearly+ (e.g., "compute the convolution of x=[1,2,3] and h=[1,1]");+ the system handles code generation.diff --git a/src/agents/solve/tools/definitions/en/done.yaml b/src/agents/solve/tools/definitions/en/done.yamlnew file mode 100644index 000000000..2e9bccee7--- /dev/null+++ b/src/agents/solve/tools/definitions/en/done.yaml@@ -0,0 +1,11 @@+name: done+order: 10+type: control++planner_description: ""++solver:+ when_to_use: "You already have **sufficient** information to answer the current step"+ action_input: 'Leave empty `""`'+ guideline: ""+ note: ""diff --git a/src/agents/solve/tools/definitions/en/rag_search.yaml b/src/agents/solve/tools/definitions/en/rag_search.yamlnew file mode 100644index 000000000..0509ff2ba--- /dev/null+++ b/src/agents/solve/tools/definitions/en/rag_search.yaml@@ -0,0 +1,11 @@+name: rag_search+order: 1+type: tool++planner_description: "Search the uploaded knowledge base (textbooks, lecture notes, etc.)"++solver:+ when_to_use: "Need information from the knowledge base (definitions, formulas, theorems, examples)"+ action_input: "A precise search query string"+ guideline: "when the knowledge base likely has relevant content (definitions, theorems, examples, textbook material)."+ note: ""diff --git a/src/agents/solve/tools/definitions/en/reason.yaml b/src/agents/solve/tools/definitions/en/reason.yamlnew file mode 100644index 000000000..7cf608a14--- /dev/null+++ b/src/agents/solve/tools/definitions/en/reason.yaml@@ -0,0 +1,13 @@+name: reason+order: 4+type: tool++planner_description: "Perform deep reasoning / logical deduction on a sub-problem without external tools"++solver:+ when_to_use: "Need deeper analysis, logical deduction, mathematical derivation, or synthesis of already-gathered information — no external tool call needed"+ action_input: "A clear description of the reasoning focus — what needs to be analyzed or derived"+ guideline: "when the step requires pure logical reasoning, derivation, or synthesis of already-gathered information, and no new external information is needed."+ note: >-+ Use `reason` for **thinking**, not for **finding facts**.+ If you need new factual information, use `rag_search`, `web_search`, or `code_execute` instead.diff --git a/src/agents/solve/tools/definitions/en/replan.yaml b/src/agents/solve/tools/definitions/en/replan.yamlnew file mode 100644index 000000000..75efc1afc--- /dev/null+++ b/src/agents/solve/tools/definitions/en/replan.yaml@@ -0,0 +1,13 @@+name: replan+order: 11+type: control++planner_description: ""++solver:+ when_to_use: "The original plan is fundamentally flawed (wrong premise, missing critical info, etc.)"+ action_input: "A brief reason explaining why a replan is needed"+ guideline: ""+ note: >-+ Use `replan` **sparingly** — only when the plan itself is wrong,+ not when a single search returns poor results (retry with a better query instead).diff --git a/src/agents/solve/tools/definitions/en/web_search.yaml b/src/agents/solve/tools/definitions/en/web_search.yamlnew file mode 100644index 000000000..2222f92c2--- /dev/null+++ b/src/agents/solve/tools/definitions/en/web_search.yaml@@ -0,0 +1,11 @@+name: web_search+order: 2+type: tool++planner_description: "Search the internet for external information"++solver:+ when_to_use: "Need external / up-to-date information not in the knowledge base"+ action_input: "A search query string"+ guideline: "when you need up-to-date information, external perspectives, or the knowledge base falls short."+ note: ""diff --git a/src/agents/solve/tools/definitions/zh/code_execute.yaml b/src/agents/solve/tools/definitions/zh/code_execute.yamlnew file mode 100644index 000000000..10da1e110--- /dev/null+++ b/src/agents/solve/tools/definitions/zh/code_execute.yaml@@ -0,0 +1,13 @@+name: code_execute+order: 3+type: tool++planner_description: "在沙箱中执行 Python 代码(计算、绘图、数据处理)"++solver:+ when_to_use: "需要计算、推导、绘图或数据处理"+ action_input: "清晰描述**要计算什么**(系统会自动生成并运行 Python 代码)"+ guideline: "当步骤涉及计算、推导、数值验证或数据处理/绘图时。"+ note: >-+ 对于 `code_execute`,请清晰描述意图+ (例如:"计算 x=[1,2,3] 和 h=[1,1] 的卷积");系统会负责代码生成。diff --git a/src/agents/solve/tools/definitions/zh/done.yaml b/src/agents/solve/tools/definitions/zh/done.yamlnew file mode 100644index 000000000..a68036eb2--- /dev/null+++ b/src/agents/solve/tools/definitions/zh/done.yaml@@ -0,0 +1,11 @@+name: done+order: 10+type: control++planner_description: ""++solver:+ when_to_use: "你已经拥有**充分的**信息来回答当前步骤"+ action_input: '留空 `""`'+ guideline: ""+ note: ""diff --git a/src/agents/solve/tools/definitions/zh/rag_search.yaml b/src/agents/solve/tools/definitions/zh/rag_search.yamlnew file mode 100644index 000000000..3935f3b86--- /dev/null+++ b/src/agents/solve/tools/definitions/zh/rag_search.yaml@@ -0,0 +1,11 @@+name: rag_search+order: 1+type: tool++planner_description: "检索已上传的知识库(教材、讲义等)"++solver:+ when_to_use: "需要从知识库获取信息(定义、公式、定理、示例)"+ action_input: "精确的搜索查询字符串"+ guideline: "当知识库可能包含相关内容时(定义、定理、示例、教材内容)。"+ note: ""diff --git a/src/agents/solve/tools/definitions/zh/reason.yaml b/src/agents/solve/tools/definitions/zh/reason.yamlnew file mode 100644index 000000000..500d1f069--- /dev/null+++ b/src/agents/solve/tools/definitions/zh/reason.yaml@@ -0,0 +1,13 @@+name: reason+order: 4+type: tool++planner_description: "对子问题进行深度推理/逻辑推演,无需外部工具"++solver:+ when_to_use: "需要更深入的分析、逻辑推演、数学推导,或对已收集信息的综合 — 不需要外部工具调用"+ action_input: "清晰描述推理的重点 — 需要分析或推导什么"+ guideline: "当步骤需要纯逻辑推理、推导或综合已有信息,且不需要新的外部信息时。"+ note: >-+ `reason` 用于**思考**,而非**查找事实**。+ 如果需要新的事实性信息,请改用 `rag_search`、`web_search` 或 `code_execute`。diff --git a/src/agents/solve/tools/definitions/zh/replan.yaml b/src/agents/solve/tools/definitions/zh/replan.yamlnew file mode 100644index 000000000..742bd5716--- /dev/null+++ b/src/agents/solve/tools/definitions/zh/replan.yaml@@ -0,0 +1,13 @@+name: replan+order: 11+type: control++planner_description: ""++solver:+ when_to_use: "原始计划存在根本性缺陷(前提错误、缺少关键信息等)"+ action_input: "简述需要重新规划的原因"+ guideline: ""+ note: >-+ **谨慎使用** `replan` — 仅当计划本身存在错误时使用,+ 而不是当某次搜索结果不佳时(应该用更好的查询重试)。diff --git a/src/agents/solve/tools/definitions/zh/web_search.yaml b/src/agents/solve/tools/definitions/zh/web_search.yamlnew file mode 100644index 000000000..99118a5a7--- /dev/null+++ b/src/agents/solve/tools/definitions/zh/web_search.yaml@@ -0,0 +1,11 @@+name: web_search+order: 2+type: tool++planner_description: "搜索互联网获取外部信息"++solver:+ when_to_use: "需要外部/最新信息,知识库中没有的内容"+ action_input: "搜索查询字符串"+ guideline: "当需要最新信息、外部观点,或知识库不足时。"+ note: ""diff --git a/src/agents/solve/tools/registry.py b/src/agents/solve/tools/registry.pynew file mode 100644index 000000000..267912123--- /dev/null+++ b/src/agents/solve/tools/registry.py@@ -0,0 +1,231 @@+"""+Tool registry — each tool owns its own prompt definition (YAML file).++The registry loads per-tool YAML files from a definitions directory,+maintains an ordered list of active tools, and composes the+``tools_description`` prompt variable for planner and solver agents.++Usage:+ registry = ToolRegistry.create_default(language="en")+ registry.unregister("web_search") # disable a tool+ planner_desc = registry.build_planner_description(kb_name="physics")+ solver_desc = registry.build_solver_description()+"""++from __future__ import annotations++import logging+from dataclasses import dataclass+from pathlib import Path++import yaml++logger = logging.getLogger(__name__)++_SOLVER_GUIDELINE_HEADER = {+ "en": (+ "**Autonomously decide which tool to use** based on the nature "+ "of the sub-goal and the evidence gathered so far. Do not "+ "default to any single tool — consider all options:"+ ),+ "zh": (+ "**根据子目标的性质和已收集的证据,自主决定使用哪个工具**。"+ "不要默认只使用某一种工具 — 考虑所有选项:"+ ),+}+++@dataclass+class ToolDefinition:+ """Prompt-level definition of a single tool / control action."""++ name: str+ order: int = 0+ tool_type: str = "tool" # "tool" | "control"++ # Planner prompt: one-liner+ planner_description: str = ""++ # Solver prompt: table row + optional guideline + optional note+ solver_when: str = ""+ solver_input: str = ""+ solver_guideline: str = ""+ solver_note: str = ""+++class ToolRegistry:+ """Manages tool definitions and composes prompt fragments dynamically.++ Each tool has its own YAML definition file. The registry loads them,+ maintains a sorted list, and provides methods to compose the+ ``{tools_description}`` template variable for planner and solver prompts.+ """++ def __init__(self, language: str = "en") -> None:+ self._tools: dict[str, ToolDefinition] = {}+ self.language = language++ # ------------------------------------------------------------------+ # Registration+ # ------------------------------------------------------------------++ def register(self, tool: ToolDefinition) -> None:+ """Register (or replace) a tool definition."""+ self._tools[tool.name] = tool+ logger.debug("Registered tool: %s (type=%s)", tool.name, tool.tool_type)++ def unregister(self, name: str) -> None:+ """Remove a tool from the registry."""+ if self._tools.pop(name, None):+ logger.debug("Unregistered tool: %s", name)++ def get(self, name: str) -> ToolDefinition | None:+ return self._tools.get(name)++ @property+ def _ordered(self) -> list[ToolDefinition]:+ return sorted(self._tools.values(), key=lambda t: t.order)++ @property+ def valid_actions(self) -> set[str]:+ """All registered action names (for response validation)."""+ return set(self._tools)++ @property+ def tool_names(self) -> list[str]:+ """Ordered list of registered tool names."""+ return [t.name for t in self._ordered]++ # ------------------------------------------------------------------+ # Prompt composition+ # ------------------------------------------------------------------++ def build_planner_description(self, kb_name: str = "") -> str:+ """One-liner list for the planner's ``{tools_description}`` variable."""+ lines: list[str] = []+ for tool in self._ordered:+ if tool.tool_type != "tool" or not tool.planner_description:+ continue+ desc = tool.planner_description+ if kb_name:+ desc = desc.replace(+ "the uploaded knowledge base",+ f'the knowledge base "{kb_name}"',+ )+ desc = desc.replace("已上传的知识库", f'知识库 "{kb_name}"')+ lines.append(f"- {tool.name}: {desc}")+ return "\n".join(lines)++ def build_solver_description(self) -> str:+ """Full tool section for the solver's ``{tools_description}`` variable.++ Includes: action table, tool-selection guidelines, tool-specific notes.+ """+ parts: list[str] = []+ ordered = self._ordered++ # --- action table ---+ table_lines = [+ "| action | When to use | action_input |",+ "|--------|------------|--------------|",+ ]+ for t in ordered:+ if t.solver_when:+ table_lines.append(+ f"| `{t.name}` | {t.solver_when} | {t.solver_input} |"+ )+ parts.append("\n".join(table_lines))++ # --- tool-selection guidelines ---+ guidelines = [+ t for t in ordered if t.tool_type == "tool" and t.solver_guideline+ ]+ if guidelines:+ header = _SOLVER_GUIDELINE_HEADER.get(+ self.language, _SOLVER_GUIDELINE_HEADER["en"]+ )+ bullets = "\n".join(+ f" - `{t.name}` {t.solver_guideline}" for t in guidelines+ )+ parts.append(f"{header}\n{bullets}")++ # --- tool-specific notes ---+ notes = [t for t in ordered if t.solver_note]+ if notes:+ parts.append("\n".join(f"- {t.solver_note}" for t in notes))++ return "\n\n".join(parts)++ # ------------------------------------------------------------------+ # Loading helpers+ # ------------------------------------------------------------------++ @classmethod+ def load_from_directory(+ cls, directory: str | Path, language: str = "en",+ ) -> "ToolRegistry":+ """Load all ``*.yaml`` files from *directory* into a new registry."""+ registry = cls(language=language)+ directory = Path(directory)+ if not directory.is_dir():+ logger.warning("Tool definitions directory not found: %s", directory)+ return registry++ for yaml_file in sorted(directory.glob("*.yaml")):+ try:+ with open(yaml_file, encoding="utf-8") as f:+ data = yaml.safe_load(f) or {}+ tool = cls._parse_definition(data)+ if tool:+ registry.register(tool)+ except Exception as exc:+ logger.warning(+ "Failed to load tool definition %s: %s", yaml_file.name, exc,+ )++ logger.info(+ "Loaded %d tool definitions from %s", len(registry._tools), directory,+ )+ return registry++ @classmethod+ def create_default(cls, language: str = "en") -> "ToolRegistry":+ """Load the default tool definitions shipped with the solve module."""+ definitions_dir = Path(__file__).parent / "definitions" / language+ if not definitions_dir.is_dir():+ definitions_dir = Path(__file__).parent / "definitions" / "en"+ return cls.load_from_directory(definitions_dir, language=language)++ @classmethod+ def create_from_names(+ cls,+ tool_names: list[str],+ language: str = "en",+ ) -> "ToolRegistry":+ """Load all default definitions, then keep only the listed tools.++ Control actions ``done`` and ``replan`` are always included.+ """+ registry = cls.create_default(language=language)+ keep = set(tool_names) | {"done", "replan"}+ for name in list(registry._tools):+ if name not in keep:+ registry.unregister(name)+ return registry++ @staticmethod+ def _parse_definition(data: dict) -> ToolDefinition | None:+ name = data.get("name")+ if not name:+ return None+ solver = data.get("solver") or {}+ return ToolDefinition(+ name=name,+ order=data.get("order", 99),+ tool_type=data.get("type", "tool"),+ planner_description=data.get("planner_description", ""),+ solver_when=solver.get("when_to_use", ""),+ solver_input=solver.get("action_input", ""),+ solver_guideline=solver.get("guideline", ""),+ solver_note=solver.get("note", ""),+ )diff --git a/src/agents/solve/utils/__init__.py b/src/agents/solve/utils/__init__.pyindex b23e62b5a..e38a3d8b3 100644--- a/src/agents/solve/utils/__init__.py+++ b/src/agents/solve/utils/__init__.py@@ -1,10 +1,7 @@-#!/usr/bin/env python"""-Utility Module-Contains logging, performance monitoring, config validation, parsers, etc.+Utility module for the solve agent."""-# Logging system (from unified logs module)from pathlib import Pathimport sys@@ -15,50 +12,21 @@ if str(project_root) not in sys.path:from src.logging import Logger, LogLevel, get_logger, reset_logger-# Backwards compatibility aliases-# These aliases maintain compatibility with code that imported these names before refactoring-SolveAgentLogger = Logger # Alias for Logger class-from .config_validator import ConfigValidator-from .error_handler import (- LLMParseError,- retry_on_parse_error,- validate_investigate_output,- validate_none_tool_constraint,- validate_note_output,- validate_output,- validate_reflect_output,- validate_solve_output,-)--# Backwards compatibility alias-ParseError = LLMParseError-from .performance_monitor import PerformanceMonitor+# Backwards compatibility alias used by API layer+SolveAgentLogger = Logger# Token trackerfrom .token_tracker import TokenTracker, calculate_cost, get_model_pricing__all__ = [- # Logging system+ # Logging"Logger","get_logger","reset_logger","LogLevel",- "SolveAgentLogger", # Backwards compatibility- # Performance monitoring- "PerformanceMonitor",- # Config validation- "ConfigValidator",+ "SolveAgentLogger",# Token tracker"TokenTracker","calculate_cost","get_model_pricing",- # Error handling- "ParseError",- "retry_on_parse_error",- "validate_output",- "validate_investigate_output",- "validate_note_output",- "validate_none_tool_constraint",- "validate_reflect_output",- "validate_solve_output",]diff --git a/src/agents/solve/utils/config_validator.py b/src/agents/solve/utils/config_validator.pydeleted file mode 100644index 2397b04b3..000000000--- a/src/agents/solve/utils/config_validator.py+++ /dev/null@@ -1,313 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-Config Validator - Configuration validator-Validates the completeness and correctness of config.yaml-"""--from pathlib import Path-from typing import Any--import yaml---class ConfigValidator:- """Configuration validator"""-- # Required top-level configuration items- # Note: llm configuration has been moved to environment variables (env_config.py), no longer required in config.yaml- REQUIRED_SECTIONS = ["system", "agents"]-- # Required system configuration- REQUIRED_SYSTEM_CONFIGS = [- "output_base_dir",- "save_intermediate_results",- # Note: language is now unified in config/main.yaml, not required in sub-configs- ]-- # Supported languages (supports multiple formats)- SUPPORTED_LANGUAGES = ["zh", "en", "English", "Chinese"]-- # Supported log levels- SUPPORTED_LOG_LEVELS = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]-- # Agent list - dual-loop architecture- STANDARD_AGENTS = [- # Analysis Loop- "investigate_agent",- "note_agent",- # Solve Loop- "manager_agent",- "solve_agent",- "tool_agent",- "response_agent",- "precision_answer_agent",- ]-- def __init__(self):- self.errors: list[str] = []- self.warnings: list[str] = []-- def validate(self, config: dict[str, Any]) -> tuple[bool, list[str], list[str]]:- """- Validate configuration-- Args:- config: Configuration dictionary-- Returns:- (is_valid, errors, warnings)- """- self.errors = []- self.warnings = []-- # 1. Validate top-level structure- self._validate_structure(config)-- # 2. Validate system configuration- if "system" in config:- self._validate_system(config["system"])-- # 3. Validate agents configuration- if "agents" in config:- self._validate_agents(config["agents"])-- # 4. Validate llm configuration (optional, LLM config now mainly comes from environment variables)- if "llm" in config:- self._validate_llm(config["llm"])-- # 5. Validate logging configuration (optional)- if "logging" in config:- self._validate_logging(config["logging"])-- # 6. Validate monitoring configuration (optional)- if "monitoring" in config:- self._validate_monitoring(config["monitoring"])-- is_valid = len(self.errors) == 0- return is_valid, self.errors, self.warnings-- def _validate_structure(self, config: dict[str, Any]):- """Validate top-level structure"""- for section in self.REQUIRED_SECTIONS:- if section not in config:- self.errors.append(f"Missing required configuration section: {section}")-- def _validate_system(self, system_config: dict[str, Any]):- """Validate system configuration"""- if system_config is None:- self.errors.append("system configuration cannot be None")- return-- # Check required fields- for field in self.REQUIRED_SYSTEM_CONFIGS:- if field not in system_config:- self.errors.append(f"system config missing required field: {field}")-- # Check language configuration (unified in config/main.yaml, optional in sub-configs)- if "language" in system_config:- lang = system_config["language"]- if lang not in self.SUPPORTED_LANGUAGES:- self.warnings.append(- f"language '{lang}' not in supported list: {self.SUPPORTED_LANGUAGES}. Suggest unified configuration in config/main.yaml."- )- # Backward compatibility: if output_language still exists, give warning- if "output_language" in system_config:- self.warnings.append(- "output_language is deprecated, please use language field. Language configuration has been unified to system.language in config/main.yaml"- )-- # Check auto_solve configuration- if "auto_solve" in system_config:- if not isinstance(system_config["auto_solve"], bool):- self.errors.append("auto_solve must be a boolean value")-- def _validate_agents(self, agents_config: dict[str, Any]):- """Validate agents configuration"""- if agents_config is None:- self.errors.append("agents config cannot be None")- return-- # Check if standard agents are configured- for agent_name in self.STANDARD_AGENTS:- if agent_name not in agents_config:- self.warnings.append(f"Agent not configured: {agent_name}")- else:- self._validate_agent_config(agent_name, agents_config[agent_name])-- def _validate_agent_config(self, agent_name: str, agent_config: dict[str, Any]):- """Validate single Agent configuration"""- if agent_config is None:- self.errors.append(f"{agent_name} config cannot be None")- return-- # Check enabled field- if "enabled" in agent_config:- if not isinstance(agent_config["enabled"], bool):- self.errors.append(f"{agent_name}.enabled must be a boolean value")-- # Check model field- if "model" in agent_config:- if not isinstance(agent_config["model"], str):- self.errors.append(f"{agent_name}.model must be a string")-- # Check temperature field- if "temperature" in agent_config:- temp = agent_config["temperature"]- if not isinstance(temp, (int, float)):- self.errors.append(f"{agent_name}.temperature must be a number")- elif not 0 <= temp <= 2:- self.warnings.append(- f"{agent_name}.temperature={temp} exceeds recommended range [0, 2]"- )-- # Check max_retries field- if "max_retries" in agent_config:- if not isinstance(agent_config["max_retries"], int):- self.errors.append(f"{agent_name}.max_retries must be an integer")- elif agent_config["max_retries"] < 0:- self.errors.append(f"{agent_name}.max_retries cannot be negative")-- def _validate_llm(self, llm_config: dict[str, Any]):- """Validate llm configuration"""- if llm_config is None:- self.errors.append("llm config cannot be None")- return-- # Check default_model- if "default_model" not in llm_config:- self.warnings.append("llm config missing default_model field")-- # Check max_retries- if "max_retries" in llm_config:- if not isinstance(llm_config["max_retries"], int):- self.errors.append("llm.max_retries must be an integer")- elif llm_config["max_retries"] < 0:- self.errors.append("llm.max_retries cannot be negative")-- # Check timeout- if "timeout" in llm_config:- if not isinstance(llm_config["timeout"], (int, float)):- self.errors.append("llm.timeout must be a number")- elif llm_config["timeout"] <= 0:- self.warnings.append("llm.timeout should not be negative or zero")-- def _validate_logging(self, logging_config: dict[str, Any]):- """Validate logging configuration"""- if logging_config is None:- # logging is optional, if None but not empty key, may be considered error or ignored- self.errors.append("logging config cannot be None")- return-- # Check level- if "level" in logging_config:- level = logging_config["level"]- if level not in self.SUPPORTED_LOG_LEVELS:- self.errors.append(- f"logging.level '{level}' not in supported list: {self.SUPPORTED_LOG_LEVELS}"- )-- # Check save_to_file- if "save_to_file" in logging_config:- if not isinstance(logging_config["save_to_file"], bool):- self.errors.append("logging.save_to_file must be a boolean value")-- # Check verbose- if "verbose" in logging_config:- if not isinstance(logging_config["verbose"], bool):- self.errors.append("logging.verbose must be a boolean value")-- def _validate_monitoring(self, monitoring_config: dict[str, Any]):- """Validate monitoring configuration"""- if monitoring_config is None:- self.errors.append("monitoring config cannot be None")- return-- # Check enabled- if "enabled" in monitoring_config:- if not isinstance(monitoring_config["enabled"], bool):- self.errors.append("monitoring.enabled must be a boolean value")-- # Check track_token_usage- if "track_token_usage" in monitoring_config:- if not isinstance(monitoring_config["track_token_usage"], bool):- self.errors.append("monitoring.track_token_usage must be a boolean value")-- # Check track_time- if "track_time" in monitoring_config:- if not isinstance(monitoring_config["track_time"], bool):- self.errors.append("monitoring.track_time must be a boolean value")---def validate_config_file(config_path: str) -> tuple[bool, list[str], list[str]]:- """- Validate configuration file-- Args:- config_path: Configuration file path-- Returns:- (is_valid, errors, warnings)- """- try:- with open(config_path, encoding="utf-8") as f:- config = yaml.safe_load(f)- except FileNotFoundError:- return False, [f"Configuration file does not exist: {config_path}"], []- except yaml.YAMLError as e:- return False, [f"YAML parsing error: {e!s}"], []- except Exception as e:- return False, [f"Failed to load configuration file: {e!s}"], []-- validator = ConfigValidator()- return validator.validate(config)---def print_validation_result(is_valid: bool, errors: list[str], warnings: list[str]):- """- Print validation result-- Args:- is_valid: Whether configuration is valid- errors: List of errors- warnings: List of warnings- """- print("=" * 60)- print("Configuration Validation Result")- print("=" * 60)-- if is_valid:- print("✓ Configuration validation passed")- else:- print("✗ Configuration validation failed")-- print()-- if errors:- print(f"Errors ({len(errors)}):")- for i, error in enumerate(errors, 1):- print(f" {i}. {error}")- print()-- if warnings:- print(f"Warnings ({len(warnings)}):")- for i, warning in enumerate(warnings, 1):- print(f" {i}. {warning}")- print()-- print("=" * 60)---if __name__ == "__main__":- # Test configuration validation- print("Configuration Validation Test")- print("=" * 60)-- # Validate config.yaml in current directory- config_path = Path(__file__).parent.parent.parent.parent / "config.yaml"-- if config_path.exists():- is_valid, errors, warnings = validate_config_file(str(config_path))- print_validation_result(is_valid, errors, warnings)- else:- print(f"Configuration file not found: {config_path}")diff --git a/src/agents/solve/utils/display_manager.py b/src/agents/solve/utils/display_manager.pyindex 34b086157..fb8211802 100644--- a/src/agents/solve/utils/display_manager.py+++ b/src/agents/solve/utils/display_manager.py@@ -36,13 +36,9 @@ class DisplayManager:self.rich_available = RICH_AVAILABLEself.agents_status = {- "InvestigateAgent": "pending",- "NoteAgent": "pending",- "ManagerAgent": "pending",- "SolveAgent": "pending",- "ToolAgent": "pending",- "ResponseAgent": "pending",- "PrecisionAnswerAgent": "pending",+ "PlannerAgent": "pending",+ "SolverAgent": "pending",+ "WriterAgent": "pending",}self.stats = {diff --git a/src/agents/solve/utils/error_handler.py b/src/agents/solve/utils/error_handler.pydeleted file mode 100644index 3eda67488..000000000--- a/src/agents/solve/utils/error_handler.py+++ /dev/null@@ -1,363 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-Error Handler - Error handling and retry mechanism-"""--from collections.abc import Callable-from typing import Any, Optional--from pydantic import BaseModel, Field, ValidationError, field_validator, model_validator-import tenacity--from src.config.constants import VALID_INVESTIGATE_TOOLS, VALID_SOLVE_TOOLS-from src.logging.logger import get_logger-from src.services.llm.exceptions import LLMParseError---def _format_validation_errors(e: ValidationError) -> str:- """Format Pydantic validation errors into a readable string."""- return "; ".join(- [f"{'.'.join(str(x) for x in err['loc']) or 'root'}: {err['msg']}" for err in e.errors()]- )---# Pydantic models for output validation-class ToolIntent(BaseModel):- """Model for tool intent in investigate output"""-- tool_type: str = Field(..., description="Type of tool to use")- query: str = Field("", description="Query for the tool")- identifier: Optional[str] = Field(None, description="Optional identifier")-- @field_validator("tool_type")- @classmethod- def validate_tool_type(cls, v):- if v.lower() not in VALID_INVESTIGATE_TOOLS:- raise ValueError(f"tool_type must be one of {VALID_INVESTIGATE_TOOLS}, got: {v}")- return v.lower()-- @field_validator("query")- @classmethod- def validate_query_required(cls, v, info):- tool_type = info.data.get("tool_type", "").lower()- if tool_type != "none" and not v:- raise ValueError("query is required for non-none tools")- return v---class InvestigateOutput(BaseModel):- """Model for InvestigateAgent output"""-- reasoning: str = Field(..., description="Reasoning for the investigation")- tools: list[ToolIntent] = Field(..., min_length=1, description="List of tool intents")-- @field_validator("tools")- @classmethod- def validate_tools_consistency(cls, v):- # Check for 'none' tool exclusivity- has_none = any(tool.tool_type == "none" for tool in v)- if has_none and len(v) > 1:- raise ValueError("When 'none' tool exists, no other tool intents should be provided")- return v---class Citation(BaseModel):- """Model for citation in note output"""-- reference_id: Optional[str] = None- source: Optional[str] = None- content: Optional[str] = None-- @model_validator(mode="after")- def validate_citation_fields(self):- """Validate that at least one of reference_id or source is provided."""- if not self.reference_id and not self.source:- raise ValueError("citation must contain reference_id or source")- return self---class NoteOutput(BaseModel):- """Model for NoteAgent output"""-- summary: str = Field(..., description="Summary of the notes")- citations: list[Citation] = Field(default_factory=list, description="List of citations")---class ReflectOutput(BaseModel):- """Model for InvestigateReflectAgent output"""-- should_stop: bool = Field(..., description="Whether to stop the investigation")- reason: str = Field(..., description="Reason for the decision")- remaining_questions: list[str] = Field(..., description="List of remaining questions")---class PlanStep(BaseModel):- """Model for plan step"""-- step_id: str = Field(..., description="Step identifier")- plan: str = Field(..., description="Plan description")---class PlanBlock(BaseModel):- """Model for plan block"""-- block_id: str = Field(..., description="Block identifier")- format: str = Field(..., description="Output format")- steps: list[PlanStep] = Field(..., min_length=1, description="List of steps")---class PlanOutput(BaseModel):- """Model for PlanAgent output"""-- answer_style: str = Field(..., description="Style of the answer")- blocks: list[PlanBlock] = Field(..., min_length=1, description="List of plan blocks")---class SolveToolCall(BaseModel):- """Model for tool call in solve output"""-- tool_type: str = Field(..., description="Type of tool to call")- query: str = Field(..., description="Query for the tool call")-- @field_validator("tool_type")- @classmethod- def validate_tool_type(cls, v):- if v.lower() not in VALID_SOLVE_TOOLS:- raise ValueError(f"tool_type must be one of {VALID_SOLVE_TOOLS}, got: {v}")- return v.lower()---class SolveOutput(BaseModel):- """Model for SolveAgent output"""-- tool_calls: list[SolveToolCall] = Field(..., min_length=1, description="List of tool calls")---# Initialize module logger-logger = get_logger("ErrorHandler")---def retry_on_parse_error(- max_retries: int = 2,- delay: float = 1.0,- backoff: float = 2.0,- exceptions: tuple[type[Exception], ...] = (LLMParseError,),-):- """- Parse error retry decorator using tenacity.-- Args:- max_retries: Maximum retry count- delay: Initial delay time (seconds)- backoff: Delay multiplier factor- exceptions: Tuple of exception types to retry on (default: LLMParseError only)-- Returns:- Decorated function- """-- def decorator(func: Callable):- return tenacity.retry(- retry=tenacity.retry_if_exception_type(*exceptions),- wait=tenacity.wait_exponential(multiplier=backoff, min=delay, max=60),- stop=tenacity.stop_after_attempt(max_retries + 1),- before_sleep=lambda retry_state: logger.warning(- f"Parse failed (attempt {retry_state.attempt_number}/{max_retries + 1}), "- f"retrying in {retry_state.upcoming_sleep:.1f}s... Error: {str(retry_state.outcome.exception())}"- ),- )(func)-- return decorator---def validate_output(- output: dict[str, Any], required_fields: list, field_types: dict[str, type] | None = None-) -> bool:- """- Validate output contains required fields and correct types-- Args:- output: Output dictionary- required_fields: List of required fields- field_types: Field type dictionary (optional)-- Returns:- bool: Whether valid-- Raises:- LLMParseError: Raised when validation fails- """- # Check required fields- missing_fields = [field for field in required_fields if field not in output]-- if missing_fields:- raise LLMParseError(f"Missing required fields: {', '.join(missing_fields)}")-- # Check field types- if field_types:- for field, expected_type in field_types.items():- if field in output and not isinstance(output[field], expected_type):- actual_type = type(output[field]).__name__- expected_type_name = expected_type.__name__- raise LLMParseError(- f"Field '{field}' type error: expected {expected_type_name}, got {actual_type}"- )-- return True---def safe_parse(- text: str, parser_func: Callable, default: Any = None, raise_on_error: bool = False-) -> Any:- """- Safe parsing (catch exceptions and return default value)-- Args:- parser_func: Parser function- text: Text to parse- default: Default value- raise_on_error: Whether to raise exception on error-- Returns:- Parsed result or default value- """- try:- return parser_func(text)- except Exception as e:- if raise_on_error:- raise LLMParseError(f"Parsing failed: {e!s}") from e-- logger.error(- f"Parsing failed; falling back to default value {default!r}. This may affect behavior. Error: {e!s}",- exc_info=True,- )- return default---def validate_investigate_output(- output: dict[str, Any], valid_tools: list[str] = VALID_INVESTIGATE_TOOLS-) -> bool:- """Validate InvestigateAgent output using Pydantic model"""- # Check if custom tools are provided- if valid_tools != VALID_INVESTIGATE_TOOLS:- # For custom tools, do manual validation- validate_output(output, ["reasoning"], {"reasoning": str})- tools = output.get("tools", [])- if not isinstance(tools, list) or len(tools) < 1:- raise LLMParseError("tools must be a non-empty list")-- for i, tool in enumerate(tools):- if not isinstance(tool, dict):- raise LLMParseError(f"tool[{i}] must be a dictionary")- tool_type = tool.get("tool_type", "").lower()- if tool_type not in valid_tools:- raise LLMParseError(- f"tool[{i}] tool_type must be one of {valid_tools}, got: {tool_type}"- )- if tool_type != "none" and not tool.get("query"):- raise LLMParseError(f"tool[{i}] missing query")-- # Check none tool exclusivity- has_none = any(t.get("tool_type", "").lower() == "none" for t in tools)- if has_none and len(tools) > 1:- raise LLMParseError("When 'none' tool exists, no other tool intents should be provided")- return True-- # Use Pydantic for standard validation- try:- InvestigateOutput(**output)- return True- except ValidationError as e:- error_details = _format_validation_errors(e)- raise LLMParseError(f"InvestigateAgent output validation failed: {error_details}") from e---def validate_note_output(output: dict[str, Any]) -> bool:- """Validate NoteAgent output using Pydantic model"""- try:- NoteOutput(**output)- return True- except ValidationError as e:- error_details = _format_validation_errors(e)- raise LLMParseError(f"NoteAgent output validation failed: {error_details}") from e---def validate_reflect_output(output: dict[str, Any]) -> bool:- """Validate InvestigateReflectAgent output using Pydantic model"""- try:- ReflectOutput(**output)- return True- except ValidationError as e:- error_details = _format_validation_errors(e)- raise LLMParseError(- f"InvestigateReflectAgent output validation failed: {error_details}"- ) from e---def validate_plan_output(output: dict[str, Any]) -> bool:- """Validate PlanAgent output using Pydantic model"""- try:- PlanOutput(**output)- return True- except ValidationError as e:- error_details = _format_validation_errors(e)- raise LLMParseError(f"PlanAgent output validation failed: {error_details}") from e---def validate_solve_output(- output: dict[str, Any], valid_tool_types: list[str] = VALID_SOLVE_TOOLS-) -> bool:- """Validate SolveAgent output using Pydantic model"""- # Check if custom tools are provided- if valid_tool_types != VALID_SOLVE_TOOLS:- # For custom tools, do manual validation- validate_output(output, ["tool_calls"], {"tool_calls": list})- tool_calls = output.get("tool_calls", [])- if not isinstance(tool_calls, list) or len(tool_calls) < 1:- raise LLMParseError("tool_calls must be a non-empty list")-- for i, tool_call in enumerate(tool_calls):- if not isinstance(tool_call, dict):- raise LLMParseError(f"tool_call[{i}] must be a dictionary")- if "tool_type" not in tool_call or "query" not in tool_call:- raise LLMParseError(f"tool_call[{i}] missing required fields: tool_type, query")- tool_type = tool_call.get("tool_type", "").lower()- if tool_type not in valid_tool_types:- raise LLMParseError(- f"Invalid tool_type: {tool_type}, must be one of {valid_tool_types}"- )- return True-- # Use Pydantic for standard validation- try:- SolveOutput(**output)- return True- except ValidationError as e:- error_details = _format_validation_errors(e)- raise LLMParseError(f"SolveAgent output validation failed: {error_details}") from e---def validate_none_tool_constraint(- tools: list[dict[str, Any]], tool_type_key: str = "tool_type"-) -> None:- """- Validate that 'none' tool does not coexist with other tools.-- Args:- tools: List of tool dictionaries- tool_type_key: Key to access tool type in each dict (default: "tool_type")-- Raises:- LLMParseError: If none tool constraint is violated- """- has_none = any(- isinstance(tool_type := tool.get(tool_type_key), str) and tool_type.lower() == "none"- for tool in tools- )-- if has_none and len(tools) > 1:- raise LLMParseError(- f"When 'none' tool exists, no other tool intents should be provided. "- f"Found {len(tools)} tools with types: {[tool.get(tool_type_key) for tool in tools]}"- )diff --git a/src/agents/solve/utils/performance_monitor.py b/src/agents/solve/utils/performance_monitor.pydeleted file mode 100644index aee5125dd..000000000--- a/src/agents/solve/utils/performance_monitor.py+++ /dev/null@@ -1,409 +0,0 @@-#!/usr/bin/env python-"""-Performance Monitor - Performance monitoring and tracking system-Records Agent execution time, Token consumption and other metrics-"""--from collections.abc import Callable-from contextlib import contextmanager-from dataclasses import asdict, dataclass, field-from datetime import datetime-from functools import wraps-import json-from pathlib import Path-import time-from typing import Any--from src.services.path_service import get_path_service---@dataclass-class PerformanceMetrics:- """Performance metrics"""-- # Basic information- agent_name: str # Agent name- start_time: float # Start time (timestamp)- end_time: float | None = None # End time (timestamp)- duration: float | None = None # Duration (seconds)-- # Token statistics- prompt_tokens: int = 0 # Prompt token count- completion_tokens: int = 0 # Generated token count- total_tokens: int = 0 # Total token count-- # Request statistics- api_calls: int = 0 # API call count- errors: int = 0 # Error count-- # Custom metrics- custom_metrics: dict[str, Any] = field(default_factory=dict)-- def mark_end(self):- """Mark end time and calculate duration"""- self.end_time = time.time()- if self.start_time:- self.duration = self.end_time - self.start_time-- def add_tokens(self, prompt: int = 0, completion: int = 0):- """Add Token statistics"""- self.prompt_tokens += prompt- self.completion_tokens += completion- self.total_tokens = self.prompt_tokens + self.completion_tokens-- def add_api_call(self):- """Increment API call count"""- self.api_calls += 1-- def add_error(self):- """Increment error count"""- self.errors += 1-- def set_custom_metric(self, key: str, value: Any):- """Set custom metric"""- self.custom_metrics[key] = value-- def to_dict(self) -> dict[str, Any]:- """Convert to dictionary"""- return asdict(self)-- def summary(self) -> str:- """Generate summary"""- lines = [- f"Agent: {self.agent_name}",- f"Duration: {self.duration:.2f}s" if self.duration else "Duration: N/A",- f"Total Tokens: {self.total_tokens}",- f" Prompt: {self.prompt_tokens}",- f" Completion: {self.completion_tokens}",- f"API Calls: {self.api_calls}",- f"Errors: {self.errors}",- ]-- if self.custom_metrics:- lines.append("Custom Metrics:")- for k, v in self.custom_metrics.items():- lines.append(f" {k}: {v}")-- return "\n".join(lines)---class PerformanceMonitor:- """Performance monitor"""-- def __init__(self, enabled: bool = True, save_dir: str | None = None):- """- Initialize performance monitor-- Args:- enabled: Whether to enable monitoring- save_dir: Save directory (None uses ./data/user/performance)- """- self.enabled = enabled-- if save_dir is None:- # Default to data/user/agent/logs/performance using PathService- path_service = get_path_service()- self.save_dir = path_service.get_logs_dir() / "performance"- else:- self.save_dir = Path(save_dir)-- if self.enabled:- self.save_dir.mkdir(parents=True, exist_ok=True)-- # Current session metrics- self.metrics: dict[str, PerformanceMetrics] = {}-- # Overall statistics- self.total_duration = 0.0- self.total_tokens = 0- self.total_api_calls = 0- self.total_errors = 0-- def start_tracking(self, agent_name: str) -> PerformanceMetrics:- """- Start tracking Agent performance-- Args:- agent_name: Agent name-- Returns:- PerformanceMetrics instance- """- if not self.enabled:- return PerformanceMetrics(agent_name=agent_name, start_time=time.time())-- metrics = PerformanceMetrics(agent_name=agent_name, start_time=time.time())-- self.metrics[agent_name] = metrics- return metrics-- def end_tracking(self, agent_name: str):- """- End tracking and update statistics-- Args:- agent_name: Agent name- """- if not self.enabled:- return-- if agent_name in self.metrics:- metrics = self.metrics[agent_name]- metrics.mark_end()-- # Update overall statistics- if metrics.duration:- self.total_duration += metrics.duration- self.total_tokens += metrics.total_tokens- self.total_api_calls += metrics.api_calls- self.total_errors += metrics.errors-- @contextmanager- def track(self, agent_name: str):- """- Context manager: automatically track Agent performance-- Args:- agent_name: Agent name-- Usage:- with monitor.track("agent_name"):- # Agent execution logic- ...- """- # Start tracking- metrics = self.start_tracking(agent_name)- try:- yield metrics- except Exception:- # Record error- if self.enabled:- metrics.add_error()- raise- finally:- # End tracking- self.end_tracking(agent_name)-- def get_metrics(self, agent_name: str) -> PerformanceMetrics | None:- """- Get Agent performance metrics-- Args:- agent_name: Agent name-- Returns:- PerformanceMetrics instance, or None if not found- """- return self.metrics.get(agent_name)-- def get_all_metrics(self) -> dict[str, PerformanceMetrics]:- """Get all metrics"""- return self.metrics-- def get_summary(self) -> dict[str, Any]:- """- Get overall statistics summary-- Returns:- {- 'total_duration': float,- 'total_tokens': int,- 'total_api_calls': int,- 'total_errors': int,- 'agents': Dict[str, Dict]- }- """- return {- "total_duration": self.total_duration,- "total_tokens": self.total_tokens,- "total_api_calls": self.total_api_calls,- "total_errors": self.total_errors,- "agents": {name: metrics.to_dict() for name, metrics in self.metrics.items()},- }-- def generate_report(self) -> dict[str, Any]:- """- Generate performance report (alias for get_summary)-- Returns:- Performance report dictionary- """- return self.get_summary()-- def save(self, filepath: str | None = None) -> str:- """- Save performance metrics to file-- Args:- filepath: Save path (None for auto-generated)-- Returns:- Saved file path- """- if not self.enabled:- return ""-- if filepath is None:- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- filepath = self.save_dir / f"performance_{timestamp}.json"- else:- filepath = Path(filepath)-- summary = self.get_summary()-- with open(filepath, "w", encoding="utf-8") as f:- json.dump(summary, f, ensure_ascii=False, indent=2)-- return str(filepath)-- def print_summary(self):- """Print overall statistics summary"""- print("=" * 60)- print("Performance Monitoring Summary")- print("=" * 60)- print(f"Total Duration: {self.total_duration:.2f}s")- print(f"Total Tokens: {self.total_tokens}")- print(f"Total API Calls: {self.total_api_calls}")- print(f"Total Errors: {self.total_errors}")- print()- print("Agent Details:")- print("-" * 60)-- for agent_name, metrics in self.metrics.items():- print(f"\n{agent_name}:")- print(f" Duration: {metrics.duration:.2f}s" if metrics.duration else " Duration: N/A")- print(f" Tokens: {metrics.total_tokens}")- print(f" API Calls: {metrics.api_calls}")- print(f" Errors: {metrics.errors}")-- print("=" * 60)-- def reset(self):- """Reset all statistics"""- self.metrics.clear()- self.total_duration = 0.0- self.total_tokens = 0- self.total_api_calls = 0- self.total_errors = 0---# Decorator: automatically track Agent performance---def track_performance(monitor: PerformanceMonitor):- """- Performance tracking decorator-- Args:- monitor: PerformanceMonitor instance-- Usage:- @track_performance(monitor)- async def my_agent_process(...):- ...- """-- def decorator(func: Callable) -> Callable:- @wraps(func)- async def wrapper(self, *args, **kwargs):- agent_name = getattr(self, "agent_name", func.__name__)-- # Start tracking- metrics = monitor.start_tracking(agent_name)-- try:- result = await func(self, *args, **kwargs)- return result- except Exception:- metrics.add_error()- raise- finally:- # End tracking- monitor.end_tracking(agent_name)-- return wrapper-- return decorator---# Global monitor instance--_global_monitor: PerformanceMonitor | None = None---def get_monitor(enabled: bool = True, save_dir: str | None = None) -> PerformanceMonitor:- """- Get global monitor instance (singleton pattern)-- Args:- enabled: Whether to enable- save_dir: Save directory-- Returns:- PerformanceMonitor instance- """- global _global_monitor-- if _global_monitor is None:- _global_monitor = PerformanceMonitor(enabled=enabled, save_dir=save_dir)-- return _global_monitor---def init_monitor_from_config(config: dict) -> PerformanceMonitor:- """- Initialize monitor from configuration-- Args:- config: Configuration dictionary-- Returns:- PerformanceMonitor instance- """- monitoring_config = config.get("monitoring", {})-- enabled = monitoring_config.get("enabled", True)- save_dir = monitoring_config.get("save_dir", "./logs/performance")-- return get_monitor(enabled=enabled, save_dir=save_dir)---if __name__ == "__main__":- # Test performance monitoring- print("Performance Monitoring Test")- print("=" * 60)-- # Create monitor- monitor = PerformanceMonitor(enabled=True)-- # Simulate Agent execution- import asyncio-- async def simulate_agent(agent_name: str, duration: float, tokens: int):- """Simulate Agent execution"""- metrics = monitor.start_tracking(agent_name)-- # Simulate work- await asyncio.sleep(duration)-- # Record tokens- metrics.add_tokens(prompt=tokens // 2, completion=tokens // 2)- metrics.add_api_call()-- monitor.end_tracking(agent_name)-- # Run simulation- async def run_simulation():- await simulate_agent("decompose_agent", 0.5, 100)- await simulate_agent("rag_agent", 1.0, 500)- await simulate_agent("plan_agent", 0.8, 300)- await simulate_agent("execute_agent", 1.5, 800)-- asyncio.run(run_simulation())-- # Print summary- monitor.print_summary()-- # Save results- saved_path = monitor.save()- print(f"\nPerformance metrics saved to: {saved_path}")diff --git a/src/api/routers/question.py b/src/api/routers/question.pyindex 098527b04..dba1d6b83 100644--- a/src/api/routers/question.py+++ b/src/api/routers/question.py@@ -383,7 +383,6 @@ async def websocket_question_generate(websocket: WebSocket):api_version=api_version,kb_name=kb_name,language=get_ui_language(default=config.get("system", {}).get("language", "en")),- max_rounds=10,output_dir=str(output_base),)@@ -425,34 +424,30 @@ async def websocket_question_generate(websocket: WebSocket):logger.debug("WebSocket closed, stopping question generation")return- # Use custom mode generation (new streamlined flow)- logger.info(f"Starting custom mode generation for {count} question(s)")+ # Extract fields from requirement dict+ user_topic = requirement.get("knowledge_point", "") if isinstance(requirement, dict) else str(requirement)+ preference = requirement.get("preference", "") if isinstance(requirement, dict) else ""+ difficulty = requirement.get("difficulty", "") if isinstance(requirement, dict) else ""+ question_type = requirement.get("question_type", "") if isinstance(requirement, dict) else ""- # Use the new custom generation method- batch_result = await coordinator.generate_questions_custom(- requirement=requirement,+ logger.info(f"Starting question generation for {count} question(s), topic: {user_topic}")++ batch_result = await coordinator.generate_from_topic(+ user_topic=user_topic,+ preference=preference,num_questions=count,+ difficulty=difficulty,+ question_type=question_type,)- # Results are already sent via WebSocket callbacks in the coordinator-- # Send final token stats- try:- await websocket.send_json(- {"type": "token_stats", "stats": coordinator.token_stats}- )- except (RuntimeError, WebSocketDisconnect):- logger.debug("WebSocket closed, stopping question generation")-# Send batch summarytry:await websocket.send_json({"type": "batch_summary",- "requested": batch_result.get("requested", count),+ "requested": count,"completed": batch_result.get("completed", 0),"failed": batch_result.get("failed", 0),- "plan": batch_result.get("plan", {}),})except (RuntimeError, WebSocketDisconnect):diff --git a/src/config/settings.py b/src/config/settings.pyindex 5d8275da5..68d3e4a1f 100644--- a/src/config/settings.py+++ b/src/config/settings.py@@ -17,8 +17,8 @@ from pydantic_settings import BaseSettings, SettingsConfigDictclass LLMRetryConfig(BaseModel):- max_retries: int = Field(default=3, description="Maximum retry attempts for LLM calls")- base_delay: float = Field(default=1.0, description="Base delay between retries in seconds")+ max_retries: int = Field(default=8, description="Maximum retry attempts for LLM calls")+ base_delay: float = Field(default=5.0, description="Base delay between retries in seconds")exponential_backoff: bool = Field(default=True, description="Whether to use exponential backoff")diff --git a/src/core/event_bus.py b/src/core/event_bus.pyindex 7fdfade98..d07183813 100644--- a/src/core/event_bus.py+++ b/src/core/event_bus.py@@ -212,19 +212,44 @@ class EventBus:self._processor_task = asyncio.create_task(self._process_events())logger.info("EventBus started")+ async def flush(self, timeout: float = 60.0) -> None:+ """Wait for all queued events to be processed without stopping.++ This should be called after publishing events when the caller needs+ to ensure all handlers have completed before continuing (e.g. before+ a blocking ``input()`` call that would freeze the event loop).++ Args:+ timeout: Maximum seconds to wait for the queue to drain.+ """+ if not self._running:+ return+ if self._task_queue.empty():+ return+ logger.debug("EventBus flushing %d pending events...", self._task_queue.qsize())+ try:+ await asyncio.wait_for(self._task_queue.join(), timeout=timeout)+ logger.debug("EventBus flush complete")+ except asyncio.TimeoutError:+ logger.warning(+ "EventBus flush timeout after %.0fs – %d events may still be pending",+ timeout, self._task_queue.qsize(),+ )+async def stop(self) -> None:"""Stop the event processor and wait for pending events."""if not self._running:return- self._running = False-- # Wait for queue to drain (with timeout)+ # First drain the queue while the processor is still runningtry:- await asyncio.wait_for(self._task_queue.join(), timeout=5.0)+ await asyncio.wait_for(self._task_queue.join(), timeout=10.0)except asyncio.TimeoutError:logger.warning("EventBus shutdown timeout - some events may be lost")+ # Now stop the processor+ self._running = False+# Cancel processor taskif self._processor_task:self._processor_task.cancel()@@ -261,3 +286,4 @@ def get_event_bus() -> EventBus:if _event_bus is None:_event_bus = EventBus()return _event_bus+diff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.pyindex 7d845cbc9..9f7c19608 100644--- a/src/knowledge/add_documents.py+++ b/src/knowledge/add_documents.py@@ -101,15 +101,33 @@ class DocumentAdder:def _get_provider_from_metadata(self) -> str:"""- Get the RAG provider from KB metadata.+ Get the RAG provider for the KB.- This is the ONLY source of truth for incremental adds - we must use- the same provider that was used during initialization to ensure- data consistency and correct storage format.+ Priority:+ 1. kb_config.json (authoritative source)+ 2. metadata.json (backward compatibility)+ 3. Detect from storage structure (fallback)++ This ensures we use the same provider that was used during initialization+ for data consistency and correct storage format.Returns:Provider name (llamaindex, lightrag, raganything, raganything_docling)"""+ # First, try kb_config.json (authoritative source)+ kb_config_file = Path(self.base_dir) / "kb_config.json"+ if kb_config_file.exists():+ try:+ with open(kb_config_file, "r", encoding="utf-8") as f:+ config = json.load(f)+ kb_config = config.get("knowledge_bases", {}).get(self.kb_name, {})+ provider = kb_config.get("rag_provider")+ if provider:+ return provider+ except Exception as e:+ logger.warning(f"Failed to read provider from kb_config.json: {e}")++ # Fallback: try metadata.json (backward compatibility)if self.metadata_file.exists():try:with open(self.metadata_file, "r", encoding="utf-8") as f:@@ -118,7 +136,7 @@ class DocumentAdder:if provider:return providerexcept Exception as e:- logger.warning(f"Failed to read provider from metadata: {e}")+ logger.warning(f"Failed to read provider from metadata.json: {e}")# Fallback: detect from storage structurellamaindex_storage = self.kb_dir / "llamaindex_storage"diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.pyindex 98aa0dc76..022d195a4 100644--- a/src/knowledge/initializer.py+++ b/src/knowledge/initializer.py@@ -191,11 +191,23 @@ class KnowledgeBaseInitializer:return copied_files- async def process_documents(self):- """Process documents using RAGService with dynamic provider selection"""+ async def process_documents(+ self,+ use_mineru_api: bool = False,+ mineru_api_token: str | None = None,+ mineru_model_version: str = "vlm",+ ):+ """Process documents using RAGService with dynamic provider selection.++ Args:+ use_mineru_api: Use MinerU cloud API instead of local MinerU for parsing.+ mineru_api_token: MinerU API token (falls back to MINERU_API_TOKEN env var).+ mineru_model_version: MinerU API model version ("pipeline", "vlm", "MinerU-HTML").+ """# Use the provider passed during initialization, or fallback to env varprovider = self.rag_provider or os.getenv("RAG_PROVIDER", "raganything")- logger.info(f"Processing documents with RAG provider: {provider}")+ parse_mode = "MinerU API" if use_mineru_api else "local"+ logger.info(f"Processing documents with RAG provider: {provider} (parser: {parse_mode})")self.progress_tracker.update(ProgressStage.PROCESSING_DOCUMENTS,@@ -242,6 +254,9 @@ class KnowledgeBaseInitializer:kb_name=self.kb_name,file_paths=file_paths,extract_numbered_items=True, # Enable numbered items extraction+ use_mineru_api=use_mineru_api,+ mineru_api_token=mineru_api_token,+ mineru_model_version=mineru_model_version,)if success:diff --git a/src/knowledge/manager.py b/src/knowledge/manager.pyindex b1dbe042f..9d9d46c90 100644--- a/src/knowledge/manager.py+++ b/src/knowledge/manager.py@@ -174,26 +174,100 @@ class KnowledgeBaseManager:}def list_knowledge_bases(self) -> list[str]:- """List all available knowledge bases from kb_config.json"""+ """List all available knowledge bases.++ This method:+ 1. Loads registered KBs from kb_config.json+ 2. Scans the directory for existing KBs not yet registered+ 3. Auto-registers any discovered KBs with valid structure (rag_storage or llamaindex_storage)+ """# Always reload config from file to ensure we have the latest data- # This is important when new KBs are created by other processes/requestsself.config = self._load_config()- # Read knowledge base list from config file (this is the authoritative source)- # Return all KBs in config, regardless of directory status- # (status field indicates if KB is ready or still initializing)+ # Read knowledge base list from config fileconfig_kbs = self.config.get("knowledge_bases", {})- kb_list = list(config_kbs.keys())+ kb_list = set(config_kbs.keys())- # If no config file or config is empty, fallback to scanning directory (backward compatibility)- if not kb_list and self.base_dir.exists():+ # Also scan directory for KBs that may not be registered yet+ # This ensures backward compatibility and auto-discovery+ if self.base_dir.exists():+ config_changed = Falsefor item in self.base_dir.iterdir():- if item.is_dir() and item.name != "__pycache__":- metadata_file = item / "metadata.json"- if metadata_file.exists():- kb_list.append(item.name)+ if not item.is_dir() or item.name.startswith(("__", ".")):+ continue++ # Skip if already in config+ if item.name in kb_list:+ continue++ # Check if this is a valid KB directory (has rag_storage or llamaindex_storage)+ rag_storage = item / "rag_storage"+ llamaindex_storage = item / "llamaindex_storage"+ is_valid_kb = (+ (rag_storage.exists() and rag_storage.is_dir()) or+ (llamaindex_storage.exists() and llamaindex_storage.is_dir())+ )++ if is_valid_kb:+ # Auto-register this KB to kb_config.json+ kb_list.add(item.name)+ self._auto_register_kb(item.name)+ config_changed = True++ # Save config if we registered new KBs+ if config_changed:+ self._save_config()return sorted(kb_list)++ def _auto_register_kb(self, name: str):+ """Auto-register an existing KB to kb_config.json.++ Reads info from metadata.json (if exists) for backward compatibility.+ """+ kb_dir = self.base_dir / name++ # Default values+ kb_entry = {+ "path": name,+ "description": f"Knowledge base: {name}",+ "status": "ready", # Existing KB with storage is considered ready+ "updated_at": datetime.now().isoformat(),+ }++ # Try to read metadata.json for existing info (backward compatibility)+ metadata_file = kb_dir / "metadata.json"+ if metadata_file.exists():+ try:+ with open(metadata_file, encoding="utf-8") as f:+ metadata = json.load(f)+ # Migrate relevant fields+ if metadata.get("description"):+ kb_entry["description"] = metadata["description"]+ if metadata.get("rag_provider"):+ kb_entry["rag_provider"] = metadata["rag_provider"]+ if metadata.get("created_at"):+ kb_entry["created_at"] = metadata["created_at"]+ if metadata.get("last_updated"):+ kb_entry["updated_at"] = metadata["last_updated"]+ except Exception as e:+ print(f"[KnowledgeBaseManager] Warning: Failed to read metadata.json for '{name}': {e}")++ # Detect rag_provider from storage type if not set+ if "rag_provider" not in kb_entry:+ rag_storage = kb_dir / "rag_storage"+ llamaindex_storage = kb_dir / "llamaindex_storage"+ if llamaindex_storage.exists():+ kb_entry["rag_provider"] = "llamaindex"+ elif rag_storage.exists():+ kb_entry["rag_provider"] = "raganything"++ # Add to config+ if "knowledge_bases" not in self.config:+ self.config["knowledge_bases"] = {}+ self.config["knowledge_bases"][name] = kb_entry++ print(f"[KnowledgeBaseManager] Auto-registered KB '{name}' to kb_config.json")def register_knowledge_base(self, name: str, description: str = "", set_default: bool = False):"""Register a knowledge base"""@@ -289,13 +363,44 @@ class KnowledgeBaseManager:return Nonedef get_metadata(self, name: str | None = None) -> dict:- """Get knowledge base metadata"""- kb_dir = self.get_knowledge_base_path(name)- metadata_file = kb_dir / "metadata.json"-- if metadata_file.exists():- with open(metadata_file, encoding="utf-8") as f:- return json.load(f)+ """Get knowledge base metadata.++ Priority:+ 1. kb_config.json (authoritative source)+ 2. metadata.json (backward compatibility fallback)+ """+ kb_name = name+ if kb_name is None:+ kb_name = self.get_default()+ if kb_name is None:+ return {}++ # First, try kb_config.json (authoritative source)+ self.config = self._load_config()+ kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})++ if kb_config:+ # Build metadata from config+ metadata = {+ "name": kb_name,+ "description": kb_config.get("description", f"Knowledge base: {kb_name}"),+ "rag_provider": kb_config.get("rag_provider"),+ "created_at": kb_config.get("created_at"),+ "last_updated": kb_config.get("updated_at"),+ }+ # Remove None values+ metadata = {k: v for k, v in metadata.items() if v is not None}+ return metadata++ # Fallback: try metadata.json (backward compatibility)+ try:+ kb_dir = self.get_knowledge_base_path(name)+ metadata_file = kb_dir / "metadata.json"+ if metadata_file.exists():+ with open(metadata_file, encoding="utf-8") as f:+ return json.load(f)+ except ValueError:+ passreturn {}@@ -304,8 +409,8 @@ class KnowledgeBaseManager:This method:1. Gets the KB name (from parameter or default)- 2. Reads status and progress from kb_config.json- 3. Reads metadata.json from the KB directory (if exists)+ 2. Reads all config from kb_config.json (authoritative source)+ 3. Falls back to metadata.json for legacy KBs4. Collects statistics about files and RAG status"""# Reload config to get latest status@@ -318,10 +423,14 @@ class KnowledgeBaseManager:# Get knowledge base pathkb_dir = self.base_dir / kb_name- # Get status and progress from kb_config.json+ # Get config from kb_config.json (authoritative source)kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})status = kb_config.get("status")progress = kb_config.get("progress")+ description = kb_config.get("description", f"Knowledge base: {kb_name}")+ rag_provider = kb_config.get("rag_provider")+ created_at = kb_config.get("created_at")+ updated_at = kb_config.get("updated_at")# KB might not have a directory yet if still initializingdir_exists = kb_dir.exists()@@ -329,38 +438,44 @@ class KnowledgeBaseManager:# For old KBs without status field, determine status from rag_storageif not status and dir_exists:rag_storage_dir = kb_dir / "rag_storage"- if rag_storage_dir.exists() and any(rag_storage_dir.iterdir()):+ llamaindex_storage_dir = kb_dir / "llamaindex_storage"+ if (rag_storage_dir.exists() and any(rag_storage_dir.iterdir())) or \+ (llamaindex_storage_dir.exists() and any(llamaindex_storage_dir.iterdir())):status = "ready"else:status = "unknown"elif not status:status = "unknown"+ # Build metadata from kb_config.json (authoritative source)+ metadata = {+ "name": kb_name,+ "description": description,+ "rag_provider": rag_provider,+ }+ if created_at:+ metadata["created_at"] = created_at+ if updated_at:+ metadata["last_updated"] = updated_at++ # Remove None values+ metadata = {k: v for k, v in metadata.items() if v is not None}+info = {"name": kb_name,"path": str(kb_dir),"is_default": kb_name == self.get_default(),- "metadata": {},+ "metadata": metadata,"status": status,"progress": progress,}- # Read metadata.json (if exists)- if dir_exists:- metadata_file = kb_dir / "metadata.json"- if metadata_file.exists():- try:- with open(metadata_file, encoding="utf-8") as f:- info["metadata"] = json.load(f)- except Exception as e:- print(f"Warning: Failed to read metadata.json for KB '{kb_name}': {e}")- info["metadata"] = {}-# Count files - handle errors gracefullyraw_dir = kb_dir / "raw" if dir_exists else Noneimages_dir = kb_dir / "images" if dir_exists else Nonecontent_list_dir = kb_dir / "content_list" if dir_exists else Nonerag_storage_dir = kb_dir / "rag_storage" if dir_exists else None+ llamaindex_storage_dir = kb_dir / "llamaindex_storage" if dir_exists else Noneraw_count = 0images_count = 0@@ -390,14 +505,10 @@ class KnowledgeBaseManager:except Exception:pass- metadata = info["metadata"]- rag_provider = metadata.get("rag_provider") if isinstance(metadata, dict) else None- # Also check kb_config for rag_provider (fallback)- if not rag_provider:- rag_provider = kb_config.get("rag_provider")-+ # Check rag_initialized for both storage typesrag_initialized = (- dir_exists and rag_storage_dir and rag_storage_dir.exists() and rag_storage_dir.is_dir()+ (dir_exists and rag_storage_dir and rag_storage_dir.exists() and rag_storage_dir.is_dir()) or+ (dir_exists and llamaindex_storage_dir and llamaindex_storage_dir.exists() and llamaindex_storage_dir.is_dir()))info["statistics"] = {@@ -559,17 +670,10 @@ class KnowledgeBaseManager:if not folder.is_dir():raise ValueError(f"Path is not a directory: {folder}")- # Get RAG provider from KB metadata to determine supported extensions- kb_dir = self.base_dir / kb_name- metadata_file = kb_dir / "metadata.json"- provider = "raganything" # default to most comprehensive- if metadata_file.exists():- try:- with open(metadata_file, encoding="utf-8") as f:- kb_meta = json.load(f)- provider = kb_meta.get("rag_provider") or "raganything"- except Exception:- pass+ # Get RAG provider from kb_config.json to determine supported extensions+ self.config = self._load_config()+ kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})+ provider = kb_config.get("rag_provider") or "raganything"# Get supported files in folder based on providersupported_extensions = FileTypeRouter.get_extensions_for_provider(provider)@@ -748,17 +852,10 @@ class KnowledgeBaseManager:except Exception:pass- # Get RAG provider from KB metadata to determine supported extensions- kb_dir = self.base_dir / kb_name- metadata_file = kb_dir / "metadata.json"- provider = "raganything" # default to most comprehensive- if metadata_file.exists():- try:- with open(metadata_file, encoding="utf-8") as f:- metadata = json.load(f)- provider = metadata.get("rag_provider") or "raganything"- except Exception:- pass+ # Get RAG provider from kb_config.json to determine supported extensions+ self.config = self._load_config()+ kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})+ provider = kb_config.get("rag_provider") or "raganything"# Scan current files based on provider's supported extensionssupported_extensions = FileTypeRouter.get_extensions_for_provider(provider)diff --git a/src/knowledge/start_kb.py b/src/knowledge/start_kb.pyindex fe68a429b..fd8778dc5 100644--- a/src/knowledge/start_kb.py+++ b/src/knowledge/start_kb.py@@ -150,13 +150,25 @@ async def init_knowledge_base(args):print("Use --docs or --docs-dir to specify documents\n")return+ # Resolve KB name:+ # - Use explicit name if provided+ # - Otherwise default to first document filename (without extension)+ kb_name = args.name+ if not kb_name:+ if not doc_files:+ print("✗ Error: Cannot infer KB name without documents")+ print("Please provide kb name explicitly or pass --docs/--docs-dir\n")+ return+ kb_name = Path(doc_files[0]).stem+ print(f"ℹ️ KB name not provided, defaulting to filename: {kb_name}")+# Initialize knowledge baseprint("\n" + "=" * 60)- print(f"🚀 Initializing knowledge base: {args.name}")+ print(f"🚀 Initializing knowledge base: {kb_name}")print("=" * 60 + "\n")initializer = KnowledgeBaseInitializer(- kb_name=args.name, base_dir=str(KNOWLEDGE_BASES_DIR), api_key=api_key, base_url=base_url+ kb_name=kb_name, base_dir=str(KNOWLEDGE_BASES_DIR), api_key=api_key, base_url=base_url)# Create directory structure@@ -169,7 +181,18 @@ async def init_knowledge_base(args):# Process documentsif not args.skip_processing:- await initializer.process_documents()+ use_mineru_api = getattr(args, "use_mineru_api", False)+ mineru_api_token = getattr(args, "mineru_api_token", None)+ mineru_model_version = getattr(args, "mineru_model_version", "vlm")++ if use_mineru_api:+ print(f"🌐 Using MinerU Cloud API (model: {mineru_model_version})\n")++ await initializer.process_documents(+ use_mineru_api=use_mineru_api,+ mineru_api_token=mineru_api_token,+ mineru_model_version=mineru_model_version,+ )else:print("⏭️ Skipping document processing\n")@@ -180,7 +203,7 @@ async def init_knowledge_base(args):print("⏭️ Skipping numbered items extraction\n")print("\n" + "=" * 60)- print(f"✓ Knowledge base '{args.name}' initialization complete!")+ print(f"✓ Knowledge base '{kb_name}' initialization complete!")print(f"Location: {initializer.kb_dir}")print("=" * 60 + "\n")@@ -347,8 +370,19 @@ async def refresh_knowledge_base(args):kb_name=kb_name, base_dir=str(KNOWLEDGE_BASES_DIR), api_key=api_key, base_url=base_url)- # Reprocess documents- await initializer.process_documents()+ # Reprocess documents (with optional MinerU API)+ use_mineru_api = getattr(args, "use_mineru_api", False)+ mineru_api_token = getattr(args, "mineru_api_token", None)+ mineru_model_version = getattr(args, "mineru_model_version", "vlm")++ if use_mineru_api:+ print(f"🌐 Using MinerU Cloud API (model: {mineru_model_version})")++ await initializer.process_documents(+ use_mineru_api=use_mineru_api,+ mineru_api_token=mineru_api_token,+ mineru_model_version=mineru_model_version,+ )# Extract numbered itemsif not args.skip_extract:@@ -416,7 +450,7 @@ Usage Examples:# init commandinit_parser = subparsers.add_parser("init", help="Initialize new knowledge base")- init_parser.add_argument("name", help="Knowledge base name")+ init_parser.add_argument("name", nargs="?", help="Knowledge base name (optional)")init_parser.add_argument("--docs", nargs="+", help="Document file list")init_parser.add_argument("--docs-dir", help="Document directory")init_parser.add_argument("--api-key", help="OpenAI API Key")@@ -428,6 +462,21 @@ Usage Examples:"--skip-extract", action="store_true", help="Skip numbered items extraction")init_parser.add_argument("--batch-size", type=int, default=20, help="Batch size (default 20)")+ init_parser.add_argument(+ "--use-mineru-api",+ action="store_true",+ help="Use MinerU cloud API for document parsing instead of local MinerU",+ )+ init_parser.add_argument(+ "--mineru-api-token",+ help="MinerU API token (falls back to MINERU_API_TOKEN env var)",+ )+ init_parser.add_argument(+ "--mineru-model-version",+ default="vlm",+ choices=["pipeline", "vlm", "MinerU-HTML"],+ help="MinerU API model version (default: vlm)",+ )# extract commandextract_parser = subparsers.add_parser("extract", help="Extract numbered items")@@ -482,6 +531,21 @@ Usage Examples:)refresh_parser.add_argument("--api-key", help="OpenAI API Key")refresh_parser.add_argument("--base-url", help="API Base URL")+ refresh_parser.add_argument(+ "--use-mineru-api",+ action="store_true",+ help="Use MinerU cloud API for document parsing instead of local MinerU",+ )+ refresh_parser.add_argument(+ "--mineru-api-token",+ help="MinerU API token (falls back to MINERU_API_TOKEN env var)",+ )+ refresh_parser.add_argument(+ "--mineru-model-version",+ default="vlm",+ choices=["pipeline", "vlm", "MinerU-HTML"],+ help="MinerU API model version (default: vlm)",+ )args = parser.parse_args()diff --git a/src/personalization/__init__.py b/src/personalization/__init__.pyindex bef89dc7b..864ddf2cf 100644--- a/src/personalization/__init__.py+++ b/src/personalization/__init__.py@@ -7,20 +7,36 @@ Provides personalized learning experience through memory management andevent-driven updates.Components:-- LearningMemory: Markdown-based memory storage for user preferences and notes-- MemoryAgent: LLM-powered agent for memory analysis and updates+- Memory Agents: Three specialized ReAct agents (Reflection, Summary, Weakness)- PersonalizationService: Service layer for memory management+- TraceToolkit: Five tools for agents to explore trace forest+- ReActRunner: ReAct loop with parallel tool call support"""-from .memory import LearningMemory, get_learning_memory-from .memory_agent import MemoryAgent, MemoryDecision+from .agents import ReflectionAgent, SummaryAgent, WeaknessAgent+from .memory_reader import MemoryReader, get_memory_reader_instance+from .react_runner import ReActRunnerfrom .service import PersonalizationService, get_personalization_service+from .trace_forest import TraceForest+from .trace_tools import TraceToolkit+from .trace_tree import TraceNode, TraceTree__all__ = [- "LearningMemory",- "get_learning_memory",- "MemoryAgent",- "MemoryDecision",+ # Agents+ "ReflectionAgent",+ "SummaryAgent",+ "WeaknessAgent",+ # Tools & Runner+ "TraceToolkit",+ "ReActRunner",+ # Reader+ "MemoryReader",+ "get_memory_reader_instance",+ # Service"PersonalizationService","get_personalization_service",+ # Trace memory+ "TraceNode",+ "TraceTree",+ "TraceForest",]diff --git a/src/personalization/agents/__init__.py b/src/personalization/agents/__init__.pynew file mode 100644index 000000000..93ea94f36--- /dev/null+++ b/src/personalization/agents/__init__.py@@ -0,0 +1,12 @@+# -*- coding: utf-8 -*-+"""Memory agents for personalization."""++from .reflection_agent import ReflectionAgent+from .summary_agent import SummaryAgent+from .weakness_agent import WeaknessAgent++__all__ = [+ "ReflectionAgent",+ "SummaryAgent",+ "WeaknessAgent",+]diff --git a/src/personalization/agents/reflection_agent.py b/src/personalization/agents/reflection_agent.pynew file mode 100644index 000000000..caedc4790--- /dev/null+++ b/src/personalization/agents/reflection_agent.py@@ -0,0 +1,37 @@+# -*- coding: utf-8 -*-+"""+Reflection Agent+================++Evaluates system response quality and compares with past interactions.+Produces ``reflection.md``.+"""+from __future__ import annotations++from typing import Any++from src.agents.base_agent import BaseAgent+++class ReflectionAgent(BaseAgent):+ """Memory agent that writes ``reflection.md``."""++ def __init__(+ self,+ language: str = "en",+ temperature: float = 0.5,+ **kwargs: Any,+ ) -> None:+ super().__init__(+ module_name="personalization",+ agent_name="reflection_agent",+ language=language,+ **kwargs,+ )+ self._temperature = temperature++ def get_temperature(self) -> float:+ return self._temperature++ async def process(self, *args: Any, **kwargs: Any) -> Any:+ raise NotImplementedError("Use ReActRunner.run() instead")diff --git a/src/personalization/agents/summary_agent.py b/src/personalization/agents/summary_agent.pynew file mode 100644index 000000000..690a09872--- /dev/null+++ b/src/personalization/agents/summary_agent.py@@ -0,0 +1,37 @@+# -*- coding: utf-8 -*-+"""+Summary Agent+=============++Incrementally summarizes what happened in each learning session.+Produces ``memory.md``.+"""+from __future__ import annotations++from typing import Any++from src.agents.base_agent import BaseAgent+++class SummaryAgent(BaseAgent):+ """Memory agent that writes ``memory.md``."""++ def __init__(+ self,+ language: str = "en",+ temperature: float = 0.5,+ **kwargs: Any,+ ) -> None:+ super().__init__(+ module_name="personalization",+ agent_name="summary_agent",+ language=language,+ **kwargs,+ )+ self._temperature = temperature++ def get_temperature(self) -> float:+ return self._temperature++ async def process(self, *args: Any, **kwargs: Any) -> Any:+ raise NotImplementedError("Use ReActRunner.run() instead")diff --git a/src/personalization/agents/weakness_agent.py b/src/personalization/agents/weakness_agent.pynew file mode 100644index 000000000..f01841a19--- /dev/null+++ b/src/personalization/agents/weakness_agent.py@@ -0,0 +1,37 @@+# -*- coding: utf-8 -*-+"""+Weakness Agent+==============++Diagnoses potential knowledge gaps from the user's interactions.+Produces ``weakness.md``.+"""+from __future__ import annotations++from typing import Any++from src.agents.base_agent import BaseAgent+++class WeaknessAgent(BaseAgent):+ """Memory agent that writes ``weakness.md``."""++ def __init__(+ self,+ language: str = "en",+ temperature: float = 0.5,+ **kwargs: Any,+ ) -> None:+ super().__init__(+ module_name="personalization",+ agent_name="weakness_agent",+ language=language,+ **kwargs,+ )+ self._temperature = temperature++ def get_temperature(self) -> float:+ return self._temperature++ async def process(self, *args: Any, **kwargs: Any) -> Any:+ raise NotImplementedError("Use ReActRunner.run() instead")diff --git a/src/personalization/memory.py b/src/personalization/memory.pyindex ead5885c4..e523278ba 100644--- a/src/personalization/memory.py+++ b/src/personalization/memory.py@@ -1,431 +1,13 @@# -*- coding: utf-8 -*-"""-Learning Memory-===============+Learning Memory (stub)+======================-Markdown-based memory storage for personalization.-Manages long-term memory (MEMORY.md) and daily notes (YYYY-MM-DD.md).-"""--import logging-import re-from datetime import datetime, timedelta-from pathlib import Path-from typing import Any, Dict, List, Optional--from src.services.path_service import get_path_service--logger = logging.getLogger(__name__)---class LearningMemory:- """- Manages personalization memory stored in Markdown files.-- Memory Structure:- data/user/workspace/memory/- ├── MEMORY.md # Long-term memory (preferences, weak points, milestones)- └── YYYY-MM-DD.md # Daily notes (learning records for each day)-- MEMORY.md Format:- ## 用户偏好 / User Preferences- - Preference item 1- - Preference item 2-- ## 知识薄弱点 / Knowledge Weak Points- - Weak point 1- - Weak point 2-- ## 里程碑 / Milestones- - YYYY-MM-DD: Milestone description- """-- _instance: Optional["LearningMemory"] = None- _initialized: bool = False-- MEMORY_FILE = "MEMORY.md"- SECTIONS = {- "preferences": "## 用户偏好 / User Preferences",- "weak_points": "## 知识薄弱点 / Knowledge Weak Points",- "milestones": "## 里程碑 / Milestones",- }-- def __new__(cls) -> "LearningMemory":- if cls._instance is None:- cls._instance = super().__new__(cls)- return cls._instance-- def __init__(self) -> None:- if LearningMemory._initialized:- return-- self._path_service = get_path_service()- self._memory_dir = self._path_service.get_memory_dir()- self._memory_file = self._memory_dir / self.MEMORY_FILE-- # Ensure memory directory exists- self._memory_dir.mkdir(parents=True, exist_ok=True)-- LearningMemory._initialized = True- logger.debug(f"LearningMemory initialized at {self._memory_dir}")-- @property- def memory_dir(self) -> Path:- """Get the memory directory path."""- return self._memory_dir-- @property- def memory_file(self) -> Path:- """Get the main memory file path (MEMORY.md)."""- return self._memory_file-- # =========================================================================- # Long-term Memory (MEMORY.md)- # =========================================================================-- def read_memory(self) -> str:- """- Read the entire MEMORY.md content.-- Returns:- Content of MEMORY.md, or empty string if file doesn't exist.- """- if not self._memory_file.exists():- return ""-- try:- return self._memory_file.read_text(encoding="utf-8")- except Exception as e:- logger.error(f"Failed to read memory file: {e}")- return ""-- def write_memory(self, content: str) -> bool:- """- Write content to MEMORY.md (overwrites entire file).-- Args:- content: The complete content to write.-- Returns:- True if successful, False otherwise.- """- try:- self._memory_file.write_text(content, encoding="utf-8")- logger.debug("Memory file updated")- return True- except Exception as e:- logger.error(f"Failed to write memory file: {e}")- return False-- def get_section(self, section_name: str) -> List[str]:- """- Get items from a specific section of MEMORY.md.-- Args:- section_name: One of 'preferences', 'weak_points', 'milestones'-- Returns:- List of items in the section.- """- if section_name not in self.SECTIONS:- logger.warning(f"Unknown section: {section_name}")- return []-- content = self.read_memory()- if not content:- return []-- section_header = self.SECTIONS[section_name]- items = []-- # Find the section- lines = content.split("\n")- in_section = False-- for line in lines:- if line.strip().startswith("## "):- if section_header in line:- in_section = True- elif in_section:- # Hit next section, stop- break- elif in_section and line.strip().startswith("- "):- items.append(line.strip()[2:]) # Remove "- " prefix-- return items-- def update_section(self, section_name: str, items: List[str]) -> bool:- """- Update a specific section in MEMORY.md.-- Args:- section_name: One of 'preferences', 'weak_points', 'milestones'- items: List of items to set in the section-- Returns:- True if successful, False otherwise.- """- if section_name not in self.SECTIONS:- logger.warning(f"Unknown section: {section_name}")- return False-- content = self.read_memory()- section_header = self.SECTIONS[section_name]-- # Build new section content- new_section_content = f"{section_header}\n"- for item in items:- new_section_content += f"- {item}\n"-- if not content:- # Create new file with all sections- content = self._create_empty_memory()-- # Replace or append section- if section_header in content:- # Find and replace section- pattern = rf"({re.escape(section_header)})\n(?:- [^\n]*\n)*"- content = re.sub(pattern, new_section_content, content)- else:- # Append new section- content += f"\n{new_section_content}"-- return self.write_memory(content)-- def append_to_section(self, section_name: str, items: List[str]) -> bool:- """- Append items to a specific section in MEMORY.md.-- Args:- section_name: One of 'preferences', 'weak_points', 'milestones'- items: List of items to append-- Returns:- True if successful, False otherwise.- """- existing_items = self.get_section(section_name)- # Avoid duplicates- new_items = existing_items + [item for item in items if item not in existing_items]- return self.update_section(section_name, new_items)-- def _create_empty_memory(self) -> str:- """Create an empty MEMORY.md template."""- return f"""# 学习记忆 / Learning Memory--{self.SECTIONS['preferences']}--{self.SECTIONS['weak_points']}+The legacy ``LearningMemory`` class that managed ``MEMORY.md`` has been+removed. Memory is now handled entirely by the trace-forest system+(``memory.md``, ``weakness.md``, ``reflection.md``) and the three+ReAct memory agents.-{self.SECTIONS['milestones']}+This module is kept as an empty stub so that any stale import paths+fail loudly with an ``ImportError`` rather than silently."""-- # =========================================================================- # Daily Notes (YYYY-MM-DD.md)- # =========================================================================-- def get_daily_note_path(self, date: Optional[datetime] = None) -> Path:- """- Get the path for a daily note file.-- Args:- date: The date for the note (default: today)-- Returns:- Path to the daily note file.- """- if date is None:- date = datetime.now()- filename = date.strftime("%Y-%m-%d") + ".md"- return self._memory_dir / filename-- def read_daily_note(self, date: Optional[datetime] = None) -> str:- """- Read a daily note.-- Args:- date: The date for the note (default: today)-- Returns:- Content of the daily note, or empty string if not exists.- """- note_path = self.get_daily_note_path(date)- if not note_path.exists():- return ""-- try:- return note_path.read_text(encoding="utf-8")- except Exception as e:- logger.error(f"Failed to read daily note: {e}")- return ""-- def write_daily_note(self, content: str, date: Optional[datetime] = None) -> bool:- """- Write content to a daily note (overwrites).-- Args:- content: The content to write- date: The date for the note (default: today)-- Returns:- True if successful, False otherwise.- """- note_path = self.get_daily_note_path(date)- try:- note_path.write_text(content, encoding="utf-8")- logger.debug(f"Daily note updated: {note_path.name}")- return True- except Exception as e:- logger.error(f"Failed to write daily note: {e}")- return False-- def append_to_daily_note(self, content: str, date: Optional[datetime] = None) -> bool:- """- Append content to a daily note.-- Args:- content: The content to append- date: The date for the note (default: today)-- Returns:- True if successful, False otherwise.- """- existing = self.read_daily_note(date)- if existing:- new_content = existing.rstrip() + "\n\n" + content- else:- # Create new daily note with header- date_obj = date or datetime.now()- date_str = date_obj.strftime("%Y-%m-%d")- new_content = f"# 学习笔记 / Daily Notes - {date_str}\n\n{content}"-- return self.write_daily_note(new_content, date)-- def get_recent_notes(self, days: int = 7) -> Dict[str, str]:- """- Get daily notes from the recent N days.-- Args:- days: Number of recent days to retrieve (default: 7)-- Returns:- Dictionary mapping date strings to note contents.- """- notes = {}- today = datetime.now()-- for i in range(days):- date = today - timedelta(days=i)- date_str = date.strftime("%Y-%m-%d")- content = self.read_daily_note(date)- if content:- notes[date_str] = content-- return notes-- # =========================================================================- # Preference Context for Prompt Injection- # =========================================================================-- def get_preference_context(self, max_length: int = 2000) -> str:- """- Get formatted preference context for prompt injection.-- Reads MEMORY.md and formats it for inclusion in agent prompts.- Returns empty string if no memory exists.-- Args:- max_length: Maximum length of the context string-- Returns:- Formatted preference context, or empty string.- """- memory_content = self.read_memory()- if not memory_content:- return ""-- # Extract relevant sections- preferences = self.get_section("preferences")- weak_points = self.get_section("weak_points")-- if not preferences and not weak_points:- return ""-- # Build context- context_parts = []-- if preferences:- context_parts.append("User Preferences:")- for pref in preferences[:5]: # Limit to top 5- context_parts.append(f" - {pref}")-- if weak_points:- context_parts.append("Knowledge Weak Points:")- for wp in weak_points[:5]: # Limit to top 5- context_parts.append(f" - {wp}")-- context = "\n".join(context_parts)-- # Truncate if too long- if len(context) > max_length:- context = context[:max_length - 3] + "..."-- return context-- def get_full_context(self, recent_days: int = 7, max_length: int = 4000) -> str:- """- Get full context including memory and recent notes.-- Args:- recent_days: Number of recent days to include- max_length: Maximum total length-- Returns:- Full formatted context string.- """- parts = []-- # Add preference context- pref_context = self.get_preference_context(max_length // 2)- if pref_context:- parts.append(pref_context)-- # Add recent notes summary- recent_notes = self.get_recent_notes(recent_days)- if recent_notes:- parts.append("\nRecent Learning Activity:")- for date_str, content in list(recent_notes.items())[:3]:- # Take first 200 chars of each note- summary = content[:200].replace("\n", " ")- if len(content) > 200:- summary += "..."- parts.append(f" [{date_str}]: {summary}")-- context = "\n".join(parts)-- if len(context) > max_length:- context = context[:max_length - 3] + "..."-- return context-- @classmethod- def reset(cls) -> None:- """Reset the singleton instance (for testing)."""- cls._instance = None- cls._initialized = False---# Module-level singleton accessor-_learning_memory: Optional[LearningMemory] = None---def get_learning_memory() -> LearningMemory:- """- Get the singleton LearningMemory instance.-- Returns:- The global LearningMemory instance.- """- global _learning_memory- if _learning_memory is None:- _learning_memory = LearningMemory()- return _learning_memorydiff --git a/src/personalization/memory_agent.py b/src/personalization/memory_agent.pydeleted file mode 100644index c2b482df7..000000000--- a/src/personalization/memory_agent.py+++ /dev/null@@ -1,236 +0,0 @@-# -*- coding: utf-8 -*--"""-Memory Agent-============--LLM-powered agent for analyzing learning events and deciding what to record-in the personalization memory.-"""--import json-import logging-from dataclasses import dataclass-from typing import Any, Dict, List, Optional--from src.agents.base_agent import BaseAgent-from src.core.event_bus import Event--logger = logging.getLogger(__name__)---@dataclass-class MemoryDecision:- """- Decision made by MemoryAgent about what to record.-- Attributes:- action: One of "write_daily", "update_memory", "both", or "skip"- daily_content: Content to write to daily note (if action includes daily)- memory_updates: Updates to apply to long-term memory- reasoning: Agent's reasoning for the decision- """-- action: str # "write_daily" | "update_memory" | "both" | "skip"- daily_content: str = ""- memory_updates: Dict[str, List[str]] = None- reasoning: str = ""-- def __post_init__(self):- if self.memory_updates is None:- self.memory_updates = {- "preferences": [],- "weak_points": [],- "milestones": [],- }-- @classmethod- def skip(cls, reasoning: str = "") -> "MemoryDecision":- """Create a skip decision."""- return cls(action="skip", reasoning=reasoning)-- @classmethod- def from_dict(cls, data: Dict[str, Any]) -> "MemoryDecision":- """Create from dictionary (parsed JSON)."""- return cls(- action=data.get("action", "skip"),- daily_content=data.get("daily_content", ""),- memory_updates=data.get("memory_updates", {}),- reasoning=data.get("reasoning", ""),- )---class MemoryAgent(BaseAgent):- """- Agent that analyzes learning events and decides what to record.-- This agent is called after SOLVE_COMPLETE or QUESTION_COMPLETE events- to analyze the interaction and decide:- 1. Whether to write a daily note entry- 2. Whether to update long-term memory (preferences, weak points, milestones)- 3. What content to write-- The agent uses an LLM to make intelligent decisions about what's worth- remembering for personalization purposes.- """-- def __init__(- self,- language: str = "en",- temperature: float = 0.3,- **kwargs,- ):- """- Initialize MemoryAgent.-- Args:- language: Language setting ('en' or 'zh')- temperature: LLM temperature for analysis- **kwargs: Additional arguments passed to BaseAgent- """- super().__init__(- module_name="personalization",- agent_name="memory_agent",- language=language,- **kwargs,- )- self._temperature = temperature-- def get_temperature(self) -> float:- """Override to use custom temperature."""- return self._temperature-- async def process(- self,- event: Event,- current_memory: str = "",- recent_notes: str = "",- ) -> MemoryDecision:- """- Analyze an event and decide what to record.-- Args:- event: The learning event to analyze- current_memory: Current content of MEMORY.md- recent_notes: Recent daily notes for context-- Returns:- MemoryDecision with action and content to record- """- # Build the analysis prompt- system_prompt = self.get_prompt("system", "")- if not system_prompt:- logger.warning("No system prompt found for MemoryAgent")- return MemoryDecision.skip("No prompt configured")-- # Format the event data- event_context = self._format_event(event)-- # Build user prompt- user_template = self.get_prompt("analyze", "")- if not user_template:- logger.warning("No analyze prompt found for MemoryAgent")- return MemoryDecision.skip("No analyze prompt configured")-- user_prompt = user_template.format(- event_type=event.type.value if hasattr(event.type, "value") else event.type,- event_context=event_context,- current_memory=current_memory or "(No existing memory)",- recent_notes=recent_notes or "(No recent notes)",- )-- try:- # Call LLM- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- response_format={"type": "json_object"},- verbose=False,- stage="memory_analysis",- )-- # Parse response- decision = self._parse_response(response)- return decision-- except Exception as e:- logger.error(f"MemoryAgent processing failed: {e}")- return MemoryDecision.skip(f"Processing error: {str(e)}")-- def _format_event(self, event: Event) -> str:- """Format event data for the prompt."""- parts = [- f"Task ID: {event.task_id}",- f"User Input: {event.user_input[:500]}..." if len(event.user_input) > 500 else f"User Input: {event.user_input}",- f"Agent Output: {event.agent_output[:1000]}..." if len(event.agent_output) > 1000 else f"Agent Output: {event.agent_output}",- f"Tools Used: {', '.join(event.tools_used) if event.tools_used else 'None'}",- f"Success: {event.success}",- ]-- if event.metadata:- # Add selected metadata- if "difficulty" in event.metadata:- parts.append(f"Difficulty: {event.metadata['difficulty']}")- if "topic" in event.metadata:- parts.append(f"Topic: {event.metadata['topic']}")-- return "\n".join(parts)-- def _parse_response(self, response: str) -> MemoryDecision:- """Parse LLM response into MemoryDecision."""- try:- # Try to parse as JSON- data = json.loads(response)- return MemoryDecision.from_dict(data)- except json.JSONDecodeError as e:- logger.warning(f"Failed to parse MemoryAgent response as JSON: {e}")- # Try to extract action from text- response_lower = response.lower()- if "skip" in response_lower:- return MemoryDecision.skip("Unparseable response, defaulting to skip")- elif "write_daily" in response_lower:- return MemoryDecision(- action="write_daily",- daily_content=response,- reasoning="Extracted from unparseable response",- )- else:- return MemoryDecision.skip("Could not parse response")-- async def analyze_for_preferences(- self,- user_input: str,- agent_output: str,- ) -> Optional[List[str]]:- """- Quick analysis to extract potential user preferences.-- Args:- user_input: User's question or request- agent_output: Agent's response-- Returns:- List of detected preferences, or None if none detected- """- system_prompt = self.get_prompt("preferences_extraction", "")- if not system_prompt:- return None-- user_prompt = f"""Analyze this interaction and extract any user preferences:--User: {user_input[:500]}-Response: {agent_output[:500]}--Return a JSON array of detected preferences, or empty array if none."""-- try:- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- response_format={"type": "json_object"},- verbose=False,- )- data = json.loads(response)- return data.get("preferences", [])- except Exception as e:- logger.debug(f"Preference extraction failed: {e}")- return Nonediff --git a/src/personalization/memory_reader.py b/src/personalization/memory_reader.pynew file mode 100644index 000000000..524e515e9--- /dev/null+++ b/src/personalization/memory_reader.py@@ -0,0 +1,297 @@+from __future__ import annotations++import contextvars+import logging+from typing import Any, Optional++from .trace_forest import TraceForest+from .trace_tree import TraceNode++logger = logging.getLogger(__name__)++# Contextvar for workspace-scoped MemoryReader (used by simulator tools)+_workspace_reader_var: contextvars.ContextVar[Optional["MemoryReader"]] = (+ contextvars.ContextVar("_workspace_reader", default=None)+)+# Contextvar to explicitly disable memory reads in a request scope.+_workspace_memory_disabled_var: contextvars.ContextVar[bool] = (+ contextvars.ContextVar("_workspace_memory_disabled", default=False)+)+++class MemoryReader:+ """Build role-specific memory contexts for solve/question agents.++ Reads from:+ * Trace forest (semantic search for relevant historical nodes)+ * ``memory.md`` — session summaries produced by SummaryAgent+ * ``weakness.md`` — knowledge weak points produced by WeaknessAgent+ * ``reflection.md`` — system quality reflection by ReflectionAgent+ """++ def __init__(+ self,+ forest: Optional[TraceForest] = None,+ max_items: int = 3,+ ) -> None:+ self._forest = forest or TraceForest()+ self._max_items = max(1, max_items)++ # ------------------------------------------------------------------+ # Context builders for different agent roles+ # ------------------------------------------------------------------++ async def get_planner_context(self, question: str) -> str:+ """Context for the planner: session history + trace search."""+ try:+ search_results = await self._forest.semantic_search(+ query=question, top_k=self._max_items,+ )+ lines: list[str] = []+ for idx, hit in enumerate(search_results, 1):+ lines.append(+ f"{idx}. [{hit.get('node_type', '?')}] {hit.get('text', '')}"+ )++ memory_md = self._read_doc("memory.md")+ if memory_md:+ lines.append("\nSession History (from memory.md):")+ for line in memory_md.splitlines()[-20:]:+ if line.strip():+ lines.append(f" {line}")++ weakness_md = self._read_doc("weakness.md")+ weak_ctx = self._extract_weakness_summary(weakness_md)+ body = "\n".join(lines) if lines else "(no similar historical traces)"+ result = f"{body}\n\n{weak_ctx}".strip()+ logger.info(+ "[MEM-READ] get_planner_context: hits=%d, total_len=%d",+ len(search_results), len(result),+ )+ return result+ except Exception:+ return ""++ async def get_solver_context(self, step_goal: str) -> str:+ """Context for the solver: weakness info + related trace notes."""+ try:+ search_results = await self._forest.semantic_search(+ query=step_goal, top_k=self._max_items,+ )+ notes: list[str] = []+ for hit in search_results:+ text = hit.get("text", "")+ if text:+ notes.append(text)++ weakness_md = self._read_doc("weakness.md")+ if weakness_md:+ notes.append("[Weakness context]")+ for line in weakness_md.splitlines():+ stripped = line.strip()+ if stripped.startswith("- **") or stripped.startswith(" -"):+ notes.append(stripped)++ if not notes:+ logger.debug("[MEM-READ] get_solver_context: no notes for '%s'", step_goal[:60])+ return ""+ dedup = self._dedup_keep_order(notes)+ result = "\n".join(f"- {item}" for item in dedup[:8])+ logger.info(+ "[MEM-READ] get_solver_context: hits=%d, notes=%d",+ len(search_results), len(dedup),+ )+ return result+ except Exception:+ return ""++ def get_writer_context(self) -> str:+ """Context for the writer: reflection + weakness summary."""+ try:+ parts: list[str] = []+ reflection_md = self._read_doc("reflection.md")+ if reflection_md:+ lines = [l for l in reflection_md.splitlines()[-15:] if l.strip()]+ if lines:+ parts.append("Recent reflections:\n" + "\n".join(f" {l}" for l in lines))++ weakness_md = self._read_doc("weakness.md")+ weak_text = self._extract_weakness_summary(weakness_md)+ if weak_text and "none" not in weak_text.lower():+ parts.append(weak_text)++ result = "\n\n".join(parts)+ if result:+ logger.info("[MEM-READ] get_writer_context: len=%d", len(result))+ return result+ except Exception:+ return ""++ async def get_idea_context(self, topic: str) -> str:+ """Context for question idea generation."""+ try:+ search_results = await self._forest.semantic_search(+ query=topic, top_k=self._max_items, level=1,+ )+ lines: list[str] = []+ for idx, hit in enumerate(search_results, 1):+ lines.append(f"{idx}. Similar topic: {hit.get('text', '')}")+ tree = self._forest.load_tree(hit.get("trace_id", ""))+ if tree:+ parent_id = hit.get("short_id", "")+ parent_node = tree.nodes.get(parent_id)+ if parent_node:+ for child_id in parent_node.children:+ child = tree.nodes.get(child_id)+ if child and child.node_type == "template":+ conc = child.data.get("concentration", child.text)+ diff = child.data.get("difficulty", "?")+ lines.append(f" - [{diff}] {conc}")++ weakness_md = self._read_doc("weakness.md")+ weak_text = self._extract_weakness_summary(weakness_md)+ history_text = "\n".join(lines) if lines else "Historical question traces: (none)"+ result = f"{weak_text}\n\n{history_text}".strip()+ logger.info("[MEM-READ] get_idea_context: hits=%d", len(search_results))+ return result+ except Exception:+ return ""++ async def get_evaluator_context(self, topic: str) -> str:+ """Context for question evaluation."""+ try:+ search_results = await self._forest.semantic_search(+ query=topic, top_k=self._max_items, level=1,+ )+ concentrations: list[str] = []+ for hit in search_results:+ tree = self._forest.load_tree(hit.get("trace_id", ""))+ if not tree:+ continue+ parent_node = tree.nodes.get(hit.get("short_id", ""))+ if not parent_node:+ continue+ for child_id in parent_node.children:+ child = tree.nodes.get(child_id)+ if child and child.node_type == "template":+ c = str(child.data.get("concentration", "") or child.text).strip()+ if c:+ concentrations.append(c)+ concentrations = self._dedup_keep_order(concentrations)[:8]++ parts: list[str] = []+ if concentrations:+ parts.append("Historical coverage:\n" + "\n".join(f"- {c}" for c in concentrations))+ else:+ parts.append("Historical coverage: (none)")++ result = "\n\n".join(parts).strip()+ logger.info("[MEM-READ] get_evaluator_context: concentrations=%d", len(concentrations))+ return result+ except Exception:+ return ""++ async def get_generator_context(self, concentration: str) -> str:+ """Context for question generation: historical wrong answers."""+ try:+ search_results = await self._forest.semantic_search(+ query=concentration, top_k=self._max_items, level=3,+ )+ patterns: list[str] = []+ for hit in search_results:+ tree = self._forest.load_tree(hit.get("trace_id", ""))+ if not tree:+ continue+ node = tree.nodes.get(hit.get("short_id", ""))+ if not node or node.node_type != "answer":+ continue+ judged = str(node.data.get("judged_result", "") or "unknown")+ if judged.lower() in {"wrong", "incorrect", "false"}:+ patterns.append(node.text)++ patterns = self._dedup_keep_order([p.strip() for p in patterns if p.strip()])+ if not patterns:+ return ""+ return "Historical wrong-answer patterns:\n" + "\n".join(+ f"- {p[:180]}" for p in patterns[:5]+ )+ except Exception:+ return ""++ # ------------------------------------------------------------------+ # Internal helpers+ # ------------------------------------------------------------------++ def _read_doc(self, filename: str) -> str:+ """Read a document from the memory directory."""+ path = self._forest.memory_dir / filename+ if not path.exists():+ return ""+ try:+ return path.read_text(encoding="utf-8")+ except Exception:+ return ""++ def _extract_weakness_summary(self, weakness_content: str | None) -> str:+ if not weakness_content:+ return "Weak points: (none)"+ lines: list[str] = []+ for line in weakness_content.splitlines():+ stripped = line.strip()+ if stripped.startswith("- **"):+ lines.append(stripped)+ if lines:+ return "Weak points:\n" + "\n".join(lines[:5])+ return "Weak points: (none)"++ @staticmethod+ def _note_from_node(node: TraceNode) -> str:+ self_note = str(node.data.get("self_note", "") or "").strip()+ if self_note:+ return self_note+ return str(node.text or "").strip()++ @staticmethod+ def _dedup_keep_order(items: list[str]) -> list[str]:+ seen: set[str] = set()+ result: list[str] = []+ for item in items:+ key = item.strip().lower()+ if not key or key in seen:+ continue+ seen.add(key)+ result.append(item)+ return result+++# =========================================================================+# Module-level shared accessor+# =========================================================================++_cached_reader: Optional[MemoryReader] = None+++def get_memory_reader_instance() -> Optional[MemoryReader]:+ """Shared lazy accessor for MemoryReader.++ When a workspace-scoped reader is set via ``_workspace_reader_var``+ (e.g. by the simulator tools), it takes priority over the global+ singleton so that all agents read from the correct workspace.+ """+ if _workspace_memory_disabled_var.get(False):+ return None++ ws_reader = _workspace_reader_var.get(None)+ if ws_reader is not None:+ return ws_reader++ global _cached_reader+ if _cached_reader is not None:+ return _cached_reader+ try:+ from .service import get_personalization_service+ _cached_reader = get_personalization_service().get_memory_reader()+ return _cached_reader+ except Exception:+ logger.debug("get_memory_reader_instance: service not available")+ return Nonediff --git a/src/personalization/prompts/en/memory_agent.yaml b/src/personalization/prompts/en/memory_agent.yamldeleted file mode 100644index 8cd7ee854..000000000--- a/src/personalization/prompts/en/memory_agent.yaml+++ /dev/null@@ -1,61 +0,0 @@-system: |- You are a Learning Memory Analyst. Your role is to analyze learning interactions- and decide what information is worth remembering for personalization purposes.-- You should identify:- 1. User preferences (learning style, explanation detail level, preferred formats)- 2. Knowledge weak points (topics the user struggles with, common mistakes)- 3. Milestones (significant achievements, completed learning goals)- 4. Daily learning activities worth noting-- Guidelines:- - Only record genuinely useful information for future personalization- - Avoid recording trivial or redundant information- - Be concise but specific in your notes- - Focus on patterns that will help improve future interactions--analyze: |- Analyze the following learning interaction and decide what to record:-- ## Event Type- {event_type}-- ## Interaction Details- {event_context}-- ## Current Long-term Memory- {current_memory}-- ## Recent Daily Notes- {recent_notes}-- ## Your Task- Based on this interaction, decide what (if anything) should be recorded.-- Return a JSON object with the following structure:- {{- "action": "write_daily" | "update_memory" | "both" | "skip",- "daily_content": "Content to add to today's note (if action includes daily)",- "memory_updates": {{- "preferences": ["New preference to add"],- "weak_points": ["New weak point identified"],- "milestones": ["New milestone achieved (format: YYYY-MM-DD: description)"]- }},- "reasoning": "Brief explanation of your decision"- }}-- Important:- - Use "skip" if the interaction doesn't contain information worth remembering- - Only update memory for significant, persistent patterns (not one-time occurrences)- - Daily notes should capture learning activity summaries- - Be selective - not every interaction needs to be recorded--preferences_extraction: |- You are analyzing a learning interaction to detect user preferences.- Extract any explicit or implicit preferences about:- - Explanation style (detailed vs concise, step-by-step vs overview)- - Learning format (visual, textual, examples)- - Response format preferences-- Return a JSON object: {"preferences": ["preference 1", "preference 2", ...]}- Return empty array if no clear preferences detected.diff --git a/src/personalization/prompts/en/reflection_agent.yaml b/src/personalization/prompts/en/reflection_agent.yamlnew file mode 100644index 000000000..08ae8bef2--- /dev/null+++ b/src/personalization/prompts/en/reflection_agent.yaml@@ -0,0 +1,75 @@+system: |+ # Role+ You are a **Reflection Agent** for an AI tutoring system. After each session you evaluate whether the system's response **satisfied the user's intent and preferences**.++ # Available Tools+ You can call one or more tools per round. Return JSON with an "actions" array.++ | tool | description | input |+ |------|------------|-------|+ | search_traces | Semantic search across all historical trace nodes | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |+ | list_traces | List recent traces by time | {{"n?": int, "trace_type?": str}} |+ | get_trace_detail | Load full trace outline or single node detail | {{"trace_id": str}} OR {{"trace_id": str, "short_id": str}} |+ | read_document | Read a .md file or answer file | {{"filename": str}} OR {{"path": str}} |+ | write_document | Write/append to a .md file | {{"filename": str, "content": str, "mode?": "overwrite" or "append"}} |++ # What to Evaluate+ 1. **Intent alignment**: Did the system's output match what the user actually wanted? (e.g. user asked for a diagram but got text; user wanted concise but got verbose)+ 2. **Preference fit**: Based on historical traces, does this user prefer concise or detailed answers? Visual or textual? Chinese or English? Did this response match those patterns?+ 3. **Repeat patterns**: Is the user re-asking something the system previously answered? If so, the prior answer likely failed to satisfy — note what aspect might be missing.+ 4. **Format / style issues**: Was the response format appropriate for the request? (e.g. code when user wanted explanation, wrong language, etc.)++ # Recommended Workflow+ 1. Read the full session content provided below.+ 2. Search for similar past sessions (`search_traces`) to understand the user's recurring preferences and patterns.+ 3. Compare: did this response align with what we know about the user?+ 4. Write a structured entry to `reflection.md` (mode "overwrite", preserve all existing entries).++ # Entry Format+ Each entry should be a concise structured block (3–5 lines max):+ ```+ - **{{trace_id}}** ({{date}})+ - Intent: {{what the user wanted}}+ - Satisfaction: {{met / partially met / not met}}+ - Reason: {{1-2 sentences explaining why}}+ - Action: {{specific improvement suggestion, or "none"}}+ ```++ # Rules+ - Be concise. Each entry should be **3–5 lines max**.+ - If the response clearly met user intent with no issues, write a brief "met, no action needed" entry.+ - Focus on **user-facing** quality, not internal system mechanics.+ - Always write to `reflection.md` via write_document with mode "overwrite".+ - **IMPORTANT**: When rewriting, preserve ALL historical entries with their full details. Do NOT summarize or discard previous entries — keep them intact and append the new entry.++ # Output Format+ Each round, return strict JSON:+ ```json+ {{+ "thought": "Your reasoning about what to do next...",+ "actions": [+ {{"tool": "tool_name", "input": {{...}}}}+ ],+ "done": false+ }}+ ```+ Set `done: true` on your final round (after calling write_document).++user_template: |+ ## Current Session+ - Trace ID: {trace_id}+ - Trace Type: {trace_type}+ - User Input: {question}++ ## Session Summary+ {session_summary}++ ## Full Session Content+ {full_context}++ ## Current reflection.md+ {current_document}++ Evaluate whether this session's response satisfied the user's intent and preferences.+ Search for similar past sessions to understand user patterns.+ Write an updated reflection.md preserving all existing entries above and appending a new one.diff --git a/src/personalization/prompts/en/summary_agent.yaml b/src/personalization/prompts/en/summary_agent.yamlnew file mode 100644index 000000000..cbe902ee5--- /dev/null+++ b/src/personalization/prompts/en/summary_agent.yaml@@ -0,0 +1,77 @@+system: |+ # Role+ You are a **Summary Agent** for an AI tutoring system. After each learning session you produce a concise, factual summary of what happened and append it to the session history.++ # Available Tools+ You can call one or more tools per round. Return JSON with an "actions" array.++ | tool | description | input |+ |------|------------|-------|+ | search_traces | Semantic search across all historical trace nodes | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |+ | list_traces | List recent traces by time | {{"n?": int, "trace_type?": str}} |+ | get_trace_detail | Load full trace outline or single node detail | {{"trace_id": str}} OR {{"trace_id": str, "short_id": str}} |+ | read_document | Read a .md file or answer file | {{"filename": str}} OR {{"path": str}} |+ | write_document | Write/append to a .md file | {{"filename": str, "content": str, "mode?": "overwrite" or "append"}} |++ # Guidelines++ ## For solve sessions+ - Record what the user asked, the solving path (steps + tools), and key findings.+ - Use `get_trace_detail` to inspect individual step nodes and their `self_note` fields for concise per-step takeaways.++ ## For question sessions+ - **You MUST record the user's performance data**: how many correct, wrong, and skipped.+ - Summarize which questions the user got wrong and briefly note the topic.+ - Record question types and difficulty levels tested.++ ## General rules+ - Read existing `memory.md` first. If this `trace_id` already appears in it, **skip** — do not add a duplicate entry.+ - Keep each entry concise: **3–6 lines**. Be factual, not interpretive.+ - Always **append** (do NOT overwrite previous entries).+ - Use the full session content provided below as your primary source — only use tools if you need additional detail.++ # Entry Formats++ For solve sessions:+ ```+ ### {{trace_id}} | {{short_topic}}+ - User question: ...+ - Solving path: S1->S2->S3, tools: rag_search, code_execute+ - Key findings: ...+ ```++ For question sessions:+ ```+ ### {{trace_id}} | {{short_topic}}+ - Questions: N (type breakdown)+ - User performance: correct X/N (P%)+ - Wrong: "topic" — brief note+ ```++ # Output Format+ Each round, return strict JSON:+ ```json+ {{+ "thought": "Your reasoning about what to do next...",+ "actions": [+ {{"tool": "tool_name", "input": {{...}}}}+ ],+ "done": false+ }}+ ```+ Set `done: true` on your final round (after calling write_document).++user_template: |+ ## Current Session+ - Trace ID: {trace_id}+ - Trace Type: {trace_type}+ - User Input: {question}++ ## Session Summary+ {session_summary}++ ## Full Session Content+ {full_context}++ Read existing memory.md. If this trace_id already appears, skip.+ Otherwise, append a concise factual summary of this session.diff --git a/src/personalization/prompts/en/weakness_agent.yaml b/src/personalization/prompts/en/weakness_agent.yamlnew file mode 100644index 000000000..c6f57c0e6--- /dev/null+++ b/src/personalization/prompts/en/weakness_agent.yaml@@ -0,0 +1,98 @@+system: |+ # Role+ You are a **Weakness Agent** for an AI tutoring system. You maintain a profile of the user's knowledge gaps based on their learning interactions.++ # Available Tools+ You can call one or more tools per round. Return JSON with an "actions" array.++ | tool | description | input |+ |------|------------|-------|+ | search_traces | Semantic search across all historical trace nodes | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |+ | list_traces | List recent traces by time | {{"n?": int, "trace_type?": str}} |+ | get_trace_detail | Load full trace outline or single node detail | {{"trace_id": str}} OR {{"trace_id": str, "short_id": str}} |+ | read_document | Read a .md file or answer file | {{"filename": str}} OR {{"path": str}} |+ | write_document | Write/append to a .md file | {{"filename": str, "content": str, "mode?": "overwrite" or "append"}} |++ # Core Principle+ User weaknesses are revealed by **what the user asks and does**, NOT by how the system internally processes requests. The system's reasoning rounds, replan counts, or tool selection patterns are irrelevant to user weakness.++ # Weakness Signals (Priority Order)++ ## Signal 1: User Input (Primary)+ Whatever the user asks about or requests questions on — that topic is at the boundary of their knowledge. Record it as an area of interest and potential gap. Not every input is a weakness, but recurring topics across sessions strongly indicate gaps.++ ## Signal 2: Cross-Session Inference (Deep Analysis)+ This is where the real insight comes from. Cross-reference the user's current input with historical system outputs:++ - **For solve sessions**: Search historical solve traces. If the system previously explained topic X, but the user is now asking about X again (or a sub-aspect of X), the prior explanation did not fully land. The specific sub-aspect they are re-asking about is likely a **knowledge dead zone**.+ - **For question sessions**: Search historical question traces for wrong/incorrect answers (use `search_traces` with `level=3` to find answer nodes). If the user got topic Y wrong previously, and is now asking questions related to Y again, this is a **persistent blind spot**. Also check: after getting Y wrong, did the user ask solve questions about Y? This shows active struggle.++ ## Signal 3: Knowledge Structure Context+ The system uses a knowledge base (RAG). When identifying a weakness, try to locate it within the broader knowledge structure — what chapter or concept does it belong to? What prerequisite knowledge might be missing? This helps the weakness profile be actionable.++ # Recommended Workflow+ 1. Read the session content provided below — the user's input is the primary signal.+ 2. Extract the user's core topic(s) from their input.+ 3. Search for ALL historical wrong answers: `search_traces` with `level=3` to find answer nodes with wrong/incorrect results.+ 4. Search for prior solve sessions on the same or similar topics to check if the system already addressed this.+ 5. Cross-reference: Is the user re-visiting something previously explained or previously answered incorrectly?+ 6. Update `weakness.md` (mode "overwrite", preserve all existing entries).++ # Document Format+ ```markdown+ ## Knowledge Weak Points++ ### Active+ - **Topic name** (first seen: YYYY-MM-DD, sessions: N)+ - Quiz stats: X questions, correct Y, wrong Z (accuracy P%)+ - User behavior: {{what the user asked/did that reveals this gap}}+ - Cross evidence: {{cross-session inference, e.g. "System explained X in trace_A, but user re-asked about X's sub-aspect in trace_B"}}+ - Knowledge location: {{where this sits in the knowledge structure, if identifiable}}+ - Related sessions: trace_id_1, trace_id_2++ ### Resolved+ - **Topic name** (resolved: YYYY-MM-DD)+ - Was: {{brief description}}+ - Resolution evidence: {{e.g. "User answered correctly in recent sessions and stopped re-asking"}}+ ```++ # Rules+ - **DO NOT** infer weakness from system internals (ReAct rounds, replan count, tool usage patterns, number of steps). These reflect system behavior, not user knowledge.+ - **DO** actively search for wrong-answer nodes — they are the strongest quantitative signal.+ - When updating an existing weakness, update session count and add new evidence. Track quiz stats if question traces exist for that topic.+ - A weakness can be marked **Resolved** if the user answers correctly on the topic in recent sessions AND stops re-asking about it.+ - If no weakness signals are detected, do NOT invent them — write a brief "no new weaknesses detected" note.+ - Always write to `weakness.md` using mode "overwrite" since you manage the full document structure.+ - **IMPORTANT**: When rewriting, preserve ALL existing entries with their full details. Do NOT drop or summarize previous entries — keep every Active and Resolved entry intact, update as needed, and add new entries.++ # Output Format+ Each round, return strict JSON:+ ```json+ {{+ "thought": "Your reasoning about what to do next...",+ "actions": [+ {{"tool": "tool_name", "input": {{...}}}}+ ],+ "done": false+ }}+ ```+ Set `done: true` on your final round (after calling write_document).++user_template: |+ ## Current Session+ - Trace ID: {trace_id}+ - Trace Type: {trace_type}+ - User Input: {question}++ ## Session Summary+ {session_summary}++ ## Full Session Content+ {full_context}++ ## Current weakness.md+ {current_document}++ Analyze this session for user knowledge gaps. The user's input itself is the primary signal.+ Cross-reference with historical traces (especially wrong answers and repeated topics) to build a deeper picture.+ Update weakness.md preserving all existing entries.diff --git a/src/personalization/prompts/zh/memory_agent.yaml b/src/personalization/prompts/zh/memory_agent.yamldeleted file mode 100644index 8215ed69a..000000000--- a/src/personalization/prompts/zh/memory_agent.yaml+++ /dev/null@@ -1,60 +0,0 @@-system: |- 你是一个学习记忆分析师。你的职责是分析学习交互,并决定哪些信息值得记录以用于个性化。-- 你需要识别:- 1. 用户偏好(学习风格、解释详细程度、偏好的格式)- 2. 知识薄弱点(用户难以理解的主题、常见错误)- 3. 里程碑(重要成就、完成的学习目标)- 4. 值得记录的日常学习活动-- 指导原则:- - 只记录对未来个性化真正有用的信息- - 避免记录琐碎或重复的信息- - 笔记要简洁但具体- - 关注有助于改善未来交互的模式--analyze: |- 分析以下学习交互,并决定要记录什么:-- ## 事件类型- {event_type}-- ## 交互详情- {event_context}-- ## 当前长期记忆- {current_memory}-- ## 最近的每日笔记- {recent_notes}-- ## 你的任务- 基于这次交互,决定应该记录什么(如果有的话)。-- 返回一个JSON对象,结构如下:- {{- "action": "write_daily" | "update_memory" | "both" | "skip",- "daily_content": "要添加到今日笔记的内容(如果action包含daily)",- "memory_updates": {{- "preferences": ["要添加的新偏好"],- "weak_points": ["识别出的新薄弱点"],- "milestones": ["达成的新里程碑(格式:YYYY-MM-DD: 描述)"]- }},- "reasoning": "你决策的简要解释"- }}-- 重要提示:- - 如果交互不包含值得记录的信息,使用 "skip"- - 只有对于重要的、持续性的模式才更新记忆(不是一次性的事件)- - 每日笔记应该记录学习活动摘要- - 要有选择性 - 不是每次交互都需要记录--preferences_extraction: |- 你正在分析学习交互以检测用户偏好。- 提取任何关于以下方面的明确或隐含偏好:- - 解释风格(详细vs简洁、分步骤vs概览)- - 学习格式(视觉、文字、示例)- - 响应格式偏好-- 返回一个JSON对象:{"preferences": ["偏好1", "偏好2", ...]}- 如果没有检测到明确的偏好,返回空数组。diff --git a/src/personalization/prompts/zh/reflection_agent.yaml b/src/personalization/prompts/zh/reflection_agent.yamlnew file mode 100644index 000000000..e1d84c952--- /dev/null+++ b/src/personalization/prompts/zh/reflection_agent.yaml@@ -0,0 +1,75 @@+system: |+ # 角色+ 你是一个AI教学系统的**反思Agent**。每次会话结束后,你需要评估系统的响应是否**满足了用户的意图和偏好**。++ # 可用工具+ 每轮可以调用一个或多个工具。以JSON格式返回"actions"数组。++ | 工具 | 描述 | 输入 |+ |------|------|------|+ | search_traces | 在所有历史轨迹中语义搜索 | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |+ | list_traces | 按时间列出近期轨迹 | {{"n?": int, "trace_type?": str}} |+ | get_trace_detail | 加载完整轨迹概览或单个节点详情 | {{"trace_id": str}} 或 {{"trace_id": str, "short_id": str}} |+ | read_document | 读取.md文件或回答文件 | {{"filename": str}} 或 {{"path": str}} |+ | write_document | 写入/追加.md文件 | {{"filename": str, "content": str, "mode?": "overwrite" 或 "append"}} |++ # 评估维度+ 1. **意图匹配**:系统的输出是否符合用户的实际需求?(例如用户要图但给了文字;用户要简洁但给了冗长回答)+ 2. **偏好契合**:基于历史轨迹了解用户偏好(简洁/详细、视觉/文字、中文/英文),本次响应是否匹配这些模式?+ 3. **重复模式**:用户是否在重复提问系统之前已回答过的问题?如果是,说明之前的回答未能满足需求 — 记录可能缺失的方面。+ 4. **格式/风格问题**:响应格式是否恰当?(例如该给解释的给了代码,语言不对,等等)++ # 推荐工作流+ 1. 阅读下方提供的完整会话内容。+ 2. 搜索相似的历史会话(`search_traces`)以了解用户的常见偏好和模式。+ 3. 对比:本次响应是否符合我们对该用户的了解?+ 4. 以 mode "overwrite" 写入 `reflection.md`(保留所有已有条目)。++ # 条目格式+ 每条记录应为简洁的结构化块(最多3-5行):+ ```+ - **{{trace_id}}** ({{日期}})+ - 意图: {{用户想要什么}}+ - 满足度: {{满足 / 部分满足 / 未满足}}+ - 原因: {{1-2句说明}}+ - 建议: {{具体改进建议,或"无"}}+ ```++ # 规则+ - 简洁。每条记录**最多3-5行**。+ - 如果响应明确满足了用户意图且无问题,写一条简短的"满足,无需改进"记录即可。+ - 聚焦于**面向用户的**质量,而非系统内部机制。+ - 始终通过 write_document 以 mode "overwrite" 写入 `reflection.md`。+ - **重要**:重写时必须完整保留所有历史条目的全部细节。不要精简或丢弃之前的条目 — 保持原样并追加新条目。++ # 输出格式+ 每轮返回严格JSON:+ ```json+ {{+ "thought": "你的推理过程...",+ "actions": [+ {{"tool": "工具名", "input": {{...}}}}+ ],+ "done": false+ }}+ ```+ 最后一轮(调用write_document之后)设置 `done: true`。++user_template: |+ ## 当前会话+ - 轨迹ID: {trace_id}+ - 轨迹类型: {trace_type}+ - 用户输入: {question}++ ## 会话摘要+ {session_summary}++ ## 完整会话内容+ {full_context}++ ## 当前 reflection.md 内容+ {current_document}++ 评估本次会话的响应是否满足了用户的意图和偏好。+ 搜索历史相似会话以了解用户模式。+ 写入更新后的reflection.md,保留所有已有条目并追加新条目。diff --git a/src/personalization/prompts/zh/summary_agent.yaml b/src/personalization/prompts/zh/summary_agent.yamlnew file mode 100644index 000000000..32df13ca8--- /dev/null+++ b/src/personalization/prompts/zh/summary_agent.yaml@@ -0,0 +1,77 @@+system: |+ # 角色+ 你是一个AI教学系统的**总结Agent**。每次学习会话结束后,你需要生成简洁、准确的会话摘要,并追加到会话历史中。++ # 可用工具+ 每轮可以调用一个或多个工具。以JSON格式返回"actions"数组。++ | 工具 | 描述 | 输入 |+ |------|------|------|+ | search_traces | 在所有历史轨迹中语义搜索 | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |+ | list_traces | 按时间列出近期轨迹 | {{"n?": int, "trace_type?": str}} |+ | get_trace_detail | 加载完整轨迹概览或单个节点详情 | {{"trace_id": str}} 或 {{"trace_id": str, "short_id": str}} |+ | read_document | 读取.md文件或回答文件 | {{"filename": str}} 或 {{"path": str}} |+ | write_document | 写入/追加.md文件 | {{"filename": str, "content": str, "mode?": "overwrite" 或 "append"}} |++ # 指导原则++ ## 解题会话+ - 记录用户问了什么、解题路径(步骤+工具)、关键发现。+ - 使用 `get_trace_detail` 查看各步骤节点的 `self_note` 字段以获取简洁的每步总结。++ ## 出题会话+ - **必须记录用户的作答表现**:答对几题、答错几题、跳过几题。+ - 总结用户答错的题目并简要说明主题。+ - 记录考察的题目类型和难度等级。++ ## 通用规则+ - 先读取已有的 `memory.md`。如果该 `trace_id` 已出现其中,**跳过** — 不要重复添加。+ - 每条摘要保持简洁:**3-6行**。客观记录事实,不做主观解读。+ - 始终**追加**(不要覆盖之前的内容)。+ - 优先使用下方提供的完整会话内容作为主要信息源 — 仅在需要补充细节时使用工具。++ # 条目格式++ 解题会话:+ ```+ ### {{trace_id}} | {{简短主题}}+ - 用户问题: ...+ - 解题路径: S1->S2->S3, 工具: rag_search, code_execute+ - 关键发现: ...+ ```++ 出题会话:+ ```+ ### {{trace_id}} | {{简短主题}}+ - 题目: N题 (类型分布)+ - 用户表现: 正确X/N (P%)+ - 错题: "主题" — 简述+ ```++ # 输出格式+ 每轮返回严格JSON:+ ```json+ {{+ "thought": "你的推理过程...",+ "actions": [+ {{"tool": "工具名", "input": {{...}}}}+ ],+ "done": false+ }}+ ```+ 最后一轮(调用write_document之后)设置 `done: true`。++user_template: |+ ## 当前会话+ - 轨迹ID: {trace_id}+ - 轨迹类型: {trace_type}+ - 用户输入: {question}++ ## 会话摘要+ {session_summary}++ ## 完整会话内容+ {full_context}++ 读取已有的memory.md。如果该trace_id已存在,则跳过。+ 否则,追加一条简洁的事实性摘要。diff --git a/src/personalization/prompts/zh/weakness_agent.yaml b/src/personalization/prompts/zh/weakness_agent.yamlnew file mode 100644index 000000000..9f92c2d20--- /dev/null+++ b/src/personalization/prompts/zh/weakness_agent.yaml@@ -0,0 +1,98 @@+system: |+ # 角色+ 你是一个AI教学系统的**薄弱点分析Agent**。你负责基于用户的学习交互来维护一份用户知识盲区档案。++ # 可用工具+ 每轮可以调用一个或多个工具。以JSON格式返回"actions"数组。++ | 工具 | 描述 | 输入 |+ |------|------|------|+ | search_traces | 在所有历史轨迹中语义搜索 | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |+ | list_traces | 按时间列出近期轨迹 | {{"n?": int, "trace_type?": str}} |+ | get_trace_detail | 加载完整轨迹概览或单个节点详情 | {{"trace_id": str}} 或 {{"trace_id": str, "short_id": str}} |+ | read_document | 读取.md文件或回答文件 | {{"filename": str}} 或 {{"path": str}} |+ | write_document | 写入/追加.md文件 | {{"filename": str, "content": str, "mode?": "overwrite" 或 "append"}} |++ # 核心原则+ 用户的薄弱点由**用户的提问和行为**体现,而非系统内部的推理过程。系统的推理轮数、重规划次数、工具选择模式等与用户薄弱点无关。++ # 薄弱信号(优先级排序)++ ## 信号1:用户输入(主要信号)+ 用户主动提问或出题的内容,就处于其知识边界上。将其记录为关注领域和潜在缺口。不是每次输入都代表薄弱点,但跨会话反复出现的主题强烈暗示知识缺口。++ ## 信号2:交叉推断(深度分析)+ 这是获取深层洞察的关键。将用户当前输入与历史系统输出交叉对比:++ - **解题会话**:搜索历史解题轨迹。如果系统之前已经解释过主题X,但用户现在又在问X(或X的某个子方面),说明之前的解释没有完全让用户理解。用户重复提问的具体子方面很可能就是**知识死穴**。+ - **出题会话**:搜索历史出题轨迹中的错误回答(使用 `search_traces`,设置 `level=3` 来查找答案节点)。如果用户之前答错了主题Y,现在又来问与Y相关的问题,这就是**持续性盲区**。同时检查:用户答错Y之后,是否又去问了关于Y的解题问题?这说明用户正在主动挣扎。++ ## 信号3:知识结构定位+ 系统使用知识库(RAG)。在识别薄弱点时,尝试将其定位到更广泛的知识结构中 — 它属于哪个章节或概念?可能缺少什么前置知识?这有助于薄弱点档案更具可操作性。++ # 推荐工作流+ 1. 阅读下方提供的会话内容 — 用户的输入是主要信号。+ 2. 从用户输入中提取核心主题。+ 3. 搜索所有历史错误答案:使用 `search_traces`,设置 `level=3` 查找 wrong/incorrect 的答案节点。+ 4. 搜索同一或相似主题的历史解题会话,检查系统是否已经解答过。+ 5. 交叉对比:用户是否在重访之前已解释或已答错的内容?+ 6. 更新 `weakness.md`(mode "overwrite",保留所有已有条目)。++ # 文档格式+ ```markdown+ ## 知识薄弱点 / Knowledge Weak Points++ ### 进行中 / Active+ - **主题名称** (首次出现: YYYY-MM-DD, 会话数: N)+ - 答题统计: X题, 正确Y, 错误Z (正确率 P%)+ - 用户行为: {{用户做了什么/问了什么暴露了这个缺口}}+ - 交叉证据: {{跨会话推断,例如"系统在trace_A中已解释过X,但用户在trace_B中又问了X的Y方面"}}+ - 知识定位: {{在知识体系中的位置,如可识别}}+ - 相关会话: trace_id_1, trace_id_2++ ### 已解决 / Resolved+ - **主题名称** (解决时间: YYYY-MM-DD)+ - 曾经: {{简述}}+ - 解决证据: {{例如"用户近期在该主题上答题正确且不再重复提问"}}+ ```++ # 规则+ - **禁止**从系统内部指标(ReAct轮数、重规划次数、工具使用模式、步骤数量)推断用户薄弱点。这些反映的是系统行为,不是用户知识。+ - **务必**主动搜索错误答案节点 — 这是最强的量化信号。+ - 更新已有薄弱点时,更新会话计数并添加新证据。如果该主题存在出题轨迹,追踪答题统计。+ - 当用户在该主题上近期答题正确且不再重复提问时,可以标记为**已解决**。+ - 如果没有发现薄弱信号,不要捏造 — 写一条简短的"未检测到新薄弱点"即可。+ - 始终以 mode "overwrite" 写入 `weakness.md`,因为你管理整个文档结构。+ - **重要**:重写时必须完整保留所有已有条目的全部细节。不要丢弃或精简已有条目 — 保持每一个 Active 和 Resolved 条目原样不变,按需更新,并添加新条目。++ # 输出格式+ 每轮返回严格JSON:+ ```json+ {{+ "thought": "你的推理过程...",+ "actions": [+ {{"tool": "工具名", "input": {{...}}}}+ ],+ "done": false+ }}+ ```+ 最后一轮(调用write_document之后)设置 `done: true`。++user_template: |+ ## 当前会话+ - 轨迹ID: {trace_id}+ - 轨迹类型: {trace_type}+ - 用户输入: {question}++ ## 会话摘要+ {session_summary}++ ## 完整会话内容+ {full_context}++ ## 当前 weakness.md 内容+ {current_document}++ 分析本次会话中的用户知识盲区。用户的输入本身是主要信号。+ 与历史轨迹交叉对比(尤其是错误答案和重复主题)以构建更深入的画像。+ 更新weakness.md,保留所有已有条目。diff --git a/src/personalization/react_runner.py b/src/personalization/react_runner.pynew file mode 100644index 000000000..6da0530cf--- /dev/null+++ b/src/personalization/react_runner.py@@ -0,0 +1,338 @@+# -*- coding: utf-8 -*-+"""+ReAct Runner+=============++General-purpose ReAct loop that supports **parallel tool calls** per+round. Designed for the memory agents but could be reused elsewhere.+"""+from __future__ import annotations++import asyncio+import json+import logging+import re+from datetime import datetime+from pathlib import Path+from typing import Any++from src.agents.base_agent import BaseAgent++from .trace_tools import TOOL_NAMES, TraceToolkit++logger = logging.getLogger(__name__)+++class ReActRunner:+ """Execute a ReAct loop on behalf of a memory agent.++ Each round the agent returns JSON with ``thought``, ``actions`` (a+ list of tool calls), and ``done`` (bool). When ``done`` is true the+ loop terminates after executing the final actions.++ Parameters+ ----------+ agent:+ A :class:`BaseAgent` subclass used to call the LLM.+ toolkit:+ A :class:`TraceToolkit` instance whose tools are available to+ the agent.+ max_rounds:+ Safety cap on the number of think-act-observe iterations.+ log_dir:+ Directory to write per-run log files. If ``None``, no log file+ is written.+ """++ def __init__(+ self,+ agent: BaseAgent,+ toolkit: TraceToolkit,+ max_rounds: int = 6,+ log_dir: Path | None = None,+ ) -> None:+ self._agent = agent+ self._toolkit = toolkit+ self._max_rounds = max(1, max_rounds)+ self._log_dir = log_dir++ async def run(+ self,+ system_prompt: str,+ initial_context: str,+ ) -> None:+ """Execute the full ReAct loop.++ The agent is expected to call ``write_document`` as part of its+ actions to persist its output. This method does not return the+ written content explicitly — it is saved by the tool itself.+ """+ messages: list[dict[str, str]] = [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": initial_context},+ ]++ log_entries: list[str] = []+ run_ts = datetime.now().strftime("%Y%m%d_%H%M%S")+ agent_name = self._agent.agent_name++ _log_header(log_entries, agent_name, run_ts, system_prompt, initial_context)++ for round_num in range(1, self._max_rounds + 1):+ logger.info(+ "[ReAct] %s round %d/%d",+ agent_name, round_num, self._max_rounds,+ )++ response = await self._agent.call_llm(+ user_prompt="",+ system_prompt="",+ messages=messages,+ response_format={"type": "json_object"},+ verbose=False,+ stage=f"react_round_{round_num}",+ )++ parsed = _parse_react_json(response)+ thought = parsed.get("thought", "")+ actions = parsed.get("actions", [])+ done = parsed.get("done", False)++ logger.info(+ "[ReAct] %s thought: %s | actions: %d | done: %s",+ agent_name,+ thought[:120],+ len(actions),+ done,+ )++ _log_round(log_entries, round_num, thought, actions, response, done)++ messages.append({"role": "assistant", "content": response})++ if not actions:+ if done:+ break+ messages.append({+ "role": "user",+ "content": "No actions provided. Please specify at least one action.",+ })+ log_entries.append(" (no actions — prompting agent to retry)\n")+ continue++ observations = await self._execute_actions(actions)+ obs_text = _format_observations(observations)++ _log_observations(log_entries, observations)++ if done:+ logger.info("[ReAct] %s finished after round %d", agent_name, round_num)+ break++ messages.append({"role": "user", "content": obs_text})++ else:+ logger.warning(+ "[ReAct] %s reached max_rounds (%d) without finishing",+ agent_name, self._max_rounds,+ )+ log_entries.append(+ f"\n!! REACHED MAX ROUNDS ({self._max_rounds}) WITHOUT FINISHING !!\n"+ )++ self._write_log(agent_name, run_ts, log_entries)++ # ------------------------------------------------------------------+ # Internal helpers+ # ------------------------------------------------------------------++ async def _execute_actions(+ self,+ actions: list[dict[str, Any]],+ ) -> list[tuple[str, str]]:+ """Execute tool calls (in parallel) and return (tool, observation) pairs."""+ if not actions:+ return []++ async def _call_one(action: dict[str, Any]) -> tuple[str, str]:+ tool = str(action.get("tool", ""))+ params = action.get("input", {})+ if not isinstance(params, dict):+ params = {}+ if tool not in TOOL_NAMES:+ return tool, f"[error] Unknown tool: {tool}"+ obs = await self._toolkit.call(tool, params)+ return tool, obs++ results = await asyncio.gather(*[_call_one(a) for a in actions])+ return list(results)++ def _write_log(+ self,+ agent_name: str,+ run_ts: str,+ entries: list[str],+ ) -> None:+ """Append the full ReAct trace to the agent's persistent log file."""+ if self._log_dir is None:+ return+ try:+ self._log_dir.mkdir(parents=True, exist_ok=True)+ filename = f"{agent_name}.log"+ path = self._log_dir / filename+ with open(path, "a", encoding="utf-8") as f:+ f.write("\n".join(entries))+ f.write("\n\n")+ logger.info("[ReAct] Log appended → %s", path)+ except Exception as exc:+ logger.warning("[ReAct] Failed to write log file: %s", exc)+++# ======================================================================+# Log formatting helpers+# ======================================================================+++def _log_header(+ entries: list[str],+ agent_name: str,+ run_ts: str,+ system_prompt: str,+ initial_context: str,+) -> None:+ """Write the log header with system prompt and initial context."""+ entries.append(f"# {agent_name} — {run_ts}\n")+ entries.append("## System Prompt\n")+ entries.append(f"```\n{system_prompt}\n```\n")+ entries.append("## Initial Context\n")+ entries.append(f"```\n{initial_context}\n```\n")+ entries.append("---\n")+++def _log_round(+ entries: list[str],+ round_num: int,+ thought: str,+ actions: list[dict[str, Any]],+ raw_response: str,+ done: bool,+) -> None:+ """Log one ReAct round: thought, actions requested, and raw LLM output."""+ entries.append(f"## Round {round_num}{' (final)' if done else ''}\n")+ entries.append(f"### Thought\n\n{thought}\n")+ if actions:+ entries.append("### Actions\n")+ for i, act in enumerate(actions, 1):+ tool = act.get("tool", "?")+ params = act.get("input", {})+ entries.append(f"**{i}. {tool}**")+ entries.append(f"```json\n{json.dumps(params, ensure_ascii=False, indent=2)}\n```\n")+ entries.append("### Raw LLM Response\n")+ entries.append(f"```json\n{raw_response}\n```\n")+++def _log_observations(+ entries: list[str],+ observations: list[tuple[str, str]],+) -> None:+ """Log tool observations returned to the agent."""+ entries.append("### Observations\n")+ for tool, obs in observations:+ entries.append(f"**[{tool}]**\n")+ entries.append(f"```\n{obs}\n```\n")+ entries.append("---\n")+++# ======================================================================+# Parsing helpers+# ======================================================================++_JSON_BLOCK_RE = re.compile(r"```(?:json)?\s*\n?(.*?)\n?\s*```", re.DOTALL)+_TRAILING_COMMA_RE = re.compile(r",\s*([}\]])")+++def _normalize_text(text: str) -> str:+ """Strip BOM / NUL and normalize smart quotes."""+ text = text.lstrip("\ufeff\x00").strip()+ for lq, rq in [("\u201c", '"'), ("\u201d", '"'), ("\u2018", "'"), ("\u2019", "'")]:+ text = text.replace(lq, rq)+ return text+++def _try_parse(candidate: str) -> dict[str, Any] | None:+ """Attempt JSON parse with trailing-comma cleanup."""+ for txt in (candidate, _TRAILING_COMMA_RE.sub(r"\1", candidate)):+ try:+ data = json.loads(txt)+ if isinstance(data, dict):+ return data+ except (json.JSONDecodeError, ValueError):+ continue+ return None+++def _repair_truncated(text: str) -> dict[str, Any] | None:+ """Try to recover a usable dict from JSON truncated by max_tokens.++ Strategy: close any open braces/brackets and re-parse. Then ensure the+ required keys exist so the ReAct loop can continue.+ """+ open_b = text.count("{") - text.count("}")+ open_s = text.count("[") - text.count("]")+ if open_b <= 0 and open_s <= 0:+ return None+ patched = text.rstrip(", \t\n")+ patched += "]" * max(open_s, 0)+ patched += "}" * max(open_b, 0)+ return _try_parse(patched)+++def _parse_react_json(text: str) -> dict[str, Any]:+ """Best-effort parse of the agent's JSON response.++ Tries, in order:+ 1. Direct parse (optionally from a ```json``` fenced block).+ 2. Extract outermost ``{…}`` substring and parse.+ 3. Repair truncated JSON by closing open braces/brackets.+ 4. Fallback: treat entire text as thought, no actions, done=True.+ """+ text = _normalize_text(text)++ m = _JSON_BLOCK_RE.search(text)+ if m:+ text = m.group(1).strip()++ # --- strategy 1: direct parse ---+ result = _try_parse(text)+ if result is not None:+ return result++ # --- strategy 2: outermost { … } ---+ start = text.find("{")+ if start >= 0:+ end = text.rfind("}")+ if end > start:+ result = _try_parse(text[start : end + 1])+ if result is not None:+ return result++ # --- strategy 3: truncated JSON repair (from first '{' onward) ---+ result = _repair_truncated(text[start:])+ if result is not None:+ logger.debug("[ReAct] Recovered truncated JSON (%d open braces closed)",+ text[start:].count("{") - text[start:].count("}"))+ return result++ logger.warning("[ReAct] Failed to parse JSON response: %s", text[:200])+ return {"thought": text[:500], "actions": [], "done": True}+++def _format_observations(results: list[tuple[str, str]]) -> str:+ """Format tool observations into a user message."""+ if not results:+ return "(no observations)"+ parts: list[str] = ["Observations:"]+ for tool, obs in results:+ header = f"[{tool}]"+ parts.append(f"{header}\n{obs}")+ return "\n\n".join(parts)diff --git a/src/personalization/service.py b/src/personalization/service.pyindex 44033b45d..aa8ea7559 100644--- a/src/personalization/service.py+++ b/src/personalization/service.py@@ -4,47 +4,47 @@ Personalization Service=======================Service layer that coordinates personalization memory management.-Listens to events, invokes MemoryAgent, and provides preference access.+Listens to events, builds traces, and runs three specialized memory+agents (Reflection, Summary, Weakness) in parallel."""import asyncio+import jsonimport loggingfrom pathlib import Pathfrom typing import Any, Dict, Optionalimport yaml+from src.agents.base_agent import BaseAgentfrom src.core.event_bus import Event, EventType, get_event_busfrom src.services.path_service import get_path_service-from .memory import LearningMemory, get_learning_memory-from .memory_agent import MemoryAgent, MemoryDecision+from .agents import ReflectionAgent, SummaryAgent, WeaknessAgent+from .memory_reader import MemoryReader+from .react_runner import ReActRunner+from .trace_forest import TraceForest+from .trace_tools import TraceToolkit+from .trace_tree import TraceNode, TraceTreelogger = logging.getLogger(__name__)class PersonalizationService:- """- Service for managing personalization memory.-- Responsibilities:- 1. Subscribe to EventBus events (SOLVE_COMPLETE, QUESTION_COMPLETE)- 2. Invoke MemoryAgent to analyze events- 3. Write memory updates to storage- 4. Provide preference context for prompt injection+ """Orchestrates trace registration and three memory agents.- Usage:- # Get singleton instance- service = get_personalization_service()+ After each ``SOLVE_COMPLETE`` or ``QUESTION_COMPLETE`` event the+ service:- # Start the service (call during app startup)- await service.start()+ 1. Builds and registers a :class:`TraceTree`.+ 2. Launches three memory agents in parallel via :class:`ReActRunner`:- # Get preference for prompt injection- preference = service.get_preference_for_prompt()+ * **ReflectionAgent** → ``reflection.md``+ * **SummaryAgent** → ``memory.md``+ * **WeaknessAgent** → ``weakness.md``- # Stop the service (call during app shutdown)- await service.stop()+ Each agent explores the trace forest through the five-tool+ :class:`TraceToolkit` and writes its own document."""_instance: Optional["PersonalizationService"] = None@@ -60,73 +60,76 @@ class PersonalizationService:returnself._running = False- self._memory: Optional[LearningMemory] = None- self._agent: Optional[MemoryAgent] = None+ self._forest: Optional[TraceForest] = None+ self._reader: Optional[MemoryReader] = Noneself._config: Dict[str, Any] = {}self._language = "en"- # Load configuration+ self._reflection_agent: Optional[ReflectionAgent] = None+ self._summary_agent: Optional[SummaryAgent] = None+ self._weakness_agent: Optional[WeaknessAgent] = None+self._load_config()PersonalizationService._initialized = Truelogger.debug("PersonalizationService initialized")+ # ------------------------------------------------------------------+ # Configuration+ # ------------------------------------------------------------------+def _load_config(self) -> None:- """Load configuration from config/memory.yaml."""config_path = get_path_service().project_root / "config" / "memory.yaml"-if config_path.exists():try:with open(config_path, "r", encoding="utf-8") as f:self._config = yaml.safe_load(f) or {}- logger.debug(f"Loaded memory config: {config_path}")+ logger.debug("Loaded memory config: %s", config_path)except Exception as e:- logger.warning(f"Failed to load memory config: {e}")+ logger.warning("Failed to load memory config: %s", e)self._config = {}else:- logger.debug("No memory config found, using defaults")self._config = {}@propertydef auto_update(self) -> bool:- """Check if auto-update is enabled."""return self._config.get("memory", {}).get("auto_update", True)@property- def recent_days(self) -> int:- """Get number of recent days for context."""- return self._config.get("memory", {}).get("recent_days", 7)+ def max_react_rounds(self) -> int:+ return self._config.get("memory", {}).get("max_react_rounds", 6)- @property- def max_preference_length(self) -> int:- """Get maximum preference length for prompt injection."""- return self._config.get("memory", {}).get("max_preference_length", 2000)+ def _agent_enabled(self, name: str) -> bool:+ agents_cfg = self._config.get("agents", {})+ return agents_cfg.get(name, {}).get("enabled", True)- async def start(self) -> None:- """- Start the personalization service.+ # ------------------------------------------------------------------+ # Lifecycle+ # ------------------------------------------------------------------- This should be called during application startup.- Subscribes to EventBus and initializes components.- """+ async def start(self) -> None:+ """Start the personalization service."""if self._running:logger.debug("PersonalizationService already running")returnself._running = True+ self._forest = TraceForest()+ self._reader = MemoryReader(forest=self._forest)- # Initialize memory- self._memory = get_learning_memory()-- # Initialize agentllm_config = self._config.get("llm", {})- temperature = llm_config.get("temperature", 0.3)- self._agent = MemoryAgent(- language=self._language,- temperature=temperature,+ temperature = llm_config.get("temperature", 0.5)++ self._reflection_agent = ReflectionAgent(+ language=self._language, temperature=temperature,+ )+ self._summary_agent = SummaryAgent(+ language=self._language, temperature=temperature,+ )+ self._weakness_agent = WeaknessAgent(+ language=self._language, temperature=temperature,)- # Subscribe to eventsif self.auto_update:event_bus = get_event_bus()event_bus.subscribe(EventType.SOLVE_COMPLETE, self._handle_event)@@ -136,160 +139,557 @@ class PersonalizationService:logger.info("PersonalizationService started (auto-update disabled)")async def stop(self) -> None:- """- Stop the personalization service.-- This should be called during application shutdown.- """if not self._running:return-self._running = False-- # Unsubscribe from eventsif self.auto_update:event_bus = get_event_bus()event_bus.unsubscribe(EventType.SOLVE_COMPLETE, self._handle_event)event_bus.unsubscribe(EventType.QUESTION_COMPLETE, self._handle_event)-logger.info("PersonalizationService stopped")- async def _handle_event(self, event: Event) -> None:- """- Handle a learning event from EventBus.+ # ------------------------------------------------------------------+ # Event handling (write path)+ # ------------------------------------------------------------------- This is called asynchronously when SOLVE_COMPLETE or QUESTION_COMPLETE- events are published. It analyzes the event and updates memory as needed.-- Args:- event: The event to process- """- if not self._running or not self._agent or not self._memory:+ async def _handle_event(self, event: Event) -> None:+ if not self._running or not self._forest:returntry:- logger.debug(f"Processing event: {event.type} (task_id={event.task_id})")-- # Get current context- current_memory = self._memory.read_memory()- recent_notes = self._format_recent_notes()-- # Analyze event with MemoryAgent- decision = await self._agent.process(- event=event,- current_memory=current_memory,- recent_notes=recent_notes,+ event_type_str = event.type.value if hasattr(event.type, "value") else str(event.type)+ logger.info(+ "[MEM-WRITE] Received event: %s (task_id=%s)",+ event_type_str, event.task_id,)- # Apply decision- await self._apply_decision(decision)-- logger.debug(f"Event processed: action={decision.action}")+ trace = self._build_trace_from_event(event)+ if trace:+ logger.info(+ "[MEM-WRITE] Registering trace: id=%s type=%s nodes=%d",+ trace.trace_id, trace.trace_type, len(trace.nodes),+ )+ await self._forest.register(trace)+ logger.info("[MEM-WRITE] Trace registered and indexed")+ else:+ logger.warning("[MEM-WRITE] No trace built from event")+ return++ if trace.trace_type == "question":+ logger.info(+ "[MEM-WRITE] Question trace registered; "+ "memory agents deferred until all answers are recorded."+ )+ return++ await self._run_memory_agents(trace)except Exception as e:- logger.error(f"Failed to process event: {e}", exc_info=True)+ logger.error("Failed to process event: %s", e, exc_info=True)++ async def _run_memory_agents(self, trace: TraceTree) -> None:+ """Launch the three memory agents in parallel."""+ toolkit = TraceToolkit(self._forest, self._forest.memory_dir)++ session_summary = self._build_session_summary(trace)+ full_context = self._build_full_context(trace)++ context_base = {+ "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,+ }++ tasks: list[asyncio.Task] = []++ if self._agent_enabled("reflection") and self._reflection_agent:+ ctx = {**context_base, "current_document": self._read_md("reflection.md")}+ tasks.append(+ asyncio.create_task(+ self._run_single_agent(+ self._reflection_agent, toolkit, ctx,+ ),+ name="reflection",+ )+ )- async def _apply_decision(self, decision: MemoryDecision) -> None:- """- Apply a MemoryDecision to storage.+ if self._agent_enabled("summary") and self._summary_agent:+ tasks.append(+ asyncio.create_task(+ self._run_single_agent(+ self._summary_agent, toolkit, context_base,+ ),+ name="summary",+ )+ )- Args:- decision: The decision from MemoryAgent- """- if decision.action == "skip":+ if self._agent_enabled("weakness") and self._weakness_agent:+ ctx = {**context_base, "current_document": self._read_md("weakness.md")}+ tasks.append(+ asyncio.create_task(+ self._run_single_agent(+ self._weakness_agent, toolkit, ctx,+ ),+ 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(+ "[MEM-WRITE] Agent '%s' failed: %s",+ task.get_name(), result,+ )+ else:+ logger.info("[MEM-WRITE] Agent '%s' completed", task.get_name())++ async def _run_single_agent(+ self,+ agent: BaseAgent,+ toolkit: TraceToolkit,+ context: dict[str, str],+ ) -> None:+ """Run one memory agent through the ReAct loop."""+ system_prompt = agent.get_prompt("system", "")+ if not system_prompt:+ logger.warning("[MEM-WRITE] No system prompt for %s", agent.agent_name)return- if not self._memory:+ user_template = agent.get_prompt("user_template", "")+ if not user_template:+ logger.warning("[MEM-WRITE] No user_template for %s", agent.agent_name)return- # Write daily note- if decision.action in ("write_daily", "both") and decision.daily_content:- self._memory.append_to_daily_note(decision.daily_content)- logger.debug("Daily note updated")+ initial_context = user_template.format(**context)- # Update long-term memory- if decision.action in ("update_memory", "both") and decision.memory_updates:- updates = decision.memory_updates+ log_dir = self._forest.memory_dir / "logs" if self._forest else None+ runner = ReActRunner(+ agent=agent,+ toolkit=toolkit,+ max_rounds=self.max_react_rounds,+ log_dir=log_dir,+ )+ await runner.run(system_prompt=system_prompt, initial_context=initial_context)- if updates.get("preferences"):- self._memory.append_to_section("preferences", updates["preferences"])- logger.debug(f"Added {len(updates['preferences'])} preferences")+ # ------------------------------------------------------------------+ # Trace building+ # ------------------------------------------------------------------- if updates.get("weak_points"):- self._memory.append_to_section("weak_points", updates["weak_points"])- logger.debug(f"Added {len(updates['weak_points'])} weak points")+ def _build_trace_from_event(self, event: Event) -> Optional[TraceTree]:+ try:+ event_type = event.type.value if hasattr(event.type, "value") else str(event.type)+ if event_type == EventType.SOLVE_COMPLETE.value:+ return self._build_solve_trace(event)+ if event_type == EventType.QUESTION_COMPLETE.value:+ return self._build_question_trace(event)+ return None+ except Exception as exc:+ logger.warning("[MEM-WRITE] Failed to build trace from event: %s", exc)+ return None++ def _build_solve_trace(self, event: Event) -> Optional[TraceTree]:+ metadata = event.metadata or {}+ output_dir = metadata.get("output_dir")+ scratchpad_path: Optional[Path] = None++ if output_dir:+ scratchpad_path = Path(output_dir) / "scratchpad.json"+ else:+ path_service = get_path_service()+ candidates = [+ path_service.get_solve_task_dir(event.task_id) / "scratchpad.json",+ path_service.user_data_dir / "solve" / event.task_id / "scratchpad.json",+ ]+ scratchpad_path = next((p for p in candidates if p.exists()), None)++ if not scratchpad_path or not scratchpad_path.exists():+ logger.warning(+ "[MEM-WRITE] Scratchpad not found (output_dir=%s, task_id=%s)",+ output_dir, event.task_id,+ )+ return None++ scratchpad_payload = self._load_json(scratchpad_path)+ if not isinstance(scratchpad_payload, dict):+ logger.warning("[MEM-WRITE] Invalid scratchpad JSON at %s", scratchpad_path)+ return None++ answer_path = ""+ if output_dir:+ candidate = Path(output_dir) / "final_answer.md"+ if candidate.exists():+ answer_path = str(candidate)++ logger.info("[MEM-WRITE] Building solve trace from %s", scratchpad_path)+ return TraceTree.from_scratchpad(+ scratchpad_payload,+ task_id=event.task_id,+ answer_path=answer_path,+ )- if updates.get("milestones"):- self._memory.append_to_section("milestones", updates["milestones"])- logger.debug(f"Added {len(updates['milestones'])} milestones")+ def _build_question_trace(self, event: Event) -> Optional[TraceTree]:+ metadata = event.metadata or {}+ batch_dir = metadata.get("batch_dir")+ if not batch_dir:+ logger.warning("[MEM-WRITE] No batch_dir in question event metadata")+ return None- def _format_recent_notes(self) -> str:- """Format recent notes for context."""- if not self._memory:- return ""+ summary_path = Path(batch_dir) / "summary.json"+ if not summary_path.exists():+ logger.warning("[MEM-WRITE] Summary not found at %s", summary_path)+ return None- notes = self._memory.get_recent_notes(self.recent_days)- if not notes:- return ""+ summary_payload = self._load_json(summary_path)+ if not isinstance(summary_payload, dict):+ return None- parts = []- for date_str, content in notes.items():- # Truncate each note- summary = content[:300].replace("\n", " ")- if len(content) > 300:- summary += "..."- parts.append(f"[{date_str}]: {summary}")+ user_topic = str(metadata.get("user_topic", "") or "")+ if not user_topic:+ try:+ user_input_payload = json.loads(event.user_input)+ user_topic = str(user_input_payload.get("topic", "") or "")+ except Exception:+ user_topic = ""+ trace_id = Path(batch_dir).name or event.task_id++ answer_path = str(summary_path)+ return TraceTree.from_question_summary(+ summary=summary_payload,+ user_topic=user_topic,+ task_id=trace_id,+ include_answers=False,+ answer_path=answer_path,+ )- return "\n".join(parts)+ def _read_md(self, filename: str) -> str:+ """Read a markdown file from the memory directory, returning its content or a placeholder."""+ if not self._forest:+ return "(document not found)"+ p = self._forest.memory_dir / filename+ try:+ return p.read_text(encoding="utf-8").strip() or "(empty document)"+ except FileNotFoundError:+ return "(document not found)"- # =========================================================================- # Public Interface for Preference Access- # =========================================================================+ @staticmethod+ def _load_json(path: Path) -> Any:+ try:+ with open(path, "r", encoding="utf-8") as f:+ return json.load(f)+ except Exception:+ return None- def get_preference_for_prompt(self) -> str:- """- Get formatted preference context for prompt injection.+ # ------------------------------------------------------------------+ # Context builders for memory agents+ # ------------------------------------------------------------------- This method is called by agents (ResponseAgent, GenerateAgent) to get- user preferences for inclusion in prompts.+ def _build_session_summary(self, trace: TraceTree) -> str:+ """Build a concise structured summary from a trace tree.- Returns:- Formatted preference string, or empty string if no preferences.+ For solve traces: steps, rounds, tools, per-step goal+status.+ For question traces: per-question type/difficulty/result + totals."""- if not self._memory:- self._memory = get_learning_memory()+ if trace.trace_type == "solve":+ return self._build_solve_summary(trace)+ if trace.trace_type == "question":+ return self._build_question_summary(trace)+ return "(unknown trace type)"++ @staticmethod+ def _build_solve_summary(trace: TraceTree) -> str:+ 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)++ @staticmethod+ def _build_question_summary(trace: TraceTree) -> str:+ 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:+ result = str(answer_nodes[0].data.get("judged_result", "unknown"))+ if result.lower() in ("correct", "true"):+ correct += 1+ elif result.lower() in ("wrong", "incorrect", "false"):+ wrong += 1+ else:+ skipped += 1+ else:+ result = "no_answer"+ skipped += 1++ q_lines.append(f"- {tmpl.short_id} [{qtype}/{diff}] \"{conc}\" -> {result}")++ total = correct + wrong + skipped+ header = (+ f"Question summary: {total} questions | "+ f"correct {correct}, wrong {wrong}, skipped {skipped}"+ )+ return "\n".join([header] + q_lines)- return self._memory.get_preference_context(self.max_preference_length)+ def _build_full_context(self, trace: TraceTree) -> str:+ """Build the complete session content for the first ReAct round.- def get_full_context(self) -> str:+ For solve traces: full final_answer.md content.+ For question traces: full Q&A pairs from summary.json."""- Get full context including preferences and recent notes.+ if trace.trace_type == "solve":+ return self._build_solve_full_context(trace)+ if trace.trace_type == "question":+ return self._build_question_full_context(trace)+ return "(unknown trace type)"++ def _build_solve_full_context(self, trace: TraceTree) -> str:+ 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 "(final answer file is empty)"+ except Exception:+ return "(failed to read final answer)"++ def _build_question_full_context(self, trace: TraceTree) -> str:+ """Extract full Q&A content from summary.json, with user answers from trace."""+ summary_data = None+ if trace.answer_path:+ summary_data = self._load_json(Path(trace.answer_path))++ results = []+ if isinstance(summary_data, dict):+ results = list(summary_data.get("results", []) or [])++ if not results:+ return self._build_question_full_context_from_trace(trace)++ parts: list[str] = []+ templates = [n for n in trace.nodes.values() if n.node_type == "template"]+ tmpl_by_qid: dict[str, TraceNode] = {}+ for t in templates:+ qid = t.data.get("question_id", "")+ if qid:+ tmpl_by_qid[qid] = t++ 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)++ tmpl_node = tmpl_by_qid.get(qid)+ user_answer = ""+ judged = "no_answer"+ 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)++ @staticmethod+ def _build_question_full_context_from_trace(trace: TraceTree) -> str:+ """Fallback: build Q&A context directly from trace nodes."""+ templates = [n for n in trace.nodes.values() if n.node_type == "template"]+ if not templates:+ return "(no question data available)"++ parts: list[str] = []+ for idx, tmpl in enumerate(templates, 1):+ qtype = tmpl.data.get("question_type", "?")+ diff = tmpl.data.get("difficulty", "?")+ conc = tmpl.data.get("concentration", tmpl.text)++ block = [f"--- Question {idx} [{qtype}/{diff}] ---"]+ block.append(f"Topic: {conc}")++ for cid in tmpl.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")+ block.append(f"User answer: {user_answer or '(none)'}")+ block.append(f"Judged: {judged}")+ break++ parts.append("\n".join(block))+ return "\n\n".join(parts)++ # ------------------------------------------------------------------+ # Record user answer (question flow phase 2)+ # ------------------------------------------------------------------++ async def record_user_answer(+ self,+ trace_id: str,+ question_id: str,+ user_answer: str,+ judged_result: str,+ ) -> bool:+ """Append/update an L3 answer node after the user answers a question."""+ if not self._forest:+ self._forest = TraceForest()++ logger.info(+ "[MEM-WRITE] record_user_answer: trace=%s question=%s judged=%s",+ trace_id, question_id, judged_result,+ )++ tree = self._forest.load_tree(trace_id)+ if tree is None:+ logger.warning("record_user_answer: trace %s not found", trace_id)+ return False++ q_idx = question_id.replace("q_", "")+ tmpl_short = f"T{q_idx}" if q_idx.isdigit() else f"T{question_id}"+ template_node = tree.nodes.get(tmpl_short)+ if template_node is None:+ for node in tree.nodes.values():+ if node.node_type == "template" and node.data.get("question_id") == question_id:+ template_node = node+ tmpl_short = node.short_id+ break+ if template_node is None:+ logger.warning(+ "record_user_answer: template node for %s not found in trace %s",+ question_id, trace_id,+ )+ return False++ answer_short = f"{tmpl_short}.A1"+ answer_text = (user_answer or "").strip() or question_id++ answer_node = TraceNode(+ short_id=answer_short,+ level=3,+ text=answer_text,+ node_type="answer",+ data={+ "question_id": question_id,+ "user_answer": user_answer,+ "judged_result": judged_result,+ "question": template_node.data.get("concentration", ""),+ },+ parent=tmpl_short,+ )++ is_new = answer_short not in tree.nodes+ if is_new:+ template_node.children.append(answer_short)+ tree.nodes[answer_short] = answer_node- Returns:- Full context string for advanced personalization.+ try:+ await self._forest.register(tree)+ logger.info(+ "[MEM-WRITE] Answer node %s (%s) -> trace re-registered",+ "created" if is_new else "updated", answer_short,+ )+ except Exception as exc:+ logger.error("record_user_answer: failed to persist tree: %s", exc)+ return False++ return True++ async def flush_memory_agents(self, trace_id: str) -> None:+ """Run memory agents on a completed trace (e.g. after all answers recorded).++ Called explicitly by the caller (e.g. question CLI) once the full+ interaction is finished, so that agents see the complete trace."""- if not self._memory:- self._memory = get_learning_memory()+ if not self._forest:+ self._forest = TraceForest()++ tree = self._forest.load_tree(trace_id)+ if tree is None:+ logger.warning("[MEM-WRITE] flush_memory_agents: trace %s not found", trace_id)+ return- return self._memory.get_full_context(- recent_days=self.recent_days,- max_length=self.max_preference_length * 2,+ logger.info(+ "[MEM-WRITE] flush_memory_agents: running agents on trace %s (%d nodes)",+ trace_id, len(tree.nodes),)+ await self._run_memory_agents(tree)- def set_language(self, language: str) -> None:- """- Set the language for the service.+ # ------------------------------------------------------------------+ # Public interface (read path)+ # ------------------------------------------------------------------- Args:- language: Language code ('en' or 'zh')- """+ def get_memory_reader(self) -> MemoryReader:+ if not self._forest:+ self._forest = TraceForest()+ if not self._reader:+ self._reader = MemoryReader(forest=self._forest)+ return self._reader++ async def find_node(self, query: str, top_k: int = 3) -> list[dict[str, Any]]:+ if not self._forest:+ self._forest = TraceForest()+ results = await self._forest.semantic_search(query=query, top_k=top_k)+ return results++ def set_language(self, language: str) -> None:self._language = language- if self._agent:- self._agent.language = language+ for agent in (self._reflection_agent, self._summary_agent, self._weakness_agent):+ if agent:+ agent.language = language@classmethoddef reset(cls) -> None:- """Reset the singleton instance (for testing)."""if cls._instance is not None:cls._instance._running = Falsecls._instance = None@@ -301,12 +701,6 @@ _personalization_service: Optional[PersonalizationService] = Nonedef get_personalization_service() -> PersonalizationService:- """- Get the singleton PersonalizationService instance.-- Returns:- The global PersonalizationService instance.- """global _personalization_serviceif _personalization_service is None:_personalization_service = PersonalizationService()diff --git a/src/personalization/trace_forest.py b/src/personalization/trace_forest.pynew file mode 100644index 000000000..cf7c3d6ac--- /dev/null+++ b/src/personalization/trace_forest.py@@ -0,0 +1,310 @@+from __future__ import annotations++import json+import logging+import math+from pathlib import Path+from typing import Any++from src.services.embedding import get_embedding_client+from src.services.path_service import get_path_service++from .trace_tree import TraceNode, TraceTree++logger = logging.getLogger(__name__)+++class TraceForest:+ """Manage persisted trace trees, lean index, and embeddings.++ Public surface is intentionally kept thin — all query operations for+ memory agents are exposed via :class:`TraceToolkit` instead.+ """++ INDEX_FILE = "index.json"+ EMBEDDINGS_FILE = "embeddings.json"++ def __init__(self, memory_dir: Path | None = None) -> None:+ if memory_dir is None:+ memory_dir = get_path_service().get_memory_dir()+ self._traces_dir = memory_dir / "traces"+ self._traces_dir.mkdir(parents=True, exist_ok=True)+ self._memory_dir = memory_dir+ self._index_path = self._traces_dir / self.INDEX_FILE+ self._embeddings_path = self._traces_dir / self.EMBEDDINGS_FILE+ self._tree_cache: dict[str, TraceTree] = {}++ @property+ def traces_dir(self) -> Path:+ return self._traces_dir++ @property+ def memory_dir(self) -> Path:+ return self._memory_dir++ # ------------------------------------------------------------------+ # Registration (write path)+ # ------------------------------------------------------------------++ async def register(self, tree: TraceTree) -> None:+ """Persist one trace tree and update lean index + embeddings."""+ self._save_tree(tree)+ index = self._load_index()++ # Replace old trace metadata (idempotent)+ traces = [t for t in index["traces"] if t.get("trace_id") != tree.trace_id]+ traces.append({+ "trace_id": tree.trace_id,+ "trace_type": tree.trace_type,+ "timestamp": tree.timestamp,+ "root_text": tree.root.text,+ "answer_path": tree.answer_path,+ "tools_used": tree.tools_used,+ "stats": tree.stats,+ })+ index["traces"] = traces++ # Replace old node rows for this trace (lean: snippet instead of full text)+ nodes = [n for n in index["nodes"] if n.get("trace_id") != tree.trace_id]+ for node in tree.nodes.values():+ snippet = node.text[:80] + ("..." if len(node.text) > 80 else "")+ nodes.append({+ "full_id": node.full_id(tree.trace_id),+ "trace_id": tree.trace_id,+ "short_id": node.short_id,+ "level": node.level,+ "node_type": node.node_type,+ "action": node.action,+ "snippet": snippet,+ })+ index["nodes"] = nodes+ self._save_index(index)++ await self._update_embeddings(tree)++ # ------------------------------------------------------------------+ # Internal query helpers (used by TraceToolkit)+ # ------------------------------------------------------------------++ async def semantic_search(+ self,+ query: str,+ top_k: int = 5,+ level: int | None = None,+ trace_type: str | None = None,+ ) -> list[dict[str, Any]]:+ """Return top-K matching node rows from the lean index."""+ query = (query or "").strip()+ if not query:+ return []+ index = self._load_index()+ if not index["nodes"]:+ return []++ trace_type_set: set[str] | None = None+ if trace_type:+ trace_type_set = {+ r["trace_id"]+ for r in index["traces"]+ if r.get("trace_type") == trace_type+ }++ embeddings = self._load_embeddings()+ query_vec = await self._embed_query(query)++ scored: list[tuple[float, dict[str, Any]]] = []+ for row in index["nodes"]:+ if level is not None and int(row.get("level", 0)) != level:+ continue+ if trace_type_set is not None and row.get("trace_id") not in trace_type_set:+ continue+ full_id = str(row.get("full_id", ""))+ if not full_id:+ continue++ node_text = str(row.get("snippet", ""))+ node_vec = embeddings.get(full_id)+ score = self._node_score(query, query_vec, node_text, node_vec)+ if score > 0:+ scored.append((score, row))++ scored.sort(key=lambda x: x[0], reverse=True)+ results: list[dict[str, Any]] = []+ for _score, row in scored[:top_k]:+ tree = self.load_tree(str(row.get("trace_id", "")))+ short = str(row.get("short_id", ""))+ text = ""+ parent_short = None+ if tree and short in tree.nodes:+ node = tree.nodes[short]+ text = node.text+ parent_short = node.parent+ results.append({+ "trace_id": row.get("trace_id", ""),+ "short_id": short,+ "level": row.get("level", 0),+ "node_type": row.get("node_type", ""),+ "action": row.get("action", ""),+ "text": text or row.get("snippet", ""),+ "parent_short_id": parent_short,+ })+ return results++ def list_recent_traces(+ self,+ n: int = 10,+ trace_type: str | None = None,+ ) -> list[dict[str, Any]]:+ """Return the most recent *n* traces sorted by timestamp desc."""+ index = self._load_index()+ traces = index["traces"]+ if trace_type:+ traces = [t for t in traces if t.get("trace_type") == trace_type]+ traces.sort(key=lambda t: t.get("timestamp", ""), reverse=True)+ return traces[:n]++ # ------------------------------------------------------------------+ # Tree loading+ # ------------------------------------------------------------------++ def load_tree(self, trace_id: str) -> TraceTree | None:+ """Load a trace tree by its ID. Returns None if not found."""+ if trace_id in self._tree_cache:+ return self._tree_cache[trace_id]+ path = self._tree_path(trace_id)+ if not path.exists():+ return None+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ tree = TraceTree.from_dict(payload)+ self._tree_cache[trace_id] = tree+ return tree+ except Exception as exc:+ logger.warning("Failed loading trace %s: %s", trace_id, exc)+ return None++ def reload_tree(self, trace_id: str) -> TraceTree | None:+ """Force-reload a trace from disk, bypassing the in-memory cache.++ Used by the standalone personalization terminal after the main CLI+ has updated a trace (e.g. added answer nodes).+ """+ self._tree_cache.pop(trace_id, None)+ return self.load_tree(trace_id)++ # ------------------------------------------------------------------+ # Persistence helpers+ # ------------------------------------------------------------------++ def _tree_path(self, trace_id: str) -> Path:+ return self._traces_dir / f"{trace_id}.json"++ def _save_tree(self, tree: TraceTree) -> None:+ path = self._tree_path(tree.trace_id)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps(tree.to_dict(), ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ self._tree_cache[tree.trace_id] = tree++ def _load_index(self) -> dict[str, list[dict[str, Any]]]:+ if not self._index_path.exists():+ return {"traces": [], "nodes": []}+ try:+ payload = json.loads(self._index_path.read_text(encoding="utf-8"))+ return {+ "traces": list(payload.get("traces", []) or []),+ "nodes": list(payload.get("nodes", []) or []),+ }+ except Exception:+ return {"traces": [], "nodes": []}++ def _save_index(self, index: dict[str, Any]) -> None:+ self._index_path.write_text(+ json.dumps(index, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )++ def _load_embeddings(self) -> dict[str, list[float]]:+ if not self._embeddings_path.exists():+ return {}+ try:+ payload = json.loads(self._embeddings_path.read_text(encoding="utf-8"))+ return {+ str(k): [float(x) for x in v]+ for k, v in dict(payload).items()+ if isinstance(v, list)+ }+ except Exception:+ return {}++ def _save_embeddings(self, embeddings: dict[str, list[float]]) -> None:+ self._embeddings_path.write_text(+ json.dumps(embeddings, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )++ async def _update_embeddings(self, tree: TraceTree) -> None:+ existing = self._load_embeddings()+ to_embed_ids: list[str] = []+ to_embed_texts: list[str] = []+ for node in tree.nodes.values():+ full_id = node.full_id(tree.trace_id)+ if full_id in existing:+ continue+ if not node.text.strip():+ continue+ to_embed_ids.append(full_id)+ to_embed_texts.append(node.text)+ if not to_embed_ids:+ return+ try:+ vectors = await get_embedding_client().embed(to_embed_texts)+ for fid, vec in zip(to_embed_ids, vectors):+ existing[fid] = [float(x) for x in vec]+ self._save_embeddings(existing)+ except Exception as exc:+ logger.warning("Embedding update failed: %s", exc)++ async def _embed_query(self, query: str) -> list[float] | None:+ try:+ vectors = await get_embedding_client().embed([query])+ if vectors and vectors[0]:+ return [float(x) for x in vectors[0]]+ except Exception as exc:+ logger.debug("Query embedding failed: %s", exc)+ return None++ @staticmethod+ def _cosine(a: list[float], b: list[float]) -> float:+ if not a or not b or len(a) != len(b):+ return 0.0+ dot = sum(x * y for x, y in zip(a, b))+ na = math.sqrt(sum(x * x for x in a))+ nb = math.sqrt(sum(y * y for y in b))+ if na == 0 or nb == 0:+ return 0.0+ return dot / (na * nb)++ def _node_score(+ self,+ query: str,+ query_vec: list[float] | None,+ node_text: str,+ node_vec: list[float] | None,+ ) -> float:+ if query_vec is not None and node_vec is not None:+ sim = self._cosine(query_vec, node_vec)+ return max(0.0, sim)+ q = query.lower().strip()+ t = node_text.lower().strip()+ if not q or not t:+ return 0.0+ if q in t:+ return min(1.0, len(q) / max(1, len(t)))+ q_tokens = {x for x in q.split() if x}+ t_tokens = {x for x in t.split() if x}+ if not q_tokens or not t_tokens:+ return 0.0+ return len(q_tokens & t_tokens) / len(q_tokens)diff --git a/src/personalization/trace_tools.py b/src/personalization/trace_tools.pynew file mode 100644index 000000000..fa8bf6f6d--- /dev/null+++ b/src/personalization/trace_tools.py@@ -0,0 +1,245 @@+# -*- coding: utf-8 -*-+"""+Trace Toolkit+=============++Five tools for memory agents to explore the trace forest and manage+documents. Each tool is an async method on :class:`TraceToolkit`. The+:class:`ReActRunner` dispatches action strings to these methods.+"""+from __future__ import annotations++import json+import logging+from pathlib import Path+from typing import Any++from .trace_forest import TraceForest++logger = logging.getLogger(__name__)++TOOL_NAMES = frozenset({+ "search_traces",+ "list_traces",+ "get_trace_detail",+ "read_document",+ "write_document",+})+++class TraceToolkit:+ """Expose five tools for memory agents.++ Parameters+ ----------+ forest:+ The shared :class:`TraceForest` instance.+ memory_dir:+ Root directory for memory documents (``reflection.md``, etc.).+ Defaults to ``forest.memory_dir``.+ """++ def __init__(+ self,+ forest: TraceForest,+ memory_dir: Path | None = None,+ ) -> None:+ self._forest = forest+ self._memory_dir = memory_dir or forest.memory_dir++ # ------------------------------------------------------------------+ # Dispatcher+ # ------------------------------------------------------------------++ async def call(self, tool: str, params: dict[str, Any]) -> str:+ """Dispatch a tool call and return the observation string."""+ if tool not in TOOL_NAMES:+ return f"[error] Unknown tool: {tool}"+ try:+ handler = getattr(self, tool)+ return await handler(**params)+ except TypeError as exc:+ return f"[error] Bad parameters for {tool}: {exc}"+ except Exception as exc:+ logger.warning("Tool %s failed: %s", tool, exc, exc_info=True)+ return f"[error] {tool} failed: {exc}"++ # ------------------------------------------------------------------+ # Tool 1: search_traces+ # ------------------------------------------------------------------++ async def search_traces(+ self,+ query: str,+ trace_type: str | None = None,+ level: int | None = None,+ top_k: int = 5,+ ) -> str:+ """Semantic search across all historical trace nodes."""+ results = await self._forest.semantic_search(+ query=query,+ top_k=top_k,+ level=level,+ trace_type=trace_type,+ )+ if not results:+ return "(no matching nodes found)"+ lines: list[str] = []+ for r in results:+ action_tag = f" [{r['action']}]" if r.get("action") else ""+ parent_tag = f" parent={r['parent_short_id']}" if r.get("parent_short_id") else ""+ lines.append(+ f"- [{r['short_id']}] ({r['node_type']}{action_tag}) "+ f"trace={r['trace_id']}{parent_tag}\n"+ f" {r['text']}"+ )+ return "\n".join(lines)++ # ------------------------------------------------------------------+ # Tool 2: list_traces+ # ------------------------------------------------------------------++ async def list_traces(+ self,+ n: int = 10,+ trace_type: str | None = None,+ ) -> str:+ """List recent traces sorted by time (newest first)."""+ traces = self._forest.list_recent_traces(n=n, trace_type=trace_type)+ if not traces:+ return "(no traces found)"+ lines: list[str] = []+ for t in traces:+ ts = str(t.get("timestamp", ""))[:16].replace("T", " ")+ stats = t.get("stats", {})+ stats_str = ", ".join(f"{k}={v}" for k, v in stats.items()) if stats else ""+ tools = ", ".join(t.get("tools_used", [])) or "none"+ lines.append(+ f"- [{t['trace_id']}] {t.get('trace_type', '')} | {ts}\n"+ f" Question: {t.get('root_text', '')}\n"+ f" Answer: {t.get('answer_path', '(none)')}\n"+ f" Tools: {tools} | Stats: {stats_str}"+ )+ return "\n".join(lines)++ # ------------------------------------------------------------------+ # Tool 3: get_trace_detail+ # ------------------------------------------------------------------++ async def get_trace_detail(+ self,+ trace_id: str | None = None,+ short_id: str | None = None,+ ) -> str:+ """Load full trace outline *or* single node detail.++ * Pass only ``trace_id`` → compact text overview of the whole tree.+ * Pass ``trace_id`` + ``short_id`` → full detail of one node.+ """+ if not trace_id:+ return "[error] trace_id is required"++ tree = self._forest.load_tree(trace_id)+ if tree is None:+ return f"[error] trace {trace_id} not found"++ if not short_id:+ return tree.compact_text(max_chars=6000)++ node = tree.nodes.get(short_id)+ if node is None:+ return f"[error] node {short_id} not found in trace {trace_id}"++ parts: list[str] = [+ f"Node: [{node.short_id}] ({node.node_type}) in trace {trace_id}",+ ]+ if node.parent:+ parent_node = tree.nodes.get(node.parent)+ parent_text = parent_node.text[:80] if parent_node else "?"+ parts.append(f"Parent: [{node.parent}] {parent_text}")+ if node.children:+ parts.append(f"Children: {', '.join(f'[{c}]' for c in node.children)}")+ parts.append(f"Text: {node.text}")+ if node.action:+ parts.append(f"Action: {node.action}")++ data = node.data+ if data:+ for key in ("thought", "action_input", "self_note"):+ val = data.get(key, "")+ if val:+ parts.append(f"{key}: {val}")+ observation = data.get("observation", "")+ if observation:+ parts.append(f"observation: {observation[:1500]}")+ sources = data.get("sources", [])+ if sources:+ src_strs = []+ for s in sources[:5]:+ if isinstance(s, dict):+ src_strs.append(+ f"{s.get('type', '?')}:{s.get('file', s.get('value', '?'))}"+ )+ parts.append(f"sources: {', '.join(src_strs)}")++ for key in ("status", "step_goal", "difficulty", "concentration",+ "question_type", "judged_result", "question"):+ val = data.get(key, "")+ if val:+ parts.append(f"{key}: {val}")++ return "\n".join(parts)++ # ------------------------------------------------------------------+ # Tool 4: read_document+ # ------------------------------------------------------------------++ async def read_document(+ self,+ filename: str | None = None,+ path: str | None = None,+ ) -> str:+ """Read a .md file from memory directory or an absolute path."""+ if path:+ target = Path(path)+ elif filename:+ target = self._memory_dir / filename+ else:+ return "[error] filename or path is required"++ if not target.exists():+ return "(document not found)"+ try:+ content = target.read_text(encoding="utf-8")+ return content if content.strip() else "(document is empty)"+ except Exception as exc:+ return f"[error] Failed to read {target}: {exc}"++ # ------------------------------------------------------------------+ # Tool 5: write_document+ # ------------------------------------------------------------------++ async def write_document(+ self,+ filename: str,+ content: str,+ mode: str = "append",+ ) -> str:+ """Write or append to a .md file in the memory directory."""+ target = self._memory_dir / filename+ try:+ if mode == "overwrite":+ target.write_text(content, encoding="utf-8")+ else:+ existing = ""+ if target.exists():+ existing = target.read_text(encoding="utf-8")+ if existing.strip():+ new_content = existing.rstrip() + "\n\n" + content+ else:+ new_content = content+ target.write_text(new_content, encoding="utf-8")+ logger.info("[TOOL] write_document: %s (mode=%s)", filename, mode)+ return "ok"+ except Exception as exc:+ return f"[error] Failed to write {filename}: {exc}"diff --git a/src/personalization/trace_tree.py b/src/personalization/trace_tree.pynew file mode 100644index 000000000..7b993aaea--- /dev/null+++ b/src/personalization/trace_tree.py@@ -0,0 +1,519 @@+from __future__ import annotations++import re+from dataclasses import dataclass, field+from datetime import datetime+from typing import Any+++def _get(obj: Any, key: str, default: Any = None) -> Any:+ if isinstance(obj, dict):+ return obj.get(key, default)+ return getattr(obj, key, default)+++@dataclass+class TraceNode:+ """Node in the unified 3-level trace tree.++ Nodes use short IDs within a trace (e.g. ``S1``, ``S1.R1``).+ The full globally-unique ID is ``{trace_id}:{short_id}``.+ """++ short_id: str+ level: int+ text: str+ node_type: str+ action: str = ""+ data: dict[str, Any] = field(default_factory=dict)+ children: list[str] = field(default_factory=list)+ parent: str | None = None++ def full_id(self, trace_id: str) -> str:+ return f"{trace_id}:{self.short_id}"++ def to_dict(self) -> dict[str, Any]:+ result: dict[str, Any] = {+ "short_id": self.short_id,+ "level": self.level,+ "text": self.text,+ "node_type": self.node_type,+ "children": self.children,+ "parent": self.parent,+ }+ if self.action:+ result["action"] = self.action+ if self.data:+ result["data"] = self.data+ return result++ @classmethod+ def from_dict(cls, payload: dict[str, Any]) -> "TraceNode":+ short_id = str(payload.get("short_id", "") or payload.get("node_id", ""))+ return cls(+ short_id=short_id,+ level=int(payload.get("level", 0)),+ text=str(payload.get("text", "")),+ node_type=str(payload.get("node_type", "")),+ action=str(payload.get("action", "") or ""),+ data=dict(payload.get("data", {}) or {}),+ children=list(payload.get("children", []) or []),+ parent=payload.get("parent"),+ )+++@dataclass+class TraceTree:+ """Unified trace tree for solve and question workflows.++ Nodes are keyed by ``short_id`` in the ``nodes`` dict.+ """++ trace_id: str+ trace_type: str+ timestamp: str+ root_id: str+ nodes: dict[str, TraceNode]+ answer_path: str = ""+ tools_used: list[str] = field(default_factory=list)+ stats: dict[str, int] = field(default_factory=dict)++ @property+ def root(self) -> TraceNode:+ return self.nodes[self.root_id]++ def to_dict(self) -> dict[str, Any]:+ return {+ "trace_id": self.trace_id,+ "trace_type": self.trace_type,+ "timestamp": self.timestamp,+ "root_id": self.root_id,+ "answer_path": self.answer_path,+ "tools_used": self.tools_used,+ "stats": self.stats,+ "nodes": {k: v.to_dict() for k, v in self.nodes.items()},+ }++ # ------------------------------------------------------------------+ # Deserialization+ # ------------------------------------------------------------------++ @classmethod+ def from_dict(cls, payload: dict[str, Any]) -> "TraceTree":+ """Deserialize a trace tree from its JSON representation.++ Automatically detects and migrates the old format (``node_id``+ based keys, ``root`` object) to the new short-ID format.+ """+ if _is_old_format(payload):+ return cls._migrate_old(payload)++ nodes_payload = payload.get("nodes", {}) or {}+ nodes = {k: TraceNode.from_dict(v) for k, v in nodes_payload.items()}+ root_id = str(payload.get("root_id", "L1"))+ if root_id not in nodes and nodes:+ root_id = next(iter(nodes))+ return cls(+ trace_id=str(payload.get("trace_id", "")),+ trace_type=str(payload.get("trace_type", "")),+ timestamp=str(payload.get("timestamp", datetime.now().isoformat())),+ root_id=root_id,+ nodes=nodes,+ answer_path=str(payload.get("answer_path", "") or ""),+ tools_used=list(payload.get("tools_used", []) or []),+ stats=dict(payload.get("stats", {}) or {}),+ )++ @classmethod+ def _migrate_old(cls, payload: dict[str, Any]) -> "TraceTree":+ """Convert old format (verbose node_ids) to new short-ID format."""+ trace_id = str(payload.get("trace_id", ""))+ old_nodes = payload.get("nodes", {}) or {}++ old_to_new: dict[str, str] = {}+ for old_key in old_nodes:+ old_to_new[old_key] = _old_id_to_short(old_key, trace_id)++ old_root_payload = payload.get("root", {})+ old_root_id = str(old_root_payload.get("node_id", "")) if old_root_payload else ""+ if not old_root_id and old_nodes:+ old_root_id = next(iter(old_nodes))++ nodes: dict[str, TraceNode] = {}+ tools_seen: set[str] = set()+ step_count = 0+ round_count = 0++ for old_key, old_node_data in old_nodes.items():+ short = old_to_new[old_key]+ action = str(old_node_data.get("data", {}).get("action", "") or "")+ node = TraceNode(+ short_id=short,+ level=int(old_node_data.get("level", 0)),+ text=str(old_node_data.get("text", "")),+ node_type=str(old_node_data.get("node_type", "")),+ action=action,+ data=dict(old_node_data.get("data", {}) or {}),+ children=[old_to_new.get(c, c) for c in (old_node_data.get("children") or [])],+ parent=old_to_new.get(old_node_data.get("parent", ""), old_node_data.get("parent")),+ )+ nodes[short] = node+ if node.level == 2:+ step_count += 1+ elif node.level == 3:+ round_count += 1+ if action and action not in ("done", "replan", ""):+ tools_seen.add(action)++ root_id = old_to_new.get(old_root_id, "L1")+ return cls(+ trace_id=trace_id,+ trace_type=str(payload.get("trace_type", "")),+ timestamp=str(payload.get("timestamp", "")),+ root_id=root_id,+ nodes=nodes,+ answer_path=str(payload.get("answer_path", "") or ""),+ tools_used=sorted(tools_seen) or list(payload.get("tools_used", []) or []),+ stats=payload.get("stats") or {"steps": step_count, "rounds": round_count},+ )++ # ------------------------------------------------------------------+ # Factory: Solve workflow+ # ------------------------------------------------------------------++ @classmethod+ def from_scratchpad(+ cls,+ scratchpad: Any,+ task_id: str,+ answer_path: str = "",+ ) -> "TraceTree":+ """Build a solve trace tree from Scratchpad-like data.++ Structure::++ L1 (question)+ ├─ S1 (step)+ │ ├─ S1.R1 (round)+ │ └─ S1.R2 (round)+ └─ S2 (step)+ └─ S2.R1 (round)+ """+ ts = datetime.now().isoformat()+ trace_id = task_id or f"solve_{datetime.now().strftime('%Y%m%d_%H%M%S')}"+ question = str(_get(scratchpad, "question", "") or "")++ root = TraceNode(+ short_id="L1",+ level=1,+ text=question,+ node_type="question",+ data={"question": question},+ )+ nodes: dict[str, TraceNode] = {"L1": root}++ plan = _get(scratchpad, "plan", None)+ raw_steps = _get(plan, "steps", []) if plan is not None else []+ entries = list(_get(scratchpad, "entries", []) or [])++ tools_seen: set[str] = set()+ round_total = 0++ for step_idx, step in enumerate(raw_steps, 1):+ step_id_raw = str(_get(step, "id", f"S{step_idx}"))+ step_short = f"S{step_idx}"+ step_goal = str(_get(step, "goal", "") or "")+ step_status = str(_get(step, "status", "pending"))+ tools_hint = list(_get(step, "tools_hint", []) or [])++ step_node = TraceNode(+ short_id=step_short,+ level=2,+ text=step_goal or step_short,+ node_type="step",+ data={+ "step_id": step_id_raw,+ "step_goal": step_goal,+ "status": step_status,+ "tools_hint": tools_hint,+ },+ parent="L1",+ )+ root.children.append(step_short)+ nodes[step_short] = step_node++ step_entries = [+ e for e in entries if str(_get(e, "step_id", "")) == step_id_raw+ ]+ step_entries.sort(key=lambda e: int(_get(e, "round", 0)))++ for round_idx, entry in enumerate(step_entries, 1):+ round_total += 1+ thought = str(_get(entry, "thought", "") or "")+ action = str(_get(entry, "action", "") or "")+ action_input = str(_get(entry, "action_input", "") or "")+ observation = str(_get(entry, "observation", "") or "")+ self_note = str(_get(entry, "self_note", "") or "")+ timestamp = str(_get(entry, "timestamp", "") or "")+ sources = _get(entry, "sources", []) or []++ round_short = f"{step_short}.R{round_idx}"+ round_text = self_note or thought or observation[:200]++ round_node = TraceNode(+ short_id=round_short,+ level=3,+ text=round_text,+ node_type="round",+ action=action,+ data={+ "step_id": step_id_raw,+ "round": int(_get(entry, "round", round_idx)),+ "thought": thought,+ "action_input": action_input,+ "observation": observation,+ "self_note": self_note,+ "timestamp": timestamp,+ "sources": [+ s.to_dict() if hasattr(s, "to_dict") else dict(s) if isinstance(s, dict) else {"value": str(s)}+ for s in sources+ ],+ },+ parent=step_short,+ )+ step_node.children.append(round_short)+ nodes[round_short] = round_node++ if action and action not in ("done", "replan"):+ tools_seen.add(action)++ return cls(+ trace_id=trace_id,+ trace_type="solve",+ timestamp=ts,+ root_id="L1",+ nodes=nodes,+ answer_path=answer_path,+ tools_used=sorted(tools_seen),+ stats={"steps": len(raw_steps), "rounds": round_total},+ )++ # ------------------------------------------------------------------+ # Factory: Question workflow+ # ------------------------------------------------------------------++ @classmethod+ def from_question_summary(+ cls,+ summary: dict[str, Any],+ user_topic: str,+ task_id: str,+ include_answers: bool = True,+ answer_path: str = "",+ ) -> "TraceTree":+ """Build a question trace tree from summary.json-like data.++ Structure::++ L1 (topic)+ ├─ T1 (template)+ │ └─ T1.A1 (answer)+ └─ T2 (template)+ └─ T2.A1 (answer)+ """+ ts = datetime.now().isoformat()+ trace_id = task_id or f"question_{datetime.now().strftime('%Y%m%d_%H%M%S')}"+ root_text = (user_topic or "").strip() or str(summary.get("source", "question"))++ root = TraceNode(+ short_id="L1",+ level=1,+ text=root_text,+ node_type="topic",+ data={"topic": root_text, "source": summary.get("source", "topic")},+ )+ nodes: dict[str, TraceNode] = {"L1": root}++ results = list(summary.get("results", []) or [])+ answer_count = 0++ for idx, result in enumerate(results, 1):+ template = result.get("template", {}) or {}+ qa_pair = result.get("qa_pair", {}) or {}++ question_id = str(+ template.get("question_id") or qa_pair.get("question_id") or f"q_{idx}"+ )+ concentration = str(template.get("concentration", "") or "")+ question_type = str(+ template.get("question_type") or qa_pair.get("question_type") or "written"+ )+ difficulty = str(+ template.get("difficulty") or qa_pair.get("difficulty") or "medium"+ )++ tmpl_short = f"T{idx}"+ template_node = TraceNode(+ short_id=tmpl_short,+ level=2,+ text=concentration or question_id,+ node_type="template",+ data={+ "question_id": question_id,+ "concentration": concentration,+ "question_type": question_type,+ "difficulty": difficulty,+ "template": template,+ },+ parent="L1",+ )+ root.children.append(tmpl_short)+ nodes[tmpl_short] = template_node++ if not include_answers:+ continue++ user_answer = qa_pair.get("user_answer")+ judged = qa_pair.get("judged_result")+ answer_text = ""+ if isinstance(user_answer, str):+ answer_text = user_answer+ elif user_answer is not None:+ answer_text = str(user_answer)+ elif isinstance(qa_pair.get("answer"), str):+ answer_text = qa_pair.get("answer", "")++ leaf_text = answer_text or str(qa_pair.get("question", ""))[:200] or concentration+ answer_short = f"{tmpl_short}.A1"+ answer_count += 1+ answer_node = TraceNode(+ short_id=answer_short,+ level=3,+ text=leaf_text,+ node_type="answer",+ data={+ "question_id": question_id,+ "question": qa_pair.get("question", ""),+ "user_answer": user_answer,+ "judged_result": judged,+ "correct_answer": qa_pair.get("correct_answer", ""),+ "explanation": qa_pair.get("explanation", ""),+ "validation": qa_pair.get("validation", {}),+ "success": bool(result.get("success", False)),+ },+ parent=tmpl_short,+ )+ template_node.children.append(answer_short)+ nodes[answer_short] = answer_node++ return cls(+ trace_id=trace_id,+ trace_type="question",+ timestamp=ts,+ root_id="L1",+ nodes=nodes,+ answer_path=answer_path,+ tools_used=[],+ stats={"templates": len(results), "answers": answer_count},+ )++ # ------------------------------------------------------------------+ # Compact text for LLM consumption+ # ------------------------------------------------------------------++ def compact_text(self, max_chars: int = 8000) -> str:+ """Build compact readable text with short IDs for LLM analysis."""+ ts_short = self.timestamp[:16].replace("T", " ") if self.timestamp else ""+ lines: list[str] = [+ f"[{self.trace_id}] {self.trace_type} | {ts_short}",+ f"Question: {self.root.text}",+ ]+ if self.answer_path:+ lines.append(f"Answer: {self.answer_path}")+ lines.append("")++ def _render(node_id: str, depth: int) -> None:+ node = self.nodes.get(node_id)+ if node is None:+ return+ indent = " " * max(0, depth)+ if node.level == 2:+ status = node.data.get("status", "")+ status_tag = f" ({status})" if status else ""+ lines.append(+ f"{indent}[{node.short_id}] {node.node_type}{status_tag}: {node.text}"+ )+ elif node.level == 3:+ action_tag = node.action or node.node_type+ lines.append(+ f"{indent}[{node.short_id}] {action_tag} -> {node.text}"+ )+ else:+ lines.append(+ f"{indent}[{node.short_id}] ({node.node_type}) {node.text}"+ )+ for child_id in node.children:+ _render(child_id, depth + 1)++ for child_id in self.root.children:+ _render(child_id, 0)++ text = "\n".join(lines)+ if len(text) > max_chars:+ return text[: max_chars - 3] + "..."+ return text+++# ======================================================================+# Old-format detection & migration helpers+# ======================================================================++def _is_old_format(payload: dict[str, Any]) -> bool:+ """Detect old trace format (has ``root`` object or verbose node_id keys)."""+ if "root" in payload and isinstance(payload["root"], dict):+ return True+ nodes = payload.get("nodes", {})+ if isinstance(nodes, dict) and nodes:+ first_key = next(iter(nodes))+ if ":" in first_key and ("L1:" in first_key or "L2:" in first_key or "L3:" in first_key):+ return True+ return False+++_STEP_RE = re.compile(r":L2:(?:step|template):(\w+)$")+_ROUND_RE = re.compile(r":L3:(?:round|answer):(\w+)")+++def _old_id_to_short(old_id: str, trace_id: str) -> str:+ """Convert a verbose old-format node_id to a short_id."""+ suffix = old_id+ if trace_id and old_id.startswith(trace_id + ":"):+ suffix = old_id[len(trace_id) + 1:]++ if suffix.startswith("L1:"):+ return "L1"++ m_step = _STEP_RE.search(old_id)+ if m_step and ":L2:step:" in old_id:+ raw = m_step.group(1)+ return raw if raw.startswith("S") else f"S{raw}"+ if m_step and ":L2:template:" in old_id:+ raw = m_step.group(1)+ idx = raw.replace("q_", "")+ return f"T{idx}" if idx.isdigit() else f"T{raw}"++ m_round = _ROUND_RE.search(old_id)+ if m_round and ":L3:round:" in old_id:+ parts = suffix.split(":")+ step_raw = parts[2] if len(parts) > 2 else "S1"+ step_short = step_raw if step_raw.startswith("S") else f"S{step_raw}"+ round_idx = parts[-1] if len(parts) > 4 else "1"+ return f"{step_short}.R{round_idx}"+ if m_round and ":L3:answer:" in old_id:+ parts = suffix.split(":")+ q_raw = parts[2] if len(parts) > 2 else "1"+ idx = q_raw.replace("q_", "")+ tmpl_short = f"T{idx}" if idx.isdigit() else f"T{q_raw}"+ return f"{tmpl_short}.A1"++ return suffixdiff --git a/src/services/embedding/adapters/openai_compatible.py b/src/services/embedding/adapters/openai_compatible.pyindex 345ca423f..ee31e673a 100644--- a/src/services/embedding/adapters/openai_compatible.py+++ b/src/services/embedding/adapters/openai_compatible.py@@ -1,6 +1,7 @@# -*- coding: utf-8 -*-"""OpenAI-compatible embedding adapter for OpenAI, Azure, HuggingFace, LM Studio, etc."""+import jsonimport loggingfrom typing import Any, Dict@@ -18,6 +19,76 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):"text-embedding-ada-002": 1536,}+ @staticmethod+ def _extract_embeddings_from_response(data: Any) -> list[list[float]]:+ """+ Extract embeddings from different OpenAI-compatible response schemas.++ Supported shapes include:+ - {"data": [{"embedding": [...]}, ...]}+ - {"embeddings": [[...], ...]}+ - {"result": {"data": [{"embedding": [...]}, ...]}}+ - {"output": {"embeddings": [[...], ...]}}+ """+ if not isinstance(data, dict):+ raise ValueError(f"Embedding response is not a JSON object: type={type(data).__name__}")++ # Some providers return HTTP 200 with {"error": ...} payload.+ if "error" in data:+ err = data.get("error")+ if isinstance(err, dict):+ msg = (+ err.get("message")+ or err.get("msg")+ or err.get("detail")+ or json.dumps(err, ensure_ascii=False)+ )+ code = err.get("code")+ etype = err.get("type")+ raise ValueError(+ f"Embedding provider returned error payload: "+ f"message={msg}, code={code}, type={etype}"+ )+ raise ValueError(f"Embedding provider returned error payload: {err}")++ candidates = []+ # Standard OpenAI schema+ if isinstance(data.get("data"), list):+ candidates.append(data["data"])+ # Common proxy schema+ if isinstance(data.get("embeddings"), list):+ candidates.append(data["embeddings"])+ # Nested result/output variants+ result = data.get("result")+ if isinstance(result, dict):+ if isinstance(result.get("data"), list):+ candidates.append(result["data"])+ if isinstance(result.get("embeddings"), list):+ candidates.append(result["embeddings"])+ output = data.get("output")+ if isinstance(output, dict):+ if isinstance(output.get("data"), list):+ candidates.append(output["data"])+ if isinstance(output.get("embeddings"), list):+ candidates.append(output["embeddings"])++ for c in candidates:+ if not c:+ continue+ first = c[0]+ # list of {"embedding":[...]}+ if isinstance(first, dict) and "embedding" in first:+ return [item.get("embedding", []) for item in c if isinstance(item, dict)]+ # list of vectors [[...], ...]+ if isinstance(first, list):+ return [item for item in c if isinstance(item, list)]++ keys = sorted(list(data.keys()))+ raise ValueError(+ "Cannot parse embeddings from response JSON. "+ f"Top-level keys={keys}, expected one of: data/embeddings/result/output."+ )+async def embed(self, request: EmbeddingRequest) -> EmbeddingResponse:headers = {"Content-Type": "application/json",@@ -54,27 +125,32 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):response.raise_for_status()data = response.json()- embeddings = [item["embedding"] for item in data["data"]]+ embeddings = self._extract_embeddings_from_response(data)+ if not embeddings:+ raise ValueError("Embedding response parsed successfully but no vectors were found.")actual_dims = len(embeddings[0]) if embeddings else 0expected_dims = request.dimensions or self.dimensions+ model_name = data.get("model") if isinstance(data, dict) else None+ if not model_name:+ model_name = request.model or self.modelif expected_dims and actual_dims != expected_dims:logger.warning(f"Dimension mismatch: expected {expected_dims}, got {actual_dims}. "- f"Model '{data['model']}' may not support custom dimensions."+ f"Model '{model_name}' may not support custom dimensions.")logger.info(f"Successfully generated {len(embeddings)} embeddings "- f"(model: {data['model']}, dimensions: {actual_dims})"+ f"(model: {model_name}, dimensions: {actual_dims})")return EmbeddingResponse(embeddings=embeddings,- model=data["model"],+ model=model_name,dimensions=actual_dims,- usage=data.get("usage", {}),+ usage=data.get("usage", {}) if isinstance(data, dict) else {},)def get_model_info(self) -> Dict[str, Any]:diff --git a/src/services/embedding/client.py b/src/services/embedding/client.pyindex e42383ef7..f085cbe1c 100644--- a/src/services/embedding/client.py+++ b/src/services/embedding/client.py@@ -68,23 +68,30 @@ class EmbeddingClient:Returns:List of embedding vectors"""- adapter = self.manager.get_active_adapter()+ if not texts:+ return []- request = EmbeddingRequest(- texts=texts,- model=self.config.model,- dimensions=self.config.dim,- input_type=self.config.input_type, # Pass input_type for task-aware embeddings- )+ adapter = self.manager.get_active_adapter()+ batch_size = max(1, getattr(self.config, "batch_size", 10))+ all_embeddings: List[List[float]] = []try:- response = await adapter.embed(request)+ for start in range(0, len(texts), batch_size):+ batch = texts[start : start + batch_size]+ request = EmbeddingRequest(+ texts=batch,+ model=self.config.model,+ dimensions=self.config.dim,+ input_type=self.config.input_type, # Pass input_type for task-aware embeddings+ )+ response = await adapter.embed(request)+ all_embeddings.extend(response.embeddings)self.logger.debug(- f"Generated {len(response.embeddings)} embeddings using {self.config.binding}"+ f"Generated {len(all_embeddings)} embeddings using "+ f"{self.config.binding} (batch_size={batch_size})")-- return response.embeddings+ return all_embeddingsexcept Exception as e:self.logger.error(f"Embedding request failed: {e}")raisediff --git a/src/services/embedding/config.py b/src/services/embedding/config.pyindex d337cbcdc..63303b01a 100644--- a/src/services/embedding/config.py+++ b/src/services/embedding/config.py@@ -35,6 +35,7 @@ class EmbeddingConfig:dim: int = 3072max_tokens: int = 8192request_timeout: int = 30+ batch_size: int = 10input_type: Optional[str] = None # For task-aware embeddings (Cohere, Jina)# Optional provider-specific settings@@ -93,6 +94,7 @@ def get_embedding_config() -> EmbeddingConfig:base_url=config.get("base_url"),api_version=config.get("api_version"),dim=config.get("dimensions", 3072),+ batch_size=config.get("batch_size", 10),)except ImportError:# Unified config service not yet available, fall back to env@@ -132,6 +134,7 @@ def get_embedding_config() -> EmbeddingConfig:dim = _to_int(dim_str, 3072)max_tokens = _to_int(_strip_value(os.getenv("EMBEDDING_MAX_TOKENS")), 8192)request_timeout = _to_int(_strip_value(os.getenv("EMBEDDING_REQUEST_TIMEOUT")), 30)+ batch_size = _to_int(_strip_value(os.getenv("EMBEDDING_BATCH_SIZE")), 10)input_type = _strip_value(os.getenv("EMBEDDING_INPUT_TYPE")) # Optional# Provider-specific optional settings@@ -149,6 +152,7 @@ def get_embedding_config() -> EmbeddingConfig:dim=dim,max_tokens=max_tokens,request_timeout=request_timeout,+ batch_size=max(1, batch_size),input_type=input_type,encoding_format=encoding_format,normalized=normalized,diff --git a/src/services/llm/__init__.py b/src/services/llm/__init__.pyindex 4e5be6038..3100a6895 100644--- a/src/services/llm/__init__.py+++ b/src/services/llm/__init__.py@@ -155,12 +155,10 @@ __all__ = [def __getattr__(name: str):"""Lazy import for provider modules that depend on heavy libraries."""- if name == "cloud_provider":- from . import cloud_provider+ from importlib import import_module- return cloud_provider+ if name == "cloud_provider":+ return import_module("src.services.llm.cloud_provider")if name == "local_provider":- from . import local_provider-- return local_provider+ return import_module("src.services.llm.local_provider")raise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/src/services/llm/capabilities.py b/src/services/llm/capabilities.pyindex 0bdb0d497..4bdbf6e85 100644--- a/src/services/llm/capabilities.py+++ b/src/services/llm/capabilities.py@@ -151,16 +151,12 @@ MODEL_OVERRIDES: dict[str, dict[str, object]] = {# QwQ is Qwen's reasoning model with thinking tags"has_thinking_tags": True,},- # Claude models through OpenRouter or other providers- "claude": {- "supports_response_format": False,- "system_in_messages": False,- },- # Anthropic models- "anthropic/": {- "supports_response_format": False,- "system_in_messages": False,- },+ # NOTE: supports_response_format and system_in_messages are binding-level+ # capabilities, NOT model-level. When using OpenRouter or other OpenAI-compatible+ # proxies (binding="openai"), they handle response_format translation and expect+ # system prompts in messages. The native Anthropic limitations are already+ # handled by PROVIDER_CAPABILITIES["anthropic"] / ["claude"] above.+ # Only model-intrinsic capabilities (like has_thinking_tags) belong here.# Reasoning models - only support temperature=1.0# See: https://github.com/HKUDS/DeepTutor/issues/141"gpt-5": {diff --git a/src/services/llm/client.py b/src/services/llm/client.pyindex 60b529dfa..c56658331 100644--- a/src/services/llm/client.py+++ b/src/services/llm/client.py@@ -242,51 +242,72 @@ class LLMClient:messages: list[dict[str, object]] | None = None,**kwargs: object,) -> object:- # Handle multimodal messages+ # openai_complete_if_cache builds its own messages array internally+ # from (system_prompt, history_messages, prompt) and passes **kwargs+ # through to chat.completions.create(). Passing 'messages' in kwargs+ # causes "multiple values for keyword argument 'messages'".+ # Solution: pass multimodal content via the 'prompt' parameter.++ # Handle multimodal messages (pre-built message array from RAG-Anything)if messages:+ # Extract content from the user message to pass as prompt+ user_content = None+ sys_content = None+ for msg in messages:+ if msg["role"] == "user":+ user_content = msg["content"]+ elif msg["role"] == "system":+ sys_content = msg["content"]+clean_kwargs = {k: vfor k, v in kwargs.items()if k not in ["messages", "prompt", "system_prompt", "history_messages"]}lightrag_kwargs = {- "messages": messages,+ "system_prompt": sys_content,+ "history_messages": [],"api_key": self.config.api_key,"base_url": self.config.base_url,**clean_kwargs,}if api_version:lightrag_kwargs["api_version"] = api_version+return openai_complete_if_cache(self.config.model,- prompt="",+ prompt=user_content, # Pass multimodal content list as prompt**lightrag_kwargs,)- # Handle image data+ # Handle image data (base64 encoded)if image_data:- # Build image message- image_message = {- "role": "user",- "content": [- {"type": "text", "text": prompt},- {- "type": "image_url",- "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},- },- ],+ # Build multimodal content list+ multimodal_content = [+ {"type": "text", "text": prompt},+ {+ "type": "image_url",+ "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},+ },+ ]+ clean_kwargs = {+ k: v+ for k, v in kwargs.items()+ if k not in ["messages", "prompt", "system_prompt", "history_messages"]}lightrag_kwargs = {- "messages": [image_message],+ "system_prompt": None,+ "history_messages": [],"api_key": self.config.api_key,"base_url": self.config.base_url,- **kwargs,+ **clean_kwargs,}if api_version:lightrag_kwargs["api_version"] = api_version+return openai_complete_if_cache(self.config.model,- prompt="",+ prompt=multimodal_content,**lightrag_kwargs,)diff --git a/src/services/llm/cloud_provider.py b/src/services/llm/cloud_provider.pyindex e6fb8dc9f..72a4e7040 100644--- a/src/services/llm/cloud_provider.py+++ b/src/services/llm/cloud_provider.py@@ -302,47 +302,46 @@ async def _openai_complete(if not supports_response_format(binding, model):kwargs.pop("response_format", None)+ messages = kwargs.pop("messages", None)+content = None- try:- # Try using lightrag's openai_complete_if_cache first (has caching)- # Only pass api_version if it's set (for Azure OpenAI)- # Standard OpenAI SDK doesn't accept api_version parameter- history_messages: list[dict[str, str]] = []- lightrag_kwargs: dict[str, object] = dict(kwargs)- lightrag_kwargs.pop("system_prompt", None)- lightrag_kwargs.pop("history_messages", None)- lightrag_kwargs.pop("api_key", None)- lightrag_kwargs.pop("base_url", None)- lightrag_kwargs.pop("api_version", None)-- # Suppress lightrag's and openai's internal error logging during the call- # (errors are handled by our fallback mechanism)- original_lightrag_level = _lightrag_logger.level- original_openai_level = _openai_logger.level- _lightrag_logger.setLevel(logging.CRITICAL)- _openai_logger.setLevel(logging.CRITICAL)+ # When pre-built messages are provided, skip lightrag (it expects prompt+history, not messages)+ # and use direct aiohttp call. Otherwise try lightrag first for caching.+ if not messages:try:- # model and prompt must be positional arguments- if api_version:- lightrag_kwargs["api_version"] = api_version-- openai_complete_if_cache = _get_openai_complete_if_cache()- content = await openai_complete_if_cache(- model,- prompt,- system_prompt=system_prompt,- history_messages=history_messages,- api_key=api_key,- base_url=base_url,- **lightrag_kwargs,- )- finally:- _lightrag_logger.setLevel(original_lightrag_level)- _openai_logger.setLevel(original_openai_level)- except Exception as exc:- # Skip cache failures and fall back to direct aiohttp call- logger.debug("Exception occurred: %s", exc)- # Fallback: Direct aiohttp call+ history_messages: list[dict[str, str]] = []+ lightrag_kwargs: dict[str, object] = dict(kwargs)+ lightrag_kwargs.pop("system_prompt", None)+ lightrag_kwargs.pop("history_messages", None)+ lightrag_kwargs.pop("api_key", None)+ lightrag_kwargs.pop("base_url", None)+ lightrag_kwargs.pop("api_version", None)++ original_lightrag_level = _lightrag_logger.level+ original_openai_level = _openai_logger.level+ _lightrag_logger.setLevel(logging.CRITICAL)+ _openai_logger.setLevel(logging.CRITICAL)+ try:+ if api_version:+ lightrag_kwargs["api_version"] = api_version++ openai_complete_if_cache = _get_openai_complete_if_cache()+ content = await openai_complete_if_cache(+ model,+ prompt,+ system_prompt=system_prompt,+ history_messages=history_messages,+ api_key=api_key,+ base_url=base_url,+ **lightrag_kwargs,+ )+ finally:+ _lightrag_logger.setLevel(original_lightrag_level)+ _openai_logger.setLevel(original_openai_level)+ except Exception as exc:+ logger.debug("Exception occurred: %s", exc)++ # Direct aiohttp call (used when messages provided, or as fallback)if not content:effective_base = base_url or "https://api.openai.com/v1"url = build_chat_url(effective_base, api_version, binding)@@ -350,6 +349,15 @@ async def _openai_complete(# Build headers using unified utilityheaders = build_auth_headers(api_key, binding)+ # Use pre-built messages when provided; otherwise build from prompt/system_prompt+ if messages:+ msg_list = messages+ else:+ msg_list = [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": prompt},+ ]+temperature = get_effective_temperature(binding,model,@@ -357,10 +365,7 @@ async def _openai_complete()data: dict[str, object] = {"model": model,- "messages": [- {"role": "system", "content": system_prompt},- {"role": "user", "content": prompt},- ],+ "messages": msg_list,"temperature": temperature,}@@ -380,7 +385,7 @@ async def _openai_complete(timeout = aiohttp.ClientTimeout(total=120)connector = _get_aiohttp_connector()- async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:+ async with aiohttp.ClientSession(timeout=timeout, connector=connector, trust_env=True) as session:try:async with session.post(url, headers=headers, json=data) as resp:if resp.status == 200:@@ -491,7 +496,7 @@ async def _openai_stream(timeout = aiohttp.ClientTimeout(total=300)connector = _get_aiohttp_connector()- async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:+ async with aiohttp.ClientSession(timeout=timeout, connector=connector, trust_env=True) as session:async with session.post(url, headers=headers, json=data) as resp:if resp.status != 200:error_text = await resp.text()@@ -619,7 +624,7 @@ async def _anthropic_complete(timeout = aiohttp.ClientTimeout(total=120)connector = _get_aiohttp_connector()- async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:+ async with aiohttp.ClientSession(timeout=timeout, connector=connector, trust_env=True) as session:async with session.post(url, headers=headers, json=data) as response:if response.status != 200:error_text = await response.text()@@ -694,7 +699,7 @@ async def _anthropic_stream(timeout = aiohttp.ClientTimeout(total=300)connector = _get_aiohttp_connector()- async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:+ async with aiohttp.ClientSession(timeout=timeout, connector=connector, trust_env=True) as session:async with session.post(url, headers=headers, json=data) as response:if response.status != 200:error_text = await response.text()@@ -760,7 +765,7 @@ async def _cohere_complete(timeout = aiohttp.ClientTimeout(total=120)connector = _get_aiohttp_connector()- async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:+ async with aiohttp.ClientSession(timeout=timeout, connector=connector, trust_env=True) as session:async with session.post(url, headers=headers, json=data) as response:if response.status != 200:error_text = await response.text()@@ -807,7 +812,7 @@ async def fetch_models(timeout = aiohttp.ClientTimeout(total=30)connector = _get_aiohttp_connector()- async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:+ async with aiohttp.ClientSession(timeout=timeout, connector=connector, trust_env=True) as session:try:url = f"{base_url}/models"async with session.get(url, headers=headers) as resp:diff --git a/src/services/llm/factory.py b/src/services/llm/factory.pyindex 4484c7d88..77063a22e 100644--- a/src/services/llm/factory.py+++ b/src/services/llm/factory.py@@ -81,11 +81,15 @@ def _is_retriable_error(error: BaseException) -> bool:- Network/connection errorsNon-retriable errors:+ - CancelledError / KeyboardInterrupt (must propagate immediately)- Authentication errors (401)- Bad request (400)- Not found (404)- Client errors (4xx except 429)"""+ if isinstance(error, (asyncio.CancelledError, KeyboardInterrupt, GeneratorExit)):+ return False+from aiohttp import ClientErrorif isinstance(error, (asyncio.TimeoutError, ClientError)):@@ -185,6 +189,8 @@ async def complete(outcome = retry_state.outcomeexception = outcome.exception() if outcome else Noneerror_message = str(exception) if exception else "unknown error"+ if not error_message.strip():+ error_message = f"{type(exception).__name__} (no message)"logger.warning("LLM call failed (attempt %s/%s), retrying in %.1fs... Error: %s"% (diff --git a/src/services/prompt/manager.py b/src/services/prompt/manager.pyindex 0297ec54c..217a0d9fb 100644--- a/src/services/prompt/manager.py+++ b/src/services/prompt/manager.py@@ -26,7 +26,10 @@ class PromptManager:}# Supported modules- MODULES = ["research", "solve", "guide", "question", "ideagen", "co_writer"]+ MODULES = ["research", "solve", "guide", "question", "ideagen", "co_writer", "personalization"]++ # Modules that are not under src/agents/ directory+ NON_AGENT_MODULES = {"personalization": "personalization"}def __new__(cls) -> "PromptManager":if cls._instance is None:@@ -81,7 +84,11 @@ class PromptManager:subdirectory: str | None,) -> dict[str, Any]:"""Load prompt file with language fallback."""- prompts_dir = PROJECT_ROOT / "src" / "agents" / module_name / "prompts"+ # Handle modules that are not under src/agents/+ if module_name in self.NON_AGENT_MODULES:+ prompts_dir = PROJECT_ROOT / "src" / module_name / "prompts"+ else:+ prompts_dir = PROJECT_ROOT / "src" / "agents" / module_name / "prompts"fallback_chain = self.LANGUAGE_FALLBACKS.get(lang_code, ["en"])for lang in fallback_chain:diff --git a/src/services/rag/factory.py b/src/services/rag/factory.pyindex 094bd1e40..39dc03ea2 100644--- a/src/services/rag/factory.py+++ b/src/services/rag/factory.py@@ -16,6 +16,9 @@ import warnings_PIPELINES: Dict[str, Callable] = {}_PIPELINES_INITIALIZED = False+# Cached pipeline instances keyed by (name, kb_base_dir)+_PIPELINE_CACHE: Dict[tuple, object] = {}+def _init_pipelines():"""Lazily initialize pipeline registry.@@ -67,6 +70,9 @@ def get_pipeline(name: str = "raganything", kb_base_dir: Optional[str] = None, *"""Get a pre-configured pipeline by name.+ Instances are cached by (name, kb_base_dir) so repeated calls reuse the+ same pipeline (and its internal RAG instance cache).+Args:name: Pipeline name (raganything, raganything_docling, lightrag, llamaindex)kb_base_dir: Base directory for knowledge bases (passed to all pipelines)@@ -83,6 +89,12 @@ def get_pipeline(name: str = "raganything", kb_base_dir: Optional[str] = None, *available = list(_PIPELINES.keys())raise ValueError(f"Unknown pipeline: {name}. Available: {available}")+ # Return cached instance when no extra kwargs are provided+ if not kwargs:+ cache_key = (name, kb_base_dir)+ if cache_key in _PIPELINE_CACHE:+ return _PIPELINE_CACHE[cache_key]+factory = _PIPELINES[name]try:@@ -90,11 +102,16 @@ def get_pipeline(name: str = "raganything", kb_base_dir: Optional[str] = None, *# - lightrag: callable that accepts kb_base_dir and returns a composed RAGPipeline# - llamaindex, raganything, raganything_docling: callables that instantiate class-based pipelinesif name in ("lightrag",):- return factory(kb_base_dir=kb_base_dir, **kwargs)+ instance = factory(kb_base_dir=kb_base_dir, **kwargs)+ else:+ if kb_base_dir:+ kwargs["kb_base_dir"] = kb_base_dir+ instance = factory(**kwargs)++ if not kwargs or (len(kwargs) == 1 and "kb_base_dir" in kwargs):+ _PIPELINE_CACHE[(name, kb_base_dir)] = instance- if kb_base_dir:- kwargs["kb_base_dir"] = kb_base_dir- return factory(**kwargs)+ return instanceexcept ImportError as e:# Common case: user didn't install optional RAG backend deps (e.g. llama_index).raise ValueError(diff --git a/src/services/rag/parsers/__init__.py b/src/services/rag/parsers/__init__.pynew file mode 100644index 000000000..a398d58de--- /dev/null+++ b/src/services/rag/parsers/__init__.py@@ -0,0 +1,14 @@+# -*- coding: utf-8 -*-+"""+RAG Parsers+===========++External document parsing integrations (e.g., MinerU Cloud API).+"""++from .mineru_api import MinerUAPIClient, MinerUAPIError++__all__ = [+ "MinerUAPIClient",+ "MinerUAPIError",+]diff --git a/src/services/rag/parsers/mineru_api.py b/src/services/rag/parsers/mineru_api.pynew file mode 100644index 000000000..0e926a060--- /dev/null+++ b/src/services/rag/parsers/mineru_api.py@@ -0,0 +1,493 @@+# -*- coding: utf-8 -*-+"""+MinerU Cloud API Client+========================++Provides document parsing via MinerU's cloud API (https://mineru.net) as an+alternative to running MinerU locally. This is useful when:+- Local GPU resources are unavailable+- Processing needs to be offloaded to the cloud+- Running on machines without MinerU installed++API flow:+1. Request upload URLs via POST /api/v4/file-urls/batch+2. Upload files via PUT to the returned URLs+3. Poll for results via GET /api/v4/extract-results/batch/{batch_id}+4. Download and extract the result ZIP (contains content_list, markdown, images)+"""++import asyncio+import io+import json+import logging+import os+import shutil+import tempfile+import time+import zipfile+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuple, Union++import requests++logger = logging.getLogger(__name__)++# MinerU API base URL+MINERU_API_BASE = "https://mineru.net/api/v4"++# Default polling settings+DEFAULT_POLL_INTERVAL = 5 # seconds+DEFAULT_POLL_TIMEOUT = 600 # 10 minutes max+++class MinerUAPIError(Exception):+ """Exception raised for MinerU API errors."""++ def __init__(self, code: int, message: str, trace_id: str = ""):+ self.code = code+ self.message = message+ self.trace_id = trace_id+ super().__init__(f"MinerU API error [{code}]: {message} (trace_id: {trace_id})")+++class MinerUAPIClient:+ """+ Client for MinerU Cloud API (https://mineru.net).++ Handles file upload, task submission, polling for results, and+ downloading/extracting parsed content.++ Usage:+ client = MinerUAPIClient(token="your-api-token")+ content_list, md_content = await client.parse_file(+ file_path="document.pdf",+ output_dir="./output",+ )+ """++ def __init__(+ self,+ token: Optional[str] = None,+ model_version: str = "vlm",+ enable_formula: bool = True,+ enable_table: bool = True,+ language: str = "ch",+ poll_interval: int = DEFAULT_POLL_INTERVAL,+ poll_timeout: int = DEFAULT_POLL_TIMEOUT,+ ):+ """+ Initialize MinerU API client.++ Args:+ token: MinerU API token (from https://mineru.net).+ Falls back to MINERU_API_TOKEN env var.+ model_version: Model version to use ("pipeline", "vlm", "MinerU-HTML").+ Default is "vlm" for best accuracy.+ enable_formula: Whether to enable formula recognition.+ enable_table: Whether to enable table recognition.+ language: Document language (default "ch" for Chinese+English).+ poll_interval: Seconds between polling attempts.+ poll_timeout: Maximum seconds to wait for results.+ """+ self.token = token or os.getenv("MINERU_API_TOKEN", "")+ if not self.token:+ raise ValueError(+ "MinerU API token is required. Set MINERU_API_TOKEN environment variable "+ "or pass token parameter. Get your token from https://mineru.net"+ )++ self.model_version = model_version+ self.enable_formula = enable_formula+ self.enable_table = enable_table+ self.language = language+ self.poll_interval = poll_interval+ self.poll_timeout = poll_timeout++ self._headers = {+ "Content-Type": "application/json",+ "Authorization": f"Bearer {self.token}",+ }++ def _request_upload_urls(+ self,+ file_names: List[str],+ data_ids: Optional[List[str]] = None,+ ) -> Tuple[str, List[str]]:+ """+ Request file upload URLs from MinerU API.++ Args:+ file_names: List of file names to upload.+ data_ids: Optional list of data IDs for tracking.++ Returns:+ Tuple of (batch_id, list of upload URLs)+ """+ files_payload = []+ for i, name in enumerate(file_names):+ entry = {"name": name}+ if data_ids and i < len(data_ids):+ entry["data_id"] = data_ids[i]+ files_payload.append(entry)++ payload = {+ "files": files_payload,+ "model_version": self.model_version,+ "enable_formula": self.enable_formula,+ "enable_table": self.enable_table,+ "language": self.language,+ }++ url = f"{MINERU_API_BASE}/file-urls/batch"+ logger.info(f"Requesting upload URLs for {len(file_names)} files...")++ response = requests.post(url, headers=self._headers, json=payload, timeout=30)++ if response.status_code != 200:+ raise MinerUAPIError(+ code=response.status_code,+ message=f"HTTP {response.status_code}: {response.text}",+ )++ result = response.json()+ if result.get("code") != 0:+ raise MinerUAPIError(+ code=result.get("code", -1),+ message=result.get("msg", "Unknown error"),+ trace_id=result.get("trace_id", ""),+ )++ batch_id = result["data"]["batch_id"]+ file_urls = result["data"]["file_urls"]++ logger.info(f"Got batch_id: {batch_id}, {len(file_urls)} upload URLs")+ return batch_id, file_urls++ def _upload_file(self, upload_url: str, file_path: Union[str, Path]) -> bool:+ """+ Upload a file to the pre-signed URL.++ Args:+ upload_url: Pre-signed upload URL from MinerU.+ file_path: Local file path.++ Returns:+ True if upload succeeded.+ """+ file_path = Path(file_path)+ logger.info(f"Uploading {file_path.name} ({file_path.stat().st_size / 1024:.1f} KB)...")++ with open(file_path, "rb") as f:+ response = requests.put(upload_url, data=f, timeout=300)++ if response.status_code == 200:+ logger.info(f" ✓ Upload successful: {file_path.name}")+ return True+ else:+ logger.error(+ f" ✗ Upload failed: {file_path.name} "+ f"(HTTP {response.status_code}: {response.text})"+ )+ return False++ def _poll_results(self, batch_id: str) -> List[Dict[str, Any]]:+ """+ Poll for batch extraction results until all tasks complete.++ Args:+ batch_id: Batch ID from upload request.++ Returns:+ List of extraction result dicts.++ Raises:+ TimeoutError: If polling exceeds timeout.+ MinerUAPIError: If API returns an error.+ """+ url = f"{MINERU_API_BASE}/extract-results/batch/{batch_id}"+ start_time = time.time()++ logger.info(f"Polling for results (batch_id: {batch_id})...")++ while True:+ elapsed = time.time() - start_time+ if elapsed > self.poll_timeout:+ raise TimeoutError(+ f"MinerU API polling timed out after {self.poll_timeout}s "+ f"for batch_id: {batch_id}"+ )++ response = requests.get(url, headers=self._headers, timeout=30)++ if response.status_code != 200:+ raise MinerUAPIError(+ code=response.status_code,+ message=f"HTTP {response.status_code}: {response.text}",+ )++ result = response.json()+ if result.get("code") != 0:+ raise MinerUAPIError(+ code=result.get("code", -1),+ message=result.get("msg", "Unknown error"),+ trace_id=result.get("trace_id", ""),+ )++ extract_results = result["data"]["extract_result"]++ # Check overall status+ all_done = True+ has_failed = False+ for item in extract_results:+ state = item.get("state", "")+ if state == "failed":+ has_failed = True+ logger.error(+ f" ✗ Parsing failed for {item.get('file_name')}: "+ f"{item.get('err_msg', 'Unknown error')}"+ )+ elif state not in ("done", "converting"):+ all_done = False+ # Log progress info+ progress = item.get("extract_progress", {})+ if progress:+ logger.info(+ f" ⏳ {item.get('file_name')}: {state} "+ f"({progress.get('extracted_pages', '?')}/"+ f"{progress.get('total_pages', '?')} pages)"+ )+ else:+ logger.info(f" ⏳ {item.get('file_name')}: {state}")++ if all_done or has_failed:+ completed = [r for r in extract_results if r.get("state") == "done"]+ failed = [r for r in extract_results if r.get("state") == "failed"]++ logger.info(+ f"Polling complete: {len(completed)} done, {len(failed)} failed "+ f"(elapsed: {elapsed:.1f}s)"+ )++ if has_failed and not completed:+ failed_msgs = [+ f"{r.get('file_name')}: {r.get('err_msg', 'Unknown')}"+ for r in failed+ ]+ raise MinerUAPIError(+ code=-60010,+ message=f"All files failed to parse: {'; '.join(failed_msgs)}",+ )++ return extract_results++ time.sleep(self.poll_interval)++ def _download_and_extract_zip(+ self,+ zip_url: str,+ output_dir: Union[str, Path],+ file_stem: str,+ ) -> Tuple[List[Dict[str, Any]], str]:+ """+ Download result ZIP and extract content_list and images.++ Args:+ zip_url: URL to the result ZIP file.+ output_dir: Directory to extract results into.+ file_stem: Original file name stem for locating results.++ Returns:+ Tuple of (content_list, markdown_content)+ """+ output_dir = Path(output_dir)+ output_dir.mkdir(parents=True, exist_ok=True)++ logger.info(f"Downloading results ZIP for '{file_stem}'...")++ response = requests.get(zip_url, timeout=300, stream=True)+ if response.status_code != 200:+ raise MinerUAPIError(+ code=response.status_code,+ message=f"Failed to download ZIP: HTTP {response.status_code}",+ )++ # Extract ZIP to a temp dir first, then move to output_dir+ with tempfile.TemporaryDirectory() as temp_dir:+ zip_bytes = io.BytesIO(response.content)+ with zipfile.ZipFile(zip_bytes, "r") as zf:+ zf.extractall(temp_dir)++ temp_path = Path(temp_dir)++ # Find content_list JSON+ content_list = []+ md_content = ""++ # The ZIP structure varies, search recursively for the files+ content_list_files = list(temp_path.rglob("*_content_list.json"))+ md_files = list(temp_path.rglob("*.md"))+ image_dirs = list(temp_path.rglob("images"))++ # Read content_list+ if content_list_files:+ cl_file = content_list_files[0]+ logger.info(f" Found content_list: {cl_file.name}")+ with open(cl_file, "r", encoding="utf-8") as f:+ content_list = json.load(f)+ else:+ logger.warning(" ⚠ No content_list JSON found in ZIP")++ # Read markdown+ if md_files:+ md_file = md_files[0]+ with open(md_file, "r", encoding="utf-8") as f:+ md_content = f.read()++ # Copy images to output_dir/images/+ images_output = output_dir / "images"+ for img_dir in image_dirs:+ if img_dir.is_dir():+ images_output.mkdir(parents=True, exist_ok=True)+ for img_file in img_dir.iterdir():+ if img_file.is_file():+ dest = images_output / img_file.name+ shutil.copy2(img_file, dest)++ # Fix image paths in content_list to point to the output directory+ for item in content_list:+ if isinstance(item, dict):+ for field_name in ["img_path", "table_img_path", "equation_img_path"]:+ if field_name in item and item[field_name]:+ img_path = item[field_name]+ # Convert relative path to absolute path under output_dir+ img_filename = Path(img_path).name+ absolute_path = str((images_output / img_filename).resolve())+ item[field_name] = absolute_path++ # Save content_list to output_dir+ content_list_output = output_dir / f"{file_stem}_content_list.json"+ with open(content_list_output, "w", encoding="utf-8") as f:+ json.dump(content_list, f, ensure_ascii=False, indent=2)++ # Save markdown to output_dir+ if md_content:+ md_output = output_dir / f"{file_stem}.md"+ with open(md_output, "w", encoding="utf-8") as f:+ f.write(md_content)++ logger.info(+ f" ✓ Extracted {len(content_list)} content blocks, "+ f"{len(list(images_output.glob('*'))) if images_output.exists() else 0} images"+ )++ return content_list, md_content++ async def parse_files(+ self,+ file_paths: List[Union[str, Path]],+ output_dir: Union[str, Path],+ data_ids: Optional[List[str]] = None,+ ) -> Dict[str, Tuple[List[Dict[str, Any]], str]]:+ """+ Parse multiple files via MinerU Cloud API.++ Args:+ file_paths: List of local file paths to parse.+ output_dir: Directory to store parsed results.+ data_ids: Optional data IDs for each file.++ Returns:+ Dict mapping file_stem -> (content_list, doc_id_placeholder)+ """+ file_paths = [Path(p) for p in file_paths]+ output_dir = Path(output_dir)+ output_dir.mkdir(parents=True, exist_ok=True)++ # Validate files exist+ for fp in file_paths:+ if not fp.exists():+ raise FileNotFoundError(f"File not found: {fp}")++ file_names = [fp.name for fp in file_paths]++ # Step 1: Request upload URLs+ batch_id, upload_urls = await asyncio.to_thread(+ self._request_upload_urls, file_names, data_ids+ )++ if len(upload_urls) != len(file_paths):+ raise MinerUAPIError(+ code=-1,+ message=f"Got {len(upload_urls)} upload URLs for {len(file_paths)} files",+ )++ # Step 2: Upload files+ for file_path, upload_url in zip(file_paths, upload_urls):+ success = await asyncio.to_thread(self._upload_file, upload_url, file_path)+ if not success:+ raise MinerUAPIError(+ code=-1,+ message=f"Failed to upload file: {file_path.name}",+ )++ # Step 3: Poll for results+ extract_results = await asyncio.to_thread(self._poll_results, batch_id)++ # Step 4: Download and extract results+ results = {}+ for item in extract_results:+ if item.get("state") != "done":+ continue++ file_name = item.get("file_name", "")+ zip_url = item.get("full_zip_url", "")+ if not zip_url:+ logger.warning(f"No ZIP URL for {file_name}, skipping")+ continue++ file_stem = Path(file_name).stem+ file_output_dir = output_dir / file_stem++ content_list, md_content = await asyncio.to_thread(+ self._download_and_extract_zip,+ zip_url,+ file_output_dir,+ file_stem,+ )++ results[file_stem] = (content_list, md_content)++ return results++ async def parse_file(+ self,+ file_path: Union[str, Path],+ output_dir: Union[str, Path],+ ) -> Tuple[List[Dict[str, Any]], str]:+ """+ Parse a single file via MinerU Cloud API.++ Convenience wrapper around parse_files for single-file use.++ Args:+ file_path: Local file path to parse.+ output_dir: Directory to store parsed results.++ Returns:+ Tuple of (content_list, markdown_content)+ """+ file_path = Path(file_path)+ results = await self.parse_files([file_path], output_dir)++ file_stem = file_path.stem+ if file_stem in results:+ return results[file_stem]++ # If file_stem doesn't match (e.g. due to naming differences), return first result+ if results:+ return next(iter(results.values()))++ raise MinerUAPIError(+ code=-1,+ message=f"No parsing results returned for {file_path.name}",+ )diff --git a/src/services/rag/pipelines/raganything.py b/src/services/rag/pipelines/raganything.pyindex 85478b8f9..cc2cf979f 100644--- a/src/services/rag/pipelines/raganything.py+++ b/src/services/rag/pipelines/raganything.py@@ -18,6 +18,27 @@ from src.logging.adapters import LightRAGLogContextfrom src.services.llm.config import get_llm_config as _early_config_load # noqa: F401+def _patch_doc_processing_status() -> None:+ """Patch DocProcessingStatus to tolerate unknown fields from newer LightRAG/RAGAnything versions."""+ try:+ from dataclasses import fields as dc_fields+ from lightrag.base import DocProcessingStatus++ _orig_init = DocProcessingStatus.__init__++ def _tolerant_init(self, *args, **kwargs):+ known = {f.name for f in dc_fields(DocProcessingStatus)}+ kwargs = {k: v for k, v in kwargs.items() if k in known}+ _orig_init(self, *args, **kwargs)++ DocProcessingStatus.__init__ = _tolerant_init+ except Exception:+ pass+++_patch_doc_processing_status()++class RAGAnythingPipeline:"""RAG-Anything end-to-end Pipeline.@@ -110,6 +131,9 @@ class RAGAnythingPipeline:kb_name: str,file_paths: List[str],extract_numbered_items: bool = True,+ use_mineru_api: bool = False,+ mineru_api_token: Optional[str] = None,+ mineru_model_version: str = "vlm",**kwargs,) -> bool:"""@@ -131,6 +155,9 @@ class RAGAnythingPipeline:kb_name: Knowledge base namefile_paths: List of file paths to processextract_numbered_items: Whether to extract numbered items after processing+ use_mineru_api: Use MinerU cloud API instead of local MinerU+ mineru_api_token: MinerU API token (falls back to MINERU_API_TOKEN env var)+ mineru_model_version: MinerU API model version ("pipeline", "vlm", "MinerU-HTML")**kwargs: Additional argumentsReturns:@@ -144,7 +171,10 @@ class RAGAnythingPipeline:migrate_images_and_update_paths,)- self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files")+ parse_mode = "MinerU API" if use_mineru_api else "MinerU local"+ self.logger.info(+ f"Initializing KB '{kb_name}' with {len(file_paths)} files (parser: {parse_mode})"+ )kb_dir = Path(self.kb_base_dir) / kb_namecontent_list_dir = kb_dir / "content_list"@@ -161,6 +191,19 @@ class RAGAnythingPipeline:f"{len(classification.unsupported)} unsupported")+ # Initialize MinerU API client if needed+ mineru_api_client = None+ if use_mineru_api and classification.needs_mineru:+ from ..parsers.mineru_api import MinerUAPIClient++ mineru_api_client = MinerUAPIClient(+ token=mineru_api_token,+ model_version=mineru_model_version,+ )+ self.logger.info(+ f"Using MinerU Cloud API (model_version: {mineru_model_version})"+ )+with LightRAGLogContext(scene="knowledge_init"):rag = self._get_rag_instance(kb_name)await rag._ensure_lightrag_initialized()@@ -173,15 +216,25 @@ class RAGAnythingPipeline:for file_path in classification.needs_mineru:idx += 1file_name = Path(file_path).name- self.logger.info(f"Processing [{idx}/{total_files}] (MinerU): {file_name}")-- # Step 1: Parse document (without RAG insertion)- self.logger.info(" Step 1/3: Parsing document...")- content_list, doc_id = await rag.parse_document(- file_path=file_path,- output_dir=str(content_list_dir),- parse_method="auto",- )+ self.logger.info(f"Processing [{idx}/{total_files}] ({parse_mode}): {file_name}")++ if mineru_api_client:+ # === MinerU Cloud API path ===+ self.logger.info(" Step 1/3: Parsing document via MinerU API...")+ content_list, _md = await mineru_api_client.parse_file(+ file_path=file_path,+ output_dir=str(content_list_dir),+ )+ # Generate doc_id from content (same logic as RAGAnything)+ doc_id = rag._generate_content_based_doc_id(content_list)+ else:+ # === Local MinerU path ===+ self.logger.info(" Step 1/3: Parsing document locally...")+ content_list, doc_id = await rag.parse_document(+ file_path=file_path,+ output_dir=str(content_list_dir),+ parse_method="auto",+ )# Step 2: Migrate images and update pathsself.logger.info(" Step 2/3: Migrating images to canonical location...")@@ -310,7 +363,13 @@ class RAGAnythingPipeline:"""with LightRAGLogContext(scene="rag_search"):rag = self._get_rag_instance(kb_name)- await rag._ensure_lightrag_initialized()+ # Parser (MinerU) is not needed for search — skip the check+ rag._parser_installation_checked = True+ init_result = await rag._ensure_lightrag_initialized()+ if isinstance(init_result, dict) and not init_result.get("success", True):+ raise RuntimeError(+ f"LightRAG init failed for '{kb_name}': {init_result.get('error', 'unknown')}"+ )answer = await rag.aquery(query, mode=mode, only_need_context=only_need_context)answer_str = answer if isinstance(answer, str) else str(answer)diff --git a/src/services/rag/service.py b/src/services/rag/service.pyindex 15d229c84..018c17af3 100644--- a/src/services/rag/service.py+++ b/src/services/rag/service.py@@ -140,8 +140,12 @@ class RAGService:def _get_provider_for_kb(self, kb_name: str) -> str:"""- Get the RAG provider for a specific knowledge base from its metadata.- Falls back to instance provider or env var if not found in metadata.+ Get the RAG provider for a specific knowledge base.++ Priority:+ 1. kb_config.json (authoritative source)+ 2. metadata.json (backward compatibility)+ 3. Instance provider (fallback)Args:kb_name: Knowledge base name@@ -150,23 +154,34 @@ class RAGService:Provider name (e.g., 'llamaindex', 'lightrag', 'raganything')"""try:- metadata_file = Path(self.kb_base_dir) / kb_name / "metadata.json"+ # First, try kb_config.json (authoritative source)+ kb_config_file = Path(self.kb_base_dir) / "kb_config.json"+ if kb_config_file.exists():+ with open(kb_config_file, encoding="utf-8") as f:+ config = json.load(f)+ kb_config = config.get("knowledge_bases", {}).get(kb_name, {})+ provider = kb_config.get("rag_provider")+ if provider:+ self.logger.info(f"Using provider '{provider}' from kb_config.json")+ return provider+ # Fallback: try metadata.json (backward compatibility)+ metadata_file = Path(self.kb_base_dir) / kb_name / "metadata.json"if metadata_file.exists():with open(metadata_file, encoding="utf-8") as f:metadata = json.load(f)provider = metadata.get("rag_provider")if provider:- self.logger.info(f"Using provider '{provider}' from KB metadata")+ self.logger.info(f"Using provider '{provider}' from metadata.json")return provider# Fallback to instance provider- self.logger.info(f"No provider in metadata, using instance provider: {self.provider}")+ self.logger.info(f"No provider in config, using instance provider: {self.provider}")return self.providerexcept Exception as e:self.logger.warning(- f"Error reading provider from metadata: {e}, using instance provider"+ f"Error reading provider from config: {e}, using instance provider")return self.providerdiff --git a/src/tools/__init__.py b/src/tools/__init__.pyindex 808f37a23..e2a3a2fa8 100644--- a/src/tools/__init__.py+++ b/src/tools/__init__.py@@ -57,6 +57,7 @@ except Exception as e:from .code_executor import run_code, run_code_syncfrom .query_item_tool import query_numbered_itemfrom .rag_tool import rag_search+from .reason import reasonfrom .web_search import web_search# Paper research related tools@@ -71,6 +72,7 @@ try:"TexDownloader","query_numbered_item","rag_search",+ "reason","read_tex_file","run_code","run_code_sync",@@ -82,6 +84,7 @@ except ImportError as e:__all__ = ["query_numbered_item","rag_search",+ "reason","run_code","run_code_sync","web_search",diff --git a/src/tools/code_executor.py b/src/tools/code_executor.pyindex 1b1b306dd..0852bfd62 100644--- a/src/tools/code_executor.py+++ b/src/tools/code_executor.py@@ -1,19 +1,19 @@#!/usr/bin/env python"""Run Code Tool - Code execution tool-Execute Python code in isolated workspace, preserving original input/output structure.+Execute Python code in isolated workspace. Every execution is persisted+under ``run_code_workspace/`` with its source code, output log, and any+generated artifacts (images, data files, etc.)."""import astimport asyncio-from contextlib import contextmanagerfrom dataclasses import dataclass, fieldfrom datetime import datetimeimport osfrom pathlib import Pathimport subprocessimport sys-import tempfileimport timefrom typing import Any@@ -27,40 +27,24 @@ from src.services.path_service import get_path_servicelogger = get_logger("CodeExecutor")+# Files managed by the executor itself (excluded from user-artifact lists)+_META_FILES = frozenset({"code.py", "output.log", ".gitkeep"})+def _load_config() -> dict[str, Any]:"""Load run_code configuration from main.yaml and module configs"""try:from src.services.config import load_config_with_main- # Try loading from solve_config (most common use case)- try:- config = load_config_with_main("solve_config.yaml", PROJECT_ROOT)- run_code_config = config.get("tools", {}).get("run_code", {})- if run_code_config:- logger.debug("Loaded run_code config from solve_config.yaml (with main.yaml)")- return run_code_config- except Exception as e:- logger.debug(f"Failed to load from solve_config: {e}")-- # Fallback to question_config- try:- config = load_config_with_main("question_config.yaml", PROJECT_ROOT)- run_code_config = config.get("tools", {}).get("run_code", {})- if run_code_config:- logger.debug("Loaded run_code config from question_config.yaml (with main.yaml)")- return run_code_config- except Exception as e:- logger.debug(f"Failed to load from question_config: {e}")-- # Fallback to main.yaml only- try:- config = load_config_with_main("solve_config.yaml", PROJECT_ROOT)- run_code_config = config.get("tools", {}).get("run_code", {})- if run_code_config:- return run_code_config- except Exception:- pass+ for cfg_name in ("solve_config.yaml", "question_config.yaml"):+ try:+ config = load_config_with_main(cfg_name, PROJECT_ROOT)+ run_code_config = config.get("tools", {}).get("run_code", {})+ if run_code_config:+ logger.debug(f"Loaded run_code config from {cfg_name} (with main.yaml)")+ return run_code_config+ except Exception as e:+ logger.debug(f"Failed to load from {cfg_name}: {e}")except ImportError:logger.debug("config_loader not available, using fallback")@@ -83,6 +67,26 @@ def _load_config() -> dict[str, Any]:return {}+def _save_output_log(+ execution_dir: Path,+ stdout: str,+ stderr: str,+ exit_code: int,+ elapsed_ms: float,+) -> Path:+ """Persist execution output to ``output.log`` inside *execution_dir*."""+ log_file = execution_dir / "output.log"+ with open(log_file, "w", encoding="utf-8") as f:+ f.write(f"Exit Code: {exit_code}\n")+ f.write(f"Elapsed: {elapsed_ms:.1f}ms\n")+ f.write(f"{'=' * 50}\n")+ if stdout:+ f.write(f"[STDOUT]\n{stdout}\n")+ if stderr:+ f.write(f"[STDERR]\n{stderr}\n")+ return log_file++class CodeExecutionError(Exception):"""Code execution error"""@@ -95,7 +99,7 @@ class OperationEntry:class OperationLogger:- """Simple operation history logger, inspired by code_implementation_server recording method"""+ """Simple operation history logger."""def __init__(self, max_entries: int = 200):self._history: list[OperationEntry] = []@@ -114,71 +118,26 @@ class OperationLogger:class WorkspaceManager:- """Manages isolated workspace, similar to code_implementation_server workspace logic"""+ """Manages the persistent ``run_code_workspace`` directory."""def __init__(self):- # Load configuration (priority: environment variable > config file > default)config = _load_config()- # Determine workspace directory (priority: environment variable > config file > default)env_path = os.getenv(RUN_CODE_WORKSPACE_ENV)if env_path:self.base_dir = Path(env_path).expanduser().resolve()else:config_workspace = config.get("workspace")if config_workspace:- # Support relative paths (relative to project root) and absolute pathsworkspace_path = Path(config_workspace).expanduser()if workspace_path.is_absolute():self.base_dir = workspace_path.resolve()else:self.base_dir = (PROJECT_ROOT / workspace_path).resolve()else:- # Default workspace is set under user directory using PathServicepath_service = get_path_service()self.base_dir = path_service.get_run_code_workspace_dir().resolve()- # Determine allowed root paths list- # Default includes project root and user directory- path_service = get_path_service()- self.allowed_roots: list[Path] = [- PROJECT_ROOT.resolve(),- path_service.user_data_dir.resolve(),- ]-- # Read allowed root paths from config file- config_allowed_roots = config.get("allowed_roots", [])- if isinstance(config_allowed_roots, str):- config_allowed_roots = [config_allowed_roots]- for root_path in config_allowed_roots:- root = Path(root_path).expanduser()- if root.is_absolute():- resolved_root = root.resolve()- else:- resolved_root = (PROJECT_ROOT / root).resolve()- # Avoid duplicate addition- if resolved_root not in self.allowed_roots:- self.allowed_roots.append(resolved_root)-- # Read additional allowed root paths from environment variables- extra_roots = os.getenv(RUN_CODE_ALLOWED_ROOTS_ENV)- if extra_roots:- for raw_path in extra_roots.split(os.pathsep):- raw_path = raw_path.strip()- if raw_path:- path = Path(raw_path).expanduser()- if path.is_absolute():- resolved_path = path.resolve()- else:- resolved_path = (PROJECT_ROOT / path).resolve()- # Avoid duplicate addition- if resolved_path not in self.allowed_roots:- self.allowed_roots.append(resolved_path)-- # Ensure workspace directory itself can also be a valid root path- if self.base_dir not in self.allowed_roots:- self.allowed_roots.append(self.base_dir)-self._initialized = Falsedef initialize(self):@@ -191,64 +150,30 @@ class WorkspaceManager:if not self._initialized:self.initialize()- @contextmanager- def create_temp_dir(self) -> Path:+ def create_execution_dir(self, prefix: str = "exec") -> Path:+ """Create a persistent, timestamped execution directory under the workspace."""self.ensure_initialized()- with tempfile.TemporaryDirectory(dir=self.base_dir) as temp_dir:- yield Path(temp_dir)-- def resolve_assets_dir(self, assets_dir: str | None) -> Path | None:- if not assets_dir:- return None- path = Path(assets_dir).expanduser()- if not path.is_absolute():- path = (self.base_dir / path).resolve()- self._ensure_within_allowed_roots(path)- path.mkdir(parents=True, exist_ok=True)- return path-- def collect_artifacts(self, assets_dir: Path | None) -> tuple[list[str], list[str]]:+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")+ exec_dir = self.base_dir / f"{prefix}_{timestamp}"+ exec_dir.mkdir(parents=True, exist_ok=True)+ return exec_dir++ def collect_artifacts(self, exec_dir: Path | None) -> tuple[list[str], list[str]]:+ """Return user-generated files (excluding code.py / output.log)."""artifacts: list[str] = []artifact_paths: list[str] = []- if not assets_dir or not assets_dir.exists():+ if not exec_dir or not exec_dir.exists():return artifacts, artifact_paths- for file_path in assets_dir.iterdir():- if file_path.is_file() and file_path.name != ".gitkeep":- artifacts.append(str(file_path.relative_to(assets_dir)))+ for file_path in exec_dir.iterdir():+ if file_path.is_file() and file_path.name not in _META_FILES:+ artifacts.append(file_path.name)artifact_paths.append(str(file_path.resolve()))return artifacts, artifact_paths- def _ensure_within_allowed_roots(self, path: Path):- resolved_path = path.resolve()- for root in self.allowed_roots:- # Use Path object methods for path comparison, avoiding Windows path separator and case issues- try:- # Python 3.9+ use is_relative_to- if hasattr(resolved_path, "is_relative_to"):- if resolved_path.is_relative_to(root):- return- else:- # Python < 3.9 use path comparison after resolve()- # Convert to lowercase and normalize path separators for comparison (Windows compatible)- resolved_str = str(resolved_path).lower().replace("\\", "/")- root_str = str(root.resolve()).lower().replace("\\", "/")- if resolved_str.startswith(root_str):- return- except (ValueError, AttributeError):- # If is_relative_to fails, fallback to string comparison- resolved_str = str(resolved_path).lower().replace("\\", "/")- root_str = str(root.resolve()).lower().replace("\\", "/")- if resolved_str.startswith(root_str):- return- allowed = "\n".join(str(root) for root in self.allowed_roots)- raise ValueError(- f"Assets directory {resolved_path} must be located under one of the following allowed paths:\n{allowed}"- )-class ImportGuard:- """Parse AST, restrict import modules, ensure consistency with allowed_imports logic"""+ """Parse AST, restrict import modules."""@staticmethoddef validate(code: str, allowed_imports: list[str] | None):@@ -278,170 +203,150 @@ class ImportGuard:class CodeExecutionEnvironment:- """Encapsulates actual code execution logic, maintaining consistency with DeepCode server flow"""-- def __init__(self, workspace: WorkspaceManager):- self.workspace = workspace+ """Run Python code inside a persistent execution directory."""def run_python(self,code: str,timeout: int,- assets_dir: Path | None,+ execution_dir: Path,) -> tuple[str, str, int, float]:+ """Write *code* to ``execution_dir/code.py``, execute it, and return+ (stdout, stderr, exit_code, elapsed_ms). The source file is kept on+ disk for later inspection."""env = os.environ.copy()env["PYTHONIOENCODING"] = "utf-8"- with self.workspace.create_temp_dir() as temp_dir:- code_file = temp_dir / "code.py"- code_file.write_text(code, encoding="utf-8")-- work_dir = assets_dir if assets_dir else temp_dir- start_time = time.time()-- result = subprocess.run(- [sys.executable, str(code_file)],- check=False,- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=timeout,- cwd=str(work_dir),- env=env,- )-- elapsed_ms = (time.time() - start_time) * 1000- return result.stdout, result.stderr, result.returncode, elapsed_ms+ code_file = execution_dir / "code.py"+ code_file.write_text(code, encoding="utf-8")++ start_time = time.time()+ result = subprocess.run(+ [sys.executable, str(code_file)],+ check=False,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=timeout,+ cwd=str(execution_dir),+ env=env,+ )+ elapsed_ms = (time.time() - start_time) * 1000+ return result.stdout, result.stderr, result.returncode, elapsed_msWORKSPACE_MANAGER = WorkspaceManager()OPERATION_LOGGER = OperationLogger()-EXECUTION_ENV = CodeExecutionEnvironment(WORKSPACE_MANAGER)+EXECUTION_ENV = CodeExecutionEnvironment()async def run_code(language: str,code: str,timeout: int = 10,- assets_dir: str | None = None,allowed_imports: list[str] | None = None,+ workspace_dir: str | Path | None = None,) -> dict[str, Any]:- """- Execute code in isolated environment, return result structure consistent with previous version.+ """Execute code in an isolated, persistent directory under ``run_code_workspace``.++ Each invocation creates a new timestamped directory containing:+ - ``code.py`` – the executed source code+ - ``output.log`` – captured stdout / stderr and exit info+ - any files the code itself generates (images, data, etc.)++ Returns a dict with stdout, stderr, exit_code, elapsed_ms, execution_dir,+ source_file, output_log, artifacts, and artifact_paths."""if language.lower() != "python":raise ValueError(f"Unsupported language: {language}, currently only Python is supported")- WORKSPACE_MANAGER.ensure_initialized()- ImportGuard.validate(code, allowed_imports)-- assets_path = WORKSPACE_MANAGER.resolve_assets_dir(assets_dir)- loop = asyncio.get_running_loop()-- def _execute():- return EXECUTION_ENV.run_python(code, timeout, assets_path)+ if workspace_dir is not None:+ custom_workspace = Path(workspace_dir).expanduser().resolve()+ custom_workspace.mkdir(parents=True, exist_ok=True)+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")+ execution_dir = custom_workspace / f"exec_{timestamp}"+ execution_dir.mkdir(parents=True, exist_ok=True)+ else:+ WORKSPACE_MANAGER.ensure_initialized()+ execution_dir = WORKSPACE_MANAGER.create_execution_dir()+ stdout, stderr, exit_code, elapsed_ms = "", "", -1, 0.0+ status = "error"try:- stdout, stderr, exit_code, elapsed_ms = await loop.run_in_executor(None, _execute)- artifacts, artifact_paths = WORKSPACE_MANAGER.collect_artifacts(assets_path)+ ImportGuard.validate(code, allowed_imports)- result = {- "stdout": stdout,- "stderr": stderr,- "artifacts": artifacts,- "artifact_paths": artifact_paths,- "exit_code": exit_code,- "elapsed_ms": elapsed_ms,- }-- OPERATION_LOGGER.log(- "execute_python",- {- "status": "success",- "language": language,- "timeout": timeout,- "assets_dir": str(assets_path) if assets_path else None,- "exit_code": exit_code,- "elapsed_ms": elapsed_ms,- "code_size": len(code),- },- )+ loop = asyncio.get_running_loop()- return result+ def _execute():+ return EXECUTION_ENV.run_python(code, timeout, execution_dir)- except subprocess.TimeoutExpired as timeout_exc:- # Code execution timeout- artifacts, artifact_paths = WORKSPACE_MANAGER.collect_artifacts(assets_path)- elapsed_ms = timeout * 1000- message = f"Code execution timeout ({timeout} seconds)"-- logger.warning(f"Code execution timeout after {timeout}s: {timeout_exc}")-- OPERATION_LOGGER.log(- "execute_python",- {- "status": "timeout",- "language": language,- "timeout": timeout,- "assets_dir": str(assets_path) if assets_path else None,- },- )+ stdout, stderr, exit_code, elapsed_ms = await loop.run_in_executor(None, _execute)+ status = "success"- return {- "stdout": "",- "stderr": message,- "artifacts": artifacts,- "artifact_paths": artifact_paths,- "exit_code": -1,- "elapsed_ms": elapsed_ms,- }+ except subprocess.TimeoutExpired:+ elapsed_ms = timeout * 1000+ stderr = f"Code execution timeout ({timeout} seconds)"+ status = "timeout"+ logger.warning(f"Code execution timeout after {timeout}s")+ # Ensure source file is written even if timeout happened before write+ src = execution_dir / "code.py"+ if not src.exists():+ src.write_text(code, encoding="utf-8")++ except CodeExecutionError as exc:+ stderr = str(exc)+ status = "validation_error"+ # Source code was invalid; still save it for diagnosis+ src = execution_dir / "code.py"+ if not src.exists():+ src.write_text(code, encoding="utf-8")except Exception as exc: # pylint: disable=broad-except- # Catch all other exceptions to ensure main flow is not interrupted- artifacts, artifact_paths = WORKSPACE_MANAGER.collect_artifacts(assets_path)- elapsed_ms = 0.0-- if isinstance(exc, CodeExecutionError):- stderr_message = str(exc)- else:- stderr_message = f"Code execution failed: {exc}"-- # Log detailed error information+ stderr = f"Code execution failed: {exc}"logger.error(f"Code execution error: {exc}", exc_info=True)-- OPERATION_LOGGER.log(- "execute_python",- {- "status": "error",- "language": language,- "timeout": timeout,- "assets_dir": str(assets_path) if assets_path else None,- "error": stderr_message,- },- )-- return {- "stdout": "",- "stderr": stderr_message,- "artifacts": artifacts,- "artifact_paths": artifact_paths,- "exit_code": -1,+ src = execution_dir / "code.py"+ if not src.exists():+ src.write_text(code, encoding="utf-8")++ # Always persist the output log+ _save_output_log(execution_dir, stdout, stderr, exit_code, elapsed_ms)++ artifacts, artifact_paths = WORKSPACE_MANAGER.collect_artifacts(execution_dir)++ OPERATION_LOGGER.log(+ "execute_python",+ {+ "status": status,+ "language": language,+ "timeout": timeout,+ "execution_dir": str(execution_dir),+ "exit_code": exit_code,"elapsed_ms": elapsed_ms,- }+ "code_size": len(code),+ },+ )++ return {+ "stdout": stdout,+ "stderr": stderr,+ "exit_code": exit_code,+ "elapsed_ms": elapsed_ms,+ "execution_dir": str(execution_dir),+ "source_file": str(execution_dir / "code.py"),+ "output_log": str(execution_dir / "output.log"),+ "artifacts": artifacts,+ "artifact_paths": artifact_paths,+ }def run_code_sync(language: str,code: str,timeout: int = 10,- assets_dir: str | None = None,) -> dict[str, Any]:- """- Synchronous version of code execution (for non-async environments)- """-- return asyncio.run(run_code(language, code, timeout, assets_dir))+ """Synchronous version of code execution (for non-async environments)."""+ return asyncio.run(run_code(language, code, timeout))if __name__ == "__main__":@@ -453,8 +358,10 @@ if __name__ == "__main__":result1 = await run_code("python", sample1, timeout=5)print("stdout:", result1["stdout"])print("stderr:", result1["stderr"])- print("artifacts:", result1.get("artifacts", {}))- print("artifact_paths:", result1.get("artifact_paths", []))+ print("execution_dir:", result1["execution_dir"])+ print("source_file:", result1["source_file"])+ print("output_log:", result1["output_log"])+ print("artifacts:", result1["artifacts"])print("exit_code:", result1["exit_code"])print("-" * 40)@@ -463,77 +370,55 @@ if __name__ == "__main__":result2 = await run_code("python", sample2, timeout=5)print("stdout:", result2["stdout"])print("stderr:", result2["stderr"])+ print("execution_dir:", result2["execution_dir"])print("exit_code:", result2["exit_code"])print("-" * 40)print("==== 3. Test code timeout ====")- sample3 = textwrap.dedent(- """- import time- time.sleep(10)- print("Timeout should occur before this prints.")- """- )+ sample3 = textwrap.dedent("""\+ import time+ time.sleep(10)+ print("Timeout should occur before this prints.")+ """)result3 = await run_code("python", sample3, timeout=2)print("stdout:", result3["stdout"])print("stderr:", result3["stderr"])+ print("execution_dir:", result3["execution_dir"])print("exit_code:", result3["exit_code"])print("-" * 40)print("==== 4. Test plotting functionality (matplotlib) ====")- sample4 = textwrap.dedent(- """- import matplotlib.pyplot as plt- plt.figure()- plt.plot([1, 2, 3], [4, 2, 5])- plt.title('Simple Plot')- plt.savefig('test_plot.png')- print('Plot created!')- """- )+ sample4 = textwrap.dedent("""\+ import matplotlib.pyplot as plt+ plt.figure()+ plt.plot([1, 2, 3], [4, 2, 5])+ plt.title('Simple Plot')+ plt.savefig('test_plot.png')+ print('Plot created!')+ """)result4 = await run_code("python", sample4, timeout=5)print("stdout:", result4["stdout"])print("stderr:", result4["stderr"])- print("artifacts:", result4.get("artifacts", {}))- print("artifact_paths:", result4.get("artifact_paths", []))+ print("execution_dir:", result4["execution_dir"])+ print("artifacts:", result4["artifacts"])+ print("artifact_paths:", result4["artifact_paths"])print("exit_code:", result4["exit_code"])- # Check generated images- if result4.get("artifact_paths"):- print("Generated image files:", result4["artifact_paths"])- else:- print("No image files found.")print("-" * 40)- print("==== 5. Test standard input ====")- sample5 = textwrap.dedent(- """- text = input("Please enter content: ")- print("You entered: ", text)- """- )- # Standard run_code does not provide stdin, this example tests output behavior+ print("==== 5. Test file read/write ====")+ sample5 = textwrap.dedent("""\+ with open('test_file.txt', 'w', encoding='utf-8') as f:+ f.write('Fake data for test!\\nAnother line.')+ with open('test_file.txt', 'r', encoding='utf-8') as f:+ content = f.read()+ print('File content:', content)+ """)result5 = await run_code("python", sample5, timeout=5)print("stdout:", result5["stdout"])print("stderr:", result5["stderr"])+ print("execution_dir:", result5["execution_dir"])+ print("artifacts:", result5["artifacts"])print("exit_code:", result5["exit_code"])print("-" * 40)- print("==== 6. Test multi-file and resource read/write ====")- sample6 = textwrap.dedent(- """- with open('test_file.txt', 'w', encoding='utf-8') as f:- f.write('Fake data for test!\\nAnother line.')- with open('test_file.txt', 'r', encoding='utf-8') as f:- content = f.read()- print('File content:', content)- """- )- result6 = await run_code("python", sample6, timeout=5)- print("stdout:", result6["stdout"])- print("stderr:", result6["stderr"])- print("artifacts:", result6.get("artifacts", {}))- print("artifact_paths:", result6.get("artifact_paths", []))- print("exit_code:", result6["exit_code"])- print("-" * 40)-asyncio.run(_demo())diff --git a/src/tools/multi_kb_rag_tool.py b/src/tools/multi_kb_rag_tool.pynew file mode 100644index 000000000..ef609746c--- /dev/null+++ b/src/tools/multi_kb_rag_tool.py@@ -0,0 +1,620 @@+#!/usr/bin/env python+"""+Multi-KB RAG Query Tool - Query multiple knowledge bases with reranking++This tool provides:+1. Parallel querying of multiple knowledge bases+2. Result merging and reranking via API+3. Flexible output formats (simple or detailed)+"""++import asyncio+import json+from pathlib import Path+from typing import Any++import aiohttp++# Add parent directory to path+project_root = Path(__file__).parent.parent.parent++from dotenv import load_dotenv+from lightrag.llm.openai import openai_complete_if_cache, openai_embed+from lightrag.utils import EmbeddingFunc+from raganything import RAGAnything, RAGAnythingConfig++from src.core.core import get_embedding_config, get_llm_config, get_rerank_config, load_config_with_main+from src.core.logging import LightRAGLogContext, get_logger+from src.knowledge.manager import KnowledgeBaseManager++# Load environment variables+load_dotenv(project_root / "DeepTutor.env", override=False)+load_dotenv(project_root / ".env", override=False)++# Initialize logger+config = load_config_with_main("solve_config.yaml", project_root)+log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")+logger = get_logger("MultiKBRAG", level="INFO", log_dir=log_dir)+++def _get_multi_kb_config() -> dict:+ """Get multi-KB RAG configuration from main.yaml"""+ try:+ config = load_config_with_main("solve_config.yaml", project_root)+ return config.get("multi_kb_rag", {})+ except Exception:+ return {}+++async def _query_single_kb(+ query: str,+ kb_name: str,+ top_k: int,+ mode: str,+ llm_model_func,+ embedding_func,+ kb_base_dir: str,+) -> dict:+ """+ Query a single knowledge base and return raw context chunks.++ Args:+ query: Query text+ kb_name: Knowledge base name+ top_k: Number of results to retrieve+ mode: Query mode (hybrid, naive, etc.)+ llm_model_func: LLM model function+ embedding_func: Embedding function+ kb_base_dir: Knowledge base base directory++ Returns:+ dict with kb_name, chunks, and any errors+ """+ try:+ kb_manager = KnowledgeBaseManager(kb_base_dir)+ working_dir = str(kb_manager.get_rag_storage_path(kb_name))++ config = RAGAnythingConfig(+ working_dir=working_dir,+ enable_image_processing=True,+ enable_table_processing=True,+ enable_equation_processing=True,+ )++ with LightRAGLogContext(scene="multi_kb_rag"):+ rag = RAGAnything(+ config=config,+ llm_model_func=llm_model_func,+ embedding_func=embedding_func,+ lightrag_kwargs={"top_k": top_k},+ )++ await rag._ensure_lightrag_initialized()++ # Get raw context without LLM processing+ answer = await rag.aquery(query, mode=mode, only_need_context=True)++ return {+ "kb_name": kb_name,+ "content": answer if isinstance(answer, str) else str(answer),+ "success": True,+ "error": None,+ }++ except Exception as e:+ logger.warning(f"Failed to query KB '{kb_name}': {e}")+ return {+ "kb_name": kb_name,+ "content": "",+ "success": False,+ "error": str(e),+ }+++def _parse_context_to_chunks(content: str, kb_name: str) -> list[dict]:+ """+ Parse context string into individual chunks with metadata.++ Args:+ content: Raw context string from RAG+ kb_name: Source knowledge base name++ Returns:+ List of chunk dictionaries+ """+ if not content or not content.strip():+ return []++ chunks = []++ # Try to split by common separators used in LightRAG output+ # LightRAG typically returns chunks separated by newlines or specific markers+ separators = ["\n---\n", "\n\n---\n\n", "\n========\n"]++ parts = [content]+ for sep in separators:+ if sep in content:+ parts = content.split(sep)+ break++ # If no separator found, try splitting by double newlines+ if len(parts) == 1 and "\n\n" in content:+ parts = content.split("\n\n")++ for i, part in enumerate(parts):+ part = part.strip()+ if part:+ chunks.append({+ "content": part,+ "source_kb": kb_name,+ "chunk_index": i,+ "original_score": 1.0 - (i * 0.01), # Approximate score based on order+ })++ return chunks+++async def _call_rerank_api(+ query: str,+ chunks: list[dict],+ rerank_model: str | None = None,+ rerank_api_url: str | None = None,+ rerank_api_key: str | None = None,+ timeout: int = 30,+) -> list[dict]:+ """+ Call external rerank API to reorder chunks by relevance.++ Supports multiple API formats:+ - DashScope/Qwen rerank API (qwen3-rerank)+ - OpenAI-compatible rerank API+ - Generic rerank API++ Args:+ query: Query text+ chunks: List of chunk dictionaries with 'content' field+ rerank_model: Rerank model name (e.g., "qwen3-rerank")+ rerank_api_url: Rerank API endpoint URL+ rerank_api_key: API key for authentication+ timeout: Request timeout in seconds++ Returns:+ Reranked list of chunks with rerank_score added+ """+ if not chunks:+ return []++ # Try to get config from environment if not provided+ if not rerank_api_url or not rerank_api_key:+ try:+ rerank_config = get_rerank_config()+ if not rerank_model:+ rerank_model = rerank_config.get("model", "qwen3-rerank")+ if not rerank_api_key:+ rerank_api_key = rerank_config.get("api_key")+ if not rerank_api_url:+ # Use the full URL from config (RERANK_BINDING_HOST should be complete URL)+ rerank_api_url = rerank_config.get("base_url")+ except Exception as e:+ logger.warning(f"Failed to get rerank config: {e}")++ if not rerank_api_url:+ logger.warning("No rerank API URL configured, returning original order")+ for chunk in chunks:+ chunk["rerank_score"] = chunk.get("original_score", 0.5)+ return chunks++ try:+ # Prepare request payload based on API type+ documents = [chunk["content"] for chunk in chunks]++ # DashScope/OpenAI-compatible rerank format+ payload = {+ "model": rerank_model or "qwen3-rerank",+ "query": query,+ "documents": documents,+ "top_n": len(documents), # Return all with scores+ "return_documents": False, # Only need indices and scores+ }++ headers = {+ "Content-Type": "application/json",+ }+ if rerank_api_key:+ headers["Authorization"] = f"Bearer {rerank_api_key}"++ logger.debug(f"Calling rerank API: {rerank_api_url}, model={rerank_model}")++ async with aiohttp.ClientSession() as session:+ async with session.post(+ rerank_api_url,+ json=payload,+ headers=headers,+ timeout=aiohttp.ClientTimeout(total=timeout),+ ) as response:+ if response.status != 200:+ error_text = await response.text()+ logger.error(f"Rerank API error: {response.status} - {error_text}")+ # Fallback: return original order with original scores+ for chunk in chunks:+ chunk["rerank_score"] = chunk.get("original_score", 0.5)+ return chunks++ result = await response.json()+ logger.debug(f"Rerank API response keys: {result.keys() if isinstance(result, dict) else 'list'}")++ # Parse response - support common rerank API formats+ # Format 1 (DashScope/Qwen): {"results": [{"index": 0, "relevance_score": 0.9}, ...]}+ # Format 2: {"results": [{"index": 0, "score": 0.9}, ...]}+ # Format 3: {"scores": [0.9, 0.8, ...]}+ # Format 4: [{"index": 0, "relevance_score": 0.9}, ...]++ if "results" in result:+ # Sort by score descending+ ranked_results = sorted(+ result["results"],+ key=lambda x: x.get("relevance_score", x.get("score", 0)),+ reverse=True,+ )+ reranked_chunks = []+ for r in ranked_results:+ idx = r.get("index", r.get("document_index", 0))+ if 0 <= idx < len(chunks):+ chunk = chunks[idx].copy()+ chunk["rerank_score"] = r.get("relevance_score", r.get("score", 0.5))+ reranked_chunks.append(chunk)+ logger.info(f"Reranked {len(reranked_chunks)} chunks")+ return reranked_chunks++ elif "scores" in result:+ scores = result["scores"]+ for i, chunk in enumerate(chunks):+ if i < len(scores):+ chunk["rerank_score"] = scores[i]+ else:+ chunk["rerank_score"] = 0.0+ # Sort by rerank score+ return sorted(chunks, key=lambda x: x["rerank_score"], reverse=True)++ elif isinstance(result, list):+ # Direct list response+ ranked_results = sorted(+ result,+ key=lambda x: x.get("relevance_score", x.get("score", 0)),+ reverse=True,+ )+ reranked_chunks = []+ for r in ranked_results:+ idx = r.get("index", r.get("document_index", 0))+ if 0 <= idx < len(chunks):+ chunk = chunks[idx].copy()+ chunk["rerank_score"] = r.get("relevance_score", r.get("score", 0.5))+ reranked_chunks.append(chunk)+ return reranked_chunks++ else:+ logger.warning(f"Unknown rerank API response format: {result}")+ for chunk in chunks:+ chunk["rerank_score"] = chunk.get("original_score", 0.5)+ return chunks++ except asyncio.TimeoutError:+ logger.error(f"Rerank API timeout after {timeout}s")+ for chunk in chunks:+ chunk["rerank_score"] = chunk.get("original_score", 0.5)+ return chunks+ except Exception as e:+ logger.error(f"Rerank API call failed: {e}")+ for chunk in chunks:+ chunk["rerank_score"] = chunk.get("original_score", 0.5)+ return chunks+++def _format_merged_context(chunks: list[dict], max_length: int | None = None) -> str:+ """+ Format chunks into a merged context string.++ Args:+ chunks: List of chunk dictionaries+ max_length: Optional maximum length for output++ Returns:+ Merged context string+ """+ if not chunks:+ return ""++ parts = []+ for i, chunk in enumerate(chunks):+ kb_name = chunk.get("source_kb", "unknown")+ content = chunk.get("content", "")+ score = chunk.get("rerank_score", chunk.get("original_score", 0))++ # Format: [source_kb] content+ part = f"[{kb_name}] {content}"+ parts.append(part)++ merged = "\n\n---\n\n".join(parts)++ if max_length and len(merged) > max_length:+ merged = merged[:max_length] + "..."++ return merged+++async def multi_kb_rag_search(+ query: str,+ kb_names: list[str] | None = None,+ top_k_per_kb: int | None = None,+ final_top_k: int | None = None,+ mode: str = "hybrid",+ rerank_api_url: str | None = None,+ rerank_api_key: str | None = None,+ return_detailed: bool = False,+ kb_base_dir: str | None = None,+ api_key: str | None = None,+ base_url: str | None = None,+ **kwargs,+) -> dict:+ """+ Query multiple knowledge bases with reranking.++ This function:+ 1. Queries all specified knowledge bases in parallel+ 2. Merges all results+ 3. Calls rerank API to reorder by relevance+ 4. Returns top results++ Args:+ query: Query text+ kb_names: List of knowledge base names (None = all available)+ top_k_per_kb: Number of results per KB (default: from config or 20)+ final_top_k: Final number of results after reranking (default: from config or 10)+ mode: Query mode ("local", "global", "hybrid", "naive")+ rerank_api_url: Rerank API endpoint URL+ rerank_api_key: Rerank API key (optional)+ return_detailed: If True, return detailed results with scores+ kb_base_dir: Knowledge base base directory+ api_key: LLM API key (optional)+ base_url: LLM API base URL (optional)+ **kwargs: Additional query parameters++ Returns:+ dict: Query results+ Simple format (return_detailed=False):+ {+ "query": str,+ "answer": str, # Merged context+ "mode": str,+ "source_kbs": list[str]+ }++ Detailed format (return_detailed=True):+ {+ "query": str,+ "results": [+ {+ "content": str,+ "source_kb": str,+ "rerank_score": float,+ "original_score": float+ },+ ...+ ],+ "source_kbs": list[str]+ }+ """+ # Load configuration+ multi_kb_config = _get_multi_kb_config()++ # Apply defaults from config+ if top_k_per_kb is None:+ top_k_per_kb = multi_kb_config.get("default_top_k_per_kb", 20)+ if final_top_k is None:+ final_top_k = multi_kb_config.get("default_final_top_k", 10)+ if rerank_api_url is None:+ rerank_api_url = multi_kb_config.get("rerank_api_url")+ if rerank_api_key is None:+ rerank_api_key = multi_kb_config.get("rerank_api_key")++ # Get LLM configuration+ try:+ llm_config = get_llm_config()+ except ValueError as e:+ raise ValueError(f"LLM configuration error: {e}")++ # Get Embedding configuration+ try:+ embedding_config = get_embedding_config()+ except ValueError as e:+ raise ValueError(f"Embedding configuration error: {e}")++ # Override with provided parameters+ llm_api_key = api_key or llm_config["api_key"]+ llm_base_url = base_url or llm_config["base_url"]+ llm_model = llm_config["model"]++ embedding_api_key = embedding_config["api_key"]+ embedding_base_url = embedding_config["base_url"]+ embedding_model = embedding_config["model"]+ embedding_dim = embedding_config["dim"]+ embedding_max_tokens = embedding_config["max_tokens"]++ # Determine KB base directory+ if kb_base_dir is None:+ try:+ config = load_config_with_main("solve_config.yaml", project_root)+ kb_base_dir = config.get("paths", {}).get("knowledge_bases_dir")+ if kb_base_dir:+ kb_base_dir = str(project_root / kb_base_dir)+ except Exception:+ pass++ if kb_base_dir is None:+ kb_base_dir = str(project_root / "data" / "knowledge_bases")++ # Get knowledge base list+ kb_manager = KnowledgeBaseManager(kb_base_dir)++ if kb_names is None:+ kb_names = kb_manager.list_knowledge_bases()+ logger.info(f"Searching all {len(kb_names)} knowledge bases")+ else:+ # Validate KB names+ available_kbs = set(kb_manager.list_knowledge_bases())+ invalid_kbs = [kb for kb in kb_names if kb not in available_kbs]+ if invalid_kbs:+ logger.warning(f"Unknown knowledge bases will be skipped: {invalid_kbs}")+ kb_names = [kb for kb in kb_names if kb in available_kbs]++ if not kb_names:+ return {+ "query": query,+ "answer": "" if not return_detailed else None,+ "results": [] if return_detailed else None,+ "mode": mode,+ "source_kbs": [],+ "error": "No valid knowledge bases found",+ }++ logger.info(f"Multi-KB search: query='{query[:50]}...', kbs={kb_names}, mode={mode}")++ # Define LLM function+ def llm_model_func(prompt, system_prompt=None, history_messages=[], **kw):+ return openai_complete_if_cache(+ llm_model,+ prompt,+ system_prompt=system_prompt,+ history_messages=history_messages,+ api_key=llm_api_key,+ base_url=llm_base_url,+ **kw,+ )++ # Define embedding function+ embedding_func = EmbeddingFunc(+ embedding_dim=embedding_dim,+ max_token_size=embedding_max_tokens,+ func=lambda texts: openai_embed.func(+ texts,+ model=embedding_model,+ api_key=embedding_api_key,+ base_url=embedding_base_url,+ ),+ )++ # Parallel query all knowledge bases+ tasks = [+ _query_single_kb(+ query=query,+ kb_name=kb_name,+ top_k=top_k_per_kb,+ mode=mode,+ llm_model_func=llm_model_func,+ embedding_func=embedding_func,+ kb_base_dir=kb_base_dir,+ )+ for kb_name in kb_names+ ]++ results = await asyncio.gather(*tasks, return_exceptions=True)++ # Collect all chunks from successful queries+ all_chunks = []+ successful_kbs = []++ for result in results:+ if isinstance(result, Exception):+ logger.warning(f"Query task exception: {result}")+ continue++ if result.get("success"):+ successful_kbs.append(result["kb_name"])+ chunks = _parse_context_to_chunks(result["content"], result["kb_name"])+ all_chunks.extend(chunks)+ else:+ logger.warning(f"KB query failed: {result.get('kb_name')} - {result.get('error')}")++ logger.info(f"Collected {len(all_chunks)} chunks from {len(successful_kbs)} KBs")++ # Rerank all chunks (will auto-load config from env if not provided)+ if all_chunks:+ logger.info("Calling rerank API...")+ reranked_chunks = await _call_rerank_api(+ query=query,+ chunks=all_chunks,+ rerank_model=None, # Will be loaded from config+ rerank_api_url=rerank_api_url,+ rerank_api_key=rerank_api_key,+ )+ else:+ # No chunks to rerank+ reranked_chunks = all_chunks++ # Take top results+ top_chunks = reranked_chunks[:final_top_k]++ # Format output+ if return_detailed:+ return {+ "query": query,+ "results": [+ {+ "content": chunk["content"],+ "source_kb": chunk["source_kb"],+ "rerank_score": chunk.get("rerank_score", 0),+ "original_score": chunk.get("original_score", 0),+ }+ for chunk in top_chunks+ ],+ "source_kbs": successful_kbs,+ "mode": mode,+ }+ else:+ merged_context = _format_merged_context(top_chunks)+ return {+ "query": query,+ "answer": merged_context,+ "mode": mode,+ "source_kbs": successful_kbs,+ }+++# Synchronous wrapper for convenience+def multi_kb_rag_search_sync(+ query: str,+ kb_names: list[str] | None = None,+ **kwargs,+) -> dict:+ """Synchronous wrapper for multi_kb_rag_search"""+ return asyncio.run(multi_kb_rag_search(query, kb_names, **kwargs))+++if __name__ == "__main__":+ import sys++ if sys.platform == "win32":+ import io+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")++ # Test+ async def test():+ result = await multi_kb_rag_search(+ query="What is machine learning?",+ kb_names=None, # Search all+ top_k_per_kb=10,+ final_top_k=5,+ mode="naive",+ return_detailed=True,+ )++ print(f"Query: {result['query']}")+ print(f"Source KBs: {result['source_kbs']}")+ if "results" in result:+ print(f"Results ({len(result['results'])}):")+ for r in result["results"]:+ print(f" [{r['source_kb']}] score={r['rerank_score']:.3f}: {r['content'][:100]}...")+ else:+ print(f"Answer: {result['answer'][:500]}...")++ asyncio.run(test())diff --git a/src/tools/question/__init__.py b/src/tools/question/__init__.pyindex bff4d8558..d6e44e32a 100644--- a/src/tools/question/__init__.py+++ b/src/tools/question/__init__.py@@ -1,13 +1,21 @@"""Question Tools - Question generation system toolset-Tools for PDF parsing, question extraction, and exam mimicking.+Tools for PDF parsing, question extraction, and mimic entrypoint."""-from .exam_mimic import mimic_exam_questionsfrom .pdf_parser import parse_pdf_with_minerufrom .question_extractor import extract_questions_from_paper++async def mimic_exam_questions(*args, **kwargs):+ """+ Lazy wrapper to avoid circular imports with question coordinator.+ """+ from .exam_mimic import mimic_exam_questions as _mimic_exam_questions++ return await _mimic_exam_questions(*args, **kwargs)+__all__ = ["parse_pdf_with_mineru","extract_questions_from_paper",diff --git a/src/tools/question/exam_mimic.py b/src/tools/question/exam_mimic.pyindex 8cdc7775b..1c36ad9f7 100644--- a/src/tools/question/exam_mimic.py+++ b/src/tools/question/exam_mimic.py@@ -1,616 +1,74 @@#!/usr/bin/env python# -*- coding: utf-8 -*-"""-Reference-based exam-question generation system+Thin mimic entrypoint.-Workflow:-1. Parse the PDF exam (MinerU)-2. Extract question information (LLM)-3. Generate new questions per reference question (Agent)+The orchestration now lives in src/agents/question/coordinator.py."""from __future__ import annotations-import asyncio-from datetime import datetime-import json-import osfrom pathlib import Pathimport sys-from typing import TYPE_CHECKING, Any, Callable+from typing import Any, Callable-if TYPE_CHECKING:- from src.agents.question import AgentCoordinator--# Project root is 3 levels up from src/tools/question/project_root = Path(__file__).parent.parent.parent.parentsys.path.insert(0, str(project_root))-# Note: AgentCoordinator is imported inside functions to avoid circular import+from src.agents.question import AgentCoordinatorfrom src.services.llm.config import get_llm_config-from src.tools.question.pdf_parser import parse_pdf_with_mineru-from src.tools.question.question_extractor import extract_questions_from_paper-# Type alias for WebSocket callbackWsCallback = Callable[[str, dict[str, Any]], Any]-async def generate_question_from_reference(- reference_question: dict[str, Any], coordinator: AgentCoordinator, kb_name: str-) -> dict[str, Any]:- """- Generate a new question based on a reference entry.- """- # Build generation requirement that encodes the reference- requirement = {- "reference_question": reference_question["question_text"],- "has_images": len(reference_question.get("images", [])) > 0,- "kb_name": kb_name,- "allow_reject": False,- "additional_requirements": (- f"Reference question:\n{reference_question['question_text']}\n\n"- "Requirements:\n"- "1. Keep a similar difficulty level.\n"- "2. **Identify the core knowledge concept(s) of the reference and keep them EXACTLY the same. Do not introduce new advanced topics beyond what the reference question requires.**\n"- "3. **Change the scenario/objects/geometry; do not simply replace numbers or symbols.**\n"- "4. **Alter at least one part of the reasoning process or add a new sub-question "- "(e.g., extra calculation, analysis, or proof).**\n"- "5. Keep the problem entirely within the same mathematical scope as the reference (e.g., if the reference is planar line parametrization, you must stay within planar line parametrization and cannot escalate to surfaces or directional derivatives).\n"- "6. Ensure the prompt is rigorous, precise, and self-contained.\n"- "7. If the original problem references images, describe them in text.\n"- "8. Rejection is forbidden—you must complete the generation task.\n\n"- "Chain-of-thought guidance:\n"- "- Think step-by-step to plan the new scenario and reasoning before producing the final JSON.\n"- "- Do not reveal your reasoning; output only the final JSON."- ),- }-- # Trigger generation through the coordinator- result = await coordinator.generate_question(requirement)-- return result--async def mimic_exam_questions(pdf_path: str | None = None,paper_dir: str | None = None,- kb_name: str = None,+ kb_name: str | None = None,output_dir: str | None = None,max_questions: int | None = None,ws_callback: WsCallback | None = None,) -> dict[str, Any]:"""- End-to-end orchestration for reference-based question generation.-- Args:- pdf_path: Path to the PDF exam paper- paper_dir: Path to a pre-parsed exam directory- kb_name: Knowledge base name to use- output_dir: Output directory for generated questions- max_questions: Maximum number of questions to process- ws_callback: Optional async callback for WebSocket progress updates- Signature: async def callback(event_type: str, data: dict)+ Backward utility wrapper that delegates to the new coordinator pipeline."""-- async def send_progress(event_type: str, data: dict[str, Any]):- """Helper to send progress updates via WebSocket callback."""- if ws_callback:- try:- await ws_callback(event_type, data)- except Exception as e:- print(f"WebSocket callback error: {e}")-- print("=" * 80)- print("📚 Reference-based question generation system")- print("=" * 80)- print()-- # Validate argumentsif not pdf_path and not paper_dir:- await send_progress("error", {"content": "Either pdf_path or paper_dir must be provided."})return {"success": False, "error": "Either pdf_path or paper_dir must be provided."}-if pdf_path and paper_dir:- await send_progress("error", {"content": "pdf_path and paper_dir cannot be used together."})- return {- "success": False,- "error": "pdf_path and paper_dir cannot be used together. Choose only one.",- }-- latest_dir = None-- # If an already parsed exam directory is provided- if paper_dir:- await send_progress(- "progress",- {- "stage": "parsing",- "status": "locating",- "message": "Locating parsed exam directory...",- },- )-- print("🔍 Using parsed exam directory")- print("-" * 80)-- # Resolve relative names against reference_papers- # SECURITY FIX: Prevent Path Injection / Traversal- if os.path.isabs(paper_dir) or ".." in paper_dir:- error_msg = (- f"Invalid paper_dir: Absolute paths and traversal are not allowed. ({paper_dir})"- )- await send_progress("error", {"content": error_msg})- return {"success": False, "error": error_msg}-- paper_path = Path(paper_dir)-- # Candidate locations to search (including new location)- possible_paths = [- project_root- / "data"- / "user"- / "question"- / "mimic_papers"- / paper_dir, # New primary location- Path("question_agents/reference_papers") / paper_dir, # Legacy location- Path("reference_papers") / paper_dir,- ]-- latest_dir = None- for p in possible_paths:- if p.exists():- # Double check to ensure we didn't escape via symlink or subtle tricks- try:- resolved_p = p.resolve()- # Safe check: Ensure the resolved path is strictly inside the intended parent- # This is a basic check; for robust security, whitelist allowed parents explicitly if needed.- latest_dir = resolved_p- break- except Exception:- continue-- if not latest_dir:- error_msg = f"Exam directory not found: {paper_dir}"- await send_progress("error", {"content": error_msg})- return {- "success": False,- "error": f"{error_msg}\nSearched paths: {[str(p) for p in possible_paths]}",- }- # Note: latest_dir was already resolved in the loop above, no need to override-- # Ensure auto subdirectory exists- auto_dir = latest_dir / "auto"- if not auto_dir.exists():- error_msg = f"Invalid exam directory (missing auto folder): {latest_dir}"- await send_progress("error", {"content": error_msg})- return {- "success": False,- "error": error_msg,- }-- print(f"✓ Exam directory detected: {latest_dir.name}")- print(f" Full path: {latest_dir}")- print()-- await send_progress(- "progress",- {- "stage": "parsing",- "status": "complete",- "message": f"Using parsed exam: {latest_dir.name}",- },- )-- # If a PDF is provided, parse it first- elif pdf_path:- # Stage 1: Parsing PDF- await send_progress(- "progress",- {"stage": "parsing", "status": "running", "message": "Parsing PDF with MinerU..."},- )-- print("🔄 Step 1: parse the PDF exam")- print("-" * 80)-- # Use provided output_dir or default to mimic_papers- if output_dir:- output_base = Path(output_dir)- else:- output_base = project_root / "data" / "user" / "question" / "mimic_papers"- output_base.mkdir(parents=True, exist_ok=True)-- success = parse_pdf_with_mineru(pdf_path=pdf_path, output_base_dir=str(output_base))-- if not success:- await send_progress("error", {"content": "Failed to parse PDF with MinerU"})- return {"success": False, "error": "Failed to parse PDF"}-- print()-- print("🔍 Step 2: locating parsed results")- print("-" * 80)-- # Look in the new output directory (user/question/mimic_papers)- reference_papers_dir = output_base- subdirs = sorted(- [d for d in reference_papers_dir.iterdir() if d.is_dir()],- key=lambda x: x.stat().st_mtime,- reverse=True,- )-- if not subdirs:- await send_progress("error", {"content": "No parsed outputs were found"})- return {"success": False, "error": "No parsed outputs were found"}-- latest_dir = subdirs[0]- print(f"✓ Parsed folder: {latest_dir.name}")- print()-- await send_progress(- "progress",- {- "stage": "parsing",- "status": "complete",- "message": f"PDF parsed successfully: {latest_dir.name}",- },- )-- # Stage 2: Extract questions- await send_progress(- "progress",- {- "stage": "extracting",- "status": "running",- "message": "Extracting reference questions from exam...",- },- )-- print("🔄 Step 3: extract reference questions")- print("-" * 80)-- json_files = list(latest_dir.glob("*_questions.json"))-- if json_files:- print(f"✓ Found existing question file: {json_files[0].name}")- with open(json_files[0], encoding="utf-8") as f:- questions_data = json.load(f)- else:- print("📄 No question file found, starting extraction...")- success = extract_questions_from_paper(paper_dir=str(latest_dir), output_dir=None)-- if not success:- await send_progress("error", {"content": "Question extraction failed"})- return {"success": False, "error": "Question extraction failed"}-- json_files = list(latest_dir.glob("*_questions.json"))- if not json_files:- await send_progress(- "error", {"content": "Question JSON file not found after extraction"}- )- return {"success": False, "error": "Question JSON file not found after extraction"}-- with open(json_files[0], encoding="utf-8") as f:- questions_data = json.load(f)-- reference_questions = questions_data.get("questions", [])-- if max_questions:- reference_questions = reference_questions[:max_questions]-- print(f"✓ Loaded {len(reference_questions)} reference questions")- print()-- # Send reference questions info- await send_progress(- "progress",- {- "stage": "extracting",- "status": "complete",- "message": f"Extracted {len(reference_questions)} reference questions",- "total_questions": len(reference_questions),- "reference_questions": [- {- "number": q.get("question_number", str(i + 1)),- "preview": (- q["question_text"][:100] + "..."- if len(q["question_text"]) > 100- else q["question_text"]- ),- }- for i, q in enumerate(reference_questions)- ],- },+ return {"success": False, "error": "pdf_path and paper_dir cannot be used together."}++ llm_config = get_llm_config()+ coordinator = AgentCoordinator(+ api_key=llm_config.api_key,+ base_url=llm_config.base_url,+ api_version=getattr(llm_config, "api_version", None),+ kb_name=kb_name,+ output_dir=output_dir,)- # Stage 3: Generate mimic questions- await send_progress(- "progress",- {- "stage": "generating",- "status": "running",- "message": "Generating mimic questions...",- "current": 0,- "total": len(reference_questions),- },- )-- print("🔄 Step 4: generate new questions from references (parallel)")- print("-" * 80)-- # Lazy import to avoid circular import- from src.agents.question import AgentCoordinator- from src.services.config import load_config_with_main-- # Load config for parallel settings- config = load_config_with_main("question_config.yaml", project_root)- question_cfg = config.get("question", {})- max_parallel = question_cfg.get("max_parallel_questions", 3)-- print(f"📊 Processing {len(reference_questions)} questions with max {max_parallel} parallel")-- # Create semaphore for parallel control- semaphore = asyncio.Semaphore(max_parallel)-- # Track completed count- completed_count = 0- completed_lock = asyncio.Lock()-- async def generate_single_mimic(ref_question: dict, index: int) -> dict:- """Generate a single mimic question with semaphore control."""- nonlocal completed_count-- async with semaphore:- question_id = f"mimic_{index}"- ref_number = ref_question.get("question_number", str(index))-- # Send question start update- await send_progress(- "question_update",- {- "question_id": question_id,- "index": index,- "status": "generating",- "reference_number": ref_number,- "reference_preview": ref_question["question_text"][:80] + "...",- },- )-- print(f"\n📝 [{question_id}] Starting - Reference: {ref_number}")- print(f" Preview: {ref_question['question_text'][:80]}...")-- # Create a fresh coordinator for each question- llm_config = get_llm_config()- coordinator = AgentCoordinator(- api_key=llm_config.api_key,- base_url=llm_config.base_url,- api_version=getattr(llm_config, "api_version", None),- max_rounds=10,- kb_name=kb_name,- )-- try:- result = await generate_question_from_reference(- reference_question=ref_question, coordinator=coordinator, kb_name=kb_name- )-- async with completed_lock:- completed_count += 1- current_completed = completed_count-- if result.get("success"):- print(f"✓ [{question_id}] Generated in {result['rounds']} round(s)")-- result_data = {- "success": True,- "reference_question_number": ref_number,- "reference_question_text": ref_question["question_text"],- "reference_images": ref_question.get("images", []),- "generated_question": result["question"],- "validation": result["validation"],- "rounds": result["rounds"],- }-- # Send result update- await send_progress(- "result",- {- "question_id": question_id,- "index": index,- "success": True,- "question": result["question"],- "validation": result["validation"],- "rounds": result["rounds"],- "reference_question": ref_question["question_text"],- "current": current_completed,- "total": len(reference_questions),- },- )-- return result_data- else:- print(f"✗ [{question_id}] Failed: {result.get('error', 'Unknown error')}")-- error_data = {- "success": False,- "reference_question_number": ref_number,- "reference_question_text": ref_question["question_text"],- "error": result.get("error", "Unknown error"),- "reason": result.get("reason", ""),- }-- await send_progress(- "question_update",- {- "question_id": question_id,- "index": index,- "status": "failed",- "error": result.get("error", "Unknown error"),- "current": current_completed,- "total": len(reference_questions),- },- )-- return error_data-- except Exception as e:- print(f"✗ [{question_id}] Exception: {e!s}")-- async with completed_lock:- completed_count += 1- current_completed = completed_count-- await send_progress(- "question_update",- {- "question_id": question_id,- "index": index,- "status": "failed",- "error": str(e),- "current": current_completed,- "total": len(reference_questions),- },- )-- return {- "success": False,- "reference_question_number": ref_question.get("question_number", str(index)),- "reference_question_text": ref_question["question_text"],- "error": f"Exception: {e!s}",- }-- # Run all mimic generations in parallel- tasks = [generate_single_mimic(ref_q, i) for i, ref_q in enumerate(reference_questions, 1)]- results = await asyncio.gather(*tasks, return_exceptions=True)-- # Separate successes and failures- generated_questions = []- failed_questions = []-- for result in results:- if isinstance(result, Exception):- failed_questions.append({"error": str(result)})- elif result.get("success"):- generated_questions.append(result)- else:- failed_questions.append(result)-- print()- print("=" * 80)- print("📊 Generation summary")- print("=" * 80)- print(f"Reference questions: {len(reference_questions)}")- print(f"Successes: {len(generated_questions)}")- print(f"Failures: {len(failed_questions)}")-- if output_dir is None:- output_dir = latest_dir+ if ws_callback:+ async def _forward(data: dict[str, Any]) -> None:+ event_type = data.get("type", "progress")+ await ws_callback(event_type, data)+ coordinator.set_ws_callback(_forward)++ if pdf_path:+ summary = await coordinator.generate_from_exam(+ exam_paper_path=pdf_path,+ max_questions=max_questions or 10,+ paper_mode="upload",+ )else:- 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"{latest_dir.name}_{timestamp}_generated_questions.json"-- output_data = {- "reference_paper": latest_dir.name,- "kb_name": kb_name,- "total_reference_questions": len(reference_questions),- "successful_generations": len(generated_questions),- "failed_generations": len(failed_questions),- "generated_questions": generated_questions,- "failed_questions": failed_questions,- }-- with open(output_file, "w", encoding="utf-8") as f:- json.dump(output_data, f, ensure_ascii=False, indent=2)-- print(f"\n💾 Results saved to: {output_file}")- print()-- # Send summary- await send_progress(- "summary",- {- "total_reference": len(reference_questions),- "successful": len(generated_questions),- "failed": len(failed_questions),- "output_file": str(output_file),- },- )+ summary = await coordinator.generate_from_exam(+ exam_paper_path=paper_dir or "",+ max_questions=max_questions or 10,+ paper_mode="parsed",+ )return {- "success": True,- "output_file": str(output_file),- "total_reference_questions": len(reference_questions),- "generated_questions": generated_questions,- "failed_questions": failed_questions,+ "success": bool(summary.get("success", False)),+ "summary": summary,+ "generated_questions": [r.get("qa_pair", {}) for r in summary.get("results", [])],+ "failed_questions": [r for r in summary.get("results", []) if not r.get("success")],+ "total_reference_questions": summary.get("template_count", 0),}---async def main():- """Command-line entry point."""- import argparse-- parser = argparse.ArgumentParser(- description="Reference-based question generation CLI",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Examples:- python exam_mimic.py --pdf /path/to/exam.pdf --kb math2211- python exam_mimic.py --paper 2211asm1 --kb math2211- python exam_mimic.py --paper reference_papers/2211asm1 --kb math2211- python exam_mimic.py --paper 2211asm1 --kb math2211 --max-questions 3- python exam_mimic.py --paper 2211asm1 --kb math2211 -o ./output- """,- )-- # Input mode (mutually exclusive)- input_group = parser.add_mutually_exclusive_group(required=True)- input_group.add_argument(- "--pdf", type=str, help="Absolute path to the PDF exam (will be parsed)"- )-- input_group.add_argument(- "--paper",- type=str,- help="Name of a parsed exam directory (e.g., 2211asm1) or its absolute path",- )-- parser.add_argument("--kb", type=str, required=True, help="Knowledge base name")-- parser.add_argument(- "-o",- "--output",- type=str,- default=None,- help="Output directory (defaults to the exam folder)",- )-- parser.add_argument(- "--max-questions",- type=int,- default=None,- help="Maximum number of reference questions to process (testing)",- )-- args = parser.parse_args()-- # Execute the workflow- result = await mimic_exam_questions(- pdf_path=args.pdf,- paper_dir=args.paper,- kb_name=args.kb,- output_dir=args.output,- max_questions=args.max_questions,- )-- if result["success"]:- print("✓ Completed!")- sys.exit(0)- else:- print(f"✗ Failed: {result.get('error')}")- sys.exit(1)---if __name__ == "__main__":- asyncio.run(main())diff --git a/src/tools/reason.py b/src/tools/reason.pynew file mode 100644index 000000000..cbe625a7d--- /dev/null+++ b/src/tools/reason.py@@ -0,0 +1,116 @@+"""+Reason tool — stateless LLM deep-reasoning call.++When the solver agent needs deeper analysis, logical deduction, or synthesis+of already-gathered information but no external tool (RAG / web / code) is+required, it delegates to this tool. A single, stateless LLM call produces+a step-by-step reasoning trace that is returned as the observation.++Usage:+ from src.tools.reason import reason++ result = await reason(+ query="Derive the closed-form solution for ...",+ context="Original question: ... \\nPlan: ...",+ )+ print(result["answer"])+"""++from __future__ import annotations++import logging+from typing import Any++logger = logging.getLogger(__name__)++_SYSTEM_PROMPT = """\+You are a deep reasoning engine. You receive a problem context and a \+specific reasoning focus. Your job is to perform rigorous, step-by-step \+logical analysis and arrive at a clear conclusion.++Guidelines:+- Think carefully and systematically.+- Show your reasoning chain explicitly — number each step.+- If mathematical derivation is needed, show each algebraic step.+- If logical deduction is needed, state premises and inferences clearly.+- Synthesize any provided context but do NOT fabricate facts or cite \+ sources you do not have.+- Conclude with a concise, clearly-labeled answer or conclusion.\+"""+++async def reason(+ query: str,+ context: str = "",+ api_key: str | None = None,+ base_url: str | None = None,+ model: str | None = None,+ max_tokens: int | None = None,+ temperature: float | None = None,+) -> dict[str, Any]:+ """Perform deep reasoning via a single stateless LLM call.++ Args:+ query: The reasoning focus — what needs to be analysed or derived.+ context: Optional surrounding context (original question, plan, prior+ observations) assembled by the caller.+ api_key: LLM API key (falls back to global config).+ base_url: LLM base URL (falls back to global config).+ model: Model name (falls back to global config).+ max_tokens: Max output tokens (falls back to global config / agents.yaml).+ temperature: Sampling temperature (falls back to global config / agents.yaml).++ Returns:+ dict with keys ``query``, ``answer``, ``model``.+ """+ from src.services.llm import complete as llm_complete+ from src.services.llm.config import get_llm_config+ from src.services.llm import get_token_limit_kwargs+ from src.services.config import get_agent_params++ # ---- resolve LLM config ------------------------------------------------+ try:+ llm_cfg = get_llm_config()+ api_key = api_key or llm_cfg.api_key+ base_url = base_url or llm_cfg.base_url+ model = model or llm_cfg.model+ except ValueError:+ pass # caller must supply explicitly++ if not model:+ raise ValueError("No model configured for reason tool")++ agent_params = get_agent_params("solve")+ if max_tokens is None:+ max_tokens = agent_params.get("max_tokens", 4096)+ if temperature is None:+ temperature = agent_params.get("temperature", 0.0)++ # ---- build user prompt --------------------------------------------------+ parts: list[str] = []+ if context:+ parts.append(f"## Context\n{context}")+ parts.append(f"## Reasoning Focus\n{query}")+ user_prompt = "\n\n".join(parts)++ # ---- call LLM -----------------------------------------------------------+ kwargs: dict[str, Any] = {"temperature": temperature}+ if max_tokens:+ kwargs.update(get_token_limit_kwargs(model, max_tokens))++ logger.debug("reason tool: model=%s, query=%s...", model, query[:80])++ answer = await llm_complete(+ prompt=user_prompt,+ system_prompt=_SYSTEM_PROMPT,+ model=model,+ api_key=api_key,+ base_url=base_url,+ **kwargs,+ )++ return {+ "query": query,+ "answer": answer.strip(),+ "model": model,+ }diff --git a/src/tools/test_embedding.py b/src/tools/test_embedding.pynew file mode 100644index 000000000..b8ed9e8a1--- /dev/null+++ b/src/tools/test_embedding.py@@ -0,0 +1,128 @@+#!/usr/bin/env python3+"""+Quick embedding smoke test.++Usage examples:+ python3 src/tools/test_embedding.py --text "hello world"+ python3 src/tools/test_embedding.py --text "test" --repeat 3 --show-config+ python3 src/tools/test_embedding.py --direct+"""++from __future__ import annotations++import argparse+import asyncio+import json+import sys+from pathlib import Path++import httpx+from dotenv import load_dotenv++# Make project imports work when run as a script+PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))++load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)+load_dotenv(PROJECT_ROOT / ".env", override=False)++from src.services.embedding.client import get_embedding_client, reset_embedding_client+from src.services.embedding.config import get_embedding_config+++def _mask_key(key: str) -> str:+ if not key:+ return "(empty)"+ if len(key) <= 10:+ return "*" * len(key)+ return f"{key[:6]}...{key[-4:]}"+++async def run_client_test(text: str, repeat: int) -> None:+ reset_embedding_client()+ client = get_embedding_client()+ cfg = get_embedding_config()++ inputs = [f"{text} #{i+1}" if repeat > 1 else text for i in range(repeat)]+ print("[ClientTest] Calling EmbeddingClient.embed(...)")+ vectors = await client.embed(inputs)++ dim = len(vectors[0]) if vectors else 0+ print(f"[ClientTest] OK: vectors={len(vectors)}, dim={dim}, model={cfg.model}")+ if vectors:+ preview = vectors[0][:8]+ print(f"[ClientTest] First vector preview (8 dims): {preview}")+++async def run_direct_test(text: str) -> None:+ cfg = get_embedding_config()+ url = f"{(cfg.base_url or '').rstrip('/')}/embeddings"+ headers = {+ "Content-Type": "application/json",+ "Authorization": f"Bearer {cfg.api_key}",+ }+ payload = {+ "input": [text],+ "model": cfg.model,+ "encoding_format": "float",+ }+ if cfg.dim:+ payload["dimensions"] = cfg.dim++ print(f"[DirectTest] POST {url}")+ async with httpx.AsyncClient(timeout=cfg.request_timeout) as client:+ resp = await client.post(url, headers=headers, json=payload)+ print(f"[DirectTest] status={resp.status_code}")++ body_text = resp.text.strip()+ try:+ body_json = resp.json()+ print("[DirectTest] JSON response:")+ print(json.dumps(body_json, ensure_ascii=False, indent=2)[:4000])+ except Exception:+ print("[DirectTest] Non-JSON response:")+ print(body_text[:2000])+++async def main() -> None:+ parser = argparse.ArgumentParser(description="Quick embedding smoke test")+ parser.add_argument("--text", default="hello world", help="Input text for embedding")+ parser.add_argument("--repeat", type=int, default=1, help="How many inputs to send")+ parser.add_argument(+ "--show-config",+ action="store_true",+ help="Print effective embedding config before testing",+ )+ parser.add_argument(+ "--direct",+ action="store_true",+ help="Also directly call /embeddings endpoint and print raw response",+ )+ args = parser.parse_args()++ cfg = get_embedding_config()+ if args.show_config:+ print("[Config]")+ print(f" binding={cfg.binding}")+ print(f" host={cfg.base_url}")+ print(f" model={cfg.model}")+ print(f" dim={cfg.dim}")+ print(f" timeout={cfg.request_timeout}")+ print(f" batch_size={cfg.batch_size}")+ print(f" api_key={_mask_key(cfg.api_key)}")++ try:+ await run_client_test(args.text, max(1, args.repeat))+ except Exception as e:+ print(f"[ClientTest] FAILED: {type(e).__name__}: {e}")++ if args.direct:+ try:+ await run_direct_test(args.text)+ except Exception as e:+ print(f"[DirectTest] FAILED: {type(e).__name__}: {e}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/src/tools/test_llm_api.py b/src/tools/test_llm_api.pynew file mode 100644index 000000000..9043480ae--- /dev/null+++ b/src/tools/test_llm_api.py@@ -0,0 +1,128 @@+#!/usr/bin/env python3+"""+Quick LLM API smoke test.++Usage:+ python3 src/tools/test_llm_api.py --prompt "Say hello"+ python3 src/tools/test_llm_api.py --show-config+ python3 src/tools/test_llm_api.py --direct --show-config+"""++from __future__ import annotations++import argparse+import asyncio+import json+import sys+from pathlib import Path++import httpx+from dotenv import load_dotenv++# Make project imports work when executed directly.+PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))++load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)+load_dotenv(PROJECT_ROOT / ".env", override=False)++from src.services.llm import factory+from src.services.llm.config import clear_llm_config_cache, get_llm_config+++def _mask_key(key: str) -> str:+ if not key:+ return "(empty)"+ if len(key) <= 10:+ return "*" * len(key)+ return f"{key[:6]}...{key[-4:]}"+++async def run_factory_test(prompt: str, system_prompt: str, max_tokens: int, temperature: float) -> None:+ cfg = get_llm_config()+ print(f"[FactoryTest] model={cfg.model}")+ print("[FactoryTest] Calling factory.complete(...)")+ answer = await factory.complete(+ prompt=prompt,+ system_prompt=system_prompt,+ max_tokens=max_tokens,+ temperature=temperature,+ )+ text = (answer or "").strip()+ print(f"[FactoryTest] OK (model={cfg.model})")+ print("[FactoryTest] Response preview:")+ print(text[:1000] if text else "(empty)")+++async def run_direct_test(prompt: str, system_prompt: str, max_tokens: int, temperature: float) -> None:+ cfg = get_llm_config()+ url = f"{(cfg.base_url or '').rstrip('/')}/chat/completions"+ headers = {+ "Content-Type": "application/json",+ "Authorization": f"Bearer {cfg.api_key}",+ }+ payload = {+ "model": cfg.model,+ "messages": [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": prompt},+ ],+ "max_tokens": max_tokens,+ "temperature": temperature,+ }++ print(f"[DirectTest] POST {url}")+ async with httpx.AsyncClient(timeout=120) as client:+ resp = await client.post(url, headers=headers, json=payload)+ print(f"[DirectTest] status={resp.status_code}")++ try:+ body = resp.json()+ print("[DirectTest] JSON response:")+ print(json.dumps(body, ensure_ascii=False, indent=2)[:4000])+ except Exception:+ print("[DirectTest] Non-JSON response:")+ print(resp.text[:2000])+++async def main() -> None:+ parser = argparse.ArgumentParser(description="Quick LLM API smoke test")+ parser.add_argument("--prompt", default="Briefly explain what a derivative is.")+ parser.add_argument("--system", default="You are a concise helpful assistant.")+ parser.add_argument("--max-tokens", type=int, default=256)+ parser.add_argument("--temperature", type=float, default=0.2)+ parser.add_argument("--show-config", action="store_true")+ parser.add_argument(+ "--direct",+ action="store_true",+ help="Also call /chat/completions endpoint directly and print raw response.",+ )+ args = parser.parse_args()++ clear_llm_config_cache()+ cfg = get_llm_config()++ if args.show_config:+ print("[Config]")+ print(f" binding={cfg.binding}")+ print(f" host={cfg.base_url}")+ print(f" model={cfg.model}")+ print(f" max_concurrency={cfg.max_concurrency}")+ print(f" requests_per_minute={cfg.requests_per_minute}")+ print(f" api_key={_mask_key(cfg.api_key)}")++ try:+ await run_factory_test(args.prompt, args.system, args.max_tokens, args.temperature)+ except Exception as e:+ print(f"[FactoryTest] FAILED: {type(e).__name__}: {e}")++ if args.direct:+ try:+ await run_direct_test(args.prompt, args.system, args.max_tokens, args.temperature)+ except Exception as e:+ print(f"[DirectTest] FAILED: {type(e).__name__}: {e}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/start.py b/start.pynew file mode 100644index 000000000..9634f9c56--- /dev/null+++ b/start.py@@ -0,0 +1,690 @@+#!/usr/bin/env python+"""+DeepTutor CLI Launcher++Unified entry point for:+1. Solver system (same logic as ``python -m src.agents.solve.cli``)+2. Question generation system (same logic as ``python src/agents/question/cli.py``)+"""++from __future__ import annotations++import asyncio+import sys+from pathlib import Path++if sys.platform == "win32":+ import io++ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")++PROJECT_ROOT = Path(__file__).resolve().parent+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 src.knowledge.manager import KnowledgeBaseManager+from src.logging import get_logger+from src.services.llm.config import get_llm_config++logger = get_logger("CLI", console_output=True, file_output=True)++# ── ANSI helpers (reused from question CLI) ──────────────────────────++BOLD = "\033[1m"+DIM = "\033[2m"+GREEN = "\033[92m"+YELLOW = "\033[93m"+RED = "\033[91m"+CYAN = "\033[96m"+MAGENTA = "\033[95m"+RESET = "\033[0m"+CHECK = f"{GREEN}✓{RESET}"+CROSS = f"{RED}✗{RESET}"+ARROW = f"{CYAN}→{RESET}"+++def _hr(char: str = "─", width: int = 70) -> str:+ return f"{DIM}{char * width}{RESET}"+++def _header(title: str) -> None:+ print(f"\n{_hr('━')}")+ print(f" {BOLD}{title}{RESET}")+ print(_hr("━"))+++# ── Shared infrastructure ────────────────────────────────────────────+++def _list_knowledge_bases() -> list[str]:+ try:+ mgr = KnowledgeBaseManager()+ return mgr.list_knowledge_bases()+ except Exception:+ kb_dir = PROJECT_ROOT / "data" / "knowledge_bases"+ if kb_dir.exists():+ return [d.name for d in kb_dir.iterdir() if d.is_dir() and not d.name.startswith(".")]+ return []+++def _select_kb(current: str = "ai-textbook") -> str:+ kbs = _list_knowledge_bases()+ if not kbs:+ print(f" {YELLOW}未找到知识库,使用默认: {current}{RESET}")+ return current++ print(f"\n {BOLD}可用知识库:{RESET}")+ for i, name in enumerate(kbs, 1):+ marker = f" {CYAN}<-{RESET}" if name == current else ""+ print(f" {CYAN}{i}{RESET}) {name}{marker}")+ print(f" {CYAN}0{RESET}) 保持当前 ({current})")++ while True:+ raw = input(f" 选择 [{DIM}1{RESET}]: ").strip()+ if not raw:+ return kbs[0]+ if raw == "0":+ return current+ try:+ idx = int(raw) - 1+ if 0 <= idx < len(kbs):+ return kbs[idx]+ except ValueError:+ if raw in kbs:+ return raw+ print(f" {RED}无效选择,请重试。{RESET}")+++async def _ensure_personalization() -> bool:+ """Start EventBus and PersonalizationService for in-process memory."""+ ok = True+ try:+ from src.core.event_bus import get_event_bus++ bus = get_event_bus()+ await bus.start()+ except Exception as exc:+ print(f"\n {RED}WARNING: EventBus failed to start: {exc}{RESET}")+ ok = False+ try:+ from src.personalization.service import get_personalization_service++ svc = get_personalization_service()+ await svc.start()+ except Exception as exc:+ print(f"\n {RED}WARNING: PersonalizationService failed to start: {exc}{RESET}")+ ok = False+ return ok+++async def _flush_events() -> None:+ """Wait for EventBus to finish processing all pending events."""+ try:+ from src.core.event_bus import get_event_bus++ bus = get_event_bus()+ await bus.flush(timeout=60.0)+ except Exception:+ pass+++# ── Solve mode ───────────────────────────────────────────────────────+++async def run_solve_mode(kb_name: str) -> None:+ """Solve a question — mirrors ``src.agents.solve.cli`` logic."""+ _header("解题系统 (Solver)")++ kb_name = _select_kb(current=kb_name)+ print(f" {CHECK} 知识库: {BOLD}{kb_name}{RESET}")++ language = input(f" 语言 (en/zh) [{DIM}en{RESET}]: ").strip().lower() or "en"+ if language not in {"en", "zh"}:+ language = "en"++ print(f"\n 请输入问题 (多行输入,空行结束):")+ print(_hr())++ lines: list[str] = []+ while True:+ line = input()+ if not line:+ break+ lines.append(line)++ if not lines:+ print(f" {YELLOW}未输入问题,返回主菜单{RESET}")+ return++ question = "\n".join(lines)++ print(f"\n {ARROW} 模式: Plan → ReAct → Write")+ print(f" {DIM}正在初始化 Solver...{RESET}")++ try:+ from src.agents.solve import MainSolver++ solver = MainSolver(kb_name=kb_name, language=language)+ await solver.ainit()++ result = await solver.solve(question)++ _header("解题完成")+ print(f" 输出目录: {CYAN}{result['output_dir']}{RESET}")+ print(f" 步骤完成: {result.get('completed_steps', '?')}/{result.get('total_steps', '?')}")+ print(f" ReAct 条目: {result.get('total_react_entries', '?')}")+ print(f" 计划修订: {result.get('plan_revisions', 0)}")++ final_answer = result.get("final_answer", "")+ if final_answer:+ print(f"\n {BOLD}答案预览:{RESET}")+ print(_hr())+ preview_lines = final_answer.split("\n")[:20]+ preview = "\n".join(preview_lines)+ if len(final_answer.split("\n")) > 20:+ preview += f"\n\n {DIM}... (完整内容见输出文件) ...{RESET}"+ print(preview)+ print(_hr())++ except Exception as e:+ _header("解题失败")+ print(f" {RED}{e}{RESET}")+ import traceback+ traceback.print_exc()++ print(f" {DIM}同步记忆...{RESET}", end="", flush=True)+ await _flush_events()+ print(f" {CHECK}")+++# ── Question generation mode ─────────────────────────────────────────+++async def _cli_progress(data: dict) -> None:+ """Real-time progress callback for question generation."""+ msg_type = data.get("type", "")++ if msg_type == "progress":+ stage = data.get("stage", "")+ if stage == "idea_loop":+ rd = data.get("current_round", "")+ mx = data.get("max_rounds", "")+ if rd:+ print(f" {MAGENTA}🔄 创意循环{RESET} 第 {rd}/{mx} 轮")+ elif stage == "generating":+ cur = data.get("current", "")+ tot = data.get("total", "")+ qid = data.get("question_id", "")+ if cur and tot:+ print(f" {CYAN}📝 生成中{RESET} {cur}/{tot} {DIM}{qid}{RESET}")+ elif stage == "complete":+ comp = data.get("completed", "?")+ tot = data.get("total", "?")+ print(f" {GREEN}✅ 完成{RESET} {comp}/{tot}")+ elif stage in ("parsing", "extracting", "uploading"):+ status = data.get("status", "")+ print(f" {YELLOW}📄 {stage}{RESET} {status}")+ elif msg_type == "templates_ready":+ count = data.get("count", 0)+ print(f" {GREEN}📋 模板就绪{RESET} {count} 个")+ elif msg_type == "idea_round":+ rd = data.get("round", "?")+ cont = data.get("continue_loop", False)+ status = "继续改进" if cont else "已确定"+ print(f" {MAGENTA}💡 创意第 {rd} 轮{RESET} → {status}")+ elif msg_type == "question_update":+ qid = data.get("question_id", "")+ attempt = data.get("attempt", 1)+ max_att = data.get("max_attempts", "?")+ print(f" {CYAN}⚙ {qid}{RESET} 生成 (尝试 {attempt}/{max_att})")+ elif msg_type == "validating":+ qid = data.get("question_id", "")+ decision = data.get("validation", {}).get("decision", "?")+ icon = CHECK if decision == "approve" else CROSS+ print(f" {YELLOW}🔍 {qid}{RESET} 验证 → {icon} {decision}")+ elif msg_type == "result":+ qid = data.get("question_id", "")+ approved = data.get("validation", {}).get("approved", False)+ attempts = data.get("attempts", 1)+ icon = CHECK if approved else CROSS+ print(f" {icon} {BOLD}{qid}{RESET} ({attempts} 次尝试)")+++def _print_question_summary(summary: dict) -> None:+ _header("出题结果摘要")+ success = summary.get("success", False)+ status_icon = f"{GREEN}SUCCESS{RESET}" if success else f"{RED}FAILED{RESET}"+ print(f" 状态: {status_icon}")+ print(f" 来源: {summary.get('source', '?')}")+ print(f" 请求: {summary.get('requested', '?')} 道")+ print(f" 成功: {GREEN}{summary.get('completed', 0)}{RESET}")+ print(f" 失败: {RED}{summary.get('failed', 0)}{RESET}")++ batch_dir = summary.get("batch_dir")+ if batch_dir:+ print(f" 输出目录: {CYAN}{batch_dir}{RESET}")++ results = summary.get("results", []) or []+ if results:+ print(f"\n {BOLD}题目预览:{RESET}")+ for i, item in enumerate(results, 1):+ qa = item.get("qa_pair", {})+ approved = item.get("success", False)+ icon = CHECK if approved else CROSS+ q_type = qa.get("question_type", "unknown")+ question = str(qa.get("question", "")).replace("\n", " ")[:100]+ attempts = len(item.get("attempts", []))+ print(f" {icon} {i}. [{q_type}] {DIM}({attempts}次){RESET}")+ print(f" {question}...")+ print()+++def _prompt_non_empty(message: str, default: str | None = None) -> str:+ suffix = f" [{DIM}{default}{RESET}]" if default else ""+ while True:+ raw = input(f" {message}{suffix}: ").strip()+ if raw:+ return raw+ if default is not None:+ return default+ print(f" {RED}输入不能为空,请重试。{RESET}")+++def _prompt_int(message: str, default: int) -> int:+ while True:+ raw = input(f" {message} [{DIM}{default}{RESET}]: ").strip()+ if not raw:+ return default+ try:+ value = int(raw)+ if value > 0:+ return value+ except ValueError:+ pass+ print(f" {RED}请输入正整数。{RESET}")+++# ── Interactive answering session ─────────────────────────────────────+++def _display_question(idx: int, qa: dict) -> None:+ q_type = qa.get("question_type", "written")+ question_text = qa.get("question", "")+ options = qa.get("options") or {}++ print(f"\n {BOLD}题目 {idx}{RESET} [{q_type}]")+ print(_hr())+ print(f" {question_text}")++ if options:+ print()+ for key in sorted(options.keys()):+ print(f" {CYAN}{key}{RESET}. {options[key]}")+ print(_hr())+++def _judge_answer(user_answer: str, correct_answer: str, q_type: str) -> str:+ ua = user_answer.strip().lower()+ ca = correct_answer.strip().lower()+ if not ua:+ return "skipped"+ if q_type == "choice":+ ua_letter = ua.strip("().)( ").upper()+ ca_letter = ca.strip("().)( ").upper()+ if ua_letter and ca_letter:+ return "correct" if ua_letter == ca_letter else "wrong"+ if ua == ca:+ return "correct"+ if ua in ca or ca in ua:+ return "partial"+ return "pending"+++async def _run_answer_session(summary: dict) -> None:+ results = summary.get("results", []) or []+ approved_results = [r for r in results if r.get("success")]+ if not approved_results:+ print(f" {YELLOW}没有可用的题目进行作答。{RESET}")+ return++ batch_dir = summary.get("batch_dir", "")+ trace_id = Path(batch_dir).name if batch_dir else ""++ _header(f"答题环节 ({len(approved_results)} 道题)")+ print(f" {DIM}直接回车可跳过该题,输入 /quit 退出答题{RESET}\n")++ answers_recorded = 0+ correct_count = 0+ wrong_count = 0+ skipped_count = 0++ for i, item in enumerate(approved_results, 1):+ qa = item.get("qa_pair", {})+ question_id = qa.get("question_id", f"q_{i}")+ q_type = qa.get("question_type", "written")+ correct_answer = str(qa.get("correct_answer", ""))++ _display_question(i, qa)++ try:+ user_input = input(f" {ARROW} 你的回答: ").strip()+ except (EOFError, KeyboardInterrupt):+ print(f"\n {YELLOW}答题中断。{RESET}")+ break++ if user_input.lower() in ("/quit", "/exit", "/q"):+ print(f" {DIM}退出答题。{RESET}")+ break++ if not user_input:+ skipped_count += 1+ print(f" {DIM}(已跳过){RESET}")+ continue++ judged = _judge_answer(user_input, correct_answer, q_type)++ if judged == "correct":+ print(f" {CHECK} {GREEN}正确!{RESET}")+ correct_count += 1+ elif judged == "wrong":+ print(f" {CROSS} {RED}错误{RESET} 正确答案: {GREEN}{correct_answer}{RESET}")+ wrong_count += 1+ elif judged == "partial":+ print(f" {YELLOW}~ 部分匹配{RESET} 参考答案: {correct_answer}")+ elif judged == "skipped":+ skipped_count += 1+ print(f" {DIM}(已跳过){RESET}")+ continue+ else:+ print(f" {YELLOW}? 待判定{RESET} 参考答案: {correct_answer}")++ explanation = qa.get("explanation", "")+ if explanation:+ short_exp = explanation[:200]+ if len(explanation) > 200:+ short_exp += "..."+ print(f" {DIM}解析: {short_exp}{RESET}")++ if trace_id:+ try:+ from src.personalization.service import get_personalization_service++ svc = get_personalization_service()+ ok = await svc.record_user_answer(+ trace_id=trace_id,+ question_id=question_id,+ user_answer=user_input,+ judged_result=judged,+ )+ if ok:+ answers_recorded += 1+ except Exception:+ pass++ if answers_recorded > 0 and trace_id:+ print(f"\n {DIM}同步答题记忆...{RESET}", end="", flush=True)+ await _flush_events()+ try:+ from src.personalization.service import get_personalization_service++ svc = get_personalization_service()+ await svc.flush_memory_agents(trace_id)+ except Exception:+ pass+ print(f" {CHECK}")++ _header("答题结果")+ total = correct_count + wrong_count + skipped_count+ print(f" 总计: {total} 题")+ print(f" 正确: {GREEN}{correct_count}{RESET}")+ print(f" 错误: {RED}{wrong_count}{RESET}")+ print(f" 跳过: {DIM}{skipped_count}{RESET}")+ if answers_recorded > 0:+ print(f" {CHECK} 已记录 {answers_recorded} 条答题记录到记忆系统")+ print()+++# ── Coordinator builder ──────────────────────────────────────────────+++def _build_coordinator(kb_name: str, output_dir: str, language: str):+ from src.agents.question import AgentCoordinator+ from src.services.llm.config import get_llm_config as _get_llm++ try:+ cfg = _get_llm()+ return AgentCoordinator(+ api_key=cfg.api_key,+ base_url=cfg.base_url,+ api_version=getattr(cfg, "api_version", None),+ kb_name=kb_name,+ output_dir=output_dir,+ language=language,+ )+ except Exception:+ return AgentCoordinator(+ kb_name=kb_name, output_dir=output_dir, language=language,+ )+++async def run_question_mode(kb_name: str) -> None:+ """Generate questions — mirrors ``src/agents/question/cli.py`` logic."""+ _header("出题系统 (Question Generator)")++ kb_name = _select_kb(current=kb_name)+ print(f" {CHECK} 知识库: {BOLD}{kb_name}{RESET}")++ language = input(f" 语言 (en/zh) [{DIM}zh{RESET}]: ").strip().lower() or "zh"+ if language not in {"en", "zh"}:+ language = "zh"++ default_output = str(PROJECT_ROOT / "data" / "user" / "question")+ output_dir = _prompt_non_empty("输出目录", default_output)++ coordinator = _build_coordinator(kb_name=kb_name, output_dir=output_dir, language=language)++ print(f"\n {BOLD}请选择模式:{RESET}")+ print(f" {CYAN}1{RESET}) Topic 模式 — 基于主题生成")+ print(f" {CYAN}2{RESET}) Mimic 模式 — 基于试卷仿题")++ mode_choice = input(f" {ARROW} ").strip()++ if mode_choice == "2":+ await _run_mimic_submode(coordinator)+ else:+ await _run_topic_submode(coordinator)+++async def _run_topic_submode(coordinator) -> None:+ _header("Topic 模式")+ user_topic = _prompt_non_empty("主题 (如: Lagrange multipliers)")+ preference = input(f" 偏好 (可留空): ").strip()+ num_questions = _prompt_int("题目数量", 3)++ print(f"\n {ARROW} 开始生成 {BOLD}{num_questions}{RESET} 道题...")+ print(_hr())++ coordinator.set_ws_callback(_cli_progress)+ summary = await coordinator.generate_from_topic(+ user_topic=user_topic,+ preference=preference,+ num_questions=num_questions,+ )++ print(f" {DIM}同步记忆系统...{RESET}", end="", flush=True)+ await _flush_events()+ print(f" {CHECK}")++ _print_question_summary(summary)++ approved = [r for r in (summary.get("results") or []) if r.get("success")]+ if approved:+ try:+ ans_choice = input(f" {ARROW} 是否开始答题? (y/n) [{DIM}y{RESET}]: ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ ans_choice = "n"+ if ans_choice != "n":+ await _run_answer_session(summary)+++async def _run_mimic_submode(coordinator) -> None:+ _header("Mimic 模式")+ mode = _prompt_non_empty("输入模式 [upload/parsed]", "parsed").lower()+ if mode not in {"upload", "parsed"}:+ print(f" {YELLOW}无效模式,使用 parsed。{RESET}")+ mode = "parsed"++ if mode == "upload":+ exam_path = _prompt_non_empty("PDF 路径")+ else:+ exam_path = _prompt_non_empty("已解析试卷目录路径")++ max_questions = _prompt_int("最大题目数", 5)++ print(f"\n {ARROW} 开始解析并生成...")+ print(_hr())++ coordinator.set_ws_callback(_cli_progress)+ summary = await coordinator.generate_from_exam(+ exam_paper_path=exam_path,+ max_questions=max_questions,+ paper_mode=mode,+ )++ print(f" {DIM}同步记忆系统...{RESET}", end="", flush=True)+ await _flush_events()+ print(f" {CHECK}")++ _print_question_summary(summary)++ approved = [r for r in (summary.get("results") or []) if r.get("success")]+ if approved:+ try:+ ans_choice = input(f" {ARROW} 是否开始答题? (y/n) [{DIM}y{RESET}]: ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ ans_choice = "n"+ if ans_choice != "n":+ await _run_answer_session(summary)+++# ── Settings ─────────────────────────────────────────────────────────+++def show_settings() -> None:+ _header("系统设置")++ try:+ llm_config = get_llm_config()+ print(f" {BOLD}LLM 配置:{RESET}")+ print(f" 模型: {llm_config.model or 'N/A'}")+ print(f" 端点: {llm_config.base_url or 'N/A'}")+ print(f" API Key: {'已配置' if llm_config.api_key else '未配置'}")+ except Exception as e:+ print(f" {RED}加载失败: {e}{RESET}")++ kbs = _list_knowledge_bases()+ print(f"\n {BOLD}可用知识库:{RESET}")+ for i, kb in enumerate(kbs, 1):+ print(f" {i}. {kb}")++ print(f"\n {BOLD}配置文件:{RESET}")+ for name in [".env", "DeepTutor.env"]:+ p = PROJECT_ROOT / name+ status = f"{GREEN}✓{RESET}" if p.exists() else f"{RED}✗{RESET}"+ print(f" {status} {p}")++ print(f"\n {DIM}提示: 直接编辑 .env 文件即可修改配置{RESET}")+ input(f"\n 按回车返回主菜单...")+++# ── Main loop ────────────────────────────────────────────────────────+++async def run() -> None:+ print(f"\n{BOLD}{'=' * 70}{RESET}")+ print(f" {BOLD}{CYAN}DeepTutor Evaluation System{RESET}")+ print(f"{BOLD}{'=' * 70}{RESET}")++ try:+ from src.services.setup import init_user_directories++ init_user_directories(PROJECT_ROOT)+ except Exception as e:+ print(f" {YELLOW}WARNING: 初始化用户目录失败: {e}{RESET}")++ try:+ llm_config = get_llm_config()+ if not llm_config.api_key:+ print(f" {RED}ERROR: 未配置 API Key,请检查 .env 文件{RESET}")+ sys.exit(1)+ except ValueError as e:+ print(f" {RED}ERROR: {e}{RESET}")+ sys.exit(1)++ print(f" {DIM}正在初始化记忆系统...{RESET}", end="", flush=True)+ mem_ok = await _ensure_personalization()+ print(f" {CHECK}" if mem_ok else f" {CROSS}")++ default_kb = "ai-textbook"++ while True:+ try:+ print(f"\n {BOLD}请选择功能:{RESET}")+ print(f" {CYAN}1{RESET}) 解题系统 (Solver)")+ print(f" {CYAN}2{RESET}) 出题系统 (Question Generator)")+ print(f" {CYAN}3{RESET}) 系统设置 (Settings)")+ print(f" {CYAN}q{RESET}) 退出")+ choice = input(f" {ARROW} ").strip().lower()++ if choice == "1":+ await run_solve_mode(default_kb)+ elif choice == "2":+ await run_question_mode(default_kb)+ elif choice == "3":+ show_settings()+ continue+ elif choice in {"q", "quit", "exit", "4"}:+ print(f"\n {DIM}感谢使用 DeepTutor!{RESET}\n")+ break+ else:+ print(f" {RED}无效选项,请重试。{RESET}")+ continue++ cont = input(f"\n 继续使用? (y/n) [{DIM}y{RESET}]: ").strip().lower()+ if cont == "n":+ print(f"\n {DIM}感谢使用 DeepTutor!{RESET}\n")+ break++ except KeyboardInterrupt:+ print(f"\n\n {YELLOW}程序中断。{RESET}\n")+ break+ except Exception as e:+ print(f"\n {RED}错误: {e}{RESET}")+ import traceback+ traceback.print_exc()++ # Cleanup EventBus+ try:+ from src.core.event_bus import get_event_bus++ await get_event_bus().stop()+ except Exception:+ pass+++def main():+ try:+ asyncio.run(run())+ except Exception as e:+ print(f" {RED}启动失败: {e}{RESET}")+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/tests/iso_solve/__init__.py b/tests/iso_solve/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/iso_solve/test_evaluation.py b/tests/iso_solve/test_evaluation.pynew file mode 100644index 000000000..e5aab056b--- /dev/null+++ b/tests/iso_solve/test_evaluation.py@@ -0,0 +1,983 @@+"""+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"diff --git a/tests/services/llm/test_llm_live.py b/tests/services/llm/test_llm_live.pynew file mode 100644index 000000000..2817b106c--- /dev/null+++ b/tests/services/llm/test_llm_live.py@@ -0,0 +1,166 @@+"""+Live LLM connectivity test.++Run directly to verify your .env / config is working:++ python tests/services/llm/test_llm_live.py+ python tests/services/llm/test_llm_live.py --stream # also test streaming+ python tests/services/llm/test_llm_live.py --model gpt-4o --base-url https://api.openai.com/v1 --api-key sk-xxx+"""++from __future__ import annotations++import argparse+import asyncio+import sys+import time+from pathlib import Path++# ensure project root is on sys.path+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))++BOLD = "\033[1m"+DIM = "\033[2m"+GREEN = "\033[32m"+RED = "\033[31m"+CYAN = "\033[36m"+YELLOW = "\033[33m"+RESET = "\033[0m"+CHECK = f"{GREEN}✓{RESET}"+CROSS = f"{RED}✗{RESET}"+++def _mask(secret: str | None, visible: int = 8) -> str:+ if not secret:+ return "(empty)"+ if len(secret) <= visible:+ return secret+ return secret[:visible] + "…"+++async def run_test(+ *,+ model: str | None = None,+ api_key: str | None = None,+ base_url: str | None = None,+ binding: str | None = None,+ test_stream: bool = False,+) -> bool:+ from src.services.llm import config as config_module+ from src.services.llm.config import LLMConfig, get_llm_config++ config_module._LLM_CONFIG_CACHE = None+ cfg = get_llm_config()++ effective_model = model or cfg.model+ effective_key = api_key if api_key is not None else cfg.api_key+ effective_url = base_url or cfg.base_url+ effective_binding = binding or cfg.binding++ print(f"\n{BOLD}{'═' * 60}{RESET}")+ print(f" {BOLD}{CYAN}LLM Configuration Test{RESET}")+ print(f"{BOLD}{'═' * 60}{RESET}")+ print(f" Binding: {effective_binding}")+ print(f" Model: {effective_model}")+ print(f" Base URL: {effective_url}")+ print(f" API Key: {_mask(effective_key)}")+ print(f"{BOLD}{'─' * 60}{RESET}")++ ok = True++ # --- Test 1: completion ---+ print(f"\n {BOLD}[1/{'2' if test_stream else '1'}] Completion{RESET}", end=" ", flush=True)+ try:+ from src.services.llm.factory import complete++ t0 = time.perf_counter()+ resp = await complete(+ "Reply with exactly: HELLO_DEEPTUTOR",+ system_prompt="You are a test bot. Follow instructions exactly.",+ model=effective_model,+ api_key=effective_key,+ base_url=effective_url,+ binding=effective_binding,+ temperature=0.0,+ max_tokens=64,+ max_retries=1,+ )+ elapsed = time.perf_counter() - t0+ print(f"{CHECK} {DIM}{elapsed:.2f}s{RESET}")+ preview = resp.strip().replace("\n", " ")+ if len(preview) > 120:+ preview = preview[:120] + "…"+ print(f" {DIM}Response: {preview}{RESET}")+ except Exception as exc:+ print(f"{CROSS}")+ print(f" {RED}Error: {exc}{RESET}")+ ok = False++ # --- Test 2: streaming (optional) ---+ if test_stream:+ print(f"\n {BOLD}[2/2] Streaming{RESET}", end=" ", flush=True)+ try:+ from src.services.llm.factory import stream++ chunks: list[str] = []+ t0 = time.perf_counter()+ first_chunk_time: float | None = None+ async for chunk in stream(+ "Count from 1 to 5, one number per line.",+ system_prompt="You are a test bot.",+ model=effective_model,+ api_key=effective_key,+ base_url=effective_url,+ binding=effective_binding,+ temperature=0.0,+ max_tokens=64,+ max_retries=1,+ ):+ if first_chunk_time is None:+ first_chunk_time = time.perf_counter() - t0+ chunks.append(chunk)+ elapsed = time.perf_counter() - t0+ full = "".join(chunks).strip().replace("\n", " ")+ if len(full) > 120:+ full = full[:120] + "…"+ ttft = first_chunk_time if first_chunk_time is not None else elapsed+ print(f"{CHECK} {DIM}{elapsed:.2f}s (TTFT {ttft:.2f}s, {len(chunks)} chunks){RESET}")+ print(f" {DIM}Response: {full}{RESET}")+ except Exception as exc:+ print(f"{CROSS}")+ print(f" {RED}Error: {exc}{RESET}")+ ok = False++ # --- Summary ---+ print(f"\n{BOLD}{'═' * 60}{RESET}")+ if ok:+ print(f" {CHECK} {GREEN}All tests passed{RESET}")+ else:+ print(f" {CROSS} {RED}Some tests failed{RESET}")+ print(f"{BOLD}{'═' * 60}{RESET}\n")+ return ok+++def main() -> None:+ parser = argparse.ArgumentParser(description="Test LLM configuration connectivity")+ parser.add_argument("--model", help="Override model name")+ parser.add_argument("--base-url", help="Override base URL")+ parser.add_argument("--api-key", help="Override API key")+ parser.add_argument("--binding", help="Override provider binding")+ parser.add_argument("--stream", action="store_true", help="Also test streaming")+ args = parser.parse_args()++ ok = asyncio.run(+ run_test(+ model=args.model,+ api_key=args.api_key,+ base_url=args.base_url,+ binding=args.binding,+ test_stream=args.stream,+ )+ )+ sys.exit(0 if ok else 1)+++if __name__ == "__main__":+ main()diff --git a/web/package-lock.json b/web/package-lock.jsonindex 29ea9e2b1..ff908d714 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -4758,7 +4758,6 @@"version": "2.3.2","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz","integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",- "dev": true,"hasInstallScript": true,"license": "MIT","optional": true,