Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

updage mem

Pancake2384bd8e75ae
diff --git a/config/main.yaml b/config/main.yaml
index 6db5d8b5c..a5842ef77 100644
--- a/config/main.yaml
+++ b/config/main.yaml
@@ -79,7 +79,7 @@ research:
researching:
max_iterations: 5
new_topic_min_score: 0.85
- execution_mode: series
+ execution_mode: series
max_parallel_topics: 1
enable_rag_naive: true
enable_rag_hybrid: true
diff --git a/config/memory.yaml b/config/memory.yaml
new file mode 100644
index 000000000..ba6df5b54
--- /dev/null
+++ b/config/memory.yaml
@@ -0,0 +1,17 @@
+# Memory System Configuration
+# ============================
+# Configuration for the personalization memory system.
+
+llm:
+ # Model to use for MemoryAgent. Empty string uses system default LLM.
+ model: "qwen3-next-80b-a3b-instruct"
+ # Temperature for memory analysis (lower = more deterministic)
+ temperature: 0.5
+
+memory:
+ # Number of recent days of notes to read for context
+ recent_days: 7
+ # Whether to automatically update memory after task completion
+ auto_update: true
+ # Maximum length of preference context to inject into prompts (characters)
+ max_preference_length: 2000
diff --git a/data/README.md b/data/README.md
index 250aae33e..519f6bdab 100644
--- a/data/README.md
+++ b/data/README.md
@@ -2,22 +2,45 @@
This directory stores all data files for the AI-Tutor system, including knowledge bases, user data, logs, etc.
-## ๐Ÿ“ Directory Structure
+## Directory Structure
```
data/
โ”œโ”€โ”€ knowledge_bases/ # Knowledge base storage
โ””โ”€โ”€ user/ # User activity data
- โ”œโ”€โ”€ solve/ # Problem-solving results
- โ”œโ”€โ”€ question/ # Generated questions
- โ”œโ”€โ”€ research/ # Research reports and cache
- โ”œโ”€โ”€ co_writer/ # Interactive IdeaGen documents
- โ”œโ”€โ”€ notebook/ # Notebook records
- โ”œโ”€โ”€ guide/ # Guided-learning sessions
- โ””โ”€โ”€ run_code_workspace/ # Code execution workspace
+ โ”œโ”€โ”€ agent/ # Agent interaction history
+ โ”‚ โ”œโ”€โ”€ solve/ # Problem-solving sessions
+ โ”‚ โ”‚ โ”œโ”€โ”€ sessions.json # Session list
+ โ”‚ โ”‚ โ””โ”€โ”€ solve_xxx/ # Individual task outputs
+ โ”‚ โ”œโ”€โ”€ chat/ # Chat sessions
+ โ”‚ โ”‚ โ””โ”€โ”€ sessions.json # Session list
+ โ”‚ โ”œโ”€โ”€ question/ # Question generation
+ โ”‚ โ”‚ โ””โ”€โ”€ batch_xxx/ # Batch outputs
+ โ”‚ โ”œโ”€โ”€ research/ # Research outputs
+ โ”‚ โ”‚ โ””โ”€โ”€ reports/ # Research reports
+ โ”‚ โ”œโ”€โ”€ co-writer/ # Co-Writer outputs
+ โ”‚ โ”‚ โ”œโ”€โ”€ history.json # Operation history
+ โ”‚ โ”‚ โ”œโ”€โ”€ audio/ # TTS audio files
+ โ”‚ โ”‚ โ””โ”€โ”€ tool_calls/ # Tool call records
+ โ”‚ โ”œโ”€โ”€ guide/ # Guided-learning sessions
+ โ”‚ โ”œโ”€โ”€ run_code_workspace/ # Code execution workspace
+ โ”‚ โ””โ”€โ”€ logs/ # Application logs
+ โ”‚
+ โ”œโ”€โ”€ workspace/ # User workspace
+ โ”‚ โ””โ”€โ”€ notebook/ # User notebooks
+ โ”‚ โ”œโ”€โ”€ notebooks_index.json
+ โ”‚ โ””โ”€โ”€ {notebook_id}.json
+ โ”‚
+ โ””โ”€โ”€ settings/ # User settings
+ โ”œโ”€โ”€ interface.json # UI preferences
+ โ”œโ”€โ”€ llm_configs.json # LLM configurations
+ โ”œโ”€โ”€ embedding_configs.json
+ โ”œโ”€โ”€ tts_configs.json
+ โ”œโ”€โ”€ search_configs.json
+ โ””โ”€โ”€ knowledge_base_configs.json
```
-## ๐Ÿ“‹ Directory Description
+## Directory Description
### knowledge_bases/
@@ -27,71 +50,97 @@ Stores all knowledge base data files for the AI-Tutor system.
Stores all user-generated data and output files.
-#### solve/
+#### agent/
-Problem-solving module output directory containing results from problem-solving tasks.
+Contains all agent interaction history, organized by module:
-#### question/
+- **solve/**: Problem-solving module outputs
+ - `sessions.json`: List of solver sessions with messages
+ - `solve_xxx/`: Individual task directories with detailed outputs
-Question generation module output directory containing generated questions and validation results.
+- **chat/**: Chat module outputs
+ - `sessions.json`: List of chat sessions with messages
-#### research/
+- **question/**: Question generation module outputs
+ - `batch_xxx/`: Batch generation directories
-Research module output directory containing research reports and cache data.
+- **research/**: Research module outputs
+ - `reports/`: Generated research reports and metadata
-#### co_writer/
+- **co-writer/**: Co-Writer module outputs
+ - `history.json`: Operation history
+ - `audio/`: TTS audio files
+ - `tool_calls/`: Tool call records
-Co-Writer module output directory for interactive IdeaGen documents.
+- **guide/**: Guided-learning module outputs
-#### notebook/
+- **run_code_workspace/**: Code execution workspace for temporarily storing files
-Notebook data storage containing notebook records and indices.
+- **logs/**: Application logs
-#### guide/
+#### workspace/
-Guided-learning module output directory containing learning session data.
+User workspace for organizing content:
-#### run_code_workspace/
+- **notebook/**: User notebooks for saving and organizing content
-Code execution workspace for temporarily storing files generated by code execution.
+#### settings/
-## ๐Ÿ”ง Configuration
+User configuration files:
-Data directory paths are configured in `config/main.yaml`:
+- **interface.json**: UI preferences (theme, language, sidebar)
+- **llm_configs.json**: LLM provider configurations
+- **embedding_configs.json**: Embedding provider configurations
+- **tts_configs.json**: TTS provider configurations
+- **search_configs.json**: Web search configurations
+- **knowledge_base_configs.json**: KB-specific settings
-```yaml
-paths:
- user_data_dir: "./data/user"
- knowledge_bases_dir: "./data/knowledge_bases"
- run_code_workspace_dir: "./data/user/run_code_workspace"
+## Configuration
+
+Data directory paths are managed by `PathService` in `src/services/path_service.py`:
+
+```python
+from src.services.path_service import get_path_service
+
+path_service = get_path_service()
+
+# Agent paths
+solve_dir = path_service.get_solve_dir()
+chat_session_file = path_service.get_chat_session_file()
+
+# Workspace paths
+notebook_dir = path_service.get_notebook_dir()
+
+# Settings paths
+settings_dir = path_service.get_settings_dir()
+interface_file = path_service.get_settings_file("interface")
```
-## ๐Ÿ“ Notes
+## Notes
1. **Backup Important Data**: Recommend regularly backing up `knowledge_bases/` and important user data
2. **Version Control**: Recommend adding `data/` directory to `.gitignore` to avoid committing large files
3. **Disk Space**: Knowledge bases and user data may occupy significant disk space, clean old data regularly
4. **Permission Management**: Ensure application has read/write permissions
-5. **Path Consistency**: All modules use unified path configuration, avoid hardcoded paths
+5. **Path Consistency**: All modules use `PathService` for unified path management
-## ๐Ÿ”— Related Modules
+## Related Modules
-- **Knowledge Base Management**: `src/knowledge/` - Knowledge base creation, updates, queries
-- **User Data**: Each functional module automatically manages its corresponding user data directory
-- **Logging System**: `src/core/logging/` - Unified logging management
+- **Path Service**: `src/services/path_service.py` - Centralized path management
+- **Session Management**: `src/services/session/` - Unified session storage
+- **Knowledge Base Management**: `src/knowledge/` - Knowledge base operations
+- **Logging System**: `src/logging/` - Unified logging management
-## ๐Ÿ› ๏ธ Maintenance Operations
+## Maintenance Operations
### Clean Old Data
```bash
-# Clean old user data directories (customize based on retention policy)
-# Replace the pattern with your actual naming convention, e.g.:
-# find data/user -type d -regex '.*_[0-9]{8}.*' -mtime +30 -exec rm -rf {} \;
-find data/user -type d -name "*_YYYYMMDD*" -mtime +30 -exec rm -rf {} \;
+# Clean old task directories (customize based on retention policy)
+find data/user/agent -type d -name "*_20*" -mtime +30 -exec rm -rf {} \;
# Clean temporary workspace files
-find data/user/run_code_workspace -type f -mtime +7 -delete
+find data/user/agent/run_code_workspace -type f -mtime +7 -delete
```
### Backup Knowledge Base
@@ -110,3 +159,17 @@ tar -czf kb_backup.tar.gz data/knowledge_bases/{kb_name}/
# Restore knowledge base
tar -xzf knowledge_bases_backup_20250101.tar.gz -C data/
```
+
+## Migration
+
+If migrating from an older directory structure, use the migration script:
+
+```bash
+python scripts/migrate_user_data.py
+```
+
+This will:
+1. Move session files to `agent/{module}/sessions.json`
+2. Move module directories under `agent/`
+3. Move notebooks to `workspace/notebook/`
+4. Delete deprecated files (user_history.json, etc.)
diff --git a/scripts/migrate_user_data.py b/scripts/migrate_user_data.py
new file mode 100644
index 000000000..43a8d3ee1
--- /dev/null
+++ b/scripts/migrate_user_data.py
@@ -0,0 +1,363 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+User Data Migration Script
+===========================
+
+Migrates user data from old directory structure to new structure:
+
+Old structure:
+data/user/
+โ”œโ”€โ”€ solver_sessions.json
+โ”œโ”€โ”€ chat_sessions.json
+โ”œโ”€โ”€ user_history.json (deprecated, to be deleted)
+โ”œโ”€โ”€ settings.json (deprecated, to be deleted)
+โ”œโ”€โ”€ llm_providers.json (deprecated, to be deleted)
+โ”œโ”€โ”€ embedding_providers.json (deprecated, to be deleted)
+โ”œโ”€โ”€ solve/
+โ”œโ”€โ”€ question/
+โ”œโ”€โ”€ research/
+โ”œโ”€โ”€ co-writer/
+โ”œโ”€โ”€ guide/
+โ”œโ”€โ”€ notebook/
+โ”œโ”€โ”€ run_code_workspace/
+โ”œโ”€โ”€ logs/
+โ””โ”€โ”€ settings/
+
+New structure:
+data/user/
+โ”œโ”€โ”€ agent/
+โ”‚ โ”œโ”€โ”€ solve/
+โ”‚ โ”‚ โ”œโ”€โ”€ sessions.json
+โ”‚ โ”‚ โ””โ”€โ”€ {task_id}/
+โ”‚ โ”œโ”€โ”€ chat/
+โ”‚ โ”‚ โ””โ”€โ”€ sessions.json
+โ”‚ โ”œโ”€โ”€ question/
+โ”‚ โ”œโ”€โ”€ research/
+โ”‚ โ”œโ”€โ”€ co-writer/
+โ”‚ โ”œโ”€โ”€ guide/
+โ”‚ โ”œโ”€โ”€ run_code_workspace/
+โ”‚ โ””โ”€โ”€ logs/
+โ”œโ”€โ”€ workspace/
+โ”‚ โ””โ”€โ”€ notebook/
+โ””โ”€โ”€ settings/
+
+Usage:
+ python scripts/migrate_user_data.py
+"""
+
+import json
+import shutil
+import sys
+from pathlib import Path
+
+# Add project root to path
+project_root = Path(__file__).parent.parent
+sys.path.insert(0, str(project_root))
+
+
+def print_banner(title: str):
+ """Print a section banner."""
+ print("\n" + "=" * 70)
+ print(f" {title}")
+ print("=" * 70)
+
+
+def print_step(message: str, status: str = ""):
+ """Print a step message."""
+ if status:
+ print(f" [OK] {message} - {status}")
+ else:
+ print(f" ... {message}")
+
+
+def move_directory(src: Path, dst: Path) -> bool:
+ """
+ Move a directory from src to dst.
+ If dst already exists, merge contents.
+ """
+ if not src.exists():
+ return False
+
+ dst.parent.mkdir(parents=True, exist_ok=True)
+
+ if dst.exists():
+ # Merge contents
+ for item in src.iterdir():
+ dst_item = dst / item.name
+ if item.is_dir():
+ if dst_item.exists():
+ # Recursively merge
+ move_directory(item, dst_item)
+ else:
+ shutil.move(str(item), str(dst_item))
+ else:
+ if not dst_item.exists():
+ shutil.move(str(item), str(dst_item))
+ # Remove empty src directory
+ if src.exists() and not any(src.iterdir()):
+ src.rmdir()
+ else:
+ shutil.move(str(src), str(dst))
+
+ return True
+
+
+def move_file(src: Path, dst: Path) -> bool:
+ """Move a file from src to dst."""
+ if not src.exists():
+ return False
+
+ dst.parent.mkdir(parents=True, exist_ok=True)
+
+ if dst.exists():
+ # Backup existing file
+ backup = dst.with_suffix(dst.suffix + ".backup")
+ shutil.move(str(dst), str(backup))
+ print_step(f"Backed up existing {dst.name}", f"-> {backup.name}")
+
+ shutil.move(str(src), str(dst))
+ return True
+
+
+def delete_file(path: Path) -> bool:
+ """Delete a file if it exists."""
+ if path.exists():
+ path.unlink()
+ return True
+ return False
+
+
+def migrate():
+ """Run the migration."""
+ user_dir = project_root / "data" / "user"
+
+ if not user_dir.exists():
+ print("No user data directory found. Nothing to migrate.")
+ return
+
+ print_banner("User Data Migration")
+ print(f"Source directory: {user_dir}")
+
+ # =========================================================================
+ # Step 1: Create new directory structure
+ # =========================================================================
+ print_banner("Step 1: Creating New Directory Structure")
+
+ agent_dir = user_dir / "agent"
+ workspace_dir = user_dir / "workspace"
+
+ agent_modules = ["solve", "chat", "question", "research", "co-writer", "guide", "run_code_workspace", "logs"]
+
+ for module in agent_modules:
+ module_dir = agent_dir / module
+ module_dir.mkdir(parents=True, exist_ok=True)
+ print_step(f"Created agent/{module}/")
+
+ # Co-writer subdirectories
+ (agent_dir / "co-writer" / "audio").mkdir(parents=True, exist_ok=True)
+ (agent_dir / "co-writer" / "tool_calls").mkdir(parents=True, exist_ok=True)
+ print_step("Created agent/co-writer/audio/ and tool_calls/")
+
+ # Research reports directory
+ (agent_dir / "research" / "reports").mkdir(parents=True, exist_ok=True)
+ print_step("Created agent/research/reports/")
+
+ # Workspace/notebook
+ (workspace_dir / "notebook").mkdir(parents=True, exist_ok=True)
+ print_step("Created workspace/notebook/")
+
+ # =========================================================================
+ # Step 2: Move session files
+ # =========================================================================
+ print_banner("Step 2: Moving Session Files")
+
+ # Move solver_sessions.json -> agent/solve/sessions.json
+ src = user_dir / "solver_sessions.json"
+ dst = agent_dir / "solve" / "sessions.json"
+ if move_file(src, dst):
+ print_step("Moved solver_sessions.json", "-> agent/solve/sessions.json")
+ else:
+ print_step("solver_sessions.json not found", "skipped")
+
+ # Move chat_sessions.json -> agent/chat/sessions.json
+ src = user_dir / "chat_sessions.json"
+ dst = agent_dir / "chat" / "sessions.json"
+ if move_file(src, dst):
+ print_step("Moved chat_sessions.json", "-> agent/chat/sessions.json")
+ else:
+ print_step("chat_sessions.json not found", "skipped")
+
+ # =========================================================================
+ # Step 3: Move module directories
+ # =========================================================================
+ print_banner("Step 3: Moving Module Directories")
+
+ moves = [
+ ("solve", "agent/solve"),
+ ("question", "agent/question"),
+ ("research", "agent/research"),
+ ("co-writer", "agent/co-writer"),
+ ("guide", "agent/guide"),
+ ("run_code_workspace", "agent/run_code_workspace"),
+ ("logs", "agent/logs"),
+ ("notebook", "workspace/notebook"),
+ ]
+
+ for src_name, dst_name in moves:
+ src = user_dir / src_name
+ dst = user_dir / dst_name
+
+ # Skip if same path (already in correct location)
+ if src == dst:
+ print_step(f"{src_name}/", "already in correct location")
+ continue
+
+ if src.exists():
+ if move_directory(src, dst):
+ print_step(f"Moved {src_name}/", f"-> {dst_name}/")
+ else:
+ print_step(f"{src_name}/", "not found, skipped")
+
+ # =========================================================================
+ # Step 4: Delete deprecated files
+ # =========================================================================
+ print_banner("Step 4: Deleting Deprecated Files")
+
+ deprecated_files = [
+ "user_history.json",
+ "settings.json",
+ "llm_providers.json",
+ "embedding_providers.json",
+ ]
+
+ for filename in deprecated_files:
+ path = user_dir / filename
+ if delete_file(path):
+ print_step(f"Deleted {filename}")
+ else:
+ print_step(f"{filename}", "not found, skipped")
+
+ # =========================================================================
+ # Step 5: Clean up empty directories
+ # =========================================================================
+ print_banner("Step 5: Cleaning Up Empty Directories")
+
+ # Try to remove any empty old directories
+ old_dirs = ["solve", "question", "research", "co-writer", "guide", "notebook", "run_code_workspace", "logs"]
+ for dir_name in old_dirs:
+ old_dir = user_dir / dir_name
+ if old_dir.exists() and old_dir.is_dir():
+ try:
+ if not any(old_dir.iterdir()):
+ old_dir.rmdir()
+ print_step(f"Removed empty {dir_name}/")
+ except OSError:
+ pass # Directory not empty
+
+ # =========================================================================
+ # Done
+ # =========================================================================
+ print_banner("Migration Complete")
+ print("""
+New structure:
+data/user/
+โ”œโ”€โ”€ agent/
+โ”‚ โ”œโ”€โ”€ solve/sessions.json + task directories
+โ”‚ โ”œโ”€โ”€ chat/sessions.json
+โ”‚ โ”œโ”€โ”€ question/batch directories
+โ”‚ โ”œโ”€โ”€ research/reports/
+โ”‚ โ”œโ”€โ”€ co-writer/audio/ + tool_calls/
+โ”‚ โ”œโ”€โ”€ guide/session files
+โ”‚ โ”œโ”€โ”€ run_code_workspace/
+โ”‚ โ””โ”€โ”€ logs/
+โ”œโ”€โ”€ workspace/
+โ”‚ โ””โ”€โ”€ notebook/
+โ””โ”€โ”€ settings/
+ """)
+
+
+def verify_migration():
+ """Verify the migration was successful."""
+ print_banner("Verification")
+
+ user_dir = project_root / "data" / "user"
+
+ # Check required directories exist
+ required = [
+ "agent/solve",
+ "agent/chat",
+ "agent/question",
+ "agent/research/reports",
+ "agent/co-writer/audio",
+ "agent/co-writer/tool_calls",
+ "agent/guide",
+ "agent/run_code_workspace",
+ "agent/logs",
+ "workspace/notebook",
+ "settings",
+ ]
+
+ all_ok = True
+ for path in required:
+ full_path = user_dir / path
+ if full_path.exists():
+ print_step(f"{path}/", "OK")
+ else:
+ print_step(f"{path}/", "MISSING!")
+ all_ok = False
+
+ # Check no deprecated files remain
+ deprecated = ["user_history.json", "settings.json", "llm_providers.json", "embedding_providers.json"]
+ for filename in deprecated:
+ path = user_dir / filename
+ if path.exists():
+ print_step(f"{filename}", "STILL EXISTS (should be deleted)")
+ all_ok = False
+
+ if all_ok:
+ print("\n [OK] All verifications passed!")
+ else:
+ print("\n [FAIL] Some issues found. Please check above.")
+
+ return all_ok
+
+
+if __name__ == "__main__":
+ import argparse
+
+ parser = argparse.ArgumentParser(description="Migrate user data to new directory structure")
+ parser.add_argument("--verify", action="store_true", help="Only verify migration status")
+ parser.add_argument("--dry-run", action="store_true", help="Show what would be done without making changes")
+ args = parser.parse_args()
+
+ if args.verify:
+ verify_migration()
+ elif args.dry_run:
+ print("DRY RUN - No changes will be made")
+ print_banner("Would perform the following actions:")
+
+ user_dir = project_root / "data" / "user"
+
+ print("\n Session files to move:")
+ if (user_dir / "solver_sessions.json").exists():
+ print(" solver_sessions.json -> agent/solve/sessions.json")
+ if (user_dir / "chat_sessions.json").exists():
+ print(" chat_sessions.json -> agent/chat/sessions.json")
+
+ print("\n Directories to move:")
+ for name in ["solve", "question", "research", "co-writer", "guide", "notebook", "run_code_workspace", "logs"]:
+ src = user_dir / name
+ if src.exists():
+ if name == "notebook":
+ print(f" {name}/ -> workspace/notebook/")
+ else:
+ print(f" {name}/ -> agent/{name}/")
+
+ print("\n Files to delete:")
+ for name in ["user_history.json", "settings.json", "llm_providers.json", "embedding_providers.json"]:
+ if (user_dir / name).exists():
+ print(f" {name}")
+ else:
+ migrate()
+ verify_migration()
diff --git a/scripts/start.py b/scripts/start.py
index bd59d20b4..2665248ba 100644
--- a/scripts/start.py
+++ b/scripts/start.py
@@ -30,7 +30,6 @@ sys.path.insert(0, str(project_root))
from src.agents.question import AgentCoordinator
from src.agents.solve import MainSolver
-from src.api.utils.history import ActivityType, history_manager
from src.logging import get_logger
from src.services.llm import get_llm_config
@@ -227,28 +226,6 @@ class AITutorStarter:
print(preview)
logger.separator()
- # Save to history
- try:
- history_manager.add_entry(
- activity_type=ActivityType.SOLVE,
- title=question[:50] + "..." if len(question) > 50 else question,
- content={
- "question": question,
- "answer": result.get("formatted_solution", ""),
- "output_dir": result["metadata"]["output_dir"],
- "kb_name": kb_name,
- "metadata": result.get("metadata", {}),
- },
- summary=(
- formatted_solution[:100] + "..."
- if formatted_solution and len(formatted_solution) > 100
- else (formatted_solution or "")
- ),
- )
- except Exception as hist_error:
- # History save failure does not affect main flow
- logger.warning(f"History save failed: {hist_error!s}")
-
except Exception as e:
logger.section("Solving failed")
logger.error(str(e))
@@ -361,27 +338,6 @@ class AITutorStarter:
print(f"\n๐Ÿ“ Output directory: {result['output_dir']}")
print("=" * 70)
-
- # Save to history
- try:
- history_manager.add_entry(
- activity_type=ActivityType.QUESTION,
- title=f"{knowledge_point} ({question_type})",
- content={
- "requirement": requirement,
- "question": question_data,
- "output_dir": result.get("output_dir", ""),
- "kb_name": kb_name,
- },
- summary=(
- question_data.get("question", "")[:100] + "..."
- if len(question_data.get("question", "")) > 100
- else question_data.get("question", "")
- ),
- )
- except Exception as hist_error:
- # History save failure does not affect main flow
- print(f"\nโš ๏ธ History save failed: {hist_error!s}")
else:
print("\n" + "=" * 70)
print(f"โŒ Question generation failed: {result.get('error', 'Unknown error')}")
@@ -538,35 +494,6 @@ class AITutorStarter:
print("=" * 70)
- # Save to history
- try:
- # Read report content
- report_content = ""
- if result.get("final_report_path") and Path(result["final_report_path"]).exists():
- with open(result["final_report_path"], encoding="utf-8") as f:
- report_content = f.read()
-
- history_manager.add_entry(
- activity_type=ActivityType.RESEARCH,
- title=topic,
- content={
- "topic": topic,
- "report": report_content,
- "report_path": result.get("final_report_path", ""),
- "research_id": result.get("research_id", ""),
- "kb_name": kb_name,
- "metadata": metadata,
- },
- summary=(
- report_content[:200] + "..."
- if len(report_content) > 200
- else report_content
- ),
- )
- except Exception as hist_error:
- # History save failure does not affect main flow
- logger.warning(f"History save failed: {hist_error!s}")
-
except Exception as e:
logger.section("Research failed")
logger.error(str(e))
diff --git a/src/agents/chat/session_manager.py b/src/agents/chat/session_manager.py
index 3c2f3d90f..1e21da573 100644
--- a/src/agents/chat/session_manager.py
+++ b/src/agents/chat/session_manager.py
@@ -8,20 +8,20 @@ This module handles:
- Retrieving session history
- Listing recent sessions
- Deleting sessions
+
+Now inherits from BaseSessionManager for consistent behavior across all modules.
"""
-import json
-from pathlib import Path
-import time
from typing import Any
-import uuid
+
+from src.services.session import BaseSessionManager
-class SessionManager:
+class SessionManager(BaseSessionManager):
"""
Manages persistent storage of chat sessions.
- Sessions are stored in a JSON file at data/user/chat_sessions.json.
+ Sessions are stored in a JSON file at data/user/agent/chat/sessions.json.
Each session contains:
- session_id: Unique identifier
- title: Session title (usually first user message)
@@ -31,156 +31,87 @@ class SessionManager:
- updated_at: Last update timestamp
"""
- def __init__(self, base_dir: str | None = None):
- """
- Initialize SessionManager.
+ def __init__(self):
+ """Initialize SessionManager."""
+ super().__init__("chat")
- Args:
- base_dir: Base directory for session storage.
- Defaults to project_root/data/user
- """
- if base_dir is None:
- # Current file: src/agents/chat/session_manager.py
- # Project root: 4 levels up
- project_root = Path(__file__).resolve().parents[3]
- base_dir_path = project_root / "data" / "user"
- else:
- base_dir_path = Path(base_dir)
-
- self.base_dir = base_dir_path
- self.base_dir.mkdir(parents=True, exist_ok=True)
-
- self.sessions_file = self.base_dir / "chat_sessions.json"
- self._ensure_file()
-
- def _ensure_file(self):
- """Ensure the sessions file exists with correct format."""
- if not self.sessions_file.exists():
- initial_data = {
- "version": "1.0",
- "sessions": [],
- }
- self._save_data(initial_data)
-
- def _load_data(self) -> dict[str, Any]:
- """Load sessions data from file."""
- try:
- with open(self.sessions_file, encoding="utf-8") as f:
- return json.load(f)
- except (json.JSONDecodeError, FileNotFoundError):
- return {"version": "1.0", "sessions": []}
-
- def _save_data(self, data: dict[str, Any]):
- """Save sessions data to file."""
- with open(self.sessions_file, "w", encoding="utf-8") as f:
- json.dump(data, f, indent=2, ensure_ascii=False)
-
- def _get_sessions(self) -> list[dict[str, Any]]:
- """Get list of all sessions."""
- data = self._load_data()
- return data.get("sessions", [])
-
- def _save_sessions(self, sessions: list[dict[str, Any]]):
- """Save sessions list."""
- data = self._load_data()
- data["sessions"] = sessions
- self._save_data(data)
+ # =========================================================================
+ # BaseSessionManager Abstract Method Implementations
+ # =========================================================================
- def create_session(
+ def _get_session_id_prefix(self) -> str:
+ """Return the prefix for session IDs."""
+ return "chat_"
+
+ def _get_default_title(self) -> str:
+ """Return the default title for new sessions."""
+ return "New Chat"
+
+ def _create_session_data(
self,
- title: str = "New Chat",
settings: dict[str, Any] | None = None,
+ **kwargs,
) -> dict[str, Any]:
"""
- Create a new chat session.
+ Create chat-specific session data.
Args:
- title: Session title
- settings: Optional settings (kb_name, enable_rag, enable_web_search)
+ settings: Chat settings (kb_name, enable_rag, enable_web_search)
Returns:
- New session dict with session_id
+ Dict with settings
"""
- session_id = f"chat_{int(time.time() * 1000)}_{uuid.uuid4().hex[:8]}"
- now = time.time()
-
- session = {
- "session_id": session_id,
- "title": title[:100], # Limit title length
- "messages": [],
+ return {
"settings": settings or {},
- "created_at": now,
- "updated_at": now,
}
- sessions = self._get_sessions()
- sessions.insert(0, session) # Add to front (newest first)
-
- # Limit total sessions to prevent file bloat
- max_sessions = 100
- if len(sessions) > max_sessions:
- sessions = sessions[:max_sessions]
-
- self._save_sessions(sessions)
-
- return session
-
- def get_session(self, session_id: str) -> dict[str, Any] | None:
+ def _get_session_summary(self, session: dict[str, Any]) -> dict[str, Any]:
"""
- Get a session by ID.
+ Create a summary of a chat session for listing.
Args:
- session_id: Session identifier
+ session: The full session data
Returns:
- Session dict or None if not found
+ Dict containing summary fields
"""
- sessions = self._get_sessions()
- for session in sessions:
- if session.get("session_id") == session_id:
- return session
- return None
+ messages = session.get("messages", [])
+ return {
+ "session_id": session.get("session_id"),
+ "title": session.get("title"),
+ "message_count": len(messages),
+ "settings": session.get("settings"),
+ "created_at": session.get("created_at"),
+ "updated_at": session.get("updated_at"),
+ # Include preview of last message
+ "last_message": (
+ messages[-1].get("content", "")[:100] if messages else ""
+ ),
+ }
- def update_session(
+ # =========================================================================
+ # Chat-Specific Methods
+ # =========================================================================
+
+ def create_session(
self,
- session_id: str,
- messages: list[dict[str, Any]] | None = None,
title: str | None = None,
settings: dict[str, Any] | None = None,
- ) -> dict[str, Any] | None:
+ ) -> dict[str, Any]:
"""
- Update a session with new data.
+ Create a new chat session.
Args:
- session_id: Session identifier
- messages: New messages list (replaces existing)
- title: New title (optional)
- settings: New settings (optional)
+ title: Session title (uses default if None)
+ settings: Optional settings (kb_name, enable_rag, enable_web_search)
Returns:
- Updated session or None if not found
+ New session dict with session_id
"""
- sessions = self._get_sessions()
-
- for i, session in enumerate(sessions):
- if session.get("session_id") == session_id:
- if messages is not None:
- session["messages"] = messages
- if title is not None:
- session["title"] = title[:100]
- if settings is not None:
- session["settings"] = settings
-
- session["updated_at"] = time.time()
-
- # Move to front (most recently updated)
- sessions.pop(i)
- sessions.insert(0, session)
-
- self._save_sessions(sessions)
- return session
-
- return None
+ return super().create_session(
+ title=title,
+ settings=settings,
+ )
def add_message(
self,
@@ -201,99 +132,38 @@ class SessionManager:
Returns:
Updated session or None if not found
"""
- session = self.get_session(session_id)
- if not session:
- return None
-
- message = {
- "role": role,
- "content": content,
- "timestamp": time.time(),
- }
- if sources:
- message["sources"] = sources
-
- messages = session.get("messages", [])
- messages.append(message)
-
- # Update title from first user message if still default
- if session.get("title") == "New Chat" and role == "user":
- new_title = content[:50] + ("..." if len(content) > 50 else "")
- return self.update_session(session_id, messages=messages, title=new_title)
+ return super().add_message(
+ session_id=session_id,
+ role=role,
+ content=content,
+ sources=sources,
+ )
- return self.update_session(session_id, messages=messages)
-
- def list_sessions(
+ def update_session(
self,
- limit: int = 20,
- include_messages: bool = False,
- ) -> list[dict[str, Any]]:
- """
- List recent sessions.
-
- Args:
- limit: Maximum number of sessions to return
- include_messages: Whether to include full message history
-
- Returns:
- List of session dicts (newest first)
- """
- sessions = self._get_sessions()[:limit]
-
- if not include_messages:
- # Return summary only (without full messages)
- return [
- {
- "session_id": s.get("session_id"),
- "title": s.get("title"),
- "message_count": len(s.get("messages", [])),
- "settings": s.get("settings"),
- "created_at": s.get("created_at"),
- "updated_at": s.get("updated_at"),
- # Include preview of last message
- "last_message": (
- s.get("messages", [])[-1].get("content", "")[:100]
- if s.get("messages")
- else ""
- ),
- }
- for s in sessions
- ]
-
- return sessions
-
- def delete_session(self, session_id: str) -> bool:
+ session_id: str,
+ messages: list[dict[str, Any]] | None = None,
+ title: str | None = None,
+ settings: dict[str, Any] | None = None,
+ ) -> dict[str, Any] | None:
"""
- Delete a session.
+ Update a session with new data.
Args:
session_id: Session identifier
+ messages: New messages list (replaces existing)
+ title: New title (optional)
+ settings: New settings (optional)
Returns:
- True if deleted, False if not found
- """
- sessions = self._get_sessions()
- original_count = len(sessions)
-
- sessions = [s for s in sessions if s.get("session_id") != session_id]
-
- if len(sessions) < original_count:
- self._save_sessions(sessions)
- return True
-
- return False
-
- def clear_all_sessions(self) -> int:
- """
- Delete all sessions.
-
- Returns:
- Number of sessions deleted
+ Updated session or None if not found
"""
- sessions = self._get_sessions()
- count = len(sessions)
- self._save_sessions([])
- return count
+ return super().update_session(
+ session_id=session_id,
+ messages=messages,
+ title=title,
+ settings=settings,
+ )
# Singleton instance for convenience
diff --git a/src/agents/co_writer/edit_agent.py b/src/agents/co_writer/edit_agent.py
index 02f5ff280..5d49b2cd4 100644
--- a/src/agents/co_writer/edit_agent.py
+++ b/src/agents/co_writer/edit_agent.py
@@ -10,12 +10,15 @@ from typing import Any, Literal
import uuid
from src.agents.base_agent import BaseAgent
+from src.services.path_service import get_path_service
from src.tools.rag_tool import rag_search
from src.tools.web_search import web_search
-USER_DIR = Path(__file__).parent.parent.parent.parent / "data" / "user" / "co-writer"
-HISTORY_FILE = USER_DIR / "history.json"
-TOOL_CALLS_DIR = USER_DIR / "tool_calls"
+# Use PathService for directory paths
+_path_service = get_path_service()
+USER_DIR = _path_service.get_co_writer_dir()
+HISTORY_FILE = _path_service.get_co_writer_history_file()
+TOOL_CALLS_DIR = _path_service.get_co_writer_tool_calls_dir()
def ensure_dirs():
diff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.py
index 9d5100e54..795a2615a 100644
--- a/src/agents/co_writer/narrator_agent.py
+++ b/src/agents/co_writer/narrator_agent.py
@@ -17,12 +17,12 @@ import uuid
from openai import AsyncAzureOpenAI, AsyncOpenAI
from src.agents.base_agent import BaseAgent
+from src.services.path_service import get_path_service
from src.services.tts import get_tts_config
-# Import shared stats from edit_agent for legacy compatibility
-
-# Define storage path (unified under user/co-writer/ directory)
-USER_DIR = Path(__file__).parent.parent.parent.parent / "data" / "user" / "co-writer" / "audio"
+# Use PathService for storage path
+_path_service = get_path_service()
+USER_DIR = _path_service.get_co_writer_audio_dir()
def ensure_dirs():
diff --git a/src/agents/guide/guide_manager.py b/src/agents/guide/guide_manager.py
index 89706cd08..f82191349 100644
--- a/src/agents/guide/guide_manager.py
+++ b/src/agents/guide/guide_manager.py
@@ -16,6 +16,7 @@ import yaml
from src.logging import get_logger
from src.services.config import load_config_with_main, parse_language
+from src.services.path_service import get_path_service
from .agents import ChatAgent, InteractiveAgent, LocateAgent, SummaryAgent
@@ -111,9 +112,9 @@ class GuideManager:
if output_dir_from_config:
self.output_dir = Path(output_dir_from_config)
else:
- # Fallback to default path
- project_root = Path(__file__).parent.parent.parent.parent
- self.output_dir = project_root / "data" / "user" / "guide"
+ # Fallback to default path using PathService
+ path_service = get_path_service()
+ self.output_dir = path_service.get_guide_dir()
self.output_dir.mkdir(parents=True, exist_ok=True)
self.locate_agent = LocateAgent(
diff --git a/src/agents/question/agents/generate_agent.py b/src/agents/question/agents/generate_agent.py
index 8dcb1996c..dcd00d752 100644
--- a/src/agents/question/agents/generate_agent.py
+++ b/src/agents/question/agents/generate_agent.py
@@ -92,6 +92,18 @@ class GenerateAgent(BaseAgent):
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,
@@ -118,13 +130,18 @@ class GenerateAgent(BaseAgent):
# 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]
@@ -181,13 +198,18 @@ class GenerateAgent(BaseAgent):
# 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]
diff --git a/src/agents/question/coordinator.py b/src/agents/question/coordinator.py
index 12c5f463b..bb1392dc6 100644
--- a/src/agents/question/coordinator.py
+++ b/src/agents/question/coordinator.py
@@ -255,6 +255,13 @@ class AgentCoordinator:
# Update token stats from shared LLMStats
self._update_token_stats()
+ # Publish QUESTION_COMPLETE event for personalization
+ await self._publish_question_complete_event(
+ requirement=requirement,
+ questions=[question],
+ mode="single",
+ )
+
return result
async def generate_questions_custom(
@@ -476,12 +483,68 @@ class AgentCoordinator:
self.logger.info(f"Completed: {len(results)}")
self.logger.info(f"Failed: {len(failures)}")
+ # 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",
+ )
+
return summary
# =========================================================================
# Helper Methods
# =========================================================================
+ async def _publish_question_complete_event(
+ self,
+ requirement: dict[str, Any],
+ questions: list[dict[str, Any]],
+ mode: str = "single",
+ ) -> 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.append(summary)
+
+ 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),
+ agent_output=json.dumps(question_summaries, ensure_ascii=False),
+ tools_used=["rag_tool"],
+ success=len(questions) > 0,
+ metadata={
+ "mode": mode,
+ "num_questions": len(questions),
+ "knowledge_point": requirement.get("knowledge_point", ""),
+ },
+ )
+ 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}")
+
async def _generate_question_plan(
self,
requirement: dict[str, Any],
diff --git a/src/agents/question/prompts/en/generate_agent.yaml b/src/agents/question/prompts/en/generate_agent.yaml
index 968e56818..e29b3cfb8 100644
--- a/src/agents/question/prompts/en/generate_agent.yaml
+++ b/src/agents/question/prompts/en/generate_agent.yaml
@@ -15,6 +15,9 @@ system: |
generate: |
Generate a question based on the following information:
+ ## User Preference
+ {preference}
+
Requirements:
{requirements}
@@ -43,6 +46,9 @@ generate: |
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}
diff --git a/src/agents/question/prompts/zh/generate_agent.yaml b/src/agents/question/prompts/zh/generate_agent.yaml
index 691a2fb7a..0ee75a8a0 100644
--- a/src/agents/question/prompts/zh/generate_agent.yaml
+++ b/src/agents/question/prompts/zh/generate_agent.yaml
@@ -15,6 +15,9 @@ system: |
generate: |
ๆ นๆฎไปฅไธ‹ไฟกๆฏ็”Ÿๆˆ้ข˜็›ฎ๏ผš
+ ## ็”จๆˆทๅๅฅฝ
+ {preference}
+
่ฆๆฑ‚๏ผš
{requirements}
@@ -43,6 +46,9 @@ generate: |
generate_with_reference: |
็”Ÿๆˆไธ€้“ๆ–ฐ้ข˜็›ฎ๏ผŒไปŽไปฅไธ‹ๅ‚่€ƒ้ข˜็›ฎ่Žทๅ–็ตๆ„Ÿ๏ผŒไฝ†ๅœจๅœบๆ™ฏๅ’ŒๆŽจ็†ไธŠๆ˜Žๆ˜พไธๅŒ๏ผš
+ ## ็”จๆˆทๅๅฅฝ
+ {preference}
+
ๅ‚่€ƒ้ข˜็›ฎ๏ผš
{reference_question}
diff --git a/src/agents/solve/__init__.py b/src/agents/solve/__init__.py
index 03a5db1f1..e56de80ce 100644
--- a/src/agents/solve/__init__.py
+++ b/src/agents/solve/__init__.py
@@ -39,6 +39,8 @@ from .memory import (
Reflections,
SolveChainStep,
SolveMemory,
+ SolveOutput,
+ TodoItem,
ToolCallRecord,
)
@@ -51,6 +53,7 @@ from .solve_loop import (
PrecisionAnswerAgent,
ResponseAgent,
SolveAgent,
+ SolveNoteAgent,
ToolAgent,
)
@@ -67,14 +70,17 @@ __all__ = [
"KnowledgeItem",
"Reflections",
"SolveMemory",
- "SolveChainStep",
+ "TodoItem",
+ "SolveOutput",
"ToolCallRecord",
+ "SolveChainStep", # Backward compatibility
# Analysis Loop
"InvestigateAgent",
"NoteAgent",
# Solve Loop
"ManagerAgent",
"SolveAgent",
+ "SolveNoteAgent",
"ResponseAgent",
"PrecisionAnswerAgent",
"ToolAgent",
diff --git a/src/agents/solve/main_solver.py b/src/agents/solve/main_solver.py
index 655be9aa2..75243190c 100644
--- a/src/agents/solve/main_solver.py
+++ b/src/agents/solve/main_solver.py
@@ -18,15 +18,22 @@ from typing import Any
import yaml
from ...services.config import parse_language
+from ...services.path_service import get_path_service
from .analysis_loop import InvestigateAgent, NoteAgent
# Dual-Loop Architecture
-from .memory import CitationMemory, InvestigateMemory, SolveChainStep, SolveMemory
+from .memory import (
+ CitationMemory,
+ InvestigateMemory,
+ SolveMemory,
+ SolveOutput,
+)
from .solve_loop import (
ManagerAgent,
PrecisionAnswerAgent,
ResponseAgent,
SolveAgent,
+ SolveNoteAgent,
ToolAgent,
)
from .utils import ConfigValidator, PerformanceMonitor, SolveAgentLogger
@@ -126,9 +133,11 @@ class MainSolver:
paths_config = full_config.get("paths", {})
# Build config structure expected by ConfigValidator
+ path_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", "./data/user/solve"),
+ "output_base_dir": paths_config.get("solve_output_dir", default_solve_dir),
"save_intermediate_results": solve_config.get(
"save_intermediate_results", True
),
@@ -308,6 +317,7 @@ class MainSolver:
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)")
@@ -324,7 +334,8 @@ class MainSolver:
"""
# Create output directory
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- output_base_dir = self.config.get("system", {}).get("output_base_dir", "./user/solve")
+ 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}")
os.makedirs(output_dir, exist_ok=True)
@@ -387,7 +398,7 @@ class MainSolver:
"""
Dual-Loop Pipeline:
1) Analysis Loop: Investigate โ†’ Note
- 2) Solve Loop: Plan โ†’ Manager โ†’ Solve โ†’ Check โ†’ Format
+ 2) Solve Loop: Plan โ†’ Solve โ†’ Note โ†’ Format
"""
self.logger.info("Pipeline: Analysis Loop โ†’ Solve Loop")
@@ -510,7 +521,10 @@ class MainSolver:
# ========== Solve Loop ==========
self.logger.stage("Solve Loop", "start", "Generating solution")
- solve_memory = SolveMemory.load_or_create(output_dir=output_dir, user_question=question)
+ solve_memory = SolveMemory.load_or_create(
+ output_dir=output_dir,
+ user_question=question,
+ )
# Initialize Solve Loop Agents (if not yet initialized)
if self.manager_agent is None:
@@ -543,6 +557,13 @@ class MainSolver:
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,
+ )
precision_enabled = (
self.config.get("agents", {})
@@ -558,8 +579,8 @@ class MainSolver:
token_tracker=self.token_tracker,
)
- # 1. Plan: Generate solving plan
- self.logger.info("Plan: Generating solution strategy...")
+ # 1. Plan: Generate todo-list
+ self.logger.info("Plan: Generating todo-list...")
plan_result = None
for attempt in range(2):
@@ -571,8 +592,8 @@ class MainSolver:
solve_memory=solve_memory,
verbose=(attempt > 0),
)
- num_steps = plan_result.get("num_steps") or plan_result.get("steps_count", 0)
- self.logger.log_stage_progress("Plan", "complete", f"steps={num_steps}")
+ 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:
@@ -580,7 +601,8 @@ class MainSolver:
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
+ output_dir=output_dir,
+ user_question=question,
)
else:
self.logger.error(f"ManagerAgent attempt {attempt + 1} also failed")
@@ -589,225 +611,251 @@ class MainSolver:
if plan_result is None:
raise ValueError("ManagerAgent failed to generate plan")
- # 2. Solve Loop - Execute steps
- self.logger.info("Solve: Executing solution steps...")
- max_correction_iterations = self.config.get("system", {}).get(
- "max_solve_correction_iterations", 3
+ # 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,
)
- total_planned_steps = len(solve_memory.solve_chains)
+
+ async def _run_solve_loop(
+ self,
+ question: str,
+ solve_memory: SolveMemory,
+ investigate_memory: InvestigateMemory,
+ citation_memory: CitationMemory,
+ 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"planned_steps={total_planned_steps}, max_corrections={max_correction_iterations}",
+ f"todos={total_todos}, max_outer={max_outer_iterations}",
)
- for step_index, step in enumerate(solve_memory.solve_chains, 1):
- if step.status in ("waiting_response", "done"):
- continue
-
- self.logger.info(f" Step {step_index}: {step.step_id}")
- self.logger.debug(f" Target: {step.step_target[:80]}")
+ step_responses = []
+ accumulated_response = ""
- if hasattr(self, "_send_progress_update"):
- self._send_progress_update(
- "solve",
- {
- "step_index": step_index,
- "step_id": step.step_id,
- "step_target": step.step_target,
- },
+ 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
- self.logger.log_stage_progress("SolveLoop", "running", f"step={step.step_id}")
+ # 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)
- if self._has_pending_tool_calls(step):
- await self._execute_tool_calls(step, solve_memory, citation_memory, output_dir)
+ # Create iteration record
+ iteration_record = solve_memory.create_iteration(current_todo.todo_id)
- iteration = 0
- while iteration < max_correction_iterations:
- iteration += 1
- current_step = solve_memory.get_step(step.step_id) or step
+ # ================================================================
+ # Inner Loop: solve_agent iterates until tool_type == "none"
+ # ================================================================
+ tool_call_history: list[ToolCallRecord] = []
- with self.monitor.track(f"solve_execute_{step.step_id}_iter_{iteration}"):
+ 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,
- current_step=current_step,
- solve_memory=solve_memory,
- investigate_memory=investigate_memory,
- citation_memory=citation_memory,
- kb_name=self.kb_name,
- output_dir=output_dir,
verbose=False,
)
- if solve_result.get("raw_llm_response"):
- self.logger.log_stage_progress(
- "SolveLoop", "running", f"step={step.step_id}, iteration={iteration}"
- )
+ tool_type = solve_result.get("tool_type", "none")
+ query = solve_result.get("query", "")
- if solve_result.get("requested_calls"):
- await self._execute_tool_calls(
- current_step, solve_memory, citation_memory, output_dir
- )
-
- self.logger.update_token_stats(self.token_tracker.get_summary())
+ self.logger.info(f" tool_type={tool_type}, query={query[:50]}...")
- if solve_result.get("finish_requested"):
- current_step = solve_memory.get_step(step.step_id) or step
- if self._has_pending_tool_calls(current_step):
- self.logger.debug(" Finish triggered but tools pending, continuing...")
- continue
- solve_memory.mark_step_waiting_response(current_step.step_id)
- solve_memory.save()
- self.logger.log_stage_progress(
- "SolveLoop", "complete", f"step={current_step.step_id} ready for response"
- )
+ # 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
- else:
- self.logger.warning(f" Step {step.step_id} max iterations reached")
- solve_memory.mark_step_waiting_response(step.step_id)
- solve_memory.save()
-
- pending_steps = [
- s.step_id
- for s in solve_memory.solve_chains
- if s.status not in ("waiting_response", "done")
- ]
- if pending_steps:
- self.logger.warning(f"Steps not ready for response: {', '.join(pending_steps)}")
- self.logger.log_stage_progress(
- "SolveLoop", "complete", f"steps_processed={total_planned_steps - len(pending_steps)}"
- )
+ # 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,
+ )
- # 3. Response: Generate responses for each step
- self.logger.info("Response: Generating step responses...")
- self.logger.log_stage_progress("ResponseLoop", "start", "Generating responses")
+ if tool_record:
+ tool_call_history.append(tool_record)
+ iteration_record.append_tool_call(tool_record)
- accumulated_response = ""
- for step in solve_memory.solve_chains:
- if step.status == "done" and step.step_response:
- accumulated_response += step.step_response + "\n\n"
-
- for step in solve_memory.solve_chains:
- if step.status != "waiting_response":
- continue
-
- original_step_index = next(
- (
- i + 1
- for i, s in enumerate(solve_memory.solve_chains)
- if s.step_id == step.step_id
- ),
- 0,
- )
+ self.logger.update_token_stats(self.token_tracker.get_summary())
- if hasattr(self, "_send_progress_update"):
- self._send_progress_update(
- "response",
- {
- "step_index": original_step_index,
- "step_id": step.step_id,
- "step_target": step.step_target,
- },
- )
+ # ================================================================
+ # Note Agent: Update todo-list based on iteration results
+ # ================================================================
+ self.logger.info(f" Calling note_agent...")
- with self.monitor.track(f"solve_response_{step.step_id}"):
- response_result = await self.response_agent.process(
- question=question,
- step=step,
+ with self.monitor.track(f"note_{outer_iter + 1}"):
+ note_result = await self.solve_note_agent.process(
solve_memory=solve_memory,
- investigate_memory=investigate_memory,
- citation_memory=citation_memory,
- output_dir=output_dir,
+ iteration_record=iteration_record,
+ target_todo=current_todo,
verbose=False,
- accumulated_response=accumulated_response,
)
- step_response = response_result.get("step_response", "")
- if step_response:
- accumulated_response += step_response + "\n\n"
-
- if response_result.get("raw_response"):
- self.logger.log_stage_progress(
- "ResponseLoop", "running", f"step={step.step_id} response generated"
+ 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,
+ )
- self.logger.update_token_stats(self.token_tracker.get_summary())
+ 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")
- self.logger.log_stage_progress("ResponseLoop", "complete", "All responses generated")
+ # Save progress
+ solve_memory.save()
+ self.logger.update_token_stats(self.token_tracker.get_summary())
- # 4. Finalize: Compile final answer
- self.logger.info("Finalize: Compiling final answer...")
- self.logger.log_stage_progress("Finalize", "start", "Compiling steps")
+ else:
+ self.logger.warning(f"Max outer iterations ({max_outer_iterations}) reached")
- actual_total_steps = len(solve_memory.solve_chains)
- completed_step_objs = [
- step
- for step in solve_memory.solve_chains
- if step.status == "done" and step.step_response
- ]
- completed_steps = len(completed_step_objs)
+ # ================================================================
+ # 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}",
+ )
- solve_memory.metadata["total_steps"] = actual_total_steps
- solve_memory.metadata["completed_steps"] = completed_steps
- solve_memory.save()
- self.logger.info(f" Stats: {completed_steps}/{actual_total_steps} steps completed")
+ # 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}")
- used_cite_ids = []
- for step in completed_step_objs:
- used_cite_ids.extend(step.used_citations)
- used_cite_ids = list(dict.fromkeys(used_cite_ids))
+ self.logger.info("Finalize: Compiling final answer...")
+ self.logger.log_stage_progress("Finalize", "start", "Compiling step responses")
- step_responses = [step.step_response for step in completed_step_objs]
- final_answer = "\n\n".join(step_responses)
+ # Compile step responses into final answer
+ final_answer = "\n\n".join(step_responses) if step_responses else ""
- # Get language setting from config (unified in config/main.yaml system.language)
+ # 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)
-
- # Check if citations are enabled
enable_citations = self.config.get("system", {}).get("enable_citations", True)
citations_section = ""
- if enable_citations and citation_memory:
+ 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}"
- format_result = {
- "final_answer": final_answer.strip(),
- "citations": used_cite_ids,
- "metadata": {
- "refined_steps": len(completed_step_objs),
- "total_steps": actual_total_steps,
- "citations_section": bool(citations_section),
- },
- }
-
- self.logger.info(f" Final answer: {len(format_result['final_answer'])} chars")
- self.logger.info(f" Citations: {len(format_result['citations'])}")
+ self.logger.info(f" Final answer: {len(final_answer)} chars")
+ self.logger.info(f" Citations: {len(used_cite_ids)}")
- # 5. Precision Answer (if enabled)
+ # Precision Answer (if enabled)
+ final_answer_content = final_answer.strip()
precision_answer_enabled = (
self.config.get("agents", {}).get("precision_answer_agent", {}).get("enabled", False)
)
- final_answer_content = format_result["final_answer"]
- if precision_answer_enabled and self.precision_answer_agent:
+ 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=format_result["final_answer"], verbose=False
+ 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## Detailed Answer\n\n{format_result['final_answer']}"
- else:
- self.logger.debug(" No precision answer needed")
+ final_answer_content = (
+ f"## Concise Answer\n\n{precision_answer}\n\n---\n\n"
+ f"## Detailed Answer\n\n{final_answer_content}"
+ )
# Save final answer
final_answer_file = Path(output_dir) / "final_answer.md"
@@ -817,6 +865,35 @@ class MainSolver:
self.logger.success(f"Final answer saved: {final_answer_file}")
self.logger.log_stage_progress("Format", "complete", f"output={final_answer_file}")
+ # Publish SOLVE_COMPLETE event for personalization
+ 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
+ ))
+
+ event = Event(
+ type=EventType.SOLVE_COMPLETE,
+ task_id=task_id,
+ user_input=question,
+ agent_output=final_answer_content[:2000], # Truncate for efficiency
+ tools_used=tools_used,
+ success=True,
+ metadata={
+ "total_todos": total_todos,
+ "completed_todos": completed_count,
+ "citations_count": len(used_cite_ids),
+ },
+ )
+ 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,
@@ -824,38 +901,199 @@ class MainSolver:
"output_md": str(final_answer_file),
"output_json": str(Path(output_dir) / "solve_chain.json"),
"formatted_solution": final_answer_content,
- "citations": format_result["citations"],
- "pipeline": "reworked",
- "total_steps": solve_memory.metadata["total_steps"],
+ "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),
- "solve_steps": solve_memory.metadata["completed_steps"],
"metadata": {
"coverage_rate": investigate_memory.metadata.get("coverage_rate", 0.0),
"avg_confidence": investigate_memory.metadata.get("avg_confidence", 0.0),
- "total_steps": solve_memory.metadata["total_steps"],
+ "total_todos": total_todos,
+ "completed_todos": completed_count,
},
}
- async def _execute_tool_calls(
+ 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,
- step: SolveChainStep,
+ output: SolveOutput,
solve_memory: SolveMemory,
citation_memory: CitationMemory,
output_dir: str | None,
) -> dict[str, Any]:
- tool_result = await self.tool_agent.process(
- step=step,
- solve_memory=solve_memory,
- citation_memory=citation_memory,
- kb_name=self.kb_name,
- output_dir=output_dir,
- verbose=False,
- )
- return tool_result
+ """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()
- @staticmethod
- def _has_pending_tool_calls(step: SolveChainStep) -> bool:
- return any(call.status in {"pending", "running"} for call in step.tool_calls)
+ return {"executed": logs, "status": "completed"}
if __name__ == "__main__":
diff --git a/src/agents/solve/memory/__init__.py b/src/agents/solve/memory/__init__.py
index 31e31f5d6..fb0067f6b 100644
--- a/src/agents/solve/memory/__init__.py
+++ b/src/agents/solve/memory/__init__.py
@@ -1,7 +1,8 @@
#!/usr/bin/env python
"""
-Memory System - Memory file system
-Provides implementations of InvestigateMemory and SolveMemory
+Memory System - Memory storage for solving process
+
+Provides implementations of InvestigateMemory and SolveMemory.
"""
from .citation_memory import (
@@ -14,8 +15,13 @@ from .investigate_memory import (
Reflections,
)
from .solve_memory import (
+ # Core data structures
+ IterationRecord,
+ NoteAction,
SolveChainStep,
SolveMemory,
+ SolveOutput,
+ TodoItem,
ToolCallRecord,
)
@@ -24,10 +30,16 @@ __all__ = [
"InvestigateMemory",
"KnowledgeItem",
"Reflections",
- # Solve Memory
+ # Solve Memory - Core
"SolveMemory",
- "SolveChainStep",
+ "TodoItem",
"ToolCallRecord",
+ # Solve Memory - New iteration architecture
+ "IterationRecord",
+ "NoteAction",
+ # Solve Memory - Legacy/Backward compatibility
+ "SolveOutput",
+ "SolveChainStep",
# Citation Memory
"CitationMemory",
"CitationItem",
diff --git a/src/agents/solve/memory/solve_memory.py b/src/agents/solve/memory/solve_memory.py
index 9823137b9..fb1829a7a 100644
--- a/src/agents/solve/memory/solve_memory.py
+++ b/src/agents/solve/memory/solve_memory.py
@@ -1,7 +1,9 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-SolveMemory - Solve-chain based solving memory system
+SolveMemory - Todo-list based solving memory system
+
+Manages the todo-list milestones and solve outputs for the problem-solving process.
"""
from __future__ import annotations
@@ -18,6 +20,173 @@ 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"""
@@ -64,9 +233,63 @@ class ToolCallRecord:
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"""
+ """Single step structure in solve-chain (kept for backward compatibility)"""
step_id: str
step_target: str
@@ -121,8 +344,13 @@ class SolveChainStep:
self.updated_at = _now()
+# ========================================================================== #
+# SolveMemory
+# ========================================================================== #
+
+
class SolveMemory:
- """solve-chain data storage"""
+ """Todo-list based solving memory storage"""
def __init__(
self,
@@ -134,19 +362,27 @@ class SolveMemory:
self.user_question = user_question
self.output_dir = output_dir
- self.version = "solve_chain_v1"
+ self.version = "solve_chain_v2" # Updated version for new architecture
self.created_at = _now()
self.updated_at = _now()
- self.solve_chains: List[SolveChainStep] = []
+ # 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_steps": 0,
- "completed_steps": 0,
+ "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
@@ -159,14 +395,12 @@ class SolveMemory:
task_id: Optional[str] = None,
) -> "SolveMemory":
file_path = Path(output_dir) / "solve_chain.json"
- legacy_path = Path(output_dir) / "solve_memory.json"
- if not file_path.exists() and legacy_path.exists():
- memory = cls(task_id=task_id, user_question=user_question, output_dir=output_dir)
- memory._load_from_legacy_file(legacy_path)
- memory.save()
- return memory
if not file_path.exists():
- return cls(task_id=task_id, user_question=user_question, output_dir=output_dir)
+ 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)
@@ -177,14 +411,34 @@ class SolveMemory:
output_dir=output_dir,
)
- memory.version = data.get("version", "solve_chain_v1")
+ 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)
- memory.solve_chains = [
- SolveChainStep.from_dict(step) for step in data.get("solve_chains", [])
+
+ # 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):
@@ -196,6 +450,23 @@ class SolveMemory:
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,
@@ -203,138 +474,523 @@ class SolveMemory:
"user_question": self.user_question,
"created_at": self.created_at,
"updated_at": self.updated_at,
- "solve_chains": [step.to_dict() for step in self.solve_chains],
"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",
}
# ------------------------------------------------------------------ #
- # Step Management
+ # Todo-list Management
# ------------------------------------------------------------------ #
- def create_chains(self, chains: List[SolveChainStep]):
- self.solve_chains = chains
- self.metadata["total_steps"] = len(chains)
- self.metadata["completed_steps"] = sum(1 for c in chains if c.status == "done")
- self.metadata["total_tool_calls"] = sum(len(c.tool_calls) for c in chains)
+ 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_step(self, step_id: str) -> Optional[SolveChainStep]:
- return next((step for step in self.solve_chains if step.step_id == step_id), None)
+ 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 get_current_step(self) -> Optional[SolveChainStep]:
- for step in self.solve_chains:
- if step.status in {"undone", "in_progress", "waiting_response"}:
- return step
+ 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
- def append_tool_call(
+ # ------------------------------------------------------------------ #
+ # Todo-list Editing (for NoteAgent)
+ # ------------------------------------------------------------------ #
+ def insert_todo_after(
self,
- step_id: str,
+ 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:
- step = self.get_step(step_id)
- if not step:
- raise ValueError(f"Step {step_id} not found")
+ """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 {},
)
- step.append_tool_call(record)
- self.metadata["total_tool_calls"] += 1
+ 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_result(
+ def update_tool_call_in_output(
self,
- step_id: str,
+ output_id: str,
call_id: str,
raw_answer: str,
summary: str,
status: str = "success",
metadata: Optional[Dict[str, Any]] = None,
):
- step = self.get_step(step_id)
- if not step:
- raise ValueError(f"Step {step_id} not found")
- record = next((tc for tc in step.tool_calls if tc.call_id == call_id), 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 step {step_id}")
+ 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()
- def mark_step_waiting_response(self, step_id: str):
- step = self.get_step(step_id)
- if not step:
- raise ValueError(f"Step {step_id} not found")
- step.mark_waiting_response()
- self.updated_at = _now()
-
- def submit_step_response(
- self,
- step_id: str,
- response: str,
- used_citations: Optional[List[str]] = None,
- ):
- step = self.get_step(step_id)
- if not step:
- raise ValueError(f"Step {step_id} not found")
- step.update_response(response=response, used_citations=used_citations or [])
- self.metadata["completed_steps"] = sum(1 for c in self.solve_chains if c.status == "done")
- 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 Steps: {self.metadata['total_steps']}",
- f"Completed: {self.metadata['completed_steps']}",
+ 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 step in self.solve_chains:
- lines.append(f"- {step.step_id} | {step.status} | target: {step.step_target[: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[:60]}...")
return "\n".join(lines)
- # ------------------------------------------------------------------ #
- # Legacy support
- # ------------------------------------------------------------------ #
- def _load_from_legacy_file(self, legacy_path: Path):
- try:
- with open(legacy_path, "r", encoding="utf-8") as f:
- data = json.load(f)
- except Exception:
- return
+ def format_todo_list_for_log(self) -> str:
+ """Format todo-list for logging output"""
+ if not self.todo_list:
+ return "(No todo-list generated)"
- steps_data = data.get("steps", [])
- converted: List[SolveChainStep] = []
- for idx, item in enumerate(steps_data, start=1):
- tool_logs = item.get("tool_logs", [])
- records: List[ToolCallRecord] = []
- for log in tool_logs:
- records.append(
- ToolCallRecord(
- tool_type=log.get("tool", "unknown"),
- query=log.get("input") or log.get("query") or "",
- cite_id=log.get("cite_id"),
- raw_answer=log.get("output"),
- summary=log.get("output"),
- status=log.get("status", "success"),
- )
- )
- converted.append(
- SolveChainStep(
- step_id=item.get("step_id", f"S{idx}"),
- step_target=item.get("plan", ""),
- available_cite=item.get("available_citations", []),
- tool_calls=records,
- step_response=item.get("content"),
- status="done" if item.get("status") == "completed" else "undone",
- used_citations=item.get("used_citations", []),
- )
- )
+ 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)
- self.solve_chains = converted
- self.metadata["total_steps"] = len(converted)
- self.metadata["completed_steps"] = sum(1 for step in converted if step.status == "done")
+ 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_file
diff --git a/src/agents/solve/prompts/en/solve_loop/manager_agent.yaml b/src/agents/solve/prompts/en/solve_loop/manager_agent.yaml
index 0514af1ca..10d3bccc9 100644
--- a/src/agents/solve/prompts/en/solve_loop/manager_agent.yaml
+++ b/src/agents/solve/prompts/en/solve_loop/manager_agent.yaml
@@ -1,52 +1,54 @@
system: |
# Role Definition
- You are the **Strategic Planner** for problem-solving. Your task is to break down a complex user question into a logically rigorous, executable **Solve Chain**.
+ 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. **Simplicity First**: Treat the user's question as the highest priority. Dynamically design the complexity of the solving workflow around the user's needs.
- 2. **Logical Progression**: Each step must be the cornerstone for the next. From understanding concepts to deriving formulas, then calculating solutions, and finally verifying and summarizing.
- 3. **Merge Trivial Steps**: Do not split a complete action (like "write and run code") into "write" and "run" steps. Each step should be relatively independent, covering completely different content. Otherwise, these two steps can be combined into one.
- 4. **Clear Roles**: Each step must be assigned a standard role type, clarifying "what to do".
- 5. **Value Driven**: Each step must yield new information or conclusions.
+ 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.
- # Standard Role Definitions
- Please select the most appropriate role from the following list. **Each step can only have one role, and roles must be strictly separated**:
- - **Calculation**: Involves numerical operations, equation solving, algorithm execution. Usually requires code execution. **Do not include drawing operations**.
- - **Drawing**: Data visualization, plotting function graphs, geometric construction. **Must be an independent step, do not mix with other roles**.
- - **Derivation**: Deriving new formulas from known formulas/theorems, mathematical theorem proofs, logical proposition deduction, symbolic calculus.
- - **Analysis**: Problem decomposition, qualitative analysis, differentiation of physical/mathematical principles, identifying key elements, textual elaboration of concepts, phenomena, or result meanings. **Do not include drawing or calculation operations**.
- - **Integration**: Synthesizing multi-step results to draw a final conclusion. Note: You don't need to deliberately use an integration step.
+ # 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"
- # Citation Norms
- - Plan steps based on the `Available Knowledge Chain`.
- - Explicitly mark the Knowledge ID (e.g., `[k-001]`) needed for reference in the step. If no specific citation is relied upon, use an empty array `[]`.
+ Bad milestones (too detailed):
+ - "Define variable x"
+ - "Substitute x into formula"
+ - "Simplify the expression"
# Output Format
- Please output in JSON format, strictly adhering to the following structure:
+ Output a JSON object with a "todos" array:
```json
{
- "steps": [
+ "todos": [
{
- "step_id": "S1",
- "role": "Calculation",
- "target": "Specific target description",
- "cite_ids": ["[cite_id1]", "[cite_id2]"]
+ "todo_id": "T1",
+ "description": "Clarify the problem's core concepts and identify key information"
},
{
- "step_id": "S2",
- "role": "Analysis",
- "target": "Specific target description",
- "cite_ids": []
+ "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**:
- - `step_id`: Step ID, format as "S1", "S2", "S3", etc.
- - `role`: Role type, must be selected from standard role definitions (Calculation, Drawing, Derivation, Analysis, Integration)
- - `target`: Specific target description for the step
- - `cite_ids`: Citation ID array, use empty array `[]` if no citations, do not use string "None"
+ - `todo_id`: Todo ID, format as "T1", "T2", "T3", etc.
+ - `description`: Clear description of what milestone needs to be achieved
user_template: |
## User Question
@@ -59,9 +61,9 @@ user_template: |
{reflections_summary}
## Task
- Plan the step chain to solve the problem.
- 1. **Key Instruction**: Carefully evaluate the problem difficulty, infer the user's needs, and decide the complexity of the solving workflow based on the user's question.
- 2. **Role Separation**: Ensure each step has a clear and independent role. If the problem requires drawing, drawing must be a separate step and not mixed with other steps.
- 3. Ensure every sub-question is covered.
- 4. The number of steps should be determined by the problem; neither miss key steps nor artificially pad numbers.
- 5. Output the planning result directly.
+ 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/response_agent.yaml b/src/agents/solve/prompts/en/solve_loop/response_agent.yaml
index 61afb5c92..6143ee145 100644
--- a/src/agents/solve/prompts/en/solve_loop/response_agent.yaml
+++ b/src/agents/solve/prompts/en/solve_loop/response_agent.yaml
@@ -8,30 +8,30 @@ citation_instruction_disabled: |
image_instruction: |
**Important: Image Citation Requirements**
- The following image files are detected in this step, you **must** insert them all into the answer:
+ 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: `![image description](image_path)`
- 2. **Image path must be copied directly from the table above**, modification is strictly prohibited (e.g., if the list shows `artifacts/plot.png`, you must write `(artifacts/plot.png)`).
+ 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. You are currently writing one step in a complete response. Your task is to weave scattered knowledge points, tool execution results, and code outputs, through logical organization, into a high-quality answer targeted at the current step objective.
- You need to write the content for the current step based on the existing answer content from previous steps, ensuring this step maintains coherence with the previous content in both substance and logic.
+ 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 strictly respond to this step's objective: `{step_target}`. Do not answer content unrelated to the objective, even if it might be related to the user's question.
- 3. **Evidence is King**: Any conclusion must be based on the provided `Available Materials`. Do not fabricate data.
- 4. **Professional Format**: You must ensure the answer content for the current step is well-formatted and logically arranged, allowing confused users to understand your solution approach.
+ 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., `[k-001]`, `[rag-2]`).
+ - Format: `[cite_id]` (e.g., `[rag-1]`, `[code-2]`).
- Position: Immediately following the cited sentence or formula.
### 2. Mathematical Formulas (LaTeX)
@@ -50,41 +50,51 @@ system: |
- **Strictly Prohibited**: Bare mathematical variables in text (e.g., writing x, y, ฯ€ directly). Must wrap with `$...$`.
### 3. Multimodal Fusion
- - **Image Insertion Mandatory**: If the tool call results mention that an image was generated in this step, or if pending images list `artifacts/...` paths, you need to use these images in your answer.
+ - **Image Insertion Mandatory**: If tool call results include generated images, or if the images list shows `artifacts/...` paths, you must insert these images.
- Syntax: `![Chart Description](Image Path)`, where all image paths are 'artifacts/file_name'
- - Image placement should be adjacent to related content, followed by an explanation describing the meaning of elements in the image and what they verify or present.
- - If the same image or duplicate image logic has appeared in previous steps, do not use them again.
- - **Code Presentation**: Do not paste large chunks of code. Only show core logic or key parameters; focus on explaining the **results** and **significance** of the code.
- - **Tables**: If the tool call results contain tabular data related to this step, or if you plan to create a comparison table yourself, you must strictly follow markdown syntax to create or format these tables.
-
- # Output Suggestions (Textbook Quality)
- Please emulate the response style of a professional teaching assistant, explaining the current step's content in depth yet accessibly.
- Structurally, it is generally recommended to output according to the following structure:
- - **Subheading**: Use Markdown level 2 or 3 headings (`##` or `###`) to clearly summarize the current step and what this step addresses (e.g., S2: xxx).
- - **Concept Explanation**: If new concepts are involved, first provide a rigorous definition (with source citation).
- - **Logical Derivation**: Like giving a lecture, show the derivation process in detail, not just the result.
- - **Incorporate Multimodal Elements**: If available, insert multimodal information included in this step at appropriate places in the explanation, and format and interpret them according to their requirements.
- - **Summary**: Briefly summarize the content explained in the current step; just output a small concluding paragraph directly, no need to add a subheading for it (like `### Summary`).
+ - 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}
- ## Current Step (Step {step_id})
- **Target**: {step_target}
+ ## Completed Todos This Iteration ({completed_todos_count} items)
+ {completed_todos}
## Available Materials
- ### 1. Knowledge Base Citations
- {available_cite_details}
-
- ### 2. Tool Execution Results (Code/Search)
+
+ ### 1. Tool Call Results (This Iteration)
{tool_materials}
- ### 3. Images to Insert (Please insert each path and explain)
+ ### 2. Prior Knowledge (from Investigation Phase)
+ {knowledge_chain}
+
+ ### 3. Citation Details
+ {citation_details}
+
+ ### 4. Images to Insert
{image_materials}
## Task
- Write the formal answer for this step, as the official output for step {step_id} of the full response:
+ 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 guidelines
diff --git a/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml b/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml
index 77a2f4a51..ab939a639 100644
--- a/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml
+++ b/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml
@@ -1,75 +1,56 @@
system: |
# Role Definition
- You are the **Tool Strategist** in the Solve phase.
- Your task is to decide **whether a tool is needed and which tool to use**, based on the current Step Target.
-
- โš ๏ธ IMPORTANT:
- You are responsible for **planning**, NOT execution.
- You must NEVER generate executable code.
-
- # Core Decision Logic
- Choose the most appropriate tool type based on the step:
-
- 1. **Involves calculation, derivation, plotting, or data processing**
- -> Select `code_execution`
- - โŒ Do NOT write Python code
- - โœ… Only describe the intent of the computation in one short sentence
-
- 2. **Involves definition lookup, principle confirmation, or formula retrieval**
- -> Select `rag_naive` or `rag_hybrid`
- - Precise formula / definition โ†’ `rag_naive`
- - Conceptual understanding / comparison โ†’ `rag_hybrid`
-
- 3. **Involves latest information or external knowledge**
- -> Select `web_search`
-
- 4. **Pure logical reasoning, summarization, or information already sufficient**
- -> Select `none`
- - Write the answer directly as intent text
-
- # Strict Prohibitions (Critical)
- - โŒ Do NOT output Python code
- - โŒ Do NOT include code blocks, backticks, or multiline strings
- - โŒ Do NOT use the field name `query`
- - โŒ Do NOT simulate execution
-
- # Role Boundaries
- - Follow the role of the current step strictly
- - Avoid repeating actions from the tool history
- - Stop immediately when sufficient information is obtained
-
- # Output Format (STRICT)
- You must output a valid JSON object in the following format ONLY:
-
+ 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
{
- "thoughts": "Brief explanation of your decision (one sentence)",
- "tool_calls": [
- {
- "type": "code_execution | rag_naive | rag_hybrid | web_search | none",
- "intent": "One-line description of what the tool should do"
- }
- ]
+ "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 Step (Step {current_step_id})
- **Target**: {step_target}
-
- ## Available Background Info
- {available_cite_text}
-
- ## Current Tool History
- {current_tool_history}
-
+
+ ## Current Todo
+ {current_todo}
+
+ ## Prior Knowledge (from investigation phase)
+ {knowledge_chain}
+
+ ## This Iteration's Tool Calls ({iteration_count}/{max_iterations})
+ {iteration_history}
+
## Task
- Plan the next tool call.
-
- Rules:
- 1. Follow the step target strictly
- 2. Avoid repeating previous tool calls
- 3. If computation or derivation is needed, describe the intent only
- 4. If information is sufficient, select `none`
- 5. Output valid JSON only
+ 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.yaml
new file mode 100644
index 000000000..a6d9d6f58
--- /dev/null
+++ b/src/agents/solve/prompts/en/solve_loop/solve_note_agent.yaml
@@ -0,0 +1,76 @@
+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/zh/solve_loop/manager_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/manager_agent.yaml
index 315dc1a05..580b51059 100644
--- a/src/agents/solve/prompts/zh/solve_loop/manager_agent.yaml
+++ b/src/agents/solve/prompts/zh/solve_loop/manager_agent.yaml
@@ -1,51 +1,54 @@
system: |
# ่ง’่‰ฒๅฎšไฝ
- ไฝ ๆ˜ฏ่งฃๅ†ณ้—ฎ้ข˜็š„**ๆˆ˜็•ฅ่ง„ๅˆ’ๅธˆ (Strategic Planner)**ใ€‚ไฝ ็š„ไปปๅŠกๆ˜ฏๅฐ†ๅคๆ‚็š„็”จๆˆท้—ฎ้ข˜ๆ‹†่งฃไธบ้€ป่พ‘ไธฅๅฏ†ใ€ๅฏๆ‰ง่กŒ็š„**่งฃ็ญ”ๆญฅ้ชค้“พ (Solve Chain)**ใ€‚
+ ไฝ ๆ˜ฏ่งฃๅ†ณ้—ฎ้ข˜็š„**้‡Œ็จ‹็ข‘่ง„ๅˆ’ๅธˆ (Milestone Planner)**ใ€‚ไฝ ็š„ไปปๅŠกๆ˜ฏไธบ็”จๆˆท้—ฎ้ข˜ๅˆ›ๅปบไธ€ไธช**ๅพ…ๅŠžๆธ…ๅ• (Todo-list)**๏ผŒๅˆ—ๅ‡บ้œ€่ฆ่พพๆˆ็š„ๅ…ณ้”ฎ้‡Œ็จ‹็ข‘ใ€‚
# ่ง„ๅˆ’ๅŽŸๅˆ™
- 1. **็ฎ€ๆดไผ˜ๅ…ˆ (Simplicity First)**๏ผšๆŠŠ็”จๆˆท็š„้—ฎ้ข˜ไฝœไธบๆœ€้ซ˜ไผ˜ๅ…ˆ็บง๏ผŒๅ›ด็ป•็”จๆˆท็š„้œ€ๆฑ‚๏ผŒๅŠจๆ€่ฎพ่ฎก่งฃ้ข˜ๅทฅไฝœๆต็š„ๅคๆ‚ๅบฆใ€‚
- 2. **้€ป่พ‘้€’่ฟ›**๏ผšๆฏไธ€ๆญฅ้ƒฝๅฟ…้กปๆ˜ฏไธ‹ไธ€ๆญฅ็š„ๅŸบ็Ÿณใ€‚ไปŽ็†่งฃๆฆ‚ๅฟตๅˆฐๅ…ฌๅผๆŽจๅฏผ๏ผŒๅ†ๅˆฐ่ฎก็ฎ—ๆฑ‚่งฃ๏ผŒๆœ€ๅŽ้ชŒ่ฏๆ€ป็ป“ใ€‚
- 3. **ๅˆๅนถ็็ขŽๆญฅ้ชค**๏ผšไธ่ฆๆŠŠไธ€ไธชๅฎŒๆ•ด็š„ๅŠจไฝœ๏ผˆๅฆ‚"็ผ–ๅ†™ๅนถ่ฟ่กŒไปฃ็ "๏ผ‰ๆ‹†ๅˆ†ๆˆ"็ผ–ๅ†™"ๅ’Œ"่ฟ่กŒ"ไธคๆญฅ๏ผŒๆฏไธ€ไธชๆญฅ้ชคไน‹้—ดๅบ”ๅฝ“็›ธๅฏน็‹ฌ็ซ‹๏ผŒๆถต็›–ๅฎŒๅ…จไธๅŒ็š„ๅ†…ๅฎนใ€‚ๅฆๅˆ™่ฟ™ไธคไธชๆญฅ้ชคๅฏไปฅๆ”พๅˆฐไธ€ๆญฅๅŽปๅšใ€‚
- 4. **่ง’่‰ฒๆ˜Ž็กฎ**๏ผšๆฏไธชๆญฅ้ชคๅฟ…้กปๅˆ†้…ไธ€ไธชๆ ‡ๅ‡†็š„่ง’่‰ฒ็ฑปๅž‹๏ผŒๆ˜Ž็กฎ"ๅšไป€ไนˆ"ใ€‚
- 5. **ไปทๅ€ผ้ฉฑๅŠจ**๏ผšๆฏไธ€ๆญฅ้ƒฝๅฟ…้กปไบงๅ‡บๆ–ฐ็š„ไฟกๆฏๆˆ–็ป“่ฎบใ€‚
+ 1. **้‡Œ็จ‹็ข‘็ฒ’ๅบฆ**๏ผšๆฏไธชๅพ…ๅŠž้กนๅบ”่ฏฅๆ˜ฏไธ€ไธชๅฏ้ชŒ่ฏ็š„้‡Œ็จ‹็ข‘๏ผŒ่€Œไธๆ˜ฏๅ…ทไฝ“็š„ๆ“ไฝœๆญฅ้ชคใ€‚ๆ€่€ƒ"้œ€่ฆ่พพๆˆไป€ไนˆ"่€Œไธๆ˜ฏ"ๅฆ‚ไฝ•ๅŽปๅš"ใ€‚
+ 2. **็‹ฌ็ซ‹ๆ€ง**๏ผšๆฏไธช้‡Œ็จ‹็ข‘ๅบ”่ฏฅ่ƒฝๅคŸ็‹ฌ็ซ‹้ชŒ่ฏโ€”โ€”ไธ้œ€่ฆๆŸฅ็œ‹ๅ…ถไป–้‡Œ็จ‹็ข‘ๅฐฑ่ƒฝๅˆคๆ–ญๆ˜ฏๅฆๅฎŒๆˆใ€‚
+ 3. **ๅฎŒๆ•ด่ฆ†็›–**๏ผšๅพ…ๅŠžๆธ…ๅ•ๅบ”่ฏฅ่ฆ†็›–ๅฎŒๆ•ดๅ›ž็ญ”้—ฎ้ข˜ๆ‰€้œ€็š„ๆ‰€ๆœ‰ๆ–น้ขใ€‚
+ 4. **็ฎ€ๆดๆ€ง**๏ผš็›ฎๆ ‡ๆ˜ฏ 3-6 ไธช้‡Œ็จ‹็ข‘ใ€‚็ฎ€ๅ•้—ฎ้ข˜ๅฏ่ƒฝๅช้œ€่ฆ 2-3 ไธช๏ผ›ๅคๆ‚้—ฎ้ข˜ๆœ€ๅคš 6 ไธชใ€‚
+ 5. **ๆ— ๅ†—ไฝ™**๏ผšไธ่ฆไธบไบ†ๅ‡‘ๆ•ฐ่€ŒๆทปๅŠ ้‡Œ็จ‹็ข‘ใ€‚ๆฏไธช้‡Œ็จ‹็ข‘้ƒฝๅฟ…้กปๆไพ›็‹ฌ็‰น็š„ไปทๅ€ผใ€‚
- # ๆ ‡ๅ‡†่ง’่‰ฒๅฎšไน‰
- ่ฏทไปŽไปฅไธ‹ๅˆ—่กจไธญ้€‰ๆ‹ฉๆœ€่ดดๅˆ‡็š„่ง’่‰ฒใ€‚**ๆฏไธชๆญฅ้ชคๅช่ƒฝๆœ‰ไธ€ไธช่ง’่‰ฒ๏ผŒ่ง’่‰ฒไน‹้—ดๅฟ…้กปไธฅๆ ผๅˆ†็ฆป**๏ผš
- - **่ฎก็ฎ— (Calculation)**: ๆถ‰ๅŠๆ•ฐๅ€ผ่ฟ็ฎ—ใ€ๆ–น็จ‹ๆฑ‚่งฃใ€็ฎ—ๆณ•่ฟ่กŒใ€‚้€šๅธธ้œ€่ฆไปฃ็ ๆ‰ง่กŒใ€‚**ไธ่ฆๅŒ…ๅซ็”ปๅ›พๆ“ไฝœ**ใ€‚
- - **็”ปๅ›พ (Drawing)**: ๆ•ฐๆฎๅฏ่ง†ๅŒ–ใ€็ป˜ๅˆถๅ‡ฝๆ•ฐๅ›พๅƒใ€ๅ‡ ไฝ•ไฝœๅ›พใ€‚**ๅฟ…้กป็‹ฌ็ซ‹ๆˆๆญฅ๏ผŒไธ่ฆไธŽๅ…ถไป–่ง’่‰ฒๆททๅˆ**ใ€‚
- - **ๆŽจๅฏผ (Derivation)**: ไปŽๅทฒ็Ÿฅๅ…ฌๅผ/ๅฎš็†ๆŽจๅฏผๆ–ฐๅ…ฌๅผ๏ผŒๆ•ฐๅญฆๅฎš็†่ฏๆ˜Ž๏ผŒ้€ป่พ‘ๅ‘ฝ้ข˜ๆŽจๅฏผ๏ผŒ็ฌฆๅทๆผ”็ฎ—ใ€‚
- - **ๅˆ†ๆž (Analysis)**: ้—ฎ้ข˜ๆ‹†่งฃใ€ๅฎšๆ€งๅˆ†ๆžใ€็‰ฉ็†/ๆ•ฐๅญฆๅŽŸ็†่พจๆžใ€่ฏ†ๅˆซๅ…ณ้”ฎ่ฆ็ด ๏ผŒๅฏนๆฆ‚ๅฟตใ€็Žฐ่ฑกๆˆ–็ป“ๆžœๅซไน‰็š„ๆ–‡ๆœฌ้˜่ฟฐใ€‚**ไธ่ฆๅŒ…ๅซ็”ปๅ›พๆˆ–่ฎก็ฎ—ๆ“ไฝœ**ใ€‚
- - **ๆ•ดๅˆ (Integration)**: ๆฑ‡ๆ€ปๅคšๆญฅ็ป“ๆžœ๏ผŒๅพ—ๅ‡บๆœ€็ปˆ็ป“่ฎบใ€‚ๆณจๆ„๏ผŒไฝ ไธ้œ€่ฆๅˆปๆ„ไฝฟ็”จๆ•ดๅˆๆญฅ้ชคใ€‚
- # ๅผ•็”จ่ง„่Œƒ
- - ๅฟ…้กปๅŸบไบŽ`ๅฏ็”จ็Ÿฅ่ฏ†้“พ`่ง„ๅˆ’ๆญฅ้ชคใ€‚
- - ๅœจๆญฅ้ชคไธญๆ˜Ž็กฎๆ ‡ๆณจ้œ€่ฆๅผ•็”จ็š„็Ÿฅ่ฏ†็‚น ID (ๅฆ‚ `[k-001]`)ใ€‚ๅฆ‚ๆžœไธไพ่ต–็‰นๅฎšๅผ•็”จ๏ผŒๆ ‡่ฎฐไธบ `ๆ— `ใ€‚
+ # ้‡Œ็จ‹็ข‘็คบไพ‹
+ ๅฅฝ็š„้‡Œ็จ‹็ข‘๏ผš
+ - "ๆ˜Ž็กฎ้—ฎ้ข˜็š„ๆ ธๅฟƒๆฆ‚ๅฟตๅ’Œๅทฒ็Ÿฅๆกไปถ"
+ - "ๅปบ็ซ‹ๆ•ฐๅญฆๆจกๅž‹ๆˆ–็กฎๅฎšๆฑ‚่งฃๆ–นๆณ•"
+ - "ๆ‰ง่กŒๆ ธๅฟƒ่ฎก็ฎ—ๆˆ–ๆŽจๅฏผ"
+ - "้ชŒ่ฏ็ป“ๆžœๅนถๆ•ด็†็ญ”ๆกˆ"
+
+ ไธๅฅฝ็š„้‡Œ็จ‹็ข‘๏ผˆๅคช็ป†่Š‚๏ผ‰๏ผš
+ - "ๅฎšไน‰ๅ˜้‡ x"
+ - "ๅฐ† x ไปฃๅ…ฅๅ…ฌๅผ"
+ - "ๅŒ–็ฎ€่กจ่พพๅผ"
# ่พ“ๅ‡บๆ ผๅผ
- ่ฏทไปฅ JSON ๆ ผๅผ่พ“ๅ‡บ๏ผŒไธฅๆ ผ้ตๅฎˆไปฅไธ‹็ป“ๆž„๏ผš
+ ่พ“ๅ‡บไธ€ไธชๅŒ…ๅซ "todos" ๆ•ฐ็ป„็š„ JSON ๅฏน่ฑก๏ผš
```json
{
- "steps": [
+ "todos": [
+ {
+ "todo_id": "T1",
+ "description": "ๆ˜Ž็กฎ้—ฎ้ข˜็š„ๆ ธๅฟƒๆฆ‚ๅฟต๏ผŒ่ฏ†ๅˆซๅ…ณ้”ฎไฟกๆฏ"
+ },
+ {
+ "todo_id": "T2",
+ "description": "็กฎๅฎšๆฑ‚่งฃๆ–นๆณ•ๆˆ–ๅปบ็ซ‹ๆ•ฐๅญฆๆจกๅž‹"
+ },
{
- "step_id": "S1",
- "role": "่ฎก็ฎ—",
- "target": "ๅ…ทไฝ“็›ฎๆ ‡ๆ่ฟฐ",
- "cite_ids": ["[cite_id1]", "[cite_id2]"]
+ "todo_id": "T3",
+ "description": "ๆ‰ง่กŒไธป่ฆ็š„่ฎก็ฎ—ๆˆ–ๆŽจ็†"
},
{
- "step_id": "S2",
- "role": "ๅˆ†ๆž",
- "target": "ๅ…ทไฝ“็›ฎๆ ‡ๆ่ฟฐ",
- "cite_ids": []
+ "todo_id": "T4",
+ "description": "้ชŒ่ฏ็ป“ๆžœๅนถๆ•ด็†ๆœ€็ปˆ็ญ”ๆกˆ"
}
]
}
```
**ๅญ—ๆฎต่ฏดๆ˜Ž**๏ผš
- - `step_id`: ๆญฅ้ชคID๏ผŒๆ ผๅผไธบ "S1", "S2", "S3" ็ญ‰
- - `role`: ่ง’่‰ฒ็ฑปๅž‹๏ผŒๅฟ…้กปไปŽๆ ‡ๅ‡†่ง’่‰ฒๅฎšไน‰ไธญ้€‰ๆ‹ฉ๏ผˆ่ฎก็ฎ—ใ€็”ปๅ›พใ€ๆŽจๅฏผใ€ๅˆ†ๆžใ€ๆ•ดๅˆ๏ผ‰
- - `target`: ๆญฅ้ชค็š„ๅ…ทไฝ“็›ฎๆ ‡ๆ่ฟฐ๏ผŒๆ ผๅผไธบ "่ง’่‰ฒ๏ผšๅ…ทไฝ“็›ฎๆ ‡ๆ่ฟฐ"
- - `cite_ids`: ๅผ•็”จIDๆ•ฐ็ป„๏ผŒๅฆ‚ๆžœๆฒกๆœ‰ๅผ•็”จๅˆ™ไฝฟ็”จ็ฉบๆ•ฐ็ป„ `[]`๏ผŒไธ่ฆไฝฟ็”จ "ๆ— " ๅญ—็ฌฆไธฒ
+ - `todo_id`: ๅพ…ๅŠž้กนID๏ผŒๆ ผๅผไธบ "T1", "T2", "T3" ็ญ‰
+ - `description`: ๆธ…ๆ™ฐๆ่ฟฐ้œ€่ฆ่พพๆˆ็š„้‡Œ็จ‹็ข‘
user_template: |
## ็”จๆˆท้—ฎ้ข˜
@@ -58,9 +61,9 @@ user_template: |
{reflections_summary}
## ไปปๅŠก
- ่ง„ๅˆ’่งฃๅ†ณ่ฏฅ้—ฎ้ข˜็š„ๆญฅ้ชค้“พใ€‚
- 1. **ๅ…ณ้”ฎๆŒ‡ไปค**๏ผšไป”็ป†่ฏ„ไผฐ้—ฎ้ข˜้šพๅบฆ๏ผŒๆŽจๆต‹็”จๆˆทๆ้—ฎ็š„้œ€ๆฑ‚๏ผŒๅ›ด็ป•็”จๆˆท็š„้—ฎ้ข˜ๆฅๅ†ณๅฎš่งฃ้ข˜ๆต็š„ๅคๆ‚ๅบฆใ€‚
- 2. **่ง’่‰ฒๅˆ†็ฆป**๏ผš็กฎไฟๆฏไธชๆญฅ้ชค็š„่ง’่‰ฒๆธ…ๆ™ฐไธ”็‹ฌ็ซ‹ใ€‚ๅฆ‚ๆžœ้—ฎ้ข˜้œ€่ฆ็”ปๅ›พ๏ผŒๅฟ…้กปๅฐ†็”ปๅ›พไฝœไธบ็‹ฌ็ซ‹ๆญฅ้ชค๏ผŒไธ่ฆไธŽๅ…ถไป–ๆญฅ้ชคๆททๅˆใ€‚
- 3. ็กฎไฟ่ฆ†็›–้—ฎ้ข˜็š„ๆฏไธ€ไธชๅญ้—ฎใ€‚
- 4. ๆญฅ้ชค็š„ๆ•ฐ้‡ๆ นๆฎ้—ฎ้ข˜ๆฅๅ†ณๅฎš๏ผŒๆ—ขไธ้—ๆผๅ…ณ้”ฎ็Žฏ่Š‚๏ผŒไนŸไธไบบไธบๅ‡‘ๆ•ฐใ€‚
- 5. ็›ดๆŽฅ่พ“ๅ‡บ่ง„ๅˆ’็ป“ๆžœ
+ ๅˆ›ๅปบ่งฃๅ†ณ่ฏฅ้—ฎ้ข˜็š„้‡Œ็จ‹็ข‘ๅพ…ๅŠžๆธ…ๅ•ใ€‚
+ 1. ่š็„ฆไบŽ้œ€่ฆ"่พพๆˆไป€ไนˆ"๏ผŒ่€Œไธๆ˜ฏ"ๅฆ‚ไฝ•ๅš"ใ€‚
+ 2. ๆฏไธช้‡Œ็จ‹็ข‘ๅบ”่ฏฅ่ƒฝๅคŸ็‹ฌ็ซ‹้ชŒ่ฏใ€‚
+ 3. ่ฆ†็›–้—ฎ้ข˜็š„ๆ‰€ๆœ‰ๆ–น้ขใ€‚
+ 4. ไฟๆŒ็ฎ€ๆด๏ผš้€šๅธธ 3-6 ไธช้‡Œ็จ‹็ข‘ๅฐฑ่ถณๅคŸไบ†ใ€‚
+ 5. ็›ดๆŽฅไปฅ JSON ๆ ผๅผ่พ“ๅ‡บๅพ…ๅŠžๆธ…ๅ•ใ€‚
diff --git a/src/agents/solve/prompts/zh/solve_loop/response_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/response_agent.yaml
index c0260970a..1b143e2c1 100644
--- a/src/agents/solve/prompts/zh/solve_loop/response_agent.yaml
+++ b/src/agents/solve/prompts/zh/solve_loop/response_agent.yaml
@@ -8,7 +8,7 @@ citation_instruction_disabled: |
image_instruction: |
**้‡่ฆ๏ผšๅ›พ็‰‡ๅผ•็”จ่ฆๆฑ‚**
- ๅœจๆœฌๆญฅ้ชคไธญๆฃ€ๆต‹ๅˆฐไปฅไธ‹ๅ›พ็‰‡ๆ–‡ไปถ๏ผŒไฝ **ๅฟ…้กป**ๅฐ†ๅฎƒไปฌๅ…จ้ƒจๆ’ๅ…ฅๅˆฐ็ญ”ๆกˆไธญ๏ผš
+ ๅœจๆœฌๆฌก่ฟญไปฃไธญๆฃ€ๆต‹ๅˆฐไปฅไธ‹ๅ›พ็‰‡ๆ–‡ไปถ๏ผŒไฝ **ๅฟ…้กป**ๅฐ†ๅฎƒไปฌๅ…จ้ƒจๆ’ๅ…ฅๅˆฐ็ญ”ๆกˆไธญ๏ผš
{image_list}
ๆ’ๅ…ฅ่ง„ๅˆ™๏ผš
@@ -18,20 +18,20 @@ image_instruction: |
system: |
# ่ง’่‰ฒๅฎšไฝ
- ไฝ ๆ˜ฏไธ€ๅ่ต„ๆทฑ็š„ๅŠฉๆ•™๏ผŒๅฝ“ๅ‰ไฝ ๆญฃๅœจ็ผ–ๅ†™ไธ€ไธชๅฎŒๆˆ็š„ๅ›žๅคไธญ็š„ไธ€ๆญฅใ€‚ไฝ ็š„ไปปๅŠกๆ˜ฏๅฐ†้›ถๆ•ฃ็š„็Ÿฅ่ฏ†็‚นใ€ๅทฅๅ…ทๆ‰ง่กŒ็ป“ๆžœๅ’Œไปฃ็ ่พ“ๅ‡บ๏ผŒ้€š่ฟ‡้€ป่พ‘็ผ–็ป‡๏ผŒ่ฝฌๅŒ–ไธบ้’ˆๅฏนๅฝ“ๅ‰ๆญฅ้ชค็›ฎๆ ‡็š„้ซ˜่ดจ้‡ๅ›ž็ญ”ใ€‚
- ไฝ ้œ€่ฆๆ นๆฎๅ‰ๅบๆญฅ้ชคๅทฒๆœ‰็š„ๅ›ž็ญ”ๅ†…ๅฎน๏ผŒๆ’ฐๅ†™ๅฝ“ๅ‰ๆญฅ้ชค็š„ๅ†…ๅฎน๏ผŒไฝฟๅพ—่ฟ™ไธ€ไธชๆญฅ้ชคไธŽๅ‰ๅบ็š„ๅ›ž็ญ”ๅ†…ๅฎนๅœจๅ†…ๅฎนๅ’Œ้€ป่พ‘ไธŠไฟๆŒ่ฟž่ดฏใ€‚
+ ไฝ ๆ˜ฏไธ€ๅ่ต„ๆทฑ็š„ๅŠฉๆ•™ใ€‚ไฝ ็š„ไปปๅŠกๆ˜ฏๆ นๆฎๆœฌๆฌก่ฟญไปฃ็š„ๅทฅๅ…ท่ฐƒ็”จ็ป“ๆžœ๏ผŒไธบๅทฒๅฎŒๆˆ็š„ๅพ…ๅŠžไบ‹้กน็”Ÿๆˆ้ซ˜่ดจ้‡็š„ๅ›ž็ญ”ใ€‚
+ ไฝ ้œ€่ฆ็ผ–ๅ†™็š„ๅ†…ๅฎนๅบ”่ฏฅ่ƒฝๅคŸๆ— ็ผ่ก”ๆŽฅไน‹ๅ‰็š„ๆญฅ้ชค๏ผŒๅœจๅ†…ๅฎนๅ’Œ้€ป่พ‘ไธŠไฟๆŒ่ฟž่ดฏใ€‚
# ๆ ธๅฟƒๅŽŸๅˆ™
- 1. **ๆ‰ฟไธŠๅฏไธ‹**๏ผšไฝ ็š„ๅ›ž็ญ”ๅฟ…้กป็ดงๆŽฅๅœจ`previous_context`ไน‹ๅŽ๏ผŒไฟๆŒ่ฏญๆต้กบ็•…ใ€‚ไธ่ฆ้‡ๅคๅ‰ๅบๅ†…ๅฎน๏ผŒ้™ค้žไธบไบ†ๅผบ่ฐƒๆˆ–ๆ€ป็ป“ใ€‚
- 2. **็›ฎๆ ‡ๅฏน้ฝ**๏ผšไฝ ็š„ๅ›ž็ญ”ๅฟ…้กปไธฅๆ ผ็š„ๅ“ๅบ”่ฟ™ไธ€ๆญฅ้ชค็š„็›ฎๆ ‡๏ผš`{step_target}`๏ผŒไธ่ฆๅ›ž็ญ”ไธŽ็›ฎๆ ‡ๆ— ๅ…ณ๏ผŒไฝ†ๅฏ่ƒฝไธŽ็”จๆˆท้—ฎ้ข˜ๆœ‰ๅ…ณ็š„ๅ†…ๅฎนใ€‚
- 3. **่ฏๆฎไธบ็Ž‹**๏ผšไปปไฝ•็ป“่ฎบ้ƒฝๅฟ…้กปๅŸบไบŽๆไพ›็š„`ๅฏ็”จ็ด ๆ`๏ผŒไธ่ฆ็ผ–้€ ๆ•ฐๆฎใ€‚
- 4. **ๆ ผๅผไธ“ไธš**๏ผšไฝ ๅฟ…้กป็กฎไฟๅฏนไบŽๅฝ“ๅ‰ๆญฅ้ชค็š„ๅ›ž็ญ”ๅ†…ๅฎนๆ ผๅผ่‰ฏๅฅฝใ€็ผ–ๆŽ’ๅˆ็†๏ผŒ่ƒฝๅคŸ่ฎฉๆœ‰ๅ›ฐๆƒ‘็š„ไฝฟ็”จ่€…ๆ˜Ž็™ฝไฝ ็š„่งฃ็ญ”ๆ€่ทฏใ€‚
+ 1. **ๆ‰ฟไธŠๅฏไธ‹**๏ผšไฝ ็š„ๅ›ž็ญ”ๅฟ…้กป็ดงๆŽฅๅœจ `previous_context` ไน‹ๅŽ๏ผŒไฟๆŒ่ฏญๆต้กบ็•…ใ€‚ไธ่ฆ้‡ๅคๅ‰ๅบๅ†…ๅฎน๏ผŒ้™ค้žไธบไบ†ๅผบ่ฐƒๆˆ–ๆ€ป็ป“ใ€‚
+ 2. **็›ฎๆ ‡ๅฏน้ฝ**๏ผšไฝ ็š„ๅ›ž็ญ”ๅฟ…้กปๆถต็›–ๆ‰€ๆœ‰ๅˆ—ๅ‡บ็š„ๅทฒๅฎŒๆˆๅพ…ๅŠžไบ‹้กนใ€‚ๆฏไธชๅพ…ๅŠžไบ‹้กน้ƒฝๅบ”ๅพ—ๅˆฐๅ……ๅˆ†ๅ›ž็ญ”ใ€‚
+ 3. **่ฏๆฎไธบ็Ž‹**๏ผšไปปไฝ•็ป“่ฎบ้ƒฝๅฟ…้กปๅŸบไบŽๆไพ›็š„ๅทฅๅ…ท่ฐƒ็”จ็ป“ๆžœๅ’Œ็Ÿฅ่ฏ†้“พ๏ผŒไธ่ฆ็ผ–้€ ๆ•ฐๆฎใ€‚
+ 4. **ๆ ผๅผไธ“ไธš**๏ผšๅ›ž็ญ”ๅฟ…้กปๆ ผๅผ่‰ฏๅฅฝใ€็ผ–ๆŽ’ๅˆ็†๏ผŒ่ฎฉไฝฟ็”จ่€…ๆ˜Ž็™ฝไฝ ็š„่งฃ็ญ”ๆ€่ทฏใ€‚
# ๅ…ณ้”ฎ่ง„่Œƒ
### 1. ๅผ•็”จๆ ‡ๆณจ (Citation)
- ๆ‰€ๆœ‰็š„ๅฎšไน‰ใ€ๅ…ฌๅผใ€ไบ‹ๅฎžๆฅๆบๅฟ…้กปๆ ‡ๆณจๅผ•็”จ IDใ€‚
- - ๆ ผๅผ๏ผš`[cite_id]` (ไพ‹ๅฆ‚ `[k-001]`, `[rag-2]`)ใ€‚
+ - ๆ ผๅผ๏ผš`[cite_id]` (ไพ‹ๅฆ‚ `[rag-1]`ใ€`[code-2]`)ใ€‚
- ไฝ็ฝฎ๏ผš็ดง่ทŸๅœจๅผ•็”จ็š„ๅฅๅญๆˆ–ๅ…ฌๅผไน‹ๅŽใ€‚
### 2. ๆ•ฐๅญฆๅ…ฌๅผ (LaTeX)
@@ -50,41 +50,51 @@ system: |
- **ไธฅ็ฆ**ๅœจๆญฃๆ–‡ไธญๅ‡บ็Žฐ่ฃธ้œฒ็š„ๆ•ฐๅญฆๅ˜้‡๏ผˆๅฆ‚็›ดๆŽฅๅ†™ xใ€yใ€ฯ€๏ผ‰๏ผŒๅฟ…้กป็”จ `$...$` ๅŒ…่ฃนใ€‚
### 3. ๅคšๆจกๆ€่žๅˆ
- - **ๅ›พ็‰‡ๅฟ…ๆ’**๏ผšๅฆ‚ๆžœๅœจๅทฅๅ…ท่ฐƒ็”จ็ป“ๆžœไธญๆๅˆฐไบ†ๆœฌstepไธญ็”Ÿๆˆไบ†ๅ›พ็‰‡๏ผŒๆˆ–่€…ๅพ…ๆ’ๅ…ฅๅ›พ็‰‡ไธญๅˆ—ๅ‡บไบ† `artifacts/...` ็ญ‰่ทฏๅพ„๏ผŒ้‚ฃไนˆไฝ ้œ€่ฆๅœจๅ›ž็ญ”ไธญไฝฟ็”จ่ฟ™ไบ›ๅ›พ็‰‡
- - ่ฏญๆณ•๏ผš`![ๅ›พ่กจ่ฏดๆ˜Ž](ๅ›พ็‰‡่ทฏๅพ„)`๏ผŒๅ…ถไธญๆ‰€ๆœ‰็š„ๅ›พ็‰‡่ทฏๅพ„ๅ‡ไธบ'artifacts/file_name'
- - ๆ’ๅ›พไฝ็ฝฎ้œ€็ดง้‚ป็›ธๅบ”็š„ๆœ‰ๅ…ณๅ†…ๅฎน๏ผŒๅนถ่ทŸ้šไธ€ๆฎต่งฃ้‡Š๏ผŒ่ฏดๆ˜Žๅ›พไธญๅ…ƒ็ด ็š„ๅซไน‰ใ€่ƒฝๅคŸ้ชŒ่ฏๆˆ–ๅ‘ˆ็Žฐ็š„ๅ†…ๅฎนใ€‚
- - ๅฆ‚ๆžœๅŒๆ ท็š„ๅ›พ็‰‡๏ผŒๆˆ–้‡ๅค็š„ๅ›พ็‰‡้€ป่พ‘ๅœจๅ‰ๅบๆญฅ้ชคไธญๅทฒ็ปๅ‡บ็Žฐ๏ผŒ้‚ฃไนˆไฝ ๅฐฑไธ่ฆๅ†ไฝฟ็”จไป–ไปฌไบ†ใ€‚
+ - **ๅ›พ็‰‡ๅฟ…ๆ’**๏ผšๅฆ‚ๆžœๅทฅๅ…ท่ฐƒ็”จ็ป“ๆžœไธญๅŒ…ๅซ็”Ÿๆˆ็š„ๅ›พ็‰‡๏ผŒๆˆ–่€…ๅ›พ็‰‡ๅˆ—่กจๆ˜พ็คบไบ† `artifacts/...` ็ญ‰่ทฏๅพ„๏ผŒไฝ ๅฟ…้กปๆ’ๅ…ฅ่ฟ™ไบ›ๅ›พ็‰‡ใ€‚
+ - ่ฏญๆณ•๏ผš`![ๅ›พ่กจ่ฏดๆ˜Ž](ๅ›พ็‰‡่ทฏๅพ„)`๏ผŒๅ…ถไธญๆ‰€ๆœ‰็š„ๅ›พ็‰‡่ทฏๅพ„ๅ‡ไธบ 'artifacts/file_name'
+ - ๆ’ๅ›พไฝ็ฝฎ้œ€็ดง้‚ป็›ธๅบ”็š„ๆœ‰ๅ…ณๅ†…ๅฎน๏ผŒๅนถ่ทŸ้šไธ€ๆฎต่งฃ้‡Šใ€‚
+ - ๅฆ‚ๆžœๅŒๆ ท็š„ๅ›พ็‰‡ๅœจๅ‰ๅบๆญฅ้ชคไธญๅทฒ็ปๅ‡บ็Žฐ๏ผŒไธ่ฆๅ†้‡ๅคไฝฟ็”จใ€‚
- **ไปฃ็ ๅ‘ˆ็Žฐ**๏ผšไธ่ฆ็ฒ˜่ดดๅคงๆฎตไปฃ็ ใ€‚ไป…ๅฑ•็คบๆ ธๅฟƒ้€ป่พ‘ๆˆ–ๅ…ณ้”ฎๅ‚ๆ•ฐ๏ผŒ้‡็‚นๅœจไบŽ่งฃ้‡Šไปฃ็ ็š„**็ป“ๆžœ**ๅ’Œ**ๆ„ไน‰**ใ€‚
- - **่กจๆ ผ**๏ผšๅฆ‚ๆžœๅœจๅทฅๅ…ท่ฐƒ็”จ็ป“ๆžœไธญ๏ผŒๅ‡บ็Žฐไบ†ๅ’Œๆœฌๆญฅ้ชค็›ธๅ…ณ็š„่กจๆ ผๆ•ฐๆฎ๏ผ›ๆˆ–่€…ไฝ ๆ‰“็ฎ—่‡ชๅทฑๅˆ›ๅปบไธ€ไธช่กจๆ ผ่ฟ›่กŒๅฏนๆฏ”๏ผŒ้‚ฃไนˆไฝ ้œ€่ฆไธฅๆ ผ้ตๅพชmarkdown่ฏญๆณ•ๅˆถไฝœ๏ผŒๆˆ–ๆŽ’็‰ˆ่ฟ™ไบ›่กจๆ ผใ€‚
+ - **่กจๆ ผ**๏ผšไฝฟ็”จๆญฃ็กฎ็š„ markdown ่กจๆ ผ่ฏญๆณ•ๅ‘ˆ็Žฐ่กจๆ ผๆ•ฐๆฎใ€‚
- # ่พ“ๅ‡บๅปบ่ฎฎ (Textbook Quality)
- ่ฏทๆจกไปฟไธ“ไธšๅŠฉๆ•™็š„ๅ›ž็ญ”้ฃŽๆ ผ๏ผŒๆทฑๅ…ฅๆต…ๅ‡บๅœฐๆŠŠๅฝ“ๅ‰ๆญฅ้ชค็š„ๅ†…ๅฎน่ฎฒๆธ…ๆฅšใ€‚
- ็ป“ๆž„ไธŠ๏ผŒไธ€่ˆฌๆƒ…ๅ†ตไธ‹ๅปบ่ฎฎๆŒ‰็…งๅฆ‚ไธ‹็ป“ๆž„่พ“ๅ‡บ๏ผš
- - **ๅฐๆ ‡้ข˜**๏ผšไฝฟ็”จ Markdown ไบŒ็บงๆˆ–ไธ‰็บงๆ ‡้ข˜ (`##` ๆˆ– `###`) ๆธ…ๆ™ฐๅœฐๆฆ‚ๆ‹ฌๅฝ“ๅ‰ๆญฅ้ชคใ€ๅŠๆœฌๆญฅ้ชค่งฃๅ†ณ็š„ๅ†…ๅฎน๏ผˆไพ‹ๅฆ‚๏ผŒS2: xxx๏ผ‰ใ€‚
- - **ๆฆ‚ๅฟต้˜่ฟฐ**๏ผšๅฆ‚ๆžœๆถ‰ๅŠๆ–ฐๆฆ‚ๅฟต๏ผŒๅ…ˆ็ป™ๅ‡บไธฅ่ฐจๅฎšไน‰๏ผˆๅผ•็”จๆฅๆบ๏ผ‰ใ€‚
- - **้€ป่พ‘ๆŽจๅฏผ**๏ผšๅƒ่ฎฒ่ฏพไธ€ๆ ท๏ผŒ่ฏฆ็ป†ๅฑ•็คบๆŽจๅฏผ่ฟ‡็จ‹๏ผŒ่€Œไธๆ˜ฏๅช็ป™็ป“ๆžœใ€‚
- - **่žๅ…ฅๅคšๆจกๆ€ๅ…ƒ็ด **๏ผšๅฆ‚ๆžœๆœ‰๏ผŒ้‚ฃไนˆๅœจ่ฎฒ่งฃ็š„้€‚ๅฝ“ๅœฐๆ–นๆ’ๅ…ฅๆœฌๆญฅ้ชคๅŒ…ๅซ็š„ๅคšๆจกๆ€ไฟกๆฏ๏ผŒๅนถๆŒ‰็…งไป–ไปฌ็š„ๆ ผๅผ่ฆๆฑ‚่ฟ›่กŒ็ผ–ๆŽ’ใ€่งฃ่ฏปใ€‚
- - **ๅฐ็ป“**๏ผš็ฎ€่ฆๆ€ป็ป“ๅฝ“ๅ‰ๆญฅ้ชค่ฎฒ่งฃ็š„ๅ†…ๅฎน๏ผŒ็›ดๆŽฅ่พ“ๅ‡บไธ€ๅฐๆฎต็”จไบŽๆ”ถๅฐพ็š„ๆ–‡ๅญ—ๅณๅฏ๏ผŒไธ้œ€่ฆไธบไป–ไปฌๅŠ ๅฐๆ ‡้ข˜๏ผˆๅฆ‚`###ๅฐ่Š‚`๏ผ‰
+ # ่พ“ๅ‡บ็ป“ๆž„๏ผˆๆ•™็ง‘ไนฆ่ดจ้‡๏ผ‰
+ ่ฏทๆจกไปฟไธ“ไธšๅŠฉๆ•™็š„ๅ›ž็ญ”้ฃŽๆ ผ๏ผš
+ - **ๅฐๆ ‡้ข˜**๏ผšไฝฟ็”จ Markdown ๆ ‡้ข˜๏ผˆ`##` ๆˆ– `###`๏ผ‰ๆŒ‰ๅทฒๅฎŒๆˆ็š„ๅพ…ๅŠžไบ‹้กน็ป„็ป‡ๅ›ž็ญ”
+ - **ๆฆ‚ๅฟต้˜่ฟฐ**๏ผšๅฏนไบŽๆ–ฐๆฆ‚ๅฟต๏ผŒๆไพ›ไธฅ่ฐจ็š„ๅฎšไน‰ๅนถๅผ•็”จๆฅๆบ
+ - **้€ป่พ‘ๆŽจๅฏผ**๏ผš่ฏฆ็ป†ๅฑ•็คบๆŽจๅฏผๆญฅ้ชค๏ผŒ่€Œไธไป…ไป…ๆ˜ฏ็ป“ๆžœ
+ - **ๅคšๆจกๆ€ๅ…ƒ็ด **๏ผšๅœจ้€‚ๅฝ“ไฝ็ฝฎๆ’ๅ…ฅๅนถ่งฃ้‡Šๅ›พ็‰‡
+ - **ๅฐ็ป“**๏ผš็ฎ€่ฆๆ€ป็ป“ๆœฌๆฌก่ฟญไปฃๆถต็›–็š„ๅ†…ๅฎน
user_template: |
+ ## ็”จๆˆทๅๅฅฝ
+ {preference}
+
## ็”จๆˆท้—ฎ้ข˜
{question}
- ## ๅ‰ๅบๅ†…ๅฎน (ๅทฒๅฎŒๆˆ็š„ๆญฅ้ชค)
+ ## ๅ‰ๅบๅ†…ๅฎน๏ผˆๅทฒๅฎŒๆˆ็š„ๆญฅ้ชค๏ผ‰
{previous_context}
- ## ๅฝ“ๅ‰ๆญฅ้ชค (Step {step_id})
- **็›ฎๆ ‡**: {step_target}
+ ## ๆœฌๆฌก่ฟญไปฃๅฎŒๆˆ็š„ๅพ…ๅŠžไบ‹้กน๏ผˆ{completed_todos_count} ้กน๏ผ‰
+ {completed_todos}
## ๅฏ็”จ็ด ๆ
- ### 1. ็Ÿฅ่ฏ†ๅบ“ๅผ•็”จ
- {available_cite_details}
-
- ### 2. ๅทฅๅ…ทๆ‰ง่กŒ็ป“ๆžœ (ไปฃ็ /ๆœ็ดข)
+
+ ### 1. ๅทฅๅ…ท่ฐƒ็”จ็ป“ๆžœ๏ผˆๆœฌๆฌก่ฟญไปฃ๏ผ‰
{tool_materials}
- ### 3. ๅพ…ๆ’ๅ…ฅๅ›พ็‰‡๏ผˆ่ฏท้€ๆกๆ’ๅ…ฅไปฅไธ‹่ทฏๅพ„ๅนถ่งฃ้‡Š๏ผ‰
+ ### 2. ๅทฒๆœ‰็Ÿฅ่ฏ†๏ผˆๆฅ่‡ช่ฐƒ็ ”้˜ถๆฎต๏ผ‰
+ {knowledge_chain}
+
+ ### 3. ๅผ•็”จ่ฏฆๆƒ…
+ {citation_details}
+
+ ### 4. ๅพ…ๆ’ๅ…ฅๅ›พ็‰‡
{image_materials}
## ไปปๅŠก
- ๆ’ฐๅ†™่ฏฅๆญฅ้ชค็š„ๆญฃๅผๅ›ž็ญ”๏ผŒไฝœไธบๅ…จๆ–‡็š„็ฌฌ{step_id}ๆญฅ็š„ๆญฃๅผ่พ“ๅ‡บ๏ผš
+ ๆ’ฐๅ†™ไธ“ไธš็š„ๅ›ž็ญ”๏ผŒๆถต็›–ไธŠ่ฟฐๆ‰€ๆœ‰ๅทฒๅฎŒๆˆ็š„ๅพ…ๅŠžไบ‹้กนใ€‚
+ - ไฝฟ็”จๅทฅๅ…ท่ฐƒ็”จ็ป“ๆžœไฝœไธบ่ฏๆฎ
+ - ๅœจ้€‚ๅฝ“ไฝ็ฝฎๅŒ…ๅซๅผ•็”จ
+ - ๆ’ๅ…ฅๅนถ่งฃ้‡Šๆ‰€ๆœ‰็”Ÿๆˆ็š„ๅ›พ็‰‡
+ - ้ตๅพชๆ ผๅผ่ง„่Œƒ
diff --git a/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml
index eed5331bb..212a6ad8b 100644
--- a/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml
+++ b/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml
@@ -1,76 +1,56 @@
system: |
- # ่ง’่‰ฒๅฎšไฝ
- ไฝ ๆ˜ฏ Solve ้˜ถๆฎต็š„**ๅทฅๅ…ท็ญ–็•ฅๅฎถ (Tool Strategist)**ใ€‚
- ไฝ ็š„ไปปๅŠกๆ˜ฏ๏ผš**ๆ นๆฎๅฝ“ๅ‰ๆญฅ้ชค็›ฎๆ ‡๏ผŒๅ†ณๅฎšๆ˜ฏๅฆ้œ€่ฆ่ฐƒ็”จๅทฅๅ…ท๏ผŒไปฅๅŠ่ฐƒ็”จๅ“ชไธ€็งๅทฅๅ…ท**ใ€‚
- โš ๏ธ ไฝ ๅช่ดŸ่ดฃโ€œๅ†ณ็ญ–โ€๏ผŒไธ่ดŸ่ดฃโ€œๆ‰ง่กŒโ€ใ€‚
-
- # ๆ ธๅฟƒๅ†ณ็ญ–้€ป่พ‘
- ไฝ ้œ€่ฆๅˆคๆ–ญๅฝ“ๅ‰ๆญฅ้ชค็š„ๆ€ง่ดจ๏ผŒๅนถ้€‰ๆ‹ฉๆœ€ๅŒน้…็š„ๅทฅๅ…ท็ฑปๅž‹๏ผš
-
- 1. **ๆถ‰ๅŠ่ฎก็ฎ—ใ€ๆŽจๅฏผใ€็ป˜ๅ›พใ€ๆ•ฐๆฎๅค„็†**
- -> ้€‰ๆ‹ฉ `code_execution`
- - โš ๏ธใ€้‡่ฆใ€‘ไฝ  **็ปๅฏนไธ่ƒฝ** ็ผ–ๅ†™ๆˆ–่พ“ๅ‡บไปปไฝ•ๅฏๆ‰ง่กŒไปฃ็ 
- - ไฝ ๅช้œ€่ฆ็”จ**ไธ€ๅฅ็ฎ€็Ÿญ็š„่ฏ**ๆ่ฟฐโ€œ่ฆๅšไป€ไนˆ่ฎก็ฎ— / ๆŽจๅฏผ / ็ป˜ๅ›พโ€
- - ไพ‹ๅฆ‚๏ผš
- - โ€œไฝฟ็”จ็ฌฆๅท่ฎก็ฎ—ๆŽจๅฏผๅๅ‘ไผ ๆ’ญไธญ็š„ๆขฏๅบฆๅ…ฌๅผโ€
- - โ€œ่ฎก็ฎ—ๅ‡ฝๆ•ฐๅœจ็ป™ๅฎšๅŒบ้—ดๅ†…็š„ๆ•ฐๅ€ผๅนถ็ป˜ๅˆถๆ›ฒ็บฟโ€
-
- 2. **ๆถ‰ๅŠๅฎšไน‰ๆŸฅๆ‰พใ€ๅŽŸ็†็กฎ่ฎคใ€ๅ…ฌๅผๆฃ€็ดข**
- -> ้€‰ๆ‹ฉ `rag_naive` ๆˆ– `rag_hybrid`
- - ็ฒพ็กฎๅ…ฌๅผ / ๅฎšไน‰ โ†’ `rag_naive`
- - ๆœบๅˆถ็†่งฃ / ๅฏนๆฏ”ๅˆ†ๆž โ†’ `rag_hybrid`
-
- 3. **ๆถ‰ๅŠๆœ€ๆ–ฐไฟกๆฏๆˆ–ๅค–้ƒจ็Ÿฅ่ฏ†**
- -> ้€‰ๆ‹ฉ `web_search`
-
- 4. **็บฏ้€ป่พ‘ๆŽจ็†ใ€ๆ€ป็ป“๏ผŒๆˆ–ๅฝ“ๅ‰ไฟกๆฏๅทฒ็ป่ถณๅคŸ**
- -> ้€‰ๆ‹ฉ `none`
- - ๅœจ `query` ๅญ—ๆฎตไธญ็›ดๆŽฅ็ป™ๅ‡บ่ฏฅๆญฅ้ชค็š„ๆ–‡ๅญ—ๆ€ง็ป“่ฎบ
-
- # ๐Ÿšซ ไธฅๆ ผ็ฆๆญขไบ‹้กน๏ผˆ้žๅธธ้‡่ฆ๏ผ‰
- - โŒ ไธ่ฆ่พ“ๅ‡บ Python ไปฃ็ 
- - โŒ ไธ่ฆ่พ“ๅ‡บๅคš่กŒๆ–‡ๆœฌ
- - โŒ ไธ่ฆไฝฟ็”จ ``` ๆˆ–ไปปไฝ•ไปฃ็ ๅ—
- - โŒ ไธ่ฆๅœจ JSON ไธญๅŒ…ๅซๆข่กŒ็ฌฆ
- - โŒ ไธ่ฆๅฐ่ฏ•โ€œๆจกๆ‹Ÿๆ‰ง่กŒไปฃ็ โ€
-
- # ่ง’่‰ฒ่พน็•Œ๏ผˆๅฟ…้กป้ตๅฎˆ๏ผ‰
- - ไฝ ๅชๅšโ€œๅทฅๅ…ท้€‰ๆ‹ฉไธŽๆ„ๅ›พๆ่ฟฐโ€๏ผŒไธๅšๅทฅๅ…ทๆ‰ง่กŒ
- - ไธ้‡ๅคๅทฒๆœ‰่ฝจ่ฟนไธญ็š„ๅทฅๅ…ท่ฐƒ็”จ
- - ไธ€ๆ—ฆไฟกๆฏ่ถณๅคŸ๏ผŒ็ซ‹ๅˆปไฝฟ็”จ `none` ็ป“ๆŸ่ฏฅๆญฅ้ชค
-
- # ่พ“ๅ‡บๆ ผๅผ๏ผˆๅฟ…้กปไธฅๆ ผ็ฌฆๅˆ๏ผ‰
- ไฝ ๅฟ…้กป **ๅช่พ“ๅ‡บไธ€ไธชๅˆๆณ• JSON ๅฏน่ฑก**๏ผŒๆ ผๅผๅฆ‚ไธ‹๏ผš
-
+ # ่ง’่‰ฒๅฎšไน‰
+ ไฝ ๆ˜ฏ **Solve Agent๏ผˆ่งฃ้ข˜ไปฃ็†๏ผ‰**๏ผŒ่ดŸ่ดฃไธบๅฝ“ๅ‰ๅพ…ๅŠžไบ‹้กนๆ”ถ้›†ๆ‰€้œ€ไฟกๆฏใ€‚
+
+ ## ไฝ ็š„ไปปๅŠก
+ ๆฏๆฌก่ฐƒ็”จๆ—ถ๏ผŒๅ†ณๅฎšไธ‹ไธ€ๆญฅไฝฟ็”จไป€ไนˆๅทฅๅ…ทๆฅๆ”ถ้›†ไฟกๆฏใ€‚
+ ไฝ ไผšๅœจไธ€ไธช่ฟญไปฃๅพช็Žฏไธญ่ขซๅคšๆฌก่ฐƒ็”จใ€‚
+ ๆฏๆฌกๅ“ๅบ”ๅช่พ“ๅ‡บไธ€ไธชๅทฅๅ…ท่ฐƒ็”จๅ†ณ็ญ–ใ€‚
+
+ ## ่พ“ๅ‡บๆ ผๅผ๏ผˆไธฅๆ ผ JSON๏ผ‰
+ ```json
{
- "thoughts": "็ฎ€่ฆ่ฏดๆ˜Žไฝ ็š„ๅ†ณ็ญ–็†็”ฑ๏ผˆไธ€ๅฅ่ฏๅณๅฏ๏ผ‰",
- "tool_calls": [
- {
- "type": "code_execution | rag_naive | rag_hybrid | web_search | none",
- "intent": "ไธ€ๅฅ่ฏๆ่ฟฐไฝ ๅธŒๆœ›ๅทฅๅ…ทๅฎŒๆˆ็š„ไบ‹ๆƒ…"
- }
- ]
+ "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}
-
- ## ๅฝ“ๅ‰ๆญฅ้ชค (Step {current_step_id})
- **็›ฎๆ ‡**: {step_target}
-
- ## ๅฏ็”จ่ƒŒๆ™ฏไฟกๆฏ
- {available_cite_text}
-
- ## ๅทฒๆœ‰่ฝจ่ฟน
- {current_tool_history}
-
+
+ ## ๅฝ“ๅ‰ๅพ…ๅŠžไบ‹้กน
+ {current_todo}
+
+ ## ๅทฒๆœ‰็Ÿฅ่ฏ†๏ผˆๆฅ่‡ช่ฐƒ็ ”้˜ถๆฎต๏ผ‰
+ {knowledge_chain}
+
+ ## ๆœฌๆฌก่ฟญไปฃ็š„ๅทฅๅ…ท่ฐƒ็”จ ({iteration_count}/{max_iterations})
+ {iteration_history}
+
## ไปปๅŠก
- ่ฏท่ง„ๅˆ’ไธ‹ไธ€ๆญฅ็š„ๅทฅๅ…ท่ฐƒ็”จใ€‚
-
- ่ฆๆฑ‚๏ผš
- 1. ไธฅๆ ผๆŒ‰็…งๅฝ“ๅ‰ๆญฅ้ชค็›ฎๆ ‡ `{step_target}` ่กŒไบ‹
- 2. ้ฟๅ…้‡ๅคๅทฒๆœ‰่ฝจ่ฟนไธญ็š„ๅทฅๅ…ท่ฐƒ็”จ
- 3. ๅฆ‚ๆžœ้œ€่ฆ่ฎก็ฎ—ๆˆ–ๆŽจๅฏผ๏ผŒๅชๆ่ฟฐโ€œๅšไป€ไนˆโ€๏ผŒไธ่ฆๅ†™ไปฃ็ 
- 4. ๅฆ‚ๆžœไฟกๆฏๅทฒ็ป่ถณๅคŸ๏ผŒ้€‰ๆ‹ฉ `none` ๅนถ็›ดๆŽฅ็ป™ๅ‡บ็ป“่ฎบ
- 5. ๅช่พ“ๅ‡บ JSON๏ผŒไธ่ฆ่พ“ๅ‡บไปปไฝ•่งฃ้‡Šๆ€งๆ–‡ๅญ—
+ ๅŸบไบŽๅฝ“ๅ‰ๅพ…ๅŠžไบ‹้กนๅ’Œๅฏ็”จไฟกๆฏ๏ผš
+ 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.yaml
new file mode 100644
index 000000000..6a88c2a31
--- /dev/null
+++ b/src/agents/solve/prompts/zh/solve_loop/solve_note_agent.yaml
@@ -0,0 +1,76 @@
+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/session_manager.py b/src/agents/solve/session_manager.py
index e739a88de..bede0605e 100644
--- a/src/agents/solve/session_manager.py
+++ b/src/agents/solve/session_manager.py
@@ -8,195 +8,127 @@ This module handles:
- Retrieving session history
- Listing recent sessions
- Deleting sessions
+
+Now inherits from BaseSessionManager for consistent behavior across all modules.
"""
-import json
-from pathlib import Path
-import time
from typing import Any
-import uuid
+
+from src.services.session import BaseSessionManager
-class SolverSessionManager:
+class SolverSessionManager(BaseSessionManager):
"""
Manages persistent storage of solver sessions.
- Sessions are stored in a JSON file at data/user/solver_sessions.json.
+ Sessions are stored in a JSON file at data/user/agent/solve/sessions.json.
Each session contains:
- session_id: Unique identifier
- title: Session title (usually first user question)
- - messages: List of messages with role, content, outputDir, timestamp
+ - messages: List of messages with role, content, output_dir, timestamp
- kb_name: Knowledge base used
- token_stats: Cost and token usage statistics
- created_at: Creation timestamp
- updated_at: Last update timestamp
"""
- def __init__(self, base_dir: str | None = None):
- """
- Initialize SolverSessionManager.
+ DEFAULT_TOKEN_STATS = {
+ "model": "Unknown",
+ "calls": 0,
+ "tokens": 0,
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "cost": 0.0,
+ }
- Args:
- base_dir: Base directory for session storage.
- Defaults to project_root/data/user
- """
- if base_dir is None:
- # Current file: src/agents/solve/session_manager.py
- # Project root: 4 levels up
- project_root = Path(__file__).resolve().parents[3]
- base_dir_path = project_root / "data" / "user"
- else:
- base_dir_path = Path(base_dir)
-
- self.base_dir = base_dir_path
- self.base_dir.mkdir(parents=True, exist_ok=True)
-
- self.sessions_file = self.base_dir / "solver_sessions.json"
- self._ensure_file()
-
- def _ensure_file(self):
- """Ensure the sessions file exists with correct format."""
- if not self.sessions_file.exists():
- initial_data = {
- "version": "1.0",
- "sessions": [],
- }
- self._save_data(initial_data)
-
- def _load_data(self) -> dict[str, Any]:
- """Load sessions data from file."""
- try:
- with open(self.sessions_file, encoding="utf-8") as f:
- return json.load(f)
- except (json.JSONDecodeError, FileNotFoundError):
- return {"version": "1.0", "sessions": []}
-
- def _save_data(self, data: dict[str, Any]):
- """Save sessions data to file."""
- with open(self.sessions_file, "w", encoding="utf-8") as f:
- json.dump(data, f, indent=2, ensure_ascii=False)
-
- def _get_sessions(self) -> list[dict[str, Any]]:
- """Get list of all sessions."""
- data = self._load_data()
- return data.get("sessions", [])
-
- def _save_sessions(self, sessions: list[dict[str, Any]]):
- """Save sessions list."""
- data = self._load_data()
- data["sessions"] = sessions
- self._save_data(data)
+ def __init__(self):
+ """Initialize SolverSessionManager."""
+ super().__init__("solve")
- def create_session(
+ # =========================================================================
+ # BaseSessionManager Abstract Method Implementations
+ # =========================================================================
+
+ def _get_session_id_prefix(self) -> str:
+ """Return the prefix for session IDs."""
+ return "solve_"
+
+ def _get_default_title(self) -> str:
+ """Return the default title for new sessions."""
+ return "New Solver Session"
+
+ def _create_session_data(
self,
- title: str = "New Solver Session",
kb_name: str = "",
token_stats: dict[str, Any] | None = None,
+ **kwargs,
) -> dict[str, Any]:
"""
- Create a new solver session.
+ Create solver-specific session data.
Args:
- title: Session title
kb_name: Knowledge base name
- token_stats: Optional token usage statistics
+ token_stats: Token usage statistics
Returns:
- New session dict with session_id
+ Dict with kb_name and token_stats
"""
- session_id = f"solver_{int(time.time() * 1000)}_{uuid.uuid4().hex[:8]}"
- now = time.time()
-
- session = {
- "session_id": session_id,
- "title": title[:100], # Limit title length
- "messages": [],
+ return {
"kb_name": kb_name,
- "token_stats": token_stats
- or {
- "model": "Unknown",
- "calls": 0,
- "tokens": 0,
- "input_tokens": 0,
- "output_tokens": 0,
- "cost": 0.0,
- },
- "created_at": now,
- "updated_at": now,
+ "token_stats": token_stats or self.DEFAULT_TOKEN_STATS.copy(),
}
- sessions = self._get_sessions()
- sessions.insert(0, session) # Add to front (newest first)
-
- # Limit total sessions to prevent file bloat
- max_sessions = 100
- if len(sessions) > max_sessions:
- sessions = sessions[:max_sessions]
-
- self._save_sessions(sessions)
-
- return session
-
- def get_session(self, session_id: str) -> dict[str, Any] | None:
+ def _get_session_summary(self, session: dict[str, Any]) -> dict[str, Any]:
"""
- Get a session by ID.
+ Create a summary of a solver session for listing.
Args:
- session_id: Session identifier
+ session: The full session data
Returns:
- Session dict or None if not found
+ Dict containing summary fields
"""
- sessions = self._get_sessions()
- for session in sessions:
- if session.get("session_id") == session_id:
- return session
- return None
+ messages = session.get("messages", [])
+ return {
+ "session_id": session.get("session_id"),
+ "title": session.get("title"),
+ "message_count": len(messages),
+ "kb_name": session.get("kb_name"),
+ "token_stats": session.get("token_stats"),
+ "created_at": session.get("created_at"),
+ "updated_at": session.get("updated_at"),
+ # Include preview of last message
+ "last_message": (
+ messages[-1].get("content", "")[:100] if messages else ""
+ ),
+ }
- def update_session(
+ # =========================================================================
+ # Solver-Specific Methods
+ # =========================================================================
+
+ def create_session(
self,
- session_id: str,
- messages: list[dict[str, Any]] | None = None,
title: str | None = None,
- kb_name: str | None = None,
+ kb_name: str = "",
token_stats: dict[str, Any] | None = None,
- ) -> dict[str, Any] | None:
+ ) -> dict[str, Any]:
"""
- Update a session with new data.
+ Create a new solver session.
Args:
- session_id: Session identifier
- messages: New messages list (replaces existing)
- title: New title (optional)
- kb_name: New knowledge base name (optional)
- token_stats: New token stats (optional)
+ title: Session title (uses default if None)
+ kb_name: Knowledge base name
+ token_stats: Optional token usage statistics
Returns:
- Updated session or None if not found
+ New session dict with session_id
"""
- sessions = self._get_sessions()
-
- for i, session in enumerate(sessions):
- if session.get("session_id") == session_id:
- if messages is not None:
- session["messages"] = messages
- if title is not None:
- session["title"] = title[:100]
- if kb_name is not None:
- session["kb_name"] = kb_name
- if token_stats is not None:
- session["token_stats"] = token_stats
-
- session["updated_at"] = time.time()
-
- # Move to front (most recently updated)
- sessions.pop(i)
- sessions.insert(0, session)
-
- self._save_sessions(sessions)
- return session
-
- return None
+ return super().create_session(
+ title=title,
+ kb_name=kb_name,
+ token_stats=token_stats,
+ )
def add_message(
self,
@@ -217,117 +149,58 @@ class SolverSessionManager:
Returns:
Updated session or None if not found
"""
- session = self.get_session(session_id)
- if not session:
- return None
-
- message = {
- "role": role,
- "content": content,
- "timestamp": time.time(),
- }
- if output_dir:
- message["output_dir"] = output_dir
-
- messages = session.get("messages", [])
- messages.append(message)
-
- # Update title from first user message if still default
- if session.get("title") == "New Solver Session" and role == "user":
- new_title = content[:50] + ("..." if len(content) > 50 else "")
- return self.update_session(session_id, messages=messages, title=new_title)
+ return super().add_message(
+ session_id=session_id,
+ role=role,
+ content=content,
+ output_dir=output_dir,
+ )
- return self.update_session(session_id, messages=messages)
-
- def update_token_stats(
+ def update_session(
self,
session_id: str,
- token_stats: dict[str, Any],
+ messages: list[dict[str, Any]] | None = None,
+ title: str | None = None,
+ kb_name: str | None = None,
+ token_stats: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
"""
- Update token stats for a session.
+ Update a session with new data.
Args:
session_id: Session identifier
- token_stats: Token usage statistics
+ messages: New messages list (replaces existing)
+ title: New title (optional)
+ kb_name: New knowledge base name (optional)
+ token_stats: New token stats (optional)
Returns:
Updated session or None if not found
"""
- return self.update_session(session_id, token_stats=token_stats)
+ return super().update_session(
+ session_id=session_id,
+ messages=messages,
+ title=title,
+ kb_name=kb_name,
+ token_stats=token_stats,
+ )
- def list_sessions(
+ def update_token_stats(
self,
- limit: int = 20,
- include_messages: bool = False,
- ) -> list[dict[str, Any]]:
- """
- List recent sessions.
-
- Args:
- limit: Maximum number of sessions to return
- include_messages: Whether to include full message history
-
- Returns:
- List of session dicts (newest first)
- """
- sessions = self._get_sessions()[:limit]
-
- if not include_messages:
- # Return summary only (without full messages)
- return [
- {
- "session_id": s.get("session_id"),
- "title": s.get("title"),
- "message_count": len(s.get("messages", [])),
- "kb_name": s.get("kb_name"),
- "token_stats": s.get("token_stats"),
- "created_at": s.get("created_at"),
- "updated_at": s.get("updated_at"),
- # Include preview of last message
- "last_message": (
- s.get("messages", [])[-1].get("content", "")[:100]
- if s.get("messages")
- else ""
- ),
- }
- for s in sessions
- ]
-
- return sessions
-
- def delete_session(self, session_id: str) -> bool:
+ session_id: str,
+ token_stats: dict[str, Any],
+ ) -> dict[str, Any] | None:
"""
- Delete a session.
+ Update token stats for a session.
Args:
session_id: Session identifier
+ token_stats: Token usage statistics
Returns:
- True if deleted, False if not found
- """
- sessions = self._get_sessions()
- original_count = len(sessions)
-
- sessions = [s for s in sessions if s.get("session_id") != session_id]
-
- if len(sessions) < original_count:
- self._save_sessions(sessions)
- return True
-
- return False
-
- def clear_all_sessions(self) -> int:
- """
- Delete all sessions.
-
- Returns:
- Number of sessions deleted
+ Updated session or None if not found
"""
- sessions = self._get_sessions()
- count = len(sessions)
- self._save_sessions([])
- return count
+ return self.update_session(session_id, token_stats=token_stats)
# Singleton instance for convenience
diff --git a/src/agents/solve/solve_loop/__init__.py b/src/agents/solve/solve_loop/__init__.py
index 65380aef9..a424f23a9 100644
--- a/src/agents/solve/solve_loop/__init__.py
+++ b/src/agents/solve/solve_loop/__init__.py
@@ -1,8 +1,11 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-Solve Loop - Solve loop (Manager โ†’ Solve โ†’ Check โ†’ Format)
-Based on Analysis output, plan and execute problem-solving process, generate high-quality answers
+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
@@ -10,13 +13,17 @@ 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",
- "ToolAgent",
+ # Utils
"CitationManager",
]
diff --git a/src/agents/solve/solve_loop/manager_agent.py b/src/agents/solve/solve_loop/manager_agent.py
index 8f2b67363..b45a7dbed 100644
--- a/src/agents/solve/solve_loop/manager_agent.py
+++ b/src/agents/solve/solve_loop/manager_agent.py
@@ -1,8 +1,10 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-ManagerAgent - Manager (Refactored: directly plans step-level solution steps)
-Based on user question and knowledge chain, plans solution steps
+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
@@ -15,12 +17,12 @@ sys.path.insert(0, str(project_root))
from src.agents.base_agent import BaseAgent
-from ..memory import InvestigateMemory, SolveChainStep, SolveMemory
+from ..memory import InvestigateMemory, SolveMemory, TodoItem
from ..utils.json_utils import extract_json_from_text
class ManagerAgent(BaseAgent):
- """Manager Agent - Plans solution steps"""
+ """Manager Agent - Generates todo-list milestones for solving"""
def __init__(
self,
@@ -50,7 +52,7 @@ class ManagerAgent(BaseAgent):
verbose: bool = True,
) -> dict[str, Any]:
"""
- Process management workflow - plan solution steps
+ Process management workflow - generate todo-list milestones
Args:
question: User question
@@ -59,22 +61,22 @@ class ManagerAgent(BaseAgent):
verbose: Whether to print detailed information
Returns:
- dict: Management result
+ 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 steps already exist
- if solve_memory.solve_chains:
- steps_count = len(solve_memory.solve_chains)
- self.logger.log_stage_progress(stage_label, "skip", f"Already has {steps_count} steps")
+ # 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_steps": True,
- "steps_count": steps_count,
- "num_steps": steps_count, # Maintain compatibility
- "message": "Steps already exist, skipping planning",
+ "has_todos": True,
+ "todos_count": todos_count,
+ "num_todos": todos_count,
+ "message": "Todo-list already exists, skipping planning",
}
# 2. Build context
@@ -93,26 +95,31 @@ class ManagerAgent(BaseAgent):
response_format={"type": "json_object"}, # Force JSON
)
- # 5. Parse output and create StepItem
- steps = self._parse_response(response, investigate_memory)
+ # 5. Parse output and create TodoItems
+ todos = self._parse_todo_response(response)
- # 6. Add steps to solve_memory
- solve_memory.create_chains(steps)
+ # 6. Add todos to solve_memory
+ solve_memory.create_todo_list(todos)
solve_memory.save()
- steps_count = len(steps)
- self.logger.log_stage_progress(stage_label, "complete", f"Generated {steps_count} steps")
+ # 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_steps": True,
- "steps_count": steps_count,
- "num_steps": steps_count, # Maintain compatibility
- "message": f"Generated {steps_count} steps",
+ "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"""
+ """Build context for LLM call"""
# Get knowledge chain information (cite_id + summary)
knowledge_info = []
for knowledge in investigate_memory.knowledge_chain:
@@ -170,12 +177,9 @@ class ManagerAgent(BaseAgent):
)
return template.format(**context)
- def _parse_response(
- self, response: str, investigate_memory: InvestigateMemory
- ) -> list[SolveChainStep]:
- """Parse LLM output (JSON format), create solve-chain steps"""
- steps: list[SolveChainStep] = []
- knowledge_ids = {k.cite_id for k in investigate_memory.knowledge_chain}
+ 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)
@@ -185,90 +189,50 @@ class ManagerAgent(BaseAgent):
f"Failed to parse valid JSON object from LLM output. Original output: {response[:200]}..."
)
- steps_data = parsed_data.get("steps", [])
- if not isinstance(steps_data, list):
- raise ValueError(f"'steps' field in JSON is not an array. Parsed result: {parsed_data}")
+ 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 steps_data:
- raise ValueError("'steps' array in JSON is empty, please check LLM output")
+ if not todos_data:
+ raise ValueError("'todos' array in JSON is empty, please check LLM output")
- # Parse each step
- for idx, step_data in enumerate(steps_data, 1):
- if not isinstance(step_data, dict):
+ # 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 step data (index {idx}): {step_data}"
+ f"[ManagerAgent] Skipping invalid todo data (index {idx}): {todo_data}"
)
continue
- # Get step_id
- step_id = step_data.get("step_id", "").strip()
- if not step_id:
- step_id = f"S{idx}"
- elif not step_id.upper().startswith("S"):
- step_id = f"S{step_id}"
-
- # Get role and target
- role = step_data.get("role", "").strip()
- target = step_data.get("target", "").strip()
-
- # If target already contains role, use directly; otherwise combine
- if target:
- if "๏ผš" in target or ":" in target:
- step_target = target
- elif role:
- step_target = f"{role}๏ผš{target}"
- else:
- step_target = target
- else:
- raise ValueError(f"Step {step_id} missing 'target' field")
-
- # Get cite_ids
- cite_ids_raw = step_data.get("cite_ids", [])
- if not isinstance(cite_ids_raw, list):
- # Compatible with string format
- if isinstance(cite_ids_raw, str):
- cite_ids_raw = [cite_ids_raw] if cite_ids_raw and cite_ids_raw != "none" else []
- else:
- cite_ids_raw = []
-
- # Clean and normalize cite_ids
- filtered_cites = []
- for cite in cite_ids_raw:
- if not cite or cite == "none":
- continue
- # Ensure format is [xxx]
- cleaned = str(cite).strip()
- if not cleaned.startswith("["):
- cleaned = f"[{cleaned.strip('[] ')}]"
-
- # Filter invalid cite
- if cleaned in knowledge_ids:
- filtered_cites.append(cleaned)
- else:
- self.logger.warning(
- f"[ManagerAgent] Skipping unknown cite_id {cleaned} (not in knowledge chain)"
- )
-
- # Create step
- steps.append(
- SolveChainStep(
- step_id=step_id,
- step_target=step_target,
- available_cite=list(dict.fromkeys(filtered_cites)), # Remove duplicates
- status="undone",
+ # 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 steps:
- raise ValueError("Failed to parse any valid steps, please check LLM output format")
+ 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_response] Parsed {len(steps)} solve-chain steps")
- for step in steps:
- logger.info(f" - {step.step_id}: {step.step_target}")
- logger.info(
- f" Available citations: {', '.join(step.available_cite) or '(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 steps
+ return todos
diff --git a/src/agents/solve/solve_loop/response_agent.py b/src/agents/solve/solve_loop/response_agent.py
index 18ef57707..b455e4321 100644
--- a/src/agents/solve/solve_loop/response_agent.py
+++ b/src/agents/solve/solve_loop/response_agent.py
@@ -2,13 +2,15 @@
# -*- coding: utf-8 -*-
"""
ResponseAgent - Step response generator
-Based on materials in solve-chain, generates formal response for current step
+
+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
+from typing import Any, List, Optional
project_root = Path(__file__).parent.parent.parent.parent
if str(project_root) not in sys.path:
@@ -16,11 +18,26 @@ if str(project_root) not in sys.path:
from src.agents.base_agent import BaseAgent
-from ..memory import CitationMemory, InvestigateMemory, SolveChainStep, SolveMemory
+from ..memory import (
+ CitationMemory,
+ InvestigateMemory,
+ IterationRecord,
+ SolveChainStep,
+ SolveMemory,
+ TodoItem,
+ ToolCallRecord,
+)
class ResponseAgent(BaseAgent):
- """Response generator Agent"""
+ """
+ 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,
@@ -47,23 +64,50 @@ class ResponseAgent(BaseAgent):
async def process(
self,
question: str,
- step: SolveChainStep,
- solve_memory: SolveMemory,
- investigate_memory: InvestigateMemory,
+ iteration_record: IterationRecord,
+ completed_todos: List[TodoItem],
citation_memory: CitationMemory,
+ knowledge_chain: List[Any],
output_dir: str | None = None,
- verbose: bool = True,
accumulated_response: str = "",
+ verbose: bool = True,
) -> dict[str, Any]:
- if not step:
- return {"step_response": "(No pending step)"}
-
+ """
+ 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,
- step=step,
- solve_memory=solve_memory,
- investigate_memory=investigate_memory,
+ iteration_record=iteration_record,
+ completed_todos=completed_todos,
citation_memory=citation_memory,
+ knowledge_chain=knowledge_chain,
output_dir=output_dir,
accumulated_response=accumulated_response,
)
@@ -72,129 +116,107 @@ class ResponseAgent(BaseAgent):
user_prompt = self._build_user_prompt(context)
response = await self.call_llm(
- user_prompt=user_prompt, system_prompt=system_prompt, verbose=verbose
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ verbose=verbose,
)
- # Directly use LLM's raw output as step_response, no parsing
+ # Process response
step_response = response.strip() if response else ""
- used_citations = self._extract_used_citations(step_response, step)
- solve_memory.submit_step_response(
- step_id=step.step_id, response=step_response, used_citations=used_citations
+ used_citations = self._extract_used_citations(
+ content=step_response,
+ tool_calls=iteration_record.tool_calls,
+ knowledge_chain=knowledge_chain,
)
- solve_memory.save()
+
+ # Update iteration record
+ iteration_record.set_step_response(step_response, used_citations)
return {
- "step_id": step.step_id,
"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,
}
# ------------------------------------------------------------------ #
- # Prompt Building
+ # Context Building
# ------------------------------------------------------------------ #
def _build_context(
self,
question: str,
- step: SolveChainStep,
- solve_memory: SolveMemory,
- investigate_memory: InvestigateMemory,
+ iteration_record: IterationRecord,
+ completed_todos: List[TodoItem],
citation_memory: CitationMemory,
+ knowledge_chain: List[Any],
output_dir: str | None,
accumulated_response: str = "",
) -> dict[str, Any]:
- available_cite_details = self._format_available_cite(step, investigate_memory)
- tool_materials, image_materials = self._format_tool_materials(step, output_dir)
- citation_details = self._format_citation_details(step, citation_memory)
+ """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,
- "step_id": step.step_id,
- "step_target": step.step_target,
- "available_cite_details": available_cite_details,
+ "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 _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:
- raise ValueError(
- "ResponseAgent missing system prompt, please configure in prompts/zh/solve_loop/response_agent.yaml."
- )
-
- # Add citation disable instruction if citations are disabled
- 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"
-
- 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:
- raise ValueError(
- "ResponseAgent missing user_template, please configure user_template in prompts/{lang}/solve_loop/response_agent.yaml"
- )
-
- # Format image_materials as clear text list
- image_materials = context.get("image_materials", [])
- if image_materials:
- image_text = "\n".join([f"- {img}" for img in image_materials])
- else:
- image_text = "(No image files)"
-
- # Create new context, format image_materials as text
- formatted_context = context.copy()
- formatted_context["image_materials"] = image_text
-
- return template.format(**formatted_context)
-
- # ------------------------------------------------------------------ #
- # Material Organization
- # ------------------------------------------------------------------ #
- def _format_available_cite(
- self, step: SolveChainStep, investigate_memory: InvestigateMemory
- ) -> str:
- if not step.available_cite:
- return "(No available knowledge chain)"
- lines: list[str] = []
- for cite in step.available_cite:
- knowledge = next(
- (k for k in investigate_memory.knowledge_chain if k.cite_id == cite), None
- )
- if not knowledge:
- continue
- summary = knowledge.summary or knowledge.raw_result[:300]
- lines.append(
- f"{cite} [{knowledge.tool_type}]\n"
- f" Query: {knowledge.query}\n"
- f" Summary: {summary}\n"
- f" Raw: {knowledge.raw_result[:300]}..."
- )
- return "\n".join(lines) if lines else "(No matching knowledge)"
-
- def _format_tool_materials(
- self, step: SolveChainStep, output_dir: str | None
+ 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]]:
- if not step.tool_calls:
- return "(No tool calls yet)", []
+ """Format tool call chain and extract images"""
+ if not tool_calls:
+ return "(No tool calls in this iteration)", []
lines: list[str] = []
images: list[str] = []
@@ -206,63 +228,79 @@ class ResponseAgent(BaseAgent):
images.append(normalized)
seen_images.add(normalized)
- for call in step.tool_calls:
+ for idx, call in enumerate(tool_calls, 1):
summary = call.summary or "(Summary pending)"
raw_preview = (call.raw_answer or "")[:500]
lines.append(
- f"{call.tool_type} | cite_id={call.cite_id} | Status={call.status}\n"
+ 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}"
)
- # Priority: use recorded relative paths, then absolute paths, finally fall back to original artifacts list
- artifact_rel_paths = call.metadata.get("artifact_rel_paths") if call.metadata else None
- artifact_paths = call.metadata.get("artifact_paths") if call.metadata else None
- artifacts = call.metadata.get("artifacts") if call.metadata else None
-
- if artifact_rel_paths:
- for rel_path in artifact_rel_paths:
- _append_image(rel_path)
-
- if artifact_paths:
- # Use absolute paths, but convert to relative paths relative to output_dir for display
- for abs_path in artifact_paths:
- path = Path(abs_path)
- if path.suffix.lower() in {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}:
- # If output_dir exists, calculate relative path; otherwise use absolute path
- if output_dir:
- try:
- rel_path = path.relative_to(Path(output_dir))
- _append_image(str(rel_path))
- except ValueError:
- # If cannot calculate relative path, use filename
+
+ # 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)
- else:
- _append_image(path.name)
- elif artifacts:
- # Fall back to using artifacts list
- for artifact in artifacts:
- path = Path(artifact)
- if path.suffix.lower() in {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}:
- # Build relative path to artifacts directory
- rel_path = Path("artifacts") / path.name
- _append_image(str(rel_path))
+ 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, step: SolveChainStep, citation_memory: CitationMemory
+ self,
+ tool_calls: List[ToolCallRecord],
+ citation_memory: CitationMemory,
) -> str:
- # If citations are disabled, return empty string
+ """Format citation details from tool calls"""
if not self.enable_citations:
return "(Citations disabled)"
- cite_ids = list(
- dict.fromkeys(
- step.available_cite + [tc.cite_id for tc in step.tool_calls if tc.cite_id]
- )
- )
+ 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)
@@ -274,28 +312,215 @@ class ResponseAgent(BaseAgent):
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, step: SolveChainStep) -> list[str]:
- # If citations are disabled, return empty list
+ 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 []
- # Allow standard English brackets [cite], also tolerate some error formats (like Chinese full-width bracketsใ€citeใ€‘), uniformly normalize to [cite]
+
+ # 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()}]")
- allowed = set(step.available_cite + [tc.cite_id for tc in step.tool_calls if tc.cite_id])
+
+ # 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.py
index a11d1306f..df9714777 100644
--- a/src/agents/solve/solve_loop/solve_agent.py
+++ b/src/agents/solve/solve_loop/solve_agent.py
@@ -1,13 +1,14 @@
#!/usr/bin/env python
"""
-SolveAgent - Tool planner
-Responsible for evaluating existing materials based on step_target and generating tool call trajectories to execute
+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 re
import sys
-from typing import Any
+from typing import Any, List, Optional
# Add project root to path
project_root = Path(__file__).parent.parent.parent.parent
@@ -16,20 +17,31 @@ if str(project_root) not in sys.path:
from src.agents.base_agent import BaseAgent
-from ..memory import CitationMemory, InvestigateMemory, SolveChainStep, SolveMemory
+from ..memory import (
+ InvestigateMemory,
+ IterationRecord,
+ SolveMemory,
+ TodoItem,
+ ToolCallRecord,
+)
from ..utils.json_utils import extract_json_from_text
class SolveAgent(BaseAgent):
- """Solver Agent - Plans and records tool calls"""
+ """
+ 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",
- "rag_naive",
- "rag_hybrid",
- "web_search",
- "code_execution",
- "finish",
+ "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__(
@@ -51,26 +63,54 @@ class SolveAgent(BaseAgent):
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,
- current_step: SolveChainStep,
- solve_memory: SolveMemory,
- investigate_memory: InvestigateMemory,
- citation_memory: CitationMemory,
- kb_name: str = "ai_textbook",
- output_dir: str | None = None,
verbose: bool = True,
) -> dict[str, Any]:
- if not current_step:
- raise ValueError("No pending solve-chain step to execute")
+ """
+ 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,
- current_step=current_step,
- solve_memory=solve_memory,
- investigate_memory=investigate_memory,
)
system_prompt = self._build_system_prompt()
@@ -80,246 +120,225 @@ class SolveAgent(BaseAgent):
user_prompt=user_prompt,
system_prompt=system_prompt,
verbose=verbose,
- response_format={"type": "json_object"}, # Force JSON
+ response_format={"type": "json_object"},
)
- tool_plan = self._parse_tool_plan(response)
- if not tool_plan:
- # Try to be compatible with old logic, or raise error
- # For robustness, if JSON parsing fails, raise more specific error
+ # Parse the decision
+ decision = self._parse_decision(response)
+ if not decision:
self.logger.warning(
- f"SolveAgent JSON parsing failed or empty, Raw: {response[:200]}..."
- )
- # If empty list, also treat as exception, because SolveAgent should output at least none or finish
- raise ValueError(
- "SolveAgent did not parse any valid tool_calls structure from LLM output"
- )
-
- finish_requested = any(item["type"] == "finish" for item in tool_plan)
- newly_created: list[dict[str, Any]] = []
- existing_calls = len(current_step.tool_calls)
-
- for order, item in enumerate(tool_plan, start=1):
- tool_type = item["type"]
- query = item["query"]
-
- if tool_type == "finish":
- continue
-
- normalized_query = self._prepare_query(tool_type, query, current_step)
-
- cite_id = None
- if tool_type != "none":
- cite_id = citation_memory.add_citation(
- tool_type=tool_type,
- query=normalized_query,
- raw_result="",
- content="",
- stage="solve",
- step_id=current_step.step_id,
- )
-
- record = solve_memory.append_tool_call(
- step_id=current_step.step_id,
- tool_type=tool_type,
- query=normalized_query,
- cite_id=cite_id,
- metadata={
- "plan_order": existing_calls + order,
- "kb_name": kb_name,
- },
+ f"SolveAgent JSON parsing failed, defaulting to none. Raw: {response[:200]}..."
)
-
- request_info = {
- "call_id": record.call_id,
- "tool_type": tool_type,
- "query": normalized_query,
- "cite_id": cite_id,
- "status": record.status,
+ return {
+ "tool_type": "none",
+ "query": "",
+ "should_stop": True,
+ "reason": "parse_error",
}
- if tool_type == "none":
- summary = self._summarize_none_answer(normalized_query)
- solve_memory.update_tool_call_result(
- step_id=current_step.step_id,
- call_id=record.call_id,
- raw_answer=normalized_query,
- summary=summary,
- status="none",
- )
- # none calls are not counted in citation system
- request_info["status"] = "none"
- request_info["summary"] = summary
- # none type indicates tool call phase is finished, but step_response must be generated by ResponseAgent
- finish_requested = True
- newly_created.append(request_info)
- # none type indicates no need to append additional tools, but won't directly write to step_response
- break
-
- newly_created.append(request_info)
-
- solve_memory.save()
- citation_memory.save()
+ tool_type = decision["tool_type"]
+ query = decision["query"]
+ should_stop = tool_type == "none"
return {
- "step_id": current_step.step_id,
- "requested_calls": newly_created,
- "finish_requested": finish_requested,
- "raw_llm_response": response,
- "status": (
- "waiting_tools"
- if newly_created
- else ("ready_for_response" if finish_requested else "idle")
- ),
+ "tool_type": tool_type,
+ "query": query,
+ "should_stop": should_stop,
+ "raw_response": response,
}
# ------------------------------------------------------------------ #
- # Prompt Building
+ # Context Building
# ------------------------------------------------------------------ #
def _build_context(
self,
+ current_todo: TodoItem,
+ iteration_history: List[ToolCallRecord],
+ knowledge_chain: List[Any],
question: str,
- current_step: SolveChainStep,
- solve_memory: SolveMemory,
- investigate_memory: InvestigateMemory,
) -> 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_step_id": current_step.step_id,
- "step_target": current_step.step_target,
- "available_cite_text": self._format_available_cite(current_step, investigate_memory),
- "previous_steps": self._format_previous_steps(current_step, solve_memory),
- "current_tool_history": self._format_tool_history(current_step),
+ "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:
- raise ValueError(
- "SolveAgent missing system prompt, please configure system in prompts/zh/solve_loop/solve_agent.yaml."
- )
+ # 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:
- raise ValueError(
- "SolveAgent missing user_template prompt, please configure user_template in prompts/zh/solve_loop/solve_agent.yaml."
- )
+ # 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)
# ------------------------------------------------------------------ #
- # Parsing and Formatting
+ # Response Parsing
# ------------------------------------------------------------------ #
- def _format_available_cite(
- self, current_step: SolveChainStep, investigate_memory: InvestigateMemory
- ) -> str:
- if not current_step.available_cite:
- return "(No available knowledge chain)"
-
- lines: list[str] = []
- for cite_id in current_step.available_cite:
- knowledge = next(
- (k for k in investigate_memory.knowledge_chain if k.cite_id == cite_id), None
- )
- if not knowledge:
- continue
- summary = knowledge.summary or knowledge.raw_result[:300]
- raw_preview = (
- knowledge.raw_result[:300].replace("\n", " ") if knowledge.raw_result else ""
- )
- lines.append(
- f"{cite_id} | {knowledge.tool_type}\n"
- f" Query: {knowledge.query}\n"
- f" Summary: {summary}\n"
- f" Raw: {raw_preview}"
- )
- return "\n".join(lines) if lines else "(No matching knowledge)"
-
- def _format_previous_steps(
- self, current_step: SolveChainStep, solve_memory: SolveMemory
- ) -> str:
- snippets: list[str] = []
- for step in solve_memory.solve_chains:
- if step.step_id == current_step.step_id:
- break
- if step.step_response:
- snippets.append(
- f"[{step.step_id}] {step.step_target}\n{step.step_response[:300]}..."
- )
- return "\n\n".join(snippets[-3:]) if snippets else "(No completed steps yet)"
-
- def _format_tool_history(self, current_step: SolveChainStep) -> str:
- if not current_step.tool_calls:
- return "(No tool calls have been made yet)"
- lines: list[str] = []
- for call in current_step.tool_calls:
- summary = call.summary or "(Pending)"
- lines.append(
- f"{call.tool_type} | cite_id={call.cite_id or 'N/A'} | Status={call.status}\n"
- f"Query: {call.query}\n"
- f"Summary: {summary[:200]}"
- )
- return "\n\n".join(lines)
-
- def _parse_tool_plan(self, response: str) -> list[dict[str, str]]:
- """
- Parse JSON plan returned by LLM
- """
+ 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 []
-
- tool_calls = parsed_data.get("tool_calls", [])
- if not isinstance(tool_calls, list):
- return []
+ 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"
- actions: list[dict[str, str]] = []
- for item in tool_calls:
- if not isinstance(item, dict):
- continue
-
- tool_type = str(item.get("type", "")).strip().lower()
- # query = str(item.get("query", "")).strip()
- query = str(item.get("intent", "")).strip()
+ return {
+ "tool_type": tool_type,
+ "query": query,
+ }
- if not tool_type:
- continue
- if tool_type not in self.SUPPORTED_TOOL_TYPES:
- self.logger.warning(f"[SolveAgent] Ignoring unknown tool type: {tool_type}")
- continue
+# Legacy compatibility - keep old process signature as alternative
+class SolveAgentLegacy(SolveAgent):
+ """Legacy wrapper for backward compatibility with old API"""
- actions.append({"type": tool_type, "query": query})
+ 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",
+ }
- return actions
+ # Get current iteration or empty history
+ current_iter = solve_memory.get_current_iteration()
+ iteration_history = current_iter.tool_calls if current_iter else []
- # ------------------------------------------------------------------ #
- # Query preprocessing & helper
- # ------------------------------------------------------------------ #
- def _prepare_query(self, tool_type: str, query: str, current_step: SolveChainStep) -> str:
- return query.strip()
-
- def _summarize_none_answer(self, text: str) -> str:
- return text.strip()
-
- def _normalize_latex_sequences(self, text: str) -> str:
- if not text or not text.strip():
- return ""
- cleaned = text.strip()
- cleaned = cleaned.replace("\\{", "{").replace("\\}", "}").replace("$", "")
- pattern = re.compile(r"(?P<var>[A-Za-z_][A-Za-z0-9_\[\]]*)\s*=\s*\{(?P<values>[^\}]+)\}")
-
- def replacer(match: re.Match) -> str:
- var = match.group("var")
- values = match.group("values")
- base_var = re.sub(r"\[.*?\]", "", var).strip()
- values = values.replace(";", ",")
- items = [v.strip() for v in values.split(",") if v.strip()]
- formatted_values = ", ".join(items)
- return f"{base_var} = [{formatted_values}]"
-
- normalized = re.sub(pattern, replacer, cleaned)
- normalized = re.sub(r"\s+", " ", normalized).strip()
- return normalized
+ 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.py
new file mode 100644
index 000000000..28407fb33
--- /dev/null
+++ b/src/agents/solve/solve_loop/solve_note_agent.py
@@ -0,0 +1,389 @@
+#!/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.py
index aa77ece8d..a21d84a7b 100644
--- a/src/agents/solve/solve_loop/tool_agent.py
+++ b/src/agents/solve/solve_loop/tool_agent.py
@@ -2,13 +2,13 @@
# -*- coding: utf-8 -*-
"""
ToolAgent - Tool executor
-Responsible for reading tool calls in solve-chain, actually executing tools and producing summary
+
+Responsible for executing tool calls and producing summaries.
"""
from pathlib import Path
import re
import sys
-import time
from typing import Any
project_root = Path(__file__).parent.parent.parent.parent
@@ -20,7 +20,6 @@ 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 import CitationMemory, SolveChainStep, SolveMemory
from ..memory.solve_memory import ToolCallRecord
@@ -47,7 +46,51 @@ class ToolAgent(BaseAgent):
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.
@@ -77,153 +120,6 @@ Rules:
return code.strip()
- async def process(
- self,
- step: SolveChainStep,
- solve_memory: SolveMemory,
- citation_memory: CitationMemory,
- kb_name: str,
- output_dir: str | None = None,
- verbose: bool = True,
- ) -> dict[str, Any]:
- pending = [
- call
- for call in step.tool_calls
- if call.tool_type not in {"none", "finish"} and call.status in {"pending", "running"}
- ]
-
- if not pending:
- return {"step_id": step.step_id, "executed": [], "status": "idle"}
-
- logs: list[dict[str, Any]] = []
- 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)
-
- self.logger.log_stage_progress(
- "Tool", "start", f"step={step.step_id}, pending_calls={len(pending)}"
- )
-
- for record in pending:
- call_label = f"{record.tool_type} | cite={record.cite_id or '-'}"
- self.logger.log_stage_progress(
- "Tool", "running", f"step={step.step_id}, call={call_label}"
- )
- start_ts = time.time()
- try:
- 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,
- )
-
- # Check if code execution failed
- is_failed = False
- if record.tool_type == "code_execution":
- is_failed = metadata.get("execution_failed", False)
- exit_code = metadata.get("exit_code", 0)
- if exit_code != 0:
- is_failed = True
-
- summary = await self._summarize_tool_result(
- tool_type=record.tool_type, query=record.query, raw_answer=raw_answer
- )
-
- # Set correct status based on execution result
- status = "failed" if is_failed else "success"
- solve_memory.update_tool_call_result(
- step_id=step.step_id,
- call_id=record.call_id,
- raw_answer=raw_answer,
- summary=summary,
- status=status,
- metadata=metadata, # Pass metadata to ensure artifacts are saved
- )
- citation_memory.update_citation(
- cite_id=record.cite_id,
- raw_result=raw_answer,
- content=summary,
- metadata=metadata,
- step_id=step.step_id,
- )
- elapsed_ms = (time.time() - start_ts) * 1000
- self.logger.log_tool_call(
- tool_name=record.tool_type,
- tool_input={
- "step_id": step.step_id,
- "call_id": record.call_id,
- "query": record.query,
- },
- tool_output=raw_answer,
- status="success",
- elapsed_ms=elapsed_ms,
- step_id=step.step_id,
- cite_id=record.cite_id,
- )
- logs.append(
- {
- "call_id": record.call_id,
- "tool_type": record.tool_type,
- "cite_id": record.cite_id,
- "status": "success",
- "summary": summary,
- }
- )
- except Exception as e:
- error_msg = str(e)
- elapsed_ms = (time.time() - start_ts) * 1000
- solve_memory.update_tool_call_result(
- step_id=step.step_id,
- call_id=record.call_id,
- raw_answer=error_msg,
- summary=error_msg[:200],
- status="failed",
- metadata={"error": True},
- )
- citation_memory.update_citation(
- cite_id=record.cite_id,
- raw_result=error_msg,
- content=error_msg[:200],
- metadata={"error": True},
- step_id=step.step_id,
- )
- self.logger.log_tool_call(
- tool_name=record.tool_type,
- tool_input={
- "step_id": step.step_id,
- "call_id": record.call_id,
- "query": record.query,
- },
- tool_output=error_msg,
- status="failed",
- elapsed_ms=elapsed_ms,
- step_id=step.step_id,
- cite_id=record.cite_id,
- )
- self.logger.log_stage_progress(
- "Tool", "warning", f"step={step.step_id}, call={call_label}, error={error_msg}"
- )
- logs.append(
- {
- "call_id": record.call_id,
- "tool_type": record.tool_type,
- "cite_id": record.cite_id,
- "status": "failed",
- "error": error_msg,
- }
- )
-
- solve_memory.save()
- citation_memory.save()
-
- self.logger.log_stage_progress(
- "Tool", "complete", f"step={step.step_id}, executed={len(logs)}"
- )
-
- return {"step_id": step.step_id, "executed": logs, "status": "completed"}
-
async def _execute_single_call(
self,
record: ToolCallRecord,
@@ -232,6 +128,19 @@ Rules:
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
@@ -315,6 +224,7 @@ Rules:
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", [])
@@ -347,6 +257,7 @@ Rules:
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(
@@ -368,7 +279,11 @@ Rules:
)
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)
@@ -380,6 +295,7 @@ Rules:
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+)\]")
@@ -393,6 +309,7 @@ Rules:
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 []
@@ -434,6 +351,7 @@ Rules:
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()
@@ -445,6 +363,7 @@ Rules:
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:
diff --git a/src/agents/solve/utils/performance_monitor.py b/src/agents/solve/utils/performance_monitor.py
index 40740ec0b..aee5125dd 100644
--- a/src/agents/solve/utils/performance_monitor.py
+++ b/src/agents/solve/utils/performance_monitor.py
@@ -14,6 +14,8 @@ from pathlib import Path
import time
from typing import Any
+from src.services.path_service import get_path_service
+
@dataclass
class PerformanceMetrics:
@@ -99,9 +101,9 @@ class PerformanceMonitor:
self.enabled = enabled
if save_dir is None:
- # Default to data/user/performance (relative to project root)
- project_root = Path(__file__).parent.parent.parent.parent.parent
- self.save_dir = project_root / "data" / "user" / "performance"
+ # 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)
diff --git a/src/api/main.py b/src/api/main.py
index 66ee5072e..b22c8ba3e 100644
--- a/src/api/main.py
+++ b/src/api/main.py
@@ -22,6 +22,7 @@ from src.api.routers import (
system,
)
from src.logging import get_logger
+from src.services.path_service import get_path_service
# Note: Don't set service_prefix here - start_web.py already adds [Backend] prefix
logger = get_logger("API")
@@ -142,10 +143,51 @@ async def lifespan(app: FastAPI):
except Exception as e:
logger.warning(f"Failed to initialize LLM client at startup: {e}")
+ # Start EventBus for personalization
+ try:
+ from src.core.event_bus import get_event_bus
+
+ event_bus = get_event_bus()
+ await event_bus.start()
+ logger.info("EventBus started")
+ except Exception as e:
+ logger.warning(f"Failed to start EventBus: {e}")
+
+ # Start PersonalizationService for memory management
+ try:
+ from src.personalization.service import get_personalization_service
+
+ personalization_service = get_personalization_service()
+ await personalization_service.start()
+ logger.info("PersonalizationService started")
+ except Exception as e:
+ logger.warning(f"Failed to start PersonalizationService: {e}")
+
yield
+
# Execute on shutdown
logger.info("Application shutdown")
+ # Stop PersonalizationService
+ try:
+ from src.personalization.service import get_personalization_service
+
+ personalization_service = get_personalization_service()
+ await personalization_service.stop()
+ logger.info("PersonalizationService stopped")
+ except Exception as e:
+ logger.warning(f"Failed to stop PersonalizationService: {e}")
+
+ # Stop EventBus
+ try:
+ from src.core.event_bus import get_event_bus
+
+ event_bus = get_event_bus()
+ await event_bus.stop()
+ logger.info("EventBus stopped")
+ except Exception as e:
+ logger.warning(f"Failed to stop EventBus: {e}")
+
app = FastAPI(
title="DeepTutor API",
@@ -169,16 +211,16 @@ app.add_middleware(
# Mount user directory as static root for generated artifacts
# This allows frontend to access generated artifacts (images, PDFs, etc.)
-# URL: /api/outputs/solve/solve_xxx/artifacts/image.png
-# Physical Path: DeepTutor/data/user/solve/solve_xxx/artifacts/image.png
-project_root = Path(__file__).parent.parent.parent
-user_dir = project_root / "data" / "user"
+# URL: /api/outputs/agent/solve/solve_xxx/artifacts/image.png
+# Physical Path: DeepTutor/data/user/agent/solve/solve_xxx/artifacts/image.png
+path_service = get_path_service()
+user_dir = path_service.user_data_dir
# Initialize user directories on startup
try:
from src.services.setup import init_user_directories
- init_user_directories(project_root)
+ init_user_directories()
except Exception:
# Fallback: just create the main directory if it doesn't exist
if not user_dir.exists():
diff --git a/src/api/routers/dashboard.py b/src/api/routers/dashboard.py
index 57c077f5d..5663de887 100644
--- a/src/api/routers/dashboard.py
+++ b/src/api/routers/dashboard.py
@@ -1,18 +1,292 @@
+"""
+Dashboard API Router
+====================
+
+Provides endpoints for retrieving recent activities aggregated from various
+agent modules (solve, chat, question, research).
+
+Activities are aggregated from:
+- Solve sessions (data/user/agent/solve/sessions.json)
+- Chat sessions (data/user/agent/chat/sessions.json)
+- Question batches (data/user/agent/question/*/summary.json)
+- Research reports (data/user/agent/research/reports/*_metadata.json)
+"""
+
+import json
+from pathlib import Path
+from typing import Any
+
from fastapi import APIRouter, HTTPException
-from src.api.utils.history import history_manager
+from src.agents.chat import SessionManager
+from src.agents.solve import SolverSessionManager
+from src.services.path_service import get_path_service
router = APIRouter()
+# Initialize session managers
+_solve_session_manager: SolverSessionManager | None = None
+_chat_session_manager: SessionManager | None = None
+
+
+def _get_solve_session_manager() -> SolverSessionManager:
+ """Lazy initialization of solve session manager."""
+ global _solve_session_manager
+ if _solve_session_manager is None:
+ _solve_session_manager = SolverSessionManager()
+ return _solve_session_manager
+
+
+def _get_chat_session_manager() -> SessionManager:
+ """Lazy initialization of chat session manager."""
+ global _chat_session_manager
+ if _chat_session_manager is None:
+ _chat_session_manager = SessionManager()
+ return _chat_session_manager
+
+
+def _get_question_activities(limit: int = 50) -> list[dict[str, Any]]:
+ """
+ Get recent question generation activities from batch directories.
+
+ Reads summary.json from each batch directory to extract activity info.
+ """
+ activities = []
+ path_service = get_path_service()
+ question_dir = path_service.get_question_dir()
+
+ if not question_dir.exists():
+ return activities
+
+ # Find all batch directories
+ batch_dirs = sorted(
+ [d for d in question_dir.iterdir() if d.is_dir() and d.name.startswith("batch_")],
+ key=lambda x: x.stat().st_mtime,
+ reverse=True,
+ )[:limit]
+
+ for batch_dir in batch_dirs:
+ summary_file = batch_dir / "summary.json"
+ if summary_file.exists():
+ try:
+ with open(summary_file, encoding="utf-8") as f:
+ summary = json.load(f)
+
+ activities.append({
+ "id": batch_dir.name,
+ "type": "question",
+ "title": summary.get("knowledge_point", batch_dir.name),
+ "timestamp": batch_dir.stat().st_mtime,
+ "summary": f"Generated {summary.get('generated', 0)} question(s)",
+ "session_ref": f"question/{batch_dir.name}",
+ })
+ except (json.JSONDecodeError, OSError):
+ # Skip invalid files
+ pass
+
+ return activities
+
+
+def _get_research_activities(limit: int = 50) -> list[dict[str, Any]]:
+ """
+ Get recent research activities from reports directory.
+
+ Reads metadata files from the reports directory.
+ """
+ activities = []
+ path_service = get_path_service()
+ reports_dir = path_service.get_research_reports_dir()
+
+ if not reports_dir.exists():
+ return activities
+
+ # Find all metadata files
+ metadata_files = sorted(
+ [f for f in reports_dir.iterdir() if f.name.endswith("_metadata.json")],
+ key=lambda x: x.stat().st_mtime,
+ reverse=True,
+ )[:limit]
+
+ for meta_file in metadata_files:
+ try:
+ with open(meta_file, encoding="utf-8") as f:
+ metadata = json.load(f)
+
+ # Extract research_id from filename (research_YYYYMMDD_HHMMSS_id_metadata.json)
+ research_id = meta_file.stem.replace("_metadata", "")
+
+ activities.append({
+ "id": research_id,
+ "type": "research",
+ "title": metadata.get("topic", research_id),
+ "timestamp": meta_file.stat().st_mtime,
+ "summary": f"Word count: {metadata.get('report_word_count', 0)}",
+ "session_ref": f"research/{research_id}",
+ })
+ except (json.JSONDecodeError, OSError):
+ # Skip invalid files
+ pass
+
+ return activities
+
@router.get("/recent")
-async def get_recent_history(limit: int = 10, type: str | None = None):
- return history_manager.get_recent(limit, type)
+async def get_recent_activities(limit: int = 50, type: str | None = None):
+ """
+ Get recent activities aggregated from all agent modules.
+
+ Args:
+ limit: Maximum number of activities to return
+ type: Optional filter by activity type (solve, chat, question, research)
+
+ Returns:
+ List of activity entries sorted by timestamp (newest first)
+ """
+ activities: list[dict[str, Any]] = []
+
+ # Aggregate from solve sessions
+ if type is None or type == "solve":
+ solve_manager = _get_solve_session_manager()
+ solve_sessions = solve_manager.list_sessions(limit=limit, include_messages=False)
+ for s in solve_sessions:
+ activities.append({
+ "id": s.get("session_id"),
+ "type": "solve",
+ "title": s.get("title", "Untitled"),
+ "timestamp": s.get("updated_at", s.get("created_at", 0)),
+ "summary": s.get("last_message", "")[:100] if s.get("last_message") else "",
+ "session_ref": f"solve/{s.get('session_id')}",
+ "message_count": s.get("message_count", 0),
+ "kb_name": s.get("kb_name"),
+ "token_stats": s.get("token_stats"),
+ })
+
+ # Aggregate from chat sessions
+ if type is None or type == "chat":
+ chat_manager = _get_chat_session_manager()
+ chat_sessions = chat_manager.list_sessions(limit=limit, include_messages=False)
+ for s in chat_sessions:
+ activities.append({
+ "id": s.get("session_id"),
+ "type": "chat",
+ "title": s.get("title", "Untitled"),
+ "timestamp": s.get("updated_at", s.get("created_at", 0)),
+ "summary": s.get("last_message", "")[:100] if s.get("last_message") else "",
+ "session_ref": f"chat/{s.get('session_id')}",
+ "message_count": s.get("message_count", 0),
+ "settings": s.get("settings"),
+ })
+
+ # Aggregate from question batches
+ if type is None or type == "question":
+ question_activities = _get_question_activities(limit)
+ activities.extend(question_activities)
+
+ # Aggregate from research reports
+ if type is None or type == "research":
+ research_activities = _get_research_activities(limit)
+ activities.extend(research_activities)
+
+ # Sort by timestamp (newest first)
+ activities.sort(key=lambda x: x.get("timestamp", 0), reverse=True)
+
+ return activities[:limit]
@router.get("/{entry_id}")
-async def get_history_entry(entry_id: str):
- entry = history_manager.get_entry(entry_id)
- if not entry:
- raise HTTPException(status_code=404, detail="Entry not found")
- return entry
+async def get_activity_entry(entry_id: str):
+ """
+ Get a specific activity entry by ID.
+
+ Args:
+ entry_id: The activity/session ID
+
+ Returns:
+ The full activity entry
+
+ Raises:
+ HTTPException: If entry not found
+ """
+ # Try to find in solve sessions
+ if entry_id.startswith("solve_"):
+ solve_manager = _get_solve_session_manager()
+ session = solve_manager.get_session(entry_id)
+ if session:
+ return {
+ "id": session.get("session_id"),
+ "type": "solve",
+ "title": session.get("title"),
+ "timestamp": session.get("updated_at", session.get("created_at")),
+ "content": {
+ "messages": session.get("messages", []),
+ "kb_name": session.get("kb_name"),
+ "token_stats": session.get("token_stats"),
+ },
+ }
+
+ # Try to find in chat sessions
+ if entry_id.startswith("chat_"):
+ chat_manager = _get_chat_session_manager()
+ session = chat_manager.get_session(entry_id)
+ if session:
+ return {
+ "id": session.get("session_id"),
+ "type": "chat",
+ "title": session.get("title"),
+ "timestamp": session.get("updated_at", session.get("created_at")),
+ "content": {
+ "messages": session.get("messages", []),
+ "settings": session.get("settings"),
+ },
+ }
+
+ # Try to find in question batches
+ if entry_id.startswith("batch_"):
+ path_service = get_path_service()
+ batch_dir = path_service.get_question_dir() / entry_id
+ summary_file = batch_dir / "summary.json"
+ if summary_file.exists():
+ try:
+ with open(summary_file, encoding="utf-8") as f:
+ summary = json.load(f)
+ return {
+ "id": entry_id,
+ "type": "question",
+ "title": summary.get("knowledge_point", entry_id),
+ "timestamp": batch_dir.stat().st_mtime,
+ "content": summary,
+ }
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ # Try to find in research reports
+ if entry_id.startswith("research_"):
+ path_service = get_path_service()
+ reports_dir = path_service.get_research_reports_dir()
+ meta_file = reports_dir / f"{entry_id}_metadata.json"
+ report_file = reports_dir / f"{entry_id}.md"
+
+ if meta_file.exists():
+ try:
+ with open(meta_file, encoding="utf-8") as f:
+ metadata = json.load(f)
+
+ report_content = ""
+ if report_file.exists():
+ with open(report_file, encoding="utf-8") as f:
+ report_content = f.read()
+
+ return {
+ "id": entry_id,
+ "type": "research",
+ "title": metadata.get("topic", entry_id),
+ "timestamp": meta_file.stat().st_mtime,
+ "content": {
+ "metadata": metadata,
+ "report": report_content,
+ },
+ }
+ except (json.JSONDecodeError, OSError):
+ pass
+
+ raise HTTPException(status_code=404, detail="Entry not found")
diff --git a/src/api/routers/question.py b/src/api/routers/question.py
index 7b0803f08..098527b04 100644
--- a/src/api/routers/question.py
+++ b/src/api/routers/question.py
@@ -9,9 +9,9 @@ import traceback
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from src.agents.question import AgentCoordinator
-from src.api.utils.history import ActivityType, history_manager
from src.api.utils.log_interceptor import LogInterceptor
from src.api.utils.task_id_manager import TaskIDManager
+from src.services.path_service import get_path_service
from src.tools.question import mimic_exam_questions
from src.utils.document_validator import DocumentValidator
from src.utils.error_utils import format_exception_message
@@ -33,9 +33,9 @@ logger = get_logger("QuestionAPI", log_dir=log_dir)
router = APIRouter()
-# Output directory for mimic mode - use data/user/question
-PROJECT_ROOT = Path(__file__).parent.parent.parent.parent
-MIMIC_OUTPUT_DIR = PROJECT_ROOT / "data" / "user" / "question" / "mimic_papers"
+# Output directory for mimic mode - use agent/question/mimic_papers
+_path_service = get_path_service()
+MIMIC_OUTPUT_DIR = _path_service.get_question_dir() / "mimic_papers"
@router.websocket("/mimic")
@@ -364,9 +364,8 @@ async def websocket_question_generate(websocket: WebSocket):
)
# 2. Initialize Coordinator
- # Define unified output directory (DeepTutor/data/user/question)
- root_dir = Path(__file__).parent.parent.parent.parent
- output_base = root_dir / "data" / "user" / "question"
+ path_service = get_path_service()
+ output_base = path_service.get_question_dir()
try:
llm_config = get_llm_config()
@@ -436,20 +435,6 @@ async def websocket_question_generate(websocket: WebSocket):
)
# Results are already sent via WebSocket callbacks in the coordinator
- # Just need to save to history for successful results
- for result in batch_result.get("results", []):
- # Save to history
- history_manager.add_entry(
- activity_type=ActivityType.QUESTION,
- title=f"{requirement.get('knowledge_point', 'Question')} ({requirement.get('question_type')})",
- content={
- "requirement": requirement,
- "question": result.get("question", {}),
- "validation": result.get("validation", {}),
- "kb_name": kb_name,
- },
- summary=result.get("question", {}).get("question", "")[:100],
- )
# Send final token stats
try:
diff --git a/src/api/routers/research.py b/src/api/routers/research.py
index 98dd6dd40..38deee8a1 100644
--- a/src/api/routers/research.py
+++ b/src/api/routers/research.py
@@ -10,8 +10,8 @@ from pydantic import BaseModel
from src.agents.research.agents import RephraseAgent
from src.agents.research.research_pipeline import ResearchPipeline
-from src.api.utils.history import ActivityType, history_manager
from src.api.utils.task_id_manager import TaskIDManager
+from src.services.path_service import get_path_service
from src.logging import get_logger
from src.services.config import load_config_with_main
from src.services.llm import get_llm_config
@@ -242,17 +242,16 @@ async def websocket_research_run(websocket: WebSocket):
if skip_rephrase:
config["planning"]["rephrase"]["enabled"] = False
- # Define unified output directory
- # Use project root directory user/research as unified output directory
- root_dir = Path(__file__).parent.parent.parent.parent
- output_base = root_dir / "data" / "user" / "research"
+ # Define unified output directory using PathService
+ path_service = get_path_service()
+ output_base = path_service.get_research_dir()
# Update config with unified output paths
if "system" not in config:
config["system"] = {}
config["system"]["output_base_dir"] = str(output_base / "cache")
- config["system"]["reports_dir"] = str(output_base / "reports")
+ config["system"]["reports_dir"] = str(path_service.get_research_reports_dir())
# Inject API keys from env if not in config
try:
@@ -351,14 +350,6 @@ async def websocket_research_run(websocket: WebSocket):
with open(result["final_report_path"], encoding="utf-8") as f:
report_content = f.read()
- # Save to history
- history_manager.add_entry(
- activity_type=ActivityType.RESEARCH,
- title=topic,
- content={"topic": topic, "report": report_content, "kb_name": kb_name},
- summary=f"Research ID: {result['research_id']}",
- )
-
await websocket.send_json(
{
"type": "result",
diff --git a/src/api/routers/settings.py b/src/api/routers/settings.py
index 92f283594..3643e95ae 100644
--- a/src/api/routers/settings.py
+++ b/src/api/routers/settings.py
@@ -13,12 +13,13 @@ from typing import List, Literal, Optional
from fastapi import APIRouter
from pydantic import BaseModel
+from src.services.path_service import get_path_service
+
router = APIRouter()
# Settings file path for UI preferences (stored in settings folder with other configs)
-SETTINGS_FILE = (
- Path(__file__).parent.parent.parent.parent / "data" / "user" / "settings" / "interface.json"
-)
+_path_service = get_path_service()
+SETTINGS_FILE = _path_service.get_settings_file("interface")
# Default sidebar navigation order
DEFAULT_SIDEBAR_NAV_ORDER = {
diff --git a/src/api/routers/solve.py b/src/api/routers/solve.py
index 480eb1890..2692d8751 100644
--- a/src/api/routers/solve.py
+++ b/src/api/routers/solve.py
@@ -14,9 +14,9 @@ from typing import Any
from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
from src.agents.solve import MainSolver, SolverSessionManager
-from src.api.utils.history import ActivityType, history_manager
from src.api.utils.log_interceptor import LogInterceptor
from src.api.utils.task_id_manager import TaskIDManager
+from src.services.path_service import get_path_service
_project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(_project_root))
@@ -189,8 +189,8 @@ async def websocket_solve(websocket: WebSocket):
await websocket.send_json({"type": "task_id", "task_id": task_id})
# 2. Initialize Solver
- root_dir = Path(__file__).parent.parent.parent.parent
- output_base = root_dir / "data" / "user" / "solve"
+ path_service = get_path_service()
+ output_base = path_service.get_solve_dir()
try:
llm_config = get_llm_config()
@@ -372,21 +372,6 @@ async def websocket_solve(websocket: WebSocket):
token_stats=display_manager.stats.copy(),
)
- # Save to history
- history_manager.add_entry(
- activity_type=ActivityType.SOLVE,
- title=question[:50] + "..." if len(question) > 50 else question,
- content={
- "question": question,
- "answer": result.get("final_answer"),
- "kb_name": kb_name,
- "session_id": session_id,
- },
- summary=(
- result.get("final_answer")[:100] + "..." if result.get("final_answer") else ""
- ),
- )
-
except Exception as e:
# Mark connection as closed before sending error (to prevent log_pusher from interfering)
connection_closed.set()
diff --git a/src/api/utils/history.py b/src/api/utils/history.py
deleted file mode 100644
index f011e897e..000000000
--- a/src/api/utils/history.py
+++ /dev/null
@@ -1,172 +0,0 @@
-from enum import Enum
-import json
-from pathlib import Path
-import time
-
-
-class ActivityType(str, Enum):
- SOLVE = "solve"
- QUESTION = "question"
- RESEARCH = "research"
- CHAT = "chat"
-
-
-class HistoryManager:
- def __init__(self, base_dir: str | None = None):
- """
- History record manager
-
- Args:
- base_dir: History record directory. Default fixed to "project root/user",
- at the same level as user/question, user/solve, user/research,
- does not depend on current working directory, avoids path misalignment
- when uvicorn / IDE start differently.
- """
- if base_dir is None:
- # Current file: DeepTutor/src/api/utils/history.py
- # Project root should be three levels up: DeepTutor/
- project_root = Path(__file__).resolve().parents[3]
- base_dir_path = project_root / "data" / "user"
- else:
- base_dir_path = Path(base_dir)
-
- self.base_dir = base_dir_path
- self.base_dir.mkdir(parents=True, exist_ok=True)
-
- self.history_file = self.base_dir / "user_history.json"
- self._ensure_file()
-
- def _ensure_file(self):
- """
- Ensure history file exists with correct format.
- If file exists but has wrong format, it will be fixed on next save.
- """
- if not self.history_file.exists():
- # Create file with correct dict format (matching user_dir_init.py)
- initial_history = {"version": "1.0", "created_at": None, "sessions": []}
- try:
- with open(self.history_file, "w", encoding="utf-8") as f:
- json.dump(initial_history, f, indent=2, ensure_ascii=False)
- except Exception:
- # If we can't create the file, that's okay - it will be handled in _load_history
- pass
- else:
- # File exists, verify it's in correct format
- # If not, it will be fixed on next save operation
- try:
- with open(self.history_file, encoding="utf-8") as f:
- data = json.load(f)
- # If file is in old list format, we'll convert it on next save
- if isinstance(data, list):
- # File is in old format, but that's okay - _load_history handles it
- pass
- except Exception:
- # File exists but is corrupted, will be recreated on next save
- pass
-
- def _load_history(self) -> list[dict]:
- """
- Load history from file. Handles multiple formats for backward compatibility.
- Returns a list of history entries.
- """
- try:
- if not self.history_file.exists():
- return []
-
- with open(self.history_file, encoding="utf-8") as f:
- data = json.load(f)
-
- # Handle both list format and dict format (with 'sessions' key)
- if isinstance(data, dict):
- # If it's a dict, try to get 'sessions' field
- sessions = data.get("sessions", [])
- # Ensure sessions is a list
- if isinstance(sessions, list):
- return sessions
- # If sessions is not a list, return empty list and log warning
- return []
- if isinstance(data, list):
- # Legacy format: direct list
- return data
- # Unknown format, return empty list
- return []
- except json.JSONDecodeError:
- # File exists but is corrupted, return empty list
- # Could log this error in production
- return []
- except Exception:
- # Any other error, return empty list
- return []
-
- def _save_history(self, history: list[dict]):
- # Load existing file to preserve metadata if it's in dict format
- try:
- with open(self.history_file, encoding="utf-8") as f:
- existing_data = json.load(f)
- if isinstance(existing_data, dict):
- # Preserve dict structure, update sessions
- existing_data["sessions"] = history
- data_to_save = existing_data
- else:
- # If it was a list, convert to dict format
- data_to_save = {
- "version": "1.0",
- "created_at": existing_data[0].get("timestamp") if existing_data else None,
- "sessions": history,
- }
- except Exception:
- # If file doesn't exist or can't be read, create new dict format
- data_to_save = {
- "version": "1.0",
- "created_at": history[0].get("timestamp") if history else None,
- "sessions": history,
- }
-
- with open(self.history_file, "w", encoding="utf-8") as f:
- json.dump(data_to_save, f, indent=2, ensure_ascii=False)
-
- def add_entry(self, activity_type: ActivityType, title: str, content: dict, summary: str = ""):
- """
- Add a new history entry.
-
- Args:
- activity_type: The type of activity (solve, question, research)
- title: A short title (e.g. the question asked, or topic)
- content: The full result/payload
- summary: A short summary if applicable
- """
- entry = {
- "id": str(int(time.time() * 1000)),
- "timestamp": time.time(),
- "type": activity_type,
- "title": title,
- "summary": summary,
- "content": content,
- }
-
- history = self._load_history()
- history.insert(0, entry) # Prepend to show latest first
-
- # Optional: Limit history size
- if len(history) > 100:
- history = history[:100]
-
- self._save_history(history)
- return entry
-
- def get_recent(self, limit: int = 10, type_filter: str | None = None) -> list[dict]:
- history = self._load_history()
- if type_filter:
- history = [h for h in history if h["type"] == type_filter]
- return history[:limit]
-
- def get_entry(self, entry_id: str) -> dict | None:
- history = self._load_history()
- for entry in history:
- if entry["id"] == entry_id:
- return entry
- return None
-
-
-# Global instance
-history_manager = HistoryManager()
diff --git a/src/api/utils/notebook_manager.py b/src/api/utils/notebook_manager.py
index 3c2f3d85c..aaf8e4611 100644
--- a/src/api/utils/notebook_manager.py
+++ b/src/api/utils/notebook_manager.py
@@ -1,6 +1,6 @@
"""
Notebook Manager - Manages user notebooks and records
-All notebook data is stored in user/notebook/ directory
+All notebook data is stored in workspace/notebook/ directory
"""
from enum import Enum
@@ -11,6 +11,8 @@ import uuid
from pydantic import BaseModel
+from src.services.path_service import get_path_service
+
class RecordType(str, Enum):
"""Record type"""
@@ -55,13 +57,12 @@ class NotebookManager:
Initialize notebook manager
Args:
- base_dir: Notebook storage directory, defaults to project root/user/notebook
+ base_dir: Notebook storage directory, defaults to workspace/notebook
"""
if base_dir is None:
- # Current file: DeepTutor/src/api/utils/notebook_manager.py
- # Project root should be three levels up: DeepTutor/
- project_root = Path(__file__).resolve().parents[3]
- base_dir_path = project_root / "data" / "user" / "notebook"
+ # Use PathService for workspace/notebook path
+ path_service = get_path_service()
+ base_dir_path = path_service.get_notebook_dir()
else:
base_dir_path = Path(base_dir)
diff --git a/src/core/__init__.py b/src/core/__init__.py
new file mode 100644
index 000000000..eba77f5a1
--- /dev/null
+++ b/src/core/__init__.py
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+"""
+Core Module
+===========
+
+Core infrastructure components for DeepTutor.
+"""
+
+from .event_bus import Event, EventType, EventBus, get_event_bus
+
+__all__ = [
+ "Event",
+ "EventType",
+ "EventBus",
+ "get_event_bus",
+]
diff --git a/src/core/event_bus.py b/src/core/event_bus.py
new file mode 100644
index 000000000..7fdfade98
--- /dev/null
+++ b/src/core/event_bus.py
@@ -0,0 +1,263 @@
+# -*- coding: utf-8 -*-
+"""
+Event Bus
+=========
+
+Asynchronous event bus for inter-module communication.
+Supports publish/subscribe pattern with non-blocking event delivery.
+"""
+
+import asyncio
+import logging
+from dataclasses import dataclass, field
+from datetime import datetime
+from enum import Enum
+from typing import Any, Callable, Coroutine, Dict, List, Optional
+from uuid import uuid4
+
+logger = logging.getLogger(__name__)
+
+
+class EventType(str, Enum):
+ """Supported event types."""
+
+ SOLVE_COMPLETE = "SOLVE_COMPLETE"
+ QUESTION_COMPLETE = "QUESTION_COMPLETE"
+
+
+@dataclass
+class Event:
+ """
+ Event data structure for the event bus.
+
+ Attributes:
+ type: Event type identifier
+ task_id: Unique task identifier
+ user_input: Original user input/question
+ agent_output: Agent's response/output
+ tools_used: List of tools used during the task
+ success: Whether the task completed successfully
+ metadata: Additional event-specific data
+ event_id: Unique event identifier (auto-generated)
+ timestamp: Event creation timestamp (auto-generated)
+ """
+
+ type: EventType
+ task_id: str
+ user_input: str
+ agent_output: str
+ tools_used: List[str] = field(default_factory=list)
+ success: bool = True
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ event_id: str = field(default_factory=lambda: str(uuid4()))
+ timestamp: datetime = field(default_factory=datetime.now)
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert event to dictionary."""
+ return {
+ "type": self.type.value if isinstance(self.type, EventType) else self.type,
+ "task_id": self.task_id,
+ "user_input": self.user_input,
+ "agent_output": self.agent_output,
+ "tools_used": self.tools_used,
+ "success": self.success,
+ "metadata": self.metadata,
+ "event_id": self.event_id,
+ "timestamp": self.timestamp.isoformat(),
+ }
+
+
+# Type alias for event handlers
+EventHandler = Callable[[Event], Coroutine[Any, Any, None]]
+
+
+class EventBus:
+ """
+ Singleton asynchronous event bus.
+
+ Provides publish/subscribe functionality with non-blocking event delivery.
+ Events are processed in the background without blocking the publisher.
+
+ Usage:
+ # Get the singleton instance
+ bus = get_event_bus()
+
+ # Subscribe to events
+ async def handle_solve(event: Event):
+ print(f"Solve completed: {event.task_id}")
+
+ bus.subscribe(EventType.SOLVE_COMPLETE, handle_solve)
+
+ # Publish events (non-blocking)
+ await bus.publish(Event(
+ type=EventType.SOLVE_COMPLETE,
+ task_id="task-123",
+ user_input="What is 2+2?",
+ agent_output="The answer is 4.",
+ ))
+ """
+
+ _instance: Optional["EventBus"] = None
+ _initialized: bool = False
+
+ def __new__(cls) -> "EventBus":
+ if cls._instance is None:
+ cls._instance = super().__new__(cls)
+ return cls._instance
+
+ def __init__(self) -> None:
+ # Only initialize once
+ if EventBus._initialized:
+ return
+
+ self._subscribers: Dict[EventType, List[EventHandler]] = {
+ event_type: [] for event_type in EventType
+ }
+ self._task_queue: asyncio.Queue[Event] = asyncio.Queue()
+ self._processor_task: Optional[asyncio.Task] = None
+ self._running: bool = False
+
+ EventBus._initialized = True
+ logger.debug("EventBus initialized")
+
+ def subscribe(self, event_type: EventType, handler: EventHandler) -> None:
+ """
+ Subscribe a handler to an event type.
+
+ Args:
+ event_type: The type of event to subscribe to
+ handler: Async function to call when event is published
+ """
+ if handler not in self._subscribers[event_type]:
+ self._subscribers[event_type].append(handler)
+ logger.debug(f"Handler subscribed to {event_type.value}")
+
+ def unsubscribe(self, event_type: EventType, handler: EventHandler) -> None:
+ """
+ Unsubscribe a handler from an event type.
+
+ Args:
+ event_type: The type of event to unsubscribe from
+ handler: The handler to remove
+ """
+ if handler in self._subscribers[event_type]:
+ self._subscribers[event_type].remove(handler)
+ logger.debug(f"Handler unsubscribed from {event_type.value}")
+
+ async def publish(self, event: Event) -> None:
+ """
+ Publish an event to all subscribers (non-blocking).
+
+ The event is queued for background processing, allowing the publisher
+ to continue immediately without waiting for handlers to complete.
+
+ Args:
+ event: The event to publish
+ """
+ await self._task_queue.put(event)
+ logger.debug(f"Event published: {event.type.value} (task_id={event.task_id})")
+
+ # Start processor if not running
+ if not self._running:
+ await self.start()
+
+ async def _process_events(self) -> None:
+ """Background task that processes queued events."""
+ while self._running:
+ try:
+ # Wait for an event with timeout to allow clean shutdown
+ try:
+ event = await asyncio.wait_for(
+ self._task_queue.get(), timeout=1.0
+ )
+ except asyncio.TimeoutError:
+ continue
+
+ # Get handlers for this event type
+ handlers = self._subscribers.get(event.type, [])
+
+ if not handlers:
+ logger.debug(f"No handlers for event type: {event.type.value}")
+ self._task_queue.task_done()
+ continue
+
+ # Execute all handlers concurrently
+ for handler in handlers:
+ try:
+ await handler(event)
+ logger.debug(
+ f"Handler completed for {event.type.value} "
+ f"(task_id={event.task_id})"
+ )
+ except Exception as e:
+ logger.error(
+ f"Handler error for {event.type.value}: {e}",
+ exc_info=True,
+ )
+
+ self._task_queue.task_done()
+
+ except asyncio.CancelledError:
+ logger.debug("Event processor cancelled")
+ break
+ except Exception as e:
+ logger.error(f"Event processing error: {e}", exc_info=True)
+
+ async def start(self) -> None:
+ """Start the event processor."""
+ if self._running:
+ return
+
+ self._running = True
+ self._processor_task = asyncio.create_task(self._process_events())
+ logger.info("EventBus started")
+
+ 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)
+ try:
+ await asyncio.wait_for(self._task_queue.join(), timeout=5.0)
+ except asyncio.TimeoutError:
+ logger.warning("EventBus shutdown timeout - some events may be lost")
+
+ # Cancel processor task
+ if self._processor_task:
+ self._processor_task.cancel()
+ try:
+ await self._processor_task
+ except asyncio.CancelledError:
+ pass
+
+ logger.info("EventBus stopped")
+
+ @classmethod
+ def reset(cls) -> None:
+ """Reset the singleton instance (for testing)."""
+ if cls._instance is not None:
+ cls._instance._running = False
+ if cls._instance._processor_task:
+ cls._instance._processor_task.cancel()
+ cls._instance = None
+ cls._initialized = False
+
+
+# Module-level singleton accessor
+_event_bus: Optional[EventBus] = None
+
+
+def get_event_bus() -> EventBus:
+ """
+ Get the singleton EventBus instance.
+
+ Returns:
+ The global EventBus instance
+ """
+ global _event_bus
+ if _event_bus is None:
+ _event_bus = EventBus()
+ return _event_bus
diff --git a/src/logging/config.py b/src/logging/config.py
index 150a40af0..a7a2b0498 100644
--- a/src/logging/config.py
+++ b/src/logging/config.py
@@ -36,8 +36,10 @@ class LoggingConfig:
def get_default_log_dir() -> Path:
"""Get the default log directory."""
- project_root = Path(__file__).resolve().parent.parent.parent
- return project_root / "data" / "user" / "logs"
+ from src.services.path_service import get_path_service
+
+ path_service = get_path_service()
+ return path_service.get_logs_dir()
def get_global_log_level() -> str:
diff --git a/src/logging/logger.py b/src/logging/logger.py
index 1dab05f6f..a47342237 100644
--- a/src/logging/logger.py
+++ b/src/logging/logger.py
@@ -24,6 +24,9 @@ from typing import Any, List, Optional, Union
from src.config.constants import PROJECT_ROOT
+# Note: path_service is imported lazily inside Logger.__init__ to avoid
+# circular import: logging -> services -> services/config -> logging
+
class LogLevel(Enum):
"""Log levels with standard tags"""
@@ -177,7 +180,10 @@ class Logger:
# Setup log directory
log_dir_path: Path
if log_dir is None:
- log_dir_path = PROJECT_ROOT / "data" / "user" / "logs"
+ # Lazy import to avoid circular import
+ from src.services.path_service import get_path_service
+ path_svc = get_path_service()
+ log_dir_path = path_svc.get_logs_dir()
else:
log_dir_path = Path(log_dir) if isinstance(log_dir, str) else log_dir
# If relative path, resolve it relative to project root
diff --git a/src/personalization/__init__.py b/src/personalization/__init__.py
new file mode 100644
index 000000000..bef89dc7b
--- /dev/null
+++ b/src/personalization/__init__.py
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+"""
+Personalization Module
+======================
+
+Provides personalized learning experience through memory management and
+event-driven updates.
+
+Components:
+- LearningMemory: Markdown-based memory storage for user preferences and notes
+- MemoryAgent: LLM-powered agent for memory analysis and updates
+- PersonalizationService: Service layer for memory management
+"""
+
+from .memory import LearningMemory, get_learning_memory
+from .memory_agent import MemoryAgent, MemoryDecision
+from .service import PersonalizationService, get_personalization_service
+
+__all__ = [
+ "LearningMemory",
+ "get_learning_memory",
+ "MemoryAgent",
+ "MemoryDecision",
+ "PersonalizationService",
+ "get_personalization_service",
+]
diff --git a/src/personalization/memory.py b/src/personalization/memory.py
new file mode 100644
index 000000000..ead5885c4
--- /dev/null
+++ b/src/personalization/memory.py
@@ -0,0 +1,431 @@
+# -*- coding: utf-8 -*-
+"""
+Learning Memory
+===============
+
+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']}
+
+{self.SECTIONS['milestones']}
+"""
+
+ # =========================================================================
+ # 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_memory
diff --git a/src/personalization/memory_agent.py b/src/personalization/memory_agent.py
new file mode 100644
index 000000000..c2b482df7
--- /dev/null
+++ b/src/personalization/memory_agent.py
@@ -0,0 +1,236 @@
+# -*- 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 None
diff --git a/src/personalization/prompts/en/memory_agent.yaml b/src/personalization/prompts/en/memory_agent.yaml
new file mode 100644
index 000000000..8cd7ee854
--- /dev/null
+++ b/src/personalization/prompts/en/memory_agent.yaml
@@ -0,0 +1,61 @@
+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/zh/memory_agent.yaml b/src/personalization/prompts/zh/memory_agent.yaml
new file mode 100644
index 000000000..8215ed69a
--- /dev/null
+++ b/src/personalization/prompts/zh/memory_agent.yaml
@@ -0,0 +1,60 @@
+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/service.py b/src/personalization/service.py
new file mode 100644
index 000000000..44033b45d
--- /dev/null
+++ b/src/personalization/service.py
@@ -0,0 +1,313 @@
+# -*- coding: utf-8 -*-
+"""
+Personalization Service
+=======================
+
+Service layer that coordinates personalization memory management.
+Listens to events, invokes MemoryAgent, and provides preference access.
+"""
+
+import asyncio
+import logging
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+import yaml
+
+from src.core.event_bus import Event, EventType, get_event_bus
+from src.services.path_service import get_path_service
+
+from .memory import LearningMemory, get_learning_memory
+from .memory_agent import MemoryAgent, MemoryDecision
+
+logger = 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
+
+ Usage:
+ # Get singleton instance
+ service = get_personalization_service()
+
+ # Start the service (call during app startup)
+ await service.start()
+
+ # Get preference for prompt injection
+ preference = service.get_preference_for_prompt()
+
+ # Stop the service (call during app shutdown)
+ await service.stop()
+ """
+
+ _instance: Optional["PersonalizationService"] = None
+ _initialized: bool = False
+
+ def __new__(cls) -> "PersonalizationService":
+ if cls._instance is None:
+ cls._instance = super().__new__(cls)
+ return cls._instance
+
+ def __init__(self) -> None:
+ if PersonalizationService._initialized:
+ return
+
+ self._running = False
+ self._memory: Optional[LearningMemory] = None
+ self._agent: Optional[MemoryAgent] = None
+ self._config: Dict[str, Any] = {}
+ self._language = "en"
+
+ # Load configuration
+ self._load_config()
+
+ PersonalizationService._initialized = True
+ logger.debug("PersonalizationService initialized")
+
+ 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}")
+ except Exception as e:
+ logger.warning(f"Failed to load memory config: {e}")
+ self._config = {}
+ else:
+ logger.debug("No memory config found, using defaults")
+ self._config = {}
+
+ @property
+ def 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)
+
+ @property
+ def max_preference_length(self) -> int:
+ """Get maximum preference length for prompt injection."""
+ return self._config.get("memory", {}).get("max_preference_length", 2000)
+
+ async def start(self) -> None:
+ """
+ Start the personalization service.
+
+ This should be called during application startup.
+ Subscribes to EventBus and initializes components.
+ """
+ if self._running:
+ logger.debug("PersonalizationService already running")
+ return
+
+ self._running = True
+
+ # Initialize memory
+ self._memory = get_learning_memory()
+
+ # Initialize agent
+ llm_config = self._config.get("llm", {})
+ temperature = llm_config.get("temperature", 0.3)
+ self._agent = MemoryAgent(
+ language=self._language,
+ temperature=temperature,
+ )
+
+ # Subscribe to events
+ if self.auto_update:
+ event_bus = get_event_bus()
+ event_bus.subscribe(EventType.SOLVE_COMPLETE, self._handle_event)
+ event_bus.subscribe(EventType.QUESTION_COMPLETE, self._handle_event)
+ logger.info("PersonalizationService started, subscribed to events")
+ else:
+ 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 events
+ if 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.
+
+ 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:
+ return
+
+ try:
+ 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,
+ )
+
+ # Apply decision
+ await self._apply_decision(decision)
+
+ logger.debug(f"Event processed: action={decision.action}")
+
+ except Exception as e:
+ logger.error(f"Failed to process event: {e}", exc_info=True)
+
+ async def _apply_decision(self, decision: MemoryDecision) -> None:
+ """
+ Apply a MemoryDecision to storage.
+
+ Args:
+ decision: The decision from MemoryAgent
+ """
+ if decision.action == "skip":
+ return
+
+ if not self._memory:
+ 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")
+
+ # Update long-term memory
+ if decision.action in ("update_memory", "both") and decision.memory_updates:
+ updates = decision.memory_updates
+
+ if updates.get("preferences"):
+ self._memory.append_to_section("preferences", updates["preferences"])
+ logger.debug(f"Added {len(updates['preferences'])} preferences")
+
+ 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")
+
+ if updates.get("milestones"):
+ self._memory.append_to_section("milestones", updates["milestones"])
+ logger.debug(f"Added {len(updates['milestones'])} milestones")
+
+ def _format_recent_notes(self) -> str:
+ """Format recent notes for context."""
+ if not self._memory:
+ return ""
+
+ notes = self._memory.get_recent_notes(self.recent_days)
+ if not notes:
+ return ""
+
+ 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}")
+
+ return "\n".join(parts)
+
+ # =========================================================================
+ # Public Interface for Preference Access
+ # =========================================================================
+
+ def get_preference_for_prompt(self) -> str:
+ """
+ Get formatted preference context for prompt injection.
+
+ This method is called by agents (ResponseAgent, GenerateAgent) to get
+ user preferences for inclusion in prompts.
+
+ Returns:
+ Formatted preference string, or empty string if no preferences.
+ """
+ if not self._memory:
+ self._memory = get_learning_memory()
+
+ return self._memory.get_preference_context(self.max_preference_length)
+
+ def get_full_context(self) -> str:
+ """
+ Get full context including preferences and recent notes.
+
+ Returns:
+ Full context string for advanced personalization.
+ """
+ if not self._memory:
+ self._memory = get_learning_memory()
+
+ return self._memory.get_full_context(
+ recent_days=self.recent_days,
+ max_length=self.max_preference_length * 2,
+ )
+
+ def set_language(self, language: str) -> None:
+ """
+ Set the language for the service.
+
+ Args:
+ language: Language code ('en' or 'zh')
+ """
+ self._language = language
+ if self._agent:
+ self._agent.language = language
+
+ @classmethod
+ def reset(cls) -> None:
+ """Reset the singleton instance (for testing)."""
+ if cls._instance is not None:
+ cls._instance._running = False
+ cls._instance = None
+ cls._initialized = False
+
+
+# Module-level singleton accessor
+_personalization_service: Optional[PersonalizationService] = None
+
+
+def get_personalization_service() -> PersonalizationService:
+ """
+ Get the singleton PersonalizationService instance.
+
+ Returns:
+ The global PersonalizationService instance.
+ """
+ global _personalization_service
+ if _personalization_service is None:
+ _personalization_service = PersonalizationService()
+ return _personalization_service
diff --git a/src/services/__init__.py b/src/services/__init__.py
index d1698e349..51a15f135 100644
--- a/src/services/__init__.py
+++ b/src/services/__init__.py
@@ -45,7 +45,9 @@ Usage:
# Note: rag and embedding modules are lazy-loaded via __getattr__
# to avoid importing heavy dependencies (lightrag, llama_index) at module load time
-from . import config, llm, prompt, search, setup, tts
+from . import config, llm, prompt, search, session, setup, tts
+from .path_service import PathService, get_path_service
+from .session import BaseSessionManager
__all__ = [
"llm",
@@ -55,7 +57,11 @@ __all__ = [
"tts",
"search",
"setup",
+ "session",
"config",
+ "PathService",
+ "get_path_service",
+ "BaseSessionManager",
]
diff --git a/src/services/config/unified_config.py b/src/services/config/unified_config.py
index bd153753d..c57280532 100644
--- a/src/services/config/unified_config.py
+++ b/src/services/config/unified_config.py
@@ -24,8 +24,11 @@ PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)
load_dotenv(PROJECT_ROOT / ".env", override=False)
-# Storage directory
-SETTINGS_DIR = PROJECT_ROOT / "data" / "user" / "settings"
+# Storage directory using PathService
+from src.services.path_service import get_path_service
+
+_path_service = get_path_service()
+SETTINGS_DIR = _path_service.get_settings_dir()
class ConfigType(str, Enum):
diff --git a/src/services/path_service.py b/src/services/path_service.py
new file mode 100644
index 000000000..05f39245a
--- /dev/null
+++ b/src/services/path_service.py
@@ -0,0 +1,367 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+PathService - Centralized path management for user data directories.
+
+This module provides a singleton service for managing all paths related to
+the data/user directory structure:
+
+data/user/
+โ”œโ”€โ”€ agent/ # All Agent interaction history
+โ”‚ โ”œโ”€โ”€ solve/
+โ”‚ โ”‚ โ”œโ”€โ”€ sessions.json
+โ”‚ โ”‚ โ””โ”€โ”€ {task_id}/
+โ”‚ โ”œโ”€โ”€ chat/
+โ”‚ โ”‚ โ””โ”€โ”€ sessions.json
+โ”‚ โ”œโ”€โ”€ question/
+โ”‚ โ”‚ โ””โ”€โ”€ {batch_id}/
+โ”‚ โ”œโ”€โ”€ research/
+โ”‚ โ”‚ โ””โ”€โ”€ reports/
+โ”‚ โ”œโ”€โ”€ co-writer/
+โ”‚ โ”‚ โ”œโ”€โ”€ history.json
+โ”‚ โ”‚ โ””โ”€โ”€ tool_calls/
+โ”‚ โ”œโ”€โ”€ guide/
+โ”‚ โ”‚ โ””โ”€โ”€ {session_id}.json
+โ”‚ โ”œโ”€โ”€ run_code_workspace/
+โ”‚ โ””โ”€โ”€ logs/
+โ”‚
+โ”œโ”€โ”€ workspace/
+โ”‚ โ””โ”€โ”€ notebook/
+โ”‚
+โ””โ”€โ”€ settings/
+ โ”œโ”€โ”€ interface.json
+ โ”œโ”€โ”€ llm_configs.json
+ โ””โ”€โ”€ ...
+"""
+
+from pathlib import Path
+from typing import Literal
+
+# Module types that have agent directories
+AgentModule = Literal["solve", "chat", "question", "research", "co-writer", "guide", "run_code_workspace", "logs"]
+
+
+class PathService:
+ """
+ Singleton service for centralized path management.
+
+ Provides consistent path resolution for all user data directories,
+ eliminating scattered path calculations across the codebase.
+ """
+
+ _instance: "PathService | None" = None
+
+ def __new__(cls) -> "PathService":
+ if cls._instance is None:
+ cls._instance = super().__new__(cls)
+ cls._instance._initialized = False
+ return cls._instance
+
+ def __init__(self):
+ if self._initialized:
+ return
+
+ # Calculate project root from this file's location
+ # This file: src/services/path_service.py
+ # Project root: 3 levels up (src/services/ -> src/ -> project_root/)
+ self._project_root = Path(__file__).resolve().parent.parent.parent
+ self._user_data_dir = self._project_root / "data" / "user"
+ self._initialized = True
+
+ @classmethod
+ def get_instance(cls) -> "PathService":
+ """Get the singleton instance of PathService."""
+ if cls._instance is None:
+ cls._instance = cls()
+ return cls._instance
+
+ @classmethod
+ def reset_instance(cls) -> None:
+ """Reset the singleton instance (mainly for testing)."""
+ cls._instance = None
+
+ # =========================================================================
+ # Core Properties
+ # =========================================================================
+
+ @property
+ def project_root(self) -> Path:
+ """Get the project root directory."""
+ return self._project_root
+
+ @property
+ def user_data_dir(self) -> Path:
+ """Get the user data directory (data/user/)."""
+ return self._user_data_dir
+
+ # =========================================================================
+ # Agent Directory Methods
+ # =========================================================================
+
+ def get_agent_base_dir(self) -> Path:
+ """Get the base agent directory (data/user/agent/)."""
+ return self._user_data_dir / "agent"
+
+ def get_agent_dir(self, module: AgentModule) -> Path:
+ """
+ Get the directory for a specific agent module.
+
+ Args:
+ module: The agent module name (solve, chat, question, etc.)
+
+ Returns:
+ Path to data/user/agent/{module}/
+ """
+ return self.get_agent_base_dir() / module
+
+ def get_session_file(self, module: AgentModule) -> Path:
+ """
+ Get the sessions file path for a specific agent module.
+
+ Args:
+ module: The agent module name
+
+ Returns:
+ Path to data/user/agent/{module}/sessions.json
+ """
+ return self.get_agent_dir(module) / "sessions.json"
+
+ def get_task_dir(self, module: AgentModule, task_id: str) -> Path:
+ """
+ Get the task directory for a specific task within an agent module.
+
+ Args:
+ module: The agent module name
+ task_id: The unique task identifier
+
+ Returns:
+ Path to data/user/agent/{module}/{task_id}/
+ """
+ return self.get_agent_dir(module) / task_id
+
+ # =========================================================================
+ # Workspace Directory Methods
+ # =========================================================================
+
+ def get_workspace_dir(self) -> Path:
+ """Get the workspace directory (data/user/workspace/)."""
+ return self._user_data_dir / "workspace"
+
+ def get_notebook_dir(self) -> Path:
+ """Get the notebook directory (data/user/workspace/notebook/)."""
+ return self.get_workspace_dir() / "notebook"
+
+ def get_notebook_file(self, notebook_id: str) -> Path:
+ """
+ Get the file path for a specific notebook.
+
+ Args:
+ notebook_id: The notebook identifier
+
+ Returns:
+ Path to data/user/workspace/notebook/{notebook_id}.json
+ """
+ return self.get_notebook_dir() / f"{notebook_id}.json"
+
+ def get_notebook_index_file(self) -> Path:
+ """Get the notebook index file path."""
+ return self.get_notebook_dir() / "notebooks_index.json"
+
+ def get_memory_dir(self) -> Path:
+ """Get the memory directory for personalization (data/user/workspace/memory/)."""
+ return self.get_workspace_dir() / "memory"
+
+ # =========================================================================
+ # Settings Directory Methods
+ # =========================================================================
+
+ def get_settings_dir(self) -> Path:
+ """Get the settings directory (data/user/settings/)."""
+ return self._user_data_dir / "settings"
+
+ def get_settings_file(self, name: str) -> Path:
+ """
+ Get the settings file path for a specific settings type.
+
+ Args:
+ name: The settings file name (without .json extension)
+
+ Returns:
+ Path to data/user/settings/{name}.json
+ """
+ if not name.endswith(".json"):
+ name = f"{name}.json"
+ return self.get_settings_dir() / name
+
+ # =========================================================================
+ # Convenience Methods for Specific Modules
+ # =========================================================================
+
+ # Solve module
+ def get_solve_dir(self) -> Path:
+ """Get the solve module directory."""
+ return self.get_agent_dir("solve")
+
+ def get_solve_session_file(self) -> Path:
+ """Get the solve sessions file path."""
+ return self.get_session_file("solve")
+
+ def get_solve_task_dir(self, task_id: str) -> Path:
+ """Get a specific solve task directory."""
+ return self.get_task_dir("solve", task_id)
+
+ # Chat module
+ def get_chat_dir(self) -> Path:
+ """Get the chat module directory."""
+ return self.get_agent_dir("chat")
+
+ def get_chat_session_file(self) -> Path:
+ """Get the chat sessions file path."""
+ return self.get_session_file("chat")
+
+ # Question module
+ def get_question_dir(self) -> Path:
+ """Get the question module directory."""
+ return self.get_agent_dir("question")
+
+ def get_question_batch_dir(self, batch_id: str) -> Path:
+ """Get a specific question batch directory."""
+ return self.get_task_dir("question", batch_id)
+
+ # Research module
+ def get_research_dir(self) -> Path:
+ """Get the research module directory."""
+ return self.get_agent_dir("research")
+
+ def get_research_reports_dir(self) -> Path:
+ """Get the research reports directory."""
+ return self.get_research_dir() / "reports"
+
+ # Co-writer module
+ def get_co_writer_dir(self) -> Path:
+ """Get the co-writer module directory."""
+ return self.get_agent_dir("co-writer")
+
+ def get_co_writer_history_file(self) -> Path:
+ """Get the co-writer history file path."""
+ return self.get_co_writer_dir() / "history.json"
+
+ def get_co_writer_tool_calls_dir(self) -> Path:
+ """Get the co-writer tool calls directory."""
+ return self.get_co_writer_dir() / "tool_calls"
+
+ def get_co_writer_audio_dir(self) -> Path:
+ """Get the co-writer audio directory."""
+ return self.get_co_writer_dir() / "audio"
+
+ # Guide module
+ def get_guide_dir(self) -> Path:
+ """Get the guide module directory."""
+ return self.get_agent_dir("guide")
+
+ def get_guide_session_file(self, session_id: str) -> Path:
+ """Get a specific guide session file."""
+ return self.get_guide_dir() / f"session_{session_id}.json"
+
+ # Code execution workspace
+ def get_run_code_workspace_dir(self) -> Path:
+ """Get the code execution workspace directory."""
+ return self.get_agent_dir("run_code_workspace")
+
+ # Logs
+ def get_logs_dir(self) -> Path:
+ """Get the user logs directory."""
+ return self.get_agent_dir("logs")
+
+ # =========================================================================
+ # Directory Creation Utilities
+ # =========================================================================
+
+ def ensure_agent_dir(self, module: AgentModule) -> Path:
+ """
+ Ensure an agent module directory exists.
+
+ Args:
+ module: The agent module name
+
+ Returns:
+ The ensured directory path
+ """
+ path = self.get_agent_dir(module)
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+ def ensure_task_dir(self, module: AgentModule, task_id: str) -> Path:
+ """
+ Ensure a task directory exists within an agent module.
+
+ Args:
+ module: The agent module name
+ task_id: The task identifier
+
+ Returns:
+ The ensured directory path
+ """
+ path = self.get_task_dir(module, task_id)
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+ def ensure_workspace_dir(self) -> Path:
+ """Ensure the workspace directory exists."""
+ path = self.get_workspace_dir()
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+ def ensure_notebook_dir(self) -> Path:
+ """Ensure the notebook directory exists."""
+ path = self.get_notebook_dir()
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+ def ensure_memory_dir(self) -> Path:
+ """Ensure the memory directory exists for personalization."""
+ path = self.get_memory_dir()
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+ def ensure_settings_dir(self) -> Path:
+ """Ensure the settings directory exists."""
+ path = self.get_settings_dir()
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+ def ensure_all_directories(self) -> None:
+ """
+ Ensure all required directories exist.
+ Called during system initialization.
+ """
+ # Agent directories
+ agent_modules: list[AgentModule] = [
+ "solve", "chat", "question", "research",
+ "co-writer", "guide", "run_code_workspace", "logs"
+ ]
+ for module in agent_modules:
+ self.ensure_agent_dir(module)
+
+ # Co-writer subdirectories
+ self.get_co_writer_tool_calls_dir().mkdir(parents=True, exist_ok=True)
+ self.get_co_writer_audio_dir().mkdir(parents=True, exist_ok=True)
+
+ # Research subdirectories
+ self.get_research_reports_dir().mkdir(parents=True, exist_ok=True)
+
+ # Workspace directories
+ self.ensure_notebook_dir()
+ self.ensure_memory_dir()
+
+ # Settings directory
+ self.ensure_settings_dir()
+
+
+# Convenience function for quick access
+def get_path_service() -> PathService:
+ """Get the PathService singleton instance."""
+ return PathService.get_instance()
+
+
+__all__ = ["PathService", "get_path_service", "AgentModule"]
diff --git a/src/services/session/__init__.py b/src/services/session/__init__.py
new file mode 100644
index 000000000..df886fd7e
--- /dev/null
+++ b/src/services/session/__init__.py
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+"""
+Session Management Module
+=========================
+
+Provides unified session management for all agent modules.
+
+Usage:
+ from src.services.session import BaseSessionManager
+
+ class MySessionManager(BaseSessionManager):
+ def __init__(self):
+ super().__init__("my_module")
+
+ def _get_session_id_prefix(self) -> str:
+ return "my_"
+
+ def _get_default_title(self) -> str:
+ return "New My Session"
+
+ # ... implement other abstract methods
+"""
+
+from .base_session_manager import BaseSessionManager
+
+__all__ = ["BaseSessionManager"]
diff --git a/src/services/session/base_session_manager.py b/src/services/session/base_session_manager.py
new file mode 100644
index 000000000..62a13bd2c
--- /dev/null
+++ b/src/services/session/base_session_manager.py
@@ -0,0 +1,373 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+BaseSessionManager - Unified session management base class.
+
+This module provides a base class for managing persistent sessions
+across different agent modules (solve, chat, etc.).
+
+Features:
+- Consistent JSON storage format
+- Session CRUD operations
+- Message management within sessions
+- Automatic session ordering (newest first)
+- Configurable session limits
+"""
+
+import json
+import time
+import uuid
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import Any
+
+from src.services.path_service import get_path_service
+
+
+class BaseSessionManager(ABC):
+ """
+ Abstract base class for session management.
+
+ Provides common functionality for storing and retrieving sessions,
+ with customization points for module-specific behavior.
+
+ Subclasses must implement:
+ - _get_session_id_prefix(): Return the session ID prefix (e.g., "solve_", "chat_")
+ - _get_default_title(): Return the default title for new sessions
+ - _create_session_data(): Create module-specific session data structure
+ - _get_session_summary(): Create module-specific session summary for listing
+ """
+
+ MAX_SESSIONS = 100 # Maximum number of sessions to keep
+
+ def __init__(self, module_name: str):
+ """
+ Initialize the session manager.
+
+ Args:
+ module_name: The module name (e.g., "solve", "chat")
+ Used to determine the session file path.
+ """
+ self.module_name = module_name
+ self.path_service = get_path_service()
+ self.sessions_file = self.path_service.get_session_file(module_name)
+ self._ensure_file()
+
+ # =========================================================================
+ # Abstract Methods - Must be implemented by subclasses
+ # =========================================================================
+
+ @abstractmethod
+ def _get_session_id_prefix(self) -> str:
+ """
+ Return the prefix for session IDs.
+
+ Example: "solve_" -> session IDs like "solve_1234567890_abc123"
+ """
+ pass
+
+ @abstractmethod
+ def _get_default_title(self) -> str:
+ """
+ Return the default title for new sessions.
+
+ Example: "New Solver Session" or "New Chat"
+ """
+ pass
+
+ @abstractmethod
+ def _create_session_data(self, **kwargs) -> dict[str, Any]:
+ """
+ Create the initial session data structure.
+
+ Args:
+ **kwargs: Module-specific parameters
+
+ Returns:
+ Dict containing module-specific session fields
+ (should NOT include session_id, title, messages, created_at, updated_at
+ as those are added by create_session())
+ """
+ pass
+
+ @abstractmethod
+ def _get_session_summary(self, session: dict[str, Any]) -> dict[str, Any]:
+ """
+ Create a summary of a session for listing.
+
+ Args:
+ session: The full session data
+
+ Returns:
+ Dict containing summary fields for list display
+ (should include session_id, title, message_count, created_at, updated_at,
+ last_message, plus any module-specific fields)
+ """
+ pass
+
+ # =========================================================================
+ # File Operations
+ # =========================================================================
+
+ def _ensure_file(self) -> None:
+ """Ensure the sessions file exists with correct format."""
+ # Ensure directory exists
+ self.sessions_file.parent.mkdir(parents=True, exist_ok=True)
+
+ if not self.sessions_file.exists():
+ initial_data = {
+ "version": "1.0",
+ "sessions": [],
+ }
+ self._save_data(initial_data)
+
+ def _load_data(self) -> dict[str, Any]:
+ """Load sessions data from file."""
+ try:
+ with open(self.sessions_file, encoding="utf-8") as f:
+ return json.load(f)
+ except (json.JSONDecodeError, FileNotFoundError):
+ return {"version": "1.0", "sessions": []}
+
+ def _save_data(self, data: dict[str, Any]) -> None:
+ """Save sessions data to file."""
+ with open(self.sessions_file, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+
+ def _get_sessions(self) -> list[dict[str, Any]]:
+ """Get list of all sessions."""
+ data = self._load_data()
+ return data.get("sessions", [])
+
+ def _save_sessions(self, sessions: list[dict[str, Any]]) -> None:
+ """Save sessions list."""
+ data = self._load_data()
+ data["sessions"] = sessions
+ self._save_data(data)
+
+ # =========================================================================
+ # Session CRUD Operations
+ # =========================================================================
+
+ def create_session(
+ self,
+ title: str | None = None,
+ **kwargs,
+ ) -> dict[str, Any]:
+ """
+ Create a new session.
+
+ Args:
+ title: Session title (uses default if None)
+ **kwargs: Module-specific parameters passed to _create_session_data()
+
+ Returns:
+ New session dict with session_id
+ """
+ prefix = self._get_session_id_prefix()
+ session_id = f"{prefix}{int(time.time() * 1000)}_{uuid.uuid4().hex[:8]}"
+ now = time.time()
+
+ # Use provided title or default
+ if title is None:
+ title = self._get_default_title()
+
+ # Create base session structure
+ session = {
+ "session_id": session_id,
+ "title": title[:100] if title else self._get_default_title(), # Limit title length
+ "messages": [],
+ "created_at": now,
+ "updated_at": now,
+ }
+
+ # Add module-specific data
+ module_data = self._create_session_data(**kwargs)
+ session.update(module_data)
+
+ # Add to sessions list
+ sessions = self._get_sessions()
+ sessions.insert(0, session) # Add to front (newest first)
+
+ # Limit total sessions
+ if len(sessions) > self.MAX_SESSIONS:
+ sessions = sessions[:self.MAX_SESSIONS]
+
+ self._save_sessions(sessions)
+
+ return session
+
+ def get_session(self, session_id: str) -> dict[str, Any] | None:
+ """
+ Get a session by ID.
+
+ Args:
+ session_id: Session identifier
+
+ Returns:
+ Session dict or None if not found
+ """
+ sessions = self._get_sessions()
+ for session in sessions:
+ if session.get("session_id") == session_id:
+ return session
+ return None
+
+ def update_session(
+ self,
+ session_id: str,
+ messages: list[dict[str, Any]] | None = None,
+ title: str | None = None,
+ **kwargs,
+ ) -> dict[str, Any] | None:
+ """
+ Update a session with new data.
+
+ Args:
+ session_id: Session identifier
+ messages: New messages list (replaces existing)
+ title: New title (optional)
+ **kwargs: Module-specific fields to update
+
+ Returns:
+ Updated session or None if not found
+ """
+ sessions = self._get_sessions()
+
+ for i, session in enumerate(sessions):
+ if session.get("session_id") == session_id:
+ if messages is not None:
+ session["messages"] = messages
+ if title is not None:
+ session["title"] = title[:100]
+
+ # Update module-specific fields
+ for key, value in kwargs.items():
+ if value is not None:
+ session[key] = value
+
+ session["updated_at"] = time.time()
+
+ # Move to front (most recently updated)
+ sessions.pop(i)
+ sessions.insert(0, session)
+
+ self._save_sessions(sessions)
+ return session
+
+ return None
+
+ def add_message(
+ self,
+ session_id: str,
+ role: str,
+ content: str,
+ **metadata,
+ ) -> dict[str, Any] | None:
+ """
+ Add a single message to a session.
+
+ Args:
+ session_id: Session identifier
+ role: Message role ('user' or 'assistant')
+ content: Message content
+ **metadata: Additional message metadata (e.g., sources, output_dir)
+
+ Returns:
+ Updated session or None if not found
+ """
+ session = self.get_session(session_id)
+ if not session:
+ return None
+
+ message = {
+ "role": role,
+ "content": content,
+ "timestamp": time.time(),
+ }
+
+ # Add any additional metadata
+ for key, value in metadata.items():
+ if value is not None:
+ message[key] = value
+
+ messages = session.get("messages", [])
+ messages.append(message)
+
+ # Update title from first user message if still default
+ title = None
+ if session.get("title") == self._get_default_title() and role == "user":
+ title = content[:50] + ("..." if len(content) > 50 else "")
+
+ return self.update_session(session_id, messages=messages, title=title)
+
+ def list_sessions(
+ self,
+ limit: int = 20,
+ include_messages: bool = False,
+ ) -> list[dict[str, Any]]:
+ """
+ List recent sessions.
+
+ Args:
+ limit: Maximum number of sessions to return
+ include_messages: Whether to include full message history
+
+ Returns:
+ List of session dicts (newest first)
+ """
+ sessions = self._get_sessions()[:limit]
+
+ if not include_messages:
+ # Return summary only (without full messages)
+ return [self._get_session_summary(s) for s in sessions]
+
+ return sessions
+
+ def delete_session(self, session_id: str) -> bool:
+ """
+ Delete a session.
+
+ Args:
+ session_id: Session identifier
+
+ Returns:
+ True if deleted, False if not found
+ """
+ sessions = self._get_sessions()
+ original_count = len(sessions)
+
+ sessions = [s for s in sessions if s.get("session_id") != session_id]
+
+ if len(sessions) < original_count:
+ self._save_sessions(sessions)
+ return True
+
+ return False
+
+ def clear_all_sessions(self) -> int:
+ """
+ Delete all sessions.
+
+ Returns:
+ Number of sessions deleted
+ """
+ sessions = self._get_sessions()
+ count = len(sessions)
+ self._save_sessions([])
+ return count
+
+ # =========================================================================
+ # Utility Methods
+ # =========================================================================
+
+ def get_session_count(self) -> int:
+ """Get the total number of sessions."""
+ return len(self._get_sessions())
+
+ def session_exists(self, session_id: str) -> bool:
+ """Check if a session exists."""
+ return self.get_session(session_id) is not None
+
+
+__all__ = ["BaseSessionManager"]
diff --git a/src/services/settings/interface_settings.py b/src/services/settings/interface_settings.py
index 85edab724..134a7690d 100644
--- a/src/services/settings/interface_settings.py
+++ b/src/services/settings/interface_settings.py
@@ -11,8 +11,10 @@ import json
from pathlib import Path
from typing import Any
-PROJECT_ROOT = Path(__file__).resolve().parents[3]
-INTERFACE_SETTINGS_FILE = PROJECT_ROOT / "data" / "user" / "settings" / "interface.json"
+from src.services.path_service import get_path_service
+
+_path_service = get_path_service()
+INTERFACE_SETTINGS_FILE = _path_service.get_settings_file("interface")
DEFAULT_UI_SETTINGS: dict[str, Any] = {
"theme": "light",
diff --git a/src/services/setup/init.py b/src/services/setup/init.py
index dcc1102cb..040549a94 100644
--- a/src/services/setup/init.py
+++ b/src/services/setup/init.py
@@ -10,7 +10,7 @@ import os
from pathlib import Path
from src.logging import get_logger
-from src.services.config import load_config_with_main
+from src.services.path_service import get_path_service
# Initialize logger for setup operations
_setup_logger = None
@@ -25,7 +25,7 @@ def _get_setup_logger():
# ============================================================================
-# User Directory Initialization (from user_dir_init.py)
+# User Directory Initialization
# ============================================================================
@@ -35,67 +35,34 @@ def init_user_directories(project_root: Path | None = None) -> None:
Creates the following directory structure:
data/user/
- โ”œโ”€โ”€ solve/ # Problem solving outputs
- โ”œโ”€โ”€ question/ # Question generation outputs
- โ”œโ”€โ”€ research/ # Research outputs
- โ”‚ โ”œโ”€โ”€ cache/ # Research cache
- โ”‚ โ””โ”€โ”€ reports/ # Research reports
- โ”œโ”€โ”€ guide/ # Guided learning outputs
- โ”œโ”€โ”€ notebook/ # Notebook data
- โ”œโ”€โ”€ co-writer/ # Co-writer outputs
- โ”‚ โ”œโ”€โ”€ audio/ # TTS audio files
- โ”‚ โ””โ”€โ”€ tool_calls/ # Tool call history
- โ”œโ”€โ”€ logs/ # User logs
- โ”œโ”€โ”€ run_code_workspace/ # Code execution workspace
- โ””โ”€โ”€ user_history.json # User history file
+ โ”œโ”€โ”€ agent/ # All Agent interaction history
+ โ”‚ โ”œโ”€โ”€ solve/
+ โ”‚ โ”‚ โ””โ”€โ”€ sessions.json
+ โ”‚ โ”œโ”€โ”€ chat/
+ โ”‚ โ”‚ โ””โ”€โ”€ sessions.json
+ โ”‚ โ”œโ”€โ”€ question/
+ โ”‚ โ”œโ”€โ”€ research/
+ โ”‚ โ”‚ โ””โ”€โ”€ reports/
+ โ”‚ โ”œโ”€โ”€ co-writer/
+ โ”‚ โ”‚ โ”œโ”€โ”€ audio/
+ โ”‚ โ”‚ โ””โ”€โ”€ tool_calls/
+ โ”‚ โ”œโ”€โ”€ guide/
+ โ”‚ โ”œโ”€โ”€ run_code_workspace/
+ โ”‚ โ””โ”€โ”€ logs/
+ โ”‚
+ โ”œโ”€โ”€ workspace/
+ โ”‚ โ”œโ”€โ”€ notebook/
+ โ”‚ โ””โ”€โ”€ memory/ # Personalization memory storage
+ โ”‚
+ โ””โ”€โ”€ settings/
+ โ””โ”€โ”€ interface.json
Args:
- project_root: Project root directory (if None, will try to detect)
+ project_root: Project root directory (ignored, kept for API compatibility)
"""
- if project_root is None:
- # Path(__file__) = src/services/setup/init.py
- # .parent = src/services/setup/
- # .parent.parent = src/services/
- # .parent.parent.parent = src/
- # .parent.parent.parent.parent = DeepTutor/ (project root)
- project_root = Path(__file__).parent.parent.parent.parent
-
- # Get user data directory from config
- try:
- config = load_config_with_main("solve_config.yaml", project_root)
- user_data_dir = config.get("paths", {}).get("user_data_dir", "./data/user")
-
- # Convert relative path to absolute
- if not Path(user_data_dir).is_absolute():
- user_data_dir = project_root / user_data_dir
- else:
- user_data_dir = Path(user_data_dir)
- except Exception:
- # Fallback to default
- user_data_dir = project_root / "data" / "user"
-
- # Required subdirectories (based on actual usage in the codebase)
- required_dirs = [
- "solve", # Problem solving outputs
- "question", # Question generation outputs
- "research", # Research outputs (will have cache/ and reports/ subdirs)
- "guide", # Guided learning outputs
- "notebook", # Notebook data
- "co-writer", # Co-writer outputs
- "logs", # User logs
- "run_code_workspace", # Code execution workspace
- ]
-
- # Additional subdirectories for specific modules
- co_writer_subdirs = [
- "audio", # TTS audio files
- "tool_calls", # Tool call history
- ]
-
- research_subdirs = [
- "cache", # Research cache
- "reports", # Research reports
- ]
+ # Use PathService for all paths
+ path_service = get_path_service()
+ user_data_dir = path_service.user_data_dir
# Check if user directory exists and is empty
user_dir_exists = user_data_dir.exists()
@@ -124,41 +91,40 @@ def init_user_directories(project_root: Path | None = None) -> None:
# Create main user directory
user_data_dir.mkdir(parents=True, exist_ok=True)
- # Create all required subdirectories
- for dir_name in required_dirs:
- dir_path = user_data_dir / dir_name
+ # Create agent directories
+ agent_modules = ["solve", "chat", "question", "research", "co-writer", "guide", "run_code_workspace", "logs"]
+ for module in agent_modules:
+ dir_path = path_service.get_agent_dir(module)
dir_path.mkdir(parents=True, exist_ok=True)
- logger.success(f"Created: {dir_name}/")
+ logger.success(f"Created: agent/{module}/")
# Create co-writer subdirectories
- co_writer_dir = user_data_dir / "co-writer"
+ co_writer_subdirs = ["audio", "tool_calls"]
+ co_writer_dir = path_service.get_co_writer_dir()
for subdir_name in co_writer_subdirs:
subdir_path = co_writer_dir / subdir_name
subdir_path.mkdir(parents=True, exist_ok=True)
- logger.success(f"Created: co-writer/{subdir_name}/")
+ logger.success(f"Created: agent/co-writer/{subdir_name}/")
# Create research subdirectories
- research_dir = user_data_dir / "research"
- for subdir_name in research_subdirs:
- subdir_path = research_dir / subdir_name
- subdir_path.mkdir(parents=True, exist_ok=True)
- logger.success(f"Created: research/{subdir_name}/")
-
- # Create user_history.json if it doesn't exist
- user_history_file = user_data_dir / "user_history.json"
- if not user_history_file.exists():
- initial_history = {"version": "1.0", "created_at": None, "sessions": []}
- try:
- with open(user_history_file, "w", encoding="utf-8") as f:
- json.dump(initial_history, f, indent=2, ensure_ascii=False)
- logger.success("Created: user_history.json")
- except Exception as e:
- logger.warning(f"Failed to create user_history.json: {e}")
-
- # Create interface.json in settings folder if it doesn't exist
- settings_dir = user_data_dir / "settings"
+ reports_dir = path_service.get_research_reports_dir()
+ reports_dir.mkdir(parents=True, exist_ok=True)
+ logger.success("Created: agent/research/reports/")
+
+ # Create workspace/notebook directory
+ notebook_dir = path_service.get_notebook_dir()
+ notebook_dir.mkdir(parents=True, exist_ok=True)
+ logger.success("Created: workspace/notebook/")
+
+ # Create workspace/memory directory for personalization
+ memory_dir = path_service.get_memory_dir()
+ memory_dir.mkdir(parents=True, exist_ok=True)
+ logger.success("Created: workspace/memory/")
+
+ # Create settings directory and interface.json
+ settings_dir = path_service.get_settings_dir()
settings_dir.mkdir(parents=True, exist_ok=True)
- interface_file = settings_dir / "interface.json"
+ interface_file = path_service.get_settings_file("interface")
if not interface_file.exists():
initial_settings = {"theme": "light", "language": "en", "output_language": "en"}
try:
@@ -173,43 +139,42 @@ def init_user_directories(project_root: Path | None = None) -> None:
logger.info("=" * 80 + "\n")
else:
# Directory exists and is not empty, just ensure all subdirectories exist
- for dir_name in required_dirs:
- dir_path = user_data_dir / dir_name
- dir_path.mkdir(parents=True, exist_ok=True)
-
- # Ensure co-writer subdirectories exist
- co_writer_dir = user_data_dir / "co-writer"
- for subdir_name in co_writer_subdirs:
- subdir_path = co_writer_dir / subdir_name
- subdir_path.mkdir(parents=True, exist_ok=True)
-
- # Ensure research subdirectories exist
- research_dir = user_data_dir / "research"
- for subdir_name in research_subdirs:
- subdir_path = research_dir / subdir_name
- subdir_path.mkdir(parents=True, exist_ok=True)
+ _ensure_directories_exist(path_service)
- # Ensure user_history.json exists
- user_history_file = user_data_dir / "user_history.json"
- if not user_history_file.exists():
- initial_history = {"version": "1.0", "created_at": None, "sessions": []}
- try:
- with open(user_history_file, "w", encoding="utf-8") as f:
- json.dump(initial_history, f, indent=2, ensure_ascii=False)
- except Exception:
- pass # Silent fail if file creation fails but directory exists
- # Ensure interface.json exists in settings folder
- settings_dir = user_data_dir / "settings"
- settings_dir.mkdir(parents=True, exist_ok=True)
- interface_file = settings_dir / "interface.json"
- if not interface_file.exists():
- initial_settings = {"theme": "light", "language": "en", "output_language": "en"}
- try:
- with open(interface_file, "w", encoding="utf-8") as f:
- json.dump(initial_settings, f, indent=2, ensure_ascii=False)
- except Exception:
- pass # Silent fail if file creation fails but directory exists
+def _ensure_directories_exist(path_service) -> None:
+ """
+ Ensure all required directories exist (silent mode for existing installations).
+ """
+ # Agent directories
+ agent_modules = ["solve", "chat", "question", "research", "co-writer", "guide", "run_code_workspace", "logs"]
+ for module in agent_modules:
+ path_service.get_agent_dir(module).mkdir(parents=True, exist_ok=True)
+
+ # Co-writer subdirectories
+ path_service.get_co_writer_tool_calls_dir().mkdir(parents=True, exist_ok=True)
+ path_service.get_co_writer_audio_dir().mkdir(parents=True, exist_ok=True)
+
+ # Research reports directory
+ path_service.get_research_reports_dir().mkdir(parents=True, exist_ok=True)
+
+ # Workspace/notebook directory
+ path_service.get_notebook_dir().mkdir(parents=True, exist_ok=True)
+
+ # Workspace/memory directory for personalization
+ path_service.get_memory_dir().mkdir(parents=True, exist_ok=True)
+
+ # Settings directory and interface.json
+ settings_dir = path_service.get_settings_dir()
+ settings_dir.mkdir(parents=True, exist_ok=True)
+ interface_file = path_service.get_settings_file("interface")
+ if not interface_file.exists():
+ initial_settings = {"theme": "light", "language": "en", "output_language": "en"}
+ try:
+ with open(interface_file, "w", encoding="utf-8") as f:
+ json.dump(initial_settings, f, indent=2, ensure_ascii=False)
+ except Exception:
+ pass # Silent fail if file creation fails but directory exists
# ============================================================================
diff --git a/src/tools/code_executor.py b/src/tools/code_executor.py
index b1338df93..1b1b306dd 100644
--- a/src/tools/code_executor.py
+++ b/src/tools/code_executor.py
@@ -23,6 +23,7 @@ DEFAULT_WORKSPACE_NAME = "run_code_workspace"
PROJECT_ROOT = Path(__file__).resolve().parents[2]
from src.logging import get_logger
+from src.services.path_service import get_path_service
logger = get_logger("CodeExecutor")
@@ -133,14 +134,16 @@ class WorkspaceManager:
else:
self.base_dir = (PROJECT_ROOT / workspace_path).resolve()
else:
- # Default workspace is set under user directory
- self.base_dir = (PROJECT_ROOT / "data" / "user" / DEFAULT_WORKSPACE_NAME).resolve()
+ # Default workspace is set under user directory using PathService
+ path_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(),
- (PROJECT_ROOT / "data" / "user").resolve(),
+ path_service.user_data_dir.resolve(),
]
# Read allowed root paths from config file
diff --git a/web/.env.local b/web/.env.local
index 8840a64d6..0b6543af3 100644
--- a/web/.env.local
+++ b/web/.env.local
@@ -3,7 +3,7 @@
# ============================================
# This file is automatically updated based on config/main.yaml
# and environment variables (NEXT_PUBLIC_API_BASE, NEXT_PUBLIC_API_BASE_EXTERNAL)
-#
+#
# To configure for remote access, set in your .env file:
# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001
# ============================================