refact solver+questiongen, add base module for personalization

This commit is contained in:
Bingxi Zhao
2026-02-12 12:29:16 +08:00
parent 2384bd8e75
commit e1bedcb336
115 changed files with 7183 additions and 13440 deletions
+12 -1
View File
@@ -1,4 +1,4 @@
# ==============================================================================
# ==============================================================================
# DeepTutor Environment Configuration
# ==============================================================================
# Copy this file to `.env` and fill in the values.
@@ -107,6 +107,17 @@ NEXT_PUBLIC_API_BASE_EXTERNAL=
# [Optional] Direct API base URL (alternative to above)
NEXT_PUBLIC_API_BASE=
# ==============================================================================
# Personalization Service Configuration
# ==============================================================================
# Control how the personalization service runs
# [Optional] Run personalization service externally
# Set to "true" to run personalization in a separate process
# When enabled, start the service with: python scripts/start_personalization.py
# This allows separate logging and independent scaling
PERSONALIZATION_EXTERNAL=false
# ==============================================================================
# Debug & Development
# ==============================================================================
+12 -1
View File
@@ -1,4 +1,4 @@
# ==============================================================================
# ==============================================================================
# DeepTutor 环境配置文件
# ==============================================================================
# 请将此文件复制为 `.env` 并填写相应的值。
@@ -107,6 +107,17 @@ NEXT_PUBLIC_API_BASE_EXTERNAL=
# [可选] 直接 API 基础地址(上述配置的替代方案)
NEXT_PUBLIC_API_BASE=
# ==============================================================================
# 个性化服务配置
# ==============================================================================
# 控制个性化服务的运行模式
# [可选] 外置模式运行个性化服务
# 设置为 "true" 时,个性化服务将在独立进程中运行
# 启用后,请使用以下命令启动服务:python scripts/start_personalization.py
# 这允许独立的日志输出和独立的扩展
PERSONALIZATION_EXTERNAL=false
# ==============================================================================
# 调试与开发配置
# ==============================================================================
+17
View File
@@ -0,0 +1,17 @@
# DeepTutor LLM System (Current Behavior)
This file describes what the current LLM system does at runtime.
## What it does
- Loads active LLM configuration (API key, base URL, model, provider binding).
- Routes requests to the correct provider (cloud or local) via a unified factory.
- Supports both single-shot completion and streaming responses.
- Applies token limits and optional response formats when the provider supports them.
- Centralizes temperature and max token limits using `config/agents.yaml`.
- Logs LLM inputs/outputs and tracks token usage and timing per module.
- Maps provider errors into consistent exceptions for callers.
- Allows runtime config refresh so agents can pick up new settings without restart.
- Picks the final model by priority: agent override → global config → env defaults.
- Injects provider-specific kwargs (e.g., token limit fields) safely per model.
- Keeps a shared stats tracker per module for aggregated usage reporting.
+15 -23
View File
@@ -13,7 +13,7 @@ paths:
tools:
rag_tool:
kb_base_dir: ./data/knowledge_bases
default_kb: ai_textbook
default_kb: ai-textbook
run_code:
workspace: ./data/user/run_code_workspace
allowed_roots:
@@ -38,34 +38,26 @@ logging:
knowledge_init: RAG-Init
rag_tool: RAG
question:
# Refactored: no iteration loops (max_rounds removed)
rag_query_count: 3
max_parallel_questions: 1
rag_mode: naive
agents:
retrieve:
top_k: 30
generate:
max_retries: 2
relevance_analyzer:
enabled: true
idea_loop:
max_rounds: 3
ideas_per_round: 5
generation:
max_retries: 2
tools:
web_search: true
rag_tool: true
write_code: true
solve:
max_solve_correction_iterations: 3
max_react_iterations: 5 # Max ReAct rounds per plan step
max_plan_steps: 10 # Max steps in a plan
max_replans: 2 # Max replan attempts
observation_max_tokens: 2000 # Truncation limit for tool results
enable_citations: true
save_intermediate_results: true
# Valid tools for investigate agent validation
valid_tools:
- "rag_naive"
- "rag_hybrid"
- "web_search"
- "query_item"
- "none"
agents:
investigate_agent:
max_actions_per_round: 1
max_iterations: 3
precision_answer_agent:
enabled: true
detailed_answer: false # true = iterative step-by-step writing; false = single-shot
research:
planning:
rephrase:
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Personalization Service Launcher
================================
Standalone script to run the personalization service in a separate process.
This service:
1. Polls the event queue for learning events from the main application
2. Processes events with the MemoryAgent to extract insights
3. Updates user memory (preferences, weak points, milestones)
Usage:
python scripts/start_personalization.py
The service runs independently and only outputs personalization-related logs.
Press Ctrl+C to stop.
"""
import asyncio
import logging
import os
import signal
import sys
import time
from pathlib import Path
# Add project root to Python path
project_root = Path(__file__).parent.parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
from dotenv import load_dotenv
# Load environment variables
load_dotenv(project_root / "DeepTutor.env", override=False)
load_dotenv(project_root / ".env", override=False)
# Force unbuffered output
os.environ["PYTHONUNBUFFERED"] = "1"
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(line_buffering=True)
def setup_personalization_logging() -> logging.Logger:
"""
Set up dedicated logging for personalization service.
Only shows logs from personalization-related modules.
"""
# Create a dedicated logger for personalization
logger = logging.getLogger("personalization")
logger.setLevel(logging.DEBUG)
logger.handlers.clear()
# Console handler with custom format
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(
"%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
datefmt="%H:%M:%S"
)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# Also capture logs from related modules
related_modules = [
"src.personalization",
"src.personalization.service",
"src.personalization.memory",
"src.personalization.memory_agent",
"src.personalization.event_queue",
]
for module_name in related_modules:
module_logger = logging.getLogger(module_name)
module_logger.setLevel(logging.DEBUG)
module_logger.handlers.clear()
module_logger.addHandler(console_handler)
module_logger.propagate = False
# Suppress other loggers
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
logging.getLogger("openai").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
return logger
def print_banner():
"""Print startup banner."""
print("=" * 60)
print(" DeepTutor Personalization Service")
print("=" * 60)
print()
print(" This service processes learning events and maintains")
print(" user memory for personalized learning experience.")
print()
print(" Press Ctrl+C to stop.")
print()
print("=" * 60)
print()
class PersonalizationRunner:
"""
Standalone runner for the personalization service.
Polls the event queue and processes events using MemoryAgent.
"""
def __init__(self, poll_interval: float = 2.0):
"""
Initialize the runner.
Args:
poll_interval: Seconds between queue polls
"""
self.poll_interval = poll_interval
self._running = False
self._logger = logging.getLogger("personalization")
self._service = None
self._event_queue = None
async def start(self) -> None:
"""Start the personalization service."""
from src.core.event_bus import Event, EventType
from src.personalization import get_personalization_service
from src.personalization.event_queue import QueuedEvent, get_event_queue
self._running = True
self._service = get_personalization_service()
self._event_queue = get_event_queue()
# Start the service (initializes memory and agent)
await self._service.start()
self._logger.info("Personalization service started")
self._logger.info(f"Polling event queue every {self.poll_interval}s")
self._logger.info(f"Auto-update: {self._service.auto_update}")
# Check for pending events
pending = self._event_queue.pending_count()
if pending > 0:
self._logger.info(f"Found {pending} pending events in queue")
# Main event loop
while self._running:
try:
await self._process_queue()
await asyncio.sleep(self.poll_interval)
except asyncio.CancelledError:
break
except Exception as e:
self._logger.error(f"Error in event loop: {e}", exc_info=True)
await asyncio.sleep(self.poll_interval)
self._logger.info("Personalization service stopping...")
async def _process_queue(self) -> None:
"""Process events from the queue."""
from src.core.event_bus import Event, EventType
from src.personalization.event_queue import QueuedEvent
# Consume events from the queue
events_processed = 0
for queued_event in self._event_queue.consume(batch_size=10):
try:
self._logger.info(
f"Processing event: {queued_event.event_type} "
f"(task_id={queued_event.task_id})"
)
# Convert QueuedEvent to Event
event = Event(
type=EventType(queued_event.event_type),
task_id=queued_event.task_id,
user_input=queued_event.user_input,
agent_output=queued_event.agent_output,
tools_used=queued_event.tools_used,
success=queued_event.success,
metadata=queued_event.metadata,
event_id=queued_event.event_id,
)
# Process with the service's handler
await self._service._handle_event(event)
events_processed += 1
self._logger.info(
f"Event processed: {queued_event.event_type} "
f"(task_id={queued_event.task_id})"
)
except Exception as e:
self._logger.error(
f"Failed to process event {queued_event.event_id}: {e}",
exc_info=True
)
if events_processed > 0:
self._logger.info(f"Batch completed: {events_processed} events processed")
async def stop(self) -> None:
"""Stop the personalization service."""
self._running = False
if self._service:
await self._service.stop()
self._logger.info("Personalization service stopped")
def request_stop(self) -> None:
"""Request graceful shutdown (called from signal handler)."""
self._running = False
async def main():
"""Main entry point."""
# Set up logging
logger = setup_personalization_logging()
# Print banner
print_banner()
# Create runner
runner = PersonalizationRunner(poll_interval=2.0)
# Set up signal handlers
loop = asyncio.get_event_loop()
def signal_handler():
logger.info("Shutdown signal received")
runner.request_stop()
# Handle SIGINT (Ctrl+C) and SIGTERM
for sig in (signal.SIGINT, signal.SIGTERM):
try:
loop.add_signal_handler(sig, signal_handler)
except NotImplementedError:
# Windows doesn't support add_signal_handler
pass
try:
await runner.start()
except KeyboardInterrupt:
logger.info("Keyboard interrupt received")
finally:
await runner.stop()
print()
print("=" * 60)
print(" Personalization service stopped.")
print("=" * 60)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\nShutdown complete.")
+86 -374
View File
@@ -1,409 +1,121 @@
# Question Generation System
# Question Module (Refactored)
Intelligent question generation system with **modular agent architecture** supporting both knowledge base-driven custom generation and reference exam paper mimicking.
`src/agents/question` 已重构为**双循环架构**,用于统一处理:
## 📁 Directory Structure
- 主题驱动出题(topic + preference)
- 试卷驱动出题(PDF/已解析试卷)
```
question/
├── __init__.py # Module exports
├── agents/ # Specialized agents
│ ├── __init__.py
│ ├── retrieve_agent.py # Knowledge retrieval from KB
│ ├── generate_agent.py # Question generation
│ └── relevance_analyzer.py # Question-KB relevance analysis
├── prompts/ # Bilingual prompts (YAML)
│ ├── zh/ # Chinese prompts
│ │ ├── retrieve_agent.yaml
│ │ ├── generate_agent.yaml
│ │ ├── relevance_analyzer.yaml
│ │ └── coordinator.yaml
│ └── en/ # English prompts
│ └── (same structure)
├── coordinator.py # Workflow orchestration
├── example.py # Usage examples
└── README.md
## 1. 目录结构
# Tools moved to src/tools/question/
src/tools/question/
```text
src/agents/question/
├── __init__.py
├── pdf_parser.py # PDF parsing with MinerU
├── question_extractor.py # Extract questions from exams
└── exam_mimic.py # Reference-based question generation
├── coordinator.py
├── models.py
├── cli.py
├── agents/
│ ├── idea_agent.py
│ ├── evaluator.py
│ ├── generator.py
│ └── validator.py
└── prompts/
├── en/
│ ├── idea_agent.yaml
│ ├── evaluator.yaml
│ ├── generator.yaml
│ └── validator.yaml
└── zh/
├── idea_agent.yaml
├── evaluator.yaml
├── generator.yaml
└── validator.yaml
```
## 🚀 Core Features
## 2. 架构概览
### Custom Mode (Knowledge Base-Driven)
- ✅ **Intelligent Search Query Generation** - Generates configurable number of RAG queries
- ✅ **Background Knowledge Acquisition** - Retrieves relevant knowledge using RAG
- ✅ **Question Planning** - Creates comprehensive plan with question IDs and focuses
- ✅ **Single-Pass Relevance Analysis** - Analyzes question relevance (no iteration/rejection)
- ✅ **Complete File Persistence** - Saves knowledge, plan, and individual results
### 路径 1:Topic 模式
### Mimic Mode (Reference Exam-Based)
- ✅ **PDF Parsing** - Automatic PDF extraction using MinerU
- ✅ **Question Extraction** - Identifies and extracts reference questions from exams
- ✅ **Style Mimicking** - Generates similar questions based on reference structure
- ✅ **Batch Organization** - All outputs saved to timestamped folders
1. `IdeaAgent` 基于 topic/preference + RAG 生成候选出题创意
2. `Evaluator` 对创意打分并给反馈,必要时继续下一轮
3. 产出 top-k `QuestionTemplate`
4. 对每个 template 进入生成-验证循环:
- `Generator` 生成 Q-A(可用 `rag_tool` / `web_search` / `write_code`)
- `Validator` approve/reject,不通过则反馈重生
### Common Features
- ✅ **Unified BaseAgent** - All agents inherit from `src/agents/base_agent.py`
- ✅ **No Iteration Loops** - Single-pass generation + analysis
- ✅ **Bilingual Prompts** - Supports both Chinese and English via YAML
- ✅ **Real-time WebSocket Streaming** - Live progress updates to frontend
### 路径 2:Mimic 模式
## System Architecture
1. PDF 先经 MinerU 解析(或直接使用已解析目录)
2. 提取参考题(question extractor)
3. 参考题映射为 `QuestionTemplate`
4. 进入与 topic 模式相同的生成-验证循环
### Modular Agent Architecture
## 3. 核心数据模型
```
User Requirement
↓
┌─────────────────────────────────────────────────┐
│ AgentCoordinator │
│ │
│ 1. RetrieveAgent │
│ ├── Generate RAG queries (LLM) │
│ └── Execute RAG searches (parallel) │
│ │
│ 2. Plan Generation (in coordinator) │
│ └── Create focuses for each question │
│ │
│ 3. GenerateAgent (per question) │
│ └── Generate question from knowledge+focus │
│ │
│ 4. RelevanceAnalyzer (per question) │
│ └── Analyze KB relevance (high/partial) │
│ │
└─────────────────────────────────────────────────┘
↓
Save Results:
- knowledge.json (queries + retrievals)
- plan.json (focuses)
- q_1/result.json, q_1/question.md
- q_2/result.json, q_2/question.md
- summary.json
```
定义在 `models.py`:
### Mimic Mode Architecture
- `QuestionTemplate`:统一中间表示
- `question_id`
- `concentration`
- `question_type`
- `difficulty`
- `source` (`custom`/`mimic`)
- `QAPair`:最终生成结果
- `question`
- `correct_answer`
- `explanation`
- `validation`
```
PDF Upload / Parsed Directory
↓
Parse PDF with MinerU (tools/pdf_parser.py)
↓
Extract Reference Questions (tools/question_extractor.py)
↓
For each reference question (parallel):
AgentCoordinator.generate_question(with_reference=True)
├── RetrieveAgent
├── GenerateAgent (with reference)
└── RelevanceAnalyzer
↓
Save to timestamped folder
```
## 4. Coordinator 入口
## Core Components
`AgentCoordinator` 提供两个主入口:
### 1. RetrieveAgent
- `generate_from_topic(user_topic, preference, num_questions)`
- `generate_from_exam(exam_paper_path, max_questions, paper_mode)`
Located in `agents/retrieve_agent.py`. Inherits from `src/agents/base_agent.py`.
**Responsibilities:**
- Generate semantic search queries from requirements
- Execute RAG searches in parallel
- Merge and summarize retrieval results
```python
retrieve_agent = RetrieveAgent(kb_name="math2211", language="en")
result = await retrieve_agent.process(requirement, num_queries=3)
# Returns: {"queries": [...], "retrievals": [...], "summary": "...", "has_content": True}
```
### 2. GenerateAgent
Located in `agents/generate_agent.py`. Generates questions based on knowledge context.
**Responsibilities:**
- Generate custom questions from requirements + knowledge
- Generate mimic questions from reference + knowledge
- Output structured question JSON
```python
generate_agent = GenerateAgent(language="en")
result = await generate_agent.process(
requirement={"knowledge_point": "...", "difficulty": "medium"},
knowledge_context="...",
focus={"focus": "...", "type": "written"},
reference_question=None # or "reference text" for mimic mode
)
# Returns: {"success": True, "question": {...}}
```
### 3. RelevanceAnalyzer
Located in `agents/relevance_analyzer.py`. Replaces old validation workflow.
**Key difference from old ValidationWorkflow:**
- **NO rejection**: all questions are accepted
- **NO iteration**: single-pass analysis
- Output: relevance level (high/partial) with explanations
```python
analyzer = RelevanceAnalyzer(language="en")
result = await analyzer.process(question={"question": "..."}, knowledge_context="...")
# Returns: {"relevance": "high", "kb_coverage": "...", "extension_points": ""}
```
### 4. AgentCoordinator
Located in `coordinator.py`. Orchestrates the workflow using specialized agents.
**Methods:**
- `generate_question()`: Single question generation (used by Mimic mode)
- `generate_questions_custom()`: Batch generation from requirement
## Usage
### Custom Mode - Batch Generation
```python
import asyncio
from src.agents.question import AgentCoordinator
async def main():
coordinator = AgentCoordinator(
kb_name="math2211",
output_dir="data/user/question",
language="en"
)
result = await coordinator.generate_questions_custom(
requirement={
"knowledge_point": "Multivariable limits",
"difficulty": "medium",
"question_type": "choice"
},
num_questions=3
)
print(f"✅ Generated {result['completed']}/{result['requested']} questions")
for r in result['results']:
print(f"- [{r['analysis']['relevance']}] {r['question']['question'][:50]}...")
asyncio.run(main())
```
### Custom Mode - Single Question
```python
requirement = {
"knowledge_point": "Limits and continuity",
"difficulty": "medium",
"question_type": "choice"
}
result = await coordinator.generate_question(requirement)
if result["success"]:
print(f"Question: {result['question']['question']}")
print(f"Relevance: {result['validation']['relevance']}")
print(f"KB Coverage: {result['validation']['kb_coverage']}")
```
### Mimic Mode - PDF Upload
```python
from src.tools.question import mimic_exam_questions
result = await mimic_exam_questions(
pdf_path="exams/midterm.pdf",
kb_name="math2211",
output_dir="data/user/question/mimic_papers",
max_questions=5
)
print(f"✅ Generated {result['successful_generations']} questions")
```
### Mimic Mode - Parsed Directory
```python
result = await mimic_exam_questions(
paper_dir="data/parsed_exams/exam_20240101",
kb_name="math2211"
)
```
## Configuration
### `config/main.yaml`
## 5. 配置项(main.yaml)
```yaml
question:
# Refactored: no iteration loops (max_rounds removed)
rag_query_count: 3
max_parallel_questions: 1
rag_mode: naive
agents:
retrieve:
top_k: 30
generate:
max_retries: 2
relevance_analyzer:
enabled: true
idea_loop:
max_rounds: 3
ideas_per_round: 5
generation:
max_retries: 2
tools:
web_search: true
rag_tool: true
write_code: true
```
### `config/agents.yaml`
## 6. 命令行交互测试
```yaml
question:
temperature: 0.7
max_tokens: 4000
新增脚本:`src/agents/question/cli.py`
从项目根目录运行:
```bash
python src/agents/question/cli.py
```
## Return Format
支持:
### Single Question Result
- 交互式 Topic 模式测试
- 交互式 Mimic 模式测试(upload/parsed)
- 输出摘要(completed/failed)与题目预览
```python
{
"success": True,
"question": {
"question_type": "choice",
"question": "Question content",
"options": {"A": "...", "B": "...", "C": "...", "D": "..."},
"correct_answer": "A",
"explanation": "Detailed explanation",
"knowledge_point": "Topic name"
},
"validation": {
"decision": "approve", # Always approve
"relevance": "high", # or "partial"
"kb_coverage": "This question tests...",
"extension_points": "" # Only if relevance is "partial"
},
"rounds": 1 # Always 1 (no iteration)
}
```
## 7. 相关工具模块
### Batch Generation Result
工具位于 `src/tools/question/`:
```python
{
"success": True,
"requested": 3,
"completed": 3,
"failed": 0,
"search_queries": ["query1", "query2", "query3"],
"plan": {"focuses": [...]},
"results": [
{
"question_id": "q_1",
"focus": {"focus": "...", "type": "written"},
"question": {...},
"analysis": {"relevance": "high", "kb_coverage": "..."}
},
...
],
"failures": []
}
```
- `pdf_parser.py`
- `question_extractor.py`
- `exam_mimic.py`(薄封装,委托 coordinator)
## Output Files
## 8. 注意事项
### Custom Mode Directory Structure
```
data/user/question/batch_YYYYMMDD_HHMMSS/
├── knowledge.json # RAG queries and retrievals
├── plan.json # Question focuses
├── q_1/
│ ├── result.json # Question + analysis
│ └── question.md # Human-readable format
├── q_2/
│ ├── result.json
│ └── question.md
└── summary.json # Overall summary
```
### Mimic Mode Directory Structure
```
data/user/question/mimic_papers/{paper_name}/
├── auto/{paper_name}.md # MinerU parsed markdown
├── {paper_name}_YYYYMMDD_HHMMSS_questions.json # Extracted reference questions
└── {paper_name}_YYYYMMDD_HHMMSS_generated.json # Generated questions
```
## Key Changes from Previous Version
### ✅ Architecture Changes
1. **Unified BaseAgent**
- All agents now inherit from `src/agents/base_agent.py`
- Automatic LLM config, prompt loading, token tracking
- No more separate ReAct base class
2. **Specialized Agents**
- `RetrieveAgent`: Knowledge retrieval only
- `GenerateAgent`: Question generation only
- `RelevanceAnalyzer`: Relevance analysis only (replaces ValidationWorkflow)
3. **No Iteration/Rejection**
- Removed `max_rounds` from config
- Single-pass generation + analysis
- All questions accepted with relevance classification
4. **Tools Moved**
- `src/agents/question/tools/` → `src/tools/question/`
- Import via `from src.tools.question import ...`
### ❌ Removed
1. **Old ReAct Architecture**
- `agents/base_agent.py` (ReAct paradigm)
- `agents/generation_agent.py` (ReAct-based)
- `agents/validation_agent.py` (deprecated)
- `validation_workflow.py` (replaced by RelevanceAnalyzer)
2. **Iteration Logic**
- No more validation loops
- No more task rejection
- No more request_modification/request_regeneration
3. **Message Queue**
- Agent communication simplified
- Direct method calls instead of message passing
## Migration Notes
**Import Path Updates:**
```python
# Old
from src.agents.question import BaseAgent, QuestionGenerationAgent
from src.tools.question import mimic_exam_questions
# New
from src.agents.question import RetrieveAgent, GenerateAgent, RelevanceAnalyzer
from src.tools.question import mimic_exam_questions
```
**API Changes:**
```python
# Old - with rejection handling
result = await coordinator.generate_question(requirement)
if result.get("error") == "task_rejected":
print("Agent rejected task")
# New - always generates, check relevance
result = await coordinator.generate_question(requirement)
if result["success"]:
if result["validation"]["relevance"] == "high":
print("Fully covered by KB:", result["validation"]["kb_coverage"])
else:
print("Extension question:", result["validation"]["extension_points"])
```
- 旧版 `retrieve_agent / generate_agent / relevance_analyzer` 已移除
- 旧版 prompt 文件已移除
- 旧文档中的旧接口(如 `generate_questions_custom`)不再适用
+12 -9
View File
@@ -1,11 +1,10 @@
"""
Question Generation System
Modular question generation using specialized agents:
- RetrieveAgent: Knowledge base retrieval
- GenerateAgent: Question generation
- RelevanceAnalyzer: Question-KB relevance analysis
- AgentCoordinator: Workflow orchestration
Refactored dual-loop architecture:
- Idea loop: IdeaAgent <-> Evaluator
- Generation loop: Generator <-> Validator
- AgentCoordinator: End-to-end orchestration for topic and exam paths
Tools (moved to src/tools/question):
- parse_pdf_with_mineru
@@ -13,12 +12,16 @@ Tools (moved to src/tools/question):
- mimic_exam_questions
"""
from .agents import GenerateAgent, RelevanceAnalyzer, RetrieveAgent
from .agents import Evaluator, Generator, IdeaAgent, Validator
from .coordinator import AgentCoordinator
from .models import QAPair, QuestionTemplate
__all__ = [
"RetrieveAgent",
"GenerateAgent",
"RelevanceAnalyzer",
"IdeaAgent",
"Evaluator",
"Generator",
"Validator",
"QuestionTemplate",
"QAPair",
"AgentCoordinator",
]
+12 -9
View File
@@ -2,17 +2,20 @@
Question Generation Agents
Specialized agents for question generation workflow:
- RetrieveAgent: Knowledge retrieval from KB
- GenerateAgent: Question generation
- RelevanceAnalyzer: Question-KB relevance analysis
- IdeaAgent: Topic-driven idea generation
- Evaluator: Idea scoring and top-k selection
- Generator: Q-A generation with tools
- Validator: Approval/reject loop with feedback
"""
from .generate_agent import GenerateAgent
from .relevance_analyzer import RelevanceAnalyzer
from .retrieve_agent import RetrieveAgent
from .evaluator import Evaluator
from .generator import Generator
from .idea_agent import IdeaAgent
from .validator import Validator
__all__ = [
"RetrieveAgent",
"GenerateAgent",
"RelevanceAnalyzer",
"IdeaAgent",
"Evaluator",
"Generator",
"Validator",
]
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Evaluator - Score idea candidates and select top-k templates.
"""
from __future__ import annotations
import json
from typing import Any
from src.agents.base_agent import BaseAgent
from src.agents.question.models import QuestionTemplate
class Evaluator(BaseAgent):
"""
Evaluate idea quality/diversity and decide whether to continue idea loop.
"""
def __init__(self, language: str = "en", **kwargs: Any) -> None:
super().__init__(
module_name="question",
agent_name="evaluator",
language=language,
**kwargs,
)
async def process(
self,
user_topic: str,
preference: str,
ideas: list[dict[str, Any]],
top_k: int,
current_round: int,
max_rounds: int,
target_difficulty: str = "",
target_question_type: str = "",
) -> dict[str, Any]:
"""
Return either feedback (continue) or selected templates (stop).
"""
system_prompt = self.get_prompt("system", "")
evaluate_prompt = self.get_prompt("evaluate_ideas", "")
if not evaluate_prompt:
evaluate_prompt = (
"Topic: {user_topic}\n"
"Preference: {preference}\n"
"Round: {current_round}/{max_rounds}\n"
"Ideas:\n{ideas_json}\n\n"
'Return JSON {"continue_loop": bool, "feedback": "...", "selected_ideas":[...]}'
)
constraints: list[str] = []
if target_difficulty:
constraints.append(f"Target difficulty: {target_difficulty}")
if target_question_type:
constraints.append(f"Target question type: {target_question_type}")
effective_preference = preference or "(none)"
if constraints:
effective_preference = f"{effective_preference}\n" + "\n".join(constraints)
user_prompt = evaluate_prompt.format(
user_topic=user_topic,
preference=effective_preference,
current_round=current_round,
max_rounds=max_rounds,
top_k=top_k,
ideas_json=json.dumps(ideas, ensure_ascii=False, indent=2),
)
parsed = await self._evaluate_with_llm(
user_prompt=user_prompt,
system_prompt=system_prompt or "",
ideas=ideas,
top_k=top_k,
)
continue_loop = bool(parsed.get("continue_loop", False))
if current_round >= max_rounds:
continue_loop = False
selected_ideas = parsed.get("selected_ideas", [])
if not isinstance(selected_ideas, list):
selected_ideas = []
# Ensure selected ideas exist
if not selected_ideas:
selected_ideas = self._fallback_select(ideas=ideas, top_k=top_k)
templates = self._ideas_to_templates(selected_ideas, top_k=top_k)
return {
"continue_loop": continue_loop,
"feedback": str(parsed.get("feedback", "")).strip(),
"templates": templates,
"selected_ideas": selected_ideas[:top_k],
"scores": parsed.get("scores", []),
}
async def _evaluate_with_llm(
self,
user_prompt: str,
system_prompt: str,
ideas: list[dict[str, Any]],
top_k: int,
) -> dict[str, Any]:
try:
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
temperature=0.2,
stage="evaluate_idea_candidates",
)
payload = json.loads(response)
if isinstance(payload, dict):
return payload
except Exception as exc:
self.logger.warning(f"Evaluator parse failed, fallback used: {exc}")
return {
"continue_loop": False,
"feedback": "",
"selected_ideas": self._fallback_select(ideas=ideas, top_k=top_k),
"scores": [],
}
def _fallback_select(self, ideas: list[dict[str, Any]], top_k: int) -> list[dict[str, Any]]:
valid = [idea for idea in ideas if isinstance(idea, dict) and idea.get("concentration")]
return valid[:top_k]
def _ideas_to_templates(
self,
selected_ideas: list[dict[str, Any]],
top_k: int,
) -> list[QuestionTemplate]:
templates: list[QuestionTemplate] = []
for idx, item in enumerate(selected_ideas[:top_k], 1):
if not isinstance(item, dict):
continue
concentration = str(item.get("concentration", "")).strip()
if not concentration:
continue
templates.append(
QuestionTemplate(
question_id=f"q_{idx}",
concentration=concentration,
question_type=str(item.get("question_type", "written")).strip() or "written",
difficulty=str(item.get("difficulty", "medium")).strip() or "medium",
source="custom",
metadata={
"idea_id": item.get("idea_id", f"idea_{idx}"),
"rationale": item.get("rationale", ""),
},
)
)
# Ensure enough templates for downstream generation
if len(templates) < top_k:
for idx in range(len(templates) + 1, top_k + 1):
templates.append(
QuestionTemplate(
question_id=f"q_{idx}",
concentration=f"Aspect {idx}",
question_type="written",
difficulty="medium",
source="custom",
)
)
return templates
@@ -1,403 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
GenerateAgent - Responsible for generating questions based on knowledge context.
Uses unified BaseAgent for LLM calls and configuration management.
"""
import json
import re
from typing import Any
from src.agents.base_agent import BaseAgent
class GenerateAgent(BaseAgent):
"""
Agent responsible for generating questions from knowledge context.
Responsibilities:
- Generate questions based on requirements and knowledge
- Support both custom mode (from scratch) and mimic mode (from reference)
- Output structured question JSON
"""
def __init__(
self,
language: str = "en",
**kwargs,
):
"""
Initialize GenerateAgent.
Args:
language: Language for prompts ("en" or "zh")
**kwargs: Additional arguments passed to BaseAgent
"""
super().__init__(
module_name="question",
agent_name="generate_agent",
language=language,
**kwargs,
)
async def process(
self,
requirement: dict[str, Any],
knowledge_context: str,
focus: dict[str, Any] | None = None,
reference_question: str | None = None,
) -> dict[str, Any]:
"""
Main processing: generate a question.
Args:
requirement: Question requirement dict (knowledge_point, difficulty, question_type, etc.)
knowledge_context: Retrieved knowledge summary
focus: Optional focus/angle for the question
reference_question: Optional reference question for mimic mode
Returns:
Dict with:
- success: Whether generation succeeded
- question: Generated question dict (if success)
- error: Error message (if failed)
"""
self.logger.info("Starting question generation")
# Build requirements string
requirements_str = json.dumps(requirement, ensure_ascii=False, indent=2)
# Build focus string
if focus:
focus_str = f"Focus: {focus.get('focus', '')}\nType: {focus.get('type', requirement.get('question_type', 'written'))}"
else:
focus_str = f"Type: {requirement.get('question_type', 'written')}"
# Choose prompt based on mode
if reference_question:
# Mimic mode
return await self._generate_with_reference(
requirements_str=requirements_str,
knowledge_context=knowledge_context,
reference_question=reference_question,
)
else:
# Custom mode
return await self._generate_custom(
requirements_str=requirements_str,
knowledge_context=knowledge_context,
focus_str=focus_str,
knowledge_point=requirement.get("knowledge_point", ""),
)
def _get_user_preference(self) -> str:
"""Get user preference from personalization service."""
try:
from src.personalization.service import get_personalization_service
service = get_personalization_service()
preference = service.get_preference_for_prompt()
return preference if preference else "(No user preference recorded)"
except Exception as e:
self.logger.debug(f"Failed to get user preference: {e}")
return "(No user preference recorded)"
async def _generate_custom(
self,
requirements_str: str,
knowledge_context: str,
focus_str: str,
knowledge_point: str,
) -> dict[str, Any]:
"""
Generate a custom question (not based on reference).
Args:
requirements_str: JSON string of requirements
knowledge_context: Retrieved knowledge summary
focus_str: Focus/angle description
knowledge_point: Main knowledge point
Returns:
Dict with success status and question/error
"""
system_prompt = self.get_prompt("system", "")
user_prompt_template = self.get_prompt("generate", "")
if not user_prompt_template:
# Fallback prompt
user_prompt_template = (
"Generate a question based on:\n"
"User Preference: {preference}\n"
"Requirements: {requirements}\n"
"Focus: {focus}\n"
"Knowledge: {knowledge}\n\n"
"Return JSON with question_type, question, correct_answer, explanation."
)
# Get user preference
preference = self._get_user_preference()
user_prompt = user_prompt_template.format(
preference=preference,
requirements=requirements_str,
focus=focus_str,
knowledge=knowledge_context[:4000]
if len(knowledge_context) > 4000
else knowledge_context,
)
try:
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
stage="generate_question",
)
question = self._parse_question_response(response)
question["knowledge_point"] = knowledge_point
self.logger.info(f"Generated {question.get('question_type', 'unknown')} question")
return {
"success": True,
"question": question,
}
except Exception as e:
self.logger.error(f"Question generation failed: {e}")
return {
"success": False,
"error": str(e),
}
async def _generate_with_reference(
self,
requirements_str: str,
knowledge_context: str,
reference_question: str,
) -> dict[str, Any]:
"""
Generate a question based on a reference (mimic mode).
Args:
requirements_str: JSON string of requirements
knowledge_context: Retrieved knowledge summary
reference_question: Reference question text
Returns:
Dict with success status and question/error
"""
system_prompt = self.get_prompt("system", "")
user_prompt_template = self.get_prompt("generate_with_reference", "")
if not user_prompt_template:
# Fallback prompt
user_prompt_template = (
"Generate a new question inspired by the reference but distinct:\n"
"User Preference: {preference}\n"
"Reference: {reference_question}\n"
"Requirements: {requirements}\n"
"Knowledge: {knowledge}\n\n"
"Return JSON with question_type, question, correct_answer, explanation."
)
# Get user preference
preference = self._get_user_preference()
user_prompt = user_prompt_template.format(
preference=preference,
reference_question=reference_question,
requirements=requirements_str,
knowledge=knowledge_context[:4000]
if len(knowledge_context) > 4000
else knowledge_context,
)
try:
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
stage="generate_with_reference",
)
question = self._parse_question_response(response)
self.logger.info(f"Generated mimic {question.get('question_type', 'unknown')} question")
return {
"success": True,
"question": question,
}
except Exception as e:
self.logger.error(f"Reference-based generation failed: {e}")
return {
"success": False,
"error": str(e),
}
def _parse_question_response(self, response: str) -> dict[str, Any]:
"""
Parse LLM response into question dict.
Uses robust JSON extraction that handles:
- Markdown code blocks
- Control characters in LaTeX formulas
- Python triple-quoted strings
- Partial JSON extraction
Args:
response: LLM response string
Returns:
Parsed question dict
Raises:
ValueError: If parsing fails
"""
if not response or not response.strip():
raise ValueError("LLM returned empty response")
# Try to extract JSON from markdown code blocks if present
json_content = self._extract_json_from_markdown(response)
# Clean control characters that may break JSON parsing
json_content = self._clean_json_string(json_content)
# Try multiple parsing strategies
question = None
parse_error = None
# Strategy 1: Direct parse
try:
question = json.loads(json_content)
except json.JSONDecodeError as e:
parse_error = e
# Strategy 2: Try extracting JSON object pattern
if question is None:
json_obj_pattern = re.compile(r"\{[\s\S]*\}")
match = json_obj_pattern.search(json_content)
if match:
try:
question = json.loads(match.group(0))
except json.JSONDecodeError:
pass
# Strategy 3: Try fixing common LLM JSON issues
if question is None:
try:
fixed_content = self._fix_common_json_issues(json_content)
question = json.loads(fixed_content)
except json.JSONDecodeError:
pass
if question is None:
raise ValueError(f"Failed to parse question JSON: {parse_error}") from parse_error
# Validate required fields
if "question" not in question:
raise ValueError("Question response missing 'question' field")
# Ensure question_type exists
if "question_type" not in question:
question["question_type"] = "written"
# Validate options for choice questions
if question.get("question_type") == "choice":
options = question.get("options")
if not options:
# Create default options if missing
self.logger.warning("Choice question missing options, adding placeholder")
question["options"] = {
"A": "Option A (placeholder)",
"B": "Option B (placeholder)",
"C": "Option C (placeholder)",
"D": "Option D (placeholder)",
}
elif not isinstance(options, dict):
# Convert to dict if it's a list or other format
self.logger.warning(f"Options is not a dict: {type(options)}, converting")
if isinstance(options, list):
question["options"] = {
chr(65 + i): str(opt) for i, opt in enumerate(options[:4])
}
else:
question["options"] = {"A": str(options)}
elif len(options) < 2:
self.logger.warning(f"Choice question has only {len(options)} options")
return question
def _clean_json_string(self, json_str: str) -> str:
"""
Clean JSON string by removing/escaping problematic characters.
Handles:
- Control characters (0x00-0x1f except tab, newline, carriage return)
- Unescaped newlines inside string values
"""
if not json_str:
return json_str
# Remove most control characters but keep \t, \n, \r
# These can appear in LLM output and break JSON parsing
cleaned = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", json_str)
return cleaned
def _fix_common_json_issues(self, content: str) -> str:
"""
Attempt to fix common JSON issues from LLM output.
Fixes:
- Python triple-quoted strings converted to JSON strings
- Trailing commas before closing braces/brackets
"""
if not content:
return content
# Fix Python triple-quoted strings (LLMs sometimes generate these)
def replace_triple_quotes(match: re.Match) -> str:
inner = match.group(1)
# Use json.dumps to properly escape the content
return json.dumps(inner)
content = re.sub(r'"""([\s\S]*?)"""', replace_triple_quotes, content)
# Remove trailing commas before } or ]
content = re.sub(r",\s*([}\]])", r"\1", content)
return content
def _extract_json_from_markdown(self, content: str) -> str:
"""
Extract JSON from markdown code blocks.
LLMs often wrap JSON in ```json ... ``` blocks. This method strips
the markdown formatting and any surrounding text.
Args:
content: Raw LLM response
Returns:
Extracted JSON string
"""
if not content:
return content
# Try to find JSON code block
json_block_pattern = r"```(?:json)?\s*\n?(.*?)```"
matches = re.findall(json_block_pattern, content, re.DOTALL)
if matches:
# Return the content inside the first code block
return matches[0].strip()
# If no code blocks found, return as-is (might already be valid JSON)
return content.strip()
+345
View File
@@ -0,0 +1,345 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Generator - Generate Q-A pairs from QuestionTemplate with dynamic tool selection.
The Generator uses a two-step process:
1. Plan which tools to use (LLM-driven decision)
2. Execute only the planned tools and generate the Q-A pair
"""
from __future__ import annotations
import asyncio
import json
import re
from typing import Any
from src.agents.base_agent import BaseAgent
from src.agents.question.models import QAPair, QuestionTemplate
from src.tools.code_executor import run_code
from src.tools.rag_tool import rag_search
from src.tools.web_search import web_search
class Generator(BaseAgent):
"""
Generate a question/answer pair with LLM-driven tool selection.
Instead of always calling all tools, the Generator first asks the LLM
which tools would be helpful for the given template, then only executes
those tools before generating the final Q-A pair.
"""
def __init__(
self,
kb_name: str | None = None,
rag_mode: str = "naive",
language: str = "en",
tool_flags: dict[str, bool] | None = None,
**kwargs: Any,
) -> None:
super().__init__(
module_name="question",
agent_name="generator",
language=language,
**kwargs,
)
self.kb_name = kb_name
self.rag_mode = rag_mode
self.tool_flags = tool_flags or {}
async def process(
self,
template: QuestionTemplate,
user_topic: str = "",
preference: str = "",
validator_feedback: str = "",
) -> QAPair:
"""
Generate one Q-A pair from a template.
Flow:
1. Ask LLM which tools to use (plan_tools)
2. Execute only the planned tools
3. Generate the Q-A pair with tool context
4. Optionally run verification code if the plan included write_code
"""
# Step 1: Plan tools
tool_plan = await self._plan_tools(template, user_topic, preference)
# Step 2: Execute planned tools
tool_context = await self._execute_tools(template, user_topic, tool_plan)
# Step 3: Generate Q-A pair
payload = await self._generate_payload(
template=template,
user_topic=user_topic,
preference=preference,
validator_feedback=validator_feedback,
tool_context=tool_context,
)
# Step 4: Optionally verify with code (only if planned)
code_result: dict[str, Any] = {}
if tool_plan.get("use_code") and payload.get("verification_code"):
code_result = await self._execute_verification_code(
payload["verification_code"]
)
return QAPair(
question_id=template.question_id,
question=payload.get("question", ""),
correct_answer=payload.get("correct_answer", ""),
explanation=payload.get("explanation", ""),
question_type=payload.get("question_type", template.question_type),
options=(
payload.get("options")
if isinstance(payload.get("options"), dict)
else None
),
concentration=template.concentration,
difficulty=template.difficulty,
metadata={
"source": template.source,
"reference_question": template.reference_question,
"tool_plan": tool_plan,
"tool_context_keys": [k for k, v in tool_context.items() if v],
"code_result": code_result,
"verification_code": payload.get("verification_code", ""),
"validator_feedback": validator_feedback,
},
)
# ------------------------------------------------------------------
# Step 1: Tool Planning
# ------------------------------------------------------------------
async def _plan_tools(
self,
template: QuestionTemplate,
user_topic: str,
preference: str,
) -> dict[str, Any]:
"""Ask LLM which tools to use for this specific template."""
plan_prompt_template = self.get_prompt("plan_tools", "")
if not plan_prompt_template:
# No prompt available — fall back to conservative defaults
return self._default_tool_plan()
try:
prompt = plan_prompt_template.format(
template=json.dumps(template.__dict__, ensure_ascii=False, indent=2),
user_topic=user_topic,
preference=preference or "(none)",
available_tools=self._describe_available_tools(),
)
response = await self.call_llm(
user_prompt=prompt,
system_prompt=self.get_prompt("system", "") or "",
response_format={"type": "json_object"},
stage="generator_plan_tools",
)
plan = self._parse_json_like(response)
# Respect config-level tool flags (config can disable tools globally)
plan["use_rag"] = bool(plan.get("use_rag", True)) and self.tool_flags.get(
"rag_tool", True
)
plan["use_web"] = bool(
plan.get("use_web", False)
) and self.tool_flags.get("web_search", True)
plan["use_code"] = bool(
plan.get("use_code", False)
) and self.tool_flags.get("write_code", True)
return plan
except Exception as exc:
self.logger.warning(f"Tool planning failed, using defaults: {exc}")
return self._default_tool_plan()
def _default_tool_plan(self) -> dict[str, Any]:
"""Conservative default: only RAG if available."""
return {
"use_rag": self.tool_flags.get("rag_tool", True),
"use_web": False,
"use_code": False,
"reasoning": "default plan (no LLM planning)",
}
def _describe_available_tools(self) -> str:
tools: list[str] = []
if self.tool_flags.get("rag_tool", True):
tools.append(
"rag_tool: Retrieve relevant knowledge from the course knowledge base. "
"Useful for factual, conceptual, and curriculum-aligned questions."
)
if self.tool_flags.get("web_search", True):
tools.append(
"web_search: Search the web for up-to-date or supplementary information. "
"Useful when the topic requires current data, real-world examples, or goes beyond the KB."
)
if self.tool_flags.get("write_code", True):
tools.append(
"write_code: Execute Python code to compute or verify answers. "
"Useful for coding questions, mathematical computations, and algorithm verification."
)
return "\n".join(f"- {t}" for t in tools) or "(no tools available)"
# ------------------------------------------------------------------
# Step 2: Execute Tools
# ------------------------------------------------------------------
async def _execute_tools(
self,
template: QuestionTemplate,
user_topic: str,
tool_plan: dict[str, Any],
) -> dict[str, str]:
"""Execute only the tools chosen by the tool plan."""
context: dict[str, str] = {}
if tool_plan.get("use_rag"):
try:
query = (
tool_plan.get("rag_query")
or template.concentration
or user_topic
)
rag_result = await rag_search(
query=query,
kb_name=self.kb_name,
mode=self.rag_mode,
only_need_context=True,
)
context["rag"] = (rag_result.get("answer", "") or "")[:4000]
except Exception as exc:
self.logger.warning(f"RAG tool failed: {exc}")
if tool_plan.get("use_web"):
try:
query = (
tool_plan.get("web_query")
or template.concentration
or user_topic
)
# web_search is synchronous — run in thread to avoid blocking
web_result = await asyncio.to_thread(web_search, query=query)
context["web"] = (web_result.get("answer", "") or "")[:2000]
except Exception as exc:
self.logger.warning(f"Web search tool failed: {exc}")
return context
# ------------------------------------------------------------------
# Step 3: Generate Q-A Pair
# ------------------------------------------------------------------
async def _generate_payload(
self,
template: QuestionTemplate,
user_topic: str,
preference: str,
validator_feedback: str,
tool_context: dict[str, str],
) -> dict[str, Any]:
system_prompt = self.get_prompt("system", "")
user_prompt_template = self.get_prompt("generate", "")
if not user_prompt_template:
user_prompt_template = (
"Template: {template}\n"
"User topic: {user_topic}\n"
"Preference: {preference}\n"
"Validator feedback: {validator_feedback}\n"
"Tool context: {tool_context}\n\n"
'Return JSON {{"question_type":"","question":"","options":{{}},"correct_answer":"","explanation":"","verification_code":""}}'
)
# Build a concise tool context description
tool_summary = {}
if tool_context.get("rag"):
tool_summary["rag_knowledge"] = tool_context["rag"]
if tool_context.get("web"):
tool_summary["web_results"] = tool_context["web"]
if not tool_summary:
tool_summary["note"] = "No external tool context was used for this question."
user_prompt = user_prompt_template.format(
template=json.dumps(template.__dict__, ensure_ascii=False, indent=2),
user_topic=user_topic,
preference=preference or "(none)",
validator_feedback=validator_feedback or "(none)",
tool_context=json.dumps(tool_summary, ensure_ascii=False, indent=2),
)
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt or "",
response_format={"type": "json_object"},
stage="generator_build_qa",
)
payload = self._parse_json_like(response)
if "question" not in payload or not str(payload.get("question", "")).strip():
payload["question"] = (
f"Based on {template.concentration}, answer this {template.difficulty} "
f"{template.question_type} question."
)
if "correct_answer" not in payload:
payload["correct_answer"] = "N/A"
if "explanation" not in payload:
payload["explanation"] = "N/A"
if "question_type" not in payload:
payload["question_type"] = template.question_type
return payload
# ------------------------------------------------------------------
# Step 4: Optional Code Verification
# ------------------------------------------------------------------
async def _execute_verification_code(self, code: str) -> dict[str, Any]:
if not code or not isinstance(code, str):
return {}
try:
result = await run_code(language="python", code=code, timeout=10)
return {
"stdout": (result.get("stdout", "") or "")[:800],
"stderr": (result.get("stderr", "") or "")[:800],
"exit_code": result.get("exit_code", -1),
}
except Exception as exc:
self.logger.warning(f"write_code tool failed: {exc}")
return {"stderr": str(exc), "exit_code": -1}
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
@staticmethod
def _parse_json_like(content: str) -> dict[str, Any]:
if not content or not content.strip():
return {}
cleaned = re.sub(
r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", content.strip()
)
block_match = re.search(r"```(?:json)?\s*(.*?)```", cleaned, re.DOTALL)
if block_match:
cleaned = block_match.group(1).strip()
try:
payload = json.loads(cleaned)
return payload if isinstance(payload, dict) else {}
except Exception:
pass
obj_match = re.search(r"\{[\s\S]*\}", cleaned)
if obj_match:
try:
payload = json.loads(obj_match.group(0))
return payload if isinstance(payload, dict) else {}
except Exception:
return {}
return {}
+217
View File
@@ -0,0 +1,217 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
IdeaAgent - Generate candidate question directions from topic and preference.
"""
from __future__ import annotations
import json
from typing import Any
from src.agents.base_agent import BaseAgent
from src.tools.rag_tool import rag_search
class IdeaAgent(BaseAgent):
"""
Generate candidate question ideas with knowledge grounding.
"""
def __init__(
self,
kb_name: str | None = None,
rag_mode: str = "naive",
language: str = "en",
**kwargs: Any,
) -> None:
super().__init__(
module_name="question",
agent_name="idea_agent",
language=language,
**kwargs,
)
self.kb_name = kb_name
self.rag_mode = rag_mode
async def process(
self,
user_topic: str,
preference: str = "",
evaluator_feedback: str = "",
num_ideas: int = 5,
target_difficulty: str = "",
target_question_type: str = "",
) -> dict[str, Any]:
"""
Build grounded candidate ideas for evaluator ranking.
"""
queries = await self._generate_rag_queries(user_topic=user_topic, num_queries=3)
retrievals = await self._retrieve_context(queries)
knowledge_context = self._build_context(retrievals)
ideas = await self._generate_ideas(
user_topic=user_topic,
preference=preference,
evaluator_feedback=evaluator_feedback,
knowledge_context=knowledge_context,
num_ideas=num_ideas,
target_difficulty=target_difficulty,
target_question_type=target_question_type,
)
return {
"ideas": ideas,
"queries": queries,
"retrievals": retrievals,
"knowledge_context": knowledge_context,
}
async def _generate_rag_queries(self, user_topic: str, num_queries: int) -> list[str]:
system_prompt = self.get_prompt("system", "")
query_prompt = self.get_prompt("generate_queries", "")
if not query_prompt:
query_prompt = (
"Generate {num_queries} concise knowledge search queries for topic:\n"
"{user_topic}\n"
'Return JSON: {"queries":["..."]}'
)
user_prompt = query_prompt.format(
user_topic=user_topic,
num_queries=num_queries,
)
try:
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt or "",
response_format={"type": "json_object"},
stage="idea_generate_queries",
)
payload = json.loads(response)
queries = payload.get("queries", [])
if not isinstance(queries, list):
queries = []
clean = [q.strip() for q in queries if isinstance(q, str) and q.strip()]
return clean[:num_queries] or [user_topic]
except Exception as exc:
self.logger.warning(f"Failed generating queries, fallback to topic: {exc}")
return [user_topic]
async def _retrieve_context(self, queries: list[str]) -> list[dict[str, Any]]:
retrievals: list[dict[str, Any]] = []
for query in queries:
try:
result = await rag_search(
query=query,
kb_name=self.kb_name,
mode=self.rag_mode,
only_need_context=True,
)
retrievals.append(
{
"query": query,
"answer": result.get("answer", ""),
"mode": result.get("mode", self.rag_mode),
}
)
except Exception as exc:
self.logger.warning(f"RAG retrieval failed for query '{query}': {exc}")
retrievals.append({"query": query, "answer": "", "error": str(exc)})
return retrievals
def _build_context(self, retrievals: list[dict[str, Any]]) -> str:
sections: list[str] = []
for item in retrievals:
answer = item.get("answer", "")
if not answer:
continue
clipped = answer[:2000] + ("...[truncated]" if len(answer) > 2000 else "")
sections.append(f"=== Query: {item.get('query','')} ===\n{clipped}")
return "\n\n".join(sections) if sections else "No retrieval context available."
async def _generate_ideas(
self,
user_topic: str,
preference: str,
evaluator_feedback: str,
knowledge_context: str,
num_ideas: int,
target_difficulty: str = "",
target_question_type: str = "",
) -> list[dict[str, Any]]:
system_prompt = self.get_prompt("system", "")
idea_prompt = self.get_prompt("generate_ideas", "")
if not idea_prompt:
idea_prompt = (
"Topic: {user_topic}\n"
"Preference: {preference}\n"
"Evaluator feedback: {evaluator_feedback}\n"
"Knowledge context:\n{knowledge_context}\n\n"
"Generate {num_ideas} candidate question ideas.\n"
'Return JSON {"ideas":[{"concentration":"","question_type":"","difficulty":"","rationale":""}]}'
)
constraints: list[str] = []
if target_difficulty:
constraints.append(f"Target difficulty: {target_difficulty}")
if target_question_type:
constraints.append(f"Target question type: {target_question_type}")
effective_preference = preference or "(none)"
if constraints:
effective_preference = f"{effective_preference}\n" + "\n".join(constraints)
user_prompt = idea_prompt.format(
user_topic=user_topic,
preference=effective_preference,
evaluator_feedback=evaluator_feedback or "(none)",
knowledge_context=knowledge_context[:6000],
num_ideas=num_ideas,
)
try:
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt or "",
response_format={"type": "json_object"},
stage="idea_generate_candidates",
)
payload = json.loads(response)
ideas_raw = payload.get("ideas", [])
if not isinstance(ideas_raw, list):
ideas_raw = []
except Exception as exc:
self.logger.warning(f"Idea generation failed, fallback used: {exc}")
ideas_raw = []
ideas: list[dict[str, Any]] = []
for idx, item in enumerate(ideas_raw, 1):
if not isinstance(item, dict):
continue
concentration = str(item.get("concentration", "")).strip()
if not concentration:
continue
ideas.append(
{
"idea_id": item.get("idea_id", f"idea_{idx}"),
"concentration": concentration,
"question_type": str(item.get("question_type", "written")).strip()
or "written",
"difficulty": str(item.get("difficulty", "medium")).strip() or "medium",
"rationale": str(item.get("rationale", "")).strip(),
}
)
if len(ideas) >= num_ideas:
break
if len(ideas) < num_ideas:
for idx in range(len(ideas) + 1, num_ideas + 1):
ideas.append(
{
"idea_id": f"idea_{idx}",
"concentration": f"{user_topic} - aspect {idx}",
"question_type": "written",
"difficulty": "medium",
"rationale": "Fallback idea generated due to parsing issues.",
}
)
return ideas
@@ -1,207 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
RelevanceAnalyzer - Analyzes the relevance between questions and knowledge base.
Replaces the old validation workflow with a single-pass relevance analysis.
No iterative validation or rejection - all questions are accepted and analyzed.
"""
import json
import re
from typing import Any
from src.agents.base_agent import BaseAgent
class RelevanceAnalyzer(BaseAgent):
"""
Agent responsible for analyzing question-knowledge relevance.
Key difference from old ValidationWorkflow:
- NO rejection: all questions are accepted
- NO iteration: single-pass analysis
- Output: relevance level (high/partial) with explanations
Responsibilities:
- Analyze how well a question aligns with knowledge base content
- Identify what KB concepts the question tests
- Identify any extensions beyond the KB (for "partial" relevance)
"""
def __init__(
self,
language: str = "en",
**kwargs,
):
"""
Initialize RelevanceAnalyzer.
Args:
language: Language for prompts ("en" or "zh")
**kwargs: Additional arguments passed to BaseAgent
"""
super().__init__(
module_name="question",
agent_name="relevance_analyzer",
language=language,
**kwargs,
)
async def process(
self,
question: dict[str, Any],
knowledge_context: str,
) -> dict[str, Any]:
"""
Main processing: analyze relevance between question and knowledge.
Args:
question: Generated question dict
knowledge_context: Retrieved knowledge summary
Returns:
Dict with:
- relevance: "high" or "partial"
- kb_coverage: Description of KB content tested
- extension_points: Description of extensions (only if partial)
"""
self.logger.info("Starting relevance analysis")
# Format question for analysis
question_str = json.dumps(question, ensure_ascii=False, indent=2)
# Truncate context if too long
if len(knowledge_context) > 4000:
knowledge_context = knowledge_context[:4000] + "...[truncated]"
# Get prompts
system_prompt = self.get_prompt("system", "")
user_prompt_template = self.get_prompt("analyze_relevance", "")
if not user_prompt_template:
# Fallback prompt
user_prompt_template = (
"Analyze the relevance between this question and knowledge base:\n\n"
"Question:\n{question}\n\n"
"Knowledge Base:\n{knowledge}\n\n"
"Return JSON with: relevance (high/partial), kb_coverage, extension_points"
)
user_prompt = user_prompt_template.format(
question=question_str,
knowledge=knowledge_context,
)
try:
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
temperature=0.3, # Lower temperature for more consistent analysis
stage="analyze_relevance",
)
result = self._parse_analysis_response(response)
self.logger.info(f"Relevance analysis completed: {result['relevance']}")
return result
except Exception as e:
self.logger.warning(f"Relevance analysis failed: {e}")
# Return default "partial" on failure
return {
"relevance": "partial",
"kb_coverage": "Unable to analyze knowledge base coverage",
"extension_points": f"Analysis could not be completed: {e}",
}
def _parse_analysis_response(self, response: str) -> dict[str, Any]:
"""
Parse LLM response into analysis result.
Uses robust JSON extraction that handles control characters
and common LLM output issues.
Args:
response: LLM response string
Returns:
Parsed analysis dict with normalized relevance value
"""
if not response or not response.strip():
raise ValueError("LLM returned empty response")
# Try to extract JSON from markdown code blocks if present
json_content = self._extract_json_from_markdown(response)
# Clean control characters
json_content = self._clean_json_string(json_content)
# Try multiple parsing strategies
result = None
parse_error = None
# Strategy 1: Direct parse
try:
result = json.loads(json_content)
except json.JSONDecodeError as e:
parse_error = e
# Strategy 2: Extract JSON object pattern
if result is None:
json_obj_pattern = re.compile(r"\{[\s\S]*\}")
match = json_obj_pattern.search(json_content)
if match:
try:
result = json.loads(match.group(0))
except json.JSONDecodeError:
pass
if result is None:
raise ValueError(f"Failed to parse analysis JSON: {parse_error}") from parse_error
# Normalize relevance value
relevance = result.get("relevance", "partial")
if relevance not in ["high", "partial"]:
relevance = "partial"
return {
"relevance": relevance,
"kb_coverage": result.get("kb_coverage", ""),
"extension_points": result.get("extension_points", "")
if relevance == "partial"
else "",
}
def _clean_json_string(self, json_str: str) -> str:
"""
Clean JSON string by removing problematic control characters.
"""
if not json_str:
return json_str
# Remove control characters except tab, newline, carriage return
return re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", json_str)
def _extract_json_from_markdown(self, content: str) -> str:
"""
Extract JSON from markdown code blocks.
Args:
content: Raw LLM response
Returns:
Extracted JSON string
"""
if not content:
return content
# Try to find JSON code block
json_block_pattern = r"```(?:json)?\s*\n?(.*?)```"
matches = re.findall(json_block_pattern, content, re.DOTALL)
if matches:
return matches[0].strip()
return content.strip()
@@ -1,239 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
RetrieveAgent - Responsible for generating RAG queries and retrieving knowledge.
Uses unified BaseAgent for LLM calls and configuration management.
"""
import asyncio
import json
from typing import Any
from src.agents.base_agent import BaseAgent
from src.tools.rag_tool import rag_search
class RetrieveAgent(BaseAgent):
"""
Agent responsible for knowledge retrieval from the knowledge base.
Responsibilities:
- Generate semantic search queries from requirements
- Execute RAG searches in parallel
- Merge and summarize retrieval results
"""
def __init__(
self,
kb_name: str | None = None,
rag_mode: str = "naive",
language: str = "en",
**kwargs,
):
"""
Initialize RetrieveAgent.
Args:
kb_name: Knowledge base name to search
rag_mode: RAG search mode ("naive" or "hybrid")
language: Language for prompts ("en" or "zh")
**kwargs: Additional arguments passed to BaseAgent
"""
super().__init__(
module_name="question",
agent_name="retrieve_agent",
language=language,
**kwargs,
)
self.kb_name = kb_name
self.rag_mode = rag_mode
async def process(
self,
requirement: dict[str, Any] | str,
num_queries: int = 3,
) -> dict[str, Any]:
"""
Main processing: generate queries and retrieve knowledge.
Args:
requirement: Question requirement (dict or string)
num_queries: Number of RAG queries to generate
Returns:
Dict with:
- queries: List of generated queries
- retrievals: List of retrieval results
- summary: Merged knowledge summary
"""
self.logger.info("Starting knowledge retrieval")
# Convert requirement to text
if isinstance(requirement, dict):
requirement_text = json.dumps(requirement, ensure_ascii=False, indent=2)
else:
requirement_text = str(requirement)
# Step 1: Generate search queries
queries = await self._generate_queries(requirement_text, num_queries)
self.logger.info(f"Generated {len(queries)} search queries")
# Step 2: Execute RAG searches in parallel
retrievals = await self._execute_searches(queries)
self.logger.info(f"Retrieved {len(retrievals)} results")
# Step 3: Summarize results
summary = self._summarize_retrievals(retrievals)
return {
"queries": queries,
"retrievals": retrievals,
"summary": summary,
"has_content": any(r.get("answer", "").strip() for r in retrievals),
}
async def _generate_queries(
self,
requirement_text: str,
num_queries: int,
) -> list[str]:
"""
Use LLM to generate semantic search queries from requirement text.
Args:
requirement_text: Natural language requirement
num_queries: Number of queries to generate
Returns:
List of query strings
"""
system_prompt = self.get_prompt("system", "")
user_prompt_template = self.get_prompt("generate_queries", "")
if not user_prompt_template:
# Fallback prompt
user_prompt_template = (
f"Extract {num_queries} knowledge point names from this requirement for retrieval:\n"
"{requirement_text}\n\n"
'Return JSON: {{"queries": ["point1", "point2", ...]}}'
)
user_prompt = user_prompt_template.format(
requirement_text=requirement_text,
num_queries=num_queries,
)
try:
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
stage="generate_queries",
)
data = json.loads(response)
queries_raw = data.get("queries", [])
# Ensure queries is a list
if not isinstance(queries_raw, list):
if isinstance(queries_raw, dict):
queries_raw = list(queries_raw.values())
elif isinstance(queries_raw, str):
queries_raw = [queries_raw]
else:
queries_raw = []
queries = [q.strip() for q in queries_raw if q and q.strip()]
except Exception as e:
self.logger.warning(f"Failed to generate queries: {e}")
queries = []
# Fallback: use requirement text as query
if not queries:
queries = [requirement_text[:100]]
return queries[:num_queries]
async def _single_rag_search(self, query: str) -> dict[str, Any]:
"""
Execute a single RAG search.
Args:
query: Search query
Returns:
Dict with query and answer
"""
try:
result = await rag_search(
query=query,
kb_name=self.kb_name,
mode=self.rag_mode,
only_need_context=True,
)
return {
"query": query,
"answer": result.get("answer", ""),
"mode": result.get("mode", self.rag_mode),
}
except Exception as e:
self.logger.warning(f"RAG search failed for '{query}': {e}")
return {
"query": query,
"answer": "",
"error": str(e),
}
async def _execute_searches(self, queries: list[str]) -> list[dict[str, Any]]:
"""
Execute RAG searches in parallel.
Args:
queries: List of search queries
Returns:
List of retrieval results
"""
self.logger.debug(f"Executing {len(queries)} RAG searches in parallel")
tasks = [self._single_rag_search(query) for query in queries]
results = await asyncio.gather(*tasks, return_exceptions=True)
retrievals = []
for i, result in enumerate(results):
if isinstance(result, Exception):
self.logger.warning(f"Search failed for query '{queries[i]}': {result}")
continue
if result.get("answer"):
retrievals.append(result)
self.logger.debug(f" → Query: {queries[i][:50]}... (retrieved)")
return retrievals
def _summarize_retrievals(self, retrievals: list[dict[str, Any]]) -> str:
"""
Merge retrieval results into a summary string.
Args:
retrievals: List of retrieval results
Returns:
Merged summary string
"""
if not retrievals:
return "No retrieval context available."
lines = []
for item in retrievals:
lines.append(f"=== Query: {item['query']} ===")
answer = item.get("answer", "")
if answer:
# Truncate very long answers
if len(answer) > 2000:
answer = answer[:2000] + "...[truncated]"
lines.append(answer)
lines.append("")
return "\n".join(lines)
+191
View File
@@ -0,0 +1,191 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Validator - Validate generated Q-A pairs with dynamic tool usage.
The Validator first makes an LLM-based quality judgment, then optionally
runs code verification only when the LLM deems it necessary.
"""
from __future__ import annotations
import json
import re
from typing import Any
from src.agents.base_agent import BaseAgent
from src.agents.question.models import QAPair, QuestionTemplate
from src.tools.code_executor import run_code
class Validator(BaseAgent):
"""
Validate generated output against template requirements.
Two-step process:
1. LLM evaluates the Q-A pair and decides if code verification is needed
2. If code check requested and code is available, run it and finalize
"""
def __init__(
self,
language: str = "en",
tool_flags: dict[str, bool] | None = None,
**kwargs: Any,
) -> None:
super().__init__(
module_name="question",
agent_name="validator",
language=language,
**kwargs,
)
self.tool_flags = tool_flags or {}
async def process(
self,
template: QuestionTemplate,
qa_pair: QAPair,
) -> dict[str, Any]:
"""
Return approval decision and feedback.
Flow:
1. LLM validates quality and decides if code check is needed
2. If code check requested, run verification code
3. If code check reveals issues, append findings to feedback
"""
verification_code = str(qa_pair.metadata.get("verification_code", "")).strip()
has_code = bool(verification_code)
code_enabled = self.tool_flags.get("write_code", True)
# Step 1: LLM validation (includes decision on code check)
llm_result = await self._validate_with_llm(
template=template,
qa_pair=qa_pair,
has_verification_code=has_code and code_enabled,
)
decision = str(llm_result.get("decision", "reject")).lower()
if decision not in {"approve", "reject"}:
decision = "reject"
issues = llm_result.get("issues", [])
if not isinstance(issues, list):
issues = []
feedback = str(llm_result.get("feedback", "")).strip()
needs_code_check = bool(llm_result.get("needs_code_check", False))
# Step 2: Optionally run code verification
code_check: dict[str, Any] = {}
if needs_code_check and has_code and code_enabled:
code_check = await self._run_code_check(verification_code)
# If code check failed, downgrade approval or augment feedback
if code_check.get("exit_code", -1) != 0:
stderr = code_check.get("stderr", "")
if decision == "approve":
decision = "reject"
feedback = (
f"Code verification failed (exit_code={code_check.get('exit_code')}). "
f"stderr: {stderr[:300]}. "
f"Original feedback: {feedback}"
)
issues.append("code_verification_failed")
else:
feedback += (
f" | Code check also failed: {stderr[:200]}"
)
if decision == "reject" and not feedback:
feedback = (
"Answer quality or alignment is insufficient. "
"Regenerate with stricter alignment to the template."
)
return {
"decision": decision,
"approved": decision == "approve",
"feedback": feedback,
"issues": issues,
"code_check": code_check,
"needs_code_check": needs_code_check,
}
async def _validate_with_llm(
self,
template: QuestionTemplate,
qa_pair: QAPair,
has_verification_code: bool,
) -> dict[str, Any]:
"""Run LLM validation. The LLM also decides if code check is needed."""
system_prompt = self.get_prompt("system", "")
validate_prompt = self.get_prompt("validate", "")
if not validate_prompt:
validate_prompt = (
"Template:\n{template}\n\n"
"QA Pair:\n{qa_pair}\n\n"
"Verification code available: {has_code}\n\n"
'Return JSON {{"decision":"approve|reject","feedback":"","issues":[],"needs_code_check":true|false}}'
)
user_prompt = validate_prompt.format(
template=json.dumps(template.__dict__, ensure_ascii=False, indent=2),
qa_pair=json.dumps(qa_pair.__dict__, ensure_ascii=False, indent=2),
has_code=str(has_verification_code).lower(),
)
try:
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt or "",
response_format={"type": "json_object"},
temperature=0.2,
stage="validator_decision",
)
return self._parse_json_like(response)
except Exception as exc:
self.logger.warning(f"Validator LLM failed, fallback reject: {exc}")
return {
"decision": "reject",
"feedback": str(exc),
"issues": ["validator_error"],
"needs_code_check": False,
}
async def _run_code_check(self, code: str) -> dict[str, Any]:
"""Execute verification code."""
try:
result = await run_code(language="python", code=code, timeout=10)
return {
"exit_code": result.get("exit_code", -1),
"stdout": (result.get("stdout", "") or "")[:800],
"stderr": (result.get("stderr", "") or "")[:800],
}
except Exception as exc:
return {"exit_code": -1, "stderr": str(exc)}
@staticmethod
def _parse_json_like(content: str) -> dict[str, Any]:
if not content:
return {}
cleaned = re.sub(
r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", content.strip()
)
block = re.search(r"```(?:json)?\s*(.*?)```", cleaned, re.DOTALL)
if block:
cleaned = block.group(1).strip()
try:
data = json.loads(cleaned)
return data if isinstance(data, dict) else {}
except Exception:
pass
obj = re.search(r"\{[\s\S]*\}", cleaned)
if obj:
try:
data = json.loads(obj.group(0))
return data if isinstance(data, dict) else {}
except Exception:
return {}
return {}
+345
View File
@@ -0,0 +1,345 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Interactive CLI for testing the refactored question module.
Usage:
python src/agents/question/cli.py
Features:
- Real-time progress display during generation
- Saves all intermediate files (templates, traces, per-question results)
to a per-batch directory under the output folder
- Detailed summary with question previews at the end
"""
from __future__ import annotations
import asyncio
from pathlib import Path
import sys
from typing import Any
# Ensure project root import works when running as a script
PROJECT_ROOT = Path(__file__).resolve().parents[3]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from src.agents.question import AgentCoordinator
from src.knowledge.config import KNOWLEDGE_BASES_DIR
from src.knowledge.manager import KnowledgeBaseManager
from src.services.llm.config import get_llm_config
# ── Formatting helpers ────────────────────────────────────────────────
BOLD = "\033[1m"
DIM = "\033[2m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
CYAN = "\033[96m"
MAGENTA = "\033[95m"
RESET = "\033[0m"
CHECK = f"{GREEN}✓{RESET}"
CROSS = f"{RED}✗{RESET}"
ARROW = f"{CYAN}→{RESET}"
def _hr(char: str = "─", width: int = 70) -> str:
return f"{DIM}{char * width}{RESET}"
def _header(title: str) -> None:
print(f"\n{_hr('━')}")
print(f" {BOLD}{title}{RESET}")
print(_hr("━"))
def _prompt_non_empty(message: str, default: str | None = None) -> str:
suffix = f" [{DIM}{default}{RESET}]" if default else ""
while True:
raw = input(f" {message}{suffix}: ").strip()
if raw:
return raw
if default is not None:
return default
print(f" {RED}输入不能为空,请重试。{RESET}")
def _list_kbs() -> list[str]:
"""Fetch available knowledge bases from the local KB manager."""
try:
manager = KnowledgeBaseManager(str(KNOWLEDGE_BASES_DIR))
return manager.list_knowledge_bases()
except Exception:
return []
def _select_kb() -> str:
"""Show a numbered list of KBs and let the user pick one."""
kbs = _list_kbs()
if not kbs:
print(f" {YELLOW}未找到已有知识库,请手动输入名称。{RESET}")
return _prompt_non_empty("KB 名称", "ai_textbook")
print(f"\n {BOLD}可用知识库:{RESET}")
for i, name in enumerate(kbs, 1):
print(f" {CYAN}{i}{RESET}) {name}")
print(f" {CYAN}0{RESET}) 手动输入")
while True:
raw = input(f" 选择 [{DIM}1{RESET}]: ").strip()
if not raw:
return kbs[0]
if raw == "0":
return _prompt_non_empty("KB 名称")
try:
idx = int(raw)
if 1 <= idx <= len(kbs):
return kbs[idx - 1]
except ValueError:
# Allow typing a name directly
if raw in kbs:
return raw
print(f" {RED}无效选择,请重试。{RESET}")
def _prompt_int(message: str, default: int) -> int:
while True:
raw = input(f" {message} [{DIM}{default}{RESET}]: ").strip()
if not raw:
return default
try:
value = int(raw)
if value > 0:
return value
except ValueError:
pass
print(f" {RED}请输入正整数。{RESET}")
# ── Progress callback ────────────────────────────────────────────────
async def _cli_progress(data: dict[str, Any]) -> None:
"""Real-time progress callback printed to terminal."""
msg_type = data.get("type", "")
if msg_type == "progress":
stage = data.get("stage", "")
if stage == "idea_loop":
rd = data.get("current_round", "")
mx = data.get("max_rounds", "")
if rd:
print(f" {MAGENTA}🔄 创意循环{RESET} 第 {rd}/{mx} 轮")
elif stage == "generating":
cur = data.get("current", "")
tot = data.get("total", "")
qid = data.get("question_id", "")
if cur and tot:
print(f" {CYAN}📝 生成中{RESET} {cur}/{tot} {DIM}{qid}{RESET}")
elif stage == "complete":
comp = data.get("completed", "?")
tot = data.get("total", "?")
print(f" {GREEN}✅ 完成{RESET} {comp}/{tot}")
elif stage in ("parsing", "extracting", "uploading"):
status = data.get("status", "")
print(f" {YELLOW}📄 {stage}{RESET} {status}")
elif msg_type == "templates_ready":
count = data.get("count", 0)
print(f" {GREEN}📋 模板就绪{RESET} {count} 个")
elif msg_type == "idea_round":
rd = data.get("round", "?")
fb = data.get("feedback", "")
cont = data.get("continue_loop", False)
status = "继续改进" if cont else "已确定"
print(f" {MAGENTA}💡 创意第 {rd} 轮{RESET} → {status}")
if fb:
print(f" {DIM}反馈: {fb[:100]}{RESET}")
elif msg_type == "question_update":
qid = data.get("question_id", "")
attempt = data.get("attempt", 1)
max_att = data.get("max_attempts", "?")
print(f" {CYAN}⚙ {qid}{RESET} 生成 (尝试 {attempt}/{max_att})")
elif msg_type == "validating":
qid = data.get("question_id", "")
attempt = data.get("attempt", 1)
validation = data.get("validation", {})
decision = validation.get("decision", "?")
icon = CHECK if decision == "approve" else CROSS
print(f" {YELLOW}🔍 {qid}{RESET} 验证 → {icon} {decision}")
elif msg_type == "result":
qid = data.get("question_id", "")
validation = data.get("validation", {})
approved = validation.get("approved", False)
attempts = data.get("attempts", 1)
icon = CHECK if approved else CROSS
print(f" {icon} {BOLD}{qid}{RESET} ({attempts} 次尝试)")
# ── Result display ────────────────────────────────────────────────────
def _print_summary(summary: dict[str, Any]) -> None:
_header("结果摘要")
success = summary.get("success", False)
status_icon = f"{GREEN}SUCCESS{RESET}" if success else f"{RED}FAILED{RESET}"
print(f" 状态: {status_icon}")
print(f" 来源: {summary.get('source', '?')}")
print(f" 请求: {summary.get('requested', '?')} 道")
print(f" 成功: {GREEN}{summary.get('completed', 0)}{RESET}")
print(f" 失败: {RED}{summary.get('failed', 0)}{RESET}")
print(f" 模板数: {summary.get('template_count', '?')}")
batch_dir = summary.get("batch_dir")
if batch_dir:
print(f" 输出目录: {CYAN}{batch_dir}{RESET}")
results = summary.get("results", []) or []
if results:
print(f"\n {BOLD}题目预览:{RESET}")
for i, item in enumerate(results, 1):
qa = item.get("qa_pair", {})
approved = item.get("success", False)
icon = CHECK if approved else CROSS
q_type = qa.get("question_type", "unknown")
question = str(qa.get("question", "")).replace("\n", " ")[:100]
attempts = len(item.get("attempts", []))
# Tool usage info
tool_plan = qa.get("metadata", {}).get("tool_plan", {})
tools_used = []
if tool_plan.get("use_rag"):
tools_used.append("rag")
if tool_plan.get("use_web"):
tools_used.append("web")
if tool_plan.get("use_code"):
tools_used.append("code")
tool_str = f" {DIM}[{', '.join(tools_used)}]{RESET}" if tools_used else ""
print(f" {icon} {i}. [{q_type}]{tool_str} {DIM}({attempts}次){RESET}")
print(f" {question}...")
print()
# ── Coordinator builder ───────────────────────────────────────────────
def _build_coordinator(
kb_name: str, output_dir: str, language: str
) -> AgentCoordinator:
try:
llm_config = get_llm_config()
return AgentCoordinator(
api_key=llm_config.api_key,
base_url=llm_config.base_url,
api_version=getattr(llm_config, "api_version", None),
kb_name=kb_name,
output_dir=output_dir,
language=language,
)
except Exception:
return AgentCoordinator(
kb_name=kb_name, output_dir=output_dir, language=language
)
# ── Mode runners ──────────────────────────────────────────────────────
async def _run_topic_mode(coordinator: AgentCoordinator) -> None:
_header("Topic 模式")
user_topic = _prompt_non_empty("主题 (如: Lagrange multipliers)")
preference = input(f" 偏好 (可留空): ").strip()
num_questions = _prompt_int("题目数量", 3)
print(f"\n {ARROW} 开始生成 {BOLD}{num_questions}{RESET} 道题...")
print(_hr())
coordinator.set_ws_callback(_cli_progress)
summary = await coordinator.generate_from_topic(
user_topic=user_topic,
preference=preference,
num_questions=num_questions,
)
_print_summary(summary)
async def _run_mimic_mode(coordinator: AgentCoordinator) -> None:
_header("Mimic 模式")
mode = _prompt_non_empty("输入模式 [upload/parsed]", "parsed").lower()
if mode not in {"upload", "parsed"}:
print(f" {YELLOW}无效模式,使用 parsed。{RESET}")
mode = "parsed"
if mode == "upload":
exam_path = _prompt_non_empty("PDF 路径")
else:
exam_path = _prompt_non_empty("已解析试卷目录路径")
max_questions = _prompt_int("最大题目数", 5)
print(f"\n {ARROW} 开始解析并生成...")
print(_hr())
coordinator.set_ws_callback(_cli_progress)
summary = await coordinator.generate_from_exam(
exam_paper_path=exam_path,
max_questions=max_questions,
paper_mode=mode,
)
_print_summary(summary)
# ── Main ──────────────────────────────────────────────────────────────
async def main() -> None:
print(f"\n{BOLD}{'=' * 70}{RESET}")
print(f" {BOLD}{CYAN}DeepTutor Question Module CLI{RESET}")
print(f"{BOLD}{'=' * 70}{RESET}")
kb_name = _select_kb()
language = _prompt_non_empty("语言 [en/zh]", "zh").lower()
if language not in {"en", "zh"}:
print(f" {YELLOW}语言无效,使用 zh。{RESET}")
language = "zh"
default_output = str(PROJECT_ROOT / "data" / "user" / "question")
output_dir = _prompt_non_empty(f"输出目录", default_output)
coordinator = _build_coordinator(
kb_name=kb_name,
output_dir=output_dir,
language=language,
)
print(f"\n {DIM}配置: KB={kb_name}, 语言={language}, 输出={output_dir}{RESET}")
while True:
print(f"\n {BOLD}请选择模式:{RESET}")
print(f" {CYAN}1{RESET}) Topic 模式 — 基于主题生成")
print(f" {CYAN}2{RESET}) Mimic 模式 — 基于试卷仿题")
print(f" {CYAN}q{RESET}) 退出")
choice = input(f" {ARROW} ").strip().lower()
try:
if choice == "1":
await _run_topic_mode(coordinator)
elif choice == "2":
await _run_mimic_mode(coordinator)
elif choice in {"q", "quit", "exit"}:
print(f"\n {DIM}已退出。{RESET}\n")
break
else:
print(f" {RED}无效输入,请重试。{RESET}")
except KeyboardInterrupt:
print(f"\n {YELLOW}已中断当前任务。{RESET}")
except Exception as exc:
print(f"\n {RED}运行失败: {exc}{RESET}")
if __name__ == "__main__":
asyncio.run(main())
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Data models for the refactored question pipeline.
"""
from dataclasses import dataclass, field
from typing import Any
@dataclass
class QuestionTemplate:
"""
Standardized intermediate template shared by all input paths.
"""
question_id: str
concentration: str
question_type: str
difficulty: str
source: str = "custom"
reference_question: str | None = None
reference_answer: str | None = None
metadata: dict[str, Any] = field(default_factory=dict)
@dataclass
class QAPair:
"""
Final generated Q-A payload.
"""
question_id: str
question: str
correct_answer: str
explanation: str
question_type: str
options: dict[str, str] | None = None
concentration: str = ""
difficulty: str = ""
validation: dict[str, Any] = field(default_factory=dict)
metadata: dict[str, Any] = field(default_factory=dict)
@@ -1,75 +0,0 @@
generate_search_queries: |
system: |
【Role】You are a knowledge base retrieval assistant, preparing for question generation.
【Current Task】Generate knowledge point retrieval queries to find theoretical explanations, definitions, and theorems in the knowledge base.
⚠️ Key: You are not generating questions now! You are looking for theoretical knowledge needed for question generation!
【Output Rules】
1. Only output pure knowledge point names (theorem names, concept names, method names)
2. Each query should be 2-5 words
3. Do not include functions, numerical values, or calculation tasks
4. Do not use questions or task descriptions
user_template: |
The user's question generation requirement is:
{requirement_text}
Please extract {num_queries} pure knowledge point names from it for knowledge base retrieval.
Correct examples:
✅ Taylor theorem
✅ Lagrange multipliers
✅ critical points
Incorrect examples (do not generate):
❌ Apply Taylor's Theorem to approximate f(x,y)=... (This is a question)
❌ Find and classify critical points (This is a task)
❌ Use Lagrange multipliers to find maximum (This is an instruction)
Return in JSON format: {{"queries": ["knowledge point 1", "knowledge point 2", ...]}}, containing exactly {num_queries} knowledge point names.
check_retrieval_relevance: |
system: |
You evaluate whether retrieved knowledge is relevant to a user's request.
Respond in JSON with key "relevant" (true/false) and optional "reason".
user_template: |
User request:
{requirement_text}
Retrieved knowledge summary:
{knowledge_summary}
Is the retrieved knowledge substantively relevant to the request?
generate_child_requirements: |
system: |
You are a curriculum designer. Given a base requirement and knowledge summary,
create distinct sub-requirements that all test the SAME knowledge point.
Each sub-requirement must describe a unique scenario and reasoning flow.
Output JSON with key "requirements" (array of length requested) where each item has:
"title", "question_type", "difficulty", "additional_requirements".
user_template: |
Base requirement:
{base_requirement}
Knowledge summary:
{knowledge_summary}
Generate exactly {num_questions} sub-requirements in JSON.
interpret_requirement_text: |
system: |
You are an instruction parser for an exam-question generator.
Given a natural-language request, extract the core knowledge point,
difficulty (easy/medium/hard), preferred question type (choice/written),
and additional requirements. Return JSON with keys:
"knowledge_point", "difficulty", "question_type", "additional_requirements".
user_template: |
Requirement:
{requirement_text}
Return JSON only.
@@ -0,0 +1,52 @@
system: |
You are an Evaluator in a question-design workflow.
You assess idea quality and diversity, and decide whether another iteration is needed.
evaluate_ideas: |
Topic:
{user_topic}
User preference:
{preference}
Current round: {current_round}
Max rounds: {max_rounds}
Required top-k: {top_k}
Candidate ideas:
{ideas_json}
Evaluate each idea by:
- relevance to topic
- diversity across ideas
- alignment with user preference
- clarity and feasibility
If idea quality/diversity is insufficient and rounds remain, set continue_loop=true
and provide actionable feedback for the next idea generation round.
Otherwise set continue_loop=false and select top-k ideas.
Return only JSON:
{{
"continue_loop": false,
"feedback": "specific guidance for next round",
"scores": [
{{
"idea_id": "idea_1",
"relevance_score": 0.0,
"diversity_score": 0.0,
"preference_score": 0.0,
"overall_score": 0.0,
"comment": "brief reason"
}}
],
"selected_ideas": [
{{
"idea_id": "idea_1",
"concentration": "focus area",
"question_type": "choice or written or coding",
"difficulty": "easy or medium or hard",
"rationale": "why selected"
}}
]
}}
@@ -1,83 +0,0 @@
system: |
You are a professional Question Generation Agent. Your responsibilities are:
1. Generate high-quality questions based on requirements
2. Use retrieved background knowledge to ensure accuracy
3. Express knowledge in the same way as the knowledge base
Important notes:
- Questions must be rigorous and accurate, based on knowledge base content
- Calculation problems should have substantial computation, not too simple
- Use the provided background knowledge as the foundation for question generation
- Multiple choice questions must have only one correct answer
- Solutions/explanations should be detailed and clear
- Chain-of-thought: reason internally step-by-step, but only output the final JSON
generate: |
Generate a question based on the following information:
## User Preference
{preference}
Requirements:
{requirements}
Focus/Angle:
{focus}
Background Knowledge:
{knowledge}
Thinking instructions:
- First, silently plan the scenario and reasoning steps to ensure the question is coherent.
- Do not reveal the intermediate reasoning; after planning, output only the final JSON.
CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.
Your response must start with {{ and end with }}.
Please generate a question in JSON format:
{{
"question_type": "choice" or "written",
"question": "question content",
"options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // only for multiple choice
"correct_answer": "correct answer",
"explanation": "detailed explanation"
}}
generate_with_reference: |
Generate a new question that draws inspiration from the following reference but is clearly distinct in scenario and reasoning:
## User Preference
{preference}
Reference question:
{reference_question}
Requirements:
{requirements}
Background Knowledge:
{knowledge}
Requirements:
1. **Maintain same core knowledge and difficulty**: Concepts being tested must stay aligned
2. **Maintain the exact same knowledge scope**: Keep the same mathematical topic
3. **Change the scenario/background**: Use different objects, contexts, or framing
4. **Change the calculation process**: Rearrange steps or add sub-questions
5. **Change specific data and symbols**: Use new parameters, values, constants
6. **Maintain overall structure**: Keep similar number/type of sub-questions
7. **Forbidden**:
- Only modifying numerical values or variable names
- Repeating the same statement with an added explanation
- Copying the same setup without new twists
CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.
Your response must start with {{ and end with }}.
Please generate question in JSON format:
{{
"question_type": "choice" or "written",
"question": "question content",
"options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // only for multiple choice
"correct_answer": "correct answer",
"explanation": "detailed explanation"
}}
@@ -0,0 +1,71 @@
system: |
You are the Generator in a question pipeline.
Produce high-quality Q-A pairs from a structured QuestionTemplate.
You can leverage tool outputs (rag/web/code) as grounding evidence when available.
plan_tools: |
You are planning which tools to use before generating a question.
QuestionTemplate:
{template}
User topic: {user_topic}
User preference: {preference}
Available tools:
{available_tools}
Decide which tools are genuinely helpful for THIS specific question template.
Do NOT use tools just because they are available — only select them when they
add real value. Consider:
- rag_tool: Usually helpful for curriculum-aligned factual/conceptual questions.
Less useful if the template already contains a reference question with a full answer.
- web_search: Helpful for real-world examples, current events, or when KB may lack coverage.
Unnecessary for standard textbook content.
- write_code: Helpful for coding questions, numerical verification, or algorithmic problems.
Unnecessary for purely conceptual or essay-type questions.
Return JSON only:
{{
"use_rag": true or false,
"use_web": true or false,
"use_code": true or false,
"rag_query": "specific knowledge retrieval query (only if use_rag is true)",
"web_query": "specific web search query (only if use_web is true)",
"reasoning": "one-sentence explanation of your tool choices"
}}
generate: |
QuestionTemplate:
{template}
User topic:
{user_topic}
User preference:
{preference}
Validator feedback from previous attempt:
{validator_feedback}
Tool context (knowledge/search results, if any):
{tool_context}
Requirements:
- Keep strict alignment with template.concentration and template.difficulty.
- Respect template.question_type.
- If question_type is choice, provide 4 options and one correct answer.
- Provide a clear explanation.
- Only include `verification_code` (python) if it is genuinely useful to verify
the correctness of your answer (e.g., for coding or math questions).
Do NOT include verification code for conceptual or essay questions.
Return JSON only:
{{
"question_type": "choice or written or coding",
"question": "question content",
"options": {{"A":"...","B":"...","C":"...","D":"..."}},
"correct_answer": "final answer",
"explanation": "detailed explanation",
"verification_code": "optional python code — only if useful for answer verification"
}}
@@ -0,0 +1,46 @@
system: |
You are an Idea Agent for exam question design.
Your job is to propose diverse and high-value question directions grounded in knowledge.
generate_queries: |
Topic: {user_topic}
Generate exactly {num_queries} concise retrieval queries for a knowledge base search.
Rules:
- Each query should be a concept, theorem, method, or key term.
- Avoid full task instructions.
- Keep each query short and precise.
Return only JSON:
{{
"queries": ["...", "..."]
}}
generate_ideas: |
Topic:
{user_topic}
User preference:
{preference}
Evaluator feedback from previous round:
{evaluator_feedback}
Grounding knowledge:
{knowledge_context}
Generate exactly {num_ideas} candidate question ideas.
Focus on diversity, relevance, and alignment with user preference.
Return only JSON in this format:
{{
"ideas": [
{{
"idea_id": "idea_1",
"concentration": "what this question should focus on",
"question_type": "choice or written or coding",
"difficulty": "easy or medium or hard",
"rationale": "why this idea is valuable"
}}
]
}}
@@ -1,41 +0,0 @@
system: |
You are an educational content analyst specializing in analyzing the relationship
between exam questions and knowledge base content.
Your task is to analyze the relevance between a question and the knowledge base,
NOT to validate or reject the question. All questions are accepted.
analyze_relevance: |
Analyze the relevance between the following exam question and the knowledge base content.
Question:
{question}
Knowledge Base Content:
{knowledge}
Please analyze and provide a JSON response with the following structure:
{{
"relevance": "high" or "partial",
"kb_coverage": "Describe specifically what concepts, theories, or methods from the knowledge base this question tests. List the key knowledge points that are directly relevant.",
"extension_points": "If relevance is 'partial', describe what aspects of this question extend beyond the knowledge base content. What additional knowledge does it require? Leave empty if relevance is 'high'."
}}
Guidelines for determining relevance:
1. "high" - The question can be fully answered using only the knowledge base content. All concepts, methods, and required knowledge are present in the KB.
2. "partial" - The question is related to the KB content but requires some knowledge beyond what's provided. The KB serves as a foundation but the question extends to additional areas.
For kb_coverage:
- Be specific about which concepts from the KB are being tested
- Reference the actual content from the KB where possible
- Explain how the KB content relates to the question
For extension_points (only when relevance is "partial"):
- Identify what additional knowledge is needed
- Explain how the question extends from the KB foundation
- Keep the tone positive - extensions are valuable for learning
CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.
Your response must start with {{ and end with }}.
Output only the JSON, no additional text.
@@ -1,32 +0,0 @@
system: |
You are a knowledge base retrieval assistant, preparing for question generation.
Your task is to generate knowledge point retrieval queries to find theoretical explanations,
definitions, and theorems in the knowledge base.
Key principle: You are NOT generating questions now! You are looking for theoretical knowledge
needed for question generation.
generate_queries: |
The user's question generation requirement is:
{requirement_text}
Please extract {num_queries} pure knowledge point names for knowledge base retrieval.
Output Rules:
1. Only output pure knowledge point names (theorem names, concept names, method names)
2. Each query should be 2-5 words
3. Do not include functions, numerical values, or calculation tasks
4. Do not use questions or task descriptions
Correct examples:
✓ Taylor theorem
✓ Lagrange multipliers
✓ critical points
Incorrect examples (do not generate):
✗ Apply Taylor's Theorem to approximate f(x,y)=... (This is a question)
✗ Find and classify critical points (This is a task)
✗ Use Lagrange multipliers to find maximum (This is an instruction)
Return in JSON format: {{"queries": ["knowledge point 1", "knowledge point 2", ...]}}, containing exactly {num_queries} knowledge point names.
@@ -0,0 +1,35 @@
system: |
You are the Validator in a question pipeline.
Validate quality and requirement alignment, then decide approve/reject.
You also decide whether running verification code would help validate the answer.
validate: |
Template:
{template}
Generated Q-A pair:
{qa_pair}
Verification code available: {has_code}
Validation checklist:
- Is the question aligned with template concentration?
- Is the difficulty appropriate?
- Is the answer correct and consistent with explanation?
- For choice questions, exactly one option should be correct.
- Is the output clear and complete?
Also decide whether code verification is needed:
- Set needs_code_check to true ONLY if: verification code is available AND
the question type benefits from computational verification (e.g., coding,
math, algorithm questions).
- Set needs_code_check to false for: conceptual, essay, definition, or
purely theoretical questions — even if verification code is provided.
Return JSON only:
{{
"decision": "approve or reject",
"feedback": "specific regeneration instruction if reject; concise confirmation if approve",
"issues": ["issue_1", "issue_2"],
"needs_code_check": true or false
}}
@@ -1,75 +0,0 @@
generate_search_queries: |
system: |
【角色】你是一个知识库检索助手,为题目生成做准备。
【当前任务】生成知识点检索查询,在知识库中查找理论解释、定义和定理。
⚠️ 关键:你现在不是在生成题目!你是在寻找题目生成所需的理论知识!
【输出规则】
1. 只输出纯粹的知识点名称(定理名称、概念名称、方法名称)
2. 每个查询应为2-5个词
3. 不要包含函数、数值或计算任务
4. 不要使用问题或任务描述
user_template: |
用户的题目生成需求是:
{requirement_text}
请从中提取{num_queries}个纯知识点名称用于知识库检索。
正确示例:
✅ 泰勒定理
✅ 拉格朗日乘数法
✅ 临界点
错误示例(不要生成):
❌ 应用泰勒定理近似f(x,y)=...(这是一道题目)
❌ 求临界点并分类(这是一个任务)
❌ 用拉格朗日乘数法求最大值(这是一条指令)
以JSON格式返回:{{"queries": ["知识点1", "知识点2", ...]}},恰好包含{num_queries}个知识点名称。
check_retrieval_relevance: |
system: |
你评估检索到的知识是否与用户的请求相关。
以JSON格式响应,包含键"relevant"(true/false)和可选的"reason"。
user_template: |
用户请求:
{requirement_text}
检索到的知识摘要:
{knowledge_summary}
检索到的知识是否实质上与请求相关?
generate_child_requirements: |
system: |
你是一个课程设计师。给定一个基础需求和知识摘要,
创建测试相同知识点的不同子需求。
每个子需求必须描述独特的场景和推理流程。
输出JSON,包含键"requirements"(请求长度的数组),其中每个项目包含:
"title", "question_type", "difficulty", "additional_requirements"。
user_template: |
基础需求:
{base_requirement}
知识摘要:
{knowledge_summary}
以JSON格式生成恰好{num_questions}个子需求。
interpret_requirement_text: |
system: |
你是考试题目生成器的指令解析器。
给定一个自然语言请求,提取核心知识点、
难度(easy/medium/hard)、首选题型(choice/written)、
和额外要求。返回JSON,包含键:
"knowledge_point", "difficulty", "question_type", "additional_requirements"。
user_template: |
需求:
{requirement_text}
仅返回JSON。
@@ -0,0 +1,52 @@
system: |
你是出题流程中的 Evaluator。
你的职责是评估创意质量与多样性,并决定是否需要下一轮迭代。
evaluate_ideas: |
主题:
{user_topic}
用户偏好:
{preference}
当前轮次:{current_round}
最大轮次:{max_rounds}
目标 top-k:{top_k}
候选创意:
{ideas_json}
请按以下维度评估每个创意:
- 与主题的相关性
- 创意之间的多样性
- 与用户偏好的一致性
- 可执行性与清晰度
若质量/多样性不足且仍有轮次,请设置 continue_loop=true,
并给出可执行的下一轮反馈。
否则设置 continue_loop=false,并输出 top-k 创意。
仅返回 JSON:
{{
"continue_loop": false,
"feedback": "下一轮改进建议",
"scores": [
{{
"idea_id": "idea_1",
"relevance_score": 0.0,
"diversity_score": 0.0,
"preference_score": 0.0,
"overall_score": 0.0,
"comment": "简短理由"
}}
],
"selected_ideas": [
{{
"idea_id": "idea_1",
"concentration": "考察方向",
"question_type": "choice 或 written 或 coding",
"difficulty": "easy 或 medium 或 hard",
"rationale": "入选原因"
}}
]
}}
@@ -1,83 +0,0 @@
system: |
你是一个专业的题目生成 Agent。你的职责是:
1. 根据要求生成高质量的题目
2. 使用检索到的背景知识确保准确性
3. 用与知识库相同的方式表达知识
重要说明:
- 题目必须严谨准确,基于知识库内容
- 计算题应有实质性的计算,不能太简单
- 使用提供的背景知识作为题目生成的基础
- 选择题必须只有一个正确答案
- 解答/解释应详细清晰
- 思维链:内部逐步推理,但只输出最终的 JSON
generate: |
根据以下信息生成题目:
## 用户偏好
{preference}
要求:
{requirements}
焦点/角度:
{focus}
背景知识:
{knowledge}
思考说明:
- 首先,默默地规划场景和推理步骤,确保题目连贯。
- 不要透露中间推理;规划后只输出最终的 JSON。
关键:只返回有效的 JSON。不要用 markdown 代码块包装。
你的回复必须以 {{ 开始,以 }} 结束。
请以 JSON 格式生成题目:
{{
"question_type": "choice" 或 "written",
"question": "题目内容",
"options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // 仅选择题需要
"correct_answer": "正确答案",
"explanation": "详细解释"
}}
generate_with_reference: |
生成一道新题目,从以下参考题目获取灵感,但在场景和推理上明显不同:
## 用户偏好
{preference}
参考题目:
{reference_question}
要求:
{requirements}
背景知识:
{knowledge}
要求:
1. **保持相同的核心知识和难度**:测试的概念必须保持一致
2. **保持完全相同的知识范围**:保持相同的数学主题
3. **改变场景/背景**:使用不同的对象、情境或框架
4. **改变计算过程**:重新安排步骤或添加子问题
5. **改变具体数据和符号**:使用新的参数、值、常数
6. **保持整体结构**:保持相似数量/类型的子问题
7. **禁止**:
- 只修改数值或变量名
- 重复相同的陈述并添加解释
- 复制相同的设置而没有新的变化
关键:只返回有效的 JSON。不要用 markdown 代码块包装。
你的回复必须以 {{ 开始,以 }} 结束。
请以 JSON 格式生成题目:
{{
"question_type": "choice" 或 "written",
"question": "题目内容",
"options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // 仅选择题需要
"correct_answer": "正确答案",
"explanation": "详细解释"
}}
@@ -0,0 +1,69 @@
system: |
你是出题流程中的 Generator。
你需要基于结构化的 QuestionTemplate 产出高质量 Q-A 对。
当有工具输出(rag/web/code)可用时,可作为生成依据。
plan_tools: |
你正在规划生成题目前需要使用哪些工具。
QuestionTemplate:
{template}
用户主题:{user_topic}
用户偏好:{preference}
可用工具:
{available_tools}
请判断哪些工具对**这道具体的题目模板**真正有帮助。
不要因为工具可用就全部使用——只在确实能提升质量时才选择。考虑:
- rag_tool:通常对课程相关的事实性/概念性题目有帮助。
如果模板已包含完整的参考题目和答案,则可能不需要。
- web_search:对需要真实案例、时事、或知识库覆盖不足的内容有帮助。
对标准教材内容通常不需要。
- write_code:对编程题、数值验证、算法问题有帮助。
对纯概念性或论述题不需要。
仅返回 JSON:
{{
"use_rag": true 或 false,
"use_web": true 或 false,
"use_code": true 或 false,
"rag_query": "具体的知识检索查询(仅当 use_rag 为 true 时填写)",
"web_query": "具体的网络搜索查询(仅当 use_web 为 true 时填写)",
"reasoning": "一句话说明你的工具选择理由"
}}
generate: |
QuestionTemplate:
{template}
用户主题:
{user_topic}
用户偏好:
{preference}
上一轮 Validator 反馈:
{validator_feedback}
工具上下文(知识/搜索结果,如有):
{tool_context}
要求:
- 严格对齐 template.concentration 与 template.difficulty。
- 遵循 template.question_type。
- 若为选择题,提供 4 个选项且仅 1 个正确答案。
- 给出清晰解释。
- 仅在对答案验证真正有用时(如编程题或数学计算题)才提供 `verification_code`(python)。
概念性或论述题不要包含验证代码。
仅返回 JSON:
{{
"question_type": "choice 或 written 或 coding",
"question": "题目内容",
"options": {{"A":"...","B":"...","C":"...","D":"..."}},
"correct_answer": "最终答案",
"explanation": "详细解释",
"verification_code": "可选的 python 代码 — 仅在有助于答案验证时提供"
}}
@@ -0,0 +1,46 @@
system: |
你是考试题目设计流程中的 Idea Agent。
你的职责是基于知识内容提出多样、有效、可执行的出题方向。
generate_queries: |
主题:{user_topic}
请生成恰好 {num_queries} 条知识库检索查询。
规则:
- 每条查询应是概念、定理、方法或关键词。
- 不要写完整任务描述。
- 表达简洁准确。
仅返回 JSON:
{{
"queries": ["...", "..."]
}}
generate_ideas: |
主题:
{user_topic}
用户偏好:
{preference}
上一轮评估反馈:
{evaluator_feedback}
知识依据:
{knowledge_context}
请生成恰好 {num_ideas} 个候选出题创意。
重点关注:多样性、相关性、与用户偏好的一致性。
仅返回 JSON,格式如下:
{{
"ideas": [
{{
"idea_id": "idea_1",
"concentration": "该题主要考察点",
"question_type": "choice 或 written 或 coding",
"difficulty": "easy 或 medium 或 hard",
"rationale": "该创意的价值"
}}
]
}}
@@ -1,39 +0,0 @@
system: |
你是一位教育内容分析师,专门分析考试题目与知识库内容之间的关系。
你的任务是分析题目与知识库的相关性,而不是验证或拒绝题目。所有题目都被接受。
analyze_relevance: |
分析以下考试题目与知识库内容之间的相关性。
题目:
{question}
知识库内容:
{knowledge}
请分析并提供以下结构的 JSON 响应:
{{
"relevance": "high" 或 "partial",
"kb_coverage": "具体描述这道题目测试了知识库中的哪些概念、理论或方法。列出直接相关的关键知识点。",
"extension_points": "如果相关性是 'partial',描述这道题目的哪些方面超出了知识库内容。它需要什么额外的知识?如果相关性是 'high' 则留空。"
}}
判断相关性的指南:
1. "high" - 题目可以完全使用知识库内容来回答。所有概念、方法和所需知识都在知识库中。
2. "partial" - 题目与知识库内容相关,但需要一些超出提供内容的知识。知识库作为基础,但题目扩展到了额外的领域。
对于 kb_coverage:
- 具体说明正在测试知识库中的哪些概念
- 尽可能参考知识库中的实际内容
- 解释知识库内容与题目的关系
对于 extension_points(仅当相关性为 "partial" 时):
- 确定需要什么额外知识
- 解释题目如何从知识库基础扩展
- 保持积极的语气 - 扩展对学习有价值
关键:只返回有效的 JSON。不要用 markdown 代码块包装。
你的回复必须以 {{ 开始,以 }} 结束。
只输出 JSON,不要有其他文字。
@@ -1,30 +0,0 @@
system: |
你是一个知识库检索助手,正在为题目生成做准备。
你的任务是生成知识点检索查询,以在知识库中找到理论解释、定义和定理。
关键原则:你现在不是在生成题目!你是在寻找题目生成所需的理论知识。
generate_queries: |
用户的题目生成需求是:
{requirement_text}
请提取 {num_queries} 个纯粹的知识点名称用于知识库检索。
输出规则:
1. 只输出纯粹的知识点名称(定理名、概念名、方法名)
2. 每个查询应为2-5个词
3. 不要包含函数、数值或计算任务
4. 不要使用问句或任务描述
正确示例:
✓ 泰勒定理
✓ 拉格朗日乘数法
✓ 临界点
错误示例(不要生成):
✗ 应用泰勒定理近似 f(x,y)=... (这是一个题目)
✗ 找出并分类临界点 (这是一个任务)
✗ 使用拉格朗日乘数法求最大值 (这是一个指令)
以 JSON 格式返回:{{"queries": ["知识点1", "知识点2", ...]}}, 包含恰好 {num_queries} 个知识点名称。
@@ -0,0 +1,33 @@
system: |
你是出题流程中的 Validator。
你需要验证题目质量与要求对齐度,并给出 approve/reject 决策。
你还需要判断是否有必要运行验证代码来辅助验证答案。
validate: |
Template:
{template}
生成的 Q-A 对:
{qa_pair}
是否有验证代码可用:{has_code}
校验清单:
- 题目是否对齐 template 的 concentration?
- 难度是否匹配?
- 答案是否正确且与解析一致?
- 选择题是否只有一个正确选项?
- 输出是否清晰、完整?
关于代码验证的判断:
- 仅在以下情况将 needs_code_check 设为 true:有验证代码可用,且题目类型
适合计算验证(如编程题、数学题、算法题)。
- 以下情况设为 false:概念题、论述题、定义题或纯理论题——即使提供了验证代码。
仅返回 JSON:
{{
"decision": "approve 或 reject",
"feedback": "若 reject 给出具体重生建议;若 approve 给出简短确认",
"issues": ["问题1", "问题2"],
"needs_code_check": true 或 false
}}
-554
View File
@@ -1,554 +0,0 @@
# Solve Agents - Dual-Loop Problem Solving System
<div align="center">
**Intelligent Problem Solving System Based on Dual-Loop Architecture**
[![Python](https://img.shields.io/badge/Python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
</div>
---
## 📋 Table of Contents
- [System Overview](#system-overview)
- [Quick Start](#quick-start)
- [System Architecture](#system-architecture)
- [Core Modules](#core-modules)
- [Configuration](#configuration)
- [Usage Guide](#usage-guide)
- [Development Guide](#development-guide)
---
## System Overview
This system is an intelligent problem-solving system based on a **dual-loop architecture**, achieving a complete workflow from problem understanding to answer generation through two collaborative loops.
### Dual-Loop Architecture
| Loop | Function | Key Features |
|------|----------|--------------|
| **Analysis Loop** | Deep understanding of user questions | Dynamic research, iterative knowledge collection, automatic stopping |
| **Solve Loop** | Strict solving and answer generation | Block planning, step-by-step execution, quality checking |
### Core Advantages
✅ **Intelligent Research** - Analysis Loop dynamically determines when to stop research
✅ **Block-based Solving** - Solve Loop decomposes complex problems into manageable blocks
✅ **Quality Assurance** - Check Agent automatically checks and corrects errors
✅ **Persistent Memory** - JSON format storage, supports checkpoint resumption
✅ **Citation Management** - Automatic citation management and formatting
✅ **Tool Integration** - RAG, Web Search, Code Execution
---
## Quick Start
### Install Dependencies & Configure Environment
```bash
pip install -r requirements.txt
# .env file (project root directory)
LLM_API_KEY=your_api_key
LLM_HOST=https://api.openai.com/v1
LLM_MODEL=gpt-4o # Optional
PERPLEXITY_API_KEY=... # Optional, enable Web search
```
### Basic Usage (Python API)
```python
import asyncio
import os
from solve_agents import MainSolver
async def main():
solver = MainSolver(
kb_name="ai_textbook",
api_key=os.getenv("LLM_API_KEY"),
base_url=os.getenv("LLM_HOST"),
)
result = await solver.solve(
question="What is linear convolution?",
verbose=True
)
print(f"📁 Output directory: {result['metadata']['output_dir']}")
print(f"📊 Analysis iterations: {result['analysis_iterations']} rounds")
print(f"📊 Solve steps: {result['solve_steps']} steps")
print(f"📝 Markdown: {result['output_md']}")
asyncio.run(main())
```
### Using Command Line Tool
```bash
cd DeepTutor/student_TA
python start.py # CLI currently defaults to dual-loop Solve mode
```
---
## System Architecture
### Overall Flow
```
User Question
│
▼
┌─────────────────────────────────────────────────────────────┐
│ MainSolver │
│ │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ Analysis Loop (Analysis Loop) │ │
│ │ │ │
│ │ ┌──────────┐ ┌──────────┐ │ │
│ │ │Investigate│ -> │ Note │ │ │
│ │ └──────────┘ └──────────┘ │ │
│ │ ▲ │ │ │
│ │ └─────────────┴───────────────┐ │ │
│ │ │ │ │
│ │ Stop condition met │ │
│ │ │ │ │
│ │ InvestigateMemory │ │
│ └───────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ Solve Loop (Solving Loop) │ │
│ │ │ │
│ │ ┌──────┐ ┌─────────┐ ┌──────┐ ┌───────┐ │ │
│ │ │ Plan │ -> │ Manager │ -> │Solve │ -> │ Check │ │ │
│ │ └──────┘ └─────────┘ └──────┘ └───────┘ │ │
│ │ │ │ │ │
│ │ └───────────┘ │ │
│ │ Loop until completion │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌────────┐ │ │
│ │ │ Format │ │ │
│ │ └────────┘ │ │
│ │ │ │ │
│ │ SolveMemory │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
│ Final Answer │
└─────────────────────────────────────────────────────────────┘
```
### Directory Structure
```
solve_agents/
├── main_solver.py # Main controller
├── base_agent.py # Agent base class
├── config.yaml # Configuration file
│
├── analysis_loop/ # Analysis Loop ⭐
│ ├── investigate_agent.py # Research Agent
│ ├── note_agent.py # Note Agent
│ └── README.md # Detailed documentation
│
├── solve_loop/ # Solve Loop ⭐
│ ├── plan_agent.py # Planning Agent
│ ├── manager_agent.py # Manager Agent
│ ├── solve_agent.py # Solving Agent
│ ├── tool_agent.py # Tool execution Agent
│ ├── response_agent.py # Aggregate tool results
│ ├── check_agent.py # Quality checking
│ ├── precision_answer_agent.py # Precision answer (optional)
│ ├── citation_manager.py # Citation manager
│ └── README.md # Detailed documentation
│
├── memory/ # Memory system ⭐
│ ├── investigate_memory.py # Analysis Loop memory
│ └── solve_memory.py # Solve Loop memory
│
├── utils/ # Utility modules
│ ├── logger.py # Logging system
│ ├── performance_monitor.py # Performance monitoring
│ ├── config_validator.py # Configuration validation
│ ├── json_utils.py # JSON utilities
│ ├── tag_parser.py # Tag parser
│ └── error_handler.py # Error handling
│
└── prompts/ # Prompt templates
├── analysis_loop/ # Analysis Loop Prompts
└── solve_loop/ # Solve Loop Prompts
```
---
## Core Modules
### Analysis Loop (Analysis Loop)
**Function**: Deep understanding of user questions
**Agents**:
- **InvestigateAgent**: Based on knowledge chain, outputs multiple queries at once and calls tools, generates `cite_id → raw_result`
- **NoteAgent**: Processes new `cite_id` one by one, generates summary and citations
**Memory**: `InvestigateMemory` (JSON)
**Detailed Documentation**: [analysis_loop/README.md](analysis_loop/README.md)
### Solve Loop (Solving Loop)
**Function**: Strict solving and answer generation
**Agents**:
- **PlanAgent**: Generates problem-solving plan (blocks)
- **ManagerAgent**: Arranges specific steps (steps) for each block
- **SolveAgent**: Calls tools and writes reasoning according to steps
- **ToolAgent**: Unified encapsulation of RAG / Web Search / Code Execution / Query Item tools
- **ResponseAgent**: Organizes outputs from SolveAgent and ToolAgent
- **CheckAgent**: Automatically checks steps and provides correction suggestions
- **PrecisionAnswerAgent**: Generates precision answer summary (optional)
**Memory**: `SolveMemory` (JSON)
**Detailed Documentation**: [solve_loop/README.md](solve_loop/README.md)
### Memory System
**InvestigateMemory**:
```python
{
"user_question": "...",
"knowledge_chain": [...], # Collected knowledge
"reflections": {...}, # Reserved field, currently only records remaining questions (default empty)
"metadata": {...} # Statistics
}
```
**SolveMemory**:
```python
{
"user_question": "...",
"plan": {
"blocks": [...] # Problem-solving plan
},
"progress": {...}, # Execution progress
"metadata": {...} # Statistics
}
```
### Tool System
ToolAgent aggregates multiple capabilities and automatically chains them step by step:
- **RAG Search**: Retrieves KBs from `knowledge_bases/`
- **Web Search**: Expands latest materials based on Perplexity API
- **Query Item**: Quickly references formulas / theorems by number
- **Code Execution**: Runs Python in sandbox, results written to `artifacts/`
---
## Configuration
### config.yaml Structure
```yaml
system:
output_base_dir: "./user/solve"
save_intermediate_results: true
output_language: "English" # or Chinese
max_analysis_iterations: 5
max_solve_correction_iterations: 3
logging:
level: "INFO"
save_to_file: true
console_output: true
log_dir: "./logs"
monitoring:
enabled: true
track_token_usage: true
track_time: true
save_dir: "./logs/performance"
llm:
max_retries: 3
timeout: 120
max_tokens: 8192
agents:
investigate_agent:
temperature: 0.4
max_iterations: 3
note_agent:
max_tokens: 4096
manager_agent: {}
solve_agent:
max_tokens: 8192
tool_agent: {}
response_agent:
max_tokens: 8192
enabled: false
max_tokens: 8192
precision_answer_agent:
enabled: true
temperature: 0.2
tools:
rag_tool:
kb_base_dir: "./knowledge_bases"
default_kb: "ai_textbook"
web_search:
enabled: true
max_results: 5
query_item:
enabled: true
run_code:
enabled: true
timeout: 10
workspace: "./student_TA/cache/run_code_workspace"
```
---
## Usage Guide
### Basic Usage
```python
from solve_agents import MainSolver
# Create solver
solver = MainSolver(
kb_name="ai_textbook", # Knowledge base name
config_path=None, # Use default configuration
api_key=None, # Read from environment variables
base_url=None # Read from environment variables
)
# Solve problem
result = await solver.solve(
question="Your question",
verbose=True # Print detailed logs
)
# View results
print(result['output_md']) # final_answer.md
print(result['output_json']) # solve_chain.json (steps + tool logs)
print(result['final_answer']) # String, may contain precision answer
print(len(result['citations'])) # Number of citations
```
### Output Files
```
user/solve/solve_20251116_160009/
├── investigate_memory.json # Analysis Loop memory
├── solve_chain.json # Solve Loop steps & tool records ⭐
├── citation_memory.json # Citation management
├── final_answer.md # Final answer (Markdown)
├── performance_report.json # Performance monitoring
├── cost_report.json # Optional: token cost
├── search_*.json # Search cache (if any)
└── artifacts/ # Code execution output
```
### View Statistics
```python
result = await solver.solve(question)
# Analysis Loop statistics
print(f"Analysis iterations: {result['analysis_iterations']} rounds")
print(f"Coverage rate: {result['metadata']['coverage_rate']:.2%}")
print(f"Average confidence: {result['metadata']['avg_confidence']:.2%}")
# Solve Loop statistics
print(f"Solve completed steps: {result['solve_steps']} / {result['metadata']['total_steps']}")
print(f"Number of citations: {len(result['citations'])}")
```
### Debug Mode
```python
# Enable detailed logging
import logging
logging.basicConfig(level=logging.DEBUG)
# View memory files
import json
output_dir = result['metadata']['output_dir']
with open(f'{output_dir}/investigate_memory.json', encoding='utf-8') as f:
memory = json.load(f)
print(json.dumps(memory, indent=2, ensure_ascii=False))
```
---
## Development Guide
### Extending New Agent
1. **Inherit BaseAgent**:
```python
from solve_agents.base_agent import BaseAgent
class MyAgent(BaseAgent):
def __init__(self, config, api_key, base_url):
super().__init__(config, api_key, base_url, 'my_agent')
async def process(self, **kwargs):
# Implement processing logic
# Prompts are auto-loaded via unified PromptManager
system_prompt = self.get_prompt("system")
response = await self.call_llm(user_prompt, system_prompt)
return self.parse_response(response)
```
2. **Add Prompt**:
Define Prompt in `prompts/analysis_loop/my_agent.yaml` or `prompts/solve_loop/my_agent.yaml`.
3. **Register to MainSolver**:
Initialize in the `_init_agents()` method of `main_solver.py`.
4. **Add Configuration**:
Add Agent configuration in `config.yaml`.
### Extending Memory System
```python
from dataclasses import dataclass, asdict
import json
@dataclass
class MyMemory:
user_question: str
data: dict
def save(self, output_dir: str):
with open(f"{output_dir}/my_memory.json", 'w') as f:
json.dump(asdict(self), f, ensure_ascii=False, indent=2)
@classmethod
def load_or_create(cls, output_dir: str, user_question: str):
path = f"{output_dir}/my_memory.json"
if os.path.exists(path):
with open(path) as f:
data = json.load(f)
return cls(**data)
return cls(user_question=user_question, data={})
```
### Adding New Tool
```python
# Create new tool in tools/ directory
class MyTool:
def __init__(self, config):
self.config = config
async def execute(self, **kwargs):
# Implement tool logic
return result
# Register in SolveAgent
self.tools['my_tool'] = MyTool(config)
```
---
## Performance Optimization
### Adjust Iteration Count
```yaml
system:
max_analysis_iterations: 3 # Reduce Analysis iterations
max_solve_correction_iterations: 2 # Reduce Solve retries
```
### Use Faster Model
```yaml
agents:
investigate_agent:
model: "gpt-3.5-turbo" # Use faster model
```
### Disable Optional Features
```yaml
agents:
precision_answer_agent:
enabled: false # Disable precision answer
```
---
## FAQ
**Q: How to adjust the iteration count of Analysis Loop?**
Set `system.max_analysis_iterations` in `config.yaml`.
**Q: How to enable precision answer feature?**
Set `agents.precision_answer_agent.enabled: true` in `config.yaml`.
**Q: How to view detailed execution logs?**
Set `logging.level: "DEBUG"` or enable `verbose=True` in code.
**Q: Where are the memory files?**
In the `{output_base_dir}/solve_{timestamp}/` directory.
**Q: How to reset citation numbers?**
```python
from solve_agents.solve_loop.citation_manager import CitationManager
CitationManager().reset()
```
**Q: What to do if code execution times out?**
Adjust the `agents.code_agent.timeout` configuration.
---
## Version History
- **v3.0** (2025-11-16) - Dual-loop architecture refactoring
- ✅ Complete refactoring to dual-loop architecture
- ✅ Remove old Router, Deep Analysis, Deep Solve modules
- ✅ Introduce dynamic memory system
- ✅ Optimize tool calling and citation management
- ✅ Simplify configuration and usage flow
- ✅ Merge utils and parsers modules
---
## Related Documentation
- [Analysis Loop Detailed Documentation](analysis_loop/README.md)
- [Solve Loop Detailed Documentation](solve_loop/README.md)
- [Configuration File Documentation](config.yaml)
---
## License
MIT License
---
**Made with ❤️ by DeepTutor Team**
+1 -81
View File
@@ -1,92 +1,12 @@
#!/usr/bin/env python
"""
Solve Agent System - Dual-Loop Architecture
Analysis Loop + Solve Loop
Solve Agent — Plan -> ReAct -> Write architecture.
"""
from pathlib import Path
import sys
# Add project root to path for logs import
_project_root = Path(__file__).parent.parent.parent.parent
if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
# Infrastructure
from src.agents.base_agent import BaseAgent
from src.logging import Logger, get_logger
from .utils import (
ConfigValidator,
PerformanceMonitor,
)
# Backwards compatibility
SolveAgentLogger = Logger
# Memory system
# Analysis loop
from .analysis_loop import (
InvestigateAgent,
NoteAgent,
)
# Main controller
from .main_solver import MainSolver
from .memory import (
InvestigateMemory,
KnowledgeItem,
Reflections,
SolveChainStep,
SolveMemory,
SolveOutput,
TodoItem,
ToolCallRecord,
)
# Session management
from .session_manager import SolverSessionManager, get_solver_session_manager
# Solve loop
from .solve_loop import (
ManagerAgent,
PrecisionAnswerAgent,
ResponseAgent,
SolveAgent,
SolveNoteAgent,
ToolAgent,
)
__all__ = [
# Infrastructure
"BaseAgent",
"Logger",
"get_logger",
"SolveAgentLogger", # Backwards compatibility
"PerformanceMonitor",
"ConfigValidator",
# Memory system
"InvestigateMemory",
"KnowledgeItem",
"Reflections",
"SolveMemory",
"TodoItem",
"SolveOutput",
"ToolCallRecord",
"SolveChainStep", # Backward compatibility
# Analysis Loop
"InvestigateAgent",
"NoteAgent",
# Solve Loop
"ManagerAgent",
"SolveAgent",
"SolveNoteAgent",
"ResponseAgent",
"PrecisionAnswerAgent",
"ToolAgent",
# Main Controller
"MainSolver",
# Session Management
"SolverSessionManager",
"get_solver_session_manager",
]
+7
View File
@@ -0,0 +1,7 @@
"""Solve Agent — three-agent architecture."""
from .planner_agent import PlannerAgent
from .solver_agent import SolverAgent
from .writer_agent import WriterAgent
__all__ = ["PlannerAgent", "SolverAgent", "WriterAgent"]
+171
View File
@@ -0,0 +1,171 @@
"""
PlannerAgent — Decomposes the user question into ordered solving steps.
Called once at the start (Phase 1) and optionally on replan requests.
"""
from __future__ import annotations
from typing import Any
from src.agents.base_agent import BaseAgent
from ..memory.scratchpad import Plan, PlanStep, Scratchpad
from ..utils.json_utils import extract_json_from_text
# Tools description injected into the prompt
TOOLS_DESCRIPTION = """\
- rag_search: Search the uploaded knowledge base (textbooks, lecture notes, etc.)
- web_search: Search the internet for external information
- code_execute: Execute Python code in a sandbox (calculations, plotting, data processing)"""
class PlannerAgent(BaseAgent):
"""Generates a high-level solving plan from the user question."""
def __init__(
self,
config: dict[str, Any] | None = None,
api_key: str | None = None,
base_url: str | None = None,
api_version: str | None = None,
token_tracker: Any | None = None,
language: str = "en",
) -> None:
super().__init__(
module_name="solve",
agent_name="planner_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
config=config or {},
token_tracker=token_tracker,
language=language,
)
async def process(
self,
question: str,
scratchpad: Scratchpad,
kb_name: str = "",
replan: bool = False,
) -> Plan:
"""Generate or revise the solving plan.
Args:
question: The user's original question.
scratchpad: Current scratchpad state.
kb_name: Knowledge base name (informational).
replan: If True, this is a replan request — include progress so far.
Returns:
A Plan object with ordered steps.
"""
system_prompt = self._build_system_prompt()
user_prompt = self._build_user_prompt(question, scratchpad, kb_name, replan)
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
stage="plan" if not replan else "replan",
)
return self._parse_plan(response, scratchpad if replan else None)
# ------------------------------------------------------------------
# Prompt construction
# ------------------------------------------------------------------
def _build_system_prompt(self) -> str:
prompt = self.get_prompt("system") if self.has_prompts() else None
if prompt:
return prompt
# Fallback if prompt file is missing
return (
"You are a problem-solving planner. Analyze the user's question and "
"decompose it into ordered steps. Each step should be a verifiable sub-goal "
"describing WHAT to establish, not HOW. Do not specify tools. "
"Simple questions need only 1 step; complex ones may need 3-6 steps. "
"Output strict JSON: {\"analysis\": \"...\", \"steps\": [{\"id\": \"S1\", "
"\"goal\": \"...\"}]}"
)
def _build_user_prompt(
self,
question: str,
scratchpad: Scratchpad,
kb_name: str,
replan: bool,
) -> str:
template = self.get_prompt("user_template") if self.has_prompts() else None
# Build scratchpad summary for replan
scratchpad_summary = "(initial plan — no progress yet)"
if replan and scratchpad.plan:
parts: list[str] = []
for step in scratchpad.plan.steps:
entries = scratchpad.get_entries_for_step(step.id)
notes = " | ".join(e.self_note for e in entries if e.self_note)
status_label = step.status.upper()
parts.append(f"[{step.id}] ({status_label}) {step.goal}")
if notes:
parts.append(f" Notes: {notes}")
# Include the replan reason from the last entry
if scratchpad.entries:
last = scratchpad.entries[-1]
if last.action == "replan" and last.action_input:
parts.append(f"\nReplan reason: {last.action_input}")
scratchpad_summary = "\n".join(parts)
tools_desc = TOOLS_DESCRIPTION
if kb_name:
tools_desc = tools_desc.replace(
"the uploaded knowledge base",
f'the knowledge base "{kb_name}"',
)
if template:
return template.format(
question=question,
tools_description=tools_desc,
scratchpad_summary=scratchpad_summary,
)
# Fallback
return (
f"## Question\n{question}\n\n"
f"## Available Tools\n{tools_desc}\n\n"
f"## Progress So Far\n{scratchpad_summary}"
)
# ------------------------------------------------------------------
# Response parsing
# ------------------------------------------------------------------
def _parse_plan(self, response: str, old_scratchpad: Scratchpad | None) -> Plan:
"""Parse LLM JSON response into a Plan object."""
data = extract_json_from_text(response)
if not data or not isinstance(data, dict):
# Graceful fallback: single-step plan
return Plan(
analysis="Failed to parse plan; using single-step fallback.",
steps=[PlanStep(id="S1", goal="Answer the question directly")],
)
analysis = data.get("analysis", "")
raw_steps = data.get("steps", [])
steps: list[PlanStep] = []
for i, s in enumerate(raw_steps):
step_id = s.get("id", f"S{i + 1}")
goal = s.get("goal", "")
tools_hint = s.get("tools_hint", [])
if isinstance(tools_hint, str):
tools_hint = [tools_hint]
steps.append(PlanStep(id=step_id, goal=goal, tools_hint=tools_hint))
if not steps:
steps = [PlanStep(id="S1", goal="Answer the question")]
return Plan(analysis=analysis, steps=steps)
+148
View File
@@ -0,0 +1,148 @@
"""
SolverAgent — ReAct agent that iteratively gathers information for each plan step.
For every step in the plan, the SolverAgent runs a think-act-observe loop:
1. THINK — reason about what information is still missing
2. ACT — choose a tool (rag_search | web_search | code_execute | done | replan)
3. OBSERVE — the tool result is appended to the Scratchpad (outside this agent)
The agent outputs a single JSON decision per call.
"""
from __future__ import annotations
from typing import Any
from src.agents.base_agent import BaseAgent
from ..memory.scratchpad import PlanStep, Scratchpad
from ..utils.json_utils import extract_json_from_text
VALID_ACTIONS = {"rag_search", "web_search", "code_execute", "done", "replan"}
class SolverAgent(BaseAgent):
"""ReAct reasoning agent — one LLM call per iteration."""
def __init__(
self,
config: dict[str, Any] | None = None,
api_key: str | None = None,
base_url: str | None = None,
api_version: str | None = None,
token_tracker: Any | None = None,
language: str = "en",
) -> None:
super().__init__(
module_name="solve",
agent_name="solver_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
config=config or {},
token_tracker=token_tracker,
language=language,
)
async def process(
self,
question: str,
current_step: PlanStep,
scratchpad: Scratchpad,
) -> dict[str, str]:
"""Run one ReAct iteration for the given plan step.
Returns:
dict with keys: thought, action, action_input, self_note
"""
system_prompt = self._build_system_prompt()
user_prompt = self._build_user_prompt(question, current_step, scratchpad)
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
stage=f"solve_{current_step.id}",
)
return self._parse_decision(response)
# ------------------------------------------------------------------
# Prompt construction
# ------------------------------------------------------------------
def _build_system_prompt(self) -> str:
prompt = self.get_prompt("system") if self.has_prompts() else None
if prompt:
return prompt
# Fallback
return (
"You are a ReAct problem-solving agent. For the current step, decide what "
"action to take next. Output strict JSON with keys: thought, action, "
"action_input, self_note.\n\n"
"Available actions:\n"
"- rag_search: search the knowledge base. action_input = query string\n"
"- web_search: search the web. action_input = query string\n"
"- code_execute: run Python code. action_input = what to compute\n"
"- done: current step has enough information. action_input = \"\"\n"
"- replan: the plan needs revision. action_input = reason\n\n"
"self_note: write a 1-sentence summary of what you learned this round."
)
def _build_user_prompt(
self,
question: str,
current_step: PlanStep,
scratchpad: Scratchpad,
) -> str:
template = self.get_prompt("user_template") if self.has_prompts() else None
ctx = scratchpad.build_solver_context(current_step.id)
current_step_text = f"[{current_step.id}] {current_step.goal}"
if template:
return template.format(
question=question,
plan=ctx["plan"],
current_step=current_step_text,
step_history=ctx["step_history"],
previous_knowledge=ctx["previous_knowledge"],
)
# Fallback
return (
f"## Original Question\n{question}\n\n"
f"## Plan\n{ctx['plan']}\n\n"
f"## Current Step\n{current_step_text}\n\n"
f"## Previous Actions for This Step\n{ctx['step_history']}\n\n"
f"## Knowledge from Previous Steps\n{ctx['previous_knowledge']}"
)
# ------------------------------------------------------------------
# Response parsing
# ------------------------------------------------------------------
def _parse_decision(self, response: str) -> dict[str, str]:
"""Parse the LLM JSON response into a decision dict."""
data = extract_json_from_text(response)
if not data or not isinstance(data, dict):
# If parsing completely fails, default to done
return {
"thought": "Failed to parse response; ending step.",
"action": "done",
"action_input": "",
"self_note": "Parse error — defaulting to done.",
}
action = str(data.get("action", "done")).strip().lower()
if action not in VALID_ACTIONS:
action = "done"
return {
"thought": str(data.get("thought", "")),
"action": action,
"action_input": str(data.get("action_input", "")),
"self_note": str(data.get("self_note", "")),
}
+315
View File
@@ -0,0 +1,315 @@
"""
WriterAgent — Generates the final structured answer from the Scratchpad.
Supports two modes:
- **Simple** (`process`): single LLM call producing the complete answer.
- **Detailed / Iterative** (`process_iterative`): step-by-step incremental
writing that processes evidence in chunks, then generates a concise answer.
"""
from __future__ import annotations
from typing import Any
from src.agents.base_agent import BaseAgent
from ..memory.scratchpad import Scratchpad
class WriterAgent(BaseAgent):
"""Produces the final answer from accumulated evidence."""
def __init__(
self,
config: dict[str, Any] | None = None,
api_key: str | None = None,
base_url: str | None = None,
api_version: str | None = None,
token_tracker: Any | None = None,
language: str = "en",
) -> None:
super().__init__(
module_name="solve",
agent_name="writer_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
config=config or {},
token_tracker=token_tracker,
language=language,
)
# ==================================================================
# Simple mode — single-shot writing
# ==================================================================
async def process(
self,
question: str,
scratchpad: Scratchpad,
language: str = "en",
preference: str = "",
) -> str:
"""Generate the final Markdown answer in a single LLM call.
Args:
question: Original user question.
scratchpad: Completed scratchpad with all evidence.
language: Output language hint (e.g. "en", "zh").
preference: Optional personalisation context.
Returns:
Markdown-formatted answer string.
"""
system_prompt = self._build_system_prompt()
user_prompt = self._build_user_prompt(question, scratchpad, language, preference)
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
max_tokens=self.get_max_tokens() or 8192,
stage="write",
)
return response.strip()
# ==================================================================
# Detailed / Iterative mode
# ==================================================================
async def process_iterative(
self,
question: str,
scratchpad: Scratchpad,
language: str = "en",
preference: str = "",
) -> str:
"""Generate a detailed answer through iterative step-by-step writing.
Flow:
Iteration 1 : evidence(S1) + evidence(S2) → draft_1
Iteration 2 : draft_1 + evidence(S3) → draft_2
...
Final : draft_N → concise_answer
Output : concise_answer + "---" + draft_N
Args:
question: Original user question.
scratchpad: Completed scratchpad with all evidence.
language: Output language hint.
preference: Optional personalisation context.
Returns:
Combined Markdown string: concise answer + detailed answer.
"""
if scratchpad.plan is None:
# Fallback: no plan, use simple mode
return await self.process(question, scratchpad, language, preference)
# Collect completed/in_progress steps that have entries
steps_with_evidence = []
for step in scratchpad.plan.steps:
if step.status in ("completed", "in_progress"):
entries = scratchpad.get_entries_for_step(step.id)
# Only include steps with actual tool observations
evidence_entries = [e for e in entries if e.action not in ("done", "replan") and e.observation]
if evidence_entries:
steps_with_evidence.append((step, evidence_entries))
if not steps_with_evidence:
return await self.process(question, scratchpad, language, preference)
sources_text = scratchpad.format_sources_markdown()
# --- Iterative draft building ---
draft = ""
for i, (step, entries) in enumerate(steps_with_evidence):
step_evidence = self._format_step_evidence(step, entries)
if i == 0:
# First iteration: if there's a second step, bundle it
if len(steps_with_evidence) > 1:
step2, entries2 = steps_with_evidence[1]
step_evidence += "\n\n---\n\n" + self._format_step_evidence(step2, entries2)
draft = await self._write_draft(
question=question,
previous_draft="(this is the first draft — no previous draft)",
new_evidence=step_evidence,
sources=sources_text,
language=language,
iteration=i + 1,
)
elif i == 1:
# Second step was already bundled in iteration 0; skip
continue
else:
# Subsequent iterations: previous draft + new step evidence
draft = await self._write_draft(
question=question,
previous_draft=draft,
new_evidence=step_evidence,
sources=sources_text,
language=language,
iteration=i,
)
# --- Concise answer generation ---
concise = await self._write_concise(
question=question,
detailed_answer=draft,
language=language,
)
# --- Assemble final output ---
final = f"## Summary\n\n{concise}\n\n---\n\n{draft}"
return final
# ------------------------------------------------------------------
# Internal helpers for iterative mode
# ------------------------------------------------------------------
async def _write_draft(
self,
question: str,
previous_draft: str,
new_evidence: str,
sources: str,
language: str,
iteration: int,
) -> str:
"""Run one iteration of the incremental draft builder."""
system_prompt = self._get_iterative_system_prompt()
template = self.get_prompt("iterative_user_template") if self.has_prompts() else None
if template:
user_prompt = template.format(
question=question,
previous_draft=previous_draft,
new_evidence=new_evidence,
sources=sources or "(no external sources)",
language=language,
)
else:
user_prompt = (
f"## Question\n{question}\n\n"
f"## Previous Draft\n{previous_draft}\n\n"
f"## New Evidence\n{new_evidence}\n\n"
f"## Available Sources\n{sources or '(none)'}\n\n"
f"## Language\n{language}"
)
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
max_tokens=self.get_max_tokens() or 8192,
stage=f"write_iter_{iteration}",
)
return response.strip()
async def _write_concise(
self,
question: str,
detailed_answer: str,
language: str,
) -> str:
"""Generate a concise answer from the completed detailed draft."""
system_prompt = self._get_concise_system_prompt()
template = self.get_prompt("concise_user_template") if self.has_prompts() else None
if template:
user_prompt = template.format(
question=question,
detailed_answer=detailed_answer,
language=language,
)
else:
user_prompt = (
f"## Question\n{question}\n\n"
f"## Detailed Answer\n{detailed_answer}\n\n"
f"## Language\n{language}"
)
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
max_tokens=1024,
stage="write_concise",
)
return response.strip()
@staticmethod
def _format_step_evidence(step, entries) -> str:
"""Format raw observations from a step into a single evidence block."""
parts = [f"### Step {step.id}: {step.goal}"]
for e in entries:
block = (
f"**Action**: {e.action}({e.action_input})\n"
f"**Observation**:\n{e.observation}"
)
parts.append(block)
return "\n\n".join(parts)
# ------------------------------------------------------------------
# Prompt construction
# ------------------------------------------------------------------
def _build_system_prompt(self) -> str:
prompt = self.get_prompt("system") if self.has_prompts() else None
if prompt:
return prompt
return (
"You are an expert answer writer. Write a structured, comprehensive answer "
"based on gathered evidence. Use Markdown with proper headings. "
"All math must use LaTeX: inline $...$ and block $$...$$. "
"Cite sources inline as [source-id]. Include a ## References section at the end."
)
def _get_iterative_system_prompt(self) -> str:
prompt = self.get_prompt("iterative_system") if self.has_prompts() else None
if prompt:
return prompt
return (
"You are an expert answer writer building an answer incrementally. "
"You receive a previous draft and new evidence. Expand and refine the draft "
"by integrating the new evidence. Use Markdown, LaTeX for math, and cite sources."
)
def _get_concise_system_prompt(self) -> str:
prompt = self.get_prompt("concise_system") if self.has_prompts() else None
if prompt:
return prompt
return (
"Produce a concise answer (2-4 sentences) for the question based on the "
"detailed answer. If it's a multiple-choice or fill-in-the-blank question, "
"give the direct answer first."
)
def _build_user_prompt(
self,
question: str,
scratchpad: Scratchpad,
language: str,
preference: str,
) -> str:
template = self.get_prompt("user_template") if self.has_prompts() else None
scratchpad_content = scratchpad.build_writer_context()
sources_text = scratchpad.format_sources_markdown()
if template:
return template.format(
question=question,
scratchpad_content=scratchpad_content,
sources=sources_text or "(no external sources)",
preference=preference or "(no specific preference)",
language=language,
)
return (
f"## Question\n{question}\n\n"
f"## Gathered Evidence\n{scratchpad_content}\n\n"
f"## Available Sources\n{sources_text or '(none)'}\n\n"
f"## User Preference\n{preference or '(none)'}\n\n"
f"## Language\n{language}"
)
-295
View File
@@ -1,295 +0,0 @@
# Analysis Loop - Deep Research Phase
## Overview
Analysis Loop is the first phase of the dual-loop architecture, responsible for **deeply understanding user questions**. Through iterative research, it dynamically collects and organizes knowledge until the question is sufficiently understood.
## Architecture
```
┌─────────────────────────────────────────┐
│ Analysis Loop (Research Phase) │
│ │
│ ┌──────────┐ ┌──────────┐ │
│ │Investigate│ -> │ Note │ ────┐ │
│ └──────────┘ └──────────┘ │ │
│ ▲ │ │ │
│ └────────────┴─────────────┘ │
│ │ │
│ Stop Condition Met │
│ │ │
│ ▼ │
│ InvestigateMemory │
└─────────────────────────────────────────┘
```
## Core Agents
### 1. InvestigateAgent
**Role**: Research planner and tool executor. Based on knowledge chain summaries and user questions, generates multiple high-value queries and calls tools to retrieve raw data.
**Key Features**:
1. Identifies knowledge gaps from cite_id summaries; generates multiple `[TOOL]tool_type | query` commands in one pass if needed.
2. Immediately calls tools (`rag_naive`, `rag_hybrid`, `web_search`, `query_item`) for each query to get `raw_result`.
3. When `[TOOL] none` appears, knowledge is sufficient and Analysis Loop automatically stops.
**Output Structure**:
```python
{
'reasoning': 'List of knowledge gaps identified this round',
'should_stop': False,
'knowledge_item_ids': ['c01', 'c02'], # List of new cite_ids this round
'actions': [
{'tool_type': 'rag_hybrid', 'query': 'Section 2.5...', 'cite_id': 'c01'},
{'tool_type': 'rag_naive', 'query': 'Lambda range in algorithm', 'cite_id': 'c02'}
]
}
```
### 2. NoteAgent
**Role**: Note-taker. For each knowledge item in `knowledge_item_ids`, sequentially calls LLM to convert `raw_result` into summaries and extract citations.
**Key Features**:
1. Automatically iterates through multiple knowledge items in one round, independently constructing Prompt → LLM → parsing summary.
2. Summaries must be concise and extract citable sources from `raw_result`.
3. After processing, updates `InvestigateMemory` and `CitationMemory` for use by Solve Loop.
**Output Structure**:
```python
{
'success': True,
'processed_items': 2,
'details': [
{'cite_id': 'c01', 'citations_count': 2},
{'cite_id': 'c02', 'citations_count': 1}
],
'failed': []
}
```
## Memory System
### InvestigateMemory
Persistent JSON structure that chains all knowledge collected during the analysis phase. Each tool call generates a unique `cite_id` and is recorded in `knowledge_chain`.
**Structure**:
```python
{
"user_question": "What is linear convolution?",
"knowledge_chain": [
{
"cite_id": "c01",
"tool_type": "rag_hybrid",
"query": "Section 2.5 Linear convolution definition and properties",
"raw_result": "...RAG source text...",
"summary": "Linear convolution derives from convolution integral; core properties include commutativity and associativity.",
"created_at": "...",
"updated_at": "..."
}
],
"reflections": {
"remaining_questions": [],
"updated_at": "..."
},
"metadata": {
"total_iterations": 2,
"total_knowledge_items": 1,
"coverage_rate": 1.0,
"avg_confidence": 0.9
}
}
```
**Storage Location**: `{output_dir}/investigate_memory.json`
## Configuration
Configure Analysis Loop in `config.yaml`:
```yaml
system:
max_analysis_iterations: 5 # Maximum iterations
agents:
investigate_agent:
enabled: true
model: "gpt-4o"
temperature: 0.4
note_agent:
enabled: true
model: "gpt-4o"
temperature: 0.3
```
## Usage Example
```python
from solve_agents.memory import InvestigateMemory
from solve_agents.analysis_loop import InvestigateAgent, NoteAgent
memory = InvestigateMemory.load_or_create(
output_dir="./output",
user_question="What is linear convolution?"
)
investigate_agent = InvestigateAgent(config, api_key, base_url)
note_agent = NoteAgent(config, api_key, base_url)
for i in range(max_iterations):
investigate_result = await investigate_agent.process(
question=question,
memory=memory,
citation_memory=citation_memory,
kb_name="ai_textbook",
output_dir="./output"
)
cite_ids = investigate_result.get('knowledge_item_ids', [])
if cite_ids:
await note_agent.process(
question=question,
memory=memory,
new_knowledge_ids=cite_ids,
citation_memory=citation_memory,
output_dir="./output"
)
if investigate_result.get('should_stop'):
break
memory.save()
```
## Workflow Example
**Question**: "What is linear convolution?"
**Round 1**:
1. **Investigate**: Outputs two queries
- `[TOOL]rag_hybrid | Linear convolution definition`
- `[TOOL]rag_naive | Geometric interpretation of convolution`
Gets cite_ids `c01/c02`.
2. **Note**: Processes `c01/c02` sequentially, generates summaries and extracts 3 citations.
**Round 2**:
1. **Investigate**: Outputs
- `[TOOL]rag_hybrid | Convolution calculation examples`
- `[TOOL]web_search | Latest application scenarios`
Gets cite_ids `c03/c04`.
2. **Note**: Processes `c03/c04`, supplements calculation procedures and practical examples.
**Round 3**:
1. **Investigate**: `[TOOL]none` - reasoning: "Definition, derivation, and examples all covered".
2. Analysis Loop completes.
**Result**: Collects 4 knowledge items; NoteAgent automatically updates summaries and citations; ready for Solve Loop consumption.
## Key Features
### 1. Dynamic Research
- No preset query count
- Dynamically determines based on actual needs
- Automatically judges when to stop
### 2. Tool Selection
- Prioritizes knowledge base (RAG)
- Uses web search when necessary
- Intelligently selects most appropriate tools
### 3. Citation Management
- Automatically extracts key citations
- Provides evidence for Solve Loop
- Supports subsequent citation formatting
### 4. Persistent Memory
- JSON format storage
- Supports checkpoint resumption
- Facilitates debugging and review
## Integration with Solve Loop
After Analysis Loop completes, `InvestigateMemory` is passed to Solve Loop:
```python
# Analysis Loop completes
investigate_memory.save()
# Solve Loop consumes
solve_memory = SolveMemory.load_or_create(...)
plan_result = await plan_agent.process(
question=question,
investigate_memory=investigate_memory, # Pass analysis results
solve_memory=solve_memory
)
```
Solve Loop can access:
- `investigate_memory.knowledge_chain`: All collected knowledge
- `investigate_memory.get_all_citations()`: All citations
- `investigate_memory.get_knowledge_summary()`: Knowledge summary
## Debugging and Monitoring
### View Memory Files
```bash
cat output/investigate_memory.json | jq .
```
### Monitor Iteration Progress
Logs display detailed information for each round:
```
--- Analysis Loop Round 1 ---
[Investigate] Reasoning: Still missing calculation examples
• rag_hybrid: Section 2.4 convolution definition -> cite_id=c01
• rag_naive: Geometric interpretation of convolution -> cite_id=c02
[Note] Processed 2 knowledge items
```
### Performance Statistics
```python
metadata = investigate_memory.metadata
print(f"Total iterations: {metadata['total_iterations']} rounds")
print(f"Total knowledge items: {metadata['total_knowledge_items']}")
print(f"Coverage rate: {metadata['coverage_rate']:.2%}")
print(f"Average confidence: {metadata['avg_confidence']:.2f}")
```
## Common Questions
**Q: How to adjust maximum iteration count?**
Set in `config.yaml`:
```yaml
system:
max_analysis_iterations: 5 # Default 5 rounds
```
**Q: How to force web search usage?**
Modify the Investigate Agent prompt or pass parameters when calling.
**Q: How to view extracted citations?**
```python
citations = investigate_memory.get_all_citations()
for citation in citations:
print(citation)
```
**Q: What if memory file becomes too large?**
Periodically clean up `raw_content`, keeping only `summary` and `citations`.
---
**Related Documentation**:
- [Solve Loop README](../solve_loop/README.md)
- [Main README](../README.md)
@@ -1,14 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Analysis Loop - Analysis loop (Investigate → Note)
Deeply understand user questions, collect and organize knowledge
"""
from .investigate_agent import InvestigateAgent
from .note_agent import NoteAgent
__all__ = [
"InvestigateAgent",
"NoteAgent",
]
@@ -1,414 +0,0 @@
#!/usr/bin/env python
"""
InvestigateAgent - Investigator
Generates query actions and calls tools based on current memory and reflections.
"""
from pathlib import Path
import sys
from typing import Any
# Add project root to path
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))
import json
from src.agents.base_agent import BaseAgent
from src.tools import query_numbered_item, rag_search, web_search
from ..memory import CitationMemory, InvestigateMemory, KnowledgeItem
from ..utils.json_utils import extract_json_from_text
class InvestigateAgent(BaseAgent):
"""Investigator Agent - Generates queries and calls tools"""
def __init__(
self,
config: dict[str, Any],
api_key: str,
base_url: str,
api_version: str | None = None,
token_tracker=None,
):
language = config.get("system", {}).get("language", "zh")
super().__init__(
module_name="solve",
agent_name="investigate_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
language=language,
config=config,
token_tracker=token_tracker,
)
# Read web_search enabled config from tools.web_search.enabled
self.enable_web_search = config.get("tools", {}).get("web_search", {}).get("enabled", True)
# Read agent-specific config from solve.agents.investigate_agent
agent_config = config.get("solve", {}).get("agents", {}).get("investigate_agent", {})
self.max_actions_per_round = agent_config.get("max_actions_per_round", 1)
self.max_iterations = agent_config.get("max_iterations", 3)
async def process(
self,
question: str,
memory: InvestigateMemory,
citation_memory: CitationMemory,
kb_name: str = "ai_textbook",
output_dir: str | None = None,
verbose: bool = True,
) -> dict[str, Any]:
"""
Process investigation flow (supports multiple tools per round)
Args:
question: User question
memory: Investigation memory
citation_memory: Citation memory (for registering citations)
kb_name: Knowledge base name
output_dir: Output directory
verbose: Whether to print detailed info
Returns:
dict: Investigation result
{
'reasoning': str,
'should_stop': bool,
'knowledge_item_ids': List[str],
'actions': List[Dict[str, Any]]
}
"""
if citation_memory is None:
raise ValueError(
"citation_memory cannot be None, InvestigateAgent needs it for citation registration"
)
# 1. Build context
context = self._build_context(question, memory)
# 2. Build prompts
system_prompt = self._build_system_prompt()
user_prompt = self._build_user_prompt(context)
# 3. Call LLM
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
verbose=verbose,
response_format={"type": "json_object"},
)
# 4. Parse output (JSON)
parsed_result = extract_json_from_text(response)
if not parsed_result or not isinstance(parsed_result, dict):
self.logger.warning("Parse failed: LLM did not return valid JSON")
return {
"reasoning": "Parse failed: invalid JSON",
"should_stop": True,
"knowledge_item_ids": [],
"actions": [],
}
reasoning = parsed_result.get("reasoning", "")
tool_plans = parsed_result.get("plan", [])
# Ensure tool_plans is a list (handle case where LLM returns dict instead of list)
if not isinstance(tool_plans, list):
if isinstance(tool_plans, dict):
# If plan is a dict, wrap it in a list
self.logger.warning("Parse warning: 'plan' field is a dict, wrapping in list")
tool_plans = [tool_plans]
else:
self.logger.warning(
"Parse warning: 'plan' field is not a list or dict, using empty list"
)
tool_plans = []
# 5. Determine if should stop
should_stop = False
if not tool_plans:
should_stop = True
else:
for plan in tool_plans:
if plan.get("tool") == "none":
should_stop = True
break
if should_stop:
return {
"reasoning": reasoning,
"should_stop": True,
"knowledge_item_ids": [],
"actions": [],
}
# 6. Execute multiple tool calls (limited by max_actions_per_round)
knowledge_ids: list[str] = []
executed_actions: list[dict[str, Any]] = []
# Limit number of actions per round based on config
tool_plans_to_execute = tool_plans[: self.max_actions_per_round]
for plan in tool_plans_to_execute:
tool_type = plan.get("tool")
if not tool_type:
continue
query = plan.get("query", "")
identifier = plan.get("identifier")
if tool_type == "none":
continue
knowledge_item = await self._execute_single_action(
tool_selection=tool_type,
query=query,
identifier=identifier,
kb_name=kb_name,
output_dir=output_dir,
citation_memory=citation_memory,
)
executed_actions.append(
{
"tool_type": tool_type,
"query": query,
"identifier": identifier,
"cite_id": knowledge_item.cite_id if knowledge_item else None,
}
)
if knowledge_item:
memory.add_knowledge(knowledge_item)
knowledge_ids.append(knowledge_item.cite_id)
if knowledge_ids and output_dir:
memory.save()
# 7. Return results
return {
"reasoning": reasoning,
"should_stop": False,
"knowledge_item_ids": knowledge_ids,
"actions": executed_actions,
}
def _build_context(self, question: str, memory: InvestigateMemory) -> dict[str, Any]:
"""Build context (pass full content, no truncation)"""
knowledge_chain_full = []
for item in memory.knowledge_chain:
knowledge_chain_full.append(
{
"cite_id": item.cite_id,
"tool_type": item.tool_type,
"query": item.query,
"raw_result": item.raw_result,
"summary": item.summary,
}
)
remaining_questions_full = []
if memory.reflections and memory.reflections.remaining_questions:
remaining_questions_full = memory.reflections.remaining_questions.copy()
knowledge_chain_summary = (
"\n".join(
f"- {item.cite_id} ({item.tool_type}): {item.summary or item.raw_result[:200]}"
for item in memory.knowledge_chain
)
if memory.knowledge_chain
else "(none)"
)
reflections_summary = (
"\n".join(f"- {q}" for q in remaining_questions_full)
if remaining_questions_full
else "(no remaining questions)"
)
return {
"question": question,
"num_knowledge": len(memory.knowledge_chain),
"knowledge_chain_full": knowledge_chain_full,
"knowledge_chain_summary": knowledge_chain_summary,
"reflections_summary": reflections_summary,
"remaining_questions": remaining_questions_full,
"action_queue": "(no action history)",
}
def _build_system_prompt(self) -> str:
"""Build system prompt"""
prompt = self.get_prompt("system") if self.has_prompts() else None
if not prompt:
raise ValueError(
"InvestigateAgent missing system prompt. Configure in src/agents/solve/prompts/en/analysis_loop/investigate_agent.yaml"
)
# If web_search is disabled, remove web_search related content from prompt
if not self.enable_web_search:
# Get the web_search disabled prompt if available, otherwise filter out web_search lines
web_search_disabled_prompt = (
self.get_prompt("web_search_disabled") if self.has_prompts() else None
)
if web_search_disabled_prompt:
# Replace web_search description with disabled message
prompt = prompt.replace(
self.get_prompt("web_search_description") or "", web_search_disabled_prompt
)
else:
# Simple filter: remove lines containing web_search tool description
lines = prompt.split("\n")
filtered_lines = []
for line in lines:
# Skip lines that describe web_search as an available tool
if "`web_search`" in line and (
"Use Sparingly" in line or "latest news" in line or "Web Search" in line
):
continue
# Also remove web_search from tool list in output format
if "web_search" in line and (
"rag_naive | rag_hybrid |" in line or 'tool":' in line
):
line = (
line.replace(" | web_search", "")
.replace("| web_search", "")
.replace("web_search |", "")
.replace("web_search", "")
)
filtered_lines.append(line)
prompt = "\n".join(filtered_lines)
return prompt
def _build_user_prompt(self, context: dict[str, Any]) -> str:
"""Build user prompt (pass full content)"""
template = self.get_prompt("user_template") if self.has_prompts() else None
if not template:
raise ValueError(
"InvestigateAgent missing user prompt template. Configure in prompts/en/analysis_loop/investigate_agent.yaml"
)
return template.format(**context)
async def _execute_single_action(
self,
tool_selection: str,
query: str,
identifier: str | None,
kb_name: str,
output_dir: str | None,
citation_memory: CitationMemory,
) -> KnowledgeItem | None:
"""Execute a single tool call"""
import time
start_time = time.time()
tool_input = {"query": query, "identifier": identifier, "kb_name": kb_name}
try:
if tool_selection == "rag_naive":
result = await self._call_rag_naive(query, kb_name, output_dir)
raw_result = result.get("answer", "")
elif tool_selection == "rag_hybrid":
result = await self._call_rag_hybrid(query, kb_name, output_dir)
raw_result = result.get("answer", "")
elif tool_selection == "web_search":
# Check if web_search is enabled
if not self.enable_web_search:
self.logger.warning(
"Tool call rejected (web_search): web_search is disabled in config"
)
return None
result = await self._call_web_search(query, output_dir)
raw_result = json.dumps(result, ensure_ascii=False, indent=2)
elif tool_selection == "query_item":
identifier_to_use = identifier or query
if (
not identifier_to_use
or not isinstance(identifier_to_use, str)
or not identifier_to_use.strip()
):
self.logger.warning(
"Tool call failed (query_item): identifier is empty or invalid"
)
return None
result = await self._call_query_item(identifier_to_use, kb_name)
raw_result = result.get("content", result.get("answer", ""))
else:
self.logger.warning(f"Unknown tool type: {tool_selection}")
return None
elapsed_ms = (time.time() - start_time) * 1000
# Create and register citation
cite_id = citation_memory.add_citation(
tool_type=tool_selection,
query=query,
raw_result=raw_result,
stage="analysis",
metadata={"identifier": identifier},
)
citation_memory.save()
# Log tool call
self.logger.log_tool_call(
tool_name=tool_selection,
tool_input=tool_input,
tool_output=result,
status="success",
elapsed_ms=elapsed_ms,
citation_id=cite_id,
)
# Create knowledge item
knowledge_item = KnowledgeItem(
cite_id=cite_id,
tool_type=tool_selection,
query=query,
raw_result=raw_result,
summary="", # Generated by NoteAgent
)
return knowledge_item
except Exception as e:
elapsed_ms = (time.time() - start_time) * 1000
error_msg = str(e)
self.logger.log_tool_call(
tool_name=tool_selection,
tool_input=tool_input,
tool_output=error_msg,
status="failed",
elapsed_ms=elapsed_ms,
error=error_msg,
)
self.logger.warning(f"Tool call failed ({tool_selection}): {e}")
return None
async def _call_rag_naive(
self, query: str, kb_name: str, output_dir: str | None
) -> dict[str, Any]:
"""Call RAG Naive"""
return await rag_search(query=query, kb_name=kb_name, mode="naive")
async def _call_rag_hybrid(
self, query: str, kb_name: str, output_dir: str | None
) -> dict[str, Any]:
"""Call RAG Hybrid"""
return await rag_search(query=query, kb_name=kb_name, mode="hybrid")
async def _call_web_search(self, query: str, output_dir: str | None) -> dict[str, Any]:
"""Call Web Search"""
return web_search(query=query, output_dir=output_dir or "./cache", verbose=False)
async def _call_query_item(self, identifier: str, kb_name: str) -> dict[str, Any]:
"""Call Query Item"""
return query_numbered_item(identifier=identifier, kb_name=kb_name)
@@ -1,190 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
NoteAgent - Note taker
Based on new knowledge, generates or updates notes, annotates covered pain points and missing points
"""
from pathlib import Path
import sys
from typing import Any
# Add project root to path
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))
from src.agents.base_agent import BaseAgent
from ..memory import CitationMemory, InvestigateMemory, KnowledgeItem
from ..utils import ParseError, validate_note_output
from ..utils.json_utils import extract_json_from_text
class NoteAgent(BaseAgent):
"""Note taker Agent - Generates and updates notes"""
def __init__(
self,
config: dict[str, Any],
api_key: str,
base_url: str,
api_version: str | None = None,
token_tracker=None,
):
language = config.get("system", {}).get("language", "zh")
super().__init__(
module_name="solve",
agent_name="note_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
language=language,
config=config,
token_tracker=token_tracker,
)
async def process(
self,
question: str,
memory: InvestigateMemory,
new_knowledge_ids: list[str],
citation_memory: CitationMemory | None = None,
output_dir: str | None = None,
verbose: bool = True,
) -> dict[str, Any]:
"""
Process note generation workflow (supports multiple knowledge_items in single round)
Args:
question: User question
memory: Investigation memory
new_knowledge_ids: List of cite_ids for new knowledge items
citation_memory: Citation memory
output_dir: Output directory
verbose: Whether to print detailed information
Returns:
dict: Aggregated note result
"""
if isinstance(new_knowledge_ids, str): # Backward compatibility
target_ids = [new_knowledge_ids]
else:
target_ids = new_knowledge_ids or []
if not target_ids:
return {"success": False, "reason": "new_knowledge_ids is empty"}
system_prompt = self._build_system_prompt()
processed_details = []
failed_ids = []
for cite_id in target_ids:
knowledge_item = next((k for k in memory.knowledge_chain if k.cite_id == cite_id), None)
if not knowledge_item:
failed_ids.append({"cite_id": cite_id, "reason": "knowledge_item not found"})
continue
context = self._build_context(question, knowledge_item, memory)
user_prompt = self._build_user_prompt(context)
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
verbose=verbose,
response_format={"type": "json_object"},
)
if verbose:
self.logger.debug(f"cite_id={cite_id} LLM output stats:")
self.logger.debug(f" - Total length: {len(response)} chars")
self.logger.debug(
f" - Last 100 chars: ...{response[-100:] if len(response) > 100 else response}"
)
try:
parsed_result = extract_json_from_text(response)
if not parsed_result or not isinstance(parsed_result, dict):
raise ParseError("LLM output is not a valid JSON object")
# citations is optional, default to empty list
if parsed_result.get("citations") is None:
parsed_result["citations"] = []
elif not isinstance(parsed_result.get("citations"), list):
raise ParseError("citations field must be a list")
validate_note_output(parsed_result)
if verbose:
summary_len = len(parsed_result.get("summary", ""))
print(f"📝 [NoteAgent] cite_id={cite_id} summary length: {summary_len}")
except ParseError as e:
failed_ids.append({"cite_id": cite_id, "reason": str(e)})
continue
except Exception as e:
failed_ids.append({"cite_id": cite_id, "reason": str(e)})
continue
citations = parsed_result.get("citations", [])
memory.update_knowledge_summary(cite_id=cite_id, summary=parsed_result["summary"])
if citation_memory:
sources = ", ".join(
citation.get("source", "") for citation in citations if citation.get("source")
)
metadata_block = {"extracted_sources": citations} if citations else None
try:
citation_memory.update_citation(
cite_id=cite_id,
content=parsed_result["summary"],
source=sources or None,
metadata=metadata_block,
stage="analysis",
)
citation_memory.save()
except ValueError:
if verbose:
print(f"⚠️ cite_id not found in CitationMemory: {cite_id}")
processed_details.append(
{
"cite_id": cite_id,
"summary": parsed_result["summary"],
"citations_count": len(citations),
}
)
if processed_details and output_dir:
memory.save()
return {
"success": len(failed_ids) == 0,
"processed_items": len(processed_details),
"details": processed_details,
"failed": failed_ids,
}
def _build_context(
self, question: str, knowledge_item: KnowledgeItem, memory: InvestigateMemory
) -> dict[str, Any]:
"""Build context (pass complete content)"""
return {
"question": question,
"tool_type": knowledge_item.tool_type,
"query": knowledge_item.query,
"raw_result": knowledge_item.raw_result, # Complete content
}
def _build_system_prompt(self) -> str:
"""Build system prompt"""
prompt = self.get_prompt("system") if self.has_prompts() else None
if not prompt:
raise ValueError(
"NoteAgent missing system prompt, please configure system in prompts/zh/analysis_loop/note_agent.yaml."
)
return prompt
def _build_user_prompt(self, context: dict[str, Any]) -> str:
"""Build user prompt (pass complete content)"""
template = self.get_prompt("user_template") if self.has_prompts() else None
if not template:
raise ValueError(
"NoteAgent missing user prompt template, please configure user_template in prompts/zh/analysis_loop/note_agent.yaml."
)
return template.format(**context)
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python
"""
CLI test script for the Solve Agent (Plan -> ReAct -> Write).
Usage:
# Single question mode
python -m src.agents.solve.cli "What is linear convolution?" --kb ai-textbook
# Detailed (iterative) answer mode
python -m src.agents.solve.cli "What is linear convolution?" --detailed
# Interactive mode (default when no question given)
python -m src.agents.solve.cli
python -m src.agents.solve.cli -i --language zh
"""
from __future__ import annotations
import argparse
import asyncio
import sys
from pathlib import Path
# Ensure project root is on sys.path
_project_root = Path(__file__).resolve().parent.parent.parent.parent
if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
def _list_knowledge_bases() -> list[str]:
"""List available knowledge bases from disk."""
try:
from src.knowledge.manager import KnowledgeBaseManager
mgr = KnowledgeBaseManager()
return mgr.list_knowledge_bases()
except Exception:
# Fallback: scan directory
kb_dir = _project_root / "data" / "knowledge_bases"
if kb_dir.exists():
return [d.name for d in kb_dir.iterdir() if d.is_dir() and not d.name.startswith(".")]
return []
def _pick_kb(current_kb: str) -> str:
"""Prompt user to pick a knowledge base, returns selected name."""
kbs = _list_knowledge_bases()
if not kbs:
print(" (no knowledge bases found, using default)")
return current_kb
print("\n Available knowledge bases:")
for i, name in enumerate(kbs, 1):
marker = " <-" if name == current_kb else ""
print(f" {i}. {name}{marker}")
print(f" 0. Keep current ({current_kb})")
try:
choice = input(" Select [0]: ").strip()
except (EOFError, KeyboardInterrupt):
return current_kb
if not choice or choice == "0":
return current_kb
try:
idx = int(choice) - 1
if 0 <= idx < len(kbs):
return kbs[idx]
except ValueError:
# Treat raw text as kb name
if choice in kbs:
return choice
print(f" Invalid choice, keeping: {current_kb}")
return current_kb
def _print_result(result: dict) -> None:
print("\n" + "=" * 60)
print("FINAL ANSWER")
print("=" * 60)
print(result["final_answer"])
print("=" * 60)
print(f"Output directory: {result['output_dir']}")
print(f"Steps: {result.get('completed_steps', '?')}/{result.get('total_steps', '?')}")
print(f"ReAct entries: {result.get('total_react_entries', '?')}")
print(f"Plan revisions: {result.get('plan_revisions', 0)}")
async def _make_solver(kb_name: str, language: str, output_dir: str | None = None):
from src.agents.solve import MainSolver
solver = MainSolver(kb_name=kb_name, language=language, output_base_dir=output_dir)
await solver.ainit()
return solver
async def run_interactive(kb_name: str, language: str, output_dir: str | None, detailed: bool = False) -> None:
print("\n" + "=" * 60)
mode_label = "Detailed" if detailed else "Simple"
print(f" DeepTutor Solve Agent — Interactive Mode ({mode_label})")
print("=" * 60)
while True:
# --- Step 1: pick knowledge base ---
kb_name = _pick_kb(kb_name)
print(f" KB: {kb_name} | Language: {language} | Detailed: {detailed}")
# --- Step 2: enter question ---
try:
question = input("\nQuestion (/quit to exit)> ").strip()
except (EOFError, KeyboardInterrupt):
print("\nBye!")
break
if not question:
continue
if question.lower() in ("/quit", "/exit", "/q"):
print("Bye!")
break
# --- Step 3: solve ---
try:
solver = await _make_solver(kb_name, language, output_dir)
result = await solver.solve(question, detailed=detailed)
_print_result(result)
except Exception as exc:
print(f"\n Error: {exc}\n")
print()
async def main() -> None:
parser = argparse.ArgumentParser(
description="DeepTutor Solve Agent — Plan -> ReAct -> Write",
)
parser.add_argument("question", nargs="?", default=None, help="Question to solve (omit for interactive mode)")
parser.add_argument("--kb", default="ai-textbook", help="Knowledge base name (default: ai-textbook)")
parser.add_argument("--language", default="en", help="Output language: en / zh (default: en)")
parser.add_argument("--output-dir", default=None, help="Override output base directory")
parser.add_argument("-i", "--interactive", action="store_true", help="Start in interactive mode")
parser.add_argument("--detailed", action="store_true", help="Enable iterative detailed answer mode")
args = parser.parse_args()
# Load environment variables
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
if args.interactive or args.question is None:
await run_interactive(args.kb, args.language, args.output_dir, args.detailed)
else:
solver = await _make_solver(args.kb, args.language, args.output_dir)
result = await solver.solve(args.question, detailed=args.detailed)
_print_result(result)
if __name__ == "__main__":
asyncio.run(main())
+450
View File
@@ -0,0 +1,450 @@
# Solve 模块 — 上下文工程审计
> 本文档从 **上下文工程 (Context Engineering)** 的视角,逐模块、逐 Agent 梳理当前 `src/agents/solve/` 中每次 LLM 调用的输入上下文组成,分析信息流转路径与压缩策略,并标注可改进点。
---
## 0. 架构总览
```
Pipeline: Plan → ReAct → Write
Phase 1 — PlannerAgent.process() → Plan (steps)
Phase 2 — SolverAgent.process() × N → Entry (thought/action/observation/self_note)
Phase 3 — WriterAgent.process() → final_answer (Markdown)
WriterAgent.process_iterative() → detailed + concise answer
Memory: Scratchpad (统一记忆体:Plan + Entries + Sources + Metadata)
```
---
## 1. PlannerAgent — 规划阶段
### 1.1 调用时机
- Phase 1 开始时(首次规划)
- Phase 2 中 SolverAgent 返回 `replan` 动作时(重新规划)
### 1.2 LLM 调用上下文
| 上下文槽位 | 来源 | 内容描述 | 动态/静态 |
|-----------|------|---------|----------|
| **system_prompt** | `prompts/en/planner_agent.yaml → system` | 角色定义 + 规则 + 输出格式 (JSON) | 静态 |
| **user_prompt → {question}** | `MainSolver.solve(question)` 传入 | 用户原始问题,完整文本 | 动态 |
| **user_prompt → {tools_description}** | `TOOLS_DESCRIPTION` 常量 + kb_name 替换 | 3 个工具的文本描述 (rag_search / web_search / code_execute) | 半静态 |
| **user_prompt → {scratchpad_summary}** | `Scratchpad` 状态 | 首次:"(initial plan — no progress yet)";replan 时:各步骤状态 + self_note 汇总 + replan reason | 动态 |
### 1.3 Prompt 模板
```yaml
# user_template
## Question
{question}
## Available Tools
{tools_description}
## Progress So Far
{scratchpad_summary}
```
### 1.4 scratchpad_summary 的组装逻辑(replan 时)
```python
# planner_agent.py → _build_user_prompt()
for step in scratchpad.plan.steps:
entries = scratchpad.get_entries_for_step(step.id)
notes = " | ".join(e.self_note for e in entries if e.self_note)
→ "[S1] (COMPLETED) 步骤目标"
→ " Notes: note1 | note2"
# 追加最后一条 replan entry 的 action_input 作为 replan reason
```
### 1.5 上下文特征分析
- **优点**:首次调用上下文极简,LLM 聚焦规划任务。
- **缺失**:
- 无用户历史对话上下文(多轮 Q&A 场景缺失)
- 无知识库元信息(不知道 KB 里有什么内容、什么格式)
- 无用户个性化偏好(风格/难度/语言偏好未注入规划阶段)
- replan 时 `scratchpad_summary` 只有 self_note 压缩摘要,丢失了具体 observation 细节
---
## 2. SolverAgent — ReAct 求解阶段
### 2.1 调用时机
- Phase 2 中对每个 PlanStep 的每轮 ReAct 迭代(最多 `max_react_iterations` 轮/步骤)
### 2.2 LLM 调用上下文
| 上下文槽位 | 来源 | 内容描述 | 动态/静态 |
|-----------|------|---------|----------|
| **system_prompt** | `prompts/en/solver_agent.yaml → system` | 角色定义 + 5 个 action 说明表 + 指南 + 输出格式 (JSON) | 静态 |
| **user_prompt → {question}** | 原始问题全文 | 用户原始问题 | 动态(但跨调用不变) |
| **user_prompt → {plan}** | `Scratchpad._format_plan()` | 完整计划概览(含分析 + 各步骤状态标记 [x]/[>]/[ ]) | 动态 |
| **user_prompt → {current_step}** | `PlanStep` 对象 | 当前步骤 ID + 目标文本 | 动态 |
| **user_prompt → {step_history}** | `Scratchpad.build_solver_context()` | 当前步骤的所有历史 round:thought + action + observation(**完整**) + self_note | 动态(增长) |
| **user_prompt → {previous_knowledge}** | `Scratchpad.build_solver_context()` | 已完成步骤的 self_note 汇总(压缩形式) | 动态(增长) |
### 2.3 Prompt 模板
```yaml
# user_template
## Original Question
{question}
## Plan
{plan}
## Current Step
{current_step}
## Previous Actions for This Step
{step_history}
## Knowledge from Previous Steps
{previous_knowledge}
```
### 2.4 上下文压缩策略 — `build_solver_context()`
```
Scratchpad.build_solver_context(current_step_id, max_tokens=6000):
1. plan_text = 完整计划(analysis + 各步骤带状态标记)
2. current_step_text = "[S2] 步骤目标"
3. step_history = 当前步骤所有 round 的 FULL observation(不压缩)
4. previous_knowledge:
- 正常:[S1] 步骤目标: note1 note2 note3(self_note 拼接)
- 超预算(>6000 tokens):仅保留 "[S1]: note1 | note2"(管道分隔)
压缩只在 previous_knowledge 上执行,step_history 始终保留完整 observation。
```
### 2.5 上下文特征分析
- **优点**:
- step_history 保留完整 observation,SolverAgent 能看到当前步骤的全部工具返回
- previous_knowledge 有 token 预算控制,避免上下文爆炸
- self_note 作为信息压缩机制,跨步骤传递关键发现
- **缺失/风险**:
- **step_history 无压缩上限**:如果某步骤迭代多轮,observation 可能非常长(每个 observation 最大 `obs_max * 4` 字符)
- **question 每轮重复**:原始问题全文在每次调用中重复传入
- **plan 每轮重复**:完整 plan 在每次调用中重复传入(步骤多时可观)
- **无 few-shot 示例**:system prompt 有输出格式示例但仅 1 个
- **code_execute 的 observation 包含完整代码**:`Code:\n```python\n{code}\n```\n\n{output}`,代码可能很长
---
## 3. WriterAgent — 写作阶段
WriterAgent 有 **3 种调用模式**,共涉及 **5 个不同的 LLM 调用**:
### 3.1 Simple 模式 — `process()`
**单次 LLM 调用生成完整答案。**
| 上下文槽位 | 来源 | 内容描述 |
|-----------|------|---------|
| **system_prompt** | `writer_agent.yaml → system` | 角色 + Markdown/LaTeX 格式规则 + 结构要求 + 引用规则 |
| **user → {question}** | 原始问题 | 用户问题全文 |
| **user → {scratchpad_content}** | `Scratchpad.build_writer_context()` | 所有步骤的 plan + entries 详情 |
| **user → {sources}** | `Scratchpad.format_sources_markdown()` | 去重后的引用来源列表 (Markdown) |
| **user → {preference}** | `PersonalizationService.get_preference_for_prompt()` | 用户学习偏好(可为空) |
| **user → {language}** | `config.system.language` | 输出语言代码 (en/zh) |
### 3.2 Iterative 模式 — `process_iterative()`
**多次 LLM 调用,逐步累积 draft,最后生成 concise answer。**
#### 3.2.1 Draft 迭代 — `_write_draft()` × N
| 上下文槽位 | 来源 | 内容描述 |
|-----------|------|---------|
| **system_prompt** | `writer_agent.yaml → iterative_system` | 增量写作角色 + 格式规则 |
| **user → {question}** | 原始问题 | 用户问题全文 |
| **user → {previous_draft}** | 上一轮 draft 输出 / 首轮为占位文本 | 累积的答案草稿(**可能很长**) |
| **user → {new_evidence}** | `_format_step_evidence(step, entries)` | 当前步骤的 action + observation(完整) |
| **user → {sources}** | `Scratchpad.format_sources_markdown()` | 引用来源列表 |
| **user → {language}** | 配置 | 输出语言 |
**Draft 迭代逻辑**:
```
Iter 1: evidence(S1) + evidence(S2) → draft_1 # 首轮合并前两步
Iter 2: draft_1 + evidence(S3) → draft_2 # 后续每步增量
Iter N: draft_{N-1} + evidence(S_{N+1}) → draft_N
```
#### 3.2.2 Concise 生成 — `_write_concise()`
| 上下文槽位 | 来源 | 内容描述 |
|-----------|------|---------|
| **system_prompt** | `writer_agent.yaml → concise_system` | 简洁回答角色 + 规则 |
| **user → {question}** | 原始问题 | 用户问题全文 |
| **user → {detailed_answer}** | 最终 draft | 完整详细答案(**可能非常长**) |
| **user → {language}** | 配置 | 输出语言 |
### 3.3 `build_writer_context()` 上下文组装逻辑
```
Scratchpad.build_writer_context(max_tokens=12000):
1. Plan 概览(带状态标记)
2. 每个 completed/in_progress 步骤:
正常:
### Step S1: 目标
**Round 0** — Action: rag_search(query)
Note: self_note
Observation: <完整 observation>
超预算(>12000 tokens)时压缩:
前 N-2 步 → 仅保留 "Round 0: self_note"(丢弃 observation)
最后 2 步 → 保留完整 observation
```
### 3.4 上下文特征分析
- **优点**:
- `build_writer_context` 有 token 预算和渐进压缩策略
- Iterative 模式通过分步投喂 evidence 降低单次上下文压力
- 个性化偏好注入(虽然仅在 Simple 模式)
- **缺失/风险**:
- **Iterative 模式的 previous_draft 持续增长**:每次迭代 draft 只增不减,后期可能超出上下文窗口
- **Iterative 模式缺少 preference**:`_write_draft()` 和 `_write_concise()` 未注入用户偏好
- **sources 在每次 draft 迭代中重复传入**:完整引用列表每轮重复
- **_format_step_evidence 无长度限制**:observation 完整传入,单步证据可能很大
---
## 4. Code Generation — 隐式 LLM 调用
### 4.1 调用时机
- SolverAgent 返回 `code_execute` 动作时,`MainSolver._generate_code()` 发起额外 LLM 调用
### 4.2 LLM 调用上下文
| 上下文槽位 | 来源 | 内容描述 |
|-----------|------|---------|
| **system_prompt** | 硬编码字符串 | "You are a Python code generator..." + 库提示 + 输出规则 |
| **user_prompt** | SolverAgent 的 `action_input` | 自然语言意图描述(如 "compute the convolution of x=[1,2,3] and h=[1,1]") |
### 4.3 上下文特征分析
- **缺失严重**:
- 无原始问题上下文(代码生成不知道整体问题背景)
- 无当前步骤目标(不知道这段代码要验证什么)
- 无先前步骤的知识(可能需要用到之前检索的公式)
- 仅靠 SolverAgent 在 `action_input` 中的描述传递意图
---
## 5. Scratchpad — 统一记忆体
### 5.1 数据结构
```
Scratchpad
├── question: str # 原始问题
├── plan: Plan # 规划
│ ├── analysis: str # 问题分析
│ └── steps: [PlanStep] # 步骤列表
│ ├── id: str # 步骤 ID (S1, S2, ...)
│ ├── goal: str # 步骤目标
│ ├── tools_hint: [str] # 工具提示(未实际使用)
│ └── status: str # 状态 (pending/in_progress/completed/skipped)
├── entries: [Entry] # ReAct 迭代记录
│ ├── step_id: str # 所属步骤
│ ├── round: int # 轮次号
│ ├── thought: str # 思考
│ ├── action: str # 动作
│ ├── action_input: str # 动作输入
│ ├── observation: str # 工具返回结果
│ ├── self_note: str # 自我总结(压缩用)
│ ├── sources: [Source] # 来源引用
│ └── timestamp: str # 时间戳
└── metadata: dict # 元数据
├── total_llm_calls: int
├── total_tokens: int
├── start_time: str
└── plan_revisions: int
```
### 5.2 信息压缩层级
| 压缩级别 | 使用场景 | 保留内容 | 丢弃内容 |
|---------|---------|---------|---------|
| **L0 完整** | step_history(SolverAgent 当前步骤) | 全部字段 | 无 |
| **L1 结构化** | build_writer_context 正常模式 | plan + action + observation + self_note | thought |
| **L2 摘要** | previous_knowledge 正常模式 | step_goal + self_note 拼接 | observation, thought, action_input |
| **L3 极简** | previous_knowledge 超预算 / writer_context 超预算 | self_note 管道分隔 | 其余全部 |
### 5.3 Token 预算
| 场景 | 预算 | 来源 |
|------|------|------|
| `build_solver_context` | 6,000 tokens | 硬编码默认值 |
| `build_writer_context` | 12,000 tokens | 硬编码默认值 |
| observation 截断 | `obs_max * 4` 字符 ≈ 2,000 × 4 = 8,000 字符 | config `solve.observation_max_tokens` |
---
## 6. 外部上下文来源
### 6.1 工具返回 (observation)
| 工具 | 返回格式 | 最大长度 | 附带 Source |
|------|---------|---------|------------|
| `rag_search` | RAG answer 文本 | `obs_max * 4` 字符 | Source(type="rag", file=kb_name, chunk_id=query[:50]) |
| `web_search` | Web answer 文本 | `obs_max * 4` 字符 | Source(type="web", url=..., file=title) × 最多 5 个 |
| `code_execute` | `Code:\n```python\n{code}\n```\n\n{stdout/stderr/artifacts}` | `obs_max * 4` 字符 (output 部分) | Source(type="code", file=artifact_name) |
### 6.2 个性化 (Personalization)
| 注入点 | 内容 | 条件 |
|--------|------|------|
| WriterAgent.process() → `{preference}` | `LearningMemory.get_preference_context()` | 仅 Simple 模式;服务可用时 |
| PlannerAgent — **未注入** | — | — |
| SolverAgent — **未注入** | — | — |
| WriterAgent Iterative — **未注入** | — | — |
### 6.3 配置参数 (agents.yaml)
| 参数 | 值 | 影响 |
|------|-----|------|
| `solve.temperature` | 0.3 | 所有 3 个 Agent 共用 |
| `solve.max_tokens` | 8192 | 所有 3 个 Agent 共用(Writer 调用时覆盖为 8192 / 1024) |
---
## 7. 完整信息流图
```
用户问题 (question)
│
▼
┌─────────────────────────────────────────────────┐
│ PlannerAgent │
│ │
│ system: 静态角色 prompt │
│ user: question │
│ + tools_description (静态) │
│ + scratchpad_summary (首次为空/replan时有) │
│ │
│ 输出: Plan { analysis, steps[] } │
└───────────────────┬─────────────────────────────┘
│ 写入 Scratchpad.plan
▼
┌─────────────────────────────────────────────────┐
│ SolverAgent (循环: 每步骤 × 每轮) │
│ │
│ system: 静态角色 prompt │
│ user: question (每轮重复) │
│ + plan (每轮重复, 含状态标记) │
│ + current_step (当前步骤目标) │
│ + step_history (当前步骤完整历史, L0) │
│ + previous_knowledge (已完成步骤摘要, L2) │
│ │
│ 输出: { thought, action, action_input, self_note }│
│ │ │
│ ├─ action=rag_search → _tool_rag() │
│ ├─ action=web_search → _tool_web() │
│ ├─ action=code_execute → _generate_code() │
│ │ → run_code() │
│ ├─ action=done → 标记步骤完成 │
│ └─ action=replan → 回到 PlannerAgent │
│ │
│ observation + sources → 写入 Scratchpad.entries │
└───────────────────┬─────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────┐
│ WriterAgent │
│ │
│ [Simple 模式] │
│ system: 格式规则 prompt │
│ user: question │
│ + scratchpad_content (L1, 预算12k) │
│ + sources (引用列表) │
│ + preference (个性化, 可为空) │
│ + language │
│ │
│ [Iterative 模式] │
│ Draft × N: │
│ system: 增量写作 prompt │
│ user: question + previous_draft + new_evidence│
│ + sources + language │
│ Concise × 1: │
│ system: 简洁回答 prompt │
│ user: question + detailed_answer + language │
│ │
│ 输出: final_answer (Markdown) │
└─────────────────────────────────────────────────┘
```
---
## 8. 关键问题与改进方向
### 8.1 上下文冗余
| 问题 | 位置 | 影响 |
|------|------|------|
| question 在 SolverAgent 每轮调用中完整重复 | solver_agent user_prompt | 浪费 tokens,尤其问题很长时 |
| plan 在 SolverAgent 每轮调用中完整重复 | solver_agent user_prompt | 步骤多时占用可观 |
| sources 在 Writer Iterative 每轮重复 | _write_draft user_prompt | 引用列表持续膨胀 |
| system_prompt 每次调用完整传入 | 所有 Agent | 协议限制,但可考虑缩短 |
### 8.2 上下文缺失
| 缺失 | 影响 | 严重度 |
|------|------|--------|
| **Code Generation 缺乏上下文** | 代码生成仅凭 action_input,不知道问题背景和已有知识 | 🔴 高 |
| **Planner 无 KB 元信息** | 不知道知识库中有什么,可能规划不切实际的步骤 | 🟡 中 |
| **Planner 无个性化偏好** | 规划不考虑用户偏好的难度/风格 | 🟡 中 |
| **Writer Iterative 无个性化** | 仅 Simple 模式注入 preference,Iterative 模式遗漏 | 🟡 中 |
| **无多轮对话历史** | 追问场景下无法理解上下文 | 🟡 中(取决于场景) |
| **Solver 无 observation 质量反馈** | 不知道 RAG 返回的是高质量精确匹配还是模糊泛化 | 🟢 低 |
### 8.3 压缩策略风险
| 风险 | 位置 | 说明 |
|------|------|------|
| **step_history 无上限** | `build_solver_context` | 当前步骤 observation 完整保留,多轮后可能超出窗口 |
| **Iterative draft 持续增长** | `_write_draft` | previous_draft 只增不减,后期可能超出模型上下文窗口 |
| **压缩粒度粗** | `build_writer_context` | 超预算时前 N-2 步直接丢弃 observation,可能丢失关键信息 |
| **token 估算不精确** | `_estimate_tokens` | tiktoken 不可用时退化为 `len/4`,非英语文本误差大 |
### 8.4 self_note 作为压缩中枢
`self_note` 是整个系统**唯一的跨步骤信息传递机制**(从 SolverAgent 到 PlannerAgent-replan、后续 SolverAgent 步骤)。其质量直接决定:
- PlannerAgent 是否能做出正确的 replan 决策
- 后续步骤的 SolverAgent 是否有足够的先验知识
- 信息在多步推理中的保真度
当前 self_note 由 SolverAgent 自行在每轮末尾生成(1 句话),**没有质量验证或格式约束**。
---
## 9. Token 消耗估算(典型场景)
假设:3 步计划,每步平均 2 轮 ReAct,每个 observation ≈ 1500 tokens
| 调用 | system | user | 合计估算 |
|------|--------|------|---------|
| Planner (首次) | ~300 | ~200 (Q) + ~100 (tools) + ~50 (empty progress) = ~350 | ~650 |
| Solver S1 R1 | ~400 | ~200 (Q) + ~150 (plan) + ~50 (step) + ~50 (no history) + ~50 (no prev) = ~500 | ~900 |
| Solver S1 R2 | ~400 | ~200 + ~150 + ~50 + ~1600 (R1 full obs) + ~50 = ~2050 | ~2450 |
| Solver S2 R1 | ~400 | ~200 + ~150 + ~50 + ~50 (no history) + ~100 (S1 notes) = ~550 | ~950 |
| Solver S2 R2 | ~400 | ~200 + ~150 + ~50 + ~1600 + ~100 = ~2100 | ~2500 |
| Solver S3 R1 | ~400 | ~200 + ~150 + ~50 + ~50 + ~200 (S1+S2 notes) = ~650 | ~1050 |
| Solver S3 R2 | ~400 | ~200 + ~150 + ~50 + ~1600 + ~200 = ~2200 | ~2600 |
| CodeGen (如有) | ~50 | ~100 | ~150 |
| Writer (Simple) | ~300 | ~200 + ~5000 (writer_context) + ~200 (sources) + ~100 (pref) = ~5500 | ~5800 |
**总输入约:~17,000 tokens**(不含 LLM 输出 tokens)
---
*最后更新:2026-02-10*
File diff suppressed because it is too large Load Diff
+7 -42
View File
@@ -1,46 +1,11 @@
#!/usr/bin/env python
"""
Memory System - Memory storage for solving process
"""Solve Agent Memory — unified Scratchpad."""
Provides implementations of InvestigateMemory and SolveMemory.
"""
from .citation_memory import (
CitationItem,
CitationMemory,
)
from .investigate_memory import (
InvestigateMemory,
KnowledgeItem,
Reflections,
)
from .solve_memory import (
# Core data structures
IterationRecord,
NoteAction,
SolveChainStep,
SolveMemory,
SolveOutput,
TodoItem,
ToolCallRecord,
)
from .scratchpad import Entry, Plan, PlanStep, Scratchpad, Source
__all__ = [
# Investigate Memory
"InvestigateMemory",
"KnowledgeItem",
"Reflections",
# Solve Memory - Core
"SolveMemory",
"TodoItem",
"ToolCallRecord",
# Solve Memory - New iteration architecture
"IterationRecord",
"NoteAction",
# Solve Memory - Legacy/Backward compatibility
"SolveOutput",
"SolveChainStep",
# Citation Memory
"CitationMemory",
"CitationItem",
"Scratchpad",
"Plan",
"PlanStep",
"Entry",
"Source",
]
-353
View File
@@ -1,353 +0,0 @@
#!/usr/bin/env python
"""
CitationMemory - Global citation management system
Unified management of citation information generated by all tool calls
"""
from dataclasses import asdict, dataclass, field
from datetime import datetime
import json
from pathlib import Path
from typing import Any
@dataclass
class CitationItem:
"""Citation item"""
cite_id: str # Citation number, e.g., "[rag-1]"
tool_type: str # Tool type: rag_naive | rag_hybrid | web_search | query_item | code_execution
query: str # Query content
raw_result: str = "" # Raw tool return content (complete)
source: str = "" # Source information (if any)
content: str = "" # Citation content summary (usually summary)
stage: str = "solve" # Stage: analysis | solve
step_id: str | None = None # Belonging step (applicable to Solve stage)
metadata: dict[str, Any] = field(default_factory=dict) # Additional metadata
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
updated_at: str = field(default_factory=lambda: datetime.now().isoformat())
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "CitationItem":
# Compatible with old versions without stage/step_id/metadata fields
if "stage" not in data:
data["stage"] = "solve"
if "metadata" not in data:
data["metadata"] = {}
if "updated_at" not in data:
data["updated_at"] = data.get("created_at", datetime.now().isoformat())
return cls(**data)
class CitationMemory:
"""Global citation management system"""
def __init__(self, output_dir: str | None = None):
self.output_dir = output_dir
self.version = "1.1"
self.created_at = datetime.now().isoformat()
self.updated_at = datetime.now().isoformat()
# Core data: citation list
self.citations: list[CitationItem] = []
# Citation counter (incremented by tool prefix)
self.tool_counters: dict[str, int] = {}
# File path
if output_dir:
self.file_path = Path(output_dir) / "citation_memory.json"
else:
self.file_path = None
@classmethod
def load_or_create(cls, output_dir: str) -> "CitationMemory":
"""Load existing citation memory or create new memory"""
file_path = Path(output_dir) / "citation_memory.json"
if file_path.exists():
# Load existing memory
with open(file_path, encoding="utf-8") as f:
data = json.load(f)
memory = cls(output_dir=output_dir)
memory.version = data.get("version", "1.1")
memory.created_at = data.get("created_at", memory.created_at)
memory.updated_at = data.get("updated_at", memory.updated_at)
# Load citation list
citations_data = data.get("citations", [])
memory.citations = [CitationItem.from_dict(item) for item in citations_data]
# Restore counters
memory.tool_counters = data.get("tool_counters", {})
if not memory.tool_counters:
# Compatible with old versions: guess from existing cite_id
for citation in memory.citations:
prefix = memory._get_tool_prefix(citation.tool_type)
number = memory._extract_counter_from_cite_id(citation.cite_id, prefix)
if number is not None:
memory.tool_counters[prefix] = max(
memory.tool_counters.get(prefix, 0), number
)
return memory
# Create new memory
return cls(output_dir=output_dir)
def add_citation(
self,
tool_type: str,
query: str,
raw_result: str = "",
source: str = "",
content: str = "",
stage: str = "solve",
step_id: str | None = None,
metadata: dict[str, Any] | None = None,
cite_id: str | None = None,
) -> str:
"""
Add new citation entry
Args:
tool_type: Tool type
query: Query content
raw_result: Raw tool return content
source: Source information
content: Citation content summary
Returns:
str: Newly generated or reused cite_id (e.g., "[rag-1]")
"""
# If cite_id is provided and already exists, return directly
if cite_id and self.get_citation(cite_id):
return cite_id
# Generate new cite_id
if not cite_id:
cite_id = self._generate_cite_id(tool_type)
citation = CitationItem(
cite_id=cite_id,
tool_type=tool_type,
query=query,
raw_result=raw_result,
source=source,
content=content,
stage=stage,
step_id=step_id,
metadata=metadata or {},
)
self.citations.append(citation)
self.updated_at = datetime.now().isoformat()
return cite_id
def get_citation(self, cite_id: str) -> CitationItem | None:
"""Get citation entry by cite_id"""
for citation in self.citations:
if citation.cite_id == cite_id:
return citation
return None
def get_all_citations(self) -> list[CitationItem]:
"""Get all citation entries"""
return self.citations
def get_citations_by_tool_type(self, tool_type: str) -> list[CitationItem]:
"""Get citation entries by tool type"""
return [c for c in self.citations if c.tool_type == tool_type]
def update_citation(
self,
cite_id: str,
raw_result: str | None = None,
source: str | None = None,
content: str | None = None,
metadata: dict[str, Any] | None = None,
stage: str | None = None,
step_id: str | None = None,
):
"""Update citation entry information"""
for citation in self.citations:
if citation.cite_id == cite_id:
if raw_result is not None:
citation.raw_result = raw_result
if source is not None:
citation.source = source
if content is not None:
citation.content = content
if metadata:
citation.metadata.update(metadata)
if stage:
citation.stage = stage
if step_id:
citation.step_id = step_id
citation.updated_at = datetime.now().isoformat()
self.updated_at = datetime.now().isoformat()
return
raise ValueError(f"cite_id not found: {cite_id}")
def save(self):
"""Save to JSON file"""
if not self.file_path:
raise ValueError("output_dir not set, cannot save")
# Ensure directory exists
self.file_path.parent.mkdir(parents=True, exist_ok=True)
self.updated_at = datetime.now().isoformat()
# Convert to dictionary
data = self.to_dict()
# Save to file
with open(self.file_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary"""
return {
"version": self.version,
"created_at": self.created_at,
"updated_at": self.updated_at,
"citations": [item.to_dict() for item in self.citations],
"tool_counters": self.tool_counters,
}
def format_citations_markdown(
self, used_cite_ids: list[str] | None = None, language: str = "zh"
) -> str:
"""
Format citation list as Markdown
Args:
used_cite_ids: Optional, specify citation ID list to format. If provided, only format these citations; if not provided, format all citations.
language: Language code, 'zh' for Chinese, 'en' for English, default 'zh'
Returns:
str: Markdown-formatted citation list
"""
# Set text based on language
if language == "en":
no_citations_text = "(No citations)"
citation_title = "## Citations\n"
stage_label = "Stage"
source_label = "Source"
query_content_label = " - Query Content:"
citation_content_label = " - Citation Content:"
else:
no_citations_text = "(No citations)"
citation_title = "## Citations\n"
stage_label = "Stage"
source_label = "Source"
query_content_label = " - Query Content:"
citation_content_label = " - Citation Content:"
if not self.citations:
return no_citations_text
# If used_cite_ids is specified, only format these citations
citations_to_format = self.citations
if used_cite_ids is not None:
cite_id_set = set(used_cite_ids)
citations_to_format = [c for c in self.citations if c.cite_id in cite_id_set]
if not citations_to_format:
return no_citations_text
lines = [citation_title]
for citation in citations_to_format:
tool_type_display = {
"rag_naive": "RAG (Naive)",
"rag_hybrid": "RAG (Hybrid)",
"web_search": "Web Search",
"query_item": "Query Item",
"code_execution": "Code Execution",
}.get(citation.tool_type, citation.tool_type)
line = f"- **{citation.cite_id}** [{tool_type_display}] {stage_label}: {citation.stage}"
if citation.source:
line += f" | {source_label}: {citation.source}"
lines.append(line)
if citation.query:
query_block = self._format_block(
citation.query,
language="python" if citation.tool_type == "code_execution" else None,
)
lines.append(query_content_label)
lines.append(self._indent_block(query_block, " "))
if citation.content:
content_block = self._format_block(
citation.content,
language="python" if citation.tool_type == "code_execution" else None,
force_block=True,
)
lines.append(citation_content_label)
lines.append(self._indent_block(content_block, " "))
elif citation.raw_result:
raw_block = self._format_block(
citation.raw_result,
language="python" if citation.tool_type == "code_execution" else None,
force_block=True,
)
lines.append(citation_content_label)
lines.append(self._indent_block(raw_block, " "))
return "\n".join(lines)
# ------------------------------------------------------------------
# Internal utility methods
# ------------------------------------------------------------------
def _get_tool_prefix(self, tool_type: str) -> str:
"""Generate unified prefix based on tool type"""
prefix_map = {
"rag_naive": "rag",
"rag_hybrid": "rag",
"web_search": "web",
"code_execution": "code",
"query_item": "query",
}
normalized = prefix_map.get(tool_type, tool_type.replace("_", "-"))
return normalized.lower()
def _generate_cite_id(self, tool_type: str) -> str:
prefix = self._get_tool_prefix(tool_type)
current = self.tool_counters.get(prefix, 0) + 1
self.tool_counters[prefix] = current
return f"[{prefix}-{current}]"
@staticmethod
def _format_block(text: str, language: str | None = None, force_block: bool = False) -> str:
if not text:
return ""
clean = text.strip()
clean = clean.strip("`")
if force_block or "\n" in clean or len(clean) > 80:
lang = language or ""
return f"```{lang}\n{clean}\n```"
return f"`{clean}`"
@staticmethod
def _indent_block(block: str, prefix: str) -> str:
if not block:
return ""
return "\n".join(prefix + line if line else prefix for line in block.splitlines())
@staticmethod
def _extract_counter_from_cite_id(cite_id: str, prefix: str) -> int | None:
"""Extract counter value from cite_id"""
try:
inner = cite_id.strip("[]")
if inner.startswith(f"{prefix}-"):
return int(inner.split("-", maxsplit=1)[1])
except (ValueError, IndexError):
return None
return None
@@ -1,226 +0,0 @@
#!/usr/bin/env python
"""
InvestigateMemory - Analysis loop memory file system (Refactored: uses unified cite_id)
"""
from dataclasses import asdict, dataclass, field
from datetime import datetime
import json
from pathlib import Path
from typing import Any
@dataclass
class KnowledgeItem:
"""Knowledge item (Refactored: uses cite_id)"""
cite_id: str # Citation ID, corresponds to cite_id in CitationMemory
tool_type: str # rag_naive | rag_hybrid | web_search | query_item
query: str
raw_result: str # Raw tool return content (complete)
summary: str = "" # Summary generated by NoteAgent
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
updated_at: str = field(default_factory=lambda: datetime.now().isoformat())
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "KnowledgeItem":
# Backward compatibility: handle old version field names
if "knowledge_id" in data and "cite_id" not in data:
# Convert old knowledge_id to cite_id
data["cite_id"] = data.pop("knowledge_id")
if "source_type" in data and "tool_type" not in data:
data["tool_type"] = data.pop("source_type")
if "query_text" in data and "query" not in data:
data["query"] = data.pop("query_text")
if "answer_raw" in data and "raw_result" not in data:
data["raw_result"] = data.pop("answer_raw")
# Remove old citations field (now managed by CitationMemory)
if "citations" in data:
data.pop("citations")
return cls(**data)
@dataclass
class Reflections:
"""Reflections"""
remaining_questions: list[str] = field(
default_factory=list
) # Questions still needing investigation
updated_at: str = field(default_factory=lambda: datetime.now().isoformat())
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "Reflections":
return cls(**data)
class InvestigateMemory:
"""Analysis loop memory management (Refactored: uses unified cite_id)"""
def __init__(
self,
task_id: str | None = None,
user_question: str = "",
output_dir: str | None = None,
):
self.task_id = task_id or f"investigate_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
self.user_question = user_question
self.output_dir = output_dir
self.version = "3.0" # New version
self.created_at = datetime.now().isoformat()
self.updated_at = datetime.now().isoformat()
# Core data
self.knowledge_chain: list[KnowledgeItem] = []
self.reflections: Reflections = Reflections()
# Metadata (for statistics and monitoring)
self.metadata: dict[str, Any] = {
"total_iterations": 0,
"coverage_rate": 0.0,
"avg_confidence": 0.0,
"total_knowledge_items": 0,
}
# File path
if output_dir:
self.file_path = Path(output_dir) / "investigate_memory.json"
else:
self.file_path = None
@classmethod
def load_or_create(
cls, output_dir: str, user_question: str = "", task_id: str | None = None
) -> "InvestigateMemory":
"""Load existing memory or create new memory (supports v1.0/v2.0 backward compatibility)"""
file_path = Path(output_dir) / "investigate_memory.json"
if file_path.exists():
# Load existing memory
with open(file_path, encoding="utf-8") as f:
data = json.load(f)
memory = cls(
task_id=data.get("task_id"),
user_question=data.get("user_question", user_question),
output_dir=output_dir,
)
file_version = data.get("version", "1.0")
memory.version = "3.0" # Upgrade to new version
memory.created_at = data.get("created_at", memory.created_at)
memory.updated_at = data.get("updated_at", memory.updated_at)
# Load knowledge chain (supports v1.0/v2.0 compatibility)
knowledge_chain_data = data.get("knowledge_chain", [])
memory.knowledge_chain = [
KnowledgeItem.from_dict(item) for item in knowledge_chain_data
]
# If v1.0, need to migrate data
if file_version == "1.0":
# Merge notes summary into knowledge_chain
notes_data = data.get("notes", [])
for note in notes_data:
related_knowledge_ids = note.get("related_knowledge_ids", [])
# Prioritize using related_knowledge_ids
for knowledge_id in related_knowledge_ids:
for k_item in memory.knowledge_chain:
# Old version uses knowledge_id, new version uses cite_id
if k_item.cite_id == knowledge_id:
if not k_item.summary:
k_item.summary = note.get("summary", "")
break
# Convert reflections to remaining_questions
reflections_data = data.get("reflections", [])
remaining_questions = []
for reflection in reflections_data:
action_items = reflection.get("action_items", [])
remaining_questions.extend(action_items)
gaps = reflection.get("gaps", [])
remaining_questions.extend(gaps)
# Deduplicate
memory.reflections.remaining_questions = list(set(remaining_questions))
else:
# v2.0/v3.0 format
reflections_data = data.get("reflections", {})
if isinstance(reflections_data, dict):
memory.reflections = Reflections.from_dict(reflections_data)
else:
memory.reflections = Reflections()
# Load metadata (if exists)
memory.metadata = data.get("metadata", memory.metadata)
return memory
# Create new memory
return cls(task_id=task_id, user_question=user_question, output_dir=output_dir)
def add_knowledge(self, item: KnowledgeItem):
"""Add knowledge item"""
self.knowledge_chain.append(item)
self.updated_at = datetime.now().isoformat()
def update_knowledge_summary(self, cite_id: str, summary: str):
"""Update knowledge item summary (called by NoteAgent)"""
for item in self.knowledge_chain:
if item.cite_id == cite_id:
item.summary = summary
item.updated_at = datetime.now().isoformat()
self.updated_at = datetime.now().isoformat()
return
raise ValueError(f"cite_id not found: {cite_id}")
def get_available_knowledge(
self, tool_types: list[str] | None = None, cite_ids: list[str] | None = None
) -> list[KnowledgeItem]:
"""Get available knowledge (supports filtering)"""
results = self.knowledge_chain
if tool_types:
results = [k for k in results if k.tool_type in tool_types]
if cite_ids:
results = [k for k in results if k.cite_id in cite_ids]
return results
def save(self):
"""Save to JSON file"""
if not self.file_path:
raise ValueError("output_dir not set, cannot save")
# Ensure directory exists
self.file_path.parent.mkdir(parents=True, exist_ok=True)
self.updated_at = datetime.now().isoformat()
# Convert to dictionary
data = self.to_dict()
# Save to file
with open(self.file_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary"""
return {
"version": self.version,
"task_id": self.task_id,
"user_question": self.user_question,
"created_at": self.created_at,
"updated_at": self.updated_at,
"knowledge_chain": [item.to_dict() for item in self.knowledge_chain],
"reflections": self.reflections.to_dict(),
"metadata": self.metadata,
}
+433
View File
@@ -0,0 +1,433 @@
"""
Scratchpad - Unified memory for the Plan -> ReAct -> Write pipeline.
Replaces InvestigateMemory + SolveMemory + CitationMemory with a single
linear data structure that tracks the plan, all ReAct iterations, and
sources for citation.
"""
from __future__ import annotations
import json
import os
from dataclasses import asdict, dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any
# Optional tiktoken for accurate token counting
try:
import tiktoken
_TIKTOKEN_AVAILABLE = True
except ImportError:
_TIKTOKEN_AVAILABLE = False
# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------
@dataclass
class Source:
"""A citation source attached to a retrieval entry."""
type: str # rag, web, code
file: str | None = None
page: int | None = None
url: str | None = None
chunk_id: str | None = None
# ---------- serialisation helpers ----------
def to_dict(self) -> dict[str, Any]:
return {k: v for k, v in asdict(self).items() if v is not None}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Source:
return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
@dataclass
class PlanStep:
"""One step in the plan produced by PlannerAgent."""
id: str
goal: str
tools_hint: list[str] = field(default_factory=list)
status: str = "pending" # pending | in_progress | completed | skipped
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: dict[str, Any]) -> PlanStep:
return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
@dataclass
class Plan:
"""High-level plan output by PlannerAgent."""
analysis: str = ""
steps: list[PlanStep] = field(default_factory=list)
def to_dict(self) -> dict[str, Any]:
return {
"analysis": self.analysis,
"steps": [s.to_dict() for s in self.steps],
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Plan:
steps = [PlanStep.from_dict(s) for s in data.get("steps", [])]
return cls(analysis=data.get("analysis", ""), steps=steps)
@dataclass
class Entry:
"""One ReAct iteration entry."""
step_id: str
round: int
thought: str = ""
action: str = ""
action_input: str = ""
observation: str = ""
self_note: str = ""
sources: list[Source] = field(default_factory=list)
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
def to_dict(self) -> dict[str, Any]:
d = asdict(self)
d["sources"] = [s.to_dict() for s in self.sources]
return d
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Entry:
sources = [Source.from_dict(s) for s in data.get("sources", [])]
filtered = {k: v for k, v in data.items() if k in cls.__dataclass_fields__ and k != "sources"}
return cls(sources=sources, **filtered)
# ---------------------------------------------------------------------------
# Scratchpad
# ---------------------------------------------------------------------------
class Scratchpad:
"""Unified memory: plan + ReAct entries + metadata."""
VERSION = "1.0"
FILENAME = "scratchpad.json"
def __init__(self, question: str) -> None:
self.question: str = question
self.plan: Plan | None = None
self.entries: list[Entry] = []
self.metadata: dict[str, Any] = {
"total_llm_calls": 0,
"total_tokens": 0,
"start_time": datetime.now().isoformat(),
"plan_revisions": 0,
}
# ------------------------------------------------------------------
# Plan management
# ------------------------------------------------------------------
def set_plan(self, plan: Plan) -> None:
"""Set the initial plan."""
self.plan = plan
def update_plan(self, new_plan: Plan) -> None:
"""Replan: keep completed steps from the old plan, replace the rest."""
if self.plan is None:
self.plan = new_plan
return
self.metadata["plan_revisions"] = self.metadata.get("plan_revisions", 0) + 1
completed = [s for s in self.plan.steps if s.status == "completed"]
completed_ids = {s.id for s in completed}
# New steps = completed (preserved) + new pending steps (with fresh IDs)
new_pending = [s for s in new_plan.steps if s.id not in completed_ids]
self.plan.analysis = new_plan.analysis
self.plan.steps = completed + new_pending
# ------------------------------------------------------------------
# Step status management
# ------------------------------------------------------------------
def mark_step_status(self, step_id: str, status: str) -> None:
if self.plan is None:
return
for step in self.plan.steps:
if step.id == step_id:
step.status = status
return
def get_next_pending_step(self) -> PlanStep | None:
if self.plan is None:
return None
for step in self.plan.steps:
if step.status == "pending":
return step
return None
def get_completed_steps(self) -> list[PlanStep]:
if self.plan is None:
return []
return [s for s in self.plan.steps if s.status == "completed"]
def is_all_completed(self) -> bool:
if self.plan is None:
return True
return all(s.status in ("completed", "skipped") for s in self.plan.steps)
# ------------------------------------------------------------------
# Entry management
# ------------------------------------------------------------------
def add_entry(
self,
step_id: str,
round_num: int,
thought: str,
action: str,
action_input: str,
observation: str,
self_note: str,
sources: list[Source] | None = None,
) -> Entry:
entry = Entry(
step_id=step_id,
round=round_num,
thought=thought,
action=action,
action_input=action_input,
observation=observation,
self_note=self_note,
sources=sources or [],
)
self.entries.append(entry)
return entry
def get_entries_for_step(self, step_id: str) -> list[Entry]:
return [e for e in self.entries if e.step_id == step_id]
# ------------------------------------------------------------------
# Context builders (for prompt construction with compression)
# ------------------------------------------------------------------
def build_solver_context(
self,
current_step_id: str,
max_tokens: int = 6000,
) -> dict[str, str]:
"""Build compressed context for SolverAgent prompt.
Returns dict with keys: plan, current_step, step_history, previous_knowledge
"""
# Plan summary
plan_text = self._format_plan()
# Current step description
current_step_text = ""
if self.plan:
for s in self.plan.steps:
if s.id == current_step_id:
current_step_text = f"[{s.id}] {s.goal}"
break
# Step history (current step entries – full observations)
current_entries = self.get_entries_for_step(current_step_id)
step_history_parts: list[str] = []
for e in current_entries:
step_history_parts.append(
f"Round {e.round}:\n"
f" Thought: {e.thought}\n"
f" Action: {e.action}({e.action_input})\n"
f" Observation: {e.observation}\n"
f" Note: {e.self_note}"
)
step_history = "\n\n".join(step_history_parts) if step_history_parts else "(no actions yet)"
# Previous knowledge from completed steps (compressed)
previous_parts: list[str] = []
if self.plan:
completed_ids = [s.id for s in self.plan.steps if s.status == "completed"]
for sid in completed_ids:
entries = self.get_entries_for_step(sid)
step_obj = next((s for s in self.plan.steps if s.id == sid), None)
goal_text = step_obj.goal if step_obj else sid
notes = [e.self_note for e in entries if e.self_note]
if notes:
previous_parts.append(f"[{sid}] {goal_text}: {' '.join(notes)}")
previous_knowledge = "\n".join(previous_parts) if previous_parts else "(no previous steps completed)"
# Token budget check – if over budget, aggressively compress previous_knowledge
total = self._estimate_tokens(plan_text + current_step_text + step_history + previous_knowledge)
if total > max_tokens and previous_parts:
# Keep only self_notes, one line each
compressed = []
for sid in completed_ids:
entries = self.get_entries_for_step(sid)
notes = " | ".join(e.self_note for e in entries if e.self_note)
if notes:
compressed.append(f"[{sid}]: {notes}")
previous_knowledge = "\n".join(compressed) if compressed else "(compressed)"
return {
"plan": plan_text,
"current_step": current_step_text,
"step_history": step_history,
"previous_knowledge": previous_knowledge,
}
def build_writer_context(self, max_tokens: int = 12000) -> str:
"""Build context for WriterAgent – preserves more detail."""
parts: list[str] = []
if self.plan:
parts.append("## Plan\n" + self._format_plan())
if not self.plan:
return "\n\n".join(parts) or "(no evidence gathered)"
for step in self.plan.steps:
if step.status not in ("completed", "in_progress"):
continue
entries = self.get_entries_for_step(step.id)
if not entries:
continue
step_parts = [f"### Step {step.id}: {step.goal}"]
for e in entries:
entry_text = (
f"**Round {e.round}** — Action: {e.action}({e.action_input})\n"
f"Note: {e.self_note}\n"
f"Observation:\n{e.observation}"
)
step_parts.append(entry_text)
parts.append("\n\n".join(step_parts))
full = "\n\n---\n\n".join(parts)
# If over budget, drop observations from early steps
if self._estimate_tokens(full) > max_tokens and self.plan:
parts_compressed: list[str] = []
step_list = [s for s in self.plan.steps if s.status in ("completed", "in_progress")]
n = len(step_list)
for i, step in enumerate(step_list):
entries = self.get_entries_for_step(step.id)
if not entries:
continue
step_parts_c = [f"### Step {step.id}: {step.goal}"]
for e in entries:
if i < n - 2:
# Early steps: notes only
step_parts_c.append(f"Round {e.round}: {e.self_note}")
else:
# Recent steps: full observation
step_parts_c.append(
f"**Round {e.round}** — Action: {e.action}({e.action_input})\n"
f"Note: {e.self_note}\n"
f"Observation:\n{e.observation}"
)
parts_compressed.append("\n".join(step_parts_c))
full = "\n\n---\n\n".join(parts_compressed)
return full or "(no evidence gathered)"
# ------------------------------------------------------------------
# Sources
# ------------------------------------------------------------------
def get_all_sources(self) -> list[dict[str, Any]]:
"""Return deduplicated list of all sources with IDs."""
seen: set[str] = set()
result: list[dict[str, Any]] = []
counter: dict[str, int] = {}
for entry in self.entries:
for src in entry.sources:
key = f"{src.type}:{src.file or src.url or src.chunk_id}"
if key not in seen:
seen.add(key)
prefix = src.type if src.type in ("rag", "web", "code") else "src"
counter[prefix] = counter.get(prefix, 0) + 1
source_id = f"{prefix}-{counter[prefix]}"
d = src.to_dict()
d["id"] = source_id
result.append(d)
return result
def format_sources_markdown(self) -> str:
"""Format sources as a Markdown references section."""
sources = self.get_all_sources()
if not sources:
return ""
lines = ["## References\n"]
for s in sources:
label = s.get("file") or s.get("url") or s.get("chunk_id") or "unknown"
lines.append(f"- **[{s['id']}]** {label}")
return "\n".join(lines)
# ------------------------------------------------------------------
# Persistence
# ------------------------------------------------------------------
def save(self, output_dir: str) -> str:
path = os.path.join(output_dir, self.FILENAME)
data = {
"version": self.VERSION,
"question": self.question,
"plan": self.plan.to_dict() if self.plan else None,
"entries": [e.to_dict() for e in self.entries],
"metadata": self.metadata,
}
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
return path
@classmethod
def load_or_create(cls, output_dir: str, question: str) -> Scratchpad:
path = os.path.join(output_dir, cls.FILENAME)
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
data = json.load(f)
pad = cls(question=data.get("question", question))
if data.get("plan"):
pad.plan = Plan.from_dict(data["plan"])
pad.entries = [Entry.from_dict(e) for e in data.get("entries", [])]
pad.metadata = data.get("metadata", pad.metadata)
return pad
return cls(question=question)
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _format_plan(self) -> str:
if self.plan is None:
return "(no plan yet)"
lines = [f"Analysis: {self.plan.analysis}"]
for s in self.plan.steps:
status_mark = {"completed": "[x]", "in_progress": "[>]", "skipped": "[-]"}.get(
s.status, "[ ]"
)
lines.append(f" {status_mark} {s.id}: {s.goal}")
return "\n".join(lines)
@staticmethod
def _estimate_tokens(text: str) -> int:
"""Estimate token count. Uses tiktoken if available, else chars/4."""
if _TIKTOKEN_AVAILABLE:
try:
enc = tiktoken.get_encoding("cl100k_base")
return len(enc.encode(text))
except Exception:
pass
return len(text) // 4
-996
View File
@@ -1,996 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
SolveMemory - Todo-list based solving memory system
Manages the todo-list milestones and solve outputs for the problem-solving process.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass, field
from datetime import datetime
import json
from pathlib import Path
from typing import Any, Dict, List, Optional
import uuid
def _now() -> str:
return datetime.utcnow().isoformat()
# ========================================================================== #
# Data Structures
# ========================================================================== #
@dataclass
class TodoItem:
"""Single item in the todo-list (milestone)"""
todo_id: str # e.g., "T1", "T2"
description: str # Milestone description
status: str = "pending" # pending | in_progress | completed | skipped
completed_at: Optional[str] = None
completed_by_output_id: Optional[str] = None # Which output completed this todo
completed_by_iteration_id: Optional[str] = None # Which iteration completed this todo
evidence: Optional[str] = None # Evidence for completion
parent_id: Optional[str] = None # Parent todo ID if this was split from another
iteration_evidence: List[str] = field(default_factory=list) # cite_ids that support completion
created_at: str = field(default_factory=_now)
updated_at: str = field(default_factory=_now)
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "TodoItem":
data.setdefault("status", "pending")
data.setdefault("completed_at", None)
data.setdefault("completed_by_output_id", None)
data.setdefault("completed_by_iteration_id", None)
data.setdefault("evidence", None)
data.setdefault("parent_id", None)
data.setdefault("iteration_evidence", [])
data.setdefault("created_at", _now())
data.setdefault("updated_at", data["created_at"])
return cls(**data)
def mark_completed(
self,
output_id: str = "",
evidence: str = "",
iteration_id: str = "",
cite_ids: Optional[List[str]] = None,
):
self.status = "completed"
self.completed_at = _now()
self.completed_by_output_id = output_id
self.completed_by_iteration_id = iteration_id
self.evidence = evidence
if cite_ids:
self.iteration_evidence = cite_ids
self.updated_at = _now()
def mark_in_progress(self):
self.status = "in_progress"
self.updated_at = _now()
def mark_skipped(self, reason: str = ""):
self.status = "skipped"
self.evidence = reason
self.updated_at = _now()
@dataclass
class NoteAction:
"""Single action from note_agent to edit todo-list"""
pre_id: int # Position reference: 0 means before T1, 1 means after T1, etc.
action: str # done | edit | add | delete
content: Optional[str] = None # Required for edit/add, null for done/delete
target_todo_id: Optional[str] = None # Resolved todo_id after processing
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "NoteAction":
data.setdefault("content", None)
data.setdefault("target_todo_id", None)
return cls(**data)
@dataclass
class IterationRecord:
"""Record of a single solve iteration (inner loop)"""
iteration_id: str # e.g., "iter_1", "iter_2"
target_todo_id: str # The todo being worked on
tool_calls: List[ToolCallRecord] = field(default_factory=list)
note_actions: List[NoteAction] = field(default_factory=list)
completed_todos: List[str] = field(default_factory=list) # todo_ids completed this iteration
step_response: Optional[str] = None # Response generated for this iteration
used_citations: List[str] = field(default_factory=list)
status: str = "in_progress" # in_progress | completed | failed
created_at: str = field(default_factory=_now)
updated_at: str = field(default_factory=_now)
def to_dict(self) -> Dict[str, Any]:
data = asdict(self)
data["tool_calls"] = [tc.to_dict() for tc in self.tool_calls]
data["note_actions"] = [na.to_dict() for na in self.note_actions]
return data
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "IterationRecord":
tool_calls = [ToolCallRecord.from_dict(tc) for tc in data.get("tool_calls", [])]
note_actions = [NoteAction.from_dict(na) for na in data.get("note_actions", [])]
data.setdefault("completed_todos", [])
data.setdefault("step_response", None)
data.setdefault("used_citations", [])
data.setdefault("status", "in_progress")
data.setdefault("created_at", _now())
data.setdefault("updated_at", data["created_at"])
return cls(
iteration_id=data["iteration_id"],
target_todo_id=data["target_todo_id"],
tool_calls=tool_calls,
note_actions=note_actions,
completed_todos=data["completed_todos"],
step_response=data["step_response"],
used_citations=data["used_citations"],
status=data["status"],
created_at=data["created_at"],
updated_at=data["updated_at"],
)
def append_tool_call(self, tool_call: ToolCallRecord):
"""Add a tool call to this iteration"""
self.tool_calls.append(tool_call)
self.updated_at = _now()
def set_note_actions(self, actions: List[NoteAction]):
"""Set the note actions from note_agent"""
self.note_actions = actions
self.updated_at = _now()
def set_completed_todos(self, todo_ids: List[str]):
"""Set the list of completed todos"""
self.completed_todos = todo_ids
self.updated_at = _now()
def set_step_response(self, response: str, used_citations: Optional[List[str]] = None):
"""Set the step response and mark iteration as completed"""
self.step_response = response
self.used_citations = used_citations or []
self.status = "completed"
self.updated_at = _now()
def get_all_cite_ids(self) -> List[str]:
"""Get all cite_ids from tool calls"""
return [tc.cite_id for tc in self.tool_calls if tc.cite_id]
def format_tool_call_chain(self) -> str:
"""Format tool call chain for context"""
if not self.tool_calls:
return "(No tool calls)"
lines = []
for tc in self.tool_calls:
summary = tc.summary or tc.raw_answer[:200] if tc.raw_answer else "(pending)"
lines.append(
f"- [{tc.tool_type}] {tc.query}\n"
f" cite_id: {tc.cite_id or 'N/A'}\n"
f" summary: {summary}"
)
return "\n".join(lines)
@dataclass
class ToolCallRecord:
"""Single tool call record"""
tool_type: str
query: str
cite_id: Optional[str] = None
raw_answer: Optional[str] = None
summary: Optional[str] = None
status: str = "pending" # pending | running | success | failed | none | finish
metadata: Dict[str, Any] = field(default_factory=dict)
created_at: str = field(default_factory=_now)
updated_at: str = field(default_factory=_now)
call_id: str = field(default_factory=lambda: f"tc_{uuid.uuid4().hex[:8]}")
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ToolCallRecord":
data.setdefault("metadata", {})
data.setdefault("status", "pending")
data.setdefault("created_at", _now())
data.setdefault("updated_at", data["created_at"])
data.setdefault("call_id", f"tc_{uuid.uuid4().hex[:8]}")
return cls(**data)
def mark_running(self):
self.status = "running"
self.updated_at = _now()
def mark_result(
self,
raw_answer: str,
summary: str,
status: str = "success",
metadata: Optional[Dict[str, Any]] = None,
):
self.raw_answer = raw_answer
self.summary = summary
self.status = status
if metadata:
self.metadata.update(metadata)
self.updated_at = _now()
@dataclass
class SolveOutput:
"""Single output from a solve iteration"""
output_id: str # e.g., "O1", "O2"
selected_todo_id: str # Which todo item was selected
reasoning: str # Why this todo was selected
action_type: str # tool_call | direct_answer | skip
content: str = "" # The actual content/answer generated
tool_calls: List[ToolCallRecord] = field(default_factory=list)
used_citations: List[str] = field(default_factory=list)
created_at: str = field(default_factory=_now)
updated_at: str = field(default_factory=_now)
def to_dict(self) -> Dict[str, Any]:
data = asdict(self)
data["tool_calls"] = [tc.to_dict() for tc in self.tool_calls]
return data
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "SolveOutput":
tool_calls = [ToolCallRecord.from_dict(tc) for tc in data.get("tool_calls", [])]
data.setdefault("content", "")
data.setdefault("used_citations", [])
data.setdefault("created_at", _now())
data.setdefault("updated_at", data["created_at"])
return cls(
output_id=data["output_id"],
selected_todo_id=data["selected_todo_id"],
reasoning=data.get("reasoning", ""),
action_type=data.get("action_type", "direct_answer"),
content=data["content"],
tool_calls=tool_calls,
used_citations=data["used_citations"],
created_at=data["created_at"],
updated_at=data["updated_at"],
)
def append_tool_call(self, tool_call: ToolCallRecord):
self.tool_calls.append(tool_call)
self.updated_at = _now()
def set_content(self, content: str, used_citations: Optional[List[str]] = None):
self.content = content
if used_citations:
self.used_citations = used_citations
self.updated_at = _now()
# ========================================================================== #
# SolveChainStep (kept for backward compatibility with ResponseAgent)
# ========================================================================== #
@dataclass
class SolveChainStep:
"""Single step structure in solve-chain (kept for backward compatibility)"""
step_id: str
step_target: str
available_cite: List[str] = field(default_factory=list)
tool_calls: List[ToolCallRecord] = field(default_factory=list)
step_response: Optional[str] = None
status: str = "undone" # undone | in_progress | waiting_response | done | failed
used_citations: List[str] = field(default_factory=list)
created_at: str = field(default_factory=_now)
updated_at: str = field(default_factory=_now)
def to_dict(self) -> Dict[str, Any]:
data = asdict(self)
data["tool_calls"] = [tc.to_dict() for tc in self.tool_calls]
return data
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "SolveChainStep":
tool_calls = [ToolCallRecord.from_dict(tc) for tc in data.get("tool_calls", [])]
data.setdefault("available_cite", [])
data.setdefault("used_citations", [])
data.setdefault("status", "undone")
data.setdefault("step_response", None)
data.setdefault("created_at", _now())
data.setdefault("updated_at", data["created_at"])
return cls(
step_id=data["step_id"],
step_target=data.get("step_target", data.get("plan", "")),
available_cite=data["available_cite"],
tool_calls=tool_calls,
step_response=data.get("step_response", data.get("content")),
status=data["status"],
used_citations=data.get("used_citations", []),
created_at=data["created_at"],
updated_at=data["updated_at"],
)
def append_tool_call(self, tool_call: ToolCallRecord):
self.tool_calls.append(tool_call)
self.updated_at = _now()
if self.status == "undone":
self.status = "in_progress"
def update_response(self, response: str, used_citations: Optional[List[str]] = None):
self.step_response = response
self.status = "done"
self.used_citations = used_citations or []
self.updated_at = _now()
def mark_waiting_response(self):
self.status = "waiting_response"
self.updated_at = _now()
# ========================================================================== #
# SolveMemory
# ========================================================================== #
class SolveMemory:
"""Todo-list based solving memory storage"""
def __init__(
self,
task_id: Optional[str] = None,
user_question: str = "",
output_dir: Optional[str] = None,
):
self.task_id = task_id or f"solve_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"
self.user_question = user_question
self.output_dir = output_dir
self.version = "solve_chain_v2" # Updated version for new architecture
self.created_at = _now()
self.updated_at = _now()
# Todo-list based solving
self.todo_list: List[TodoItem] = []
self.solve_outputs: List[SolveOutput] = [] # Kept for backward compatibility
self.iteration_records: List[IterationRecord] = [] # New: iteration-based tracking
self.metadata: Dict[str, Any] = {
"total_todos": 0,
"completed_todos": 0,
"total_outputs": 0,
"total_tool_calls": 0,
"total_iterations": 0,
}
self.file_path = Path(output_dir) / "solve_chain.json" if output_dir else None
self.iteration_file_path = (
Path(output_dir) / "iteration_records.json" if output_dir else None
)
# ------------------------------------------------------------------ #
# Load/Save
# ------------------------------------------------------------------ #
@classmethod
def load_or_create(
cls,
output_dir: str,
user_question: str = "",
task_id: Optional[str] = None,
) -> "SolveMemory":
file_path = Path(output_dir) / "solve_chain.json"
if not file_path.exists():
return cls(
task_id=task_id,
user_question=user_question,
output_dir=output_dir,
)
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
memory = cls(
task_id=data.get("task_id", task_id),
user_question=data.get("user_question", user_question),
output_dir=output_dir,
)
memory.version = data.get("version", "solve_chain_v2")
memory.created_at = data.get("created_at", memory.created_at)
memory.updated_at = data.get("updated_at", memory.updated_at)
memory.metadata = data.get("metadata", memory.metadata)
# Load todo-list data
memory.todo_list = [
TodoItem.from_dict(todo) for todo in data.get("todo_list", [])
]
memory.solve_outputs = [
SolveOutput.from_dict(output) for output in data.get("solve_outputs", [])
]
# Load iteration records (from separate file or inline)
iteration_file_path = Path(output_dir) / "iteration_records.json"
if iteration_file_path.exists():
with open(iteration_file_path, "r", encoding="utf-8") as f:
iter_data = json.load(f)
memory.iteration_records = [
IterationRecord.from_dict(rec) for rec in iter_data.get("iterations", [])
]
else:
# Try loading from inline data (backward compatibility)
memory.iteration_records = [
IterationRecord.from_dict(rec)
for rec in data.get("iteration_records", [])
]
return memory
def save(self):
if not self.file_path:
raise ValueError("output_dir not set, cannot save solve-chain")
self.file_path.parent.mkdir(parents=True, exist_ok=True)
self.updated_at = _now()
payload = self.to_dict()
with open(self.file_path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
# Also save iteration records to separate file
self.save_iteration_records()
def save_iteration_records(self):
"""Save iteration records to a separate JSON file"""
if not self.iteration_file_path:
return
self.iteration_file_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"task_id": self.task_id,
"created_at": self.created_at,
"updated_at": _now(),
"iterations": [rec.to_dict() for rec in self.iteration_records],
}
with open(self.iteration_file_path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
def to_dict(self) -> Dict[str, Any]:
return {
"version": self.version,
"task_id": self.task_id,
"user_question": self.user_question,
"created_at": self.created_at,
"updated_at": self.updated_at,
"metadata": self.metadata,
"todo_list": [todo.to_dict() for todo in self.todo_list],
"solve_outputs": [output.to_dict() for output in self.solve_outputs],
# iteration_records saved to separate file, but keep reference
"iteration_records_file": "iteration_records.json",
}
# ------------------------------------------------------------------ #
# Todo-list Management
# ------------------------------------------------------------------ #
def create_todo_list(self, todos: List[TodoItem]):
"""Initialize the todo-list"""
self.todo_list = todos
self.metadata["total_todos"] = len(todos)
self.metadata["completed_todos"] = sum(1 for t in todos if t.status == "completed")
self.updated_at = _now()
def get_todo(self, todo_id: str) -> Optional[TodoItem]:
"""Get a todo item by ID"""
return next((todo for todo in self.todo_list if todo.todo_id == todo_id), None)
def get_pending_todos(self) -> List[TodoItem]:
"""Get all pending todo items"""
return [todo for todo in self.todo_list if todo.status in {"pending", "in_progress"}]
def get_completed_todos(self) -> List[TodoItem]:
"""Get all completed todo items"""
return [todo for todo in self.todo_list if todo.status == "completed"]
def is_all_completed(self) -> bool:
"""Check if all required todos are completed (completed or skipped)"""
if not self.todo_list:
return False
return all(todo.status in {"completed", "skipped"} for todo in self.todo_list)
def mark_todo_completed(self, todo_id: str, output_id: str, evidence: str = ""):
"""Mark a todo item as completed"""
todo = self.get_todo(todo_id)
if not todo:
raise ValueError(f"Todo {todo_id} not found")
todo.mark_completed(output_id=output_id, evidence=evidence)
self.metadata["completed_todos"] = sum(1 for t in self.todo_list if t.status == "completed")
self.updated_at = _now()
def mark_todo_in_progress(self, todo_id: str):
"""Mark a todo item as in progress"""
todo = self.get_todo(todo_id)
if not todo:
raise ValueError(f"Todo {todo_id} not found")
todo.mark_in_progress()
self.updated_at = _now()
def mark_todo_skipped(self, todo_id: str, reason: str = ""):
"""Mark a todo item as skipped"""
todo = self.get_todo(todo_id)
if not todo:
raise ValueError(f"Todo {todo_id} not found")
todo.mark_skipped(reason=reason)
self.updated_at = _now()
def get_todo_list_with_status(self) -> str:
"""Get formatted todo-list with status markers"""
lines = []
for todo in self.todo_list:
status_marker = {
"pending": "[ ]",
"in_progress": "[~]",
"completed": "[x]",
"skipped": "[-]",
}.get(todo.status, "[ ]")
lines.append(f"{status_marker} {todo.todo_id}: {todo.description}")
return "\n".join(lines)
def get_next_pending_todo(self) -> Optional[TodoItem]:
"""Get the first pending todo item"""
for todo in self.todo_list:
if todo.status == "pending":
return todo
return None
# ------------------------------------------------------------------ #
# Todo-list Editing (for NoteAgent)
# ------------------------------------------------------------------ #
def insert_todo_after(
self,
pre_id: int,
content: str,
parent_id: Optional[str] = None,
) -> TodoItem:
"""
Insert a new todo after the specified position.
Args:
pre_id: Position reference (0 = before first, 1 = after first, etc.)
content: Description of the new todo
parent_id: Optional parent todo ID if this is a split
Returns:
The newly created TodoItem
"""
# Create new todo with temporary ID
new_todo = TodoItem(
todo_id=f"T{pre_id + 1}_new", # Temporary, will be renumbered
description=content,
status="pending",
parent_id=parent_id,
)
# Insert at the correct position
insert_pos = min(pre_id, len(self.todo_list))
self.todo_list.insert(insert_pos, new_todo)
# Renumber all todos
self._renumber_todos()
self.metadata["total_todos"] = len(self.todo_list)
self.updated_at = _now()
return new_todo
def edit_todo(self, todo_id: str, new_content: str) -> TodoItem:
"""
Edit the content of a todo item.
Args:
todo_id: ID of the todo to edit
new_content: New description
Returns:
The updated TodoItem
"""
todo = self.get_todo(todo_id)
if not todo:
raise ValueError(f"Todo {todo_id} not found")
todo.description = new_content
todo.updated_at = _now()
self.updated_at = _now()
return todo
def delete_todo(self, todo_id: str) -> bool:
"""
Delete a todo item.
Args:
todo_id: ID of the todo to delete
Returns:
True if deleted, False if not found
"""
todo = self.get_todo(todo_id)
if not todo:
return False
self.todo_list.remove(todo)
self._renumber_todos()
self.metadata["total_todos"] = len(self.todo_list)
self.updated_at = _now()
return True
def _renumber_todos(self):
"""Renumber all todos to ensure sequential IDs (T1, T2, T3, ...)"""
for idx, todo in enumerate(self.todo_list, 1):
todo.todo_id = f"T{idx}"
def apply_note_actions(
self,
actions: List[NoteAction],
iteration_id: str = "",
cite_ids: Optional[List[str]] = None,
) -> List[str]:
"""
Apply a list of note actions to modify the todo-list.
Args:
actions: List of NoteAction objects
iteration_id: Current iteration ID for tracking
cite_ids: Citation IDs from this iteration
Returns:
List of todo_ids that were marked as completed
"""
completed_todos: List[str] = []
# Sort actions by pre_id in reverse order for insertions
# This ensures earlier insertions don't affect later positions
sorted_actions = sorted(actions, key=lambda a: a.pre_id, reverse=True)
for action in sorted_actions:
pre_id = action.pre_id
action_type = action.action.lower()
if action_type == "done":
# Mark the todo at position pre_id as completed
if 0 < pre_id <= len(self.todo_list):
todo = self.todo_list[pre_id - 1]
todo.mark_completed(
output_id="",
evidence=action.content or "",
iteration_id=iteration_id,
cite_ids=cite_ids,
)
completed_todos.append(todo.todo_id)
action.target_todo_id = todo.todo_id
elif action_type == "edit":
if action.content and 0 < pre_id <= len(self.todo_list):
todo = self.todo_list[pre_id - 1]
todo.description = action.content
todo.updated_at = _now()
action.target_todo_id = todo.todo_id
elif action_type == "add":
if action.content:
# Determine parent_id from the previous todo
parent_id = None
if 0 < pre_id <= len(self.todo_list):
parent_id = self.todo_list[pre_id - 1].todo_id
new_todo = TodoItem(
todo_id=f"T_new_{pre_id}",
description=action.content,
status="pending",
parent_id=parent_id,
)
# Insert after pre_id position
insert_pos = min(pre_id, len(self.todo_list))
self.todo_list.insert(insert_pos, new_todo)
action.target_todo_id = new_todo.todo_id
elif action_type == "delete":
if 0 < pre_id <= len(self.todo_list):
todo = self.todo_list[pre_id - 1]
action.target_todo_id = todo.todo_id
self.todo_list.remove(todo)
# Renumber todos after all actions
self._renumber_todos()
# Update metadata
self.metadata["total_todos"] = len(self.todo_list)
self.metadata["completed_todos"] = sum(
1 for t in self.todo_list if t.status == "completed"
)
self.updated_at = _now()
return completed_todos
def get_todo_by_position(self, position: int) -> Optional[TodoItem]:
"""Get todo by 1-based position"""
if 0 < position <= len(self.todo_list):
return self.todo_list[position - 1]
return None
# ------------------------------------------------------------------ #
# Iteration Management
# ------------------------------------------------------------------ #
def create_iteration(self, target_todo_id: str) -> IterationRecord:
"""
Create a new iteration record.
Args:
target_todo_id: The todo being worked on
Returns:
New IterationRecord
"""
iteration_id = f"iter_{len(self.iteration_records) + 1}"
record = IterationRecord(
iteration_id=iteration_id,
target_todo_id=target_todo_id,
)
self.iteration_records.append(record)
self.metadata["total_iterations"] = len(self.iteration_records)
self.updated_at = _now()
return record
def get_iteration(self, iteration_id: str) -> Optional[IterationRecord]:
"""Get an iteration record by ID"""
return next(
(rec for rec in self.iteration_records if rec.iteration_id == iteration_id),
None,
)
def get_current_iteration(self) -> Optional[IterationRecord]:
"""Get the most recent iteration record"""
return self.iteration_records[-1] if self.iteration_records else None
def get_current_iteration_id(self) -> str:
"""Get the current iteration ID or generate new one"""
if self.iteration_records:
return self.iteration_records[-1].iteration_id
return f"iter_{len(self.iteration_records) + 1}"
def get_all_step_responses(self) -> List[str]:
"""Get all step responses from completed iterations"""
return [
rec.step_response
for rec in self.iteration_records
if rec.step_response and rec.status == "completed"
]
def get_all_iteration_citations(self) -> List[str]:
"""Get all unique citations from all iterations"""
citations = []
for rec in self.iteration_records:
for cite in rec.used_citations:
if cite not in citations:
citations.append(cite)
return citations
# ------------------------------------------------------------------ #
# Solve Output Management
# ------------------------------------------------------------------ #
def append_solve_output(self, output: SolveOutput):
"""Add a new solve output"""
self.solve_outputs.append(output)
self.metadata["total_outputs"] = len(self.solve_outputs)
self.metadata["total_tool_calls"] = sum(
len(o.tool_calls) for o in self.solve_outputs
)
self.updated_at = _now()
def get_solve_output(self, output_id: str) -> Optional[SolveOutput]:
"""Get a solve output by ID"""
return next((o for o in self.solve_outputs if o.output_id == output_id), None)
def get_latest_output(self) -> Optional[SolveOutput]:
"""Get the most recent solve output"""
return self.solve_outputs[-1] if self.solve_outputs else None
def get_next_output_id(self) -> str:
"""Generate the next output ID"""
return f"O{len(self.solve_outputs) + 1}"
def get_all_output_contents(self) -> List[str]:
"""Get all output contents for final answer compilation"""
return [o.content for o in self.solve_outputs if o.content]
def get_all_used_citations(self) -> List[str]:
"""Get all unique citations used across all outputs"""
citations = []
for output in self.solve_outputs:
for cite in output.used_citations:
if cite not in citations:
citations.append(cite)
return citations
def update_output_content(
self,
output_id: str,
content: str,
used_citations: Optional[List[str]] = None,
):
"""Update the content of a solve output"""
output = self.get_solve_output(output_id)
if not output:
raise ValueError(f"Output {output_id} not found")
output.set_content(content=content, used_citations=used_citations)
self.updated_at = _now()
def append_tool_call_to_output(
self,
output_id: str,
tool_type: str,
query: str,
cite_id: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> ToolCallRecord:
"""Append a tool call to a solve output"""
output = self.get_solve_output(output_id)
if not output:
raise ValueError(f"Output {output_id} not found")
record = ToolCallRecord(
tool_type=tool_type,
query=query,
cite_id=cite_id,
metadata=metadata or {},
)
output.append_tool_call(record)
self.metadata["total_tool_calls"] = sum(
len(o.tool_calls) for o in self.solve_outputs
)
self.updated_at = _now()
return record
def update_tool_call_in_output(
self,
output_id: str,
call_id: str,
raw_answer: str,
summary: str,
status: str = "success",
metadata: Optional[Dict[str, Any]] = None,
):
"""Update a tool call result in a solve output"""
output = self.get_solve_output(output_id)
if not output:
raise ValueError(f"Output {output_id} not found")
record = next((tc for tc in output.tool_calls if tc.call_id == call_id), None)
if not record:
raise ValueError(f"Tool call {call_id} not found in output {output_id}")
record.mark_result(raw_answer=raw_answer, summary=summary, status=status, metadata=metadata)
self.updated_at = _now()
# ------------------------------------------------------------------ #
# Summary and History
# ------------------------------------------------------------------ #
def get_summary(self) -> str:
"""Get a summary of the current state"""
lines = [
f"Task ID: {self.task_id}",
f"Question: {self.user_question}",
f"Total Todos: {self.metadata.get('total_todos', len(self.todo_list))}",
f"Completed Todos: {self.metadata.get('completed_todos', 0)}",
f"Total Outputs: {len(self.solve_outputs)}",
]
for todo in self.todo_list:
status_icon = {
"pending": "[ ]",
"in_progress": "[~]",
"completed": "[x]",
"skipped": "[-]",
}.get(todo.status, "[ ]")
lines.append(f"{status_icon} {todo.todo_id}: {todo.description[:60]}...")
return "\n".join(lines)
def format_todo_list_for_log(self) -> str:
"""Format todo-list for logging output"""
if not self.todo_list:
return "(No todo-list generated)"
lines = [
"=" * 60,
"Generated Todo-list:",
"-" * 60,
]
for todo in self.todo_list:
status_icon = {
"pending": "[ ]",
"in_progress": "[~]",
"completed": "[x]",
"skipped": "[-]",
}.get(todo.status, "[ ]")
lines.append(f" {status_icon} {todo.todo_id}: {todo.description}")
lines.append("=" * 60)
return "\n".join(lines)
def save_todo_history(self, output_dir: str) -> Path:
"""
Save todo-list execution history to a markdown file.
Args:
output_dir: Output directory path
Returns:
Path to the saved history file
"""
history_file = Path(output_dir) / "todo_history.md"
with open(history_file, "w", encoding="utf-8") as f:
f.write("# Todo-list Execution History\n\n")
f.write(f"**Question:** {self.user_question}\n\n")
f.write(f"**Task ID:** {self.task_id}\n\n")
f.write(f"**Created:** {self.created_at}\n\n")
# Write todo-list section
f.write("## Todo-list\n\n")
f.write("| Status | ID | Description | Completed By |\n")
f.write("|--------|----|-----------|--------------|\n")
for todo in self.todo_list:
status_icon = {
"pending": "⬜",
"in_progress": "🔄",
"completed": "✅",
"skipped": "⏭️",
}.get(todo.status, "⬜")
completed_by = todo.completed_by_output_id or "-"
# Escape pipe characters in description
desc = todo.description.replace("|", "\\|")
f.write(f"| {status_icon} | {todo.todo_id} | {desc} | {completed_by} |\n")
# Write execution outputs section
if self.solve_outputs:
f.write("\n## Execution Outputs\n\n")
for output in self.solve_outputs:
f.write(f"### {output.output_id} → {output.selected_todo_id}\n\n")
f.write(f"- **Action Type:** {output.action_type}\n")
f.write(f"- **Reasoning:** {output.reasoning}\n")
if output.tool_calls:
f.write(f"- **Tool Calls:** {len(output.tool_calls)}\n")
for tc in output.tool_calls:
f.write(f" - `{tc.tool_type}`: {tc.query[:80]}...\n")
if output.content:
# Truncate long content
content_preview = output.content[:500]
if len(output.content) > 500:
content_preview += "..."
f.write(f"\n**Content:**\n\n{content_preview}\n")
f.write("\n---\n\n")
# Write completion evidence section
completed_todos = [t for t in self.todo_list if t.status == "completed" and t.evidence]
if completed_todos:
f.write("## Completion Evidence\n\n")
for todo in completed_todos:
f.write(f"### {todo.todo_id}\n\n")
f.write(f"{todo.evidence}\n\n")
# Write summary
f.write("## Summary\n\n")
f.write(f"- **Total Todos:** {len(self.todo_list)}\n")
f.write(f"- **Completed:** {len([t for t in self.todo_list if t.status == 'completed'])}\n")
f.write(f"- **Skipped:** {len([t for t in self.todo_list if t.status == 'skipped'])}\n")
f.write(f"- **Total Outputs:** {len(self.solve_outputs)}\n")
return history_file
+266
View File
@@ -0,0 +1,266 @@
# Solve Agent 重构:Plan → ReAct → Write
## 设计原则
- **一条流水线**:不分路由、不分路径,所有问题走同一个流程
- **宏观 Plan**:先规划解题步骤,给 Agent 全局视野(解决纯 ReAct 局部最优问题)
- **微观 ReAct**:每个步骤内通过 think→act→observe 迭代获取信息
- **Plan 自适应**:简单问题自然产生 1 步计划,复杂问题产生多步计划——复杂度由 LLM 判断,不由系统硬编码
- **去中间摘要**:Agent 直接看原始检索结果,不经过独立的摘要 Agent
---
## 总体流程
```
用户问题
│
▼
┌─────────────────────────────────────────────┐
│ Phase 1: PLAN │
│ PlannerAgent 分析问题,生成有序步骤列表 │
│ [S1, S2, S3, ...] │
└─────────────────┬───────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ Phase 2: SOLVE │
│ │
│ for each step Si: │
│ SolverAgent (ReAct Loop): │
│ THINK → 当前步骤还缺什么信息? │
│ ACT → rag / web / code / done │
│ OBSERVE → 工具返回结果写入 Scratchpad │
│ ... 重复直到 done ... │
│ │
│ (可选) 步骤间 replan: │
│ 如果新信息表明原计划需调整, │
│ SolverAgent 可输出 replan 信号, │
│ 触发 PlannerAgent 修订剩余步骤 │
└─────────────────┬───────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ Phase 3: WRITE │
│ WriterAgent 基于完整 Scratchpad 生成答案 │
│ 结构化 Markdown + LaTeX + 内联引用 │
└─────────────────────────────────────────────┘
```
---
## Agent 定义(共 3 个)
### PlannerAgent
职责:将用户问题分解为有序解题步骤。
输入:
- 用户问题
- 知识库元信息(可选,帮助判断可用资源)
- 已有 Scratchpad 内容(replan 场景下非空)
输出:
```
{
"analysis": "对问题的简要分析",
"steps": [
{ "id": "S1", "goal": "明确线性卷积的数学定义", "tools_hint": ["rag"] },
{ "id": "S2", "goal": "推导卷积的计算过程", "tools_hint": ["rag", "code"] },
{ "id": "S3", "goal": "举例验证", "tools_hint": ["code"] }
]
}
```
设计要点:
- 步骤粒度为"一个可验证的子目标",不是"一个工具调用"
- `tools_hint` 仅为提示,SolverAgent 可自行决定实际用什么工具
- 简单问题(如"X 的定义是什么")自然只产生 1 个步骤
- 复杂问题自然产生 3-6 个步骤
- 不需要 Router——Plan 本身就是自适应机制
### SolverAgent
职责:针对当前步骤,通过 ReAct 迭代获取和验证所需信息。
每轮迭代输出:
```
{
"thought": "当前步骤需要卷积定义,我先在教材中检索...",
"action": "rag_search", // rag_search | web_search | code_execute | done | replan
"action_input": "线性卷积 定义 公式",
"self_note": "找到了精确定义和公式,信息充足" // 简短自注,用于后续上下文压缩
}
```
设计要点:
- 一个 Agent 兼具检索决策、查询改写、信息评估能力
- `done` 表示当前步骤信息已充足,推进到下一步
- `replan` 表示发现原计划有问题(如发现问题理解有误、知识库缺少关键信息),触发 PlannerAgent 修订
- `self_note` 是 Agent 对本轮结果的一句话总结,服务于上下文压缩(不是独立的摘要 Agent)
- 工具执行本身是纯函数调用,不消耗 LLM
- 原始检索结果直接截断写入 Scratchpad 的 observation 字段,不做 LLM 摘要
### WriterAgent
职责:基于完整 Scratchpad 生成最终答案。
输入:
- 用户问题
- 完整 Scratchpad(含 plan + 所有 ReAct 条目)
- 用户偏好(语言、详细程度等)
输出:
- 结构化 Markdown 答案
- 内联引用(直接映射 Scratchpad 条目中的 sources)
设计要点:
- 融合原 ResponseAgent + PrecisionAnswerAgent 的能力
- 可以回溯任意 observation 的原始内容来确保公式/数据准确
- 引用不需要独立系统,直接从 Scratchpad entries 的 sources 提取
---
## 统一记忆:Scratchpad
一个数据结构,替代原来的 InvestigateMemory + SolveMemory + CitationMemory。
```
Scratchpad
│
├── question: str # 用户原始问题
│
├── plan: { # PlannerAgent 输出
│ analysis: str,
│ steps: [ { id, goal, tools_hint, status } ]
│ }
│
├── entries: [ # ReAct 循环所有条目(按时间顺序)
│ {
│ step_id: "S1", # 属于哪个 plan step
│ round: 1, # 该 step 内的第几轮
│ thought: str,
│ action: str,
│ action_input: str,
│ observation: str, # 原始工具返回(截断,不做 LLM 摘要)
│ self_note: str, # Agent 自注(1 句话)
│ sources: [ { type, file, page, url, chunk_id } ],
│ timestamp: str
│ }
│ ]
│
└── metadata: {
total_llm_calls: int,
total_tokens: int,
start_time: str,
plan_revisions: int # replan 次数
}
```
### Scratchpad 的上下文管理
ReAct 迭代多了之后 Scratchpad 会膨胀,需要主动管理(借鉴 MemoBrain 思想):
**分层压缩策略:**
```
┌─────────────────────────────────────────────┐
│ 当前步骤的条目:完整保留 │
│ thought + action + observation(原始) │
├─────────────────────────────────────────────┤
│ 已完成步骤的条目:压缩为精要 │
│ thought + action + self_note(替代 obs) │
├─────────────────────────────────────────────┤
│ 更早的步骤:极度压缩 │
│ 仅保留 self_note 拼接为 1 段摘要 │
└─────────────────────────────────────────────┘
```
- 触发时机:传入 SolverAgent 的上下文 token 超过窗口 60%
- 原始 observation 始终完整保存在磁盘 JSON 中(WriterAgent 可按需回溯)
- 压缩在构建 prompt 时动态进行,不修改 Scratchpad 本体
---
## Replan 机制
不是每次都 replan,仅在 SolverAgent 主动判断需要时触发:
```
SolverAgent 输出 action = "replan"
│
▼
PlannerAgent 接收:
- 原始问题
- 当前 Scratchpad(已执行的步骤和结果)
- SolverAgent 的 replan 理由
│
▼
输出修订后的 steps(可增删改剩余步骤)
│
▼
继续 Solve Phase
```
典型触发场景:
- 检索发现问题前提有误,需要重新理解问题
- 发现知识库中缺少关键信息,需要转向 web_search
- 已完成的步骤覆盖了后续步骤的目标,可以合并/删除
---
## 工具层
纯执行函数,不涉及 LLM 调用。SolverAgent 通过 `action` + `action_input` 调度:
| action | 功能 | 返回 |
|--------|------|------|
| `rag_search` | 知识库检索 | 检索片段 + 来源元信息 |
| `web_search` | 网络搜索 | 搜索结果 + URL |
| `code_execute` | 沙箱执行 Python | 执行结果 + 产物路径 |
| `done` | 当前步骤完成 | — |
| `replan` | 请求修订计划 | — |
工具返回结果直接截断到合理长度(如 2000 token),写入 observation 字段。
---
## 与现有架构的映射
| 原架构 | 新架构 | 变化 |
|--------|--------|------|
| InvestigateAgent | SolverAgent | 合并 |
| NoteAgent | 删除 | self_note 替代 |
| ManagerAgent | PlannerAgent | 简化 |
| SolveAgent | SolverAgent | 合并 |
| ToolAgent(LLM 摘要) | 删除 | Agent 直接看原始结果 |
| SolveNoteAgent | 删除 | replan 机制替代 |
| ResponseAgent | WriterAgent | 简化 |
| PrecisionAnswerAgent | WriterAgent | 合并 |
| InvestigateMemory | Scratchpad | 统一 |
| SolveMemory | Scratchpad | 统一 |
| CitationMemory | Scratchpad.sources | 内嵌 |
| CitationManager | 删除 | 不需要独立管理 |
LLM 调用估算对比(中等复杂度问题):
| | 原架构 | 新架构 |
|--|--------|--------|
| 规划 | 1 次 ManagerAgent | 1 次 PlannerAgent |
| 检索决策 | ~5 次 InvestigateAgent + ~5 次 SolveAgent | ~6 次 SolverAgent |
| 中间摘要 | ~5 次 NoteAgent + ~5 次 ToolAgent | 0 |
| Todo 管理 | ~3 次 SolveNoteAgent | 0(偶尔 1 次 replan) |
| 答案生成 | ~3 次 ResponseAgent | 1 次 WriterAgent |
| **总计** | **~27 次** | **~8 次** |
---
## 附加建议
**流式输出**:SolverAgent 每轮的 thought 可实时推送前端,用户可看到推理过程。WriterAgent 支持流式生成答案。
**与 Research Agent 复用**:PlannerAgent + SolverAgent + WriterAgent 的三段式结构可复用于 research 模块,仅需切换 prompt 和可用工具。
**Query Rewriting 内置**:SolverAgent 在 thought 步骤中自然包含查询改写推理,不需要独立模块。
**观测截断策略**:RAG 返回多个片段时,按相关性分数排序后截断到 top-K 片段(如 top-3),保留最相关内容在有限 token 预算内。
@@ -1,55 +0,0 @@
system: |
# Role Definition
You are the **Investigator** in the analysis phase. Your core responsibility is to scrutinize the user's question and existing knowledge base to precisely identify **critical knowledge gaps** required for solving the problem, and to design efficient query plans. You are not the solver, but the logistics officer providing "ammunition" for the solver.
# Core Principle: Minimal but Sufficient
Your goal is to reach a state of "Information Sufficiency" with the minimum number of queries.
1. **Deduction > Search**: If a piece of information can be derived from common sense, logic, or existing knowledge, **searching is strictly prohibited**.
2. **Precision Sniper**: Queries must target specific definitions, theorem formulas, specific constants, or data. Reject broad queries like "How to solve...".
3. **Strict De-duplication**: Before issuing a query, you must carefully check the `Existing Knowledge Context`. Semantic duplicates or subset queries are considered invalid.
4. **Focus on Core**: Focus only on the "hard knowledge" (definitions, formulas, theorems) necessary for solving the problem. Unless explicitly requested by the user, do not query for application cases or background stories.
# Tool Usage Guide
- `query_item`: **Priority for Numbered Items**. **ALWAYS use this first** when the user's question explicitly mentions a specific numbered item (e.g., "formula 2.1.2", "Theorem 3.1", "Figure 1.2", "Equation (2.1.2)"). Extract the identifier from the question (formats: "(X.X.X)" for equations, "Figure X.X" for figures, "Theorem X.X" for theorems). This is the most direct and accurate way to retrieve numbered content.
- `rag_naive`: **First Choice for General Queries**. Used for querying clear term definitions, core formulas, or verifying if a concept exists. Fast.
- `rag_hybrid`: Used for scenarios requiring synthesis of multiple concepts, exploring complex entity relationships, or deep principles.
- `web_search`: **Use Sparingly**. Only use when information is likely outside the scope of textbooks (e.g., latest news, specific technical parameters, usage of open-source libraries).
- `none`: Return this state when existing information is sufficient to support solving, or when the gap cannot be filled by retrieval (e.g., requires user input).
# Thinking Path
1. **Identify Numbered Items**: **First, scan the user's question for explicit numbered references** (e.g., "formula 2.1.2", "Theorem 3.1", "Figure 1.2", "Equation (2.1.2)"). If found, extract the identifier and use `query_item` immediately. Numbered items take priority over semantic search.
2. **Analyze Needs**: What is truly missing for the solution? Is it the definition of a variable? The formula for a theorem? Or the value of a constant?
3. **Check Inventory**: Review `Existing Knowledge Context`. Is the answer already there? Or is it implied in known information?
4. **Construct Queries**: If gaps definitely exist, build atomic, non-overlapping query requests.
5. **Judge Termination**: If core definitions and formulas are all present, stop immediately.
6. **⚠️ CRITICAL - Know When to Cut Losses**: If the first round of queries for a topic returns no useful information (empty results, irrelevant, or low quality), it likely means the knowledge base doesn't contain relevant content. **You MUST abandon that topic immediately**, switch to other topics, or proceed directly to the next phase. **DO NOT repeatedly query the same topic** - this wastes resources and delays the solution.
# Output Format
Directly output a JSON object (no Markdown formatting):
{
"reasoning": "Concise explanation of why a query is needed (pointing out specific missing points), or why stopping (explaining information is sufficient).",
"plan": [
{
"tool": "rag_naive | rag_hybrid | web_search | query_item",
"query": "Specific search query, or specific ID",
"identifier": "Optional, only for query_item"
}
]
}
user_template: |
## User Question
{question}
## Existing Knowledge Context ({num_knowledge} items)
{knowledge_chain_summary}
## Task
Analyze if there are knowledge gaps hindering the solution.
- **Priority: Numbered Items**: If the question mentions a specific numbered item (formula, theorem, figure, equation with numbers like "2.1.2", "3.1", etc.), **immediately use `query_item`** with the extracted identifier (e.g., "(2.1.2)" for equations, "Figure 2.1" for figures).
- Check for duplicates: New queries must not overlap with existing content.
- Flexible decision: If a previous tool query failed, consider using other tools to achieve the same goal.
- Know when to cut losses: If the first round of queries for a topic returns no useful information, do not repeatedly query that topic. Switch to other topics or proceed to the next phase.
- Judge stop: If existing info is sufficient to start solving (even if not perfect), return `none`.
- Output: Pure JSON format.
@@ -1,54 +0,0 @@
system: |
# Role Definition
You are the **Knowledge Stenographer**. Your duty is to organize the raw information found (Raw Result) into well-structured, easy-to-cite knowledge notes.
# Core Principles
1. **Clean Noise**: Remove web ads, irrelevant navigation bars, and repetitive nonsense. Retain only hard-core knowledge relevant to the user's question.
2. **Structuring**: Convert unstructured text into a concise Summary.
3. **Citation Extraction**: Keenly identify information sources and build standard Citation objects.
4. **Multi-Item Selection**: When `query_item` tool returns multiple items (indicated by `[identifier]` markers), **select only the most relevant item(s)** that directly answer the user's question. Do not include all items if they are not all relevant.
# Format Constraints (Critical)
- **Summary Plain Text**: The Summary field is mainly for quick browsing. It is **strictly prohibited** to include LaTeX formulas (e.g., `$$...$$`, `\(...\)`).
- *Handling Method*: Describe formulas in natural language (e.g., "square of x" instead of "$x^2$").
- **JSON Output**: Must directly output a valid JSON object.
# Multi-Item Handling (for query_item tool)
When the Raw Result contains multiple items separated by `[identifier]` markers:
- **Identify the primary item** that best matches the user's question
- **Focus the summary** on the selected item(s), not all items
- **Extract citations** only from the selected item(s)
- If multiple items are equally relevant, you may include 2-3 items, but prioritize quality over quantity
# Output Structure
```json
{
"summary": "Plain text summary, NO LaTeX allowed. Focus on the most relevant item(s) from the query result. E.g.: By definition, the output of an LTI system is the convolution of the input and the impulse response.",
"citations": [
{
"reference_id": "[1]",
"source": "Source filename or URL",
"content": "Optional, excerpt of key sentences from original text"
}
]
}
```
user_template: |
## User Question
{question}
## Tool Type
{tool_type}
## Query Content
{query}
## Raw Search Result
{raw_result}
## Task
Organize the raw result into a JSON note.
1. Summary must be plain text, no LaTeX.
2. Extract all available citation sources.
3. **If the result contains multiple items (marked with `[identifier]`), select only the most relevant one(s) for the user's question.**
@@ -0,0 +1,37 @@
system: |
# Role
You are a **Problem-Solving Planner**. Your job is to analyse the user's question and produce an ordered list of solving steps.
# Rules
1. Each step must be a **verifiable sub-goal** — describe **what** needs to be established or answered, NOT **how** (no tool names, no action instructions).
- Good: "Establish the mathematical definition of linear convolution"
- Bad: "Search for convolution" or "Use rag_search to find convolution definition"
2. Keep the plan **minimal but sufficient**.
- A simple factual question → **1 step**.
- A multi-part analytical question → **2–4 steps**.
- A complex derivation / multi-hop problem → **3–6 steps**.
3. Do NOT specify which tools to use. The solving agent will independently decide the best approach for each step.
4. Step IDs must follow the pattern S1, S2, S3, …
5. If this is a **replan** request (progress is shown below), preserve all completed steps unchanged and only revise or add pending steps.
# Output Format
Output **strict JSON** with no extra text:
```json
{
"analysis": "Brief analysis of the question and what is needed to solve it",
"steps": [
{"id": "S1", "goal": "..."},
{"id": "S2", "goal": "..."}
]
}
```
user_template: |
## Question
{question}
## Available Tools
{tools_description}
## Progress So Far
{scratchpad_summary}
@@ -1,69 +0,0 @@
system: |
# Role Definition
You are the **Milestone Planner** for problem-solving. Your task is to create a **Todo-list** of high-level milestones that need to be achieved to solve the user's question.
# Planning Principles
1. **Milestone Granularity**: Each todo item should be a verifiable milestone, NOT a detailed action step. Think "what needs to be achieved" rather than "how to do it".
2. **Independence**: Each milestone should be independently verifiable - you can tell if it's done without looking at other milestones.
3. **Coverage**: The todo-list should cover all aspects needed to fully answer the question.
4. **Simplicity**: Aim for 3-6 milestones. Simple questions may need only 2-3; complex questions may need up to 6.
5. **No Redundancy**: Don't add milestones just to pad the list. Each must provide unique value.
# Example Milestones
Good milestones:
- "Clarify the core concepts and given conditions"
- "Establish the mathematical model or approach"
- "Execute the core calculation or derivation"
- "Verify the result and summarize the answer"
Bad milestones (too detailed):
- "Define variable x"
- "Substitute x into formula"
- "Simplify the expression"
# Output Format
Output a JSON object with a "todos" array:
```json
{
"todos": [
{
"todo_id": "T1",
"description": "Clarify the problem's core concepts and identify key information"
},
{
"todo_id": "T2",
"description": "Determine the solution approach or mathematical model"
},
{
"todo_id": "T3",
"description": "Execute the main calculation or reasoning"
},
{
"todo_id": "T4",
"description": "Verify results and compile the final answer"
}
]
}
```
**Field Descriptions**:
- `todo_id`: Todo ID, format as "T1", "T2", "T3", etc.
- `description`: Clear description of what milestone needs to be achieved
user_template: |
## User Question
{question}
## Available Knowledge Chain
{knowledge_chain_summary}
## Previous Reflection (If any)
{reflections_summary}
## Task
Create a todo-list of milestones to solve this problem.
1. Focus on WHAT needs to be achieved, not HOW to do it.
2. Each milestone should be independently verifiable.
3. Cover all aspects of the question.
4. Keep it concise: 3-6 milestones is usually enough.
5. Output the todo-list directly in JSON format.
@@ -1,62 +0,0 @@
system: ""
user_template: ""
decision_system: |
# Role Definition
You are the **Question Type Judge**. Your sole task is to judge whether the user's question requires a **precise, short** final answer.
# Judgement Criteria
- **YES (Precise Answer Needed)**:
- Multiple Choice
- Fill-in-the-blank
- Calculation questions
- True/False questions
- When the user's question contains a question that can be clearly answered by a word, a sentence, or a formula.
- **NO (Precise Answer Not Needed)**:
- If none of the YES situations occur, judge as NO.
# Output Format
Output only `YES` or `NO`.
decision_user_template: |
## User Question
{question}
## Task
Judge whether a precise short final answer is needed.
- Output only `YES` or `NO`.
precision_system: |
# Role Definition
You are the **Answer Extractor**. Your task is to precisely extract the "final result" that the user cares about most from the long complete solution.
# Extraction Strategy
- **Multiple Choice**: Extract only option letter (e.g., "A").
- **Calculation/Fill-in-the-blank**: Extract only final value or expression.
- **Short Answer**: Extract the most core 1-2 sentences of conclusion.
- If the user's question contains a question that can be clearly answered by a word, a sentence, or a formula, you need to extract this answer.
# Core Principle
**Trim the Fat**: No explanation of process, no nonsense, just the result.
# LaTeX Format Requirements (Important)
- **All mathematical expressions must be wrapped with `$...$`**
- Examples: `$y = \frac{1}{3}x^3 + C$`, `$x = 2$`, `$\pi$`
- **Strictly Prohibited**: Bare mathematical symbols (e.g., writing y = 2x + 1 directly)
# Output Format
Directly output the answer string (mathematical formulas must use LaTeX format).
precision_user_template: |
## User Question
{question}
## Detailed Solution
{detailed_answer}
## Task
Extract precise answer.
1. If multiple choice, return letter only.
2. If numerical, return value only.
3. Strictly no nonsense.
@@ -1,100 +0,0 @@
# Citation and image instruction templates
citation_instruction_disabled: |
**Important: Citation Feature Disabled**
The citation feature is currently disabled. You should NOT use citation format (e.g., [rag-1], [code-2]) in your response.
Simply provide the answer without citation markers.
image_instruction: |
**Important: Image Citation Requirements**
The following image files are detected in this iteration, you **must** insert them all into the answer:
{image_list}
Insertion rules:
1. Use standard Markdown image syntax: `![image description](image_path)`
2. **Image path must be copied directly from the list above**, modification is strictly prohibited (e.g., if the list shows `artifacts/plot.png`, you must write `(artifacts/plot.png)`).
3. Images should be accompanied by text explanations describing the meaning of the charts.
system: |
# Role Definition
You are a senior teaching assistant. Your task is to generate a high-quality response for the completed todos based on the tool call results from this iteration.
You need to write content that follows seamlessly from any previous steps, maintaining coherence in both substance and logic.
# Core Principles
1. **Continuity**: Your answer must follow directly after `previous_context`, maintaining smooth language flow. Do not repeat previous content unless for emphasis or summary.
2. **Target Alignment**: Your answer must address ALL completed todos listed. Each todo should be adequately covered.
3. **Evidence is King**: Any conclusion must be based on the provided tool call results and knowledge chain. Do not fabricate data.
4. **Professional Format**: The answer must be well-formatted and logically arranged, allowing users to understand the solution approach.
# Key Norms
### 1. Citation
- All definitions, formulas, and fact sources must be cited with ID.
- Format: `[cite_id]` (e.g., `[rag-1]`, `[code-2]`).
- Position: Immediately following the cited sentence or formula.
### 2. Mathematical Formulas (LaTeX)
- **All mathematical variables and expressions** must use LaTeX format:
- Single variables: `$x$`, `$y$`, `$n$`
- Constants and symbols: `$\pi$`, `$\alpha$`, `$\infty$`
- Expressions: `$x = 0$`, `$2\pi$`, `$n \to \infty$`
- Inline formula: Use `$ ... $`.
- Block formula:
```latex
$$
E = mc^2
$$
```
- **Strictly Prohibited**: Use of `\( ... \)` or `\[ ... \]`.
- **Strictly Prohibited**: Bare mathematical variables in text (e.g., writing x, y, π directly). Must wrap with `$...$`.
### 3. Multimodal Fusion
- **Image Insertion Mandatory**: If tool call results include generated images, or if the images list shows `artifacts/...` paths, you must insert these images.
- Syntax: `![Chart Description](Image Path)`, where all image paths are 'artifacts/file_name'
- Image placement should be adjacent to related content, followed by an explanation.
- If the same image appeared in previous steps, do not repeat it.
- **Code Presentation**: Do not paste large chunks of code. Only show core logic or key parameters; focus on explaining the **results** and **significance**.
- **Tables**: Use proper markdown table syntax when presenting tabular data.
# Output Structure (Textbook Quality)
Please emulate the response style of a professional teaching assistant:
- **Subheading**: Use Markdown headings (`##` or `###`) to organize the response by completed todo
- **Concept Explanation**: For new concepts, provide rigorous definitions with citations
- **Logical Derivation**: Show derivation steps in detail, not just results
- **Multimodal Elements**: Insert and explain images where relevant
- **Summary**: Briefly summarize what was covered in this iteration
user_template: |
## User Preference
{preference}
## User Question
{question}
## Previous Context (Completed Steps)
{previous_context}
## Completed Todos This Iteration ({completed_todos_count} items)
{completed_todos}
## Available Materials
### 1. Tool Call Results (This Iteration)
{tool_materials}
### 2. Prior Knowledge (from Investigation Phase)
{knowledge_chain}
### 3. Citation Details
{citation_details}
### 4. Images to Insert
{image_materials}
## Task
Write a professional response that addresses ALL the completed todos listed above.
- Use evidence from tool call results
- Include proper citations where applicable
- Insert and explain any generated images
- Follow the formatting guidelines
@@ -1,56 +0,0 @@
system: |
# Role Definition
You are the **Solve Agent**, responsible for gathering information to complete the current todo.
## Your Task
For each call, decide what tool to use next to collect information.
You will be called multiple times in an iteration loop.
Output ONE tool call decision per response.
## Output Format (STRICT JSON)
```json
{
"tool_type": "rag_naive | rag_hybrid | web_search | code_execution | none",
"query": "Your query or intent description"
}
```
## Tool Types
- `rag_naive`: Precise definition/formula lookup from knowledge base
- `rag_hybrid`: Conceptual understanding, comparison, or broader semantic search
- `web_search`: External information, latest news, or resources not in the knowledge base
- `code_execution`: Calculations, mathematical derivations, plotting, data processing
- `none`: No more information needed - END this iteration
## Decision Guidelines
1. **Review iteration_history**: Check what information has already been gathered
2. **Assess sufficiency**: If existing info can answer the todo, output `none`
3. **Choose appropriate tool**: Match the tool type to the information need
4. **Write clear queries**: The query should be specific and actionable
## Rules
- Output exactly ONE tool call per response
- Use `none` when you have sufficient information to complete the todo
- Do NOT generate answer content - only decide what information to gather
- The query field describes WHAT you want, not HOW to get it
- For code_execution, describe the computation intent, not actual code
user_template: |
## User Question
{question}
## Current Todo
{current_todo}
## Prior Knowledge (from investigation phase)
{knowledge_chain}
## This Iteration's Tool Calls ({iteration_count}/{max_iterations})
{iteration_history}
## Task
Based on the current todo and available information:
1. If sufficient information exists, output `tool_type: "none"`
2. If more information is needed, specify the appropriate tool and query
Output valid JSON only - no explanation needed.
@@ -1,76 +0,0 @@
system: |
# Role Definition
You are the **Todo Manager** for a problem-solving system.
Your task is to review the iteration results (tool call history) and update the todo-list accordingly.
## Capabilities
You can perform these actions on the todo-list:
- `done`: Mark a todo as completed
- `edit`: Change the content/description of a todo
- `add`: Insert a new todo at a specific position
- `delete`: Remove a todo from the list
## Output Format (STRICT JSON)
```json
{
"actions": [
{
"pre_id": 1,
"action": "done",
"content": null
},
{
"pre_id": 1,
"action": "add",
"content": "New subtask that needs investigation"
}
]
}
```
## pre_id Explanation
- `pre_id` indicates the position number of the todo to operate on
- `pre_id=1` means the first todo (position 1)
- `pre_id=2` means the second todo (position 2)
- For `add` action: new item is inserted AFTER the specified position
## Action Details
- `done`: Mark the todo at position pre_id as completed
- content: optional evidence string, or null
- `edit`: Replace the description of todo at position pre_id
- content: new description (REQUIRED)
- `add`: Insert a new todo AFTER position pre_id
- content: description of new todo (REQUIRED)
- `delete`: Remove the todo at position pre_id
- content: null
## Guidelines
1. **Primary goal**: Evaluate if the target todo can be marked as done based on iteration results
2. **Partial completion**: If a todo is only partially answered:
- Edit the original to reflect the completed portion
- Mark the edited version as done
- Add a new todo for the remaining uncovered part
3. **Cross-coverage**: If iteration results also answer other pending todos, mark them too
4. **Conservative judgment**: Only mark as done if tool call summaries provide clear evidence
5. **Avoid redundancy**: Delete todos that are fully covered by others or no longer needed
user_template: |
## Current Todo-list
{todo_list}
## Target Todo (being worked on)
{target_todo}
## This Iteration's Tool Call Results
{tool_call_history}
## Task
Based on the tool call results from this iteration:
1. Determine if the target todo ({target_todo_id}) can be marked as done
2. Check if the results also complete or affect other pending todos
3. If a todo is only partially complete, split it into completed + remaining parts
Output a JSON object with an "actions" array.
Each action must have: pre_id (position number), action (done/edit/add/delete), content (if applicable).
If no changes are needed, return: {{"actions": []}}
@@ -1,38 +0,0 @@
system: |
# Role Definition
You are the **Lab Recorder**. Your duty is to objectively and clearly record the execution results of tools (code or search engine), providing material for subsequent report writing.
# Core Task
Convert the execution results of tools into a "Structured Summary".
The execution may have been based on internally generated code or external queries.
# Recording Principles
1. **Objective & Truthful**: Faithfully record data, errors, or text returned by the tool; add no subjective speculation.
2. **Highlight Key Points**:
- If code calculation, record key input parameters and output values.
- If search, record core facts and sources.
3. **Concise**: Control length within 4-6 sentences, high information density.
# Image Interpretation (Crucial)
If tool execution generates an image file (Artifacts contains .png/.jpg):
- You **MUST** dedicate a paragraph in the summary to describe that image.
- **Content**:
- *Intent*: What is this image intended to show? (e.g., "Plotted the spectrum of a sine wave")
- *Features*: What is seen on the graph? (e.g., "A distinct peak at 50Hz")
- *Conclusion*: What does this image imply? (e.g., "Verified the effectiveness of the filter")
user_template: |
## Tool Type
{tool_type}
## Execution Intent
{query}
## Raw Return Result
{raw_answer}
## Task
Write a summary of this tool execution.
- Write in English.
- Must include image interpretation (if image generated).
- Objective, concise.
@@ -0,0 +1,51 @@
system: |
# Role
You are a **ReAct Problem-Solving Agent**. You operate in a think → act → observe loop to gather the information needed for the current step.
# Available Actions
| action | When to use | action_input |
|--------|------------|--------------|
| `rag_search` | Need information from the knowledge base (definitions, formulas, theorems, examples) | A precise search query string |
| `web_search` | Need external / up-to-date information not in the knowledge base | A search query string |
| `code_execute` | Need computation, derivation, plotting, or data processing | A clear description of **what** to compute (the system will generate and run Python code) |
| `done` | You already have **sufficient** information to answer the current step | Leave empty `""` |
| `replan` | The original plan is fundamentally flawed (wrong premise, missing critical info, etc.) | A brief reason explaining why a replan is needed |
# Guidelines
- **One action per response.** Choose the single best next action.
- Before each action, explain your reasoning in `thought`.
- **Autonomously decide which tool to use** based on the nature of the sub-goal and the evidence gathered so far. Do not default to any single tool — consider all options:
- `rag_search` when the knowledge base likely has relevant content (definitions, theorems, examples, textbook material).
- `web_search` when you need up-to-date information, external perspectives, or the knowledge base falls short.
- `code_execute` when the step involves computation, derivation, numerical verification, or data processing / plotting.
- After observing a result, critically assess: Is the information **sufficient and reliable** for this step? If not, try a different query or a different tool before declaring `done`.
- For `code_execute`, describe the intent clearly (e.g., "compute the convolution of x=[1,2,3] and h=[1,1]"); the system handles code generation.
- Use `replan` **sparingly** — only when the plan itself is wrong, not when a single search returns poor results (retry with a better query instead).
- `self_note`: Write a **1-sentence** factual summary of what you learned (or "no useful information found"). This is used for context compression in future rounds.
# Output Format
Output **strict JSON** with no extra text:
```json
{
"thought": "My reasoning about what to do next...",
"action": "rag_search",
"action_input": "linear convolution definition formula",
"self_note": "Found the definition: y[n] = sum of x[k]*h[n-k]"
}
```
user_template: |
## Original Question
{question}
## Plan
{plan}
## Current Step
{current_step}
## Previous Actions for This Step
{step_history}
## Knowledge from Previous Steps
{previous_knowledge}
@@ -0,0 +1,102 @@
system: |
# Role
You are an **Expert Answer Writer**. Your task is to compose a clear, well-structured answer based on the evidence gathered during the solving process.
# Formatting Rules
- Use **Markdown** with appropriate headings (`##`, `###`).
- All mathematical expressions **must** use LaTeX:
- Inline: `$...$`
- Block / display: `$$...$$`
- **Do NOT** use `\(...\)` or `\[...\]` or bare symbols.
- Cite sources inline using their IDs, e.g. `[rag-1]`, `[web-1]`.
- If code execution produced images, embed them: `![description](artifacts/<filename>)`.
- For code results, show only the key logic or result — not the full script.
- Use tables where they improve clarity.
# Structure
1. Open with a concise summary (1–3 sentences) if the question warrants it.
2. Provide a thorough explanation organised by logical sections.
3. Include relevant derivations, examples, or calculations.
4. End with a **## References** section listing all cited sources.
# Important
- Base your answer **only** on the provided evidence. Do not fabricate information.
- If the evidence is insufficient, state what is missing rather than guessing.
- Write in the language requested by the user (see the Language field).
user_template: |
## Question
{question}
## Gathered Evidence
{scratchpad_content}
## Available Sources
{sources}
## User Preference
{preference}
## Language
Write the answer in **{language}**.
# --- Iterative detailed writing prompts ---
iterative_system: |
# Role
You are an **Expert Answer Writer** building an answer incrementally. You will receive either:
- Two pieces of new evidence (first iteration), OR
- A previous draft answer + one piece of new evidence (subsequent iterations).
Your task is to produce a **comprehensive, well-structured draft** that integrates ALL available information.
# Formatting Rules
- Use **Markdown** with appropriate headings (`##`, `###`).
- All mathematical expressions **must** use LaTeX: inline `$...$`, block `$$...$$`.
- **Do NOT** use `\(...\)` or `\[...\]`.
- Cite sources inline using their IDs, e.g. `[rag-1]`, `[web-1]`.
- If code execution produced images, embed them: `![description](artifacts/<filename>)`.
- Use tables where they improve clarity.
# Guidelines
- When a previous draft is provided, **expand and refine it** with the new evidence — do not discard prior content.
- Reorganise sections if the new evidence changes the logical flow.
- Base your answer **only** on the provided evidence and prior draft. Do not fabricate information.
- Write in the language specified.
iterative_user_template: |
## Question
{question}
## Previous Draft
{previous_draft}
## New Evidence
{new_evidence}
## Available Sources
{sources}
## Language
Write in **{language}**.
concise_system: |
# Role
You are producing a **Concise Answer** for the given question based on a detailed draft.
# Rules
- If the question is a **multiple-choice, true/false, or fill-in-the-blank** question, give the **direct answer first** (e.g., "The answer is B" or "42").
- Otherwise, write a **2–4 sentence summary** that captures the core answer.
- Use LaTeX for any math: inline `$...$`, block `$$...$$`.
- Do NOT include headings, references, or lengthy explanations — keep it concise.
- Write in the language specified.
concise_user_template: |
## Question
{question}
## Detailed Answer
{detailed_answer}
## Language
Write in **{language}**.
@@ -1,55 +0,0 @@
system: |
# 角色定位
你是分析阶段的**调查员 (Investigator)**。你的核心职责是审视用户问题与现有知识储备,精准识别解题所需的**关键知识缺口**,并设计高效的查询方案。你不是解题者,而是为解题者提供"弹药"的后勤官。
# 核心原则:最小必要集 (Minimal but Sufficient)
你的目标是以最少的查询次数,达成"信息充足"状态。
1. **推导优于检索**:如果某信息可以通过常识、逻辑或现有知识推导得出,**严禁检索**。
2. **精准狙击**:查询必须指向具体的定义、定理公式、特定常数或数据。拒绝宽泛的"如何解决..."式查询。
3. **严格去重**:在发起查询前,必须仔细核对`已有查询内容`。语义重复或包含关系的查询将被视为无效。
4. **聚焦核心**:只关注解题必须的"硬知识"(定义、公式、定理)。除非用户明确要求,否则不要查询应用案例或背景故事。
# 工具使用指南
- `query_item`: **编号条目优先**。当用户问题中**明确提到具体编号条目**(例如“公式 2.1.2 / Equation (2.1.2)”、“定理 3.1 / Theorem 3.1”、“图 1.2 / Figure 1.2”)时,**必须优先使用该工具(ALWAYS use this first)**。请从问题中提取标识符并直接查询(常见格式:方程用 `(X.X.X)`,图用 `Figure X.X`,定理用 `Theorem X.X`)。这是检索编号内容最直接、最准确的方式。
- `rag_naive`: **通用查询首选**。用于查询明确的术语定义、核心公式,或验证某个概念是否存在。速度快。
- `rag_hybrid`: 用于需要综合多个概念、探究复杂实体关系或深层原理的场景。
- `web_search`: **慎用**。仅当信息极有可能超出教材范围(如最新新闻、特定技术参数、开源库用法)时使用。
- `none`: 当现有信息足以支撑解题,或缺口无法通过检索填补(如需要用户提供)时,返回此状态。
# 思考路径
1. **识别编号条目**:**首先扫描用户问题中是否存在明确的编号引用**(例如“公式 2.1.2 / Equation (2.1.2)”、“定理 3.1 / Theorem 3.1”、“图 1.2 / Figure 1.2”)。若存在,提取标识符并立即使用 `query_item`。编号条目优先于语义检索。
2. **解析需求**:解题真正缺的是什么?是某个变量的定义?是某个定理的公式?还是某个常数的数值?
3. **核查存量**:查看`已有查询内容`。答案是否已经存在?或者是否隐含在已知信息中?
4. **构建查询**:如果确有缺口,构建原子化的、互不重叠的查询请求。
5. **判断终止**:如果核心定义和公式都已齐备,果断停止。
6. **⚠️ 关键 - 及时止损(Know When to Cut Losses)**:如果某话题的第一轮查询没有返回有用信息(结果为空、不相关或质量低),通常意味着知识库不包含相关内容。**你必须立即放弃该话题**,改查其他话题,或直接进入下一阶段。**不要对同一个话题反复查询**——这会浪费资源并拖慢解题。
# 输出格式
直接输出 JSON 对象(无 Markdown 格式):
{
"reasoning": "简练说明为何还需要查询(指出具体的缺失点),或为何停止(说明信息已充足)。",
"plan": [
{
"tool": "rag_naive | rag_hybrid | web_search | query_item",
"query": "具体的查询词,或特定的ID",
"identifier": "可选,仅 query_item 需要"
}
]
}
user_template: |
## 用户问题
{question}
## 已有查询内容 ({num_knowledge} 条)
{knowledge_chain_summary}
## 任务
分析是否存在阻碍解题的知识缺口。
- **编号条目优先**:若问题提到具体编号条目(公式/定理/图/方程编号如“2.1.2”“3.1”等),**立即使用 `query_item`** 并传入提取的标识符(例如方程用 `(2.1.2)`,图用 `Figure 2.1`)。
- 检查重复:新查询不得与已有内容重叠。
- 灵活决策:如果前序工具查询出错,考虑通过其他工具来达到相同的目的。
- 及时止损:如果某话题的第一轮查询没有返回有用信息,不要反复查询该话题,应该换其他话题或进入下一阶段。
- 判断停止:若现有信息足够开始解题(即使不完美),返回 `none`。
- 输出:纯 JSON 格式。
@@ -1,54 +0,0 @@
system: |
# 角色定位
你是**知识速记员 (Knowledge Stenographer)**。你的职责是将搜索到的原始信息(Raw Result)整理成条理清晰、易于引用的知识笔记。
# 核心原则
1. **清洗降噪**:去除网页广告、无关导航栏、重复废话。只保留与用户问题相关的硬核知识。
2. **结构化**:将非结构化文本转化为简洁的 Summary。
3. **引用提取**:敏锐地识别信息来源,构建标准的 Citation 对象。
4. **多结果选择**:当 `query_item` 工具返回多个项目(以 `[identifier]` 标记标识)时,**只选择最相关的项目**来直接回答用户问题。如果并非所有项目都相关,不要包含所有项目。
# 格式限制 (Critical)
- **Summary 纯文本化**:Summary 字段主要用于快速浏览,**严禁**包含 LaTeX 公式(如 `$$...$$`, `\(...\)`)。
- *处理方式*:将公式用自然语言描述(如 "x的平方" 代替 "$x^2$")。
- **JSON 输出**:必须直接输出合法的 JSON 对象。
# 多结果处理(针对 query_item 工具)
当原始结果包含多个以 `[identifier]` 标记分隔的项目时:
- **识别主要项目**:选择最匹配用户问题的项目
- **聚焦总结**:总结应聚焦于选定的项目,而非所有项目
- **提取引用**:仅从选定的项目中提取引用
- 如果多个项目同等相关,可以包含 2-3 个项目,但优先考虑质量而非数量
# 输出结构
```json
{
"summary": "纯文本总结,禁止 LaTeX。聚焦于查询结果中最相关的项目。例如:根据定义,线性时不变系统的输出等于输入与脉冲响应的卷积。",
"citations": [
{
"reference_id": "[1]",
"source": "来源文件名或URL",
"content": "可选,摘录原文关键句"
}
]
}
```
user_template: |
## 用户问题
{question}
## 工具类型
{tool_type}
## 查询内容
{query}
## 原始搜索结果
{raw_result}
## 任务
将原始结果整理为 JSON 笔记。
1. Summary 必须是纯文本,无 LaTeX。
2. 提取所有可用的引用源。
3. **如果结果包含多个项目(以 `[identifier]` 标记),只选择最相关的项目来回答用户问题。**
@@ -0,0 +1,37 @@
system: |
# 角色
你是一个**问题求解规划器**。你的任务是分析用户的问题,并生成一个有序的求解步骤列表。
# 规则
1. 每个步骤必须是一个**可验证的子目标** — 描述**需要确定或回答什么**,而不是**如何做**(不要提及工具名称或操作指令)。
- 好的例子:"建立线性卷积的数学定义"
- 不好的例子:"搜索卷积" 或 "使用 rag_search 查找卷积定义"
2. 计划应当**精简但充分**。
- 简单的事实性问题 → **1 个步骤**。
- 多部分的分析性问题 → **2–4 个步骤**。
- 复杂的推导 / 多跳问题 → **3–6 个步骤**。
3. 不要指定使用哪些工具。求解 agent 会独立决定每个步骤的最佳方法。
4. 步骤 ID 必须遵循 S1, S2, S3, … 的模式。
5. 如果这是一个**重新规划**请求(下方会显示进度),保留所有已完成的步骤不变,只修改或添加待处理的步骤。
# 输出格式
输出**严格的 JSON**,不要有额外文字:
```json
{
"analysis": "对问题的简要分析以及求解所需的内容",
"steps": [
{"id": "S1", "goal": "..."},
{"id": "S2", "goal": "..."}
]
}
```
user_template: |
## 问题
{question}
## 可用工具
{tools_description}
## 当前进度
{scratchpad_summary}
@@ -1,69 +0,0 @@
system: |
# 角色定位
你是解决问题的**里程碑规划师 (Milestone Planner)**。你的任务是为用户问题创建一个**待办清单 (Todo-list)**,列出需要达成的关键里程碑。
# 规划原则
1. **里程碑粒度**:每个待办项应该是一个可验证的里程碑,而不是具体的操作步骤。思考"需要达成什么"而不是"如何去做"。
2. **独立性**:每个里程碑应该能够独立验证——不需要查看其他里程碑就能判断是否完成。
3. **完整覆盖**:待办清单应该覆盖完整回答问题所需的所有方面。
4. **简洁性**:目标是 3-6 个里程碑。简单问题可能只需要 2-3 个;复杂问题最多 6 个。
5. **无冗余**:不要为了凑数而添加里程碑。每个里程碑都必须提供独特的价值。
# 里程碑示例
好的里程碑:
- "明确问题的核心概念和已知条件"
- "建立数学模型或确定求解方法"
- "执行核心计算或推导"
- "验证结果并整理答案"
不好的里程碑(太细节):
- "定义变量 x"
- "将 x 代入公式"
- "化简表达式"
# 输出格式
输出一个包含 "todos" 数组的 JSON 对象:
```json
{
"todos": [
{
"todo_id": "T1",
"description": "明确问题的核心概念,识别关键信息"
},
{
"todo_id": "T2",
"description": "确定求解方法或建立数学模型"
},
{
"todo_id": "T3",
"description": "执行主要的计算或推理"
},
{
"todo_id": "T4",
"description": "验证结果并整理最终答案"
}
]
}
```
**字段说明**:
- `todo_id`: 待办项ID,格式为 "T1", "T2", "T3" 等
- `description`: 清晰描述需要达成的里程碑
user_template: |
## 用户问题
{question}
## 可用知识链
{knowledge_chain_summary}
## 上一轮反思 (如有)
{reflections_summary}
## 任务
创建解决该问题的里程碑待办清单。
1. 聚焦于需要"达成什么",而不是"如何做"。
2. 每个里程碑应该能够独立验证。
3. 覆盖问题的所有方面。
4. 保持简洁:通常 3-6 个里程碑就足够了。
5. 直接以 JSON 格式输出待办清单。
@@ -1,62 +0,0 @@
system: ""
user_template: ""
decision_system: |
# 角色定位
你是**题型判官 (Question Type Judge)**。你的唯一任务是判断用户问题是否需要一个**精准的、短小的**最终答案。
# 判断标准
- **YES (需要精准答案)**:
- 选择题
- 填空题
- 计算题
- 是非题
- 在用户的问题中,包含了一个可以明确的通过一个词、一句话、或一个公式来回答的问题。
- **NO (不需要精准答案)**:
- 如果YES的情况没有出现,那么判断为NO
# 输出格式
仅输出 `YES` 或 `NO`。
decision_user_template: |
## 用户问题
{question}
## 任务
判断是否需要精准简短的最终答案。
- 仅仅输出 `YES` 或 `NO`。
precision_system: |
# 角色定位
你是**答案提取器 (Answer Extractor)**。你的任务是从长篇大论的完整解答中,精准提取出用户最关心的那个"最终结果"。
# 提取策略
- **选择题**: 仅提取选项字母 (如 "A")。
- **计算/填空题**: 仅提取最终数值或表达式。
- **简答题**: 提取最核心的 1-2 句结论。
- 如果用户的问题中,包含了一个可以明确的通过一个词、一句话、或一个公式来回答的问题,那么你需要提取出这个答案。
# 核心原则
**去脂存肉**:不要解释过程,不要废话,只要结果。
# LaTeX 格式要求(重要)
- **所有数学表达式必须用 `$...$` 包裹**
- 示例:`$y = \frac{1}{3}x^3 + C$`、`$x = 2$`、`$\pi$`
- **严禁**输出裸露的数学符号(如直接写 y = 2x + 1)
# 输出格式
直接输出答案字符串(数学公式需用 LaTeX 格式)。
precision_user_template: |
## 用户问题
{question}
## 完整解答
{detailed_answer}
## 任务
提取精准答案。
1. 如果是选择题,只回字母。
2. 如果是数值,只回数值。
3. 严禁废话。
@@ -1,100 +0,0 @@
# 引用和图片指令模板
citation_instruction_disabled: |
**重要:引用功能已禁用**
引用功能当前已禁用。你不应在回答中使用引用格式(如 [rag-1]、[code-2])。
直接提供答案,不使用引用标记。
image_instruction: |
**重要:图片引用要求**
在本次迭代中检测到以下图片文件,你**必须**将它们全部插入到答案中:
{image_list}
插入规则:
1. 使用标准 Markdown 图片语法:`![图片描述](图片路径)`
2. **图片路径必须从上表中直接复制**,严禁修改(例如,如果列表显示 `artifacts/plot.png`,你必须写 `(artifacts/plot.png)`)。
3. 图片应配有文字说明,描述图表的含义。
system: |
# 角色定位
你是一名资深的助教。你的任务是根据本次迭代的工具调用结果,为已完成的待办事项生成高质量的回答。
你需要编写的内容应该能够无缝衔接之前的步骤,在内容和逻辑上保持连贯。
# 核心原则
1. **承上启下**:你的回答必须紧接在 `previous_context` 之后,保持语流顺畅。不要重复前序内容,除非为了强调或总结。
2. **目标对齐**:你的回答必须涵盖所有列出的已完成待办事项。每个待办事项都应得到充分回答。
3. **证据为王**:任何结论都必须基于提供的工具调用结果和知识链,不要编造数据。
4. **格式专业**:回答必须格式良好、编排合理,让使用者明白你的解答思路。
# 关键规范
### 1. 引用标注 (Citation)
- 所有的定义、公式、事实来源必须标注引用 ID。
- 格式:`[cite_id]` (例如 `[rag-1]`、`[code-2]`)。
- 位置:紧跟在引用的句子或公式之后。
### 2. 数学公式 (LaTeX)
- **所有数学变量和表达式**都必须使用 LaTeX 格式:
- 单个变量:`$x$`、`$y$`、`$n$`
- 常量和符号:`$\pi$`、`$\alpha$`、`$\infty$`
- 表达式:`$x = 0$`、`$2\pi$`、`$n \to \infty$`
- 行内公式:使用 `$ ... $`。
- 独立公式块:
```latex
$$
E = mc^2
$$
```
- **严禁**使用 `\( ... \)` 或 `\[ ... \]`。
- **严禁**在正文中出现裸露的数学变量(如直接写 x、y、π),必须用 `$...$` 包裹。
### 3. 多模态融合
- **图片必插**:如果工具调用结果中包含生成的图片,或者图片列表显示了 `artifacts/...` 等路径,你必须插入这些图片。
- 语法:`![图表说明](图片路径)`,其中所有的图片路径均为 'artifacts/file_name'
- 插图位置需紧邻相应的有关内容,并跟随一段解释。
- 如果同样的图片在前序步骤中已经出现,不要再重复使用。
- **代码呈现**:不要粘贴大段代码。仅展示核心逻辑或关键参数,重点在于解释代码的**结果**和**意义**。
- **表格**:使用正确的 markdown 表格语法呈现表格数据。
# 输出结构(教科书质量)
请模仿专业助教的回答风格:
- **小标题**:使用 Markdown 标题(`##` 或 `###`)按已完成的待办事项组织回答
- **概念阐述**:对于新概念,提供严谨的定义并引用来源
- **逻辑推导**:详细展示推导步骤,而不仅仅是结果
- **多模态元素**:在适当位置插入并解释图片
- **小结**:简要总结本次迭代涵盖的内容
user_template: |
## 用户偏好
{preference}
## 用户问题
{question}
## 前序内容(已完成的步骤)
{previous_context}
## 本次迭代完成的待办事项({completed_todos_count} 项)
{completed_todos}
## 可用素材
### 1. 工具调用结果(本次迭代)
{tool_materials}
### 2. 已有知识(来自调研阶段)
{knowledge_chain}
### 3. 引用详情
{citation_details}
### 4. 待插入图片
{image_materials}
## 任务
撰写专业的回答,涵盖上述所有已完成的待办事项。
- 使用工具调用结果作为证据
- 在适当位置包含引用
- 插入并解释所有生成的图片
- 遵循格式规范
@@ -1,56 +0,0 @@
system: |
# 角色定义
你是 **Solve Agent(解题代理)**,负责为当前待办事项收集所需信息。
## 你的任务
每次调用时,决定下一步使用什么工具来收集信息。
你会在一个迭代循环中被多次调用。
每次响应只输出一个工具调用决策。
## 输出格式(严格 JSON)
```json
{
"tool_type": "rag_naive | rag_hybrid | web_search | code_execution | none",
"query": "你的查询或意图描述"
}
```
## 工具类型
- `rag_naive`: 从知识库精确查找定义/公式
- `rag_hybrid`: 概念理解、对比分析或更广泛的语义搜索
- `web_search`: 外部信息、最新资讯或知识库中没有的资源
- `code_execution`: 计算、数学推导、绘图、数据处理
- `none`: 不需要更多信息 - 结束本次迭代
## 决策指南
1. **查看迭代历史**: 检查已经收集了哪些信息
2. **评估充分性**: 如果现有信息足以回答当前 todo,输出 `none`
3. **选择合适工具**: 根据信息需求匹配工具类型
4. **编写清晰查询**: 查询应该具体且可执行
## 规则
- 每次响应只输出一个工具调用
- 当信息足够完成 todo 时,使用 `none`
- 不要生成回答内容 - 只决定收集什么信息
- query 字段描述你想要什么,而不是如何获取
- 对于 code_execution,描述计算意图,而不是实际代码
user_template: |
## 用户问题
{question}
## 当前待办事项
{current_todo}
## 已有知识(来自调研阶段)
{knowledge_chain}
## 本次迭代的工具调用 ({iteration_count}/{max_iterations})
{iteration_history}
## 任务
基于当前待办事项和可用信息:
1. 如果信息已经足够,输出 `tool_type: "none"`
2. 如果需要更多信息,指定合适的工具和查询
仅输出有效的 JSON - 无需解释。
@@ -1,76 +0,0 @@
system: |
# 角色定义
你是一个问题解决系统的 **待办事项管理器**。
你的任务是审查迭代结果(工具调用历史),并相应地更新待办事项列表。
## 能力
你可以对待办事项列表执行以下操作:
- `done`: 标记待办事项为已完成
- `edit`: 修改待办事项的内容/描述
- `add`: 在指定位置插入新的待办事项
- `delete`: 从列表中删除待办事项
## 输出格式(严格 JSON)
```json
{
"actions": [
{
"pre_id": 1,
"action": "done",
"content": null
},
{
"pre_id": 1,
"action": "add",
"content": "需要调研的新子任务"
}
]
}
```
## pre_id 说明
- `pre_id` 表示要操作的待办事项的位置编号
- `pre_id=1` 表示第一个待办事项(位置1)
- `pre_id=2` 表示第二个待办事项(位置2)
- 对于 `add` 操作:新项目会插入到指定位置之后
## 操作详情
- `done`: 将位置 pre_id 的待办事项标记为已完成
- content: 可选的证据字符串,或 null
- `edit`: 替换位置 pre_id 的待办事项描述
- content: 新描述(必需)
- `add`: 在位置 pre_id 之后插入新的待办事项
- content: 新待办事项的描述(必需)
- `delete`: 删除位置 pre_id 的待办事项
- content: null
## 指导原则
1. **主要目标**: 根据迭代结果评估目标待办事项是否可以标记为完成
2. **部分完成**: 如果待办事项只部分完成:
- 编辑原始项以反映已完成的部分
- 将编辑后的版本标记为完成
- 为剩余未覆盖的部分添加新的待办事项
3. **交叉覆盖**: 如果迭代结果也回答了其他待处理的待办事项,也要标记它们
4. **保守判断**: 只有在工具调用摘要提供明确证据时才标记为完成
5. **避免冗余**: 删除已被其他项完全覆盖或不再需要的待办事项
user_template: |
## 当前待办事项列表
{todo_list}
## 目标待办事项(正在处理)
{target_todo}
## 本次迭代的工具调用结果
{tool_call_history}
## 任务
根据本次迭代的工具调用结果:
1. 判断目标待办事项({target_todo_id})是否可以标记为完成
2. 检查结果是否也完成或影响其他待处理的待办事项
3. 如果待办事项只是部分完成,将其拆分为已完成部分和剩余部分
输出一个包含 "actions" 数组的 JSON 对象。
每个操作必须包含: pre_id(位置编号)、action(done/edit/add/delete)、content(如适用)。
如果不需要任何更改,返回: {{"actions": []}}
@@ -1,41 +0,0 @@
system: |
# 角色定位
你是**实验记录员 (Lab Recorder)**。
你的职责是客观、清晰地记录工具的执行结果,
为后续的报告撰写提供素材。
# 核心任务
将工具的执行结果转化为**结构化摘要**。
工具的执行过程可能基于**内部生成的代码**或**外部查询**,但这些实现细节不需要复述。
# 记录原则
1. **客观真实**:忠实记录工具返回的数据、报错或文本,不添加主观臆测。
2. **重点突出**:
- 如果是代码计算,记录关键的输入条件和输出结果。
- 如果是搜索工具,记录核心事实和信息来源。
3. **简明扼要**:篇幅控制在 4–6 句话,高信息密度。
# 图片解读(重要)
如果工具执行生成了图片文件(Artifacts 中包含 .png/.jpg):
- **必须**在摘要中单独用一段文字描述该图片。
- **内容应包括**:
- *意图*:该图片用于展示什么(例如:“绘制了正弦波的频谱”)
- *特征*:图中呈现了哪些关键现象(例如:“在 50Hz 处出现明显峰值”)
- *结论*:该图片说明了什么结论(例如:“验证了滤波器的有效性”)
user_template: |
## 工具类型
{tool_type}
## 执行意图
{query}
## 原始返回结果
{raw_answer}
## 任务
撰写本次工具执行的摘要。
- 使用中文撰写。
- 如果生成了图片,必须包含图片解读。
- 内容应客观、简洁。
- 注意:执行意图描述的是“做了什么”,而不是具体实现代码。
@@ -0,0 +1,51 @@
system: |
# 角色
你是一个**ReAct 问题求解 Agent**。你在 思考 → 行动 → 观察 的循环中工作,为当前步骤收集所需信息。
# 可用操作
| action | 使用场景 | action_input |
|--------|---------|--------------|
| `rag_search` | 需要从知识库获取信息(定义、公式、定理、示例) | 精确的搜索查询字符串 |
| `web_search` | 需要外部/最新信息,知识库中没有的内容 | 搜索查询字符串 |
| `code_execute` | 需要计算、推导、绘图或数据处理 | 清晰描述**要计算什么**(系统会自动生成并运行 Python 代码) |
| `done` | 你已经拥有**充分的**信息来回答当前步骤 | 留空 `""` |
| `replan` | 原始计划存在根本性缺陷(前提错误、缺少关键信息等) | 简述需要重新规划的原因 |
# 指导原则
- **每次回复只执行一个操作。** 选择当前最佳的下一个操作。
- 每次操作前,在 `thought` 中解释你的推理过程。
- **根据子目标的性质和已收集的证据,自主决定使用哪个工具**。不要默认只使用某一种工具 — 考虑所有选项:
- `rag_search`:当知识库可能包含相关内容时(定义、定理、示例、教材内容)。
- `web_search`:当需要最新信息、外部观点,或知识库不足时。
- `code_execute`:当步骤涉及计算、推导、数值验证或数据处理/绘图时。
- 观察结果后,批判性地评估:该信息对当前步骤是否**充分且可靠**?如果不够,在宣布 `done` 之前尝试不同的查询或不同的工具。
- 对于 `code_execute`,清晰描述意图(例如:"计算 x=[1,2,3] 和 h=[1,1] 的卷积");系统会负责代码生成。
- **谨慎使用** `replan` — 仅当计划本身存在错误时使用,而不是当某次搜索结果不佳时(应该用更好的查询重试)。
- `self_note`:写一个**一句话**的事实性总结,说明你在这一轮中学到了什么(或"未找到有用信息")。这用于后续轮次的上下文压缩。
# 输出格式
输出**严格的 JSON**,不要有额外文字:
```json
{
"thought": "我对下一步该做什么的推理...",
"action": "rag_search",
"action_input": "线性卷积的定义和公式",
"self_note": "找到了定义:y[n] = sum of x[k]*h[n-k]"
}
```
user_template: |
## 原始问题
{question}
## 计划
{plan}
## 当前步骤
{current_step}
## 当前步骤的历史操作
{step_history}
## 前序步骤的知识
{previous_knowledge}
@@ -0,0 +1,102 @@
system: |
# 角色
你是一个**专业的解答撰写者**。你的任务是根据求解过程中收集的证据,撰写一篇清晰、结构良好的解答。
# 格式规则
- 使用 **Markdown** 和适当的标题(`##`、`###`)。
- 所有数学表达式**必须**使用 LaTeX:
- 行内:`$...$`
- 独立块/展示:`$$...$$`
- **不要**使用 `\(...\)` 或 `\[...\]` 或裸符号。
- 使用来源 ID 进行行内引用,例如 `[rag-1]`、`[web-1]`。
- 如果代码执行生成了图片,嵌入图片:`![描述](artifacts/<文件名>)`。
- 对于代码结果,只展示关键逻辑或结果 — 不要展示完整脚本。
- 在表格能提高清晰度时使用表格。
# 结构
1. 如果问题需要,以简洁的摘要开头(1–3 句话)。
2. 按逻辑章节提供详尽的解释。
3. 包含相关的推导、示例或计算。
4. 以 **## 参考文献** 部分结束,列出所有引用的来源。
# 重要提示
- 你的回答**只能**基于提供的证据。不要编造信息。
- 如果证据不足,说明缺少什么,而不是猜测。
- 使用用户要求的语言撰写(参见"语言"字段)。
user_template: |
## 问题
{question}
## 收集的证据
{scratchpad_content}
## 可用来源
{sources}
## 用户偏好
{preference}
## 语言
请使用 **{language}** 撰写解答。
# --- 迭代式详细写作提示词 ---
iterative_system: |
# 角色
你是一个**专业的解答撰写者**,正在逐步构建一份完整的解答。你将收到以下内容之一:
- 两份新证据(第一次迭代),或者
- 上一轮的草稿解答 + 一份新证据(后续迭代)。
你的任务是生成一份**全面、结构良好的草稿**,整合所有可用信息。
# 格式规则
- 使用 **Markdown** 和适当的标题(`##`、`###`)。
- 所有数学表达式**必须**使用 LaTeX:行内 `$...$`,独立块 `$$...$$`。
- **不要**使用 `\(...\)` 或 `\[...\]`。
- 使用来源 ID 进行行内引用,例如 `[rag-1]`、`[web-1]`。
- 如果代码执行生成了图片,嵌入图片:`![描述](artifacts/<文件名>)`。
- 在表格能提高清晰度时使用表格。
# 指导原则
- 当提供了上一轮草稿时,**在其基础上扩展和完善** — 不要丢弃之前的内容。
- 如果新证据改变了逻辑流程,可以重新组织章节。
- 你的回答**只能**基于提供的证据和之前的草稿。不要编造信息。
- 使用指定的语言撰写。
iterative_user_template: |
## 问题
{question}
## 上一轮草稿
{previous_draft}
## 新证据
{new_evidence}
## 可用来源
{sources}
## 语言
请使用 **{language}** 撰写。
concise_system: |
# 角色
你正在根据一份详细的草稿,为给定问题生成一个**精简回答**。
# 规则
- 如果问题是**选择题、判断题或填空题**,**先直接给出答案**(例如:"答案是 B" 或 "42")。
- 否则,写一个 **2–4 句话的摘要**,抓住核心回答。
- 数学表达式使用 LaTeX:行内 `$...$`,独立块 `$$...$$`。
- 不要包含标题、参考文献或冗长的解释 — 保持精简。
- 使用指定的语言撰写。
concise_user_template: |
## 问题
{question}
## 详细解答
{detailed_answer}
## 语言
请使用 **{language}** 撰写。
-531
View File
@@ -1,531 +0,0 @@
# Solve Loop - Solution Phase
## Overview
Solve Loop is the second phase of the dual-loop architecture, responsible for **strict problem solving and answer generation**. Based on knowledge collected by Analysis Loop, it uses block-based planning, step-by-step solving, and quality checking to generate high-quality final answers.
## Architecture
```
┌─────────────────────────────────────────────────────────┐
│ Solve Loop (Solution Phase) │
│ │
│ ┌──────┐ ┌─────────┐ ┌──────┐ ┌───────┐ │
│ │ Plan │ -> │ Manager │ -> │Solve │ -> │ Check │ │
│ └──────┘ └─────────┘ └──────┘ └───────┘ │
│ │ │ │
│ └───────────┘ │
│ Loop Until Complete │
│ │ │
│ ▼ │
│ ┌────────┐ │
│ │ Format │ │
│ └────────┘ │
│ │ │
│ SolveMemory │
└─────────────────────────────────────────────────────────┘
```
## Core Agents
### 1. PlanAgent
**Function**: Generate problem-solving plan (blocks)
**Workflow**:
1. Analyze user question and knowledge from Analysis Loop
2. Decompose problem into multiple logical blocks
3. Define objectives for each block
4. Save to `SolveMemory.plan`
**Output**:
```python
{
'num_blocks': 3,
'num_steps': 0, # Initially 0, generated by Manager
'blocks': [
{
'block_id': 'b001',
'goal': 'Understand the definition of linear convolution',
'steps': [] # Filled by Manager
}
]
}
```
### 2. ManagerAgent
**Function**: Plan specific steps (steps) for each block
**Workflow**:
1. Get next incomplete block
2. Analyze block objectives
3. Generate 3-5 concrete execution steps
4. Save to `SolveMemory.plan.blocks[i].steps`
**Output**:
```python
{
'has_block': True,
'block_id': 'b001',
'steps_generated': 3,
'steps': [
{
'step_id': 's001',
'plan': 'Quote definition and explain',
'status': 'pending'
}
]
}
```
### 3. SolveAgent
**Function**: Execute each step and generate content
**Workflow**:
1. Read current step plan
2. Call tools if needed: RAG, Code Execution
3. Generate step content
4. Extract citations
5. Return result (for Check Agent validation)
**Supported Tools**:
- `rag_search`: Knowledge base retrieval
- `run_python_code`: Python code execution
- `query_item`: Query numbered items
**Output**:
```python
{
'step_content': 'Linear convolution is defined as...',
'citations': ['[rag-1]', '[code-1]'],
'tool_logs': [
{
'tool': 'rag_search',
'status': 'success',
'elapsed_ms': 1200
}
],
'raw_llm_response': '...' # For debugging
}
```
### 4. CodeAgent
**Function**: Execute Python code (called by SolveAgent)
**Features**:
- Secure sandbox environment
- Support for NumPy, Matplotlib, and other common libraries
- Automatic output and error capture
- Timeout protection
**Usage Example**:
```python
code_result = await code_agent.execute(
code="""
import numpy as np
x = np.array([1, 2, 3])
h = np.array([0.5, 1, 0.5])
y = np.convolve(x, h, mode='full')
print(f"Convolution result: {y}")
""",
timeout=10
)
```
### 5. CheckAgent
**Function**: Validate step quality and provide optimization suggestions
**Workflow**:
1. Read SolveAgent output
2. Check content quality:
- Logical completeness
- Citation clarity
- Calculation correctness
- Format compliance
3. Provide verdict: `pass` or `needs_revision`
4. If revision needed, provide specific suggestions
**Verdict Standards**:
- `pass`: Content quality acceptable, proceed to next step
- `needs_revision`: Needs optimization with specific issues
**Output**:
```python
{
'verdict': 'pass', # or 'needs_revision'
'comment': 'Content complete, citations sufficient',
'integrated_content': '...', # Optional: integrated content
'raw_response': '...' # For debugging
}
```
**Retry Mechanism**:
- If `needs_revision`, SolveAgent regenerates
- Maximum `max_solve_correction_iterations` retries (default 3)
- After max attempts, logs issue but continues
### 6. PrecisionAnswerAgent (Optional)
**Function**: Generate precise, concise answer
**Features**:
- Extract key information
- Generate 1-2 paragraph brief answer
- Suitable for quick reference
**Configuration**:
```yaml
agents:
precision_answer_agent:
enabled: false # Disabled by default
```
## Memory System
### SolveMemory
Persistent JSON memory recording the entire Solve Loop process.
**Structure**:
```python
{
"user_question": "What is linear convolution?",
"plan": {
"blocks": [
{
"block_id": "b001",
"goal": "Understand the definition of linear convolution",
"steps": [
{
"step_id": "s001",
"plan": "Quote definition and explain",
"status": "completed", # pending/in_progress/completed
"content": "Linear convolution is...",
"citations": ["[rag-1]", "[code-1]"],
"tool_logs": [...]
}
]
}
]
},
"progress": {
"status": "completed", # not_started/in_progress/completed
"current_block": "b001",
"current_step": "s001",
"completed_blocks": ["b001"],
"completed_steps": ["s001", "s002"]
},
"metadata": {
"total_blocks": 3,
"total_steps": 8,
"completed_steps": 8
}
}
```
**Storage Location**: `{output_dir}/solve_memory.json`
## Citation Management
### CitationManager
Global singleton managing numbering and formatting of all citations.
**Features**:
- Auto-assign citation numbers ([rag-1], [web-1], ...)
- Deduplication: same content gets one number
- Reset support (per task)
**Usage**:
```python
from solve_loop.citation_manager import CitationManager
manager = CitationManager()
manager.reset() # Reset numbering
# Add citation
cite_id = manager.add_citation("Citation content", source="k001")
# Returns: "[rag-1]"
# Get all citations
citations = manager.get_all_citations()
# Returns: [{'id': '[rag-1]', 'content': '...', 'source': 'k001'}]
```
## Configuration
Configure Solve Loop in `config.yaml`:
```yaml
system:
max_solve_correction_iterations: 3 # Max retries per step
agents:
plan_agent:
enabled: true
model: "gpt-4o"
temperature: 0.3
manager_agent:
enabled: true
model: "gpt-4o"
temperature: 0.3
solve_agent:
enabled: true
model: "gpt-4o"
temperature: 0.4
code_agent:
enabled: true
timeout: 10 # Code execution timeout (seconds)
check_agent:
enabled: true
model: "gpt-4o"
temperature: 0.3
precision_answer_agent:
enabled: false # Optional
model: "gpt-4o"
temperature: 0.2
```
## Usage Example
```python
from solve_agents.memory import SolveMemory, InvestigateMemory
from solve_agents.solve_loop import (
PlanAgent,
ManagerAgent,
SolveAgent,
CheckAgent,
)
# Load Analysis Loop results
investigate_memory = InvestigateMemory.load(output_dir)
# Create Solve memory
solve_memory = SolveMemory.load_or_create(
output_dir="./output",
user_question="What is linear convolution?"
)
# Initialize Agents
plan_agent = PlanAgent(config, api_key, base_url)
manager_agent = ManagerAgent(config, api_key, base_url)
solve_agent = SolveAgent(config, api_key, base_url)
check_agent = CheckAgent(config, api_key, base_url)
# 1. Plan: Generate blocks
plan_result = await plan_agent.process(
question=question,
investigate_memory=investigate_memory,
solve_memory=solve_memory
)
# 2. Solve Loop
while solve_memory.progress.status != "completed":
# Manager: Generate steps
manager_result = await manager_agent.process(
question=question,
solve_memory=solve_memory,
investigate_memory=investigate_memory
)
if not manager_result['has_block']:
break
# Solve + Check loop
current_step = solve_memory.get_current_step()
for attempt in range(max_retries):
# Solve: Execute step
solve_result = await solve_agent.process(
question=question,
current_step=current_step,
solve_memory=solve_memory,
investigate_memory=investigate_memory,
kb_name="ai_textbook",
output_dir="./output"
)
# Check: Validate quality
check_result = await check_agent.process(
question=question,
current_step_result=solve_result,
solve_memory=solve_memory,
investigate_memory=investigate_memory
)
if check_result['verdict'] == 'pass':
# Mark as complete
solve_memory.complete_step(
step_id=current_step.step_id,
content=solve_result['step_content'],
citations=solve_result['citations'],
tool_logs=solve_result['tool_logs']
)
break
# Save
solve_memory.save()
with open(f"{output_dir}/final_answer.md", 'w') as f:
f.write(format_result['final_answer'])
```
## Workflow Example
**Question**: "What is linear convolution?"
**Plan Phase**:
Generate 3 blocks:
- `b001`: Understand linear convolution definition
- `b002`: Master calculation methods
- `b003`: Learn application scenarios
**Block 1 (b001)**:
1. **Manager**: Generate 3 steps
- `s001`: Quote definition and explain
- `s002`: Explain mathematical expression
- `s003`: Provide examples
2. **Solve + Check**: Execute stepwise
- `s001`: Pass (1 attempt)
- `s002`: Needs revision (pass on 2nd attempt)
- `s003`: Pass (1 attempt)
**Block 2 (b002)**:
1. **Manager**: Generate 2 steps
- `s004`: Explain calculation steps
- `s005`: Demonstrate with code
2. **Solve + Check**: Execute stepwise
- `s004`: Pass
- `s005`: Call CodeAgent for execution, pass
**Block 3 (b003)**:
1. **Manager**: Generate 2 steps
- `s006`: List application domains
- `s007`: Summarize pros and cons
2. **Solve + Check**: Execute stepwise
- `s006`: Pass
- `s007`: Pass
**Format Phase**:
Integrate all steps, generate final answer, format 5 citations
## Key Features
### 1. Block-Based Planning
- Decompose complex problems into multiple blocks
- Each block has clear objectives
- Supports parallel thinking (though sequential execution)
### 2. Step-by-Step Solving
- Each block decomposes into concrete steps
- Execute sequentially, accumulate context
- Support tool calls (RAG, code execution)
### 3. Quality Assurance
- Check Agent cyclically validates
- Automatic error correction
- Maximum 3 retries
### 4. Citation Management
- Auto-assign numbering
- Deduplication handling
- Formatted output
### 5. Persistent Memory
- JSON format storage
- Supports checkpoint resumption
- Facilitates debugging and review
## Debugging and Monitoring
### View Memory Files
```bash
cat output/solve_memory.json | jq .
```
### Monitor Execution
Logs display detailed information for each step:
```
--- Step 1: s001 ---
Plan: Quote definition and explain
[Solve] Generating content...
[Check] Verdict: pass
✓ Step s001 completed
```
### Performance Statistics
```python
metadata = solve_memory.metadata
print(f"Total blocks: {metadata['total_blocks']}")
print(f"Total steps: {metadata['total_steps']}")
print(f"Completed: {metadata['completed_steps']}")
```
### View Citations
```python
from solve_loop.citation_manager import CitationManager
manager = CitationManager()
citations = manager.get_all_citations()
for cite in citations:
print(f"{cite['id']}: {cite['content'][:50]}...")
```
## Common Questions
**Q: How to adjust maximum retries per step?**
Set in `config.yaml`:
```yaml
system:
max_solve_correction_iterations: 3 # Default 3
```
**Q: How to enable precision answer?**
```yaml
agents:
precision_answer_agent:
enabled: true
```
**Q: Code execution timeout, what to do?**
Increase timeout:
```yaml
agents:
code_agent:
timeout: 20 # Increase to 20 seconds
```
**Q: How to view Check Agent feedback?**
Check logs for `[Check]` section or inspect `tool_logs` in `solve_memory.json`.
**Q: How to manually reset CitationManager?**
```python
from solve_loop.citation_manager import CitationManager
manager = CitationManager()
manager.reset()
```
---
**Related Documentation**:
- [Analysis Loop README](../analysis_loop/README.md)
- [Main README](../README.md)
-29
View File
@@ -1,29 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Solve Loop - Problem-solving workflow
Pipeline: Manager → [Solve → Tool → Note]* → PrecisionAnswer
Based on Analysis output, plan and execute problem-solving process, generate high-quality answers.
"""
from .citation_manager import CitationManager
from .manager_agent import ManagerAgent
from .precision_answer_agent import PrecisionAnswerAgent
from .response_agent import ResponseAgent
from .solve_agent import SolveAgent
from .solve_note_agent import SolveNoteAgent
from .tool_agent import ToolAgent
__all__ = [
# Core agents
"ManagerAgent",
"SolveAgent",
"ToolAgent",
"SolveNoteAgent",
"ResponseAgent",
"PrecisionAnswerAgent",
# Utils
"CitationManager",
]
@@ -1,74 +0,0 @@
#!/usr/bin/env python
"""
CitationManager - Citation number manager
Maintains singleton throughout Solve process, ensures citation numbers are globally unique and continuous
"""
from typing import Any, Optional
class CitationManager:
"""Citation number manager"""
_instance: Optional["CitationManager"] = None
def __new__(cls):
"""Singleton pattern"""
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._initialized = False
return cls._instance
def __init__(self):
"""Initialize citation manager"""
if self._initialized:
return
self.citation_counter = 0
self.citation_map: dict[str, dict[str, Any]] = {} # {citation_id: citation_info}
self._initialized = True
def allocate_citation_id(
self,
knowledge_id: str,
reference_id: str | None = None,
source: str | None = None,
content: str | None = None,
) -> str:
"""
Allocate citation number
Args:
knowledge_id: Knowledge item ID
reference_id: reference_id from KnowledgeItem.citations (e.g., "[1]")
source: Citation source
content: Citation content
Returns:
str: Citation number (e.g., "[1]")
"""
self.citation_counter += 1
citation_id = f"[{self.citation_counter}]"
self.citation_map[citation_id] = {
"knowledge_id": knowledge_id,
"reference_id": reference_id, # From KnowledgeItem.citations
"source": source,
"content": content,
"citation_id": citation_id,
}
return citation_id
def get_citation_info(self, citation_id: str) -> dict[str, Any] | None:
"""Get citation information"""
return self.citation_map.get(citation_id)
def get_all_citations(self) -> dict[str, dict[str, Any]]:
"""Get all citation mappings"""
return self.citation_map.copy()
def reset(self):
"""Reset citation manager (for new task)"""
self.citation_counter = 0
self.citation_map = {}
@@ -1,238 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ManagerAgent - Milestone Planner
Based on user question and knowledge chain, generates a coarse-grained todo-list
for the solve phase to iterate over.
"""
from pathlib import Path
import sys
from typing import Any
# Add project root to path
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))
from src.agents.base_agent import BaseAgent
from ..memory import InvestigateMemory, SolveMemory, TodoItem
from ..utils.json_utils import extract_json_from_text
class ManagerAgent(BaseAgent):
"""Manager Agent - Generates todo-list milestones for solving"""
def __init__(
self,
config: dict[str, Any],
api_key: str,
base_url: str,
api_version: str | None = None,
token_tracker=None,
):
language = config.get("system", {}).get("language", "zh")
super().__init__(
module_name="solve",
agent_name="manager_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
language=language,
config=config,
token_tracker=token_tracker,
)
async def process(
self,
question: str,
investigate_memory: InvestigateMemory,
solve_memory: SolveMemory,
verbose: bool = True,
) -> dict[str, Any]:
"""
Process management workflow - generate todo-list milestones
Args:
question: User question
investigate_memory: Investigation memory (contains knowledge chain)
solve_memory: Solve memory
verbose: Whether to print detailed information
Returns:
dict: Management result with todo-list info
"""
stage_label = "Plan"
self.logger.log_stage_progress(
stage_label, "start", f"question={question[:60]}{'...' if len(question) > 60 else ''}"
)
# 1. Check if todo-list already exists
if solve_memory.todo_list:
todos_count = len(solve_memory.todo_list)
self.logger.log_stage_progress(stage_label, "skip", f"Already has {todos_count} todos")
return {
"has_todos": True,
"todos_count": todos_count,
"num_todos": todos_count,
"message": "Todo-list already exists, skipping planning",
}
# 2. Build context
context = self._build_context(question=question, investigate_memory=investigate_memory)
# 3. Build Prompt
system_prompt = self._build_system_prompt()
user_prompt = self._build_user_prompt(context)
# 4. Call LLM (requires JSON format output)
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
verbose=verbose,
stage=stage_label,
response_format={"type": "json_object"}, # Force JSON
)
# 5. Parse output and create TodoItems
todos = self._parse_todo_response(response)
# 6. Add todos to solve_memory
solve_memory.create_todo_list(todos)
solve_memory.save()
# 7. Log todo-list details
todo_list_log = solve_memory.format_todo_list_for_log()
for line in todo_list_log.split("\n"):
self.logger.info(line)
todos_count = len(todos)
self.logger.log_stage_progress(stage_label, "complete", f"Generated {todos_count} todos")
return {
"has_todos": True,
"todos_count": todos_count,
"num_todos": todos_count,
"message": f"Generated {todos_count} todos",
}
def _build_context(
self, question: str, investigate_memory: InvestigateMemory
) -> dict[str, Any]:
"""Build context for LLM call"""
# Get knowledge chain information (cite_id + summary)
knowledge_info = []
for knowledge in investigate_memory.knowledge_chain:
if knowledge.summary: # Only use knowledge with summary
knowledge_info.append(
{
"cite_id": knowledge.cite_id,
"tool_type": knowledge.tool_type,
"query": knowledge.query,
"summary": knowledge.summary,
}
)
knowledge_text = ""
for info in knowledge_info:
knowledge_text += f"\n{info['cite_id']} [{info['tool_type']}]\n"
knowledge_text += f" Query: {info['query']}\n"
knowledge_text += f" Summary: {info['summary']}\n"
remaining_questions = []
if investigate_memory and getattr(investigate_memory, "reflections", None):
remaining_questions = investigate_memory.reflections.remaining_questions or []
reflections_summary = (
"\n".join(f"- {q}" for q in remaining_questions)
if remaining_questions
else "(No remaining questions)"
)
knowledge_summary_text = knowledge_text if knowledge_text else "(No research information)"
return {
"question": question,
"knowledge_info": knowledge_info,
"knowledge_text": knowledge_summary_text,
"knowledge_chain_summary": knowledge_summary_text,
"reflections_summary": reflections_summary,
}
def _build_system_prompt(self) -> str:
"""Build system prompt"""
prompt = self.get_prompt("system") if self.has_prompts() else None
if not prompt:
raise ValueError(
"ManagerAgent missing system prompt, please configure system section in prompts/zh/solve_loop/manager_agent.yaml."
)
return prompt
def _build_user_prompt(self, context: dict[str, Any]) -> str:
"""Build user prompt"""
template = self.get_prompt("user_template") if self.has_prompts() else None
if not template:
raise ValueError(
"ManagerAgent missing user prompt template, please configure user_template in prompts/zh/solve_loop/manager_agent.yaml."
)
return template.format(**context)
def _parse_todo_response(self, response: str) -> list[TodoItem]:
"""Parse LLM output (JSON format), create todo-list items"""
todos: list[TodoItem] = []
# Use json_utils to extract JSON
parsed_data = extract_json_from_text(response)
if not parsed_data or not isinstance(parsed_data, dict):
raise ValueError(
f"Failed to parse valid JSON object from LLM output. Original output: {response[:200]}..."
)
todos_data = parsed_data.get("todos", [])
if not isinstance(todos_data, list):
raise ValueError(f"'todos' field in JSON is not an array. Parsed result: {parsed_data}")
if not todos_data:
raise ValueError("'todos' array in JSON is empty, please check LLM output")
# Parse each todo
for idx, todo_data in enumerate(todos_data, 1):
if not isinstance(todo_data, dict):
self.logger.warning(
f"[ManagerAgent] Skipping invalid todo data (index {idx}): {todo_data}"
)
continue
# Get todo_id
todo_id = todo_data.get("todo_id", "").strip()
if not todo_id:
todo_id = f"T{idx}"
elif not todo_id.upper().startswith("T"):
todo_id = f"T{todo_id}"
# Get description
description = todo_data.get("description", "").strip()
if not description:
self.logger.warning(f"[ManagerAgent] Skipping todo {todo_id} with empty description")
continue
# Create todo item
todos.append(
TodoItem(
todo_id=todo_id,
description=description,
status="pending",
)
)
if not todos:
raise ValueError("Failed to parse any valid todos, please check LLM output format")
logger = getattr(self, "logger", None)
if logger is not None:
logger.info(f"[ManagerAgent._parse_todo_response] Parsed {len(todos)} todo items")
for todo in todos:
logger.info(f" - {todo.todo_id}: {todo.description}")
return todos
@@ -1,96 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PrecisionAnswerAgent - Precision answer generator (two-stage)
"""
from pathlib import Path
import sys
from typing import Any, Dict
project_root = Path(__file__).parent.parent.parent.parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
from src.agents.base_agent import BaseAgent
class PrecisionAnswerAgent(BaseAgent):
"""Staged precision answer"""
def __init__(
self,
config: Dict[str, Any],
api_key: str,
base_url: str,
api_version: str | None = None,
token_tracker=None,
):
language = config.get("system", {}).get("language", "zh")
super().__init__(
module_name="solve",
agent_name="precision_answer_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
language=language,
config=config,
token_tracker=token_tracker,
)
async def process(
self, question: str, detailed_answer: str, verbose: bool = True
) -> Dict[str, Any]:
decision = await self._should_generate(question, verbose)
if not decision["needs_precision"]:
return {
"needs_precision": False,
"precision_answer": "",
"final_answer": detailed_answer,
}
precision_answer = await self._generate_precision_answer(
question=question, detailed_answer=detailed_answer, verbose=verbose
)
return {
"needs_precision": True,
"precision_answer": precision_answer,
"final_answer": detailed_answer,
}
async def _should_generate(self, question: str, verbose: bool) -> Dict[str, Any]:
system_prompt = self.get_prompt("decision_system") if self.has_prompts() else None
if not system_prompt:
raise ValueError(
"PrecisionAnswerAgent missing decision_system prompt, please configure decision_system in prompts/{lang}/solve_loop/precision_answer_agent.yaml"
)
template = self.get_prompt("decision_user_template") if self.has_prompts() else None
if not template:
raise ValueError(
"PrecisionAnswerAgent missing decision_user_template, please configure decision_user_template in prompts/{lang}/solve_loop/precision_answer_agent.yaml"
)
user_prompt = template.format(question=question)
response = await self.call_llm(
user_prompt=user_prompt, system_prompt=system_prompt, verbose=verbose
)
needs_precision = response.strip().upper().startswith("Y")
return {"needs_precision": needs_precision, "raw_decision": response.strip()}
async def _generate_precision_answer(
self, question: str, detailed_answer: str, verbose: bool
) -> str:
system_prompt = self.get_prompt("precision_system") if self.has_prompts() else None
if not system_prompt:
raise ValueError(
"PrecisionAnswerAgent missing precision_system prompt, please configure precision_system in prompts/{lang}/solve_loop/precision_answer_agent.yaml"
)
template = self.get_prompt("precision_user_template") if self.has_prompts() else None
if not template:
raise ValueError(
"PrecisionAnswerAgent missing precision_user_template, please configure precision_user_template in prompts/{lang}/solve_loop/precision_answer_agent.yaml"
)
user_prompt = template.format(question=question, detailed_answer=detailed_answer)
response = await self.call_llm(
user_prompt=user_prompt, system_prompt=system_prompt, verbose=verbose
)
return response.strip()
@@ -1,526 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ResponseAgent - Step response generator
Based on completed todos and tool call chain from an iteration,
generates a formal, professional response for the completed work.
"""
from pathlib import Path
import re
import sys
from typing import Any, List, Optional
project_root = Path(__file__).parent.parent.parent.parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
from src.agents.base_agent import BaseAgent
from ..memory import (
CitationMemory,
InvestigateMemory,
IterationRecord,
SolveChainStep,
SolveMemory,
TodoItem,
ToolCallRecord,
)
class ResponseAgent(BaseAgent):
"""
Response generator Agent.
Generates professional step_response content based on:
- Completed todos from an iteration
- Tool call chain with summaries
- Knowledge from investigation phase
"""
def __init__(
self,
config: dict[str, Any],
api_key: str,
base_url: str,
api_version: str | None = None,
token_tracker=None,
):
language = config.get("system", {}).get("language", "zh")
super().__init__(
module_name="solve",
agent_name="response_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
language=language,
config=config,
token_tracker=token_tracker,
)
# Store citation configuration
self.enable_citations = config.get("system", {}).get("enable_citations", True)
async def process(
self,
question: str,
iteration_record: IterationRecord,
completed_todos: List[TodoItem],
citation_memory: CitationMemory,
knowledge_chain: List[Any],
output_dir: str | None = None,
accumulated_response: str = "",
verbose: bool = True,
) -> dict[str, Any]:
"""
Generate step_response for completed todos based on iteration results.
Args:
question: Original user question
iteration_record: The iteration record with tool call history
completed_todos: List of TodoItem objects that were completed
citation_memory: Citation memory for source tracking
knowledge_chain: Knowledge from investigation phase
output_dir: Output directory path
accumulated_response: Previous step responses for context
verbose: Whether to print detailed information
Returns:
dict: {
"step_response": str,
"used_citations": List[str],
"iteration_id": str
}
"""
if not completed_todos:
return {
"step_response": "",
"used_citations": [],
"iteration_id": iteration_record.iteration_id,
"skipped": True,
"reason": "No completed todos to respond to",
}
# Build context
context = self._build_context(
question=question,
iteration_record=iteration_record,
completed_todos=completed_todos,
citation_memory=citation_memory,
knowledge_chain=knowledge_chain,
output_dir=output_dir,
accumulated_response=accumulated_response,
)
system_prompt = self._build_system_prompt(context["image_materials"])
user_prompt = self._build_user_prompt(context)
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
verbose=verbose,
)
# Process response
step_response = response.strip() if response else ""
used_citations = self._extract_used_citations(
content=step_response,
tool_calls=iteration_record.tool_calls,
knowledge_chain=knowledge_chain,
)
# Update iteration record
iteration_record.set_step_response(step_response, used_citations)
return {
"step_response": step_response,
"used_citations": used_citations,
"iteration_id": iteration_record.iteration_id,
"completed_todo_ids": [t.todo_id for t in completed_todos],
"raw_response": response,
}
# ------------------------------------------------------------------ #
# Context Building
# ------------------------------------------------------------------ #
def _build_context(
self,
question: str,
iteration_record: IterationRecord,
completed_todos: List[TodoItem],
citation_memory: CitationMemory,
knowledge_chain: List[Any],
output_dir: str | None,
accumulated_response: str = "",
) -> dict[str, Any]:
"""Build context for LLM call"""
# Format completed todos
completed_todos_text = self._format_completed_todos(completed_todos)
# Format tool call chain
tool_materials, image_materials = self._format_tool_call_chain(
iteration_record.tool_calls, output_dir
)
# Format knowledge chain
knowledge_text = self._format_knowledge_chain(knowledge_chain)
# Format citation details
citation_details = self._format_citation_details(
iteration_record.tool_calls, citation_memory
)
# Get user preference from personalization service
preference = self._get_user_preference()
return {
"question": question,
"iteration_id": iteration_record.iteration_id,
"completed_todos": completed_todos_text,
"completed_todos_count": len(completed_todos),
"tool_materials": tool_materials,
"knowledge_chain": knowledge_text,
"citation_details": citation_details,
"image_materials": image_materials,
"previous_context": accumulated_response
or "(No previous content, this is the first step)",
"preference": preference,
}
def _get_user_preference(self) -> str:
"""Get user preference from personalization service."""
try:
from src.personalization.service import get_personalization_service
service = get_personalization_service()
preference = service.get_preference_for_prompt()
return preference if preference else "(No user preference recorded)"
except Exception as e:
self.logger.debug(f"Failed to get user preference: {e}")
return "(No user preference recorded)"
def _format_completed_todos(self, todos: List[TodoItem]) -> str:
"""Format completed todos for context"""
if not todos:
return "(No todos completed)"
lines = []
for todo in todos:
lines.append(f"- {todo.todo_id}: {todo.description}")
return "\n".join(lines)
def _format_tool_call_chain(
self,
tool_calls: List[ToolCallRecord],
output_dir: str | None,
) -> tuple[str, list[str]]:
"""Format tool call chain and extract images"""
if not tool_calls:
return "(No tool calls in this iteration)", []
lines: list[str] = []
images: list[str] = []
seen_images: set[str] = set()
def _append_image(path_str: str):
normalized = str(path_str).replace("\\", "/")
if normalized and normalized not in seen_images:
images.append(normalized)
seen_images.add(normalized)
for idx, call in enumerate(tool_calls, 1):
summary = call.summary or "(Summary pending)"
raw_preview = (call.raw_answer or "")[:500]
lines.append(
f"[{idx}] {call.tool_type} | cite_id={call.cite_id or 'N/A'} | Status={call.status}\n"
f"Query: {call.query}\n"
f"Summary: {summary}\n"
f"Raw excerpt: {raw_preview}"
)
# Extract images from metadata
if call.metadata:
artifact_rel_paths = call.metadata.get("artifact_rel_paths", [])
artifact_paths = call.metadata.get("artifact_paths", [])
artifacts = call.metadata.get("artifacts", [])
if artifact_rel_paths:
for rel_path in artifact_rel_paths:
_append_image(rel_path)
if artifact_paths:
for abs_path in artifact_paths:
path = Path(abs_path)
if path.suffix.lower() in {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}:
if output_dir:
try:
rel_path = path.relative_to(Path(output_dir))
_append_image(str(rel_path))
except ValueError:
_append_image(path.name)
else:
_append_image(path.name)
elif artifacts:
for artifact in artifacts:
path = Path(artifact)
if path.suffix.lower() in {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}:
rel_path = Path("artifacts") / path.name
_append_image(str(rel_path))
return "\n\n".join(lines), images
def _format_knowledge_chain(self, knowledge_chain: List[Any]) -> str:
"""Format knowledge chain from investigation phase"""
if not knowledge_chain:
return "(No prior knowledge from investigation)"
lines = []
for knowledge in knowledge_chain:
cite_id = getattr(knowledge, "cite_id", "")
tool_type = getattr(knowledge, "tool_type", "")
query = getattr(knowledge, "query", "")
summary = getattr(knowledge, "summary", "") or getattr(knowledge, "raw_result", "")[:300]
lines.append(
f"{cite_id} [{tool_type}]\n"
f" Query: {query}\n"
f" Summary: {summary}"
)
return "\n\n".join(lines) if lines else "(No prior knowledge)"
def _format_citation_details(
self,
tool_calls: List[ToolCallRecord],
citation_memory: CitationMemory,
) -> str:
"""Format citation details from tool calls"""
if not self.enable_citations:
return "(Citations disabled)"
cite_ids = [tc.cite_id for tc in tool_calls if tc.cite_id]
if not cite_ids:
return "(No citations)"
lines: list[str] = []
for cite_id in cite_ids:
citation = citation_memory.get_citation(cite_id)
if not citation:
continue
summary = citation.content or citation.raw_result[:200]
lines.append(f"- {cite_id} [{citation.tool_type}] Query: {citation.query}")
if summary:
lines.append(f" Summary: {summary[:300]}")
return "\n".join(lines) if lines else "(Citation information missing)"
# ------------------------------------------------------------------ #
# Prompt Building
# ------------------------------------------------------------------ #
def _build_system_prompt(self, image_materials: list[str]) -> str:
base_prompt = self.get_prompt("system") if self.has_prompts() else None
if not base_prompt:
# Fallback system prompt
base_prompt = """# Role Definition
You are a professional teaching assistant. Generate a high-quality response based on the completed todos and tool call results.
## Core Principles
1. **Continuity**: Follow directly after previous_context, maintaining smooth flow
2. **Evidence-based**: All conclusions must be based on the provided materials
3. **Professional format**: Well-structured with proper headings and formatting
## Key Norms
### Citation Format
- Cite sources using: `[cite_id]` (e.g., `[rag-1]`, `[code-2]`)
- Place immediately after the cited content
### Mathematical Formulas (LaTeX)
- Inline: `$x$`, `$E = mc^2$`
- Block: `$$` on separate lines
- Never use bare math variables in text
### Output Structure
- Use Markdown headings (## or ###)
- Include explanations for concepts
- Show logical derivation steps
- Summarize key points at the end
"""
# Add citation disable instruction if needed
citation_instruction = ""
if not self.enable_citations:
citation_instruction_yaml = self.get_prompt("citation_instruction_disabled")
if citation_instruction_yaml:
citation_instruction = citation_instruction_yaml
else:
citation_instruction = "\n\n**Important: Citation Feature Disabled**\n"
# Add image instructions if there are images
if image_materials:
image_list = "\n".join([f" - {img}" for img in image_materials])
image_instruction_template = self.get_prompt("image_instruction")
if image_instruction_template:
image_instruction = image_instruction_template.format(image_list=image_list)
else:
image_instruction = f"\n\n**Image files to insert**:\n{image_list}\n"
return base_prompt + citation_instruction + image_instruction
return base_prompt + citation_instruction
def _build_user_prompt(self, context: dict[str, Any]) -> str:
template = self.get_prompt("user_template") if self.has_prompts() else None
if not template:
# Fallback user template
template = """## User Preference
{preference}
## User Question
{question}
## Previous Context (Completed Steps)
{previous_context}
## Completed Todos This Iteration ({completed_todos_count} items)
{completed_todos}
## Tool Call Results
{tool_materials}
## Prior Knowledge (from investigation)
{knowledge_chain}
## Citation Details
{citation_details}
## Images to Insert
{image_materials}
## Task
Generate a professional response for the completed todos listed above.
The response should:
1. Address each completed todo with appropriate depth
2. Use evidence from tool call results
3. Include proper citations where applicable
4. Follow the formatting guidelines
"""
# Format image_materials as text
image_materials = context.get("image_materials", [])
if isinstance(image_materials, list):
if image_materials:
image_text = "\n".join([f"- {img}" for img in image_materials])
else:
image_text = "(No image files)"
else:
image_text = str(image_materials)
formatted_context = context.copy()
formatted_context["image_materials"] = image_text
return template.format(**formatted_context)
# ------------------------------------------------------------------ #
# Citation Extraction
# ------------------------------------------------------------------ #
def _extract_used_citations(
self,
content: str,
tool_calls: List[ToolCallRecord],
knowledge_chain: List[Any],
) -> list[str]:
"""Extract citation IDs used in the response"""
if not self.enable_citations:
return []
if not content:
return []
# Pattern to match citations
pattern = re.compile(r"\[([^\]\[]+)\](?!\()|【([^】\[]+)】")
matches = pattern.findall(content)
normalized: list[str] = []
for match in matches:
candidate = match[0] or match[1]
if not candidate:
continue
normalized.append(f"[{candidate.strip()}]")
# Build set of allowed citations
allowed = set()
for tc in tool_calls:
if tc.cite_id:
allowed.add(tc.cite_id)
for k in knowledge_chain:
cite_id = getattr(k, "cite_id", "")
if cite_id:
allowed.add(cite_id)
# Filter to only allowed citations, preserving order
ordered: list[str] = []
for cite in normalized:
if cite in allowed and cite not in ordered:
ordered.append(cite)
return ordered
# ------------------------------------------------------------------ #
# Legacy compatibility
# ------------------------------------------------------------------ #
class ResponseAgentLegacy(ResponseAgent):
"""Legacy wrapper for backward compatibility with SolveChainStep API"""
async def process_legacy(
self,
question: str,
step: SolveChainStep,
solve_memory: SolveMemory,
investigate_memory: InvestigateMemory,
citation_memory: CitationMemory,
output_dir: str | None = None,
verbose: bool = True,
accumulated_response: str = "",
) -> dict[str, Any]:
"""Legacy process method using SolveChainStep"""
if not step:
return {"step_response": "(No pending step)"}
# Convert SolveChainStep to IterationRecord format
iteration_record = IterationRecord(
iteration_id=step.step_id,
target_todo_id=step.step_id,
tool_calls=step.tool_calls,
)
# Create a pseudo TodoItem for the step
completed_todo = TodoItem(
todo_id=step.step_id,
description=step.step_target,
status="completed",
)
result = await self.process(
question=question,
iteration_record=iteration_record,
completed_todos=[completed_todo],
citation_memory=citation_memory,
knowledge_chain=investigate_memory.knowledge_chain,
output_dir=output_dir,
accumulated_response=accumulated_response,
verbose=verbose,
)
# Update legacy memory structures
if result.get("step_response"):
step.update_response(
response=result["step_response"],
used_citations=result.get("used_citations", []),
)
solve_memory.save()
return {
"step_id": step.step_id,
"step_response": result.get("step_response", ""),
"used_citations": result.get("used_citations", []),
"raw_response": result.get("raw_response", ""),
}
-344
View File
@@ -1,344 +0,0 @@
#!/usr/bin/env python
"""
SolveAgent - Iterative information collector
For a given todo item, iteratively decides which tool to call to gather information.
Outputs {tool_type, query} per iteration until tool_type == "none" signals completion.
"""
from pathlib import Path
import sys
from typing import Any, List, Optional
# Add project root to path
project_root = Path(__file__).parent.parent.parent.parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
from src.agents.base_agent import BaseAgent
from ..memory import (
InvestigateMemory,
IterationRecord,
SolveMemory,
TodoItem,
ToolCallRecord,
)
from ..utils.json_utils import extract_json_from_text
class SolveAgent(BaseAgent):
"""
Solve Agent - Information collector for solving todos.
For each todo, this agent iteratively decides what information to gather.
Each call returns a single {tool_type, query} decision.
When tool_type == "none", the iteration ends.
"""
SUPPORTED_TOOL_TYPES = {
"none", # End iteration - information is sufficient
"rag_naive", # Precise formula/definition lookup
"rag_hybrid", # Conceptual understanding/comparison
"web_search", # External/latest information
"code_execution", # Calculations, plotting, derivations
}
def __init__(
self,
config: dict[str, Any],
api_key: str,
base_url: str,
api_version: str | None = None,
token_tracker=None,
):
language = config.get("system", {}).get("language", "zh")
super().__init__(
module_name="solve",
agent_name="solve_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
language=language,
config=config,
token_tracker=token_tracker,
)
# Max iterations per todo to prevent infinite loops
self.max_iterations = config.get("solve", {}).get("max_inner_iterations", 5)
async def process(
self,
current_todo: TodoItem,
iteration_history: List[ToolCallRecord],
knowledge_chain: List[Any],
question: str,
verbose: bool = True,
) -> dict[str, Any]:
"""
Process a single iteration step for the current todo.
Decides whether to call a tool or end the iteration.
Args:
current_todo: The todo item being worked on
iteration_history: Previous tool calls in this iteration
knowledge_chain: Knowledge from investigate phase
question: Original user question
verbose: Whether to print detailed information
Returns:
dict: {
"tool_type": str, # "none" to end iteration
"query": str, # Query/intent for the tool
"should_stop": bool # True if tool_type is "none"
}
"""
# Check iteration limit
if len(iteration_history) >= self.max_iterations:
self.logger.warning(
f"[SolveAgent] Max iterations ({self.max_iterations}) reached for {current_todo.todo_id}"
)
return {
"tool_type": "none",
"query": "",
"should_stop": True,
"reason": "max_iterations_reached",
}
# Build context
context = self._build_context(
current_todo=current_todo,
iteration_history=iteration_history,
knowledge_chain=knowledge_chain,
question=question,
)
system_prompt = self._build_system_prompt()
user_prompt = self._build_user_prompt(context)
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
verbose=verbose,
response_format={"type": "json_object"},
)
# Parse the decision
decision = self._parse_decision(response)
if not decision:
self.logger.warning(
f"SolveAgent JSON parsing failed, defaulting to none. Raw: {response[:200]}..."
)
return {
"tool_type": "none",
"query": "",
"should_stop": True,
"reason": "parse_error",
}
tool_type = decision["tool_type"]
query = decision["query"]
should_stop = tool_type == "none"
return {
"tool_type": tool_type,
"query": query,
"should_stop": should_stop,
"raw_response": response,
}
# ------------------------------------------------------------------ #
# Context Building
# ------------------------------------------------------------------ #
def _build_context(
self,
current_todo: TodoItem,
iteration_history: List[ToolCallRecord],
knowledge_chain: List[Any],
question: str,
) -> dict[str, Any]:
"""Build context for LLM call"""
# Format current todo
todo_text = f"{current_todo.todo_id}: {current_todo.description}"
# Format iteration history
history_text = self._format_iteration_history(iteration_history)
# Format knowledge chain from investigate phase
knowledge_text = self._format_knowledge_chain(knowledge_chain)
return {
"question": question,
"current_todo": todo_text,
"iteration_history": history_text,
"knowledge_chain": knowledge_text,
"iteration_count": len(iteration_history),
"max_iterations": self.max_iterations,
}
def _format_iteration_history(self, history: List[ToolCallRecord]) -> str:
"""Format the iteration history for context"""
if not history:
return "(No previous tool calls in this iteration)"
lines = []
for idx, record in enumerate(history, 1):
summary = record.summary or "(pending)"
if record.raw_answer and not record.summary:
summary = record.raw_answer[:300] + "..."
lines.append(
f"[{idx}] {record.tool_type}\n"
f" Query: {record.query}\n"
f" cite_id: {record.cite_id or 'N/A'}\n"
f" Summary: {summary}"
)
return "\n\n".join(lines)
def _format_knowledge_chain(self, knowledge_chain: List[Any]) -> str:
"""Format knowledge chain from investigate phase"""
if not knowledge_chain:
return "(No prior knowledge from investigation)"
lines = []
for knowledge in knowledge_chain:
cite_id = getattr(knowledge, "cite_id", "")
tool_type = getattr(knowledge, "tool_type", "")
query = getattr(knowledge, "query", "")
summary = getattr(knowledge, "summary", "") or getattr(knowledge, "raw_result", "")[:300]
lines.append(
f"{cite_id} [{tool_type}]\n"
f" Query: {query}\n"
f" Summary: {summary}"
)
return "\n\n".join(lines) if lines else "(No prior knowledge)"
# ------------------------------------------------------------------ #
# Prompt Building
# ------------------------------------------------------------------ #
def _build_system_prompt(self) -> str:
prompt = self.get_prompt("system") if self.has_prompts() else None
if not prompt:
# Fallback prompt
prompt = """# Role Definition
You are the **Solve Agent**, responsible for gathering information to complete the current todo.
## Task
Decide what tool to call next to collect information for the current todo.
Output ONE tool call decision per response.
## Output Format (STRICT JSON)
{
"tool_type": "rag_naive | rag_hybrid | web_search | code_execution | none",
"query": "Your query or intent description"
}
## Tool Types
- `rag_naive`: Precise definition/formula lookup from knowledge base
- `rag_hybrid`: Conceptual understanding, comparison, or broader search
- `web_search`: External information, latest news, or resources not in KB
- `code_execution`: Calculations, derivations, plotting, data processing
- `none`: No more information needed, end this iteration
## Rules
1. Output exactly ONE tool call per response
2. Use `none` when you have sufficient information to complete the todo
3. Do NOT generate answer content - only decide what information to gather
4. Consider what's already been collected in iteration_history
"""
return prompt
def _build_user_prompt(self, context: dict[str, Any]) -> str:
template = self.get_prompt("user_template") if self.has_prompts() else None
if not template:
# Fallback template
template = """## User Question
{question}
## Current Todo
{current_todo}
## Prior Knowledge (from investigation phase)
{knowledge_chain}
## This Iteration's Tool Calls ({iteration_count}/{max_iterations})
{iteration_history}
## Task
Decide the next tool call to gather information for the current todo.
Output "none" as tool_type if information is sufficient.
Output valid JSON only."""
return template.format(**context)
# ------------------------------------------------------------------ #
# Response Parsing
# ------------------------------------------------------------------ #
def _parse_decision(self, response: str) -> Optional[dict[str, Any]]:
"""Parse the LLM decision - simplified output format"""
parsed_data = extract_json_from_text(response)
if not parsed_data or not isinstance(parsed_data, dict):
return None
tool_type = str(parsed_data.get("tool_type", "none")).strip().lower()
query = str(parsed_data.get("query", "")).strip()
# Normalize tool_type
if tool_type not in self.SUPPORTED_TOOL_TYPES:
# Try to map common variations
if tool_type in {"finish", "stop", "end", "done"}:
tool_type = "none"
elif tool_type in {"rag", "search", "kb"}:
tool_type = "rag_hybrid"
elif tool_type in {"web", "internet"}:
tool_type = "web_search"
elif tool_type in {"code", "python", "execute"}:
tool_type = "code_execution"
else:
self.logger.warning(f"[SolveAgent] Unknown tool_type '{tool_type}', defaulting to none")
tool_type = "none"
return {
"tool_type": tool_type,
"query": query,
}
# Legacy compatibility - keep old process signature as alternative
class SolveAgentLegacy(SolveAgent):
"""Legacy wrapper for backward compatibility with old API"""
async def process_legacy(
self,
question: str,
solve_memory: SolveMemory,
investigate_memory: InvestigateMemory,
citation_memory: Any,
kb_name: str = "ai_textbook",
output_dir: str | None = None,
verbose: bool = True,
) -> dict[str, Any]:
"""
Legacy process method - wraps new API for backward compatibility.
"""
current_todo = solve_memory.get_next_pending_todo()
if not current_todo:
return {
"tool_type": "none",
"query": "",
"should_stop": True,
"reason": "no_pending_todo",
}
# Get current iteration or empty history
current_iter = solve_memory.get_current_iteration()
iteration_history = current_iter.tool_calls if current_iter else []
return await self.process(
current_todo=current_todo,
iteration_history=iteration_history,
knowledge_chain=investigate_memory.knowledge_chain,
question=question,
verbose=verbose,
)
@@ -1,389 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
SolveNoteAgent - Todo-list manager
Responsible for reviewing the iteration results and managing the todo-list.
Can mark todos as done, edit their content, add new todos, or delete existing ones.
This agent enables dynamic todo-list management based on what was discovered during solving.
"""
from pathlib import Path
import sys
from typing import Any, List, Optional
# Add project root to path
project_root = Path(__file__).parent.parent.parent.parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
from src.agents.base_agent import BaseAgent
from ..memory import (
IterationRecord,
NoteAction,
SolveMemory,
TodoItem,
ToolCallRecord,
)
from ..utils.json_utils import extract_json_from_text
class SolveNoteAgent(BaseAgent):
"""
Note Agent - Manages todo-list based on iteration results.
Capabilities:
- Mark todos as done (completed)
- Edit todo content (for partial completion or refinement)
- Add new todos (for split tasks or discovered subtasks)
- Delete todos (if no longer needed or merged)
"""
VALID_ACTIONS = {"done", "edit", "add", "delete"}
def __init__(
self,
config: dict[str, Any],
api_key: str,
base_url: str,
api_version: str | None = None,
token_tracker=None,
):
language = config.get("system", {}).get("language", "zh")
super().__init__(
module_name="solve",
agent_name="solve_note_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
language=language,
config=config,
token_tracker=token_tracker,
)
async def process(
self,
solve_memory: SolveMemory,
iteration_record: IterationRecord,
target_todo: TodoItem,
verbose: bool = True,
) -> dict[str, Any]:
"""
Review iteration results and manage the todo-list.
Args:
solve_memory: Solve memory containing todo-list
iteration_record: The iteration record with tool call history
target_todo: The todo that was being worked on
verbose: Whether to print detailed information
Returns:
dict: {
"success": bool,
"actions": List[NoteAction],
"completed_todos": List[str], # todo_ids that were marked done
"raw_response": str
}
"""
# Build context
context = self._build_context(
solve_memory=solve_memory,
iteration_record=iteration_record,
target_todo=target_todo,
)
# Build prompts
system_prompt = self._build_system_prompt()
user_prompt = self._build_user_prompt(context)
# Call LLM
response = await self.call_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
verbose=verbose,
response_format={"type": "json_object"},
)
# Parse actions
actions = self._parse_actions(response)
# Convert to NoteAction objects
note_actions = [
NoteAction(
pre_id=action["pre_id"],
action=action["action"],
content=action.get("content"),
)
for action in actions
]
# Get cite_ids from iteration for evidence
cite_ids = iteration_record.get_all_cite_ids()
# Apply actions to solve_memory
completed_todos = solve_memory.apply_note_actions(
actions=note_actions,
iteration_id=iteration_record.iteration_id,
cite_ids=cite_ids,
)
# Update iteration record
iteration_record.set_note_actions(note_actions)
iteration_record.set_completed_todos(completed_todos)
# Save memory
solve_memory.save()
return {
"success": True,
"actions": [a.to_dict() for a in note_actions],
"completed_todos": completed_todos,
"total_actions": len(note_actions),
"raw_response": response,
}
# ------------------------------------------------------------------ #
# Context Building
# ------------------------------------------------------------------ #
def _build_context(
self,
solve_memory: SolveMemory,
iteration_record: IterationRecord,
target_todo: TodoItem,
) -> dict[str, Any]:
"""Build context for the note agent"""
# Format todo list with positions
todo_list_text = self._format_todo_list_with_positions(solve_memory.todo_list)
# Format iteration tool call history
tool_call_history = self._format_tool_call_history(iteration_record.tool_calls)
# Target todo info
target_todo_text = f"{target_todo.todo_id}: {target_todo.description}"
return {
"todo_list": todo_list_text,
"target_todo": target_todo_text,
"target_todo_id": target_todo.todo_id,
"tool_call_history": tool_call_history,
"total_todos": len(solve_memory.todo_list),
}
def _format_todo_list_with_positions(self, todo_list: List[TodoItem]) -> str:
"""Format todo-list with position numbers for reference"""
if not todo_list:
return "(Empty todo-list)"
lines = []
for idx, todo in enumerate(todo_list, 1):
status_marker = {
"pending": "[ ]",
"in_progress": "[~]",
"completed": "[x]",
"skipped": "[-]",
}.get(todo.status, "[ ]")
# Position is 1-indexed, pre_id for this todo would be idx
lines.append(f"[pos={idx}] {status_marker} {todo.todo_id}: {todo.description}")
return "\n".join(lines)
def _format_tool_call_history(self, tool_calls: List[ToolCallRecord]) -> str:
"""Format tool call history"""
if not tool_calls:
return "(No tool calls in this iteration)"
lines = []
for idx, call in enumerate(tool_calls, 1):
summary = call.summary or "(No summary)"
if call.raw_answer and not call.summary:
summary = call.raw_answer[:500] + "..."
lines.append(
f"[{idx}] {call.tool_type} (cite: {call.cite_id or 'N/A'})\n"
f" Query: {call.query}\n"
f" Summary: {summary}"
)
return "\n\n".join(lines)
# ------------------------------------------------------------------ #
# Prompt Building
# ------------------------------------------------------------------ #
def _build_system_prompt(self) -> str:
"""Build system prompt"""
prompt = self.get_prompt("system") if self.has_prompts() else None
if not prompt:
prompt = """# Role Definition
You are the **Todo Manager** for a problem-solving system.
Your task is to review the iteration results (tool call history) and update the todo-list accordingly.
## Capabilities
You can perform these actions on the todo-list:
- `done`: Mark a todo as completed
- `edit`: Change the content of a todo
- `add`: Insert a new todo at a specific position
- `delete`: Remove a todo from the list
## Output Format (STRICT JSON)
```json
{
"actions": [
{
"pre_id": 1,
"action": "done",
"content": null
},
{
"pre_id": 1,
"action": "add",
"content": "New subtask that needs investigation"
}
]
}
```
## pre_id Explanation
- `pre_id` indicates the position BEFORE which to operate
- `pre_id=1` means operate on position 1 (first todo)
- `pre_id=2` means operate on position 2 (second todo)
- For `add`, the new item is inserted AFTER the pre_id position
## Action Details
- `done`: Mark the todo at position pre_id as completed. content can be evidence or null.
- `edit`: Replace the content of todo at position pre_id with new content.
- `add`: Insert a new todo AFTER position pre_id. content is required.
- `delete`: Remove the todo at position pre_id. content is null.
## Guidelines
1. **At minimum**: Mark the target todo as done if the iteration provided sufficient information
2. **Partial completion**: If a todo is only partially answered, split it:
- Edit the original to reflect what was completed
- Mark it as done
- Add a new todo for the remaining part
3. **Discovered coverage**: If iteration results also cover other todos, mark them too
4. **Conservative**: Only mark as done if there's clear evidence from tool calls
"""
return prompt
def _build_user_prompt(self, context: dict[str, Any]) -> str:
"""Build user prompt"""
template = self.get_prompt("user_template") if self.has_prompts() else None
if not template:
template = """## Current Todo-list
{todo_list}
## Target Todo (being worked on)
{target_todo}
## This Iteration's Tool Call Results
{tool_call_history}
## Task
Based on the tool call results from this iteration:
1. Determine if the target todo ({target_todo_id}) can be marked as done
2. Check if the results also complete or affect other todos
3. If a todo is partially complete, consider splitting it
Output a JSON object with an "actions" array.
Each action must have: pre_id (position), action (done/edit/add/delete), content (if needed).
If no changes needed, return empty actions array: {{"actions": []}}
"""
return template.format(**context)
# ------------------------------------------------------------------ #
# Response Parsing
# ------------------------------------------------------------------ #
def _parse_actions(self, response: str) -> List[dict[str, Any]]:
"""Parse the actions from LLM response"""
parsed_data = extract_json_from_text(response)
if not parsed_data or not isinstance(parsed_data, dict):
self.logger.warning("[SolveNoteAgent] Failed to parse JSON response")
return []
actions = parsed_data.get("actions", [])
if not isinstance(actions, list):
return []
valid_actions = []
for action in actions:
if not isinstance(action, dict):
continue
pre_id = action.get("pre_id")
action_type = str(action.get("action", "")).strip().lower()
content = action.get("content")
# Validate pre_id
if pre_id is None:
self.logger.warning("[SolveNoteAgent] Missing pre_id in action")
continue
try:
pre_id = int(pre_id)
except (TypeError, ValueError):
self.logger.warning(f"[SolveNoteAgent] Invalid pre_id: {pre_id}")
continue
# Validate action type
if action_type not in self.VALID_ACTIONS:
self.logger.warning(f"[SolveNoteAgent] Invalid action: {action_type}")
continue
# Validate content for actions that need it
if action_type in {"edit", "add"} and not content:
self.logger.warning(f"[SolveNoteAgent] {action_type} requires content")
continue
# Normalize content
if content is not None:
content = str(content).strip()
if not content:
content = None
valid_actions.append({
"pre_id": pre_id,
"action": action_type,
"content": content,
})
return valid_actions
# Legacy compatibility wrapper
class SolveNoteAgentLegacy(SolveNoteAgent):
"""Legacy wrapper for backward compatibility"""
async def process_legacy(
self,
solve_memory: SolveMemory,
verbose: bool = True,
) -> dict[str, Any]:
"""
Legacy process method - gets context from solve_memory.
"""
current_iter = solve_memory.get_current_iteration()
if not current_iter:
return {
"success": False,
"reason": "No current iteration",
"actions": [],
"completed_todos": [],
}
target_todo = solve_memory.get_todo(current_iter.target_todo_id)
if not target_todo:
return {
"success": False,
"reason": f"Target todo {current_iter.target_todo_id} not found",
"actions": [],
"completed_todos": [],
}
return await self.process(
solve_memory=solve_memory,
iteration_record=current_iter,
target_todo=target_todo,
verbose=verbose,
)
-389
View File
@@ -1,389 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ToolAgent - Tool executor
Responsible for executing tool calls and producing summaries.
"""
from pathlib import Path
import re
import sys
from typing import Any
project_root = Path(__file__).parent.parent.parent.parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
from src.agents.base_agent import BaseAgent
from src.tools.code_executor import run_code
from src.tools.rag_tool import rag_search
from src.tools.web_search import web_search
from ..memory.solve_memory import ToolCallRecord
class ToolAgent(BaseAgent):
"""Execute tool calls and generate summary"""
def __init__(
self,
config: dict[str, Any],
api_key: str,
base_url: str,
api_version: str | None = None,
token_tracker=None,
):
language = config.get("system", {}).get("language", "zh")
super().__init__(
module_name="solve",
agent_name="tool_agent",
api_key=api_key,
base_url=base_url,
api_version=api_version,
language=language,
config=config,
token_tracker=token_tracker,
)
async def process(
self,
record: ToolCallRecord,
kb_name: str,
output_dir: str | None = None,
verbose: bool = True,
) -> dict[str, Any]:
"""
Execute a single tool call and return the result.
Args:
record: The tool call record to execute
kb_name: Knowledge base name
output_dir: Output directory path
verbose: Whether to print detailed information
Returns:
dict: Execution result with raw_answer, summary, and metadata
"""
base_dir = Path(output_dir).resolve() if output_dir else Path().resolve()
artifacts_dir = base_dir / "artifacts"
artifacts_dir.mkdir(parents=True, exist_ok=True)
raw_answer, metadata = await self._execute_single_call(
record=record,
kb_name=kb_name,
output_dir=output_dir,
artifacts_dir=str(artifacts_dir),
verbose=verbose,
)
summary = await self._summarize_tool_result(
tool_type=record.tool_type,
query=record.query,
raw_answer=raw_answer,
)
return {
"raw_answer": raw_answer,
"summary": summary,
"metadata": metadata,
}
async def _generate_code_from_intent(self, intent: str) -> str:
"""Generate Python code from a natural language intent description"""
system_prompt = """
You are a Python code generator.
Generate ONLY executable Python code.
Do NOT include explanations.
Do NOT include markdown fences.
Do NOT include comments unless necessary.
The code must be self-contained and runnable.
"""
user_prompt = f"""
Task:
{intent}
Rules:
- Output only Python code
- No ``` fences
- No natural language
"""
code = await self.call_llm(
system_prompt=system_prompt,
user_prompt=user_prompt,
verbose=False,
)
if "```" in code:
raise ValueError("LLM returned markdown code fences, which is forbidden")
if len(code) > 8000:
raise ValueError("Generated code too large")
return code.strip()
async def _execute_single_call(
self,
record: ToolCallRecord,
kb_name: str,
output_dir: str | None,
artifacts_dir: str,
verbose: bool,
) -> tuple[str, dict[str, Any]]:
"""
Execute a single tool call.
Args:
record: The tool call record
kb_name: Knowledge base name
output_dir: Output directory path
artifacts_dir: Directory for code execution artifacts
verbose: Whether to print detailed information
Returns:
tuple: (raw_answer, metadata)
"""
tool_type = record.tool_type
query = record.query
if tool_type == "rag_naive":
result = await rag_search(query=query, kb_name=kb_name, mode="naive")
answer = result.get("answer", "")
source, auto_sources = self._infer_sources(answer)
metadata = {"source": source, "auto_sources": auto_sources, "mode": "naive"}
return answer, metadata
if tool_type == "rag_hybrid":
result = await rag_search(query=query, kb_name=kb_name, mode="hybrid")
answer = result.get("answer", "")
source, auto_sources = self._infer_sources(answer)
metadata = {"source": source, "auto_sources": auto_sources, "mode": "hybrid"}
return answer, metadata
if tool_type == "web_search":
result = web_search(query=query, output_dir=output_dir, verbose=verbose)
answer = result.get("answer") or result.get("summary") or ""
used_citation_ids = self._extract_answer_citations(answer)
filtered_citations = self._select_web_citations(used_citation_ids, result)
metadata = {"result_file": result.get("result_file"), "citations": filtered_citations}
return answer, metadata
if tool_type == "code_execution":
artifacts_path = Path(artifacts_dir)
before_snapshot = self._snapshot_image_artifacts(artifacts_path)
if not query or not query.strip():
# If code is empty, directly return failure without execution
raw_answer = "【⚠️ Code execution failed】\nError: No valid code input received (Code is empty). Please check if [QUERY] contains a markdown code block."
metadata = {
"exit_code": 1,
"artifacts": [],
"artifact_paths": [],
"artifact_rel_paths": [],
"work_dir": artifacts_dir,
"execution_failed": True,
}
return raw_answer, metadata
code = await self._generate_code_from_intent(query)
exec_result = await run_code(
language="python",
code=code,
timeout=self.agent_config.get("code_timeout", 20),
assets_dir=artifacts_dir,
)
raw_answer = self._format_code_answer(exec_result, artifacts_dir)
exit_code = exec_result.get("exit_code", 0)
# Check if code execution failed
is_failed = exit_code != 0
if is_failed:
stderr = exec_result.get("stderr", "")
# Add obvious error prefix at the beginning of raw_answer
error_prefix = "【⚠️ Code execution failed】\n"
if "FileNotFoundError" in stderr and "artifacts/" in stderr:
error_prefix += "Path error detected: Code uses 'artifacts/xxx.png', but working directory is already the artifacts directory.\n"
error_prefix += "Please use 'xxx.png' instead of 'artifacts/xxx.png'.\n\n"
raw_answer = error_prefix + raw_answer
new_image_paths = self._collect_new_image_artifacts(
artifacts_path=artifacts_path,
before_snapshot=before_snapshot,
output_dir=output_dir,
)
metadata = {
"exit_code": exit_code,
"artifacts": exec_result.get("artifacts", []),
"artifact_paths": exec_result.get("artifact_paths", []),
"artifact_rel_paths": new_image_paths,
"work_dir": artifacts_dir,
"execution_failed": is_failed,
}
return raw_answer, metadata
raise ValueError(f"Unknown tool type: {tool_type}")
def _format_code_answer(self, exec_result: dict[str, Any], artifacts_dir: str) -> str:
"""Format code execution result as a readable string"""
stdout = exec_result.get("stdout", "")
stderr = exec_result.get("stderr", "")
artifacts = exec_result.get("artifacts", [])
artifact_paths = exec_result.get("artifact_paths", [])
lines = [
"【Code Execution Result】",
f"Exit code: {exec_result.get('exit_code')}",
f"Elapsed time: {exec_result.get('elapsed_ms', 0):.2f} ms",
f"Working directory: {artifacts_dir}",
"",
"stdout:",
stdout or "(empty)",
"",
"stderr:",
stderr or "(empty)",
]
if artifacts:
lines.append("")
lines.append("Artifacts:")
for idx, artifact in enumerate(artifacts):
abs_path = (
artifact_paths[idx]
if idx < len(artifact_paths)
else str(Path(artifacts_dir) / artifact)
)
lines.append(f"- {abs_path}")
return "\n".join(lines)
async def _summarize_tool_result(self, tool_type: str, query: str, raw_answer: str) -> str:
"""Generate a summary of the tool result using LLM"""
system_prompt = self.get_prompt("system") if self.has_prompts() else None
if not system_prompt:
raise ValueError(
"ToolAgent missing system prompt, please configure system in prompts/{lang}/solve_loop/tool_agent.yaml"
)
template = self.get_prompt("user_template") if self.has_prompts() else None
if not template:
raise ValueError(
"ToolAgent missing user_template, please configure user_template in prompts/{lang}/solve_loop/tool_agent.yaml"
)
user_prompt = template.format(
tool_type=tool_type, query=query, raw_answer=raw_answer[:2000]
)
response = await self.call_llm(
user_prompt=user_prompt, system_prompt=system_prompt, verbose=False
)
return response.strip()
# ------------------------------------------------------------------ #
# Helper methods
# ------------------------------------------------------------------ #
def _infer_sources(self, text: str) -> tuple[str, list[str]]:
"""Extract URLs from text"""
if not text:
return "", []
matches = re.findall(r"(https?://[^\s\)\]]+)", text)
cleaned = []
for item in matches:
normalized = item.strip().strip(".,;:()[]{}")
if normalized and normalized not in cleaned:
cleaned.append(normalized)
return (", ".join(cleaned), cleaned)
def _extract_answer_citations(self, answer: str) -> list[str]:
"""Extract citation IDs from answer text"""
if not answer:
return []
pattern = re.compile(r"\[(\d+)\]")
ids = pattern.findall(answer)
unique: list[str] = []
for cid in ids:
if cid not in unique:
unique.append(cid)
return unique
def _select_web_citations(
self, used_ids: list[str], result: dict[str, Any]
) -> list[dict[str, Any]]:
"""Select and format web citations based on used IDs"""
if not used_ids:
return []
raw_citations = result.get("citations") or []
search_results = result.get("search_results") or []
search_map = {item.get("url"): item for item in search_results if item.get("url")}
selected: list[dict[str, Any]] = []
for cid in used_ids:
matched = None
for raw in raw_citations:
ref_id = str(raw.get("id")) if raw.get("id") is not None else ""
ref_token = (raw.get("reference") or "").strip()
normalized_token = ref_token.strip("[]")
if cid == ref_id or cid == normalized_token:
matched = dict(raw)
break
if not matched:
continue
url = matched.get("url")
if url and url in search_map:
fallback = search_map[url]
matched.setdefault("title", fallback.get("title", ""))
matched.setdefault("snippet", fallback.get("snippet", ""))
selected.append(
{
"id": matched.get("id") or (int(cid) if cid.isdigit() else cid),
"reference": matched.get("reference") or f"[{cid}]",
"url": matched.get("url"),
"title": matched.get("title", ""),
}
)
return selected
# ------------------------------------------------------------------ #
# Artifacts helpers
# ------------------------------------------------------------------ #
IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}
def _snapshot_image_artifacts(self, artifacts_path: Path) -> set:
"""Take a snapshot of existing image files in artifacts directory"""
if not artifacts_path.exists():
return set()
snapshot = set()
for file_path in artifacts_path.rglob("*"):
if file_path.is_file() and file_path.suffix.lower() in self.IMAGE_SUFFIXES:
snapshot.add(file_path.resolve())
return snapshot
def _collect_new_image_artifacts(
self, artifacts_path: Path, before_snapshot: set, output_dir: str | None
) -> list[str]:
"""Collect newly created image artifacts"""
after_snapshot = self._snapshot_image_artifacts(artifacts_path)
new_files = sorted(after_snapshot - before_snapshot)
if not new_files:
return []
rel_paths: list[str] = []
output_base = Path(output_dir).resolve() if output_dir else None
for file_path in new_files:
rel_path: str | None = None
if output_base:
try:
rel_path = str(file_path.relative_to(output_base)).replace("\\", "/")
except ValueError:
rel_path = None
if rel_path is None:
try:
rel_path = str(file_path.relative_to(artifacts_path.parent)).replace("\\", "/")
except ValueError:
rel_path = str(Path("artifacts") / file_path.name)
rel_paths.append(rel_path)
return rel_paths
+5 -37
View File
@@ -1,10 +1,7 @@
#!/usr/bin/env python
"""
Utility Module
Contains logging, performance monitoring, config validation, parsers, etc.
Utility module for the solve agent.
"""
# Logging system (from unified logs module)
from pathlib import Path
import sys
@@ -15,50 +12,21 @@ if str(project_root) not in sys.path:
from src.logging import Logger, LogLevel, get_logger, reset_logger
# Backwards compatibility aliases
# These aliases maintain compatibility with code that imported these names before refactoring
SolveAgentLogger = Logger # Alias for Logger class
from .config_validator import ConfigValidator
from .error_handler import (
LLMParseError,
retry_on_parse_error,
validate_investigate_output,
validate_none_tool_constraint,
validate_note_output,
validate_output,
validate_reflect_output,
validate_solve_output,
)
# Backwards compatibility alias
ParseError = LLMParseError
from .performance_monitor import PerformanceMonitor
# Backwards compatibility alias used by API layer
SolveAgentLogger = Logger
# Token tracker
from .token_tracker import TokenTracker, calculate_cost, get_model_pricing
__all__ = [
# Logging system
# Logging
"Logger",
"get_logger",
"reset_logger",
"LogLevel",
"SolveAgentLogger", # Backwards compatibility
# Performance monitoring
"PerformanceMonitor",
# Config validation
"ConfigValidator",
"SolveAgentLogger",
# Token tracker
"TokenTracker",
"calculate_cost",
"get_model_pricing",
# Error handling
"ParseError",
"retry_on_parse_error",
"validate_output",
"validate_investigate_output",
"validate_note_output",
"validate_none_tool_constraint",
"validate_reflect_output",
"validate_solve_output",
]
-313
View File
@@ -1,313 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Config Validator - Configuration validator
Validates the completeness and correctness of config.yaml
"""
from pathlib import Path
from typing import Any
import yaml
class ConfigValidator:
"""Configuration validator"""
# Required top-level configuration items
# Note: llm configuration has been moved to environment variables (env_config.py), no longer required in config.yaml
REQUIRED_SECTIONS = ["system", "agents"]
# Required system configuration
REQUIRED_SYSTEM_CONFIGS = [
"output_base_dir",
"save_intermediate_results",
# Note: language is now unified in config/main.yaml, not required in sub-configs
]
# Supported languages (supports multiple formats)
SUPPORTED_LANGUAGES = ["zh", "en", "English", "Chinese"]
# Supported log levels
SUPPORTED_LOG_LEVELS = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
# Agent list - dual-loop architecture
STANDARD_AGENTS = [
# Analysis Loop
"investigate_agent",
"note_agent",
# Solve Loop
"manager_agent",
"solve_agent",
"tool_agent",
"response_agent",
"precision_answer_agent",
]
def __init__(self):
self.errors: list[str] = []
self.warnings: list[str] = []
def validate(self, config: dict[str, Any]) -> tuple[bool, list[str], list[str]]:
"""
Validate configuration
Args:
config: Configuration dictionary
Returns:
(is_valid, errors, warnings)
"""
self.errors = []
self.warnings = []
# 1. Validate top-level structure
self._validate_structure(config)
# 2. Validate system configuration
if "system" in config:
self._validate_system(config["system"])
# 3. Validate agents configuration
if "agents" in config:
self._validate_agents(config["agents"])
# 4. Validate llm configuration (optional, LLM config now mainly comes from environment variables)
if "llm" in config:
self._validate_llm(config["llm"])
# 5. Validate logging configuration (optional)
if "logging" in config:
self._validate_logging(config["logging"])
# 6. Validate monitoring configuration (optional)
if "monitoring" in config:
self._validate_monitoring(config["monitoring"])
is_valid = len(self.errors) == 0
return is_valid, self.errors, self.warnings
def _validate_structure(self, config: dict[str, Any]):
"""Validate top-level structure"""
for section in self.REQUIRED_SECTIONS:
if section not in config:
self.errors.append(f"Missing required configuration section: {section}")
def _validate_system(self, system_config: dict[str, Any]):
"""Validate system configuration"""
if system_config is None:
self.errors.append("system configuration cannot be None")
return
# Check required fields
for field in self.REQUIRED_SYSTEM_CONFIGS:
if field not in system_config:
self.errors.append(f"system config missing required field: {field}")
# Check language configuration (unified in config/main.yaml, optional in sub-configs)
if "language" in system_config:
lang = system_config["language"]
if lang not in self.SUPPORTED_LANGUAGES:
self.warnings.append(
f"language '{lang}' not in supported list: {self.SUPPORTED_LANGUAGES}. Suggest unified configuration in config/main.yaml."
)
# Backward compatibility: if output_language still exists, give warning
if "output_language" in system_config:
self.warnings.append(
"output_language is deprecated, please use language field. Language configuration has been unified to system.language in config/main.yaml"
)
# Check auto_solve configuration
if "auto_solve" in system_config:
if not isinstance(system_config["auto_solve"], bool):
self.errors.append("auto_solve must be a boolean value")
def _validate_agents(self, agents_config: dict[str, Any]):
"""Validate agents configuration"""
if agents_config is None:
self.errors.append("agents config cannot be None")
return
# Check if standard agents are configured
for agent_name in self.STANDARD_AGENTS:
if agent_name not in agents_config:
self.warnings.append(f"Agent not configured: {agent_name}")
else:
self._validate_agent_config(agent_name, agents_config[agent_name])
def _validate_agent_config(self, agent_name: str, agent_config: dict[str, Any]):
"""Validate single Agent configuration"""
if agent_config is None:
self.errors.append(f"{agent_name} config cannot be None")
return
# Check enabled field
if "enabled" in agent_config:
if not isinstance(agent_config["enabled"], bool):
self.errors.append(f"{agent_name}.enabled must be a boolean value")
# Check model field
if "model" in agent_config:
if not isinstance(agent_config["model"], str):
self.errors.append(f"{agent_name}.model must be a string")
# Check temperature field
if "temperature" in agent_config:
temp = agent_config["temperature"]
if not isinstance(temp, (int, float)):
self.errors.append(f"{agent_name}.temperature must be a number")
elif not 0 <= temp <= 2:
self.warnings.append(
f"{agent_name}.temperature={temp} exceeds recommended range [0, 2]"
)
# Check max_retries field
if "max_retries" in agent_config:
if not isinstance(agent_config["max_retries"], int):
self.errors.append(f"{agent_name}.max_retries must be an integer")
elif agent_config["max_retries"] < 0:
self.errors.append(f"{agent_name}.max_retries cannot be negative")
def _validate_llm(self, llm_config: dict[str, Any]):
"""Validate llm configuration"""
if llm_config is None:
self.errors.append("llm config cannot be None")
return
# Check default_model
if "default_model" not in llm_config:
self.warnings.append("llm config missing default_model field")
# Check max_retries
if "max_retries" in llm_config:
if not isinstance(llm_config["max_retries"], int):
self.errors.append("llm.max_retries must be an integer")
elif llm_config["max_retries"] < 0:
self.errors.append("llm.max_retries cannot be negative")
# Check timeout
if "timeout" in llm_config:
if not isinstance(llm_config["timeout"], (int, float)):
self.errors.append("llm.timeout must be a number")
elif llm_config["timeout"] <= 0:
self.warnings.append("llm.timeout should not be negative or zero")
def _validate_logging(self, logging_config: dict[str, Any]):
"""Validate logging configuration"""
if logging_config is None:
# logging is optional, if None but not empty key, may be considered error or ignored
self.errors.append("logging config cannot be None")
return
# Check level
if "level" in logging_config:
level = logging_config["level"]
if level not in self.SUPPORTED_LOG_LEVELS:
self.errors.append(
f"logging.level '{level}' not in supported list: {self.SUPPORTED_LOG_LEVELS}"
)
# Check save_to_file
if "save_to_file" in logging_config:
if not isinstance(logging_config["save_to_file"], bool):
self.errors.append("logging.save_to_file must be a boolean value")
# Check verbose
if "verbose" in logging_config:
if not isinstance(logging_config["verbose"], bool):
self.errors.append("logging.verbose must be a boolean value")
def _validate_monitoring(self, monitoring_config: dict[str, Any]):
"""Validate monitoring configuration"""
if monitoring_config is None:
self.errors.append("monitoring config cannot be None")
return
# Check enabled
if "enabled" in monitoring_config:
if not isinstance(monitoring_config["enabled"], bool):
self.errors.append("monitoring.enabled must be a boolean value")
# Check track_token_usage
if "track_token_usage" in monitoring_config:
if not isinstance(monitoring_config["track_token_usage"], bool):
self.errors.append("monitoring.track_token_usage must be a boolean value")
# Check track_time
if "track_time" in monitoring_config:
if not isinstance(monitoring_config["track_time"], bool):
self.errors.append("monitoring.track_time must be a boolean value")
def validate_config_file(config_path: str) -> tuple[bool, list[str], list[str]]:
"""
Validate configuration file
Args:
config_path: Configuration file path
Returns:
(is_valid, errors, warnings)
"""
try:
with open(config_path, encoding="utf-8") as f:
config = yaml.safe_load(f)
except FileNotFoundError:
return False, [f"Configuration file does not exist: {config_path}"], []
except yaml.YAMLError as e:
return False, [f"YAML parsing error: {e!s}"], []
except Exception as e:
return False, [f"Failed to load configuration file: {e!s}"], []
validator = ConfigValidator()
return validator.validate(config)
def print_validation_result(is_valid: bool, errors: list[str], warnings: list[str]):
"""
Print validation result
Args:
is_valid: Whether configuration is valid
errors: List of errors
warnings: List of warnings
"""
print("=" * 60)
print("Configuration Validation Result")
print("=" * 60)
if is_valid:
print("✓ Configuration validation passed")
else:
print("✗ Configuration validation failed")
print()
if errors:
print(f"Errors ({len(errors)}):")
for i, error in enumerate(errors, 1):
print(f" {i}. {error}")
print()
if warnings:
print(f"Warnings ({len(warnings)}):")
for i, warning in enumerate(warnings, 1):
print(f" {i}. {warning}")
print()
print("=" * 60)
if __name__ == "__main__":
# Test configuration validation
print("Configuration Validation Test")
print("=" * 60)
# Validate config.yaml in current directory
config_path = Path(__file__).parent.parent.parent.parent / "config.yaml"
if config_path.exists():
is_valid, errors, warnings = validate_config_file(str(config_path))
print_validation_result(is_valid, errors, warnings)
else:
print(f"Configuration file not found: {config_path}")
+3 -7
View File
@@ -36,13 +36,9 @@ class DisplayManager:
self.rich_available = RICH_AVAILABLE
self.agents_status = {
"InvestigateAgent": "pending",
"NoteAgent": "pending",
"ManagerAgent": "pending",
"SolveAgent": "pending",
"ToolAgent": "pending",
"ResponseAgent": "pending",
"PrecisionAnswerAgent": "pending",
"PlannerAgent": "pending",
"SolverAgent": "pending",
"WriterAgent": "pending",
}
self.stats = {
-363
View File
@@ -1,363 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Error Handler - Error handling and retry mechanism
"""
from collections.abc import Callable
from typing import Any, Optional
from pydantic import BaseModel, Field, ValidationError, field_validator, model_validator
import tenacity
from src.config.constants import VALID_INVESTIGATE_TOOLS, VALID_SOLVE_TOOLS
from src.logging.logger import get_logger
from src.services.llm.exceptions import LLMParseError
def _format_validation_errors(e: ValidationError) -> str:
"""Format Pydantic validation errors into a readable string."""
return "; ".join(
[f"{'.'.join(str(x) for x in err['loc']) or 'root'}: {err['msg']}" for err in e.errors()]
)
# Pydantic models for output validation
class ToolIntent(BaseModel):
"""Model for tool intent in investigate output"""
tool_type: str = Field(..., description="Type of tool to use")
query: str = Field("", description="Query for the tool")
identifier: Optional[str] = Field(None, description="Optional identifier")
@field_validator("tool_type")
@classmethod
def validate_tool_type(cls, v):
if v.lower() not in VALID_INVESTIGATE_TOOLS:
raise ValueError(f"tool_type must be one of {VALID_INVESTIGATE_TOOLS}, got: {v}")
return v.lower()
@field_validator("query")
@classmethod
def validate_query_required(cls, v, info):
tool_type = info.data.get("tool_type", "").lower()
if tool_type != "none" and not v:
raise ValueError("query is required for non-none tools")
return v
class InvestigateOutput(BaseModel):
"""Model for InvestigateAgent output"""
reasoning: str = Field(..., description="Reasoning for the investigation")
tools: list[ToolIntent] = Field(..., min_length=1, description="List of tool intents")
@field_validator("tools")
@classmethod
def validate_tools_consistency(cls, v):
# Check for 'none' tool exclusivity
has_none = any(tool.tool_type == "none" for tool in v)
if has_none and len(v) > 1:
raise ValueError("When 'none' tool exists, no other tool intents should be provided")
return v
class Citation(BaseModel):
"""Model for citation in note output"""
reference_id: Optional[str] = None
source: Optional[str] = None
content: Optional[str] = None
@model_validator(mode="after")
def validate_citation_fields(self):
"""Validate that at least one of reference_id or source is provided."""
if not self.reference_id and not self.source:
raise ValueError("citation must contain reference_id or source")
return self
class NoteOutput(BaseModel):
"""Model for NoteAgent output"""
summary: str = Field(..., description="Summary of the notes")
citations: list[Citation] = Field(default_factory=list, description="List of citations")
class ReflectOutput(BaseModel):
"""Model for InvestigateReflectAgent output"""
should_stop: bool = Field(..., description="Whether to stop the investigation")
reason: str = Field(..., description="Reason for the decision")
remaining_questions: list[str] = Field(..., description="List of remaining questions")
class PlanStep(BaseModel):
"""Model for plan step"""
step_id: str = Field(..., description="Step identifier")
plan: str = Field(..., description="Plan description")
class PlanBlock(BaseModel):
"""Model for plan block"""
block_id: str = Field(..., description="Block identifier")
format: str = Field(..., description="Output format")
steps: list[PlanStep] = Field(..., min_length=1, description="List of steps")
class PlanOutput(BaseModel):
"""Model for PlanAgent output"""
answer_style: str = Field(..., description="Style of the answer")
blocks: list[PlanBlock] = Field(..., min_length=1, description="List of plan blocks")
class SolveToolCall(BaseModel):
"""Model for tool call in solve output"""
tool_type: str = Field(..., description="Type of tool to call")
query: str = Field(..., description="Query for the tool call")
@field_validator("tool_type")
@classmethod
def validate_tool_type(cls, v):
if v.lower() not in VALID_SOLVE_TOOLS:
raise ValueError(f"tool_type must be one of {VALID_SOLVE_TOOLS}, got: {v}")
return v.lower()
class SolveOutput(BaseModel):
"""Model for SolveAgent output"""
tool_calls: list[SolveToolCall] = Field(..., min_length=1, description="List of tool calls")
# Initialize module logger
logger = get_logger("ErrorHandler")
def retry_on_parse_error(
max_retries: int = 2,
delay: float = 1.0,
backoff: float = 2.0,
exceptions: tuple[type[Exception], ...] = (LLMParseError,),
):
"""
Parse error retry decorator using tenacity.
Args:
max_retries: Maximum retry count
delay: Initial delay time (seconds)
backoff: Delay multiplier factor
exceptions: Tuple of exception types to retry on (default: LLMParseError only)
Returns:
Decorated function
"""
def decorator(func: Callable):
return tenacity.retry(
retry=tenacity.retry_if_exception_type(*exceptions),
wait=tenacity.wait_exponential(multiplier=backoff, min=delay, max=60),
stop=tenacity.stop_after_attempt(max_retries + 1),
before_sleep=lambda retry_state: logger.warning(
f"Parse failed (attempt {retry_state.attempt_number}/{max_retries + 1}), "
f"retrying in {retry_state.upcoming_sleep:.1f}s... Error: {str(retry_state.outcome.exception())}"
),
)(func)
return decorator
def validate_output(
output: dict[str, Any], required_fields: list, field_types: dict[str, type] | None = None
) -> bool:
"""
Validate output contains required fields and correct types
Args:
output: Output dictionary
required_fields: List of required fields
field_types: Field type dictionary (optional)
Returns:
bool: Whether valid
Raises:
LLMParseError: Raised when validation fails
"""
# Check required fields
missing_fields = [field for field in required_fields if field not in output]
if missing_fields:
raise LLMParseError(f"Missing required fields: {', '.join(missing_fields)}")
# Check field types
if field_types:
for field, expected_type in field_types.items():
if field in output and not isinstance(output[field], expected_type):
actual_type = type(output[field]).__name__
expected_type_name = expected_type.__name__
raise LLMParseError(
f"Field '{field}' type error: expected {expected_type_name}, got {actual_type}"
)
return True
def safe_parse(
text: str, parser_func: Callable, default: Any = None, raise_on_error: bool = False
) -> Any:
"""
Safe parsing (catch exceptions and return default value)
Args:
parser_func: Parser function
text: Text to parse
default: Default value
raise_on_error: Whether to raise exception on error
Returns:
Parsed result or default value
"""
try:
return parser_func(text)
except Exception as e:
if raise_on_error:
raise LLMParseError(f"Parsing failed: {e!s}") from e
logger.error(
f"Parsing failed; falling back to default value {default!r}. This may affect behavior. Error: {e!s}",
exc_info=True,
)
return default
def validate_investigate_output(
output: dict[str, Any], valid_tools: list[str] = VALID_INVESTIGATE_TOOLS
) -> bool:
"""Validate InvestigateAgent output using Pydantic model"""
# Check if custom tools are provided
if valid_tools != VALID_INVESTIGATE_TOOLS:
# For custom tools, do manual validation
validate_output(output, ["reasoning"], {"reasoning": str})
tools = output.get("tools", [])
if not isinstance(tools, list) or len(tools) < 1:
raise LLMParseError("tools must be a non-empty list")
for i, tool in enumerate(tools):
if not isinstance(tool, dict):
raise LLMParseError(f"tool[{i}] must be a dictionary")
tool_type = tool.get("tool_type", "").lower()
if tool_type not in valid_tools:
raise LLMParseError(
f"tool[{i}] tool_type must be one of {valid_tools}, got: {tool_type}"
)
if tool_type != "none" and not tool.get("query"):
raise LLMParseError(f"tool[{i}] missing query")
# Check none tool exclusivity
has_none = any(t.get("tool_type", "").lower() == "none" for t in tools)
if has_none and len(tools) > 1:
raise LLMParseError("When 'none' tool exists, no other tool intents should be provided")
return True
# Use Pydantic for standard validation
try:
InvestigateOutput(**output)
return True
except ValidationError as e:
error_details = _format_validation_errors(e)
raise LLMParseError(f"InvestigateAgent output validation failed: {error_details}") from e
def validate_note_output(output: dict[str, Any]) -> bool:
"""Validate NoteAgent output using Pydantic model"""
try:
NoteOutput(**output)
return True
except ValidationError as e:
error_details = _format_validation_errors(e)
raise LLMParseError(f"NoteAgent output validation failed: {error_details}") from e
def validate_reflect_output(output: dict[str, Any]) -> bool:
"""Validate InvestigateReflectAgent output using Pydantic model"""
try:
ReflectOutput(**output)
return True
except ValidationError as e:
error_details = _format_validation_errors(e)
raise LLMParseError(
f"InvestigateReflectAgent output validation failed: {error_details}"
) from e
def validate_plan_output(output: dict[str, Any]) -> bool:
"""Validate PlanAgent output using Pydantic model"""
try:
PlanOutput(**output)
return True
except ValidationError as e:
error_details = _format_validation_errors(e)
raise LLMParseError(f"PlanAgent output validation failed: {error_details}") from e
def validate_solve_output(
output: dict[str, Any], valid_tool_types: list[str] = VALID_SOLVE_TOOLS
) -> bool:
"""Validate SolveAgent output using Pydantic model"""
# Check if custom tools are provided
if valid_tool_types != VALID_SOLVE_TOOLS:
# For custom tools, do manual validation
validate_output(output, ["tool_calls"], {"tool_calls": list})
tool_calls = output.get("tool_calls", [])
if not isinstance(tool_calls, list) or len(tool_calls) < 1:
raise LLMParseError("tool_calls must be a non-empty list")
for i, tool_call in enumerate(tool_calls):
if not isinstance(tool_call, dict):
raise LLMParseError(f"tool_call[{i}] must be a dictionary")
if "tool_type" not in tool_call or "query" not in tool_call:
raise LLMParseError(f"tool_call[{i}] missing required fields: tool_type, query")
tool_type = tool_call.get("tool_type", "").lower()
if tool_type not in valid_tool_types:
raise LLMParseError(
f"Invalid tool_type: {tool_type}, must be one of {valid_tool_types}"
)
return True
# Use Pydantic for standard validation
try:
SolveOutput(**output)
return True
except ValidationError as e:
error_details = _format_validation_errors(e)
raise LLMParseError(f"SolveAgent output validation failed: {error_details}") from e
def validate_none_tool_constraint(
tools: list[dict[str, Any]], tool_type_key: str = "tool_type"
) -> None:
"""
Validate that 'none' tool does not coexist with other tools.
Args:
tools: List of tool dictionaries
tool_type_key: Key to access tool type in each dict (default: "tool_type")
Raises:
LLMParseError: If none tool constraint is violated
"""
has_none = any(
isinstance(tool_type := tool.get(tool_type_key), str) and tool_type.lower() == "none"
for tool in tools
)
if has_none and len(tools) > 1:
raise LLMParseError(
f"When 'none' tool exists, no other tool intents should be provided. "
f"Found {len(tools)} tools with types: {[tool.get(tool_type_key) for tool in tools]}"
)
@@ -1,409 +0,0 @@
#!/usr/bin/env python
"""
Performance Monitor - Performance monitoring and tracking system
Records Agent execution time, Token consumption and other metrics
"""
from collections.abc import Callable
from contextlib import contextmanager
from dataclasses import asdict, dataclass, field
from datetime import datetime
from functools import wraps
import json
from pathlib import Path
import time
from typing import Any
from src.services.path_service import get_path_service
@dataclass
class PerformanceMetrics:
"""Performance metrics"""
# Basic information
agent_name: str # Agent name
start_time: float # Start time (timestamp)
end_time: float | None = None # End time (timestamp)
duration: float | None = None # Duration (seconds)
# Token statistics
prompt_tokens: int = 0 # Prompt token count
completion_tokens: int = 0 # Generated token count
total_tokens: int = 0 # Total token count
# Request statistics
api_calls: int = 0 # API call count
errors: int = 0 # Error count
# Custom metrics
custom_metrics: dict[str, Any] = field(default_factory=dict)
def mark_end(self):
"""Mark end time and calculate duration"""
self.end_time = time.time()
if self.start_time:
self.duration = self.end_time - self.start_time
def add_tokens(self, prompt: int = 0, completion: int = 0):
"""Add Token statistics"""
self.prompt_tokens += prompt
self.completion_tokens += completion
self.total_tokens = self.prompt_tokens + self.completion_tokens
def add_api_call(self):
"""Increment API call count"""
self.api_calls += 1
def add_error(self):
"""Increment error count"""
self.errors += 1
def set_custom_metric(self, key: str, value: Any):
"""Set custom metric"""
self.custom_metrics[key] = value
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary"""
return asdict(self)
def summary(self) -> str:
"""Generate summary"""
lines = [
f"Agent: {self.agent_name}",
f"Duration: {self.duration:.2f}s" if self.duration else "Duration: N/A",
f"Total Tokens: {self.total_tokens}",
f" Prompt: {self.prompt_tokens}",
f" Completion: {self.completion_tokens}",
f"API Calls: {self.api_calls}",
f"Errors: {self.errors}",
]
if self.custom_metrics:
lines.append("Custom Metrics:")
for k, v in self.custom_metrics.items():
lines.append(f" {k}: {v}")
return "\n".join(lines)
class PerformanceMonitor:
"""Performance monitor"""
def __init__(self, enabled: bool = True, save_dir: str | None = None):
"""
Initialize performance monitor
Args:
enabled: Whether to enable monitoring
save_dir: Save directory (None uses ./data/user/performance)
"""
self.enabled = enabled
if save_dir is None:
# Default to data/user/agent/logs/performance using PathService
path_service = get_path_service()
self.save_dir = path_service.get_logs_dir() / "performance"
else:
self.save_dir = Path(save_dir)
if self.enabled:
self.save_dir.mkdir(parents=True, exist_ok=True)
# Current session metrics
self.metrics: dict[str, PerformanceMetrics] = {}
# Overall statistics
self.total_duration = 0.0
self.total_tokens = 0
self.total_api_calls = 0
self.total_errors = 0
def start_tracking(self, agent_name: str) -> PerformanceMetrics:
"""
Start tracking Agent performance
Args:
agent_name: Agent name
Returns:
PerformanceMetrics instance
"""
if not self.enabled:
return PerformanceMetrics(agent_name=agent_name, start_time=time.time())
metrics = PerformanceMetrics(agent_name=agent_name, start_time=time.time())
self.metrics[agent_name] = metrics
return metrics
def end_tracking(self, agent_name: str):
"""
End tracking and update statistics
Args:
agent_name: Agent name
"""
if not self.enabled:
return
if agent_name in self.metrics:
metrics = self.metrics[agent_name]
metrics.mark_end()
# Update overall statistics
if metrics.duration:
self.total_duration += metrics.duration
self.total_tokens += metrics.total_tokens
self.total_api_calls += metrics.api_calls
self.total_errors += metrics.errors
@contextmanager
def track(self, agent_name: str):
"""
Context manager: automatically track Agent performance
Args:
agent_name: Agent name
Usage:
with monitor.track("agent_name"):
# Agent execution logic
...
"""
# Start tracking
metrics = self.start_tracking(agent_name)
try:
yield metrics
except Exception:
# Record error
if self.enabled:
metrics.add_error()
raise
finally:
# End tracking
self.end_tracking(agent_name)
def get_metrics(self, agent_name: str) -> PerformanceMetrics | None:
"""
Get Agent performance metrics
Args:
agent_name: Agent name
Returns:
PerformanceMetrics instance, or None if not found
"""
return self.metrics.get(agent_name)
def get_all_metrics(self) -> dict[str, PerformanceMetrics]:
"""Get all metrics"""
return self.metrics
def get_summary(self) -> dict[str, Any]:
"""
Get overall statistics summary
Returns:
{
'total_duration': float,
'total_tokens': int,
'total_api_calls': int,
'total_errors': int,
'agents': Dict[str, Dict]
}
"""
return {
"total_duration": self.total_duration,
"total_tokens": self.total_tokens,
"total_api_calls": self.total_api_calls,
"total_errors": self.total_errors,
"agents": {name: metrics.to_dict() for name, metrics in self.metrics.items()},
}
def generate_report(self) -> dict[str, Any]:
"""
Generate performance report (alias for get_summary)
Returns:
Performance report dictionary
"""
return self.get_summary()
def save(self, filepath: str | None = None) -> str:
"""
Save performance metrics to file
Args:
filepath: Save path (None for auto-generated)
Returns:
Saved file path
"""
if not self.enabled:
return ""
if filepath is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filepath = self.save_dir / f"performance_{timestamp}.json"
else:
filepath = Path(filepath)
summary = self.get_summary()
with open(filepath, "w", encoding="utf-8") as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
return str(filepath)
def print_summary(self):
"""Print overall statistics summary"""
print("=" * 60)
print("Performance Monitoring Summary")
print("=" * 60)
print(f"Total Duration: {self.total_duration:.2f}s")
print(f"Total Tokens: {self.total_tokens}")
print(f"Total API Calls: {self.total_api_calls}")
print(f"Total Errors: {self.total_errors}")
print()
print("Agent Details:")
print("-" * 60)
for agent_name, metrics in self.metrics.items():
print(f"\n{agent_name}:")
print(f" Duration: {metrics.duration:.2f}s" if metrics.duration else " Duration: N/A")
print(f" Tokens: {metrics.total_tokens}")
print(f" API Calls: {metrics.api_calls}")
print(f" Errors: {metrics.errors}")
print("=" * 60)
def reset(self):
"""Reset all statistics"""
self.metrics.clear()
self.total_duration = 0.0
self.total_tokens = 0
self.total_api_calls = 0
self.total_errors = 0
# Decorator: automatically track Agent performance
def track_performance(monitor: PerformanceMonitor):
"""
Performance tracking decorator
Args:
monitor: PerformanceMonitor instance
Usage:
@track_performance(monitor)
async def my_agent_process(...):
...
"""
def decorator(func: Callable) -> Callable:
@wraps(func)
async def wrapper(self, *args, **kwargs):
agent_name = getattr(self, "agent_name", func.__name__)
# Start tracking
metrics = monitor.start_tracking(agent_name)
try:
result = await func(self, *args, **kwargs)
return result
except Exception:
metrics.add_error()
raise
finally:
# End tracking
monitor.end_tracking(agent_name)
return wrapper
return decorator
# Global monitor instance
_global_monitor: PerformanceMonitor | None = None
def get_monitor(enabled: bool = True, save_dir: str | None = None) -> PerformanceMonitor:
"""
Get global monitor instance (singleton pattern)
Args:
enabled: Whether to enable
save_dir: Save directory
Returns:
PerformanceMonitor instance
"""
global _global_monitor
if _global_monitor is None:
_global_monitor = PerformanceMonitor(enabled=enabled, save_dir=save_dir)
return _global_monitor
def init_monitor_from_config(config: dict) -> PerformanceMonitor:
"""
Initialize monitor from configuration
Args:
config: Configuration dictionary
Returns:
PerformanceMonitor instance
"""
monitoring_config = config.get("monitoring", {})
enabled = monitoring_config.get("enabled", True)
save_dir = monitoring_config.get("save_dir", "./logs/performance")
return get_monitor(enabled=enabled, save_dir=save_dir)
if __name__ == "__main__":
# Test performance monitoring
print("Performance Monitoring Test")
print("=" * 60)
# Create monitor
monitor = PerformanceMonitor(enabled=True)
# Simulate Agent execution
import asyncio
async def simulate_agent(agent_name: str, duration: float, tokens: int):
"""Simulate Agent execution"""
metrics = monitor.start_tracking(agent_name)
# Simulate work
await asyncio.sleep(duration)
# Record tokens
metrics.add_tokens(prompt=tokens // 2, completion=tokens // 2)
metrics.add_api_call()
monitor.end_tracking(agent_name)
# Run simulation
async def run_simulation():
await simulate_agent("decompose_agent", 0.5, 100)
await simulate_agent("rag_agent", 1.0, 500)
await simulate_agent("plan_agent", 0.8, 300)
await simulate_agent("execute_agent", 1.5, 800)
asyncio.run(run_simulation())
# Print summary
monitor.print_summary()
# Save results
saved_path = monitor.save()
print(f"\nPerformance metrics saved to: {saved_path}")
+44 -16
View File
@@ -153,30 +153,58 @@ async def lifespan(app: FastAPI):
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
# Check if personalization should run externally
# Set PERSONALIZATION_EXTERNAL=true to run personalization in a separate process
# via: python scripts/start_personalization.py
import os
personalization_external = os.environ.get("PERSONALIZATION_EXTERNAL", "").lower() in ("true", "1", "yes")
if personalization_external:
# External mode: Enable file queue for cross-process communication
# Personalization service will be started separately via start_personalization.py
try:
from src.core.event_bus import enable_file_queue
enable_file_queue()
logger.info("Personalization running in external mode - file queue enabled")
logger.info("Start personalization service with: python scripts/start_personalization.py")
except Exception as e:
logger.warning(f"Failed to enable file queue for external personalization: {e}")
else:
# Internal mode: Start PersonalizationService in-process
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}")
personalization_service = get_personalization_service()
await personalization_service.start()
logger.info("PersonalizationService started (internal mode)")
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
# Stop PersonalizationService (only if running in internal mode)
if not personalization_external:
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}")
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}")
else:
# In external mode, just disable file queue
try:
from src.core.event_bus import disable_file_queue
disable_file_queue()
logger.info("File queue disabled")
except Exception as e:
logger.warning(f"Failed to disable file queue: {e}")
# Stop EventBus
try:
+139 -463
View File
@@ -1,524 +1,200 @@
import asyncio
from __future__ import annotations
import base64
from datetime import datetime
from pathlib import Path
import re
import sys
import traceback
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from src.agents.question import AgentCoordinator
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
# Add project root for imports
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))
from src.logging import get_logger
from src.services.config import load_config_with_main
from src.services.llm.config import get_llm_config
from src.services.path_service import get_path_service
from src.services.settings.interface_settings import get_ui_language
from src.utils.document_validator import DocumentValidator
from src.utils.error_utils import format_exception_message
router = APIRouter()
# Setup module logger with unified logging system (from config)
project_root = Path(__file__).parent.parent.parent.parent
config = load_config_with_main("question_config.yaml", project_root)
log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")
logger = get_logger("QuestionAPI", log_dir=log_dir)
router = APIRouter()
# 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"
path_service = get_path_service()
QUESTION_OUTPUT_DIR = path_service.get_question_dir()
MIMIC_OUTPUT_DIR = QUESTION_OUTPUT_DIR / "mimic_papers"
@router.websocket("/mimic")
async def websocket_mimic_generate(websocket: WebSocket):
"""
WebSocket endpoint for mimic exam paper question generation.
def _build_coordinator(kb_name: str) -> AgentCoordinator:
try:
llm_config = get_llm_config()
return AgentCoordinator(
api_key=llm_config.api_key,
base_url=llm_config.base_url,
api_version=getattr(llm_config, "api_version", None),
kb_name=kb_name,
output_dir=str(QUESTION_OUTPUT_DIR),
language=get_ui_language(default=config.get("system", {}).get("language", "en")),
)
except Exception:
return AgentCoordinator(
kb_name=kb_name,
output_dir=str(QUESTION_OUTPUT_DIR),
language=get_ui_language(default=config.get("system", {}).get("language", "en")),
)
Supports two modes:
1. Upload PDF directly via WebSocket (base64 encoded)
2. Use a pre-parsed paper directory path
Message format for PDF upload:
{
"mode": "upload",
"pdf_data": "base64_encoded_pdf_content",
"pdf_name": "exam.pdf",
"kb_name": "knowledge_base_name",
"max_questions": 5 // optional
}
Message format for pre-parsed:
{
"mode": "parsed",
"paper_path": "directory_name",
"kb_name": "knowledge_base_name",
"max_questions": 5 // optional
}
"""
@router.websocket("/generate")
async def websocket_question_generate(websocket: WebSocket) -> None:
await websocket.accept()
pusher_task = None
original_stdout = sys.stdout
task_manager = TaskIDManager.get_instance()
try:
# 1. Wait for config
data = await websocket.receive_json()
mode = data.get("mode", "parsed") # "upload" or "parsed"
requirement = data.get("requirement") or {}
kb_name = data.get("kb_name", "ai_textbook")
max_questions = data.get("max_questions")
count = int(data.get("count", 1))
logger.info(f"Starting mimic generation (mode: {mode}, kb: {kb_name})")
user_topic = str(requirement.get("knowledge_point", "")).strip()
preference = str(requirement.get("additional_requirements", "")).strip()
difficulty = str(requirement.get("difficulty", "")).strip()
question_type = str(requirement.get("question_type", "")).strip()
if not user_topic:
await websocket.send_json({"type": "error", "content": "knowledge_point is required"})
return
# 2. Setup Log Queue
log_queue = asyncio.Queue()
task_key = f"question_{kb_name}_{hash(str(requirement))}"
task_id = task_manager.generate_task_id("question_gen", task_key)
await websocket.send_json({"type": "task_id", "task_id": task_id})
async def log_pusher():
while True:
entry = await log_queue.get()
try:
await websocket.send_json(entry)
except Exception:
break
log_queue.task_done()
coordinator = _build_coordinator(kb_name)
pusher_task = asyncio.create_task(log_pusher())
async def ws_callback(data: dict) -> None:
await websocket.send_json(data)
# 3. Stdout interceptor for capturing prints
# ANSI escape sequence pattern for stripping color codes
ANSI_ESCAPE_PATTERN = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")
coordinator.set_ws_callback(ws_callback)
await websocket.send_json({"type": "status", "content": "started"})
class StdoutInterceptor:
def __init__(self, queue, original):
self.queue = queue
self.original_stdout = original
self._closed = False
def write(self, message):
if self._closed:
return
# Write to terminal first (with ANSI codes for color)
try:
self.original_stdout.write(message)
except Exception:
pass
# Strip ANSI escape codes before sending to frontend
clean_message = ANSI_ESCAPE_PATTERN.sub("", message).strip()
# Then send to frontend (non-blocking)
if clean_message:
try:
self.queue.put_nowait(
{
"type": "log",
"content": clean_message,
"timestamp": asyncio.get_event_loop().time(),
}
)
except (asyncio.QueueFull, RuntimeError):
pass
def flush(self):
if not self._closed:
try:
self.original_stdout.flush()
except Exception:
pass
def close(self):
"""Mark interceptor as closed to prevent further writes."""
self._closed = True
interceptor = StdoutInterceptor(log_queue, original_stdout)
sys.stdout = interceptor
try:
await websocket.send_json(
{"type": "status", "stage": "init", "content": "Initializing..."}
)
pdf_path = None
paper_dir = None
# Handle PDF upload mode
if mode == "upload":
pdf_data = data.get("pdf_data")
pdf_name = data.get("pdf_name", "exam.pdf")
if not pdf_data:
await websocket.send_json(
{"type": "error", "content": "PDF data is required for upload mode"}
)
return
# Decode PDF data first to check size
try:
pdf_bytes = base64.b64decode(pdf_data)
except Exception as e:
await websocket.send_json(
{"type": "error", "content": f"Invalid base64 PDF data: {e}"}
)
return
# Pre-validate filename and file size before writing
try:
safe_name = DocumentValidator.validate_upload_safety(
pdf_name, len(pdf_bytes), {".pdf"}
)
except ValueError as e:
await websocket.send_json({"type": "error", "content": str(e)})
return
# Create batch directory for this mimic session
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
pdf_stem = Path(safe_name).stem
batch_dir = MIMIC_OUTPUT_DIR / f"mimic_{timestamp}_{pdf_stem}"
batch_dir.mkdir(parents=True, exist_ok=True)
# Save uploaded PDF in batch directory
pdf_path = batch_dir / safe_name
await websocket.send_json(
{"type": "status", "stage": "upload", "content": f"Saving PDF: {safe_name}"}
)
# Write the validated PDF bytes
with open(pdf_path, "wb") as f:
f.write(pdf_bytes)
# Additional validation (file readability, etc.)
try:
DocumentValidator.validate_file(pdf_path)
except (ValueError, FileNotFoundError, PermissionError) as e:
# Clean up invalid or inaccessible file
pdf_path.unlink(missing_ok=True)
await websocket.send_json({"type": "error", "content": str(e)})
return
await websocket.send_json(
{
"type": "status",
"stage": "parsing",
"content": "Parsing PDF exam paper (MinerU)...",
}
)
logger.info(f"Saved and validated uploaded PDF to: {pdf_path}")
# Pass batch_dir as output directory
pdf_path = str(pdf_path)
output_dir = str(batch_dir)
elif mode == "parsed":
paper_path = data.get("paper_path")
if not paper_path:
await websocket.send_json(
{"type": "error", "content": "paper_path is required for parsed mode"}
)
return
paper_dir = paper_path
# Create batch directory for parsed mode too
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
batch_dir = MIMIC_OUTPUT_DIR / f"mimic_{timestamp}_{Path(paper_path).name}"
batch_dir.mkdir(parents=True, exist_ok=True)
output_dir = str(batch_dir)
else:
await websocket.send_json({"type": "error", "content": f"Unknown mode: {mode}"})
return
# Create WebSocket callback for real-time progress updates
async def ws_callback(event_type: str, data: dict):
"""Send progress updates to the frontend via WebSocket."""
try:
message = {"type": event_type, **data}
await websocket.send_json(message)
except Exception as e:
logger.debug(f"WebSocket send failed: {e}")
# Run the complete mimic workflow with callback
await websocket.send_json(
{
"type": "status",
"stage": "processing",
"content": "Executing question generation workflow...",
}
)
result = await mimic_exam_questions(
pdf_path=pdf_path,
paper_dir=paper_dir,
kb_name=kb_name,
output_dir=output_dir,
max_questions=max_questions,
ws_callback=ws_callback,
)
if result.get("success"):
# Results are already sent via ws_callback during generation
# Just send the final complete signal
total_ref = result.get("total_reference_questions", 0)
generated = result.get("generated_questions", [])
failed = result.get("failed_questions", [])
logger.success(
f"Mimic generation complete: {len(generated)} succeeded, {len(failed)} failed"
)
try:
await websocket.send_json({"type": "complete"})
except (RuntimeError, WebSocketDisconnect):
logger.debug("WebSocket closed before complete signal could be sent")
else:
error_msg = result.get("error", "Unknown error")
try:
await websocket.send_json({"type": "error", "content": error_msg})
except (RuntimeError, WebSocketDisconnect):
pass
logger.error(f"Mimic generation failed: {error_msg}")
finally:
# Close interceptor and restore stdout
if "interceptor" in locals():
interceptor.close()
sys.stdout = original_stdout
summary = await coordinator.generate_from_topic(
user_topic=user_topic,
preference=preference,
num_questions=count,
difficulty=difficulty,
question_type=question_type,
)
await websocket.send_json(
{
"type": "batch_summary",
"requested": summary.get("requested", count),
"completed": summary.get("completed", 0),
"failed": summary.get("failed", 0),
"templates": summary.get("templates", []),
}
)
await websocket.send_json({"type": "complete"})
task_manager.update_task_status(task_id, "completed")
except WebSocketDisconnect:
logger.debug("Client disconnected during mimic generation")
except Exception as e:
logger.exception("Mimic generation error")
error_msg = format_exception_message(e)
logger.debug("Client disconnected from /question/generate")
except Exception as exc:
logger.error(f"/question/generate failed: {exc}\n{traceback.format_exc()}")
error_msg = format_exception_message(exc)
try:
await websocket.send_json({"type": "error", "content": error_msg})
except Exception:
pass
finally:
# Ensure stdout is always restored
sys.stdout = original_stdout
# Clean up pusher task
if pusher_task:
try:
pusher_task.cancel()
await pusher_task
except asyncio.CancelledError:
pass # Expected when cancelling
except Exception:
pass
# Drain any remaining items in the queue
try:
while not log_queue.empty():
log_queue.get_nowait()
except Exception:
pass
# Close WebSocket
try:
await websocket.close()
except Exception:
pass
@router.websocket("/generate")
async def websocket_question_generate(websocket: WebSocket):
@router.websocket("/mimic")
async def websocket_mimic_generate(websocket: WebSocket) -> None:
await websocket.accept()
# Get task ID manager
task_manager = TaskIDManager.get_instance()
try:
# 1. Wait for config
data = await websocket.receive_json()
requirement = data.get("requirement")
mode = data.get("mode", "parsed") # upload | parsed
kb_name = data.get("kb_name", "ai_textbook")
count = data.get("count", 1)
max_questions = int(data.get("max_questions", 10))
if not requirement:
try:
await websocket.send_json({"type": "error", "content": "Requirement is required"})
except (RuntimeError, WebSocketDisconnect):
pass
return
coordinator = _build_coordinator(kb_name)
# Generate task ID
task_key = f"question_{kb_name}_{hash(str(requirement))}"
task_id = task_manager.generate_task_id("question_gen", task_key)
# Send task ID to frontend
try:
await websocket.send_json({"type": "task_id", "task_id": task_id})
except (RuntimeError, WebSocketDisconnect):
logger.debug("WebSocket closed, cannot send task_id")
return
logger.info(
f"[{task_id}] Starting question generation: {requirement.get('knowledge_point', 'Unknown')}"
)
# 2. Initialize Coordinator
path_service = get_path_service()
output_base = path_service.get_question_dir()
try:
llm_config = get_llm_config()
api_key = llm_config.api_key
base_url = llm_config.base_url
api_version = getattr(llm_config, "api_version", None)
except Exception:
api_key = None
base_url = None
api_version = None
coordinator = AgentCoordinator(
api_key=api_key,
base_url=base_url,
api_version=api_version,
kb_name=kb_name,
language=get_ui_language(default=config.get("system", {}).get("language", "en")),
max_rounds=10,
output_dir=str(output_base),
)
# 3. Setup Log Queue for WebSocket streaming
log_queue = asyncio.Queue()
# WebSocket callback for coordinator to send structured updates
async def ws_callback(data: dict):
try:
await log_queue.put(data)
except Exception:
pass
async def ws_callback(data: dict) -> None:
await websocket.send_json(data)
coordinator.set_ws_callback(ws_callback)
# 4. Define background pusher for logs
async def log_pusher():
while True:
entry = await log_queue.get()
try:
await websocket.send_json(entry)
except Exception:
break
log_queue.task_done()
paper_mode = "parsed"
exam_path = ""
pusher_task = asyncio.create_task(log_pusher())
# 5. Setup LogInterceptor for capturing logger output (same as solve.py)
# Get the coordinator's logger to intercept
target_logger = coordinator.logger.logger
interceptor = LogInterceptor(target_logger, log_queue)
# 6. Run Generation with LogInterceptor
try:
with interceptor:
try:
await websocket.send_json({"type": "status", "content": "started"})
except (RuntimeError, WebSocketDisconnect):
logger.debug("WebSocket closed, stopping question generation")
return
# Use custom mode generation (new streamlined flow)
logger.info(f"Starting custom mode generation for {count} question(s)")
# Use the new custom generation method
batch_result = await coordinator.generate_questions_custom(
requirement=requirement,
num_questions=count,
)
# Results are already sent via WebSocket callbacks in the coordinator
# Send final token stats
try:
await websocket.send_json(
{"type": "token_stats", "stats": coordinator.token_stats}
)
except (RuntimeError, WebSocketDisconnect):
logger.debug("WebSocket closed, stopping question generation")
# Send batch summary
try:
await websocket.send_json(
{
"type": "batch_summary",
"requested": batch_result.get("requested", count),
"completed": batch_result.get("completed", 0),
"failed": batch_result.get("failed", 0),
"plan": batch_result.get("plan", {}),
}
)
except (RuntimeError, WebSocketDisconnect):
pass
if not batch_result.get("success"):
logger.warning(
f"Question generation had failures: {batch_result.get('failed', 0)} failed"
)
# Wait for any pending messages in the queue to be sent
# Give the pusher a moment to process remaining messages
await asyncio.sleep(0.1)
while not log_queue.empty():
await asyncio.sleep(0.05)
# Send complete signal
try:
await websocket.send_json({"type": "complete"})
logger.info(f"[{task_id}] Question generation completed")
task_manager.update_task_status(task_id, "completed")
except (RuntimeError, WebSocketDisconnect):
logger.debug("WebSocket closed, cannot send complete signal")
except Exception as e:
error_msg = format_exception_message(e)
error_traceback = traceback.format_exc()
logger.error(f"Question generation error: {error_msg}")
logger.error(f"Error traceback:\n{error_traceback}")
# Log additional context if available
try:
if "result" in locals():
logger.error(
f"Result type: {type(result)}, result keys: {result.keys() if isinstance(result, dict) else 'N/A'}"
)
if isinstance(result, dict) and "validation" in result:
validation = result["validation"]
logger.error(f"Validation type: {type(validation)}")
if isinstance(validation, dict):
logger.error(f"Validation keys: {validation.keys()}")
logger.error(
f"Issues type: {type(validation.get('issues'))}, value: {validation.get('issues')}"
)
logger.error(
f"Suggestions type: {type(validation.get('suggestions'))}, value: {validation.get('suggestions')}"
)
except Exception as context_error:
logger.warning(f"Failed to log error context: {context_error}")
if mode == "upload":
pdf_data = data.get("pdf_data")
pdf_name = data.get("pdf_name", "exam.pdf")
if not pdf_data:
await websocket.send_json({"type": "error", "content": "pdf_data is required"})
return
try:
await websocket.send_json({"type": "error", "content": error_msg})
except (RuntimeError, WebSocketDisconnect):
logger.debug("WebSocket closed, cannot send error message")
task_manager.update_task_status(task_id, "error", error=error_msg)
pdf_bytes = base64.b64decode(pdf_data)
except Exception as exc:
await websocket.send_json({"type": "error", "content": f"Invalid PDF encoding: {exc}"})
return
finally:
pusher_task.cancel()
try:
await pusher_task
except asyncio.CancelledError:
pass
await websocket.close()
safe_name = DocumentValidator.validate_upload_safety(pdf_name, len(pdf_bytes), {".pdf"})
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
batch_dir = MIMIC_OUTPUT_DIR / f"mimic_{ts}_{Path(safe_name).stem}"
batch_dir.mkdir(parents=True, exist_ok=True)
pdf_path = batch_dir / safe_name
with open(pdf_path, "wb") as f:
f.write(pdf_bytes)
DocumentValidator.validate_file(pdf_path)
paper_mode = "upload"
exam_path = str(pdf_path)
elif mode == "parsed":
paper_path = str(data.get("paper_path", "")).strip()
if not paper_path:
await websocket.send_json({"type": "error", "content": "paper_path is required"})
return
paper_mode = "parsed"
exam_path = paper_path
else:
await websocket.send_json({"type": "error", "content": f"Unknown mode: {mode}"})
return
await websocket.send_json({"type": "status", "content": "started"})
summary = await coordinator.generate_from_exam(
exam_paper_path=exam_path,
max_questions=max_questions,
paper_mode=paper_mode,
)
await websocket.send_json(
{
"type": "batch_summary",
"requested": max_questions,
"completed": summary.get("completed", 0),
"failed": summary.get("failed", 0),
"templates": summary.get("templates", []),
}
)
await websocket.send_json({"type": "complete"})
except WebSocketDisconnect:
logger.debug("Client disconnected")
except Exception as e:
error_msg = format_exception_message(e)
logger.error(f"WebSocket error: {error_msg}")
logger.debug("Client disconnected from /question/mimic")
except Exception as exc:
logger.error(f"/question/mimic failed: {exc}\n{traceback.format_exc()}")
try:
await websocket.send_json({"type": "error", "content": format_exception_message(exc)})
except Exception:
pass
finally:
try:
await websocket.close()
except Exception:
pass
+3 -2
View File
@@ -148,8 +148,9 @@ async def websocket_solve(websocket: WebSocket):
# 1. Wait for the initial message with the question and config
data = await websocket.receive_json()
question = data.get("question")
kb_name = data.get("kb_name", "ai_textbook")
kb_name = data.get("kb_name", "ai-textbook")
session_id = data.get("session_id") # Optional session ID
detailed_answer = data.get("detailed_answer", False) # Iterative detailed mode
if not question:
await websocket.send_json({"type": "error", "content": "Question is required"})
@@ -298,7 +299,7 @@ async def websocket_solve(websocket: WebSocket):
logger.progress(f"[{task_id}] Solving started")
result = await solver.solve(question, verbose=True)
result = await solver.solve(question, verbose=True, detailed=detailed_answer)
logger.success(f"[{task_id}] Solving completed")
task_manager.update_task_status(task_id, "completed")
+1 -1
View File
@@ -18,7 +18,7 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
class LLMRetryConfig(BaseModel):
max_retries: int = Field(default=3, description="Maximum retry attempts for LLM calls")
base_delay: float = Field(default=1.0, description="Base delay between retries in seconds")
base_delay: float = Field(default=5.0, description="Base delay between retries in seconds")
exponential_backoff: bool = Field(
default=True, description="Whether to use exponential backoff"
)
+92
View File
@@ -5,6 +5,9 @@ Event Bus
Asynchronous event bus for inter-module communication.
Supports publish/subscribe pattern with non-blocking event delivery.
Also supports writing events to a file queue for cross-process communication
with external services like the standalone personalization service.
"""
import asyncio
@@ -17,6 +20,9 @@ from uuid import uuid4
logger = logging.getLogger(__name__)
# Global flag to enable/disable file queue for external personalization service
_file_queue_enabled: bool = False
class EventType(str, Enum):
"""Supported event types."""
@@ -151,12 +157,22 @@ class EventBus:
The event is queued for background processing, allowing the publisher
to continue immediately without waiting for handlers to complete.
If file queue is enabled (for external personalization service),
the event is also written to the file queue for cross-process delivery.
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})")
# Write to file queue if enabled (for external personalization service)
if _file_queue_enabled:
try:
_write_event_to_file_queue(event)
except Exception as e:
logger.warning(f"Failed to write event to file queue: {e}")
# Start processor if not running
if not self._running:
await self.start()
@@ -261,3 +277,79 @@ def get_event_bus() -> EventBus:
if _event_bus is None:
_event_bus = EventBus()
return _event_bus
# ============================================================================
# File Queue Integration for External Personalization Service
# ============================================================================
def enable_file_queue() -> None:
"""
Enable writing events to file queue for external personalization service.
Call this during application startup if you want to run the personalization
service in a separate process.
Usage:
from src.core.event_bus import enable_file_queue
enable_file_queue()
"""
global _file_queue_enabled
_file_queue_enabled = True
logger.info("File queue enabled for external personalization service")
def disable_file_queue() -> None:
"""
Disable writing events to file queue.
Use this when running personalization in-process (default behavior).
"""
global _file_queue_enabled
_file_queue_enabled = False
logger.debug("File queue disabled")
def is_file_queue_enabled() -> bool:
"""Check if file queue is enabled."""
return _file_queue_enabled
def _write_event_to_file_queue(event: Event) -> None:
"""
Write an event to the file queue for cross-process delivery.
This is called automatically when file queue is enabled and an event
is published. The event will be picked up by the standalone
personalization service.
Args:
event: The event to write
"""
try:
from src.personalization.event_queue import QueuedEvent, get_event_queue
# Convert Event to QueuedEvent
queued_event = QueuedEvent(
event_id=event.event_id,
event_type=event.type.value if isinstance(event.type, EventType) else event.type,
task_id=event.task_id,
user_input=event.user_input,
agent_output=event.agent_output,
tools_used=event.tools_used,
success=event.success,
metadata=event.metadata,
timestamp=event.timestamp.isoformat(),
)
# Push to file queue
queue = get_event_queue()
queue.push(queued_event)
logger.debug(f"Event written to file queue: {event.type.value} ({event.event_id})")
except ImportError:
logger.warning("personalization.event_queue not available, skipping file queue")
except Exception as e:
logger.error(f"Failed to write event to file queue: {e}")
+23 -5
View File
@@ -101,15 +101,33 @@ class DocumentAdder:
def _get_provider_from_metadata(self) -> str:
"""
Get the RAG provider from KB metadata.
Get the RAG provider for the KB.
This is the ONLY source of truth for incremental adds - we must use
the same provider that was used during initialization to ensure
data consistency and correct storage format.
Priority:
1. kb_config.json (authoritative source)
2. metadata.json (backward compatibility)
3. Detect from storage structure (fallback)
This ensures we use the same provider that was used during initialization
for data consistency and correct storage format.
Returns:
Provider name (llamaindex, lightrag, raganything, raganything_docling)
"""
# First, try kb_config.json (authoritative source)
kb_config_file = Path(self.base_dir) / "kb_config.json"
if kb_config_file.exists():
try:
with open(kb_config_file, "r", encoding="utf-8") as f:
config = json.load(f)
kb_config = config.get("knowledge_bases", {}).get(self.kb_name, {})
provider = kb_config.get("rag_provider")
if provider:
return provider
except Exception as e:
logger.warning(f"Failed to read provider from kb_config.json: {e}")
# Fallback: try metadata.json (backward compatibility)
if self.metadata_file.exists():
try:
with open(self.metadata_file, "r", encoding="utf-8") as f:
@@ -118,7 +136,7 @@ class DocumentAdder:
if provider:
return provider
except Exception as e:
logger.warning(f"Failed to read provider from metadata: {e}")
logger.warning(f"Failed to read provider from metadata.json: {e}")
# Fallback: detect from storage structure
llamaindex_storage = self.kb_dir / "llamaindex_storage"
+161 -64
View File
@@ -174,26 +174,100 @@ class KnowledgeBaseManager:
}
def list_knowledge_bases(self) -> list[str]:
"""List all available knowledge bases from kb_config.json"""
"""List all available knowledge bases.
This method:
1. Loads registered KBs from kb_config.json
2. Scans the directory for existing KBs not yet registered
3. Auto-registers any discovered KBs with valid structure (rag_storage or llamaindex_storage)
"""
# Always reload config from file to ensure we have the latest data
# This is important when new KBs are created by other processes/requests
self.config = self._load_config()
# Read knowledge base list from config file (this is the authoritative source)
# Return all KBs in config, regardless of directory status
# (status field indicates if KB is ready or still initializing)
# Read knowledge base list from config file
config_kbs = self.config.get("knowledge_bases", {})
kb_list = list(config_kbs.keys())
kb_list = set(config_kbs.keys())
# If no config file or config is empty, fallback to scanning directory (backward compatibility)
if not kb_list and self.base_dir.exists():
# Also scan directory for KBs that may not be registered yet
# This ensures backward compatibility and auto-discovery
if self.base_dir.exists():
config_changed = False
for item in self.base_dir.iterdir():
if item.is_dir() and item.name != "__pycache__":
metadata_file = item / "metadata.json"
if metadata_file.exists():
kb_list.append(item.name)
if not item.is_dir() or item.name.startswith(("__", ".")):
continue
# Skip if already in config
if item.name in kb_list:
continue
# Check if this is a valid KB directory (has rag_storage or llamaindex_storage)
rag_storage = item / "rag_storage"
llamaindex_storage = item / "llamaindex_storage"
is_valid_kb = (
(rag_storage.exists() and rag_storage.is_dir()) or
(llamaindex_storage.exists() and llamaindex_storage.is_dir())
)
if is_valid_kb:
# Auto-register this KB to kb_config.json
kb_list.add(item.name)
self._auto_register_kb(item.name)
config_changed = True
# Save config if we registered new KBs
if config_changed:
self._save_config()
return sorted(kb_list)
def _auto_register_kb(self, name: str):
"""Auto-register an existing KB to kb_config.json.
Reads info from metadata.json (if exists) for backward compatibility.
"""
kb_dir = self.base_dir / name
# Default values
kb_entry = {
"path": name,
"description": f"Knowledge base: {name}",
"status": "ready", # Existing KB with storage is considered ready
"updated_at": datetime.now().isoformat(),
}
# Try to read metadata.json for existing info (backward compatibility)
metadata_file = kb_dir / "metadata.json"
if metadata_file.exists():
try:
with open(metadata_file, encoding="utf-8") as f:
metadata = json.load(f)
# Migrate relevant fields
if metadata.get("description"):
kb_entry["description"] = metadata["description"]
if metadata.get("rag_provider"):
kb_entry["rag_provider"] = metadata["rag_provider"]
if metadata.get("created_at"):
kb_entry["created_at"] = metadata["created_at"]
if metadata.get("last_updated"):
kb_entry["updated_at"] = metadata["last_updated"]
except Exception as e:
print(f"[KnowledgeBaseManager] Warning: Failed to read metadata.json for '{name}': {e}")
# Detect rag_provider from storage type if not set
if "rag_provider" not in kb_entry:
rag_storage = kb_dir / "rag_storage"
llamaindex_storage = kb_dir / "llamaindex_storage"
if llamaindex_storage.exists():
kb_entry["rag_provider"] = "llamaindex"
elif rag_storage.exists():
kb_entry["rag_provider"] = "raganything"
# Add to config
if "knowledge_bases" not in self.config:
self.config["knowledge_bases"] = {}
self.config["knowledge_bases"][name] = kb_entry
print(f"[KnowledgeBaseManager] Auto-registered KB '{name}' to kb_config.json")
def register_knowledge_base(self, name: str, description: str = "", set_default: bool = False):
"""Register a knowledge base"""
@@ -289,13 +363,44 @@ class KnowledgeBaseManager:
return None
def get_metadata(self, name: str | None = None) -> dict:
"""Get knowledge base metadata"""
kb_dir = self.get_knowledge_base_path(name)
metadata_file = kb_dir / "metadata.json"
if metadata_file.exists():
with open(metadata_file, encoding="utf-8") as f:
return json.load(f)
"""Get knowledge base metadata.
Priority:
1. kb_config.json (authoritative source)
2. metadata.json (backward compatibility fallback)
"""
kb_name = name
if kb_name is None:
kb_name = self.get_default()
if kb_name is None:
return {}
# First, try kb_config.json (authoritative source)
self.config = self._load_config()
kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})
if kb_config:
# Build metadata from config
metadata = {
"name": kb_name,
"description": kb_config.get("description", f"Knowledge base: {kb_name}"),
"rag_provider": kb_config.get("rag_provider"),
"created_at": kb_config.get("created_at"),
"last_updated": kb_config.get("updated_at"),
}
# Remove None values
metadata = {k: v for k, v in metadata.items() if v is not None}
return metadata
# Fallback: try metadata.json (backward compatibility)
try:
kb_dir = self.get_knowledge_base_path(name)
metadata_file = kb_dir / "metadata.json"
if metadata_file.exists():
with open(metadata_file, encoding="utf-8") as f:
return json.load(f)
except ValueError:
pass
return {}
@@ -304,8 +409,8 @@ class KnowledgeBaseManager:
This method:
1. Gets the KB name (from parameter or default)
2. Reads status and progress from kb_config.json
3. Reads metadata.json from the KB directory (if exists)
2. Reads all config from kb_config.json (authoritative source)
3. Falls back to metadata.json for legacy KBs
4. Collects statistics about files and RAG status
"""
# Reload config to get latest status
@@ -318,10 +423,14 @@ class KnowledgeBaseManager:
# Get knowledge base path
kb_dir = self.base_dir / kb_name
# Get status and progress from kb_config.json
# Get config from kb_config.json (authoritative source)
kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})
status = kb_config.get("status")
progress = kb_config.get("progress")
description = kb_config.get("description", f"Knowledge base: {kb_name}")
rag_provider = kb_config.get("rag_provider")
created_at = kb_config.get("created_at")
updated_at = kb_config.get("updated_at")
# KB might not have a directory yet if still initializing
dir_exists = kb_dir.exists()
@@ -329,38 +438,44 @@ class KnowledgeBaseManager:
# For old KBs without status field, determine status from rag_storage
if not status and dir_exists:
rag_storage_dir = kb_dir / "rag_storage"
if rag_storage_dir.exists() and any(rag_storage_dir.iterdir()):
llamaindex_storage_dir = kb_dir / "llamaindex_storage"
if (rag_storage_dir.exists() and any(rag_storage_dir.iterdir())) or \
(llamaindex_storage_dir.exists() and any(llamaindex_storage_dir.iterdir())):
status = "ready"
else:
status = "unknown"
elif not status:
status = "unknown"
# Build metadata from kb_config.json (authoritative source)
metadata = {
"name": kb_name,
"description": description,
"rag_provider": rag_provider,
}
if created_at:
metadata["created_at"] = created_at
if updated_at:
metadata["last_updated"] = updated_at
# Remove None values
metadata = {k: v for k, v in metadata.items() if v is not None}
info = {
"name": kb_name,
"path": str(kb_dir),
"is_default": kb_name == self.get_default(),
"metadata": {},
"metadata": metadata,
"status": status,
"progress": progress,
}
# Read metadata.json (if exists)
if dir_exists:
metadata_file = kb_dir / "metadata.json"
if metadata_file.exists():
try:
with open(metadata_file, encoding="utf-8") as f:
info["metadata"] = json.load(f)
except Exception as e:
print(f"Warning: Failed to read metadata.json for KB '{kb_name}': {e}")
info["metadata"] = {}
# Count files - handle errors gracefully
raw_dir = kb_dir / "raw" if dir_exists else None
images_dir = kb_dir / "images" if dir_exists else None
content_list_dir = kb_dir / "content_list" if dir_exists else None
rag_storage_dir = kb_dir / "rag_storage" if dir_exists else None
llamaindex_storage_dir = kb_dir / "llamaindex_storage" if dir_exists else None
raw_count = 0
images_count = 0
@@ -390,14 +505,10 @@ class KnowledgeBaseManager:
except Exception:
pass
metadata = info["metadata"]
rag_provider = metadata.get("rag_provider") if isinstance(metadata, dict) else None
# Also check kb_config for rag_provider (fallback)
if not rag_provider:
rag_provider = kb_config.get("rag_provider")
# Check rag_initialized for both storage types
rag_initialized = (
dir_exists and rag_storage_dir and rag_storage_dir.exists() and rag_storage_dir.is_dir()
(dir_exists and rag_storage_dir and rag_storage_dir.exists() and rag_storage_dir.is_dir()) or
(dir_exists and llamaindex_storage_dir and llamaindex_storage_dir.exists() and llamaindex_storage_dir.is_dir())
)
info["statistics"] = {
@@ -559,17 +670,10 @@ class KnowledgeBaseManager:
if not folder.is_dir():
raise ValueError(f"Path is not a directory: {folder}")
# Get RAG provider from KB metadata to determine supported extensions
kb_dir = self.base_dir / kb_name
metadata_file = kb_dir / "metadata.json"
provider = "raganything" # default to most comprehensive
if metadata_file.exists():
try:
with open(metadata_file, encoding="utf-8") as f:
kb_meta = json.load(f)
provider = kb_meta.get("rag_provider") or "raganything"
except Exception:
pass
# Get RAG provider from kb_config.json to determine supported extensions
self.config = self._load_config()
kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})
provider = kb_config.get("rag_provider") or "raganything"
# Get supported files in folder based on provider
supported_extensions = FileTypeRouter.get_extensions_for_provider(provider)
@@ -748,17 +852,10 @@ class KnowledgeBaseManager:
except Exception:
pass
# Get RAG provider from KB metadata to determine supported extensions
kb_dir = self.base_dir / kb_name
metadata_file = kb_dir / "metadata.json"
provider = "raganything" # default to most comprehensive
if metadata_file.exists():
try:
with open(metadata_file, encoding="utf-8") as f:
metadata = json.load(f)
provider = metadata.get("rag_provider") or "raganything"
except Exception:
pass
# Get RAG provider from kb_config.json to determine supported extensions
self.config = self._load_config()
kb_config = self.config.get("knowledge_bases", {}).get(kb_name, {})
provider = kb_config.get("rag_provider") or "raganything"
# Scan current files based on provider's supported extensions
supported_extensions = FileTypeRouter.get_extensions_for_provider(provider)
+15
View File
@@ -10,17 +10,32 @@ 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
- EventFileQueue: File-based event queue for cross-process communication
Running Modes:
1. In-process mode (default): Service runs within the main application
2. External mode: Service runs as a separate process via start_personalization.py
- Enable file queue with: from src.core.event_bus import enable_file_queue
- Run: python scripts/start_personalization.py
"""
from .event_queue import EventFileQueue, QueuedEvent, get_event_queue
from .memory import LearningMemory, get_learning_memory
from .memory_agent import MemoryAgent, MemoryDecision
from .service import PersonalizationService, get_personalization_service
__all__ = [
# Memory
"LearningMemory",
"get_learning_memory",
# Agent
"MemoryAgent",
"MemoryDecision",
# Service
"PersonalizationService",
"get_personalization_service",
# Event Queue (for external mode)
"EventFileQueue",
"QueuedEvent",
"get_event_queue",
]
+334
View File
@@ -0,0 +1,334 @@
# -*- coding: utf-8 -*-
"""
Event Queue for Inter-Process Communication
============================================
File-based event queue that enables the main application to pass events
to the personalization service running in a separate process.
The queue uses a simple JSON Lines format where each line is a complete
event. Events are appended atomically and consumed in order.
"""
import fcntl
import json
import logging
import os
import time
from dataclasses import asdict, dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional
from src.services.path_service import get_path_service
logger = logging.getLogger(__name__)
@dataclass
class QueuedEvent:
"""
Event stored in the file queue.
This is a simplified event format for cross-process communication.
"""
event_id: str
event_type: str
task_id: str
user_input: str
agent_output: str
tools_used: List[str]
success: bool
metadata: Dict[str, Any]
timestamp: str # ISO format string
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "QueuedEvent":
"""Create from dictionary."""
return cls(
event_id=data["event_id"],
event_type=data["event_type"],
task_id=data["task_id"],
user_input=data["user_input"],
agent_output=data["agent_output"],
tools_used=data.get("tools_used", []),
success=data.get("success", True),
metadata=data.get("metadata", {}),
timestamp=data["timestamp"],
)
class EventFileQueue:
"""
File-based event queue for inter-process communication.
Features:
- Atomic append operations with file locking
- FIFO ordering with offset tracking
- Automatic cleanup of processed events
Usage:
# Producer (main application)
queue = EventFileQueue()
queue.push(event)
# Consumer (personalization service)
queue = EventFileQueue()
for event in queue.consume():
process(event)
"""
_instance: Optional["EventFileQueue"] = None
def __new__(cls) -> "EventFileQueue":
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._initialized = False
return cls._instance
def __init__(self) -> None:
if self._initialized:
return
path_service = get_path_service()
self._queue_dir = path_service.get_memory_dir() / "event_queue"
self._queue_file = self._queue_dir / "events.jsonl"
self._offset_file = self._queue_dir / "offset.txt"
self._lock_file = self._queue_dir / ".lock"
# Ensure directory exists
self._queue_dir.mkdir(parents=True, exist_ok=True)
self._initialized = True
logger.debug(f"EventFileQueue initialized at {self._queue_dir}")
def push(self, event: QueuedEvent) -> None:
"""
Push an event to the queue.
Thread-safe and process-safe with file locking.
Args:
event: The event to enqueue
"""
try:
with open(self._lock_file, "w") as lock_f:
# Acquire exclusive lock
fcntl.flock(lock_f.fileno(), fcntl.LOCK_EX)
try:
# Append event as JSON line
with open(self._queue_file, "a", encoding="utf-8") as f:
line = json.dumps(event.to_dict(), ensure_ascii=False)
f.write(line + "\n")
f.flush()
os.fsync(f.fileno())
logger.debug(f"Event pushed to queue: {event.event_type} ({event.event_id})")
finally:
# Release lock
fcntl.flock(lock_f.fileno(), fcntl.LOCK_UN)
except Exception as e:
logger.error(f"Failed to push event to queue: {e}")
raise
def _get_offset(self) -> int:
"""Get the current read offset."""
if not self._offset_file.exists():
return 0
try:
return int(self._offset_file.read_text().strip())
except (ValueError, IOError):
return 0
def _set_offset(self, offset: int) -> None:
"""Set the current read offset."""
self._offset_file.write_text(str(offset))
def consume(self, batch_size: int = 10) -> Iterator[QueuedEvent]:
"""
Consume events from the queue.
Yields events starting from the current offset and updates
the offset as events are consumed.
Args:
batch_size: Maximum number of events to consume at once
Yields:
QueuedEvent instances
"""
if not self._queue_file.exists():
return
try:
with open(self._lock_file, "w") as lock_f:
# Acquire shared lock for reading
fcntl.flock(lock_f.fileno(), fcntl.LOCK_SH)
try:
offset = self._get_offset()
count = 0
with open(self._queue_file, "r", encoding="utf-8") as f:
# Seek to current offset
f.seek(offset)
# Use readline() instead of for-loop iteration
# because for-loop disables f.tell()
while count < batch_size:
line = f.readline()
if not line:
# End of file
break
line = line.strip()
if not line:
continue
try:
data = json.loads(line)
event = QueuedEvent.from_dict(data)
count += 1
# Update offset before yielding
# (in case consumer crashes mid-processing)
new_offset = f.tell()
yield event
# Only update offset after successful processing
self._set_offset(new_offset)
except json.JSONDecodeError as e:
logger.warning(f"Invalid JSON in queue file: {e}")
continue
except Exception as e:
logger.error(f"Error processing queued event: {e}")
continue
finally:
fcntl.flock(lock_f.fileno(), fcntl.LOCK_UN)
except Exception as e:
logger.error(f"Failed to consume events from queue: {e}")
def peek(self) -> Optional[QueuedEvent]:
"""
Peek at the next event without consuming it.
Returns:
The next event, or None if queue is empty
"""
if not self._queue_file.exists():
return None
try:
offset = self._get_offset()
with open(self._queue_file, "r", encoding="utf-8") as f:
f.seek(offset)
line = f.readline().strip()
if not line:
return None
data = json.loads(line)
return QueuedEvent.from_dict(data)
except Exception as e:
logger.error(f"Failed to peek event: {e}")
return None
def pending_count(self) -> int:
"""
Get the approximate number of pending events.
Returns:
Number of unprocessed events (approximate)
"""
if not self._queue_file.exists():
return 0
try:
offset = self._get_offset()
count = 0
with open(self._queue_file, "r", encoding="utf-8") as f:
f.seek(offset)
for line in f:
if line.strip():
count += 1
return count
except Exception as e:
logger.error(f"Failed to count pending events: {e}")
return 0
def cleanup(self, max_age_days: int = 7) -> None:
"""
Clean up old events from the queue file.
This compacts the queue by removing already-processed events.
Args:
max_age_days: Remove events older than this many days
"""
if not self._queue_file.exists():
return
try:
with open(self._lock_file, "w") as lock_f:
fcntl.flock(lock_f.fileno(), fcntl.LOCK_EX)
try:
offset = self._get_offset()
# Read remaining events
remaining = []
with open(self._queue_file, "r", encoding="utf-8") as f:
f.seek(offset)
remaining = f.readlines()
# Rewrite file with only remaining events
with open(self._queue_file, "w", encoding="utf-8") as f:
f.writelines(remaining)
# Reset offset
self._set_offset(0)
logger.info(f"Queue cleaned up, {len(remaining)} events remaining")
finally:
fcntl.flock(lock_f.fileno(), fcntl.LOCK_UN)
except Exception as e:
logger.error(f"Failed to cleanup queue: {e}")
def clear(self) -> None:
"""Clear all events from the queue."""
try:
if self._queue_file.exists():
self._queue_file.unlink()
self._set_offset(0)
logger.info("Queue cleared")
except Exception as e:
logger.error(f"Failed to clear queue: {e}")
@classmethod
def reset(cls) -> None:
"""Reset the singleton instance (for testing)."""
cls._instance = None
# Module-level singleton accessor
_event_queue: Optional[EventFileQueue] = None
def get_event_queue() -> EventFileQueue:
"""
Get the singleton EventFileQueue instance.
Returns:
The global EventFileQueue instance.
"""
global _event_queue
if _event_queue is None:
_event_queue = EventFileQueue()
return _event_queue
+4 -6
View File
@@ -155,12 +155,10 @@ __all__ = [
def __getattr__(name: str):
"""Lazy import for provider modules that depend on heavy libraries."""
from importlib import import_module
if name == "cloud_provider":
from . import cloud_provider
return cloud_provider
return import_module("src.services.llm.cloud_provider")
if name == "local_provider":
from . import local_provider
return local_provider
return import_module("src.services.llm.local_provider")
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+9 -2
View File
@@ -26,7 +26,10 @@ class PromptManager:
}
# Supported modules
MODULES = ["research", "solve", "guide", "question", "ideagen", "co_writer"]
MODULES = ["research", "solve", "guide", "question", "ideagen", "co_writer", "personalization"]
# Modules that are not under src/agents/ directory
NON_AGENT_MODULES = {"personalization": "personalization"}
def __new__(cls) -> "PromptManager":
if cls._instance is None:
@@ -81,7 +84,11 @@ class PromptManager:
subdirectory: str | None,
) -> dict[str, Any]:
"""Load prompt file with language fallback."""
prompts_dir = PROJECT_ROOT / "src" / "agents" / module_name / "prompts"
# Handle modules that are not under src/agents/
if module_name in self.NON_AGENT_MODULES:
prompts_dir = PROJECT_ROOT / "src" / module_name / "prompts"
else:
prompts_dir = PROJECT_ROOT / "src" / "agents" / module_name / "prompts"
fallback_chain = self.LANGUAGE_FALLBACKS.get(lang_code, ["en"])
for lang in fallback_chain:

Some files were not shown because too many files have changed in this diff Show More