DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
work/llm-error-framework (#35)
Scarlet Moorecddc5160e8bd
diff --git a/.env.example b/.env.exampleindex 0c37f6230..ea835b1c4 100644--- a/.env.example+++ b/.env.example@@ -64,6 +64,8 @@ LLM_MODEL=# - OpenAI: https://api.openai.com/v1# - Azure OpenAI: https://{your-resource}.openai.azure.com/openai/deployments/{deployment-id}# (Note: For Azure, you must include the full deployment path, not just the base URL)+# - DeepSeek: https://api.deepseek.com+# - Anthropic: https://api.anthropic.com# Local examples:# - Ollama: http://localhost:11434/v1# - LM Studio: http://localhost:1234/v1@@ -159,7 +161,7 @@ SEARCH_PROVIDER=perplexity# ----------------------------------------------------------------------------# Perplexity AI Search Configuration# -----------------------------------------------------------------------------# Perplexity API key for AI-powered search+# Perplexity API key for web search functionality# Get your API key at: https://www.perplexity.ai/settings/apiPERPLEXITY_API_KEY=diff --git a/.env.example_CN b/.env.example_CNindex 6a67f93a8..e70fda6eb 100644--- a/.env.example_CN+++ b/.env.example_CN@@ -1,4 +1,4 @@-# ============================================================================+# ============================================================================# Deep-Tutor 环境配置文件# ============================================================================# 将此文件复制为 .env 并填写您的 API 密钥和设置。diff --git a/.gitignore b/.gitignoreindex 209774732..4b737348e 100644--- a/.gitignore+++ b/.gitignore@@ -70,6 +70,9 @@ web/dist/build/web/build/+# TypeScript build info+*.tsbuildinfo+# ============================================# Common Output and Cache Directories# ============================================diff --git a/DYNAMIC_RAG_PROVIDER.md b/DYNAMIC_RAG_PROVIDER.mddeleted file mode 100644index 9bf21efe8..000000000--- a/DYNAMIC_RAG_PROVIDER.md+++ /dev/null@@ -1,135 +0,0 @@-# Dynamic RAG Provider Selection--## Overview--The knowledge base initialization has been refactored to support dynamic RAG provider selection based on the `RAG_PROVIDER` environment variable.--## Changes Made--### 1. Updated `src/knowledge/initializer.py`--**Previous Behavior:**-- Hardcoded to use `RAGAnything` directly-- Imported `raganything`, `RAGAnythingConfig`, `LightRAGLogContext`, `EmbeddingFunc`-- Manually configured LLM, vision, and embedding functions-- Directly instantiated `RAGAnything` class--**New Behavior:**-- Uses `RAGService` which respects `RAG_PROVIDER` environment variable-- Simplified imports - only imports `RAGService`-- Provider selection is automatic based on environment configuration-- Supports all registered RAG pipelines: `raganything`, `lightrag`, `llamaindex`, `academic`--### 2. Key Code Changes--#### Imports (Lines 26-33)-```python-# Before: Direct RAGAnything imports-from raganything import RAGAnything, RAGAnythingConfig-from lightrag.utils import EmbeddingFunc--# After: RAGService import-from src.services.rag.service import RAGService-```--#### Process Documents Method (Lines 151-235)-```python-# Before: 200+ lines of RAGAnything configuration-config = RAGAnythingConfig(...)-rag = RAGAnything(config=config, llm_model_func=..., ...)-for doc in docs:- await rag.process_document_complete(...)--# After: Simple RAGService usage-provider = os.getenv("RAG_PROVIDER", "raganything")-rag_service = RAGService(kb_base_dir=str(self.base_dir), provider=provider)-success = await rag_service.initialize(- kb_name=self.kb_name,- file_paths=file_paths,- extract_numbered_items=True-)-```--#### Statistics Display (Lines 405-465)-```python-# Added generic statistics method that works with all providers-async def display_statistics_generic(self):- # Shows stats for RAGAnything/LightRAG (entities, relations, chunks)- # Shows stats for LlamaIndex (vector embeddings, dimensions)- # Displays which provider was used-```--## How It Works--1. **Environment Variable**: Set `RAG_PROVIDER` in `.env` file:- ```bash- RAG_PROVIDER=llamaindex # or raganything, lightrag, academic- ```--2. **Automatic Provider Selection**: `RAGService` reads the environment variable and selects the appropriate pipeline from the factory--3. **Pipeline Execution**: The selected pipeline processes documents according to its implementation:- - **raganything**: Uses RAG-Anything with MinerU parser, creates graph storage- - **lightrag**: Uses LightRAG, creates graph-based knowledge base- - **llamaindex**: Uses LlamaIndex with VectorIndexer and DenseRetriever, creates vector store- - **academic**: Stub implementation (needs implementation)--4. **Storage Format**: Each provider creates its own storage format:- - **raganything/lightrag**: `rag_storage/` with JSON files (entities, relations, chunks)- - **llamaindex**: `vector_store/` with FAISS index and embeddings- - **Note**: Storage formats are incompatible between providers--## Testing--To test different providers:--1. Set environment variable:- ```bash- # In .env file- RAG_PROVIDER=llamaindex- ```--2. Create a new knowledge base:- ```bash- # Via API or web interface- # Upload documents to create new KB- ```--3. Check logs to verify correct provider:- ```- [KnowledgeInit] Processing documents with RAG provider: llamaindex- [RAGService] Initializing KB 'test_kb' with provider 'llamaindex'- ```--4. Verify storage structure:- ```bash- # For LlamaIndex- ls data/knowledge_bases/test_kb/vector_store/- # Should see: index.faiss, embeddings.pkl, metadata.json, info.json-- # For RAGAnything/LightRAG- ls data/knowledge_bases/test_kb/rag_storage/- # Should see: kv_store_*.json files- ```--## Benefits--1. **Flexibility**: Switch RAG providers without code changes-2. **Maintainability**: Single point of configuration in environment variables-3. **Extensibility**: Easy to add new RAG providers via factory pattern-4. **Consistency**: All pipelines use the same interface-5. **Testing**: Easy to test different providers for comparison--## Migration Notes--- **Existing KBs**: Continue to work with their original provider-- **New KBs**: Use provider specified in `RAG_PROVIDER` at creation time-- **Provider Changes**: Cannot change provider for existing KB without rebuilding-- **Storage Incompatibility**: Different providers cannot share the same KB storage--## Future Improvements--1. Store provider information in KB metadata to track which provider was used-2. Implement provider migration tool to convert between storage formats-3. Add DocumentAdder support for dynamic provider selection-4. Create unified storage format that all providers can usediff --git a/README.md b/README.mdindex a26f178e0..94f4ef1d3 100644--- a/README.md+++ b/README.md@@ -1,35 +1,1449 @@-# branch structure and status overview+### 📰 News-this document outlines the current state and purpose of the active branches in the repository. documentation is provided to facilitate rebasing strategies and merge order.+> **[2026.1.1]** Join our [Discord Community](https://discord.gg/zpP9cssj) and [GitHub Discussions](https://github.com/HKUDS/DeepTutor/discussions) - shape the future of DeepTutor! 💬-## core branches+> **[2025.12.30]** Visit our [Official Website](https://hkuds.github.io/DeepTutor/) for more details!-### dev-primary development branch. serves as the baseline for all feature and work branches. contains the most recent merged code for the agent architectures, api routers, and web interface.+> **[2025.12.29]** DeepTutor is now live! ✨-### shk-dev-synchronization branch for upstream/dev. used as a staging area to pull latest changes from the upstream repository and resolve merge conflicts before propagating updates to specific feature branches.+### 📦 Releases-## architectural and feature branches+> **[2026.1.9]** Release [v0.4.1](https://github.com/HKUDS/DeepTutor/releases/tag/v0.4.1) with LLM Provider system overhaul, Question Generation robustness improvements, and codebase cleanup - Thanks to all the contributors!+<details>+<summary>History releases</summary>-### feature/config-governance-implements centralized configuration governance. introduces `config_manager.py` to enforce schema validation and provide a unified interface for system settings. this branch is currently required as a dependency for advanced error handling logic to manage retry counts and timeouts globally.+> **[2026.1.9]** Release [v0.4.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.4.0) with new code structure, multiple llm & embeddings support - Thanks to all the contributors!-### work/llm-error-framework-introduces a provider-registry architecture, unified error mapping, and telemetry. replaces direct exception pass-through in the service layer with standardized exceptions.-* **status:** high priority integration.-* **dependency:** requires rebasing onto `dev` to resolve conflicts in `factory.py` and sync with `config_manager.py`.+> **[2026.1.5]** [v0.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.3.0) - Unified PromptManager architecture, CI/CD automation & pre-built Docker images on GHCR-### ui/provider-autofill-model-dropdown-targets the `web/` directory components. enables dynamic population of model selection inputs based on the currently active llm provider configuration. reduces hardcoded values in the frontend interface.+> **[2026.1.2]** [v0.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.2.0) - Docker deployment, Next.js 16 & React 19 upgrade, WebSocket security & critical vulnerability fixes-## optimization and maintenance branches+</details>-### work/ingestion-oom-hardening-focuses on the `src/knowledge` module. implements improvements to memory management during document parsing and vector store ingestion. designed to prevent out-of-memory process termination when processing large pdfs or extensive datasets.+----### work/focused-error-handling-addresses specific, localized exception scenarios within agent loops. distinct from the systemic changes in the `llm-error-framework`, this branch provides immediate patches for common runtime failures in the solve and research agents.+## Key Features of DeepTutor-### build/cloud-contains infrastructure configurations required for cloud deployment environments. includes adjustments to `dockerfile` and container orchestration scripts to support remote execution contexts different from local development.+### 📚 Massive Document Knowledge Q&A+• **Smart Knowledge Base**: Upload textbooks, research papers, technical manuals, and domain-specific documents. Build a comprehensive AI-powered knowledge repository for instant access.<br>+• **Multi-Agent Problem Solving**: Dual-loop reasoning architecture with RAG, web search, and code execution -- delivering step-by-step solutions with precise citations.++### 🎨 Interactive Learning Visualization+• **Knowledge Simplification & Explanations**: Transform complex concepts, knowledge, and algorithms into easy-to-understand visual aids, detailed step-by-step breakdowns, and engaging interactive demonstrations.<br>+• **Personalized Q&A**: Context-aware conversations that adapt to your learning progress, with interactive pages and session-based knowledge tracking.++### 🎯 Knowledge Reinforcement with Practice Exercise Generator+• **Intelligent Exercise Creation**: Generate targeted quizzes, practice problems, and customized assessments tailored to your current knowledge level and specific learning objectives.<br>+• **Authentic Exam Simulation**: Upload reference exams to generate practice questions that perfectly match the original style, format, and difficulty—giving you realistic preparation for the actual test.++### 🔍 Deep Research & Idea Generation+• **Comprehensive Research & Literature Review**: Conduct in-depth topic exploration with systematic analysis. Identify patterns, connect related concepts across disciplines, and synthesize existing research findings.<br>+• **Novel Insight Discovery**: Generate structured learning materials and uncover knowledge gaps. Identify promising new research directions through intelligent cross-domain knowledge synthesis.++---++<div align="center">+ <img src="assets/figs/title_gradient.svg" alt="All-in-One Tutoring System" width="70%">+</div>++<!-- ━━━━━━━━━━━━━━━━ Core Learning Experience ━━━━━━━━━━━━━━━━ -->++<table>+<tr>+<td width="50%" align="center" valign="top">++<h3>📚 Massive Document Knowledge Q&A</h3>+<a href="#problem-solving-agent">+<img src="assets/gifs/solve.gif" width="100%">+</a>+<br>+<sub>Multi-agent Problem Solving with Exact Citations</sub>++</td>+<td width="50%" align="center" valign="top">++<h3>🎨 Interactive Learning Visualization</h3>+<a href="#guided-learning">+<img src="assets/gifs/guided-learning.gif" width="100%">+</a>+<br>+<sub>Step-by-step Visual Explanations with Personal QAs.</sub>++</td>+</tr>+</table>++<!-- ━━━━━━━━━━━━━━━━ Practice & Reinforcement ━━━━━━━━━━━━━━━━ -->++<h3 align="center">🎯 Knowledge Reinforcement</h3>++<table>+<tr>+<td width="50%" valign="top" align="center">++<a href="#question-generator">+<img src="assets/gifs/question-1.gif" width="100%">+</a>++**Custom Questions**+<sub>Auto-Validated Practice Questions Generation</sub>++</td>+<td width="50%" valign="top" align="center">++<a href="#question-generator">+<img src="assets/gifs/question-2.gif" width="100%">+</a>++**Mimic Questions**+<sub>Clone Exam Style for Authentic Practice</sub>++</td>+</tr>+</table>++<!-- ━━━━━━━━━━━━━━━━ Research & Creation ━━━━━━━━━━━━━━━━ -->++<h3 align="center">🔍 Deep Research & Idea Generation</h3>++<table>+<tr>+<td width="33%" align="center">++<a href="#deep-research">+<img src="assets/gifs/deepresearch.gif" width="100%">+</a>++**Deep Research**+<sub>Knowledge Extension from Textbook with RAG, Web and Paper-search</sub>++</td>+<td width="33%" align="center">++<a href="#idea-generation">+<img src="assets/gifs/ideagen.gif" width="100%">+</a>++**Automated IdeaGen**+<sub>Brainstorming and Concept Synthesis with Dual-filter Workflow</sub>++</td>+<td width="33%" align="center">++<a href="#co-writer">+<img src="assets/gifs/co-writer.gif" width="100%">+</a>++**Interactive IdeaGen**+<sub>RAG and Web-search Powered Co-writer with Podcast Generation</sub>++</td>+</tr>+</table>++<!-- ━━━━━━━━━━━━━━━━ Knowledge Infrastructure ━━━━━━━━━━━━━━━━ -->++<h3 align="center">🏗️ All-in-One Knowledge System</h3>++<table>+<tr>+<td width="50%" align="center">++<a href="#dashboard--knowledge-base-management">+<img src="assets/gifs/knowledge_bases.png" width="100%">+</a>++**Personal Knowledge Base**+<sub>Build and Organize Your Own Knowledge Repository</sub>++</td>+<td width="50%" align="center">++<a href="#notebook">+<img src="assets/gifs/notebooks.png" width="100%">+</a>++**Personal Notebook**+<sub>Your Contextual Memory for Learning Sessions</sub>++</td>+</tr>+</table>++<p align="center">+ <sub>🌙 Use DeepTutor in <b>Dark Mode</b>!</sub>+</p>++---++## 🏛️ DeepTutor's Framework++<div align="center">+<img src="assets/figs/full-pipe.png" alt="DeepTutor Full-Stack Workflow" width="100%">+</div>++### 💬 User Interface Layer+• **Intuitive Interaction**: Simple bidirectional query-response flow for intuitive interaction.<br>+• **Structured Output**: Structured response generation that organizes complex information into actionable outputs.++### 🤖 Intelligent Agent Modules+• **Problem Solving & Assessment**: Step-by-step problem solving and custom assessment generation.<br>+• **Research & Learning**: Deep Research for topic exploration and Guided Learning with visualization.<br>+• **Idea Generation**: Automated and interactive concept development with multi-source insights.++### 🔧 Tool Integration Layer+• **Information Retrieval**: RAG hybrid retrieval, real-time web search, and academic paper databases.<br>+• **Processing & Analysis**: Python code execution, query item lookup, and PDF parsing for document analysis.++### 🧠 Knowledge & Memory Foundation+• **Knowledge Graph**: Entity-relation mapping for semantic connections and knowledge discovery.<br>+• **Vector Store**: Embedding-based semantic search for intelligent content retrieval.<br>+• **Memory System**: Session state management and citation tracking for contextual continuity.++## 📋 Todo+> 🌟 Star to follow our future updates!+- [ x ] Support More RAG Pipelines+- [ x ] DataBase Robostness and Visualization+- [ ] Personalized Interaction with Notebook++## 🚀 Getting Started++### Step 1: Pre-Configuration++**① Clone Repository**++```bash+git clone https://github.com/HKUDS/DeepTutor.git+cd DeepTutor+```++**② Set Up Environment Variables**++```bash+cp .env.example .env+# Edit .env file with your API keys+```++<details>+<summary>📋 <b>Environment Variables Reference</b></summary>++| Variable | Required | Description |+|:---|:---:|:---|+| `LLM_MODEL` | **Yes** | Model name (e.g., `gpt-4o`) |+| `LLM_API_VERSION` | No | API version for Azure OpenAI (e.g., `2024-02-15-preview`) |+| `LLM_API_KEY` | **Yes** | Your LLM API key |+| `LLM_HOST` | **Yes** | API endpoint URL |+| `EMBEDDING_MODEL` | **Yes** | Embedding model name |+| `EMBEDDING_API_VERSION` | No | API version for Azure OpenAI Embeddings |+| `EMBEDDING_API_KEY` | **Yes** | Embedding API key |+| `EMBEDDING_HOST` | **Yes** | Embedding API endpoint |+| `BACKEND_PORT` | No | Backend port (default: `8001`) |+| `FRONTEND_PORT` | No | Frontend port (default: `3782`) |+| `NEXT_PUBLIC_API_BASE` | No | **Frontend API URL** - Set this for remote/LAN access (e.g., `http://192.168.1.100:8001`) |+| `TTS_*` | No | Text-to-Speech settings |+| `SEARCH_PROVIDER` | No | Search provider (options: `perplexity`, `baidu`, default: `perplexity`) |+| `PERPLEXITY_API_KEY` | No | For Perplexity web search |+| `BAIDU_API_KEY` | No | For Baidu AI search |++> 💡 **Remote Access**: If accessing from another device (e.g., `192.168.31.66:3782`), add to `.env`:+> ```bash+> NEXT_PUBLIC_API_BASE=http://192.168.31.66:8001+> ```++</details>++**③ Configure Ports & LLM** *(Optional)*++- **Ports**: Set in `.env` file → `BACKEND_PORT` / `FRONTEND_PORT` (defaults: 8001/3782)+- **LLM**: Edit `config/agents.yaml` → `temperature` / `max_tokens` per module+- See [Configuration Docs](config/README.md) for details++**④ Try Demo Knowledge Bases** *(Optional)*++<details>+<summary>📚 <b>Available Demos</b></summary>++- **Research Papers** — 5 papers from our lab ([AI-Researcher](https://github.com/HKUDS/AI-Researcher), [LightRAG](https://github.com/HKUDS/LightRAG), etc.)+- **Data Science Textbook** — 8 chapters, 296 pages ([Book Link](https://ma-lab-berkeley.github.io/deep-representation-learning-book/))++</details>++1. Download from [Google Drive](https://drive.google.com/drive/folders/1iWwfZXiTuQKQqUYb5fGDZjLCeTUP6DA6?usp=sharing)+2. Extract into `data/` directory++> Demo KBs use `text-embedding-3-large` with `dimensions = 3072`++**⑤ Create Your Own Knowledge Base** *(After Launch)*++1. Go to http://localhost:3782/knowledge+2. Click "New Knowledge Base" → Enter name → Upload PDF/TXT/MD files+3. Monitor progress in terminal++---++### Step 2: Choose Your Installation Method++#### 🐳 Option A: Docker Deployment++> No Python/Node.js setup required++**Prerequisites**: [Docker](https://docs.docker.com/get-docker/) & [Docker Compose](https://docs.docker.com/compose/install/)++**Quick Start** — Build from source:++```bash+docker compose up --build -d # Build and start (~5-10 min first run)+docker compose logs -f # View logs+```++**Or use pre-built image** (faster):++```bash+# Linux/macOS (AMD64)+docker run -d --name deeptutor \+ -p 8001:8001 -p 3782:3782 \+ --env-file .env \+ -v $(pwd)/data:/app/data \+ -v $(pwd)/config:/app/config:ro \+ ghcr.io/hkuds/deeptutor:latest++# Apple Silicon (ARM64): use ghcr.io/hkuds/deeptutor:latest-arm64+# Windows PowerShell: use ${PWD} instead of $(pwd)+```++**Common Commands**:++```bash+docker compose up -d # Start+docker compose down # Stop+docker compose logs -f # View logs+docker compose up --build # Rebuild after changes+```++<details>+<summary>📋 <b>More Docker Options</b> (Pre-built images, Cloud deployment, Custom ports)</summary>++**Pre-built Image Architecture Reference:**++| Architecture | Image Tag | Use Case |+|:-------------|:----------|:---------|+| **AMD64** | `ghcr.io/hkuds/deeptutor:latest` | Intel/AMD (most servers, Windows/Linux PCs) |+| **ARM64** | `ghcr.io/hkuds/deeptutor:latest-arm64` | Apple Silicon, AWS Graviton, Raspberry Pi |++> 💡 Run `uname -m` to check: `x86_64` = AMD64, `arm64`/`aarch64` = ARM64++**Cloud Deployment** — Must set external API URL:++```bash+docker run -d --name deeptutor \+ -p 8001:8001 -p 3782:3782 \+ -e NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001 \+ --env-file .env \+ -v $(pwd)/data:/app/data \+ ghcr.io/hkuds/deeptutor:latest+```++**Custom Ports Example:**++```bash+docker run -d --name deeptutor \+ -p 9001:9001 -p 3000:3000 \+ -e BACKEND_PORT=9001 \+ -e FRONTEND_PORT=3000 \+ -e NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:9001 \+ --env-file .env \+ -v $(pwd)/data:/app/data \+ ghcr.io/hkuds/deeptutor:latest+```++</details>++---++#### 💻 Option B: Manual Installation++> For development or non-Docker environments++**Prerequisites**: Python 3.10+, Node.js 18+++**1. Set Up Environment**:++```bash+# Using conda (Recommended)+conda create -n deeptutor python=3.10 && conda activate deeptutor++# Or using venv+python -m venv venv && source venv/bin/activate # Windows: venv\Scripts\activate+```++**2. Install Dependencies**:++```bash+pip install -r requirements.txt+npm install --prefix web+```++**3. Launch**:++```bash+python scripts/start_web.py # Start frontend + backend+# Or: python scripts/start.py # CLI only+# Stop: Ctrl+C+```++<details>+<summary>🔧 <b>Start Frontend & Backend Separately</b></summary>++**Backend** (FastAPI):+```bash+python src/api/run_server.py+# Or: uvicorn src.api.main:app --host 0.0.0.0 --port 8001 --reload+```++**Frontend** (Next.js):+```bash+cd web && npm install && npm run dev -- -p 3782+```++**Note**: Create `web/.env.local`:+```bash+NEXT_PUBLIC_API_BASE=http://localhost:8001+```++| Service | Default Port |+|:---:|:---:|+| Backend | `8001` |+| Frontend | `3782` |++</details>++### Access URLs++| Service | URL | Description |+|:---:|:---|:---|+| **Frontend** | http://localhost:3782 | Main web interface |+| **API Docs** | http://localhost:8001/docs | Interactive API documentation |++---++## 📂 Data Storage++All user content and system data are stored in the `data/` directory:++```+data/+├── knowledge_bases/ # Knowledge base storage+└── user/ # User activity data+ ├── solve/ # Problem solving results and artifacts+ ├── question/ # Generated questions+ ├── research/ # Research reports and cache+ ├── co-writer/ # Interactive IdeaGen documents and audio files+ ├── notebook/ # Notebook records and metadata+ ├── guide/ # Guided learning sessions+ ├── logs/ # System logs+ └── run_code_workspace/ # Code execution workspace+```++Results are automatically saved during all activities. Directories are created automatically as needed.++## 📦 Core Modules++<details>+<summary><b>🧠 Smart Solver</b></summary>++<details>+<summary><b>Architecture Diagram</b></summary>++++</details>++> **Intelligent problem-solving system** based on **Analysis Loop + Solve Loop** dual-loop architecture, supporting multi-mode reasoning and dynamic knowledge retrieval.++**Core Features**++| Feature | Description |+|:---:|:---|+| Dual-Loop Architecture | **Analysis Loop**: InvestigateAgent → NoteAgent<br>**Solve Loop**: PlanAgent → ManagerAgent → SolveAgent → CheckAgent → Format |+| Multi-Agent Collaboration | Specialized agents: InvestigateAgent, NoteAgent, PlanAgent, ManagerAgent, SolveAgent, CheckAgent |+| Real-time Streaming | WebSocket transmission with live reasoning process display |+| Tool Integration | RAG (naive/hybrid), Web Search, Query Item, Code Execution |+| Persistent Memory | JSON-based memory files for context preservation |+| Citation Management | Structured citations with reference tracking |++**Usage**++1. Visit http://localhost:{frontend_port}/solver+2. Select a knowledge base+3. Enter your question, click "Solve"+4. Watch the real-time reasoning process and final answer++<details>+<summary><b>Python API</b></summary>++```python+import asyncio+from src.agents.solve import MainSolver++async def main():+ solver = MainSolver(kb_name="ai_textbook")+ result = await solver.solve(+ question="Calculate the linear convolution of x=[1,2,3] and h=[4,5]",+ mode="auto"+ )+ print(result['formatted_solution'])++asyncio.run(main())+```++</details>++<details>+<summary><b>Output Location</b></summary>++```+data/user/solve/solve_YYYYMMDD_HHMMSS/+├── investigate_memory.json # Analysis Loop memory+├── solve_chain.json # Solve Loop steps & tool records+├── citation_memory.json # Citation management+├── final_answer.md # Final solution (Markdown)+├── performance_report.json # Performance monitoring+└── artifacts/ # Code execution outputs+```++</details>++</details>++---++<details>+<summary><b>📝 Question Generator</b></summary>++<details>+<summary><b>Architecture Diagram</b></summary>++++</details>++> **Dual-mode question generation system** supporting **custom knowledge-based generation** and **reference exam paper mimicking** with automatic validation.++**Core Features**++| Feature | Description |+|:---:|:---|+| Custom Mode | **Background Knowledge** → **Question Planning** → **Generation** → **Single-Pass Validation**<br>Analyzes question relevance without rejection logic |+| Mimic Mode | **PDF Upload** → **MinerU Parsing** → **Question Extraction** → **Style Mimicking**<br>Generates questions based on reference exam structure |+| ReAct Engine | QuestionGenerationAgent with autonomous decision-making (think → act → observe) |+| Validation Analysis | Single-pass relevance analysis with `kb_coverage` and `extension_points` |+| Question Types | Multiple choice, fill-in-the-blank, calculation, written response, etc. |+| Batch Generation | Parallel processing with progress tracking |+| Complete Persistence | All intermediate files saved (background knowledge, plan, individual results) |+| Timestamped Output | Mimic mode creates batch folders: `mimic_YYYYMMDD_HHMMSS_{pdf_name}/` |++**Usage**++**Custom Mode:**+1. Visit http://localhost:{frontend_port}/question+2. Fill in requirements (topic, difficulty, question type, count)+3. Click "Generate Questions"+4. View generated questions with validation reports++**Mimic Mode:**+1. Visit http://localhost:{frontend_port}/question+2. Switch to "Mimic Exam" tab+3. Upload PDF or provide parsed exam directory+4. Wait for parsing → extraction → generation+5. View generated questions alongside original references++<details>+<summary><b>Python API</b></summary>++**Custom Mode - Full Pipeline:**+```python+import asyncio+from src.agents.question import AgentCoordinator++async def main():+ coordinator = AgentCoordinator(+ kb_name="ai_textbook",+ output_dir="data/user/question"+ )++ # Generate multiple questions from text requirement+ result = await coordinator.generate_questions_custom(+ requirement_text="Generate 3 medium-difficulty questions about deep learning basics",+ difficulty="medium",+ question_type="choice",+ count=3+ )++ print(f"✅ Generated {result['completed']}/{result['requested']} questions")+ for q in result['results']:+ print(f"- Relevance: {q['validation']['relevance']}")++asyncio.run(main())+```++**Mimic Mode - PDF Upload:**+```python+from src.agents.question.tools.exam_mimic import mimic_exam_questions++result = await mimic_exam_questions(+ pdf_path="exams/midterm.pdf",+ kb_name="calculus",+ output_dir="data/user/question/mimic_papers",+ max_questions=5+)++print(f"✅ Generated {result['successful_generations']} questions")+print(f"Output: {result['output_file']}")+```++</details>++<details>+<summary><b>Output Location</b></summary>++**Custom Mode:**+```+data/user/question/custom_YYYYMMDD_HHMMSS/+├── background_knowledge.json # RAG retrieval results+├── question_plan.json # Question planning+├── question_1_result.json # Individual question results+├── question_2_result.json+└── ...+```++**Mimic Mode:**+```+data/user/question/mimic_papers/+└── mimic_YYYYMMDD_HHMMSS_{pdf_name}/+ ├── {pdf_name}.pdf # Original PDF+ ├── auto/{pdf_name}.md # MinerU parsed markdown+ ├── {pdf_name}_YYYYMMDD_HHMMSS_questions.json # Extracted questions+ └── {pdf_name}_YYYYMMDD_HHMMSS_generated_questions.json # Generated questions+```++</details>++</details>++---++<details>+<summary><b>🎓 Guided Learning</b></summary>++<details>+<summary><b>Architecture Diagram</b></summary>++++</details>++> **Personalized learning system** based on notebook content, automatically generating progressive learning paths through interactive pages and smart Q&A.++**Core Features**++| Feature | Description |+|:---:|:---|+| Multi-Agent Architecture | **LocateAgent**: Identifies 3-5 progressive knowledge points<br>**InteractiveAgent**: Converts to visual HTML pages<br>**ChatAgent**: Provides contextual Q&A<br>**SummaryAgent**: Generates learning summaries |+| Smart Knowledge Location | Automatic analysis of notebook content |+| Interactive Pages | HTML page generation with bug fixing |+| Smart Q&A | Context-aware answers with explanations |+| Progress Tracking | Real-time status with session persistence |+| Cross-Notebook Support | Select records from multiple notebooks |++**Usage Flow**++1. **Select Notebook(s)** — Choose one or multiple notebooks (cross-notebook selection supported)+2. **Generate Learning Plan** — LocateAgent identifies 3-5 core knowledge points+3. **Start Learning** — InteractiveAgent generates HTML visualization+4. **Learning Interaction** — Ask questions, click "Next" to proceed+5. **Complete Learning** — SummaryAgent generates learning summary++<details>+<summary><b>Output Location</b></summary>++```+data/user/guide/+└── session_{session_id}.json # Complete session state, knowledge points, chat history+```++</details>++</details>++---++<details>+<summary><b>✏️ Interactive IdeaGen (Co-Writer)</b></summary>++<details>+<summary><b>Architecture Diagram</b></summary>++++</details>++> **Intelligent Markdown editor** supporting AI-assisted writing, auto-annotation, and TTS narration.++**Core Features**++| Feature | Description |+|:---:|:---|+| Rich Text Editing | Full Markdown syntax support with live preview |+| EditAgent | **Rewrite**: Custom instructions with optional RAG/web context<br>**Shorten**: Compress while preserving key information<br>**Expand**: Add details and context |+| Auto-Annotation | Automatic key content identification and marking |+| NarratorAgent | Script generation, TTS audio, multiple voices (Cherry, Stella, Annie, Cally, Eva, Bella) |+| Context Enhancement | Optional RAG or web search for additional context |+| Multi-Format Export | Markdown, PDF, etc. |++**Usage**++1. Visit http://localhost:{frontend_port}/co_writer+2. Enter or paste text in the editor+3. Use AI features: Rewrite, Shorten, Expand, Auto Mark, Narrate+4. Export to Markdown or PDF++<details>+<summary><b>Output Location</b></summary>++```+data/user/co-writer/+├── audio/ # TTS audio files+│ └── {operation_id}.mp3+├── tool_calls/ # Tool call history+│ └── {operation_id}_{tool_type}.json+└── history.json # Edit history+```++</details>++</details>++---++<details>+<summary><b>🔬 Deep Research</b></summary>++<details>+<summary><b>Architecture Diagram</b></summary>++++</details>++> **DR-in-KG** (Deep Research in Knowledge Graph) — A systematic deep research system based on **Dynamic Topic Queue** architecture, enabling multi-agent collaboration across three phases: **Planning → Researching → Reporting**.++**Core Features**++| Feature | Description |+|:---:|:---|+| Three-Phase Architecture | **Phase 1 (Planning)**: RephraseAgent (topic optimization) + DecomposeAgent (subtopic decomposition)<br>**Phase 2 (Researching)**: ManagerAgent (queue scheduling) + ResearchAgent (research decisions) + NoteAgent (info compression)<br>**Phase 3 (Reporting)**: Deduplication → Three-level outline generation → Report writing with citations |+| Dynamic Topic Queue | Core scheduling system with TopicBlock state management: `PENDING → RESEARCHING → COMPLETED/FAILED`. Supports dynamic topic discovery during research |+| Execution Modes | **Series Mode**: Sequential topic processing<br>**Parallel Mode**: Concurrent multi-topic processing with `AsyncCitationManagerWrapper` for thread-safe operations |+| Multi-Tool Integration | **RAG** (hybrid/naive), **Query Item** (entity lookup), **Paper Search**, **Web Search**, **Code Execution** — dynamically selected by ResearchAgent |+| Unified Citation System | Centralized CitationManager as single source of truth for citation ID generation, ref_number mapping, and deduplication |+| Preset Configurations | **quick**: Fast research (1-2 subtopics, 1-2 iterations)<br>**medium/standard**: Balanced depth (5 subtopics, 4 iterations)<br>**deep**: Thorough research (8 subtopics, 7 iterations)<br>**auto**: Agent autonomously decides depth |++**Citation System Architecture**++The citation system follows a centralized design with CitationManager as the single source of truth:++```+┌─────────────────────────────────────────────────────────────────┐+│ CitationManager │+│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │+│ │ ID Generation │ │ ref_number Map │ │ Deduplication │ │+│ │ PLAN-XX │ │ citation_id → │ │ (papers only) │ │+│ │ CIT-X-XX │ │ ref_number │ │ │ │+│ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │+└───────────┼────────────────────┼────────────────────┼───────────┘+ │ │ │+ ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐+ │DecomposeAgent│ │ReportingAgent│ │ References │+ │ ResearchAgent│ │ (inline [N]) │ │ Section │+ │ NoteAgent │ └─────────────┘ └────────────┘+ └─────────────┘+```++| Component | Description |+|:---:|:---|+| ID Format | **PLAN-XX** (planning stage RAG queries) + **CIT-X-XX** (research stage, X=block number) |+| ref_number Mapping | Sequential 1-based numbers built from sorted citation IDs, with paper deduplication |+| Inline Citations | Simple `[N]` format in LLM output, post-processed to clickable `[[N]](#ref-N)` links |+| Citation Table | Clear reference table provided to LLM: `Cite as [1] → (RAG) query preview...` |+| Post-processing | Automatic format conversion + validation to remove invalid citation references |+| Parallel Safety | Thread-safe async methods (`get_next_citation_id_async`, `add_citation_async`) for concurrent execution |++**Parallel Execution Architecture**++When `execution_mode: "parallel"` is enabled, multiple topic blocks are researched concurrently:++```+┌─────────────────────────────────────────────────────────────────────────┐+│ Parallel Research Execution │+├─────────────────────────────────────────────────────────────────────────┤+│ │+│ DynamicTopicQueue AsyncCitationManagerWrapper │+│ ┌─────────────────┐ ┌─────────────────────────┐ │+│ │ Topic 1 (PENDING)│ ──┐ │ Thread-safe wrapper │ │+│ │ Topic 2 (PENDING)│ ──┼──→ asyncio │ for CitationManager │ │+│ │ Topic 3 (PENDING)│ ──┤ Semaphore │ │ │+│ │ Topic 4 (PENDING)│ ──┤ (max=5) │ • get_next_citation_ │ │+│ │ Topic 5 (PENDING)│ ──┘ │ id_async() │ │+│ └─────────────────┘ │ • add_citation_async() │ │+│ │ └───────────┬─────────────┘ │+│ ▼ │ │+│ ┌─────────────────────────────────────────────────────────────┐ │+│ │ Concurrent ResearchAgent Tasks │ │+│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │+│ │ │ Task 1 │ │ Task 2 │ │ Task 3 │ │ Task 4 │ ... │ │+│ │ │(Topic 1)│ │(Topic 2)│ │(Topic 3)│ │(Topic 4)│ │ │+│ │ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ │ │+│ │ │ │ │ │ │ │+│ │ └────────────┴────────────┴────────────┘ │ │+│ │ │ │ │+│ │ ▼ │ │+│ │ AsyncManagerAgentWrapper │ │+│ │ (Thread-safe queue updates) │ │+│ └─────────────────────────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────┘+```++| Component | Description |+|:---:|:---|+| `asyncio.Semaphore` | Limits concurrent tasks to `max_parallel_topics` (default: 5) |+| `AsyncCitationManagerWrapper` | Wraps CitationManager with `asyncio.Lock()` for thread-safe ID generation |+| `AsyncManagerAgentWrapper` | Ensures queue state updates are atomic across parallel tasks |+| Real-time Progress | Live display of all active research tasks with status indicators |++**Agent Responsibilities**++| Agent | Phase | Responsibility |+|:---:|:---:|:---|+| RephraseAgent | Planning | Optimizes user input topic, supports multi-turn user interaction for refinement |+| DecomposeAgent | Planning | Decomposes topic into subtopics with RAG context, obtains citation IDs from CitationManager |+| ManagerAgent | Researching | Queue state management, task scheduling, dynamic topic addition |+| ResearchAgent | Researching | Knowledge sufficiency check, query planning, tool selection, requests citation IDs before each tool call |+| NoteAgent | Researching | Compresses raw tool outputs into summaries, creates ToolTraces with pre-assigned citation IDs |+| ReportingAgent | Reporting | Builds citation map, generates three-level outline, writes report sections with citation tables, post-processes citations |++**Report Generation Pipeline**++```+1. Build Citation Map → CitationManager.build_ref_number_map()+2. Generate Outline → Three-level headings (H1 → H2 → H3)+3. Write Sections → LLM uses [N] citations with provided citation table+4. Post-process → Convert [N] → [[N]](#ref-N), validate references+5. Generate References → Academic-style entries with collapsible source details+```++**Usage**++1. Visit http://localhost:{frontend_port}/research+2. Enter research topic+3. Select research mode (quick/medium/deep/auto)+4. Watch real-time progress with parallel/series execution+5. View structured report with clickable inline citations+6. Export as Markdown or PDF (with proper page splitting and Mermaid diagram support)++<details>+<summary><b>CLI</b></summary>++```bash+# Quick mode (fast research)+python src/agents/research/main.py --topic "Deep Learning Basics" --preset quick++# Medium mode (balanced)+python src/agents/research/main.py --topic "Transformer Architecture" --preset medium++# Deep mode (thorough research)+python src/agents/research/main.py --topic "Graph Neural Networks" --preset deep++# Auto mode (agent decides depth)+python src/agents/research/main.py --topic "Reinforcement Learning" --preset auto+```++</details>++<details>+<summary><b>Python API</b></summary>++```python+import asyncio+from src.agents.research import ResearchPipeline+from src.core.core import get_llm_config, load_config_with_main++async def main():+ # Load configuration (main.yaml merged with any module-specific overrides)+ config = load_config_with_main("research_config.yaml")+ llm_config = get_llm_config()++ # Create pipeline (agent parameters loaded from agents.yaml automatically)+ pipeline = ResearchPipeline(+ config=config,+ api_key=llm_config["api_key"],+ base_url=llm_config["base_url"],+ kb_name="ai_textbook" # Optional: override knowledge base+ )++ # Run research+ result = await pipeline.run(topic="Attention Mechanisms in Deep Learning")+ print(f"Report saved to: {result['final_report_path']}")++asyncio.run(main())+```++</details>++<details>+<summary><b>Output Location</b></summary>++```+data/user/research/+├── reports/ # Final research reports+│ ├── research_YYYYMMDD_HHMMSS.md # Markdown report with clickable citations [[N]](#ref-N)+│ └── research_*_metadata.json # Research metadata and statistics+└── cache/ # Research process cache+ └── research_YYYYMMDD_HHMMSS/+ ├── queue.json # DynamicTopicQueue state (TopicBlocks + ToolTraces)+ ├── citations.json # Citation registry with ID counters and ref_number mapping+ │ # - citations: {citation_id: citation_info}+ │ # - counters: {plan_counter, block_counters}+ ├── step1_planning.json # Planning phase results (subtopics + PLAN-XX citations)+ ├── planning_progress.json # Planning progress events+ ├── researching_progress.json # Researching progress events+ ├── reporting_progress.json # Reporting progress events+ ├── outline.json # Three-level report outline structure+ └── token_cost_summary.json # Token usage statistics+```++**Citation File Structure** (`citations.json`):+```json+{+ "research_id": "research_20241209_120000",+ "citations": {+ "PLAN-01": {"citation_id": "PLAN-01", "tool_type": "rag_hybrid", "query": "...", "summary": "..."},+ "CIT-1-01": {"citation_id": "CIT-1-01", "tool_type": "paper_search", "papers": [...], ...}+ },+ "counters": {+ "plan_counter": 2,+ "block_counters": {"1": 3, "2": 2}+ }+}+```++</details>++<details>+<summary><b>Configuration Options</b></summary>++Key configuration in `config/main.yaml` (research section) and `config/agents.yaml`:++```yaml+# config/agents.yaml - Agent LLM parameters+research:+ temperature: 0.5+ max_tokens: 12000++# config/main.yaml - Research settings+research:+ # Execution Mode+ researching:+ execution_mode: "parallel" # "series" or "parallel"+ max_parallel_topics: 5 # Max concurrent topics+ max_iterations: 5 # Max iterations per topic++ # Tool Switches+ enable_rag_hybrid: true # Hybrid RAG retrieval+ enable_rag_naive: true # Basic RAG retrieval+ enable_paper_search: true # Academic paper search+ enable_web_search: true # Web search (also controlled by tools.web_search.enabled)+ enable_run_code: true # Code execution++ # Queue Limits+ queue:+ max_length: 5 # Maximum topics in queue++ # Reporting+ reporting:+ enable_inline_citations: true # Enable clickable [N] citations in report++ # Presets: quick, medium, deep, auto++# Global tool switches in tools section+tools:+ web_search:+ enabled: true # Global web search switch (higher priority)+```++</details>++</details>++---++<details>+<summary><b>💡 Automated IdeaGen</b></summary>++<details>+<summary><b>Architecture Diagram</b></summary>++++</details>++> **Research idea generation system** that extracts knowledge points from notebook records and generates research ideas through multi-stage filtering.++**Core Features**++| Feature | Description |+|:---:|:---|+| MaterialOrganizerAgent | Extracts knowledge points from notebook records |+| Multi-Stage Filtering | **Loose Filter** → **Explore Ideas** (5+ per point) → **Strict Filter** → **Generate Markdown** |+| Idea Exploration | Innovative thinking from multiple dimensions |+| Structured Output | Organized markdown with knowledge points and ideas |+| Progress Callbacks | Real-time updates for each stage |++**Usage**++1. Visit http://localhost:{frontend_port}/ideagen+2. Select a notebook with records+3. Optionally provide user thoughts/preferences+4. Click "Generate Ideas"+5. View generated research ideas organized by knowledge points++<details>+<summary><b>Python API</b></summary>++```python+import asyncio+from src.agents.ideagen import IdeaGenerationWorkflow, MaterialOrganizerAgent+from src.core.core import get_llm_config++async def main():+ llm_config = get_llm_config()++ # Step 1: Extract knowledge points from materials+ organizer = MaterialOrganizerAgent(+ api_key=llm_config["api_key"],+ base_url=llm_config["base_url"]+ )+ knowledge_points = await organizer.extract_knowledge_points(+ "Your learning materials or notebook content here"+ )++ # Step 2: Generate research ideas+ workflow = IdeaGenerationWorkflow(+ api_key=llm_config["api_key"],+ base_url=llm_config["base_url"]+ )+ result = await workflow.process(knowledge_points)+ print(result) # Markdown formatted research ideas++asyncio.run(main())+```++</details>++</details>++---++<details>+<summary><b>📊 Dashboard + Knowledge Base Management</b></summary>++> **Unified system entry** providing activity tracking, knowledge base management, and system status monitoring.++**Key Features**++| Feature | Description |+|:---:|:---|+| Activity Statistics | Recent solving/generation/research records |+| Knowledge Base Overview | KB list, statistics, incremental updates |+| Notebook Statistics | Notebook counts, record distribution |+| Quick Actions | One-click access to all modules |++**Usage**++- **Web Interface**: Visit http://localhost:{frontend_port} to view system overview+- **Create KB**: Click "New Knowledge Base", upload PDF/Markdown documents+- **View Activity**: Check recent learning activities on Dashboard++</details>++---++<details>+<summary><b>📓 Notebook</b></summary>++> **Unified learning record management**, connecting outputs from all modules to create a personalized learning knowledge base.++**Core Features**++| Feature | Description |+|:---:|:---|+| Multi-Notebook Management | Create, edit, delete notebooks |+| Unified Record Storage | Integrate solving/generation/research/Interactive IdeaGen records |+| Categorization Tags | Auto-categorize by type, knowledge base |+| Custom Appearance | Color, icon personalization |++**Usage**++1. Visit http://localhost:{frontend_port}/notebook+2. Create new notebook (set name, description, color, icon)+3. After completing tasks in other modules, click "Add to Notebook"+4. View and manage all records on the notebook page++</details>++---++### 📖 Module Documentation++<table>+<tr>+<td align="center"><a href="config/README.md">Configuration</a></td>+<td align="center"><a href="data/README.md">Data Directory</a></td>+<td align="center"><a href="src/api/README.md">API Backend</a></td>+<td align="center"><a href="src/core/README.md">Core Utilities</a></td>+</tr>+<tr>+<td align="center"><a href="src/knowledge/README.md">Knowledge Base</a></td>+<td align="center"><a href="src/tools/README.md">Tools</a></td>+<td align="center"><a href="web/README.md">Web Frontend</a></td>+<td align="center"><a href="src/agents/solve/README.md">Solve Module</a></td>+</tr>+<tr>+<td align="center"><a href="src/agents/question/README.md">Question Module</a></td>+<td align="center"><a href="src/agents/research/README.md">Research Module</a></td>+<td align="center"><a href="src/agents/co_writer/README.md">Interactive IdeaGen Module</a></td>+<td align="center"><a href="src/agents/guide/README.md">Guide Module</a></td>+</tr>+<tr>+<td align="center" colspan="4"><a href="src/agents/ideagen/README.md">Automated IdeaGen Module</a></td>+</tr>+</table>++## ❓ FAQ++<details>+<summary><b>Backend fails to start?</b></summary>++**Checklist**+- Confirm Python version >= 3.10+- Confirm all dependencies installed: `pip install -r requirements.txt`+- Check if port 8001 is in use+- Check `.env` file configuration++**Solutions**+- **Change port**: Set `BACKEND_PORT=9001` in `.env` file+- **Check logs**: Review terminal error messages++</details>++<details>+<summary><b>Port occupied after Ctrl+C?</b></summary>++**Problem**++After pressing Ctrl+C during a running task (e.g., deep research), restarting shows "port already in use" error.++**Cause**++Ctrl+C sometimes only terminates the frontend process while the backend continues running in the background.++**Solution**++```bash+# macOS/Linux: Find and kill the process+lsof -i :8001+kill -9 <PID>++# Windows: Find and kill the process+netstat -ano | findstr :8001+taskkill /PID <PID> /F+```++Then restart the service with `python scripts/start_web.py`.++</details>++<details>+<summary><b>npm: command not found error?</b></summary>++**Problem**++Running `scripts/start_web.py` shows `npm: command not found` or exit status 127.++**Checklist**+- Check if npm is installed: `npm --version`+- Check if Node.js is installed: `node --version`+- Confirm conda environment is activated (if using conda)++**Solutions**+```bash+# Option A: Using Conda (Recommended)+conda install -c conda-forge nodejs++# Option B: Using Official Installer+# Download from https://nodejs.org/++# Option C: Using nvm+nvm install 18+nvm use 18+```++**Verify Installation**+```bash+node --version # Should show v18.x.x or higher+npm --version # Should show version number+```++</details>++<details>+<summary><b>Long path names on Windows installation?</b></summary>++**Problem**++On Windows, you may encounter errors related to long file paths during installation, such as "The filename or extension is too long" or similar path length issues.++**Cause**++Windows has a default limitation on path lengths (260 characters), which can be exceeded by DeepTutor's nested directory structures and dependencies.++**Solution**++Enable long path support system-wide by running the following command in an Administrator Command Prompt:++```cmd+reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f+```++After running this command, restart your terminal for the changes to take effect.++</details>++<details>+<summary><b>Frontend cannot connect to backend?</b></summary>++**Checklist**+- Confirm backend is running (visit http://localhost:8001/docs)+- Check browser console for error messages++**Solution**++Create `.env.local` in `web` directory:++```bash+NEXT_PUBLIC_API_BASE=http://localhost:8001+```++</details>++<details>+<summary><b>Docker: Frontend cannot connect in cloud deployment?</b></summary>++**Problem**++When deploying to a cloud server, the frontend shows connection errors like "Failed to fetch" or "NEXT_PUBLIC_API_BASE is not configured".++**Cause**++The default API URL is `localhost:8001`, which points to the user's local machine in the browser, not your server.++**Solution**++Set the `NEXT_PUBLIC_API_BASE_EXTERNAL` environment variable to your server's public URL:++```bash+# Using docker run+docker run -d --name deeptutor \+ -e NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001 \+ ... other options ...+ ghcr.io/hkuds/deeptutor:latest++# Or in .env file+NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001+```++**Custom Port Example:**+```bash+# If using backend port 9001+-e BACKEND_PORT=9001 \+-e NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:9001+```++</details>++<details>+<summary><b>Docker: How to use custom ports?</b></summary>++**Solution**++Set both the port environment variables AND the port mappings:++```bash+docker run -d --name deeptutor \+ -p 9001:9001 -p 4000:4000 \+ -e BACKEND_PORT=9001 \+ -e FRONTEND_PORT=4000 \+ -e NEXT_PUBLIC_API_BASE_EXTERNAL=http://localhost:9001 \+ ... other env vars ...+ ghcr.io/hkuds/deeptutor:latest+```++**Important**: The `-p` port mapping must match the `BACKEND_PORT`/`FRONTEND_PORT` values.++</details>++<details>+<summary><b>WebSocket connection fails?</b></summary>++**Checklist**+- Confirm backend is running+- Check firewall settings+- Confirm WebSocket URL is correct++**Solution**+- **Check backend logs**+- **Confirm URL format**: `ws://localhost:8001/api/v1/...`++</details>++<details>+<summary><b>Where are module outputs stored?</b></summary>++| Module | Output Path |+|:---:|:---|+| Solve | `data/user/solve/solve_YYYYMMDD_HHMMSS/` |+| Question | `data/user/question/question_YYYYMMDD_HHMMSS/` |+| Research | `data/user/research/reports/` |+| Interactive IdeaGen | `data/user/co-writer/` |+| Notebook | `data/user/notebook/` |+| Guide | `data/user/guide/session_{session_id}.json` |+| Logs | `data/user/logs/` |++</details>++<details>+<summary><b>How to add a new knowledge base?</b></summary>++**Web Interface**+1. Visit http://localhost:{frontend_port}/knowledge+2. Click "New Knowledge Base"+3. Enter knowledge base name+4. Upload PDF/TXT/MD documents+5. System will process documents in background++**CLI**+```bash+python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>+```++</details>++<details>+<summary><b>How to incrementally add documents to existing KB?</b></summary>++**CLI (Recommended)**+```bash+python -m src.knowledge.add_documents <kb_name> --docs <new_document.pdf>+```++**Benefits**+- Only processes new documents, saves time and API costs+- Automatically merges with existing knowledge graph+- Preserves all existing data++</details>++<details>+<summary><b>Numbered items extraction failed with uvloop.Loop error?</b></summary>++**Problem**++When initializing a knowledge base, you may encounter this error:+```+ValueError: Can't patch loop of type <class 'uvloop.Loop'>+```++This occurs because Uvicorn uses `uvloop` event loop by default, which is incompatible with `nest_asyncio`.++**Solution**++Use one of the following methods to extract numbered items:++```bash+# Option 1: Using the shell script (recommended)+./scripts/extract_numbered_items.sh <kb_name>++# Option 2: Direct Python command+python src/knowledge/extract_numbered_items.py --kb <kb_name> --base-dir ./data/knowledge_bases+```++This will extract numbered items (Definitions, Theorems, Equations, etc.) from your knowledge base without reinitializing it.++</details>+++</div>++## ⭐ Star History++<div align="center">++<p>+ <a href="https://github.com/HKUDS/DeepTutor/stargazers"><img src="assets/roster/stargazers.svg" alt="Stargazers"/></a>+ + <a href="https://github.com/HKUDS/DeepTutor/network/members"><img src="assets/roster/forkers.svg" alt="Forkers"/></a>+</p>++<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />+ </picture>+</a>++</div>++## 🤝 Contribution++<div align="center">++We hope DeepTutor could become a gift for the community. 🎁++<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">+ <img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="Contributors to HKUDS/DeepTutor" />+</a>++</div>++## 🔗 Related Projects++<div align="center">++| [⚡ LightRAG](https://github.com/HKUDS/LightRAG) | [🎨 RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [💻 DeepCode](https://github.com/HKUDS/DeepCode) | [🔬 AI-Researcher](https://github.com/HKUDS/AI-Researcher) |+|:---:|:---:|:---:|:---:|+| Simple and Fast RAG | Multimodal RAG | AI Code Assistant | Research Automation |++**[Data Intelligence Lab @ HKU](https://github.com/HKUDS)**++[⭐ Star us](https://github.com/HKUDS/DeepTutor/stargazers) · [🐛 Report a bug](https://github.com/HKUDS/DeepTutor/issues) · [💬 Discussions](https://github.com/HKUDS/DeepTutor/discussions)++---++This project is licensed under the ***[AGPL-3.0 License](LICENSE)***.++*✨ Thanks for visiting **DeepTutor**!*++<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="Views">++</div>diff --git a/config/agents.yaml b/config/agents.yamlindex d8adc7cf5..f8a0b8132 100644--- a/config/agents.yaml+++ b/config/agents.yaml@@ -12,6 +12,9 @@solve:temperature: 0.3max_tokens: 8192+ # NOTE: Valid tools for investigate agent validation are defined in+ # config/main.yaml, which is the SINGLE source of truth for valid_tools.+ # Do not re-declare valid_tools here to avoid configuration drift.# Research Module - Deep research agents# Agents: rephrase_agent, decompose_agent, manager_agent, research_agent, note_agent, reporting_agentdiff --git a/config/main.yaml b/config/main.yamlindex c3c135357..f95d83389 100644--- a/config/main.yaml+++ b/config/main.yaml@@ -22,7 +22,7 @@ tools:web_search:enabled: trueconsolidation: template- consolid ation_template: ''+ consolidation_template: ''provider: jinaquery_item:enabled: true@@ -55,6 +55,13 @@ solve:max_solve_correction_iterations: 3enable_citations: truesave_intermediate_results: true+ # Valid tools for investigate agent validation+ valid_tools:+ - "rag_naive"+ - "rag_hybrid"+ - "web_search"+ - "query_item"+ - "none"agents:investigate_agent:max_actions_per_round: 1diff --git a/data/README.md b/data/README.mdindex 576964da4..250aae33e 100644--- a/data/README.md+++ b/data/README.md@@ -6,70 +6,22 @@ This directory stores all data files for the AI-Tutor system, including knowledg```data/-├── knowledge_bases/ # Knowledge base storage directory-│ ├── kb_config.json # Knowledge base configuration file-│ └── {kb_name}/ # Individual knowledge base directories-│ ├── metadata.json # Knowledge base metadata-│ ├── numbered_items.json # Numbered items (definitions, theorems, etc.)-│ ├── raw/ # Original documents (PDF/Markdown)-│ ├── images/ # Extracted images-│ ├── content_list/ # Document content list-│ └── rag_storage/ # RAG knowledge graph storage-│ ├── graph_chunk_entity_relation.graphml-│ ├── kv_store_*.json-│ └── vdb_*.json-│-└── user/ # User data directory- ├── solve/ # Problem solving module output- │ └── solve_YYYYMMDD_HHMMSS/- │ ├── investigate_memory.json- │ ├── solve_chain.json- │ ├── citation_memory.json- │ ├── final_answer.md- │ └── artifacts/ # Code execution output- │- ├── question/ # Question generation module output- │ └── question_YYYYMMDD_HHMMSS/- │- ├── research/ # Research module output- │ ├── cache/ # Research cache- │ │ └── research_*/ # Queue and intermediate results- │ └── reports/ # Research reports- │ └── research_*.md- │- ├── guide/ # Guided learning output- │ └── session_{session_id}.json- │- ├── notebook/ # Notebook data- │ └── notebooks_index.json- │- ├── co-writer/ # Co-Writer output- │ ├── audio/ # TTS audio files- │ └── tool_calls/ # Tool call history- │- ├── logs/ # System logs- │ └── ai_tutor_*.log- │- ├── run_code_workspace/ # Code execution workspace- │- └── user_history.json # User activity history+├── knowledge_bases/ # Knowledge base storage+└── user/ # User activity data+ ├── solve/ # Problem-solving results+ ├── question/ # Generated questions+ ├── research/ # Research reports and cache+ ├── co_writer/ # Interactive IdeaGen documents+ ├── notebook/ # Notebook records+ ├── guide/ # Guided-learning sessions+ └── run_code_workspace/ # Code execution workspace```## 📋 Directory Description### knowledge_bases/-Stores all knowledge base data files. Each knowledge base contains:--- **metadata.json**: Knowledge base metadata, including creation time, update time, update history, etc.-- **numbered_items.json**: Extracted numbered items (Definition, Theorem, Formula, etc.)-- **raw/**: Original uploaded documents (PDF, Markdown, etc.)-- **images/**: Images extracted from documents-- **content_list/**: Document content list (JSON format)-- **rag_storage/**: RAG knowledge graph storage files- - `graph_chunk_entity_relation.graphml`: Knowledge graph structure- - `kv_store_*.json`: Key-value storage (documents, entities, relations, etc.)- - `vdb_*.json`: Vector database indices+Stores all knowledge base data files for the AI-Tutor system.### user/@@ -77,44 +29,31 @@ Stores all user-generated data and output files.#### solve/-Problem solving module output directory. Each solving task generates a timestamped directory:-- `investigate_memory.json`: Analysis Loop memory data-- `solve_chain.json`: Complete Solve Loop steps and tool call records-- `citation_memory.json`: Citation management data-- `final_answer.md`: Final answer (Markdown format)-- `artifacts/`: Files generated by code execution (images, data files, etc.)+Problem-solving module output directory containing results from problem-solving tasks.#### question/-Question generation module output directory. Each question generation task generates a timestamped directory containing generated questions and validation results.+Question generation module output directory containing generated questions and validation results.#### research/-Research module output directory:-- `cache/`: Intermediate data during research (queue state, planning results, etc.)-- `reports/`: Final generated research reports (Markdown format)+Research module output directory containing research reports and cache data.-#### guide/+#### co_writer/-Guided learning module output directory. Each learning session is saved as a JSON file containing session state, knowledge points, chat history, etc.+Co-Writer module output directory for interactive IdeaGen documents.#### notebook/-Notebook data storage. `notebooks_index.json` contains index information for all notebooks.--#### co-writer/+Notebook data storage containing notebook records and indices.-Co-Writer module output directory:-- `audio/`: TTS-generated audio files-- `tool_calls/`: AI tool call history--#### logs/+#### guide/-System log files, named by date.+Guided-learning module output directory containing learning session data.#### run_code_workspace/-Code execution tool workspace for temporarily storing files generated by code execution.+Code execution workspace for temporarily storing files generated by code execution.## 🔧 Configuration@@ -124,7 +63,7 @@ Data directory paths are configured in `config/main.yaml`:paths:user_data_dir: "./data/user"knowledge_bases_dir: "./data/knowledge_bases"- user_log_dir: "./data/user/logs"+ run_code_workspace_dir: "./data/user/run_code_workspace"```## 📝 Notes@@ -146,11 +85,13 @@ paths:### Clean Old Data```bash-# Clean old solving records (keep last 30 days)-find data/user/solve -type d -mtime +30 -exec rm -rf {} \;+# Clean old user data directories (customize based on retention policy)+# Replace the pattern with your actual naming convention, e.g.:+# find data/user -type d -regex '.*_[0-9]{8}.*' -mtime +30 -exec rm -rf {} \;+find data/user -type d -name "*_YYYYMMDD*" -mtime +30 -exec rm -rf {} \;-# Clean old log files (keep last 7 days)-find data/user/logs -name "*.log" -mtime +7 -delete+# Clean temporary workspace files+find data/user/run_code_workspace -type f -mtime +7 -delete```### Backup Knowledge Base@@ -160,7 +101,7 @@ find data/user/logs -name "*.log" -mtime +7 -deletetar -czf knowledge_bases_backup_$(date +%Y%m%d).tar.gz data/knowledge_bases/# Backup specific knowledge base-tar -czf ai_textbook_backup.tar.gz data/knowledge_bases/ai-textbook/+tar -czf kb_backup.tar.gz data/knowledge_bases/{kb_name}/```### Restore Knowledge Basediff --git a/docs/features/overview.md b/docs/features/overview.mdindex 8ed2c0846..d257ccb89 100644--- a/docs/features/overview.md+++ b/docs/features/overview.md@@ -1,57 +1,162 @@-# Features+# 🏛️ DeepTutor's Framework-DeepTutor provides six specialized modules for AI-powered learning.+<img src="/full-pipe.png" alt="DeepTutor Full-Stack Workflow" width="100%">-<div class="feature-nav">+## 💬 User Interface Layer+• **Intuitive Interaction**: Simple bidirectional query-response flow for intuitive interaction.+• **Structured Output**: Structured response generation that organizes complex information into actionable outputs.+• **Dark/Light Mode**: System-wide theme support with automatic system preference detection.+• **Collapsible Sidebar**: Compact navigation with icon-only mode for focused learning.-## Core Modules+## 🤖 Intelligent Agent Modules+• **Problem Solving & Assessment**: Step-by-step problem solving and custom assessment generation.+• **Research & Learning**: Deep Research for topic exploration and Guided Learning with visualization.+• **Idea Generation**: Automated and interactive concept development with multi-source insights.-| Module | Description | Documentation |-|:-------|:------------|:--------------|-| 🧠 **Smart Solver** | Multi-agent problem solving with dual-loop reasoning | [Details →](https://github.com/HKUDS/DeepTutor#-smart-solver) |-| 🎯 **Question Generator** | Custom quiz generation & exam style mimicking | [Details →](https://github.com/HKUDS/DeepTutor#-question-generator) |-| 🎓 **Guided Learning** | Personalized learning paths with interactive visualization | [Details →](https://github.com/HKUDS/DeepTutor#-guided-learning) |-| 🔬 **Deep Research** | Systematic topic exploration with dynamic topic queue | [Details →](https://github.com/HKUDS/DeepTutor#-deep-research) |-| 💡 **IdeaGen** | Automated research idea generation with multi-stage filtering | [Details →](https://github.com/HKUDS/DeepTutor#-automated-ideagen) |-| ✏️ **Co-Writer** | AI-assisted writing with TTS narration | [Details →](https://github.com/HKUDS/DeepTutor#-interactive-ideagen-co-writer) |+## 🔧 Tool Integration Layer+• **Information Retrieval**: RAG hybrid retrieval, real-time web search, and academic paper databases.+• **Processing & Analysis**: Python code execution, query item lookup, and PDF parsing for document analysis.+• **Multi-Provider Support**: Flexible LLM providers (OpenAI, Anthropic, Ollama, etc.) and embedding adapters (OpenAI, Jina, Cohere, Ollama, etc.).-## Architecture+## 🧠 Knowledge & Memory Foundation+• **Knowledge Graph**: Entity-relation mapping for semantic connections and knowledge discovery.+• **Vector Store**: Embedding-based semantic search for intelligent content retrieval.+• **Memory System**: Session state management and citation tracking for contextual continuity.-<img src="/full-pipe.png" alt="DeepTutor Architecture" style="width: 100%; border-radius: 8px; margin: 24px 0;">+---++# Key Features of DeepTutor++## 📚 Massive Document Knowledge Q&A++• **Smart Knowledge Base**: Upload textbooks, research papers, technical manuals, and domain-specific documents. Build a comprehensive AI-powered knowledge repository for instant access.++• **Multi-Agent Problem Solving**: Dual-loop reasoning architecture with RAG, web search, paper search, and code execution—delivering step-by-step solutions with precise citations.++## 🎨 Interactive Learning Visualization-### System Layers+• **Knowledge Simplification & Explanations**: Transform complex concepts, knowledge, and algorithms into easy-to-understand visual aids, detailed step-by-step breakdowns, and engaging interactive demonstrations.-- **User Interface** — Bidirectional query-response with structured output-- **Agent Modules** — Specialized AI agents for each learning task-- **Tool Integration** — RAG, web search, paper search, code execution-- **Knowledge Foundation** — Knowledge graph + vector store + memory system+• **Personalized Q&A**: Context-aware conversations that adapt to your learning progress, with interactive pages and session-based knowledge tracking.-</div>+## 🎯 Knowledge Reinforcement with Practice Problem Generator-## Provider Support+• **Intelligent Exercise Creation**: Generate targeted quizzes, practice problems, and customized assessments tailored to your current knowledge level and specific learning objectives.-DeepTutor works with multiple LLM and embedding providers:+• **Authentic Exam Simulation**: Upload reference exams to generate practice questions that perfectly match the original style, format, and difficulty—giving you realistic preparation for the actual test.-::: details LLM Providers-- OpenAI (GPT-4o, GPT-4)-- Anthropic (Claude 3.5)-- Azure OpenAI-- DeepSeek-- Groq-- OpenRouter-- Ollama (local)-- Google Gemini-:::+## 🔍 Deep Research & Idea Generation-::: details Embedding Providers-- OpenAI-- Jina AI-- Cohere-- Ollama-- LM Studio-- HuggingFace-:::+• **Comprehensive Research & Literature Review**: Conduct in-depth topic exploration with systematic analysis. Identify patterns, connect related concepts across disciplines, and synthesize existing research findings.++• **Novel Insight Discovery**: Generate structured learning materials and uncover knowledge gaps. Identify promising new research directions through intelligent cross-domain knowledge synthesis.----📖 **Full documentation**: [GitHub README](https://github.com/HKUDS/DeepTutor)+<!-- Core Learning Experience -->++<table>+<tr>+<td width="50%" align="center" valign="top">++### 📚 Massive Document Knowledge Q&A++<img src="/solve.gif" alt="Document Q&A demonstration" width="100%">++Document Q&A and Step-by-Step Problem Solving++</td>+<td width="50%" align="center" valign="top">++### 🎨 Interactive Learning Visualization++<img src="/guided-learning.gif" alt="Interactive learning visualization demo" width="100%">++Interactive AI Learning with Knowledge Visual Explanations++</td>+</tr>+</table>++<!-- Practice & Reinforcement -->++### 🎯 Knowledge Reinforcement++<table>+<tr>+<td width="50%" valign="top" align="center">++<img src="/question-1.gif" alt="Custom question generation demo" width="100%">++**Custom Questions**+Auto-Validated Practice Questions with Instant Feedback++</td>+<td width="50%" valign="top" align="center">++<img src="/question-2.gif" alt="Mimic exam style questions demo" width="100%">++**Mimic Questions**+Clone Exam Style for Authentic Practice++</td>+</tr>+</table>++<!-- Research & Creation -->++### 🔍 Deep Research & Idea Generation++<table>+<tr>+<td width="33%" align="center">++<img src="/deepresearch.gif" alt="Deep research with web and paper search demo" width="100%">++**Deep Research**+Web and Paper Search with Literature Review++</td>+<td width="33%" align="center">++<img src="/ideagen.gif" alt="Automated idea generation demo" width="100%">++**Automated IdeaGen**+Systematic Brainstorming and Concept Synthesis++</td>+<td width="33%" align="center">++<img src="/co-writer.gif" alt="Interactive idea generation demo" width="100%">++**Interactive IdeaGen**+RAG-powered Idea Generation with Multi-Source Insights++</td>+</tr>+</table>++<!-- Knowledge Infrastructure -->++### 🏗️ All-in-One Knowledge System++<table>+<tr>+<td width="50%" align="center">++<img src="/knowledge_bases.png" alt="Personal knowledge base demo" width="100%">++**Personal Knowledge Base**+Build and Organize Your Own Knowledge Repository++</td>+<td width="50%" align="center">++<img src="/notebooks.png" alt="Personal notebook demo" width="100%">++**Personal Notebook**+Your Contextual Memory for Learning Sessions++</td>+</tr>+</table>diff --git a/docs/guide/configuration.md b/docs/guide/configuration.mdindex 660dbdfca..3d2c16703 100644--- a/docs/guide/configuration.md+++ b/docs/guide/configuration.md@@ -1,31 +1,25 @@# Configuration-## Config Files+DeepTutor uses YAML configuration files and environment variables for easy customization.++## 📁 Configuration Files++```+config/+├── main.yaml # Main system configuration (paths, tools, module settings)+├── agents.yaml # Unified agent parameters (temperature, max_tokens)+└── README.md # Full documentation+```| File | Purpose ||:-----|:--------|-| `.env` | API keys, ports, providers |-| `config/agents.yaml` | LLM parameters (temperature, max_tokens) |+| `.env` | API keys, server ports, and service configuration |+| `config/agents.yaml` | LLM parameters for each agent module || `config/main.yaml` | Paths, tools, module settings |-## Environment Variables--### Required--```bash-# LLM-LLM_MODEL=gpt-4o-LLM_API_KEY=your_api_key-LLM_HOST=https://api.openai.com/v1--# Embedding-EMBEDDING_MODEL=text-embedding-3-large-EMBEDDING_API_KEY=your_api_key-EMBEDDING_HOST=https://api.openai.com/v1-EMBEDDING_DIMENSION=3072-```+## 🔧 Server Configuration-### Optional+Server ports are configured in `.env` file:```bash# Server ports (defaults: 8001/3782)@@ -72,32 +66,150 @@ EMBEDDING_API_VERSION=2024-02-15-previewEdit `config/agents.yaml`:```yaml+# Solve Module - Problem solving agentssolve:temperature: 0.3max_tokens: 8192+# Research Module - Deep research agentsresearch:temperature: 0.5max_tokens: 12000+# Question Module - Question generation agentsquestion:temperature: 0.7max_tokens: 4096++# Guide Module - Learning guidance agents+guide:+ temperature: 0.5+ max_tokens: 8192++# IdeaGen Module - Idea generation agents+ideagen:+ temperature: 0.7+ max_tokens: 4096++# CoWriter Module - Collaborative writing agents+co_writer:+ temperature: 0.7+ max_tokens: 4096+```++## 🔑 Environment Variables++Create a `.env` file based on `.env.example`:++```bash+# ============================================================================+# Server Configuration+# ============================================================================+BACKEND_PORT=8001 # Backend API port+FRONTEND_PORT=3782 # Frontend web port++# For remote/LAN access - set to your server's IP address+# Example: http://192.168.1.100:8001 (if not set, defaults to localhost)+# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001++# ============================================================================+# LLM (Large Language Model) Configuration - Required+# ============================================================================+LLM_BINDING=openai # Provider type (see supported list below)+LLM_MODEL=gpt-4o # e.g., gpt-4o, deepseek-chat, qwen-plus+LLM_HOST=https://api.openai.com/v1+LLM_API_KEY=your_api_key+DISABLE_SSL_VERIFY=false # Set true for self-signed certificates++# ============================================================================+# Embedding Model Configuration - Required for Knowledge Base+# ============================================================================+EMBEDDING_BINDING=openai # Provider type (see supported list below)+EMBEDDING_MODEL=text-embedding-3-large # e.g., text-embedding-3-large, nomic-embed-text+EMBEDDING_DIMENSION=3072 # Important! Must match model dimensions+EMBEDDING_HOST=https://api.openai.com/v1+EMBEDDING_API_KEY=your_api_key++# ============================================================================+# Web Search Configuration - Optional+# ============================================================================+SEARCH_PROVIDER=perplexity # Options: perplexity, baidu+PERPLEXITY_API_KEY=your_perplexity_key+BAIDU_API_KEY=your_baidu_key # For Baidu AI Search (百度AI搜索)++# ============================================================================+# TTS (Text-to-Speech) Configuration - Optional+# ============================================================================+TTS_MODEL=+TTS_URL=+TTS_API_KEY=```-## Data Locations+## 🔌 Supported Providers++### LLM Providers++| Provider | `LLM_BINDING` Value | Notes |+|:---------|:--------------------|:------|+| OpenAI | `openai` | GPT-4o, GPT-4, GPT-3.5, etc. |+| Anthropic | `anthropic` | Claude 3.5, Claude 3, etc. |+| Azure OpenAI | `azure_openai` | Enterprise deployments |+| Ollama | `ollama` | Local models (auto adds `/v1` suffix) |+| Groq | `groq` | Fast inference |+| OpenRouter | `openrouter` | Multi-model gateway |+| DeepSeek | `deepseek` | DeepSeek-V3, DeepSeek-R1 |+| Google Gemini | `gemini` | OpenAI-compatible mode |++### Embedding Providers++| Provider | `EMBEDDING_BINDING` Value | Notes |+|:---------|:--------------------------|:------|+| OpenAI | `openai` | text-embedding-3-large/small |+| Azure OpenAI | `azure_openai` | Enterprise deployments |+| Jina AI | `jina` | jina-embeddings-v3 |+| Cohere | `cohere` | embed-v3 series |+| Ollama | `ollama` | Local embedding models |+| LM Studio | `lm_studio` | Local inference server |+| HuggingFace | `huggingface` | OpenAI-compatible endpoints |++> **Note**: Ensure that `EMBEDDING_DIMENSION` matches your embedding model's output dimensions. The RAG module uses RAG-Anything—see [the repository](https://github.com/HKUDS/RAG-Anything) for details.++## 🛠️ Tool Configuration++Configure tool availability in `config/main.yaml`:++```yaml+tools:+ rag_tool:+ kb_base_dir: ./data/knowledge_bases+ default_kb: ai_textbook+ run_code:+ workspace: ./data/user/run_code_workspace+ web_search:+ enabled: true # Global switch for web search+ query_item:+ enabled: true+ max_results: 5+```++## 📂 Data Storage++All user content and system data are stored in the `data/` directory:```data/-├── knowledge_bases/ # Your uploaded documents-└── user/- ├── solve/ # Problem solving outputs- ├── question/ # Generated questions- ├── research/ # Research reports- ├── guide/ # Learning sessions- └── logs/ # System logs+├── knowledge_bases/ # Knowledge base storage+└── user/ # User activity data+ ├── solve/ # Problem solving results+ ├── question/ # Generated questions+ ├── research/ # Research reports and cache+ ├── co_writer/ # Interactive IdeaGen documents+ ├── notebook/ # Notebook records+ ├── guide/ # Guided learning sessions+ ├── logs/ # System logs+ └── run_code_workspace/ # Code execution workspace```----+## 🔗 Advanced Configuration-📖 **Full reference**: [config/README.md](https://github.com/HKUDS/DeepTutor/tree/main/config)+For the full configuration reference, see [config/README.md](https://github.com/HKUDS/DeepTutor/tree/main/config).diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.mdindex 7842c3b0b..8ac42f98b 100644--- a/docs/guide/getting-started.md+++ b/docs/guide/getting-started.md@@ -17,59 +17,130 @@ Get DeepTutor running in under 5 minutes.git clone https://github.com/HKUDS/DeepTutor.gitcd DeepTutor-# Configure API keys-cp .env.example .env-# Edit .env with your API keys+## Step 1: Set Up Virtual Environment (Choose One Option)++# Option A: Using conda (Recommended)+conda create -n aitutor python=3.10+conda activate aitutor++# Option B: Using venv+python -m venv venv+# On Windows:+venv\Scripts\activate+# On macOS/Linux:+source venv/bin/activate+```++## Step 2: Install Dependencies-# Install and launch+Run the automated installation script to install all required dependencies:++```bash+# Recommended: Automated Installationbash scripts/install_all.sh-python scripts/start_web.py++# Alternative: Manual Installation+python scripts/install_all.py++# Or Install Dependencies Manually+pip install -r requirements.txt+npm install+```++## Step 3: Set Up Environment Variables++Create a `.env` file in the project root directory based on `.env.example`:++```bash+# Copy from .env.example template (if exists)+cp .env.example .env++# Then edit .env file with your API keys```-```bash [Docker]-docker run -d --name deeptutor \- -p 8001:8001 -p 3782:3782 \- -e LLM_MODEL=gpt-4o \- -e LLM_API_KEY=your-key \- -e LLM_HOST=https://api.openai.com/v1 \- -e EMBEDDING_MODEL=text-embedding-3-large \- -e EMBEDDING_API_KEY=your-key \- -e EMBEDDING_HOST=https://api.openai.com/v1 \- ghcr.io/hkuds/deeptutor:latest+## Step 4: Configure Ports and LLM Settings *(Optional)*++By default, the application uses:+- **Backend (FastAPI)**: `8001`+- **Frontend (Next.js)**: `3782`++You can modify these ports in your `.env` file:++```bash+BACKEND_PORT=8001+FRONTEND_PORT=3782++# For remote/LAN access, set your server's IP address:+# NEXT_PUBLIC_API_BASE=http://192.168.1.100:8001```-:::+**LLM Configuration**: Agent settings for `temperature` and `max_tokens` are centralized in `config/agents.yaml`. Each module (guide, solve, research, question, ideagen, co_writer) has customizable parameters. See [Configuration](/guide/configuration) for details.++## Step 5: Try Our Demos *(Optional)*++Experience the system quickly with two pre-built knowledge bases and a collection of challenging questions with usage examples.++<details>+<summary><b>Research Papers Collection</b> — 5 papers (20-50 pages each)</summary>++A curated collection of 5 research papers from our lab covering RAG and Agent fields. This demo showcases broad knowledge coverage for research scenarios.++**Used Papers**: [AI-Researcher](https://github.com/HKUDS/AI-Researcher) | [AutoAgent](https://github.com/HKUDS/AutoAgent) | [RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [LightRAG](https://github.com/HKUDS/LightRAG) | [VideoRAG](https://github.com/HKUDS/VideoRAG)++</details>++<details>+<summary><b>Data Science Textbook</b> — 8 chapters, 296 pages</summary>-## Essential `.env` Variables+A comprehensive data science textbook with challenging content. This demo showcases **deep knowledge depth** for learning scenarios.++**Book Link**: [Deep Representation Learning Book](https://ma-lab-berkeley.github.io/deep-representation-learning-book/)+</details>++**Download and Setup:**++1. Download the demo package: [Google Drive](https://drive.google.com/drive/folders/1iWwfZXiTuQKQqUYb5fGDZjLCeTUP6DA6?usp=sharing)+2. Extract the compressed files directly into the `data/` directory+3. Knowledge bases will be automatically available once you start the system++> **Note:** Our **demo knowledge bases** use `text-embedding-3-large` with `dimensions = 3072`. Ensure your embeddings model has matching dimensions (3072) for compatibility.++## Step 6: Launch the Application```bash-# Required-LLM_MODEL=gpt-4o-LLM_API_KEY=your_api_key-LLM_HOST=https://api.openai.com/v1--EMBEDDING_MODEL=text-embedding-3-large-EMBEDDING_API_KEY=your_api_key-EMBEDDING_HOST=https://api.openai.com/v1+# Activate virtual environment+conda activate aitutor # or: source venv/bin/activate++# Start web interface (frontend + backend)+python scripts/start_web.py++# Alternative: CLI interface only+python scripts/start.py++# Stop the service: Ctrl+C```-> 📖 **Full configuration options**: See [Configuration](/guide/configuration) or [README](https://github.com/HKUDS/DeepTutor#step-1-pre-configuration)+## Step 7: Create Your Own Knowledge Base-## Access Points+Create custom knowledge bases through the web interface with support for multiple file formats.-| Service | URL |-|:--------|:----|-| **Web App** | http://localhost:3782 |-| **API Docs** | http://localhost:8001/docs |+1. **Access Knowledge Base**: Navigate to `http://localhost:3782/knowledge`+2. **Create New Base**: Click "New Knowledge Base"+3. **Configure Settings**: Enter a unique name for your knowledge base+4. **Upload Content**: Add single or multiple files for batch processing+5. **Monitor Progress**: Track processing status in the terminal running `start_web.py`+ - Large files may take several minutes to complete+ - Knowledge base becomes available once processing finishes-## Your First Knowledge Base+> **Tips:** Large files may require several minutes to process. Multiple files can be uploaded simultaneously for efficient batch processing.-1. Navigate to http://localhost:3782/knowledge-2. Click **"New Knowledge Base"**-3. Upload PDF, TXT, or Markdown files-4. Wait for processing to complete+## Access URLs-That's it! Start exploring with the **Solver**, **Question Generator**, or **Deep Research** modules.+| Service | URL | Description |+|:---:|:---|:---|+| **Frontend** | `http://localhost:3782` | Main web interface |+| **API Docs** | `http://localhost:8001/docs` | Interactive API documentation |+| **Health** | `http://localhost:8001/api/v1/knowledge/health` | System health check |## Next Stepsdiff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex cf96b0127..37803c3ff 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -1,50 +1,170 @@-# Troubleshooting+# ❓ FAQ-Quick solutions for common issues.+## Backend fails to start?-## Startup Issues+**Checklist**+- Confirm Python version >= 3.10+- Confirm all dependencies installed: `pip install -r requirements.txt`+- Check if port 8001 is in use (configurable in `config/main.yaml`)+- Check `.env` file configuration-| Problem | Solution |-|:--------|:---------|-| Backend fails to start | Check Python ≥ 3.10, verify `.env` config |-| `npm: command not found` | Install Node.js: `conda install -c conda-forge nodejs` |-| Port already in use | Kill process: `lsof -i :8001` → `kill -9 <PID>` |-| Long path errors on Windows when cloning the repo or installing dependencies | Enable long paths*: Run as admin `reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f`, then restart your terminal |+**Solutions**+- **Change port**: Edit `config/main.yaml` server.backend_port+- **Check logs**: Review terminal error messages-* Restart your terminal and, if the issue persists, log out and back in (or restart Windows) for the registry change to fully take effect.-## Connection Issues+----| Problem | Solution |-|:--------|:---------|-| Frontend can't reach backend | Verify backend at http://localhost:8001/docs |-| WebSocket fails | Check firewall, confirm `ws://localhost:8001/api/v1/...` format |-| Remote access fails | Set `NEXT_PUBLIC_API_BASE=http://your-ip:8001` in `.env` |+## Port occupied after Ctrl+C?-## Docker Issues+**Problem**-| Problem | Solution |-|:--------|:---------|-| Cloud frontend won't connect | Set `NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server:8001` |-| Wrong architecture | Check with `uname -m`: use `:latest` (AMD64) or `:latest-arm64` (ARM) |+After pressing Ctrl+C during a running task (e.g., deep research), restarting shows "port already in use" error.-## Knowledge Base+**Cause**-| Problem | Solution |-|:--------|:---------|-| Processing stuck | Check terminal logs, verify API keys |-| `uvloop.Loop` error | Run: `./scripts/extract_numbered_items.sh <kb_name>` |+Ctrl+C sometimes only terminates the frontend process while the backend continues running in the background.-## Kill Background Processes+**Solution**```bash# macOS/Linux-lsof -i :8001 && kill -9 <PID>+kill -9 $(lsof -t -i :8001)# Windowsnetstat -ano | findstr :8001taskkill /PID <PID> /F```+Then restart the service with `python scripts/start_web.py`.++---++## npm: command not found error?++**Problem**++Running `scripts/start_web.py` shows `npm: command not found` or exit status 127.++**Checklist**+- Check if npm is installed: `npm --version`+- Check if Node.js is installed: `node --version`+- Confirm conda environment is activated (if using conda)++**Solutions**+```bash+# Option A: Using Conda (Recommended)+conda install -c conda-forge nodejs++# Option B: Using Official Installer+# Download from https://nodejs.org/++# Option C: Using nvm+nvm install 18+nvm use 18+```++**Verify Installation**+```bash+node --version # Should show v18.x.x or higher+npm --version # Should show version number+```++---++## Frontend cannot connect to backend?++**Checklist**+- Confirm backend is running (visit `http://localhost:8001/docs`)+- Check browser console for error messages++**Solution**++Create `.env.local` in `web` directory:++```bash+NEXT_PUBLIC_API_BASE=http://localhost:8001+```++---++## WebSocket connection fails?++**Checklist**+- Confirm backend is running+- Check firewall settings+- Confirm WebSocket URL is correct++**Solution**+- **Check backend logs**+- **Confirm URL format**: `ws://localhost:8001/api/v1/...`+----📖 **Full FAQ**: [GitHub README](https://github.com/HKUDS/DeepTutor#-faq)+## Where are module outputs stored?++| Module | Output Path |+|:---:|:---|+| Solve | `data/user/solve/solve_YYYYMMDD_HHMMSS/` |+| Question | `data/user/question/question_YYYYMMDD_HHMMSS/` |+| Research | `data/user/research/reports/` |+| Interactive IdeaGen | `data/user/co-writer/` |+| Notebook | `data/user/notebook/` |+| Guide | `data/user/guide/session_{session_id}.json` |+| Logs | `data/user/logs/` |++---++## How to add a new knowledge base?++**Web Interface**+1. Visit `http://localhost:3782/knowledge`+2. Click "New Knowledge Base"+3. Enter knowledge base name+4. Upload PDF/TXT/MD documents+5. System will process documents in background++**CLI**+```bash+python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>+```++---++## How to incrementally add documents to existing KB?++**CLI (Recommended)**+```bash+python -m src.knowledge.add_documents <kb_name> --docs <new_document.pdf>+```++**Benefits**+- Only processes new documents, saves time and API costs+- Automatically merges with existing knowledge graph+- Preserves all existing data++---++## Numbered items extraction failed with uvloop.Loop error?++**Problem**++When initializing a knowledge base, you may encounter this error:+```text+ValueError: Can't patch loop of type <class 'uvloop.Loop'>+```++This occurs because Uvicorn uses `uvloop` event loop by default, which is incompatible with `nest_asyncio`.++**Solution**++Use one of the following methods to extract numbered items:++```bash+# Option 1: Using the shell script (recommended)+./scripts/extract_numbered_items.sh <kb_name>++# Option 2: Direct Python command+python src/knowledge/extract_numbered_items.py --kb <kb_name> --base-dir ./data/knowledge_bases+```++This will extract numbered items (Definitions, Theorems, Equations, etc.) from your knowledge base without reinitializing it.diff --git a/docs/index.md b/docs/index.mdindex 8ce7bda94..5e587a387 100644--- a/docs/index.md+++ b/docs/index.md@@ -20,6 +20,12 @@ hero:link: /roadmapfeatures:+ - icon: 📚+ title: Massive Document Q&A+ details: Upload textbooks, papers, and manuals. Build AI-powered knowledge repositories with RAG and knowledge graph integration.+ - icon: 🎨+ title: Interactive Visualization+ details: Transform complex concepts into visual aids with step-by-step breakdowns and engaging interactive demonstrations.- icon: 🧠title: Smart Problem Solvingdetails: Dual-loop reasoning with step-by-step solutions and precise citations from your documents.@@ -34,12 +40,32 @@ features:details: Systematic topic exploration with web search, paper retrieval, and literature synthesis.- icon: 💡title: Idea Generation- details: Brainstorm research ideas with automated concept synthesis and novelty evaluation.- - icon: ✏️- title: Co-Writer- details: AI-assisted writing with smart editing, auto-annotation, and TTS narration.+ details: Automated and interactive concept development with multi-source insights and novelty evaluation.---+## Why DeepTutor?++DeepTutor transforms how students interact with educational materials through a unified multi-agent architecture. Unlike traditional tools, it provides:++- **Deep Understanding** - Not just answers, but guided learning journeys with visual explanations+- **Multi-Modal Support** - PDF, LaTeX, images, code execution, and more+- **Knowledge Graph** - Semantic connections powered by LightRAG for better comprehension+- **All-in-One Platform** - Problem solving, question generation, research, and idea generation++## Quick Demo++```bash+# Clone and setup+git clone https://github.com/HKUDS/DeepTutor.git+cd DeepTutor++# Install dependencies+bash scripts/install_all.sh++# Start the application+python scripts/start_web.py+```+<style>:root {--vp-home-hero-name-color: transparent;@@ -74,13 +100,13 @@ features:}/* Hero 区域 Roadmap 按钮特殊样式 */-.VPButton.alt[href="/DeepTutor/roadmap"] {+.VPButton.alt[href="/roadmap"] {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;color: white !important;border: none !important;}-.VPButton.alt[href="/DeepTutor/roadmap"]:hover {+.VPButton.alt[href="/roadmap"]:hover {box-shadow: 0 4px 16px rgba(102, 126, 234, 0.5);transform: translateY(-2px);}diff --git a/docs/roadmap.md b/docs/roadmap.mdindex 9edad611f..c0e530452 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -1,177 +1,41 @@# Roadmap-## ⚡ Current Focus+Our vision for DeepTutor's future development.-- 🔄 **More RAG Pipelines** — Expanding retrieval architectures and backends-- **Database Robustness & Visualization** — Stability improvements and visual insights-- 🔄 **Bug Fixing** — Addressing reported issues and edge cases+## ✅ Recently Completed (v0.4.0)-## 📬 Received Feature Wishlist+- [x] **RAG Module Decoupling** — Modular RAG architecture with provider-agnostic interface+ - Currently supports RAG-Anything (MinerU + LightRAG)+ - More backends coming soon+- [x] **Multi-Provider Support** — Expanded LLM and Embedding provider options+ - LLM: OpenAI, Anthropic, Azure, Ollama, Groq, OpenRouter, DeepSeek, Gemini+ - Embedding: OpenAI, Jina, Cohere, Ollama, LM Studio, HuggingFace+- [x] **Dark Mode** — System-wide dark/light theme support+- [x] **Environment Configuration** — Unified `.env` based configuration-Community-requested features we're considering:+## 🚀 Planned Features-- 👥 **Multi-user Collaborative Learning** — Real-time shared sessions-- 🎓 **Generalized Guided Learning** — Broader adaptive learning paths-- 📝 **Automatic Note Generation** — AI-powered summary and note creation+- [ ] **Deepcoding from Idea Generation** — Transform research ideas into working prototypes+- [ ] **Personalized Memory** — Adapt tutoring style based on user learning history+- [ ] **Additional RAG Backends** — LlamaIndex, ChromaDB, Pinecone integration+- [ ] **More Embedding Adapters** — Voyage AI, Mixedbread, local transformers------<div class="community-wrapper">--<div class="community-header">- <h2>🤝 Shape the Future !</h2>- <p>DeepTutor is built by the community, for the community.</p>-</div>--<div class="community-grid">--<div class="community-card">- <div class="card-icon">💡</div>- <div class="card-title">Ideas</div>- <div class="card-desc">Share feedback & propose features</div>- <div class="card-links">- <div class="link-row">- <a href="https://discord.gg/zpP9cssj" class="discord">Discord</a>- <a href="https://github.com/HKUDS/DeepTutor/issues/78" class="wechat">WeChat</a>- </div>- <div class="link-row">- <a href="https://github.com/HKUDS/DeepTutor/discussions" class="github">GitHub Discussions</a>- </div>- </div>-</div>--<div class="community-card">- <div class="card-icon">🔧</div>- <div class="card-title">Code</div>- <div class="card-desc">PRs welcome on <code>dev</code> branch</div>- <div class="card-links">- <a href="https://github.com/HKUDS/DeepTutor/blob/main/CONTRIBUTING.md" class="github">Contributing Guide →</a>- </div>-</div>--</div>--</div>--<style>-.community-wrapper {- margin-top: 24px;- padding: 40px;- background: linear-gradient(135deg, rgba(102, 126, 234, 0.03) 0%, rgba(118, 75, 162, 0.03) 100%);- border: 1px solid rgba(102, 126, 234, 0.1);- border-radius: 16px;-}--.community-header {- text-align: center;- margin-bottom: 32px;-}+## 💭 Under Consideration-.community-header h2 {- margin: 0 0 8px;- font-size: 1.6rem;- border: none;-}+- Multi-language support+- Mobile-friendly interface+- Collaborative learning features+- Voice interaction support+- Faster frontend framework-.community-header p {- margin: 0;- color: var(--vp-c-text-2);- font-size: 1rem;-}+## 🤝 Community Requests-.community-grid {- display: grid;- grid-template-columns: repeat(2, 1fr);- gap: 20px;- max-width: 600px;- margin: 0 auto;-}+Have a feature idea? We'd love to hear it!-@media (max-width: 640px) {- .community-grid {- grid-template-columns: 1fr;- }-}+- Open a [Feature Request](https://github.com/HKUDS/DeepTutor/issues/new?template=feature_request.yml)+- Join the discussion on existing proposals+- Check our [GitHub Discussions](https://github.com/HKUDS/DeepTutor/discussions)-.community-card {- background: var(--vp-c-bg);- border: 1px solid var(--vp-c-divider);- border-radius: 12px;- padding: 24px;- text-align: center;- transition: all 0.25s ease;-}--.community-card:hover {- border-color: rgba(102, 126, 234, 0.4);- box-shadow: 0 4px 20px rgba(102, 126, 234, 0.08);- transform: translateY(-2px);-}--.card-icon {- font-size: 2rem;- margin-bottom: 12px;-}--.card-title {- font-size: 1.15rem;- font-weight: 600;- margin-bottom: 6px;- color: var(--vp-c-text-1);-}--.card-desc {- font-size: 0.9rem;- color: var(--vp-c-text-2);- margin-bottom: 16px;-}--.card-links {- display: flex;- flex-direction: column;- align-items: center;- gap: 8px;-}--.link-row {- display: flex;- gap: 8px;- justify-content: center;-}--.card-links a {- font-size: 0.85rem;- font-weight: 500;- text-decoration: none;- padding: 6px 14px;- border-radius: 6px;- transition: all 0.2s;-}--/* Discord - 蓝紫色 */-.card-links a.discord {- color: #5865F2;- background: rgba(88, 101, 242, 0.1);-}-.card-links a.discord:hover {- background: rgba(88, 101, 242, 0.2);-}--/* WeChat - 绿色 */-.card-links a.wechat {- color: #07C160;- background: rgba(7, 193, 96, 0.1);-}-.card-links a.wechat:hover {- background: rgba(7, 193, 96, 0.2);-}+----/* GitHub - 深灰紫 */-.card-links a.github {- color: #6e5494;- background: rgba(110, 84, 148, 0.1);-}-.card-links a.github:hover {- background: rgba(110, 84, 148, 0.2);-}-</style>+⭐ **Star the repo** to follow our future updates!diff --git a/docs/zh/guide/configuration.md b/docs/zh/guide/configuration.mdindex 29d6cff68..be7e74b4b 100644--- a/docs/zh/guide/configuration.md+++ b/docs/zh/guide/configuration.md@@ -65,7 +65,7 @@ question:## 数据存储位置-```+```textdata/├── knowledge_bases/ # 你上传的文档└── user/diff --git a/docs/zh/guide/troubleshooting.md b/docs/zh/guide/troubleshooting.mdindex 4c76f76f0..4bccdce0d 100644--- a/docs/zh/guide/troubleshooting.md+++ b/docs/zh/guide/troubleshooting.md@@ -14,7 +14,7 @@| 问题 | 解决方案 ||:--------|:---------|-| 前端无法连接后端 | 确认后端运行在 http://localhost:8001/docs |+| 前端无法连接后端 | 确认后端运行在 <http://localhost:8001/docs> || WebSocket 连接失败 | 检查防火墙,确认 `ws://localhost:8001/api/v1/...` 格式 || 远程访问失败 | 在 `.env` 中设置 `NEXT_PUBLIC_API_BASE=http://your-ip:8001` |diff --git a/pyproject.toml b/pyproject.tomlindex 4d6323870..31bc048d7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -7,12 +7,23 @@ build-backend = "setuptools.build_meta"[project]name = "ai-tutor"-version = "0.1.0"+version = "0.4.1"description = "An intelligent learning companion with multi-agent collaboration and RAG"requires-python = ">=3.10"readme = "README.md"license = {text = "Apache-2.0"}+# Optional dependencies for different LLM providers+[project.optional-dependencies]+anthropic = ["anthropic>=0.30.0"]+dashscope = ["dashscope>=1.14.0"]+search = ["perplexityai>=0.1.0"]+all = [+ "anthropic>=0.30.0",+ "dashscope>=1.14.0",+ "perplexityai>=0.1.0"+]+# ============================================# Black code formatter configuration# ============================================@@ -156,3 +167,16 @@ split-on-trailing-comma = true# ============================================[tool.ruff.lint.mccabe]max-complexity = 10++# ============================================+# Pytest configuration+# ============================================+[tool.pytest.ini_options]+testpaths = ["tests"]+pythonpath = ["."]+addopts = [+ "--strict-markers",+ "--strict-config",+ "--disable-warnings",+ "--tb=short"+]diff --git a/requirements.txt b/requirements.txtindex 192a20bf5..b003de7f6 100644--- a/requirements.txt+++ b/requirements.txt@@ -26,6 +26,7 @@ urllib3>=2.2.1# Async support# ============================================nest_asyncio>=1.5.8+tenacity>=8.0.0# ============================================# Web framework and server@@ -50,13 +51,13 @@ arxiv>=2.0.0# ============================================# Scientific computing (for RAG and code execution)# ============================================-numpy>=1.24.0+numpy>=1.24.0,<2.0.0 # NumPy 1.24+ required for array API, <2.0 for compatibility# matplotlib>=3.7.0 # Uncomment if needed for plotting# scipy>=1.11.0 # Uncomment if needed for scientific computing# pandas>=2.0.0 # Uncomment if needed for data analysis# PDF parsing-PyMuPDF>=1.23.0 # For PDF text extraction (fast and reliable)+PyMuPDF>=1.26.0 # For PDF text extraction (fast and reliable)# Vector search (optional but recommended for llamaindex pipeline)# faiss-cpu>=1.7.4 # Uncomment for CPU-only FAISS support (faster search)diff --git a/src/agents/base_agent.py b/src/agents/base_agent.pyindex 11c5cad88..2332be34d 100644--- a/src/agents/base_agent.py+++ b/src/agents/base_agent.py@@ -25,12 +25,12 @@ _project_root = Path(__file__).parent.parent.parentif str(_project_root) not in sys.path:sys.path.insert(0, str(_project_root))+from src.config.settings import settingsfrom src.logging import LLMStats, get_loggerfrom src.services.config import get_agent_paramsfrom src.services.llm import complete as llm_complete-from src.services.llm import get_llm_config, get_token_limit_kwargs+from src.services.llm import get_llm_config, get_token_limit_kwargs, supports_response_formatfrom src.services.llm import stream as llm_stream-from src.services.llm import supports_response_formatfrom src.services.prompt import get_prompt_manager@@ -61,6 +61,7 @@ class BaseAgent(ABC):model: str | None = None,api_version: str | None = None,language: str = "zh",+ binding: str = "openai",config: dict[str, Any] | None = None,token_tracker: Any | None = None,log_dir: str | None = None,@@ -74,7 +75,9 @@ class BaseAgent(ABC):api_key: API key (optional, defaults to environment variable)base_url: API endpoint (optional, defaults to environment variable)model: Model name (optional, defaults to environment variable)+ api_version: API version for Azure OpenAI (optional)language: Language setting ('zh' | 'en'), default 'zh'+ binding: Provider binding type (optional, defaults to 'openai')config: Optional configuration dictionarytoken_tracker: Optional external TokenTracker instancelog_dir: Optional log directory path@@ -102,12 +105,14 @@ class BaseAgent(ABC):self.base_url = base_url or env_llm.base_urlself.model = model or env_llm.modelself.api_version = api_version or getattr(env_llm, "api_version", None)+ self.binding = binding or getattr(env_llm, "binding", "openai")except ValueError:# Fallback if env config not availableself.api_key = api_key or os.getenv("LLM_API_KEY")self.base_url = base_url or os.getenv("LLM_HOST")self.model = model or os.getenv("LLM_MODEL")self.api_version = api_version or os.getenv("LLM_API_VERSION")+ self.binding = binding# Get Agent-specific configuration (if config provided)self.agent_config = self.config.get("agents", {}).get(agent_name, {})@@ -206,7 +211,7 @@ class BaseAgent(ABC):Returns:Retry count"""- return self.agent_config.get("max_retries", self.llm_config.get("max_retries", 3))+ return self.agent_config.get("max_retries", settings.retry.max_retries)# -------------------------------------------------------------------------# Token Tracking@@ -343,6 +348,7 @@ class BaseAgent(ABC):model = model or self.get_model()temperature = temperature if temperature is not None else self.get_temperature()max_tokens = max_tokens if max_tokens is not None else self.get_max_tokens()+ max_retries = self.get_max_retries()# Record call start timestart_time = time.time()@@ -367,9 +373,7 @@ class BaseAgent(ABC):if supports_response_format(binding, model):kwargs["response_format"] = response_formatelse:- self.logger.debug(- f"response_format not supported for {binding}/{model}, skipping"- )+ self.logger.debug(f"response_format not supported for {binding}/{model}, skipping")if messages:kwargs["messages"] = messages@@ -395,6 +399,7 @@ class BaseAgent(ABC):api_key=self.api_key,base_url=self.base_url,api_version=self.api_version,+ max_retries=max_retries,**kwargs,)except Exception as e:diff --git a/src/agents/co_writer/edit_agent.py b/src/agents/co_writer/edit_agent.pyindex 6a68441d7..37317111f 100644--- a/src/agents/co_writer/edit_agent.py+++ b/src/agents/co_writer/edit_agent.py@@ -87,7 +87,9 @@ class EditAgent(BaseAgent):if source == "rag":if not kb_name:- self.logger.warning("RAG source selected but no kb_name provided, skipping RAG search")+ self.logger.warning(+ "RAG source selected but no kb_name provided, skipping RAG search"+ )source = Noneelse:self.logger.info(f"Searching RAG in KB: {kb_name} for: {instruction}")@@ -136,9 +138,7 @@ class EditAgent(BaseAgent):source = None# Build prompts- system_prompt = self.get_prompt(- "system", "You are an expert editor and writing assistant."- )+ system_prompt = self.get_prompt("system", "You are an expert editor and writing assistant.")action_verbs = {"rewrite": "Rewrite", "shorten": "Shorten", "expand": "Expand"}action_verb = action_verbs.get(action, "Rewrite")diff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.pyindex 6099f89c0..ed7bb6a4c 100644--- a/src/agents/co_writer/narrator_agent.py+++ b/src/agents/co_writer/narrator_agent.py@@ -10,7 +10,7 @@ import jsonimport osfrom pathlib import Pathimport re-from typing import Any+from typing import Any, Optionalfrom urllib.parse import urlparseimport uuid@@ -21,7 +21,6 @@ from src.services.config import load_config_with_mainfrom src.services.tts import get_tts_config# Import shared stats from edit_agent for legacy compatibility-from .edit_agent import get_stats# Define storage path (unified under user/co-writer/ directory)USER_DIR = Path(__file__).parent.parent.parent.parent / "data" / "user" / "co-writer" / "audio"@@ -42,16 +41,17 @@ class NarratorAgent(BaseAgent):agent_name="narrator_agent",language=language,)-+# Override prompts to load from co_writer module# (narrator_agent prompts are stored under co_writer/prompts/)from src.services.prompt import get_prompt_manager+self.prompts = get_prompt_manager().load_prompts(module_name="co_writer",agent_name="narrator_agent",language=language,)-+# Load TTS-specific configurationself._load_tts_config()@@ -128,7 +128,13 @@ class NarratorAgent(BaseAgent):self.logger.info(f" API Key: {api_key_preview}")self.logger.info(f" Default Voice: {self.default_voice}")- async def process(self, content: str, style: str = "friendly", voice: str = None, skip_audio: bool = False) -> dict[str, Any]:+ async def process(+ self,+ content: str,+ style: str = "friendly",+ voice: Optional[str] = None,+ skip_audio: bool = False,+ ) -> dict[str, Any]:"""Main processing method - alias for narrate().diff --git a/src/agents/guide/agents/chat_agent.py b/src/agents/guide/agents/chat_agent.pyindex 6b2b42f6d..69672ca0a 100644--- a/src/agents/guide/agents/chat_agent.py+++ b/src/agents/guide/agents/chat_agent.py@@ -27,6 +27,7 @@ class ChatAgent(BaseAgent):base_url=base_url,api_version=api_version,language=language,+ binding=binding,)def _format_chat_history(self, history: list[dict[str, str]]) -> str:diff --git a/src/agents/guide/agents/locate_agent.py b/src/agents/guide/agents/locate_agent.pyindex 32d6d33fa..da48515dc 100644--- a/src/agents/guide/agents/locate_agent.py+++ b/src/agents/guide/agents/locate_agent.py@@ -5,7 +5,7 @@ Analyzes notebook content and generates progressive knowledge point learning pla"""import json-from typing import Any+from typing import Any, Optionalfrom src.agents.base_agent import BaseAgent@@ -18,7 +18,7 @@ class LocateAgent(BaseAgent):api_key: str,base_url: str,language: str = "zh",- api_version: str | None = None,+ api_version: Optional[str] = None,binding: str = "openai",):super().__init__(@@ -28,6 +28,7 @@ class LocateAgent(BaseAgent):base_url=base_url,api_version=api_version,language=language,+ binding=binding,)def _format_records(self, records: list[dict[str, Any]]) -> str:diff --git a/src/agents/question/agents/base_agent.py b/src/agents/question/agents/base_agent.pyindex ca93be2c3..a8535d016 100644--- a/src/agents/question/agents/base_agent.py+++ b/src/agents/question/agents/base_agent.py@@ -123,6 +123,7 @@ class BaseAgent(ABC):if not self.model:from src.services.llm.exceptions import LLMConfigError+raise LLMConfigError("LLM_MODEL not configured. Please set it in .env or activate a provider.")diff --git a/src/agents/question/tools/question_extractor.py b/src/agents/question/tools/question_extractor.pyindex 6d1097a17..03b654351 100644--- a/src/agents/question/tools/question_extractor.py+++ b/src/agents/question/tools/question_extractor.py@@ -182,36 +182,80 @@ Please analyze the above exam paper content, extract all question information, atry:# Call LLM via unified Factory (async, so we need to run in event loop)- result_text = asyncio.run(- llm_complete(- prompt=user_prompt,- system_prompt=system_prompt,- model=model,- api_key=api_key,- base_url=base_url,- api_version=api_version,- binding=binding,- **llm_kwargs,+ loop = asyncio.get_event_loop()+ if loop.is_running():+ # We're in an existing event loop, run in a thread+ import concurrent.futures++ with concurrent.futures.ThreadPoolExecutor() as executor:+ future = executor.submit(+ asyncio.run,+ llm_complete(+ prompt=user_prompt,+ system_prompt=system_prompt,+ model=model,+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ binding=binding,+ **llm_kwargs,+ ),+ )+ result_text = future.result()+ else:+ # No running loop, use run_until_complete+ result_text = loop.run_until_complete(+ llm_complete(+ prompt=user_prompt,+ system_prompt=system_prompt,+ model=model,+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ binding=binding,+ **llm_kwargs,+ ))- )-+ except RuntimeError as e:+ if "already running" in str(e):+ # Fallback: use asyncio.run in a thread+ import concurrent.futures++ with concurrent.futures.ThreadPoolExecutor() as executor:+ future = executor.submit(+ asyncio.run,+ llm_complete(+ prompt=user_prompt,+ system_prompt=system_prompt,+ model=model,+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ binding=binding,+ **llm_kwargs,+ ),+ )+ result_text = future.result()+ else:+ raise++ # Parse JSON response+ try:+ if not result_text:+ raise ValueError("LLM returned empty or None response")result = json.loads(result_text)-- questions = result.get("questions", [])- print(f"✓ Successfully extracted {len(questions)} questions")-- return questions-except json.JSONDecodeError as e:print(f"✗ JSON parsing error: {e!s}")print(f"LLM response content: {result_text[:500]}...")- return []- except Exception as e:- print(f"✗ LLM call failed: {e!s}")- import traceback+ raise ValueError(+ f"Failed to parse LLM JSON response: {e}. "+ f"Raw response (first 500 chars): {result_text[:500]!r}"+ ) from e++ questions = result.get("questions", [])+ print(f"✓ Successfully extracted {len(questions)} questions")- traceback.print_exc()- return []+ return questionsdef save_questions_json(questions: list[dict[str, Any]], output_dir: Path, paper_name: str) -> Path:diff --git a/src/agents/question/validation_workflow.py b/src/agents/question/validation_workflow.pyindex 1494ddacb..bf727e5e2 100644--- a/src/agents/question/validation_workflow.py+++ b/src/agents/question/validation_workflow.py@@ -75,6 +75,7 @@ class QuestionValidationWorkflow:if not self.model:from src.services.llm.exceptions import LLMConfigError+raise LLMConfigError("LLM_MODEL not configured. Please set it in .env or activate a provider.")@@ -191,13 +192,14 @@ Output the retrieval query directly, no additional content.response_content = response_content.strip()+ # Rough estimation: ~4 chars per token+ input_tokens_est = (len(system_prompt) + len(prompt)) // 4+ output_tokens_est = len(response_content) // 4+# Update token statistics if callback is availableif self.token_stats_callback:- # Rough estimation: ~4 chars per token- input_tokens = (len(system_prompt) + len(prompt)) // 4- output_tokens = len(response_content) // 4self.token_stats_callback(- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model+ input_tokens=input_tokens_est, output_tokens=output_tokens_est, model=self.model)# Log LLM call with detailed information@@ -208,9 +210,9 @@ Output the retrieval query directly, no additional content.user_prompt=prompt,response=response_content,agent_name="QuestionValidationWorkflow",- input_tokens=0,- output_tokens=0,- cost=0.0,+ input_tokens=input_tokens_est,+ output_tokens=output_tokens_est,+ cost=0.0, # Cost estimation would require pricing infolevel="DEBUG",)diff --git a/src/agents/research/agents/decompose_agent.py b/src/agents/research/agents/decompose_agent.pyindex 604711bcf..76f90042e 100644--- a/src/agents/research/agents/decompose_agent.py+++ b/src/agents/research/agents/decompose_agent.py@@ -27,9 +27,9 @@ class DecomposeAgent(BaseAgent):def __init__(self,config: dict[str, Any],- api_key: str = None,- base_url: str = None,- api_version: str = None,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,kb_name: str = "ai_textbook",):language = config.get("system", {}).get("language", "zh")diff --git a/src/agents/research/agents/manager_agent.py b/src/agents/research/agents/manager_agent.pyindex c46b3e34a..780114045 100644--- a/src/agents/research/agents/manager_agent.py+++ b/src/agents/research/agents/manager_agent.py@@ -23,9 +23,9 @@ class ManagerAgent(BaseAgent):def __init__(self,config: dict[str, Any],- api_key: str = None,- base_url: str = None,- api_version: str = None,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,):language = config.get("system", {}).get("language", "zh")super().__init__(diff --git a/src/agents/research/agents/note_agent.py b/src/agents/research/agents/note_agent.pyindex 9b3bbf643..2d2c46004 100644--- a/src/agents/research/agents/note_agent.py+++ b/src/agents/research/agents/note_agent.py@@ -8,7 +8,7 @@ Responsible for information compression and summary generation, converting raw dfrom pathlib import Pathfrom string import Templateimport sys-from typing import Any+from typing import Any, Optionalproject_root = Path(__file__).parent.parent.parent.parentsys.path.insert(0, str(project_root))@@ -25,9 +25,9 @@ class NoteAgent(BaseAgent):def __init__(self,config: dict[str, Any],- api_key: str = None,- base_url: str = None,- api_version: str = None,+ api_key: Optional[str] = None,+ base_url: Optional[str] = None,+ api_version: Optional[str] = None,):language = config.get("system", {}).get("language", "zh")super().__init__(diff --git a/src/agents/research/agents/rephrase_agent.py b/src/agents/research/agents/rephrase_agent.pyindex e66a17245..3fb4352eb 100644--- a/src/agents/research/agents/rephrase_agent.py+++ b/src/agents/research/agents/rephrase_agent.py@@ -23,9 +23,9 @@ class RephraseAgent(BaseAgent):def __init__(self,config: dict[str, Any],- api_key: str = None,- base_url: str = None,- api_version: str = None,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,):language = config.get("system", {}).get("language", "zh")super().__init__(diff --git a/src/agents/research/agents/research_agent.py b/src/agents/research/agents/research_agent.pyindex ecf59a833..7e7a29b98 100644--- a/src/agents/research/agents/research_agent.py+++ b/src/agents/research/agents/research_agent.py@@ -27,9 +27,9 @@ class ResearchAgent(BaseAgent):def __init__(self,config: dict[str, Any],- api_key: str = None,- base_url: str = None,- api_version: str = None,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,):language = config.get("system", {}).get("language", "zh")super().__init__(diff --git a/src/agents/solve/main_solver.py b/src/agents/solve/main_solver.pyindex 55b13275a..21328d087 100644--- a/src/agents/solve/main_solver.py+++ b/src/agents/solve/main_solver.py@@ -12,19 +12,12 @@ from datetime import datetimeimport jsonimport osfrom pathlib import Path-import sysimport tracebackfrom typing import Anyimport yaml-# Add parent directory to path-project_root = Path(__file__).parent.parent.parent.parent-sys.path.insert(0, str(project_root))--from src.services.config import load_config_with_main, parse_language-from src.services.llm import get_llm_config-+from ...services.config import parse_languagefrom .analysis_loop import InvestigateAgent, NoteAgent# Dual-Loop Architecture@@ -54,7 +47,8 @@ class MainSolver:output_base_dir: str | None = None,):"""- Initialize MainSolver+ Initialize MainSolver with lightweight setup.+ Call ainit() to complete async initialization.Args:config_path: Config file path (default: config.yaml in current directory)@@ -64,11 +58,64 @@ class MainSolver:kb_name: Knowledge base nameoutput_base_dir: Output base directory (optional, overrides config)"""+ # Store initialization parameters+ self._config_path = config_path+ self._api_key = api_key+ self._base_url = base_url+ self._api_version = api_version+ self._kb_name = kb_name+ self._output_base_dir = output_base_dir++ # Initialize with None - will be set in ainit()+ self.config = None+ self.api_key = None+ self.base_url = None+ self.api_version = None+ self.kb_name = kb_name+ self.logger = None+ self.monitor = None+ self.token_tracker = None++ async def ainit(self) -> None:+ """+ Complete the asynchronous second phase of MainSolver initialization.++ This class uses a two-phase initialization pattern:++ 1. ``__init__`` performs only lightweight, synchronous setup and stores+ constructor arguments. Attributes such as ``config``, ``api_key``,+ ``base_url``, ``api_version``, ``logger``, ``monitor``, and+ ``token_tracker`` are intentionally left as ``None``.+ 2. :meth:`ainit` performs all I/O-bound and asynchronous work required to+ make the instance fully usable (e.g., loading configuration, wiring up+ logging/monitoring, and preparing external-service clients).++ You **must** call and await this method exactly once after constructing+ ``MainSolver`` and **before** invoking any other methods that rely on+ configuration, logging, metrics, or API access. Using the object prior+ to calling :meth:`ainit` may result in attributes still being ``None``,+ which can lead to confusing runtime errors such as ``AttributeError``,+ misconfigured API calls, missing logs/metrics, or incorrect output paths.++ This async initialization pattern is used instead of performing all setup+ in ``__init__`` so that object construction remains fast and synchronous,+ while allowing potentially slow operations (disk I/O, network requests,+ validation) to be awaited explicitly by the caller in an async context.+ """+ config_path = self._config_path+ api_key = self._api_key+ base_url = self._base_url+ api_version = self._api_version+ kb_name = self._kb_name+ output_base_dir = self._output_base_dir+# Load config from config directory (main.yaml unified config)if config_path is None:project_root = Path(__file__).parent.parent.parent.parent# Load main.yaml (solve_config.yaml is optional and will be merged if exists)- full_config = load_config_with_main("main.yaml", project_root)+ from ...services.config.loader import load_config_with_main_async++ full_config = await load_config_with_main_async("main.yaml", project_root)# Extract solve-specific config and build validator-compatible structuresolve_config = full_config.get("solve", {})@@ -95,10 +142,12 @@ class MainSolver:local_config = {}if Path(config_path).exists():try:- with open(config_path, encoding="utf-8") as f:- loaded = yaml.safe_load(f)- if loaded:- local_config = loaded++ def load_local_config(path: str) -> dict:+ with open(path, encoding="utf-8") as f:+ return yaml.safe_load(f) or {}++ local_config = await asyncio.to_thread(load_local_config, config_path)except Exception:# Config loading warning will be handled by config_loaderpass@@ -125,7 +174,9 @@ class MainSolver:# API configif api_key is None or base_url is None or "llm" not in self.config:try:- llm_config = get_llm_config()+ from ...services.llm.config import get_llm_config_async++ llm_config = await get_llm_config_async()if api_key is None:api_key = llm_config.api_keyif base_url is None:diff --git a/src/agents/solve/solve_loop/manager_agent.py b/src/agents/solve/solve_loop/manager_agent.pyindex dd3d2457d..8f2b67363 100644--- a/src/agents/solve/solve_loop/manager_agent.py+++ b/src/agents/solve/solve_loop/manager_agent.py@@ -190,7 +190,7 @@ class ManagerAgent(BaseAgent):raise ValueError(f"'steps' field in JSON is not an array. Parsed result: {parsed_data}")if not steps_data:- raise ValueError("'steps' array in JSON is empty, please check LLM output.")+ raise ValueError("'steps' array in JSON is empty, please check LLM output")# Parse each stepfor idx, step_data in enumerate(steps_data, 1):@@ -260,7 +260,7 @@ class ManagerAgent(BaseAgent):)if not steps:- raise ValueError("Failed to parse any valid steps, please check LLM output format.")+ raise ValueError("Failed to parse any valid steps, please check LLM output format")logger = getattr(self, "logger", None)if logger is not None:diff --git a/src/agents/solve/utils/__init__.py b/src/agents/solve/utils/__init__.pyindex 4a1ef836a..b23e62b5a 100644--- a/src/agents/solve/utils/__init__.py+++ b/src/agents/solve/utils/__init__.py@@ -15,21 +15,23 @@ if str(project_root) not in sys.path:from src.logging import Logger, LogLevel, get_logger, reset_logger-# Backwards compatibility alias-SolveAgentLogger = Logger--# Performance monitoring-# Config validation+# Backwards compatibility aliases+# These aliases maintain compatibility with code that imported these names before refactoring+SolveAgentLogger = Logger # Alias for Logger classfrom .config_validator import ConfigValidatorfrom .error_handler import (- ParseError,+ LLMParseError,retry_on_parse_error,validate_investigate_output,+ validate_none_tool_constraint,validate_note_output,validate_output,- validate_plan_output,validate_reflect_output,+ validate_solve_output,)++# Backwards compatibility alias+ParseError = LLMParseErrorfrom .performance_monitor import PerformanceMonitor# Token tracker@@ -56,6 +58,7 @@ __all__ = ["validate_output","validate_investigate_output","validate_note_output",+ "validate_none_tool_constraint","validate_reflect_output",- "validate_plan_output",+ "validate_solve_output",]diff --git a/src/agents/solve/utils/error_handler.py b/src/agents/solve/utils/error_handler.pyindex 85c62beee..3eda67488 100644--- a/src/agents/solve/utils/error_handler.py+++ b/src/agents/solve/utils/error_handler.py@@ -4,50 +4,169 @@Error Handler - Error handling and retry mechanism"""-import asynciofrom collections.abc import Callable-import functools-from typing import Any+from typing import Any, Optional+from pydantic import BaseModel, Field, ValidationError, field_validator, model_validator+import tenacity-class ParseError(Exception):- """Parse error"""+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 retry_on_parse_error(max_retries: int = 2, delay: float = 1.0, backoff: float = 2.0):+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+ Parse error retry decorator using tenacity.Args:max_retries: Maximum retry countdelay: 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):- @functools.wraps(func)- async def wrapper(*args, **kwargs):- current_delay = delay-- for attempt in range(max_retries + 1):- try:- return await func(*args, **kwargs)- except ParseError as e:- if attempt == max_retries:- # Last attempt failed, raise exception- raise e-- # Wait and retry- print(- f"⚠️ Parse failed (attempt {attempt + 1}), retrying in {current_delay:.1f}s..."- )- await asyncio.sleep(current_delay)- current_delay *= backoff-- # Should not reach here- raise ParseError("Retry attempts exhausted")-- return wrapper+ 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@@ -67,13 +186,13 @@ def validate_output(bool: Whether validRaises:- ParseError: Raised when validation fails+ LLMParseError: Raised when validation fails"""# Check required fieldsmissing_fields = [field for field in required_fields if field not in output]if missing_fields:- raise ParseError(f"Missing required fields: {', '.join(missing_fields)}")+ raise LLMParseError(f"Missing required fields: {', '.join(missing_fields)}")# Check field typesif field_types:@@ -81,7 +200,7 @@ def validate_output(if field in output and not isinstance(output[field], expected_type):actual_type = type(output[field]).__name__expected_type_name = expected_type.__name__- raise ParseError(+ raise LLMParseError(f"Field '{field}' type error: expected {expected_type_name}, got {actual_type}")@@ -89,7 +208,7 @@ def validate_output(def safe_parse(- parser_func: Callable, text: str, default: Any = None, raise_on_error: bool = False+ text: str, parser_func: Callable, default: Any = None, raise_on_error: bool = False) -> Any:"""Safe parsing (catch exceptions and return default value)@@ -107,147 +226,138 @@ def safe_parse(return parser_func(text)except Exception as e:if raise_on_error:- raise ParseError(f"Parsing failed: {e!s}")+ raise LLMParseError(f"Parsing failed: {e!s}") from e- print(f"⚠️ Parsing failed, using default value: {e!s}")+ 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]) -> bool:- """Validate InvestigateAgent output (refactored: multi-tool intent)"""- required_fields = ["reasoning", "tools"]- field_types = {"reasoning": str, "tools": list}-- validate_output(output, required_fields, field_types)-- valid_tools = ["rag_naive", "rag_hybrid", "web_search", "query_item", "none"]- tools = output["tools"]- if not tools:- raise ParseError("tools list cannot be empty")-- for idx, tool in enumerate(tools):- if not isinstance(tool, dict):- raise ParseError(f"tool[{idx}] must be a dictionary")-- tool_type = tool.get("tool_type", "").lower()- query = tool.get("query", "")- identifier = tool.get("identifier", "")-- if tool_type not in valid_tools:- raise ParseError(- f"tool[{idx}] tool_type must be one of {valid_tools}, got: {tool_type}"- )-- if tool_type == "none":- if len(tools) > 1:- raise ParseError(- "When [TOOL] none exists, no other tool intents should be provided"+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}")- continue-- if not query:- raise ParseError(f"tool[{idx}] missing query")+ if tool_type != "none" and not tool.get("query"):+ raise LLMParseError(f"tool[{i}] missing query")- if tool_type == "query_item" and not (identifier or query):- raise ParseError("query_item must provide identifier or 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- 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 edef validate_note_output(output: dict[str, Any]) -> bool:- """Validate NoteAgent output (new format: only summary and citations)"""- required_fields = ["summary"]- field_types = {"summary": str, "citations": list}-- validate_output(output, required_fields, field_types)-- # Validate citations list- if "citations" in output:- for citation in output["citations"]:- if not isinstance(citation, dict):- raise ParseError(f"citation must be a dictionary, got: {type(citation)}")-- # citations should contain reference_id, source, content- if "reference_id" not in citation and "source" not in citation:- raise ParseError("citation must contain reference_id or source")-- return True+ """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 edef validate_reflect_output(output: dict[str, Any]) -> bool:- """Validate InvestigateReflectAgent output (new format: simplified)"""- required_fields = ["should_stop", "reason", "remaining_questions"]- field_types = {"should_stop": bool, "reason": str, "remaining_questions": list}-- validate_output(output, required_fields, field_types)-- # Validate remaining_questions list- if "remaining_questions" in output:- for question in output["remaining_questions"]:- if not isinstance(question, str):- raise ParseError(f"remaining_question must be a string, got: {type(question)}")-- return True+ """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 edef validate_plan_output(output: dict[str, Any]) -> bool:- """Validate PlanAgent output"""- required_fields = ["answer_style", "blocks"]- field_types = {"answer_style": str, "blocks": list}-- validate_output(output, required_fields, field_types)-- # Validate blocks list is not empty (new)- if not output["blocks"] or len(output["blocks"]) == 0:- raise ParseError(- "blocks list is empty, PlanAgent must generate at least one block.\n"- "Possible reasons:\n"- "1. LLM did not output [Block-N] tags\n"- "2. Output format is incorrect\n"- "3. Prompt design has issues"- )-- # Validate blocks list- for block in output["blocks"]:- if not isinstance(block, dict):- raise ParseError(f"block must be a dictionary, got: {type(block)}")-- if "block_id" not in block or "format" not in block or "steps" not in block:- raise ParseError("block missing required fields: block_id, format, steps")-- # Validate steps list- for step in block["steps"]:- if not isinstance(step, dict):- raise ParseError(f"step must be a dictionary, got: {type(step)}")+ """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- if "step_id" not in step or "plan" not in step:- raise ParseError("step missing required fields: step_id, plan")- return True+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-# Example usage-if __name__ == "__main__":- # Test validation functions- test_investigate_output = {- "investigation_summary": "This round investigation target...",- "actions": [- {"type": "rag_naive", "query": "What is linear convolution?", "priority": "high"}- ],- "followup_suggestions": "If definition is unclear..",- }- try:- validate_investigate_output(test_investigate_output)- print("✓ InvestigateAgent output validation passed")- except ParseError as e:- print(f"✗ InvestigateAgent output validation failed: {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.- # Test missing required fields- test_invalid_output = {"actions": []}+ Args:+ tools: List of tool dictionaries+ tool_type_key: Key to access tool type in each dict (default: "tool_type")- try:- validate_investigate_output(test_invalid_output)- print("✓ Invalid output validation passed (should not happen)")- except ParseError as e:- print(f"✗ Invalid output validation failed (expected): {e}")+ Raises:+ LLMParseError: If none tool constraint is violated+ """+ has_none = any(+ isinstance(tool_type := tool.get(tool_type_key), str) and tool_type.lower() == "none"+ for tool in tools+ )++ if has_none and len(tools) > 1:+ raise LLMParseError(+ f"When 'none' tool exists, no other tool intents should be provided. "+ f"Found {len(tools)} tools with types: {[tool.get(tool_type_key) for tool in tools]}"+ )diff --git a/src/api/main.py b/src/api/main.pyindex 276dfa4f1..e6c3e1f06 100644--- a/src/api/main.py+++ b/src/api/main.py@@ -26,6 +26,98 @@ from src.logging import get_loggerlogger = get_logger("API")+CONFIG_DRIFT_ERROR_TEMPLATE = (+ "Configuration Drift Detected: Tools {drift} found in agents.yaml "+ "investigate.valid_tools but missing from main.yaml solve.valid_tools. "+ "Add these tools to main.yaml solve.valid_tools or remove them from "+ "agents.yaml investigate.valid_tools."+)+++def validate_tool_consistency():+ """+ Validate that the tools configured for agents are consistent with the main application+ configuration.++ This function loads the main configuration (``main.yaml``) and the agents configuration+ (``agents.yaml``) from the project root and compares:++ * ``solve.valid_tools`` in ``main.yaml``+ * ``investigate.valid_tools`` in ``agents.yaml``++ All tools referenced by agents must be present in the main configuration. If any tools are+ defined for agents that are not listed in the main configuration, a ``RuntimeError`` is+ raised describing the drift. The error is logged and re-raised, which causes the FastAPI+ application startup to fail when this function is called from the ``lifespan`` handler.++ Impact on startup+ ------------------+ This validation runs during application startup. Any configuration drift will:++ * Be logged as an error with details about the unknown tools.+ * Prevent the API from starting until the configuration is corrected.++ How to resolve configuration drift+ ----------------------------------+ If startup fails with a configuration drift error:++ 1. Inspect the set of tools reported in the error message.+ 2. Either:+ * Add the missing tools to ``solve.valid_tools`` in ``main.yaml``, **or**+ * Remove or rename the offending tools from ``investigate.valid_tools`` in ``agents.yaml``.+ 3. Restart the application after updating the configuration files.++ Example of aligned configuration+ --------------------------------+ ``main.yaml``::++ solve:+ valid_tools:+ - web_search+ - code_execution++ ``agents.yaml``::++ investigate:+ valid_tools:+ - web_search++ In this case, validation passes because ``investigate.valid_tools`` is a subset of+ ``solve.valid_tools``.++ Example of configuration drift+ ------------------------------+ ``agents.yaml``::++ investigate:+ valid_tools:+ - web_search+ - unknown_tool++ Here, ``unknown_tool`` is not present in ``solve.valid_tools`` in ``main.yaml``, so+ validation will fail and prevent the application from starting until the configurations+ are aligned.+ """+ try:+ from src.services.config import load_config_with_main++ project_root = Path(__file__).parent.parent.parent+ main_config = load_config_with_main("main.yaml", project_root)+ agent_config_data = load_config_with_main("agents.yaml", project_root)++ main_tools = set(main_config.get("solve", {}).get("valid_tools", []))+ agent_tools = set(agent_config_data.get("investigate", {}).get("valid_tools", []))++ if not agent_tools.issubset(main_tools):+ drift = agent_tools - main_tools+ raise RuntimeError(CONFIG_DRIFT_ERROR_TEMPLATE.format(drift=drift))+ except RuntimeError:+ logger.exception("Configuration validation failed")+ raise+ except Exception:+ logger.exception("Failed to load configuration for validation")+ raise+@asynccontextmanagerasync def lifespan(app: FastAPI):@@ -35,6 +127,10 @@ async def lifespan(app: FastAPI):"""# Execute on startuplogger.info("Application startup")++ # Validate configuration consistency+ validate_tool_consistency()+yield# Execute on shutdownlogger.info("Application shutdown")diff --git a/src/api/routers/knowledge.py b/src/api/routers/knowledge.pyindex d36bd0a3e..6d2c3737d 100644--- a/src/api/routers/knowledge.py+++ b/src/api/routers/knowledge.py@@ -7,6 +7,7 @@ Handles knowledge base CRUD operations, file uploads, and initialization.import asynciofrom datetime import datetime+import osfrom pathlib import Pathimport shutilimport sys@@ -30,6 +31,8 @@ from src.knowledge.add_documents import DocumentAdderfrom src.knowledge.initializer import KnowledgeBaseInitializerfrom src.knowledge.manager import KnowledgeBaseManagerfrom src.knowledge.progress_tracker import ProgressStage, ProgressTracker+from src.utils.document_validator import DocumentValidator+from src.utils.error_utils import format_exception_message_project_root = Path(__file__).parent.parent.parent.parentsys.path.insert(0, str(_project_root))@@ -45,6 +48,21 @@ logger = get_logger("Knowledge", level="INFO", log_dir=log_dir)router = APIRouter()+# Constants for byte conversions+BYTES_PER_GB = 1024**3+BYTES_PER_MB = 1024**2+++def format_bytes_human_readable(size_bytes: int) -> str:+ """Format bytes into human-readable string (GB, MB, or bytes)."""+ if size_bytes >= BYTES_PER_GB:+ return f"{size_bytes / BYTES_PER_GB:.1f} GB"+ elif size_bytes >= BYTES_PER_MB:+ return f"{size_bytes / BYTES_PER_MB:.1f} MB"+ else:+ return f"{size_bytes} bytes"++_kb_base_dir = _project_root / "data" / "knowledge_bases"# Lazy initialization@@ -301,12 +319,50 @@ async def upload_files(uploaded_files = []uploaded_file_paths = []++ # 1. Save files and validate size during streamingfor file in files:- file_path = raw_dir / file.filename- with open(file_path, "wb") as buffer:- shutil.copyfileobj(file.file, buffer)- uploaded_files.append(file.filename)- uploaded_file_paths.append(str(file_path))+ file_path = None+ try:+ # Sanitize filename first (without size validation)+ sanitized_filename = DocumentValidator.validate_upload_safety(file.filename, None)+ file.filename = sanitized_filename++ # Save file to disk with size checking during streaming+ file_path = raw_dir / file.filename+ max_size = DocumentValidator.MAX_FILE_SIZE+ written_bytes = 0+ with open(file_path, "wb") as buffer:+ for chunk in iter(lambda: file.file.read(8192), b""):+ written_bytes += len(chunk)+ if written_bytes > max_size:+ # Format size in human-readable format+ size_str = format_bytes_human_readable(max_size)+ raise HTTPException(+ status_code=400,+ detail=f"File '{file.filename}' exceeds maximum size limit of {size_str}",+ )+ buffer.write(chunk)++ # Validate with actual size (additional checks)+ DocumentValidator.validate_upload_safety(file.filename, written_bytes)++ uploaded_files.append(file.filename)+ uploaded_file_paths.append(str(file_path))++ except Exception as e:+ # Clean up partially saved file+ if file_path and file_path.exists():+ try:+ os.unlink(file_path)+ except OSError:+ pass++ error_message = (+ f"Validation failed for file '{file.filename}': {format_exception_message(e)}"+ )+ logger.error(error_message, exc_info=True)+ raise HTTPException(status_code=400, detail=error_message) from elogger.info(f"Uploading {len(uploaded_files)} files to KB '{kb_name}'")@@ -326,7 +382,9 @@ async def upload_files(except ValueError:raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found")except Exception as e:- raise HTTPException(status_code=500, detail=str(e))+ # Unexpected failure (Server error)+ formatted_error = format_exception_message(e)+ raise HTTPException(status_code=500, detail=formatted_error) from e@router.post("/create")diff --git a/src/api/routers/question.py b/src/api/routers/question.pyindex f3dee24d4..f629a8506 100644--- a/src/api/routers/question.py+++ b/src/api/routers/question.py@@ -13,6 +13,8 @@ from src.agents.question.tools.exam_mimic import mimic_exam_questionsfrom src.api.utils.history import ActivityType, history_managerfrom src.api.utils.log_interceptor import LogInterceptorfrom src.api.utils.task_id_manager import TaskIDManager+from src.utils.document_validator import DocumentValidator+from src.utils.error_utils import format_exception_message# Add project root for importsproject_root = Path(__file__).parent.parent.parent.parent@@ -140,24 +142,50 @@ async def websocket_mimic_generate(websocket: WebSocket):)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 sessiontimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- pdf_stem = Path(pdf_name).stem+ pdf_stem = Path(safe_name).stembatch_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 / pdf_name+ pdf_path = batch_dir / safe_nameawait websocket.send_json(- {"type": "status", "stage": "upload", "content": f"Saving PDF: {pdf_name}"}+ {"type": "status", "stage": "upload", "content": f"Saving PDF: {safe_name}"})- # Decode and save PDF- pdf_bytes = base64.b64decode(pdf_data)+ # Write the validated PDF byteswith 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",@@ -165,7 +193,7 @@ async def websocket_mimic_generate(websocket: WebSocket):"content": "Parsing PDF exam paper (MinerU)...",})- logger.info(f"Saved uploaded PDF to: {pdf_path}")+ logger.info(f"Saved and validated uploaded PDF to: {pdf_path}")# Pass batch_dir as output directorypdf_path = str(pdf_path)@@ -240,10 +268,11 @@ async def websocket_mimic_generate(websocket: WebSocket):except WebSocketDisconnect:logger.debug("Client disconnected during mimic generation")except Exception as e:- logger.error(f"Mimic generation error: {e}")+ logger.exception("Mimic generation error")+ error_msg = format_exception_message(e)try:- await websocket.send_json({"type": "error", "content": str(e)})- except:+ await websocket.send_json({"type": "error", "content": error_msg})+ except Exception:passfinally:sys.stdout = original_stdout@@ -251,11 +280,11 @@ async def websocket_mimic_generate(websocket: WebSocket):try:pusher_task.cancel()await pusher_task- except:+ except Exception:passtry:await websocket.close()- except:+ except Exception:pass@@ -433,8 +462,9 @@ async def websocket_question_generate(websocket: WebSocket):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: {e}")+ logger.error(f"Question generation error: {error_msg}")logger.error(f"Error traceback:\n{error_traceback}")# Log additional context if available@@ -458,10 +488,10 @@ async def websocket_question_generate(websocket: WebSocket):logger.warning(f"Failed to log error context: {context_error}")try:- await websocket.send_json({"type": "error", "content": str(e)})+ 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=str(e))+ task_manager.update_task_status(task_id, "error", error=error_msg)finally:pusher_task.cancel()@@ -474,4 +504,5 @@ async def websocket_question_generate(websocket: WebSocket):except WebSocketDisconnect:logger.debug("Client disconnected")except Exception as e:- logger.error(f"WebSocket error: {e}")+ error_msg = format_exception_message(e)+ logger.error(f"WebSocket error: {error_msg}")diff --git a/src/api/routers/research.py b/src/api/routers/research.pyindex 3162e07d0..9198c6ab1 100644--- a/src/api/routers/research.py+++ b/src/api/routers/research.py@@ -250,6 +250,7 @@ async def websocket_research_run(websocket: WebSocket):llm_config = get_llm_config()api_key = llm_config.api_keybase_url = llm_config.base_url+ api_version = getattr(llm_config, "api_version", None)except ValueError as e:await websocket.send_json({"error": f"LLM configuration error: {e!s}"})await websocket.close()@@ -267,16 +268,6 @@ async def websocket_research_run(websocket: WebSocket):except Exception as e:logger.error(f"Progress callback error: {e}")- 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-pipeline = ResearchPipeline(config=config,api_key=api_key,diff --git a/src/api/routers/settings.py b/src/api/routers/settings.pyindex 8d59f735b..4f971a939 100644--- a/src/api/routers/settings.py+++ b/src/api/routers/settings.py@@ -844,7 +844,9 @@ async def get_web_search_config():return get_current_config()except Exception as e:- raise HTTPException(status_code=500, detail=f"Failed to get web search config: {str(e)}")+ raise HTTPException(+ status_code=500, detail=f"Failed to get web search config: {str(e)}"+ ) from e# ==================== RAG Provider Configuration ====================diff --git a/src/api/routers/solve.py b/src/api/routers/solve.pyindex 3ec312416..176aa34ab 100644--- a/src/api/routers/solve.py+++ b/src/api/routers/solve.py@@ -68,6 +68,7 @@ async def websocket_solve(websocket: WebSocket):# Connection closed, stop pushinglogger.debug(f"WebSocket connection closed in log_pusher: {e}")connection_closed.set()+ log_queue.task_done()breakexcept Exception as e:logger.debug(f"Error sending log entry: {e}")@@ -104,10 +105,10 @@ async def websocket_solve(websocket: WebSocket):api_key = llm_config.api_keybase_url = llm_config.base_urlapi_version = getattr(llm_config, "api_version", None)- except Exception:- api_key = None- base_url = None- api_version = None+ except Exception as e:+ logger.error(f"Failed to get LLM config: {e}", exc_info=True)+ await websocket.send_json({"type": "error", "content": f"LLM configuration error: {e}"})+ returnsolver = MainSolver(kb_name=kb_name,@@ -117,6 +118,9 @@ async def websocket_solve(websocket: WebSocket):api_version=api_version,)+ # Complete async initialization+ await solver.ainit()+logger.info(f"[{task_id}] Solving: {question[:50]}...")target_logger = solver.logger.loggerdiff --git a/src/config/accessors.py b/src/config/accessors.pyindex 8a966852a..37b9c1845 100644--- a/src/config/accessors.py+++ b/src/config/accessors.py@@ -1,5 +1,6 @@from typing import Callable+class ConfigAccessor:def __init__(self, loader: Callable[[], dict]):self._loader = loader@@ -15,4 +16,3 @@ class ConfigAccessor:def user_data_dir(self) -> str:cfg = self._loader()return str(cfg.get("paths", {}).get("user_data_dir", "./data/user"))-diff --git a/src/config/constants.py b/src/config/constants.pynew file mode 100644index 000000000..a42ddf7b5--- /dev/null+++ b/src/config/constants.py@@ -0,0 +1,34 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+Constants for DeepTutor+"""++from pathlib import Path++# Project root directory - central location for all path calculations+PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent++# Valid tools for investigate agent+VALID_INVESTIGATE_TOOLS = ["rag_naive", "rag_hybrid", "web_search", "query_item", "none"]++# Valid tools for solve agent+VALID_SOLVE_TOOLS = [+ "web_search",+ "code_execution",+ "rag_naive",+ "rag_hybrid",+ "query_item",+ "none",+ "finish",+]++# Logging symbols for different log levels+LOG_SYMBOLS = {+ "DEBUG": "·",+ "INFO": "●",+ "SUCCESS": "✓",+ "WARNING": "⚠",+ "ERROR": "✗",+ "CRITICAL": "✗",+}diff --git a/src/config/defaults.py b/src/config/defaults.pyindex e69de29bb..5bd843b29 100644--- a/src/config/defaults.py+++ b/src/config/defaults.py@@ -0,0 +1,18 @@+"""+Default configuration values for DeepTutor.+"""++from pathlib import Path++# Get project root+_project_root = Path(__file__).parent.parent.parent++# Default configuration+DEFAULTS = {+ "llm": {"model": "gpt-4o-mini", "provider": "openai"},+ "paths": {+ "user_data_dir": str(_project_root / "data" / "user"),+ "knowledge_bases_dir": str(_project_root / "data" / "knowledge_bases"),+ "user_log_dir": str(_project_root / "logs"),+ },+}diff --git a/src/config/schema.py b/src/config/schema.pyindex ad43dcbb8..e946191bb 100644--- a/src/config/schema.py+++ b/src/config/schema.py@@ -1,30 +1,36 @@from typing import Any, Dict+from pydantic import BaseModel, field_validator+class LLMConfig(BaseModel):model: strprovider: str = "openai"+class PathsConfig(BaseModel):user_data_dir: strknowledge_bases_dir: struser_log_dir: str+class AppConfig(BaseModel):llm: LLMConfigpaths: PathsConfig@field_validator("llm", mode="before")@classmethod- def ensure_llm(cls, v: Dict[str, Any]) -> Dict[str, Any]:+ def ensure_llm(cls, v: Any) -> Dict[str, Any]:if not isinstance(v, dict):raise ValueError("llm section must be a mapping")if "model" not in v:raise ValueError("llm.model is required")return v+CURRENT_SCHEMA_VERSION = 1+def migrate_config(cfg: Dict[str, Any]) -> Dict[str, Any]:"""No-op migration for now; placeholder for future versioned changes.diff --git a/src/config/settings.py b/src/config/settings.pynew file mode 100644index 000000000..5d8275da5--- /dev/null+++ b/src/config/settings.py@@ -0,0 +1,50 @@+"""+Configuration Settings for DeepTutor++Environment Variables:+ LLM_RETRY__MAX_RETRIES: Maximum retry attempts for LLM calls (default: 3)+ LLM_RETRY__BASE_DELAY: Base delay between retries in seconds (default: 1.0)+ LLM_RETRY__EXPONENTIAL_BACKOFF: Whether to use exponential backoff (default: True)++Examples:+ export LLM_RETRY__MAX_RETRIES=5+ export LLM_RETRY__BASE_DELAY=2.0+ export LLM_RETRY__EXPONENTIAL_BACKOFF=false+"""++from pydantic import BaseModel, Field+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")+ exponential_backoff: bool = Field(+ default=True, description="Whether to use exponential backoff"+ )+++class Settings(BaseSettings):+ # LLM retry configuration+ retry: LLMRetryConfig = Field(default_factory=LLMRetryConfig)++ # Deprecated: use retry instead+ @property+ def llm_retry(self):+ import warnings++ warnings.warn(+ "settings.llm_retry is deprecated, use settings.retry instead",+ DeprecationWarning,+ stacklevel=2,+ )+ return self.retry++ model_config = SettingsConfigDict(+ env_prefix="LLM_",+ env_nested_delimiter="__",+ )+++# Global settings instance+settings = Settings()diff --git a/src/core/errors.py b/src/core/errors.pyindex dfaa989d5..43b5b2a91 100644--- a/src/core/errors.py+++ b/src/core/errors.py@@ -1,13 +1,65 @@+"""+Base exception classes for consistent error handling across the application.+Provides a standardized way to distinguish between bugs, recoverable errors,+and configuration issues.+"""+from typing import Any, Dict, Optional-class BaseError(Exception):- def __init__(self, message: str, *, context: Optional[Dict[str, Any]] = None):++class DeepTutorError(Exception):+ """Base class for all application errors in DeepTutor."""++ def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):super().__init__(message)- self.context = context or {}+ self.message = message+ self.details = details or {}++ def __str__(self) -> str:+ if self.details:+ return f"{self.message} (details: {self.details})"+ return self.message+ if self.details:+ return f"{self.message} (details: {self.details})"+ return self.message+++class ConfigurationError(DeepTutorError):+ """Raised when there's a configuration-related error."""-class ConfigError(BaseError):pass-class EnvError(BaseError):++class ValidationError(DeepTutorError):+ """Raised when input validation fails."""++ pass+++class ServiceError(DeepTutorError):+ """Base class for service layer errors."""+pass++class LLMServiceError(ServiceError):+ """Base class for LLM service-related errors."""++ pass+++class LLMContextError(LLMServiceError):+ """Raised when prompt exceeds model context window."""++ pass+++class EnvironmentConfigError(ConfigurationError):+ """Raised when there's an environment-related configuration error."""++ pass+++# Aliases for backward compatibility+ConfigError = ConfigurationError+EnvError = EnvironmentConfigErrordiff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.pyindex 7ff749e9f..18a45a7f7 100644--- a/src/knowledge/add_documents.py+++ b/src/knowledge/add_documents.py@@ -1,165 +1,223 @@#!/usr/bin/env python# -*- coding: utf-8 -*-"""-Incrementally add documents to existing knowledge base--This script allows adding new documents to an existing knowledge base,-rather than recreating the entire knowledge base.-Only newly added documents will be processed, without affecting the existing knowledge graph.+Incrementally add documents to existing knowledge base.+Improved version with Hash-based duplicate checking, robust error handling,+and architectural improvements for data integrity and vision support."""import argparseimport asynciofrom datetime import datetime+from functools import partial+import hashlibimport jsonimport osfrom pathlib import Pathimport shutilimport sys--project_root = Path(__file__).parent.parent.parent-sys.path.insert(0, str(project_root))-# Add raganything module path-raganything_path = project_root.parent / "raganything" / "RAG-Anything"-if raganything_path.exists():- sys.path.insert(0, str(raganything_path))+import tempfile+from typing import TYPE_CHECKING, Any, Dict, Listfrom dotenv import load_dotenv-from lightrag.llm.openai import openai_complete_if_cache-from lightrag.utils import EmbeddingFunc-from raganything import RAGAnything, RAGAnythingConfig-from src.services.embedding import get_embedding_client, get_embedding_config-from src.services.llm import get_llm_config+# Attempt imports for dynamic dependencies+try:+ from lightrag.llm.openai import openai_complete_if_cache+ from lightrag.utils import EmbeddingFunc+except ImportError:+ # These will be caught during runtime if needed+ openai_complete_if_cache = None+ EmbeddingFunc = None++# Type hinting support for dynamic imports+if TYPE_CHECKING:+ try:+ from raganything import RAGAnything+ from raganything import RAGAnythingConfig as RAGAnythingConfigType+ except ImportError:+ RAGAnything = Any+ RAGAnythingConfigType = Any+else:+ RAGAnything = None+ RAGAnythingConfigType = None++# Placeholder for runtime classes+raganything_cls = None+RAGAnythingConfig = None+++def load_dynamic_imports(project_root: Path):+ """Handle the path injections and dynamic imports safely."""+ global raganything_cls, RAGAnythingConfig++ sys.path.insert(0, str(project_root))+ raganything_path = project_root.parent / "raganything" / "RAG-Anything"+ if raganything_path.exists():+ sys.path.insert(0, str(raganything_path))++ try:+ from raganything import RAGAnything as RA+ from raganything import RAGAnythingConfig as RAC-load_dotenv(dotenv_path=".env", override=False)+ raganything_cls = RA+ RAGAnythingConfig = RAC+ except ImportError:+ pass++from src.knowledge.extract_numbered_items import process_content_listfrom src.logging import LightRAGLogContext, get_logger+from src.services.embedding import (+ get_embedding_client,+ get_embedding_config,+ reset_embedding_client,+)+from src.services.llm import get_llm_configlogger = get_logger("KnowledgeInit")-# Import numbered items extraction functionality-from src.knowledge.extract_numbered_items import process_content_list+# Default base directory for knowledge bases+DEFAULT_BASE_DIR = "./data/knowledge_bases"class DocumentAdder:- """Add documents to existing knowledge base"""+ """Add documents to existing knowledge base with Hash-validation"""def __init__(self,kb_name: str,- base_dir="./data/knowledge_bases",- api_key: str = None,- base_url: str = None,+ base_dir=DEFAULT_BASE_DIR,+ api_key: str | None = None,+ base_url: str | None = None,progress_tracker=None,):self.kb_name = kb_nameself.base_dir = Path(base_dir)self.kb_dir = self.base_dir / kb_name- # Check if knowledge base existsif not self.kb_dir.exists():raise ValueError(f"Knowledge base does not exist: {kb_name}")- # Directory structureself.raw_dir = self.kb_dir / "raw"self.images_dir = self.kb_dir / "images"self.rag_storage_dir = self.kb_dir / "rag_storage"self.content_list_dir = self.kb_dir / "content_list"+ self.metadata_file = self.kb_dir / "metadata.json"- # Check directory structureif not self.rag_storage_dir.exists():- raise ValueError(- f"Knowledge base not initialized: {kb_name}, please create knowledge base first"- )+ raise ValueError(f"Knowledge base not initialized: {kb_name}")self.api_key = api_keyself.base_url = base_url- self.embedding_cfg = get_embedding_config()- self.llm_cfg = get_llm_config()self.progress_tracker = progress_tracker+ self._ensure_working_directories()- def get_existing_files(self) -> set:- """Get list of existing documents"""- existing_files = set()- if self.raw_dir.exists():- for file_path in self.raw_dir.glob("*"):- if file_path.is_file():- existing_files.add(file_path.name)- return existing_files+ def _ensure_working_directories(self):+ for directory in [self.raw_dir, self.images_dir, self.content_list_dir]:+ directory.mkdir(parents=True, exist_ok=True)- def add_documents(self, source_files: list[str], skip_duplicates: bool = True) -> list[Path]:+ def _get_file_hash(self, file_path: Path) -> str:"""- Add documents to knowledge base-- Args:- source_files: List of document files to add- skip_duplicates: Whether to skip duplicate files (files with same name)-- Returns:- List of successfully added new file paths+ Calculate SHA-256 hash of a file.+ Uses 64KB chunks for better throughput on SSDs."""- logger.info(f"Adding documents to knowledge base '{self.kb_name}'...")+ sha256_hash = hashlib.sha256()+ chunk_size = 65536 # 64KB+ with open(file_path, "rb") as f:+ for byte_block in iter(lambda: f.read(chunk_size), b""):+ sha256_hash.update(byte_block)+ return sha256_hash.hexdigest()++ def get_ingested_hashes(self) -> Dict[str, str]:+ """Get map of filename -> hash from metadata."""+ if self.metadata_file.exists():+ try:+ with open(self.metadata_file, "r", encoding="utf-8") as f:+ data = json.load(f)+ return data.get("file_hashes", {})+ except Exception:+ return {}+ return {}++ async def _run_in_executor(self, func, *args, **kwargs):+ loop = asyncio.get_running_loop()+ return await loop.run_in_executor(None, partial(func, *args, **kwargs))++ def add_documents(self, source_files: List[str], allow_duplicates: bool = False) -> List[Path]:+ """+ Synchronous phase: Validates hashes and prepares files.+ Treats 'raw/' as a Write-Ahead Log: files exist there before being canonized in metadata.+ """+ logger.info(f"Validating documents for '{self.kb_name}'...")- existing_files = self.get_existing_files()- new_files = []- skipped_files = []+ ingested_hashes = self.get_ingested_hashes()+ files_to_process = []for source in source_files:source_path = Path(source)if not source_path.exists():- logger.warning(f" ⚠ Source file does not exist: {source}")+ logger.warning(f" ⚠ Missing: {source}")continue- # Check if already exists- if source_path.name in existing_files:- if skip_duplicates:- logger.info(f" → Skipped (already exists): {source_path.name}")- skipped_files.append(source_path.name)- continue- logger.warning(f" ⚠ Overwriting existing file: {source_path.name}")-- # Copy to raw directory- dest_path = self.raw_dir / source_path.name- shutil.copy2(source_path, dest_path)- new_files.append(dest_path)- logger.info(f" ✓ Added: {source_path.name}")+ current_hash = self._get_file_hash(source_path)- if skipped_files:- logger.info(f"\nSkipped {len(skipped_files)} existing files")+ # 1. Check if content is already fully ingested (Canon Check)+ # We look for value matches in the metadata hash map+ if current_hash in ingested_hashes.values() and not allow_duplicates:+ logger.info(f" → Skipped (content already indexed): {source_path.name}")+ continue- logger.info(f"Successfully added {len(new_files)} new files")- return new_files+ # 2. Prepare file in raw/ (Write-Ahead Log)+ dest_path = self.raw_dir / source_path.name- async def process_new_documents(self, new_files: list[Path]):- """Process newly added documents. Re-reads config to catch .env changes."""+ should_copy = True+ if dest_path.exists():+ # If file exists in raw, check if it's the same content+ dest_hash = self._get_file_hash(dest_path)+ if dest_hash == current_hash:+ should_copy = False+ logger.info(f" ⚠ Recovering staged file (interrupted run): {source_path.name}")+ else:+ if not allow_duplicates:+ # Name collision with different content+ logger.info(+ f" → Skipped (filename collision with different content): {source_path.name}"+ )+ continue+ else:+ logger.info(f" → Overwriting existing raw file: {source_path.name}")++ if should_copy:+ shutil.copy2(source_path, dest_path)+ logger.info(f" ✓ Staged to raw: {source_path.name}")++ files_to_process.append(dest_path)++ return files_to_process++ async def process_new_documents(self, new_files: List[Path]):+ """Async phase: Ingests files into the RAG system."""if not new_files:- logger.warning("No new files to process")return None- logger.info(f"\nProcessing {len(new_files)} new documents...")-- self.embedding_cfg = get_embedding_config()- self.llm_cfg = get_llm_config()-- logger.info(- f"Using: {self.embedding_cfg.model} "- f"({self.embedding_cfg.dim}D, {self.embedding_cfg.binding})"- )+ if raganything_cls is None:+ raise ImportError("RAGAnything module not found.")- config = RAGAnythingConfig(- working_dir=str(self.rag_storage_dir),- parser="mineru",- enable_image_processing=True,- enable_table_processing=True,- enable_equation_processing=True,- )+ # Pre-import progress stage if needed to avoid overhead in loop+ ProgressStage = None+ if self.progress_tracker:+ from src.knowledge.progress_tracker import ProgressStage+ self.llm_cfg = get_llm_config()model = self.llm_cfg.modelapi_key = self.api_key or self.llm_cfg.api_keybase_url = self.base_url or self.llm_cfg.base_url- def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):+ # LLM Function Wrapper+ def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):+ if history_messages is None:+ history_messages = []return openai_complete_if_cache(model,prompt,@@ -170,93 +228,88 @@ class DocumentAdder:**kwargs,)+ # Vision Function Wrapper - Robust history handlingdef vision_model_func(prompt,system_prompt=None,- history_messages=[],+ history_messages=None,image_data=None,messages=None,**kwargs,):+ if history_messages is None:+ history_messages = []+ # If pre-formatted messages are provided, sanitize themif messages:- clean_kwargs = {- k: v- for k, v in kwargs.items()- if k not in ["messages", "prompt", "system_prompt", "history_messages"]- }+ safe_messages = self._filter_valid_messages(messages)return openai_complete_if_cache(model,prompt="",- system_prompt=None,- history_messages=[],- messages=messages,+ messages=safe_messages,api_key=api_key,base_url=base_url,- **clean_kwargs,+ **kwargs,)- # Traditional single image format++ # --- Construct Message History ---+ current_messages = []++ # 1. Add System Prompt (if provided)+ if system_prompt:+ current_messages.append({"role": "system", "content": system_prompt})++ # 2. Add History (Filtering out conflicting system prompts)+ if history_messages:+ # Filter out system messages from history to avoid duplicates/conflicts with the new system_prompt+ filtered_history = [+ msg+ for msg in history_messages+ if isinstance(msg, dict) and msg.get("role") != "system"+ ]+ current_messages.extend(filtered_history)++ # 3. Construct New User Message+ user_content: List[Dict[str, Any]] = [{"type": "text", "text": prompt}]if image_data:- clean_kwargs = {- k: v- for k, v in kwargs.items()- if k not in ["messages", "prompt", "system_prompt", "history_messages"]- }- return openai_complete_if_cache(- model,- prompt="",- system_prompt=None,- history_messages=[],- messages=[- {"role": "system", "content": system_prompt} if system_prompt else None,- (- {- "role": "user",- "content": [- {"type": "text", "text": prompt},- {- "type": "image_url",- "image_url": {- "url": f"data:image/jpeg;base64,{image_data}"- },- },- ],- }- if image_data- else {"role": "user", "content": prompt}- ),- ],- api_key=api_key,- base_url=base_url,- **clean_kwargs,+ user_content.append(+ {+ "type": "image_url",+ "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},+ })- return llm_model_func(prompt, system_prompt, history_messages, **kwargs)- # Define embedding function using unified EmbeddingClient- # Reset client to pick up latest config (including active provider from UI)- from src.services.embedding import reset_embedding_client-- reset_embedding_client()+ # 4. Merge Logic: Avoid back-to-back user messages+ if current_messages and current_messages[-1].get("role") == "user":+ last_msg = current_messages[-1]+ # If last content is string, convert to list format first+ if isinstance(last_msg["content"], str):+ last_msg["content"] = [{"type": "text", "text": last_msg["content"]}]++ # Append new content blocks+ if isinstance(last_msg["content"], list):+ last_msg["content"].extend(user_content)+ else:+ # Fallback if structure is unexpected, just append new message+ current_messages.append({"role": "user", "content": user_content})+ else:+ current_messages.append({"role": "user", "content": user_content})- embedding_cfg = get_embedding_config() # Reload config- embedding_client = get_embedding_client() # Get fresh client with new config+ return openai_complete_if_cache(+ model,+ prompt="",+ messages=current_messages,+ api_key=api_key,+ base_url=base_url,+ **kwargs,+ )- logger.info(- f"Using embedding: {embedding_cfg.model} "- f"({embedding_cfg.dim}D, {embedding_cfg.binding})"- )+ # Embedding Setup+ reset_embedding_client()+ embedding_cfg = get_embedding_config()+ embedding_client = get_embedding_client()- # Create async wrapper compatible with LightRAG's expected signatureasync def unified_embed_func(texts):- """- Unified embedding function using EmbeddingClient.- Supports multiple providers: OpenAI, Cohere, Jina, Ollama, etc.- """- try:- embeddings = await embedding_client.embed(texts)- return embeddings- except Exception as e:- logger.error(f"Embedding failed: {e}")- raise+ return await embedding_client.embed(texts)embedding_func = EmbeddingFunc(embedding_dim=embedding_cfg.dim,@@ -264,405 +317,215 @@ class DocumentAdder:func=unified_embed_func,)- # Initialize RAGAnything with existing storage and log forwarding+ config = RAGAnythingConfig(+ working_dir=str(self.rag_storage_dir),+ parser="mineru",+ enable_image_processing=True,+ enable_table_processing=True,+ enable_equation_processing=True,+ )+with LightRAGLogContext(scene="knowledge_init"):- rag = RAGAnything(+ rag = raganything_cls(config=config,llm_model_func=llm_model_func,vision_model_func=vision_model_func,embedding_func=embedding_func,)+ if hasattr(rag, "_ensure_lightrag_initialized"):+ await rag._ensure_lightrag_initialized()- # Ensure LightRAG is initialized (will load existing knowledge base)- await rag._ensure_lightrag_initialized()- logger.info("✓ Loaded existing knowledge base")-- # Process each new documentprocessed_files = []- total_files = len(new_files)for idx, doc_file in enumerate(new_files, 1):- logger.info(f"\nProcessing: {doc_file.name}")-- # Update progress- if self.progress_tracker:- from src.knowledge.progress_tracker import ProgressStage-- self.progress_tracker.update(- ProgressStage.PROCESSING_FILE,- f"Processing: {doc_file.name}",- current=idx,- total=total_files,- file_name=doc_file.name,- )-try:- # Use RAGAnything's process_document_complete method with timeout- logger.info(" → Starting document processing...")+ if self.progress_tracker and ProgressStage:+ self.progress_tracker.update(+ ProgressStage.PROCESSING_FILE,+ f"Ingesting {doc_file.name}",+ current=idx,+ total=len(new_files),+ )++ # Verify file still exists in raw/ (it should, as we staged it)+ if not doc_file.exists():+ logger.error(f" ✗ Failed: Staged file missing {doc_file.name}")+ continue+await asyncio.wait_for(rag.process_document_complete(file_path=str(doc_file),output_dir=str(self.content_list_dir),parse_method="auto",),- timeout=600.0, # 10 minute timeout+ timeout=600.0,)- logger.info(f" ✓ Successfully processed: {doc_file.name}")processed_files.append(doc_file)-- # Content list should be automatically saved- doc_name = doc_file.stem- content_list_file = self.content_list_dir / f"{doc_name}.json"- if content_list_file.exists():- logger.info(f" ✓ Content list saved: {content_list_file.name}")-- except asyncio.TimeoutError:- logger.error(f" ✗ Processing timeout for {doc_file.name} (>10 minutes)")- logger.error(" Possible causes: Large PDF, slow embedding API, network issues")- if self.progress_tracker:- from src.knowledge.progress_tracker import ProgressStage-- self.progress_tracker.update(- ProgressStage.ERROR,- f"Timeout processing: {doc_file.name}",- current=idx,- total=total_files,- error="Processing timeout (>10 minutes)",- )+ # Store hash on success - "Canonizing" the file+ self._record_successful_hash(doc_file)+ logger.info(f" ✓ Processed & Indexed: {doc_file.name}")except Exception as e:- logger.error(f" ✗ Processing failed {doc_file.name}: {e!s}")- import traceback+ logger.exception(f" ✗ Failed {doc_file.name}: {e}")- logger.error(traceback.format_exc())- if self.progress_tracker:- from src.knowledge.progress_tracker import ProgressStage+ await self.fix_structure()+ return processed_files- self.progress_tracker.update(- ProgressStage.ERROR,- f"Error processing: {doc_file.name}",- current=idx,- total=total_files,- error=str(e),- )+ def _record_successful_hash(self, file_path: Path):+ """Update metadata with the hash of a successfully processed file."""+ file_hash = self._get_file_hash(file_path)+ try:+ metadata = {}+ if self.metadata_file.exists():+ with open(self.metadata_file, "r", encoding="utf-8") as f:+ metadata = json.load(f)- # Copy extracted images- rag_images_dir = self.rag_storage_dir / "images"- if rag_images_dir.exists():- logger.info("\nCopying extracted images...")- image_count = 0- for img_file in rag_images_dir.glob("*"):- if img_file.is_file():- dest = self.images_dir / img_file.name- if not dest.exists():- shutil.copy2(img_file, dest)- image_count += 1- if image_count > 0:- logger.info(f" ✓ Copied {image_count} images")-- # Fix structure- await self.fix_structure()+ if "file_hashes" not in metadata:+ metadata["file_hashes"] = {}- logger.info("\n✓ Document processing completed!")+ metadata["file_hashes"][file_path.name] = file_hash+ # Atomic write: write to temp file, then rename+ fd, tmp_path = tempfile.mkstemp(dir=self.kb_dir, suffix=".json")+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ json.dump(metadata, f, indent=2, ensure_ascii=False)+ os.replace(tmp_path, self.metadata_file)+ except Exception:+ os.unlink(tmp_path)+ raise+ except Exception as e:+ logger.warning(f"Could not update hash metadata: {e}")- return processed_files+ @staticmethod+ def _filter_valid_messages(messages):+ return [+ m+ for m in messages+ if isinstance(m, dict) and m.get("role") is not None and m.get("content") is not None+ ]async def fix_structure(self):- """Fix nested directory structure"""- logger.info("\nFixing directory structure...")+ """Robustly moves nested outputs and cleans up."""+ logger.info("Organizing storage structure...")- # Find nested content lists- content_list_moves = []+ # 1. Identify moves+ moves = []for doc_dir in self.content_list_dir.glob("*"):if not doc_dir.is_dir():continue- auto_dir = doc_dir / "auto"- if not auto_dir.exists():- continue-- # Find the _content_list.json file- for json_file in auto_dir.glob("*_content_list.json"):- target_file = self.content_list_dir / f"{doc_dir.name}.json"- content_list_moves.append((json_file, target_file))-- # Move content list files- for source, target in content_list_moves:- try:- shutil.copy2(source, target)- logger.info(f" ✓ Moved: {source.name} -> {target.name}")- except Exception as e:- logger.error(f" ✗ Move failed {source.name}: {e!s}")+ # Content List+ json_src = next(doc_dir.glob("auto/*_content_list.json"), None)+ if json_src:+ moves.append((json_src, self.content_list_dir / f"{doc_dir.name}.json"))- # Find and move nested images- for doc_dir in self.content_list_dir.glob("*"):- if not doc_dir.is_dir():- continue+ # Images+ for img in doc_dir.glob("auto/images/*"):+ moves.append((img, self.images_dir / img.name))- auto_dir = doc_dir / "auto"- if not auto_dir.exists():- continue+ # 2. Execute moves+ for src, dest in moves:+ if src.exists():+ await self._run_in_executor(shutil.copy2, src, dest)- images_dir = auto_dir / "images"- if images_dir.exists() and images_dir.is_dir():- image_count = 0- # Ensure target directory exists- self.images_dir.mkdir(parents=True, exist_ok=True)-- for img_file in images_dir.glob("*"):- if img_file.is_file() and img_file.exists():- target_img = self.images_dir / img_file.name- if not target_img.exists():- try:- # Ensure source file exists- if not img_file.exists():- logger.warning(f" ⚠ Source image does not exist: {img_file}")- continue- shutil.copy2(img_file, target_img)- image_count += 1- except FileNotFoundError:- logger.error(- f" ✗ Failed to move image {img_file.name}: Source file does not exist: {img_file}"- )- except Exception as e:- logger.error(f" ✗ Failed to move image {img_file.name}: {e!s}")-- if image_count > 0:- logger.info(f" ✓ Moved {image_count} images from {doc_dir.name}/auto/images/")-- # Clean up nested directories+ # 3. Safe Cleanup: Only delete directories we actually processedfor doc_dir in self.content_list_dir.glob("*"):if doc_dir.is_dir():- try:- shutil.rmtree(doc_dir)- logger.info(f" ✓ Cleaned: {doc_dir.name}/")- except Exception as e:- logger.error(f" ✗ Cleanup failed {doc_dir.name}: {e!s}")-- logger.info("✓ Directory structure fixed!")+ # Safety check: only delete if it looks like a parser output (has 'auto' subdir)+ # This prevents wiping manual user folders in content_list_dir+ if (doc_dir / "auto").exists():+ await self._run_in_executor(shutil.rmtree, doc_dir, ignore_errors=True)- def extract_numbered_items_for_new_docs(- self, processed_files: list[Path], batch_size: int = 20- ):- """- Extract numbered items for newly added documents-- Args:- processed_files: List of newly processed files- batch_size: Number of items to process per batch- """+ def extract_numbered_items_for_new_docs(self, processed_files, batch_size=20):if not processed_files:- logger.info("No new files need numbered items extraction")return- logger.info("\n" + "=" * 60)- logger.info("🔍 Extracting numbered items for new documents...")- logger.info("=" * 60 + "\n")-- # Use credentials from config as fallback- api_key = self.api_key or self.llm_cfg.api_key- base_url = self.base_url or self.llm_cfg.base_url-+ llm_cfg = getattr(self, "llm_cfg", None)+ if llm_cfg is None:+ llm_cfg = get_llm_config()+ api_key = self.api_key or llm_cfg.api_key+ base_url = self.base_url or llm_cfg.base_urloutput_file = self.kb_dir / "numbered_items.json"- try:- for idx, doc_file in enumerate(processed_files, 1):- doc_name = doc_file.stem- content_list_file = self.content_list_dir / f"{doc_name}.json"-- if not content_list_file.exists():- logger.warning(f"Content list file not found: {content_list_file.name}")- continue-- logger.info(- f"\nProcessing file [{idx}/{len(processed_files)}]: {content_list_file.name}"- )-- # Always merge to existing file (if exists)- merge = output_file.exists()-+ for doc_file in processed_files:+ content_list_file = self.content_list_dir / f"{doc_file.stem}.json"+ if content_list_file.exists():process_content_list(content_list_file=content_list_file,output_file=output_file,api_key=api_key,base_url=base_url,batch_size=batch_size,- merge=merge,+ merge=output_file.exists(),)- logger.info(f"\n{'=' * 60}")- logger.info("✓ Numbered items extraction complete!")- logger.info(f"Output file: {output_file}")- logger.info(f"{'=' * 60}\n")-- except Exception as e:- logger.error(f"\n✗ Numbered items extraction failed: {e}")- import traceback-- traceback.print_exc()-def update_metadata(self, added_count: int):- """Update knowledge base metadata"""- metadata_file = self.kb_dir / "metadata.json"-+ if not self.metadata_file.exists():+ returntry:- if metadata_file.exists():- with open(metadata_file, encoding="utf-8") as f:- metadata = json.load(f)- else:- metadata = {}+ with open(self.metadata_file, "r", encoding="utf-8") as f:+ metadata = json.load(f)- # Update modification timemetadata["last_updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")-- # Record add operation- if "update_history" not in metadata:- metadata["update_history"] = []-- metadata["update_history"].append(+ history = metadata.get("update_history", [])+ history.append({- "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),- "action": "add_documents",- "files_added": added_count,+ "timestamp": metadata["last_updated"],+ "action": "incremental_add",+ "count": added_count,})+ metadata["update_history"] = history- with open(metadata_file, "w", encoding="utf-8") as f:+ with open(self.metadata_file, "w", encoding="utf-8") as f:json.dump(metadata, f, indent=2, ensure_ascii=False)-- logger.info("✓ Metadata updated")-except Exception as e:- logger.warning(f"Failed to update metadata: {e!s}")+ logger.warning(f"Metadata update failed: {e}")async def main():- """Main function"""- parser = argparse.ArgumentParser(- description="Incrementally add documents to existing knowledge base",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Usage examples:- # Add a single document to knowledge base- python add_documents.py ai_textbook --docs new_chapter.pdf-- # Add multiple documents to knowledge base- python add_documents.py math2211 --docs chapter1.pdf chapter2.pdf-- # Add documents from directory- python add_documents.py ai_textbook --docs-dir ./new_materials/-- # Allow overwriting files with same name- python add_documents.py ai_textbook --docs document.pdf --allow-duplicates-- # Only add files, skip processing (process manually later)- python add_documents.py ai_textbook --docs file.pdf --skip-processing-- # Skip numbered items extraction- python add_documents.py ai_textbook --docs file.pdf --skip-extract- """,- )-- parser.add_argument("kb_name", help="Knowledge base name")- parser.add_argument("--docs", nargs="+", help="Document files to add")- parser.add_argument("--docs-dir", help="Directory containing documents to add")- parser.add_argument(- "--base-dir",- default="./knowledge_bases",- help="Knowledge base base directory (default: ./knowledge_bases)",- )- parser.add_argument("--api-key", default=os.getenv("LLM_API_KEY"), help="OpenAI API key")- parser.add_argument("--base-url", default=os.getenv("LLM_HOST"), help="API base URL")- parser.add_argument(- "--allow-duplicates",- action="store_true",- help="Allow overwriting files with same name (default: skip)",- )- parser.add_argument(- "--skip-processing", action="store_true", help="Only add files, skip document processing"- )- parser.add_argument(- "--skip-extract", action="store_true", help="Skip numbered items extraction"- )- parser.add_argument(- "--batch-size",- type=int,- default=20,- help="Batch size for numbered items extraction (default: 20)",- )+ parser = argparse.ArgumentParser(description="Incrementally add documents to RAG KB")+ parser.add_argument("kb_name", help="KB Name")+ parser.add_argument("--docs", nargs="+", help="Files")+ parser.add_argument("--docs-dir", help="Directory")+ parser.add_argument("--base-dir", default=DEFAULT_BASE_DIR)+ parser.add_argument("--api-key", default=os.getenv("LLM_API_KEY"))+ parser.add_argument("--base-url", default=os.getenv("LLM_HOST"))+ parser.add_argument("--allow-duplicates", action="store_true")args = parser.parse_args()- # Check API key- if not args.skip_processing and not args.api_key:- logger.error("Error: OpenAI API key required")- logger.error("Please set LLM_API_KEY environment variable or use --api-key option")- return+ # Initialize dynamic paths+ project_root = Path(__file__).parent.parent.parent+ load_dynamic_imports(project_root)++ load_dotenv()- # Collect document filesdoc_files = []if args.docs:doc_files.extend(args.docs)-if args.docs_dir:- docs_dir = Path(args.docs_dir)- if docs_dir.exists() and docs_dir.is_dir():- for ext in ["*.pdf", "*.docx", "*.doc", "*.txt", "*.md"]:- doc_files.extend([str(f) for f in docs_dir.glob(ext)])- else:- logger.error(f"Error: Document directory does not exist: {args.docs_dir}")- return+ p = Path(args.docs_dir)+ for ext in ["*.pdf", "*.docx", "*.txt", "*.md"]:+ doc_files.extend([str(f) for f in p.glob(ext)])if not doc_files:- logger.error("Error: No documents specified")- logger.error("Use --docs or --docs-dir to specify documents to add")+ logger.error("No documents provided.")return- # Initialize document adder- try:- adder = DocumentAdder(- kb_name=args.kb_name,- base_dir=args.base_dir,- api_key=args.api_key,- base_url=args.base_url,- )- except ValueError as e:- logger.error(f"Error: {e!s}")- return+ adder = DocumentAdder(args.kb_name, args.base_dir, args.api_key, args.base_url)- logger.info(f"\n{'=' * 60}")- logger.info(f"Adding documents to knowledge base: {args.kb_name}")- logger.info(f"{'=' * 60}\n")+ # 1. Sync Phase (Validate and Stage)+ new_files = adder.add_documents(doc_files, allow_duplicates=args.allow_duplicates)- # Add documents to raw directory- new_files = adder.add_documents(doc_files, skip_duplicates=not args.allow_duplicates)-- if not new_files:- logger.info("\nNo new files need processing")- return-- # Process new documents- processed_files = []- if not args.skip_processing:- processed_files = await adder.process_new_documents(new_files)+ # 2. Async Ingestion (Process and Canonize)+ if new_files:+ processed = await adder.process_new_documents(new_files)+ if processed:+ adder.extract_numbered_items_for_new_docs(processed)+ adder.update_metadata(len(processed))+ logger.info(f"Done! Successfully added {len(processed)} documents.")else:- logger.info("\nSkipping document processing (--skip-processing specified)")- processed_files = new_files-- # Extract numbered items for new documents- if not args.skip_processing and not args.skip_extract and processed_files:- adder.extract_numbered_items_for_new_docs(processed_files, batch_size=args.batch_size)- elif args.skip_extract:- logger.info("\nSkipping numbered items extraction (--skip-extract specified)")-- # Update metadata- adder.update_metadata(len(new_files))-- logger.info(f"\n{'=' * 60}")- logger.info(- f"✓ Successfully added {len(new_files)} documents to knowledge base '{args.kb_name}'!"- )- logger.info(f"{'=' * 60}\n")+ logger.info("No new unique documents to add.")if __name__ == "__main__":- # Logging configuration is done during module import, no need to configure again hereasyncio.run(main())diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.pyindex 7970151e2..7d348a99a 100644--- a/src/knowledge/initializer.py+++ b/src/knowledge/initializer.py@@ -17,21 +17,11 @@ import jsonimport osfrom pathlib import Pathimport shutil-import sys-project_root = Path(__file__).parent.parent.parent-sys.path.insert(0, str(project_root))--from dotenv import load_dotenv--# Import RAGService for dynamic provider selection based on RAG_PROVIDER env var-from src.services.rag.service import RAGService+from src.logging import get_loggerfrom src.services.embedding import get_embedding_configfrom src.services.llm import get_llm_config--load_dotenv(dotenv_path=".env", override=False)--from src.logging import get_logger+from src.services.rag.service import RAGServicelogger = get_logger("KnowledgeInit")@@ -47,9 +37,9 @@ class KnowledgeBaseInitializer:self,kb_name: str,base_dir="./data/knowledge_bases",- api_key: str = None,- base_url: str = None,- progress_tracker: ProgressTracker = None,+ api_key: str | None = None,+ base_url: str | None = None,+ progress_tracker: ProgressTracker | None = None,):self.kb_name = kb_nameself.base_dir = Path(base_dir)@@ -152,7 +142,7 @@ class KnowledgeBaseInitializer:"""Process documents using RAGService with dynamic provider selection"""provider = os.getenv("RAG_PROVIDER", "raganything")logger.info(f"Processing documents with RAG provider: {provider}")-+self.progress_tracker.update(ProgressStage.PROCESSING_DOCUMENTS,f"Starting to process documents with {provider} provider...",@@ -182,8 +172,10 @@ class KnowledgeBaseInitializer:# Initialize RAGService with the selected providerrag_service = RAGService(- kb_base_dir=str(self.base_dir), # Base directory for all KBs (e.g., data/knowledge_bases)- provider=provider+ kb_base_dir=str(+ self.base_dir+ ), # Base directory for all KBs (e.g., data/knowledge_bases)+ provider=provider,)# Convert Path objects to strings for file paths@@ -194,7 +186,7 @@ class KnowledgeBaseInitializer:success = await rag_service.initialize(kb_name=self.kb_name,file_paths=file_paths,- extract_numbered_items=True # Enable numbered items extraction+ extract_numbered_items=True, # Enable numbered items extraction)if success:@@ -210,12 +202,12 @@ class KnowledgeBaseInitializer:self.progress_tracker.update(ProgressStage.ERROR,"Document processing failed",- error="RAG pipeline returned failure"+ error="RAG pipeline returned failure",)except asyncio.TimeoutError:error_msg = "Processing timeout (>10 minutes)"- logger.error(f"✗ Timeout processing documents")+ logger.error("✗ Timeout processing documents")logger.error("Possible causes: Large files, slow embedding API, network issues")self.progress_tracker.update(ProgressStage.ERROR,@@ -226,10 +218,11 @@ class KnowledgeBaseInitializer:error_msg = str(e)logger.error(f"✗ Error processing documents: {error_msg}")import traceback+logger.error(traceback.format_exc())self.progress_tracker.update(ProgressStage.ERROR,- f"Failed to process documents",+ "Failed to process documents",error=error_msg,)@@ -402,7 +395,7 @@ class KnowledgeBaseInitializer:ProgressStage.ERROR, "Numbered items extraction failed", error=error_msg)- async def display_statistics(self, rag: "RAGAnything"):+ async def display_statistics(self, rag):"""Display knowledge base statistics (legacy - for RAGAnything)"""await self.display_statistics_generic()@@ -423,15 +416,15 @@ class KnowledgeBaseInitializer:# Check for RAG storage (different providers use different formats)provider = os.getenv("RAG_PROVIDER", "raganything")-+# RAGAnything/LightRAG formatentities_file = self.rag_storage_dir / "kv_store_full_entities.json"relations_file = self.rag_storage_dir / "kv_store_full_relations.json"chunks_file = self.rag_storage_dir / "kv_store_text_chunks.json"-+# LlamaIndex formatvector_store_dir = self.base_dir / self.kb_name / "vector_store"-+try:if entities_file.exists():with open(entities_file, encoding="utf-8") as f:@@ -447,7 +440,7 @@ class KnowledgeBaseInitializer:with open(chunks_file, encoding="utf-8") as f:chunks = json.load(f)logger.info(f"Text chunks: {len(chunks)}")-+if vector_store_dir.exists():metadata_file = vector_store_dir / "metadata.json"if metadata_file.exists():diff --git a/src/logging/logger.py b/src/logging/logger.pyindex befa1e201..9446424f3 100644--- a/src/logging/logger.py+++ b/src/logging/logger.py@@ -21,6 +21,8 @@ from pathlib import Pathimport sysfrom typing import Any, Optional+from src.config.constants import LOG_SYMBOLS, PROJECT_ROOT+class LogLevel(Enum):"""Log levels with associated symbols"""@@ -55,32 +57,39 @@ class ConsoleFormatter(logging.Formatter):DIM = "\033[2m"# Symbols for different log types- SYMBOLS = {- "DEBUG": "·",- "INFO": "●",- "SUCCESS": "✓",- "WARNING": "⚠",- "ERROR": "✗",- "CRITICAL": "✗",- }+ SYMBOLS = LOG_SYMBOLS++ def __init__(self):+ super().__init__()+ # Check TTY status once during initialization+ stdout_tty = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()+ stderr_tty = hasattr(sys.stderr, "isatty") and sys.stderr.isatty()+ self.use_colors = stdout_tty or stderr_ttydef format(self, record: logging.LogRecord) -> str:# Get module name (padded to 12 chars for alignment)module = getattr(record, "module_name", record.name)module_padded = f"[{module}]".ljust(14)-- # Get symbol (can be overridden via record.symbol)symbol = getattr(record, "symbol", self.SYMBOLS.get(record.levelname, "●"))-- # Get color- level = getattr(record, "display_level", record.levelname)- color = self.COLORS.get(level, self.COLORS["INFO"])+ # Use pre-computed TTY status+ use_colors = self.use_colors+ if use_colors:+ # Get color+ level = getattr(record, "display_level", record.levelname)+ color = self.COLORS.get(level, self.COLORS["INFO"])+ dim = self.DIM+ reset = self.RESET+ else:+ # No colors for non-interactive output+ color = ""+ dim = ""+ reset = ""# Format messagemessage = record.getMessage()# Build output: [Module] ● Message- return f"{self.DIM}{module_padded}{self.RESET} {color}{symbol}{self.RESET} {message}"+ return f"{dim}{module_padded}{reset} {color}{symbol}{reset} {message}"class FileFormatter(logging.Formatter):@@ -145,20 +154,14 @@ class Logger:self.logger = logging.getLogger(f"ai_tutor.{name}")self.logger.setLevel(logging.DEBUG) # Capture all, filter at handlersself.logger.handlers.clear()- self.logger.propagate = False-# Setup log directoryif log_dir is None:- # Default: DeepTutor/data/user/logs/- # Use resolve() to get absolute path, ensuring correct project root regardless of working directory- project_root = Path(__file__).resolve().parent.parent.parent- log_dir = project_root / "data" / "user" / "logs"+ log_dir = PROJECT_ROOT / "data" / "user" / "logs"else:log_dir = Path(log_dir)# If relative path, resolve it relative to project rootif not log_dir.is_absolute():- project_root = Path(__file__).resolve().parent.parent.parent- log_dir = project_root / log_dir+ log_dir = PROJECT_ROOT / log_dirlog_dir.mkdir(parents=True, exist_ok=True)self.log_dir = log_dir@@ -584,8 +587,21 @@ class Logger:self.debug(f"Token Stats: {total_tokens} tokens")def shutdown(self):- """Shutdown the logger and cleanup resources"""- self.remove_task_log_handlers()+ """+ Shut down this logger by cleaning up **all** attached handlers.++ This method iterates over a copy of ``self.logger.handlers``, calls+ ``close()`` on each handler to release any underlying resources+ (such as open file streams or other I/O handles), and then removes+ the handler from the underlying ``logging.Logger`` instance.++ Note:+ This closes and removes every handler currently attached to this+ logger instance (including any task-specific handlers), not just a+ subset of handlers. Callers that previously relied on only+ task-specific handlers being removed should be aware that this+ method now performs a full cleanup of all handlers.+ """# Close all handlersfor handler in self.logger.handlers[:]:handler.close()@@ -624,9 +640,8 @@ def get_logger(from src.services.config import get_path_from_config, load_config_with_main# Use resolve() to get absolute path, ensuring correct project root regardless of working directory- project_root = Path(__file__).resolve().parent.parent.parentconfig = load_config_with_main(- "solve_config.yaml", project_root+ "solve_config.yaml", PROJECT_ROOT) # Use any config to get main.yamllog_dir = get_path_from_config(config, "user_log_dir") or config.get("paths", {}).get("user_log_dir"@@ -637,15 +652,18 @@ def get_logger(if not log_dir_path.is_absolute():# Remove leading ./ if presentlog_dir_str = str(log_dir_path).lstrip("./")- log_dir = str(project_root / log_dir_str)+ log_dir = str(PROJECT_ROOT / log_dir_str)else:log_dir = str(log_dir_path)except Exception:# Fallback to defaultpass+ log_dir_key = str(log_dir) if log_dir is not None else None+ # Create a cache key that includes configuration, using a normalized log_dir+ cache_key = (name, level, console_output, file_output, log_dir_key)- if name not in _loggers:- _loggers[name] = Logger(+ if cache_key not in _loggers:+ _loggers[cache_key] = Logger(name=name,level=level,console_output=console_output,@@ -653,7 +671,7 @@ def get_logger(log_dir=log_dir,)- return _loggers[name]+ return _loggers[cache_key]def reset_logger(name: Optional[str] = None):@@ -666,6 +684,25 @@ def reset_logger(name: Optional[str] = None):global _loggersif name is None:- _loggers.clear()- elif name in _loggers:- del _loggers[name]+ keys_to_remove = list(_loggers.keys())+ else:+ # Remove all loggers with the given name, supporting both tuple and string keys+ keys_to_remove = [+ key+ for key in _loggers.keys()+ if (isinstance(key, tuple) and len(key) > 0 and key[0] == name) or key == name+ ]++ for key in keys_to_remove:+ _loggers.pop(key, None)+++def reload_loggers():+ """+ Reload configuration for all cached loggers.++ This method clears the logger cache, forcing recreation with current config+ on next get_logger() calls.+ """+ global _loggers+ _loggers.clear()diff --git a/src/services/config/loader.py b/src/services/config/loader.pyindex 466524a37..56b0e2716 100644--- a/src/services/config/loader.py+++ b/src/services/config/loader.py@@ -8,6 +8,7 @@ Unified configuration loading for all DeepTutor modules.Provides YAML configuration loading, path resolution, and language parsing."""+import asynciofrom pathlib import Pathfrom typing import Any@@ -46,6 +47,17 @@ def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Anyreturn result+def _load_yaml_file(file_path: Path) -> dict[str, Any]:+ """Load a YAML file and return its contents as a dict."""+ with open(file_path, encoding="utf-8") as f:+ return yaml.safe_load(f) or {}+++async def _load_yaml_file_async(file_path: Path) -> dict[str, Any]:+ """Async version of _load_yaml_file."""+ return await asyncio.to_thread(_load_yaml_file, file_path)++def load_config_with_main(config_file: str, project_root: Path | None = None) -> dict[str, Any]:"""Load configuration file, automatically merge with main.yaml common configuration@@ -67,8 +79,51 @@ def load_config_with_main(config_file: str, project_root: Path | None = None) ->main_config_path = config_dir / "main.yaml"if main_config_path.exists():try:- with open(main_config_path, encoding="utf-8") as f:- main_config = yaml.safe_load(f) or {}+ main_config = _load_yaml_file(main_config_path)+ except Exception as e:+ print(f"⚠️ Failed to load main.yaml: {e}")++ # 2. Load sub-module configuration file+ module_config = {}+ module_config_path = config_dir / config_file+ if module_config_path.exists():+ try:+ module_config = _load_yaml_file(module_config_path)+ except Exception as e:+ print(f"⚠️ Failed to load {config_file}: {e}")++ # 3. Merge configurations: main.yaml as base, sub-module config overrides+ merged_config = _deep_merge(main_config, module_config)++ return merged_config+++async def load_config_with_main_async(+ config_file: str, project_root: Path | None = None+) -> dict[str, Any]:+ """+ Async version of load_config_with_main for non-blocking file operations.++ Load configuration file, automatically merge with main.yaml common configuration++ Args:+ config_file: Sub-module configuration file name (e.g., "solve_config.yaml")+ project_root: Project root directory (if None, will try to auto-detect)++ Returns:+ Merged configuration dictionary+ """+ if project_root is None:+ project_root = PROJECT_ROOT++ config_dir = project_root / "config"++ # 1. Load main.yaml (common configuration)+ main_config = {}+ main_config_path = config_dir / "main.yaml"+ if main_config_path.exists():+ try:+ main_config = await _load_yaml_file_async(main_config_path)except Exception as e:print(f"⚠️ Failed to load main.yaml: {e}")@@ -77,8 +132,7 @@ def load_config_with_main(config_file: str, project_root: Path | None = None) ->module_config_path = config_dir / config_fileif module_config_path.exists():try:- with open(module_config_path, encoding="utf-8") as f:- module_config = yaml.safe_load(f) or {}+ module_config = await _load_yaml_file_async(module_config_path)except Exception as e:print(f"⚠️ Failed to load {config_file}: {e}")diff --git a/src/services/embedding/provider_config.py b/src/services/embedding/provider_config.pyindex 12e46fbcc..eb52d50fa 100644--- a/src/services/embedding/provider_config.py+++ b/src/services/embedding/provider_config.py@@ -10,7 +10,7 @@ import jsonfrom pathlib import Pathfrom typing import Any, Dict, List, Optional-from pydantic import BaseModel, Field+from pydantic import BaseModel, ConfigDict, FieldUSER_DATA_DIR = Path("./data/user")PROVIDERS_FILE = USER_DATA_DIR / "embedding_providers.json"@@ -39,8 +39,7 @@ class EmbeddingProvider(BaseModel):normalized: bool = Field(default=True, description="L2 normalization")truncate: bool = Field(default=True, description="Truncate long texts")- class Config:- populate_by_name = True+ model_config = ConfigDict(populate_by_name=True)class EmbeddingProviderConfigManager:@@ -98,7 +97,7 @@ class EmbeddingProviderConfigManager:"""Add a new provider. If name exists, raises ValueError."""providers = self.list_providers()if any(p.name == provider.name for p in providers):- raise ValueError(f"Provider with name '{provider.name}' already exists.")+ raise ValueError(f"Provider with name '{provider.name}' already exists")# If this is the first provider or set as active, handle activation logicif not providers or provider.is_active:diff --git a/src/services/llm/capabilities.py b/src/services/llm/capabilities.pyindex 53877fb8d..f612395ba 100644--- a/src/services/llm/capabilities.py+++ b/src/services/llm/capabilities.py@@ -19,7 +19,6 @@ Usage:from typing import Any, Optional-# Provider capabilities configuration# Keys are binding names (lowercase), values are capability dictionariesPROVIDER_CAPABILITIES: dict[str, dict[str, Any]] = {@@ -194,7 +193,8 @@ def get_capability(# 1. Check model-specific overrides firstif model:model_lower = model.lower()- for pattern, overrides in MODEL_OVERRIDES.items():+ # Sort by pattern length descending to match most specific first+ for pattern, overrides in sorted(MODEL_OVERRIDES.items(), key=lambda x: -len(x[0])):if model_lower.startswith(pattern):if capability in overrides:return overrides[capability]diff --git a/src/services/llm/client.py b/src/services/llm/client.pyindex d2d6adb68..f2105600f 100644--- a/src/services/llm/client.py+++ b/src/services/llm/client.py@@ -82,23 +82,16 @@ class LLMClient:import asynciotry:- loop = asyncio.get_event_loop()- if loop.is_running():- # If already in an async context, we need to use a different approach- import concurrent.futures-- with concurrent.futures.ThreadPoolExecutor() as executor:- future = executor.submit(- asyncio.run, self.complete(prompt, system_prompt, history, **kwargs)- )- return future.result()- else:- return loop.run_until_complete(- self.complete(prompt, system_prompt, history, **kwargs)- )+ asyncio.get_running_loop()except RuntimeError:+ # No running event loop -> safe to run synchronously.return asyncio.run(self.complete(prompt, system_prompt, history, **kwargs))+ raise RuntimeError(+ "LLMClient.complete_sync() cannot be called from a running event loop. "+ "Use `await llm.complete(...)` instead."+ )+def get_model_func(self):"""Get a function compatible with LightRAG's llm_model_func parameter.@@ -128,6 +121,7 @@ class LLMClient:api_key=self.config.api_key,base_url=self.config.base_url,binding=binding,+ history_messages=history_messages,**kwargs,)@@ -194,6 +188,8 @@ class LLMClient:base_url=self.config.base_url,binding=binding,messages=messages,+ history_messages=history_messages,+ image_data=image_data,**kwargs,)diff --git a/src/services/llm/config.py b/src/services/llm/config.pyindex b15a883aa..3b6440dfc 100644--- a/src/services/llm/config.py+++ b/src/services/llm/config.py@@ -12,6 +12,7 @@ Supports multiple deployment modes:"""from dataclasses import dataclass+import loggingimport osfrom pathlib import Pathimport re@@ -21,6 +22,8 @@ from dotenv import load_dotenvfrom .exceptions import LLMConfigError+logger = logging.getLogger(__name__)+# Load environment variablesPROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parentload_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)@@ -65,6 +68,49 @@ def _get_llm_mode_str() -> str:return os.getenv("LLM_MODE", LLM_MODE_HYBRID).lower()+def _get_llm_config_from_env() -> LLMConfig:+ """Get LLM configuration from environment variables."""+ binding = _strip_value(os.getenv("LLM_BINDING", "openai"))+ model = _strip_value(os.getenv("LLM_MODEL"))+ api_key = _strip_value(os.getenv("LLM_API_KEY"))+ base_url = _strip_value(os.getenv("LLM_HOST"))+ api_version = _strip_value(os.getenv("LLM_API_VERSION"))++ # Validate required configuration+ if not model:+ raise LLMConfigError(+ "LLM_MODEL not set, please configure it in .env file or activate a provider"+ )++ # Determine provider type from base_url+ from .utils import is_local_llm_server++ provider_type: Literal["api", "local"] = "local" if is_local_llm_server(base_url) else "api"++ # Check if API key is required (not required for local providers)+ requires_key = (+ provider_type == "api" or os.getenv("LLM_API_KEY_REQUIRED", "false").lower() == "true"+ )++ if requires_key and not api_key:+ raise LLMConfigError(+ "LLM_API_KEY not set, please configure it in .env file or activate a provider"+ )+ if not base_url:+ raise LLMConfigError(+ "LLM_HOST not set, please configure it in .env file or activate a provider"+ )++ return LLMConfig(+ binding=binding,+ model=model,+ api_key=api_key or "",+ base_url=base_url,+ api_version=api_version,+ provider_type=provider_type,+ )++def get_llm_config() -> LLMConfig:"""Load LLM configuration from environment variables or provider manager.@@ -114,48 +160,67 @@ def get_llm_config() -> LLMConfig:provider_type=getattr(active_provider, "provider_type", "local"),)except Exception as e:- print(f"⚠️ Failed to load active provider: {e}")+ logger.warning(f"Failed to load active provider: {e}")# 2. Fallback to environment variables- binding = _strip_value(os.getenv("LLM_BINDING", "openai"))- model = _strip_value(os.getenv("LLM_MODEL"))- api_key = _strip_value(os.getenv("LLM_API_KEY"))- base_url = _strip_value(os.getenv("LLM_HOST"))- api_version = _strip_value(os.getenv("LLM_API_VERSION"))+ return _get_llm_config_from_env()- # Validate required configuration- if not model:- raise LLMConfigError(- "LLM_MODEL not set, please configure it in .env file or activate a provider"- )- # Determine provider type from base_url- from .utils import is_local_llm_server+async def get_llm_config_async() -> LLMConfig:+ """+ Async version of get_llm_config for non-blocking configuration loading.- provider_type: Literal["api", "local"] = "local" if is_local_llm_server(base_url) else "api"+ Load LLM configuration from environment variables or provider manager.- # Check if API key is required (not required for local providers)- requires_key = (- provider_type == "api" or os.getenv("LLM_API_KEY_REQUIRED", "false").lower() == "true"- )+ The behavior depends on the LLM_MODE environment variable:+ - hybrid (default): Use active provider if available, else env config+ - api: Only use API providers (active API provider or env config)+ - local: Only use local providers (active local provider or env config)- if requires_key and not api_key:- raise LLMConfigError(- "LLM_API_KEY not set, please configure it in .env file or activate a provider"- )- if not base_url:- raise LLMConfigError(- "LLM_HOST not set, please configure it in .env file or activate a provider"- )+ Priority:+ 1. Active provider from llm_providers.json (if mode compatible)+ 2. Environment variables (.env)- return LLMConfig(- binding=binding,- model=model,- api_key=api_key or "",- base_url=base_url,- api_version=api_version,- provider_type=provider_type,- )+ Returns:+ LLMConfig: Configuration dataclass++ Raises:+ ValueError: If required configuration is missing+ """+ mode = _get_llm_mode_str()++ # 1. Try to get active provider from provider manager+ try:+ from .provider import provider_manager++ active_provider = await provider_manager.get_active_provider_async()++ if active_provider:+ provider_is_local = getattr(active_provider, "provider_type", "local") == "local"++ # Check mode compatibility+ use_provider = False+ if mode == LLM_MODE_HYBRID:+ use_provider = True+ elif mode == LLM_MODE_API and not provider_is_local:+ use_provider = True+ elif mode == LLM_MODE_LOCAL and provider_is_local:+ use_provider = True++ if use_provider:+ return LLMConfig(+ binding=active_provider.binding,+ model=active_provider.model,+ api_key=active_provider.api_key,+ base_url=active_provider.base_url,+ api_version=getattr(active_provider, "api_version", None),+ provider_type=getattr(active_provider, "provider_type", "local"),+ )+ except Exception as e:+ logger.warning(f"Failed to load active provider: {e}")++ # 2. Fallback to environment variables (no async needed since these are env vars)+ return _get_llm_config_from_env()def uses_max_completion_tokens(model: str) -> bool:@@ -219,6 +284,7 @@ def get_token_limit_kwargs(model: str, max_tokens: int) -> dict:__all__ = ["LLMConfig","get_llm_config",+ "get_llm_config_async","uses_max_completion_tokens","get_token_limit_kwargs","LLM_MODE_API",diff --git a/src/services/llm/error_mapping.py b/src/services/llm/error_mapping.pynew file mode 100644index 000000000..4ef511dc2--- /dev/null+++ b/src/services/llm/error_mapping.py@@ -0,0 +1,125 @@+"""+Error Mapping - Map provider-specific errors to unified exceptions.+"""++from __future__ import annotations++from dataclasses import dataclass+import logging+from typing import Callable, List, Optional, Type++try:+ import openai # type: ignore++ _HAS_OPENAI = True+except ImportError: # pragma: no cover+ openai = None # type: ignore+ _HAS_OPENAI = False+++logger = logging.getLogger(__name__)+++class LLMError(Exception):+ """Base exception for all LLM-related errors."""+++class LLMAPIError(LLMError):+ """Generic API error raised for provider-specific failures."""++ def __init__(+ self,+ message: str,+ *,+ status_code: Optional[int] = None,+ provider: Optional[str] = None,+ ) -> None:+ super().__init__(message)+ self.status_code = status_code+ self.provider = provider+++class LLMAuthenticationError(LLMAPIError):+ """Authentication/authorization related error for LLM providers."""+++class LLMRateLimitError(LLMAPIError):+ """Rate limiting / quota exhaustion error for LLM providers."""+++class ProviderContextWindowError(LLMAPIError):+ """Error indicating the request exceeded the provider's context window."""+++ErrorClassifier = Callable[[Exception], bool]+++@dataclass(frozen=True)+class MappingRule:+ classifier: ErrorClassifier+ factory: Callable[[Exception, Optional[str]], LLMError]+++def _instance_of(*types: Type[BaseException]) -> ErrorClassifier:+ return lambda exc: isinstance(exc, types)+++def _message_contains(*needles: str) -> ErrorClassifier:+ def _classifier(exc: Exception) -> bool:+ msg = str(exc).lower()+ return any(needle in msg for needle in needles)++ return _classifier+++_GLOBAL_RULES: List[MappingRule] = [+ MappingRule(+ classifier=_message_contains("rate limit", "429", "quota"),+ factory=lambda exc, provider: LLMRateLimitError(str(exc), provider=provider),+ ),+ MappingRule(+ classifier=_message_contains("context length", "maximum context"),+ factory=lambda exc, provider: ProviderContextWindowError(str(exc), provider=provider),+ ),+]++if _HAS_OPENAI:+ _GLOBAL_RULES[:0] = [+ MappingRule(+ classifier=_instance_of(openai.AuthenticationError),+ factory=lambda exc, provider: LLMAuthenticationError(str(exc), provider=provider),+ ),+ MappingRule(+ classifier=_instance_of(openai.RateLimitError),+ factory=lambda exc, provider: LLMRateLimitError(str(exc), provider=provider),+ ),+ ]++# Attempt to load Anthropic and Google rules if SDKs are present+try:+ import anthropic++ _GLOBAL_RULES.append(+ MappingRule(+ classifier=_instance_of(anthropic.RateLimitError),+ factory=lambda exc, provider: LLMRateLimitError(str(exc), provider=provider),+ )+ )+except ImportError:+ pass+++def map_error(exc: Exception, provider: Optional[str] = None) -> LLMError:+ """Map provider-specific errors to unified internal exceptions."""+ # Heuristic check for status codes before rules+ status_code = getattr(exc, "status_code", None)+ if status_code == 401:+ return LLMAuthenticationError(str(exc), provider=provider)+ if status_code == 429:+ return LLMRateLimitError(str(exc), provider=provider)++ for rule in _GLOBAL_RULES:+ if rule.classifier(exc):+ return rule.factory(exc, provider)++ return LLMAPIError(str(exc), status_code=status_code, provider=provider)diff --git a/src/services/llm/exceptions.py b/src/services/llm/exceptions.pyindex 9f2196ea9..d10975b26 100644--- a/src/services/llm/exceptions.py+++ b/src/services/llm/exceptions.py@@ -4,63 +4,38 @@ LLM Service ExceptionsCustom exception classes for the LLM service.Provides a consistent exception hierarchy for better error handling.--Usage:- from src.services.llm.exceptions import LLMError, LLMConfigError, LLMAPIError-- try:- response = await complete(...)- except LLMConfigError as e:- # Handle configuration errors (missing API key, etc.)- logger.error(f"Configuration error: {e}")- except LLMAPIError as e:- # Handle API errors (rate limits, invalid requests, etc.)- logger.error(f"API error: {e.status_code} - {e.message}")- except LLMError as e:- # Handle all other LLM-related errors- logger.error(f"LLM error: {e}")+Maintains parity with upstream dev branch."""-from typing import Optional+from typing import Any, Dict, Optionalclass LLMError(Exception):"""Base exception for all LLM-related errors."""- def __init__(self, message: str, details: Optional[dict] = None):+ def __init__(+ self, message: str, details: Optional[Dict[str, Any]] = None, provider: Optional[str] = None+ ):super().__init__(message)self.message = messageself.details = details or {}+ self.provider = providerdef __str__(self) -> str:+ provider_prefix = f"[{self.provider}] " if self.provider else ""if self.details:- return f"{self.message} (details: {self.details})"- return self.message+ return f"{provider_prefix}{self.message} (details: {self.details})"+ return f"{provider_prefix}{self.message}"class LLMConfigError(LLMError):- """- Raised when there's an error in LLM configuration.-- Examples:- - Missing API key- - Missing model name- - Invalid base URL- - Missing required environment variables- """+ """Raised when there's an error in LLM configuration."""passclass LLMProviderError(LLMError):- """- Raised when there's an error with the LLM provider.-- Examples:- - Provider not found- - Provider not configured- - Provider activation failed- """+ """Raised when there's an error with the LLM provider."""pass@@ -68,10 +43,7 @@ class LLMProviderError(LLMError):class LLMAPIError(LLMError):"""Raised when an API call to an LLM provider fails.-- Attributes:- status_code: HTTP status code from the API (if available)- provider: Name of the provider that returned the error+ Standardizes status_code and provider name."""def __init__(@@ -79,11 +51,10 @@ class LLMAPIError(LLMError):message: str,status_code: Optional[int] = None,provider: Optional[str] = None,- details: Optional[dict] = None,+ details: Optional[Dict[str, Any]] = None,):- super().__init__(message, details)+ super().__init__(message, details, provider)self.status_code = status_code- self.provider = providerdef __str__(self) -> str:parts = []@@ -96,9 +67,7 @@ class LLMAPIError(LLMError):class LLMTimeoutError(LLMAPIError):- """- Raised when an API call times out.- """+ """Raised when an API call times out."""def __init__(self,@@ -111,9 +80,7 @@ class LLMTimeoutError(LLMAPIError):class LLMRateLimitError(LLMAPIError):- """- Raised when rate limited by the API.- """+ """Raised when rate limited by the API."""def __init__(self,@@ -126,9 +93,7 @@ class LLMRateLimitError(LLMAPIError):class LLMAuthenticationError(LLMAPIError):- """- Raised when authentication fails (invalid API key, etc.).- """+ """Raised when authentication fails (invalid API key, etc.)."""def __init__(self,@@ -139,9 +104,7 @@ class LLMAuthenticationError(LLMAPIError):class LLMModelNotFoundError(LLMAPIError):- """- Raised when the requested model is not found or not available.- """+ """Raised when the requested model is not found."""def __init__(self,@@ -153,6 +116,27 @@ class LLMModelNotFoundError(LLMAPIError):self.model = model+class LLMParseError(LLMError):+ """Raised when parsing LLM output fails."""++ def __init__(+ self,+ message: str = "Failed to parse LLM output",+ provider: Optional[str] = None,+ details: Optional[Dict[str, Any]] = None,+ ):+ super().__init__(message, details=details, provider=provider)+++# Multi-provider specific aliases for mapping rules+class ProviderQuotaExceededError(LLMRateLimitError):+ pass+++class ProviderContextWindowError(LLMAPIError):+ pass++__all__ = ["LLMError","LLMConfigError",@@ -162,4 +146,7 @@ __all__ = ["LLMRateLimitError","LLMAuthenticationError","LLMModelNotFoundError",+ "LLMParseError",+ "ProviderQuotaExceededError",+ "ProviderContextWindowError",]diff --git a/src/services/llm/factory.py b/src/services/llm/factory.pyindex 002c97f73..c1282674f 100644--- a/src/services/llm/factory.py+++ b/src/services/llm/factory.py@@ -36,8 +36,12 @@ from enum import Enumimport osfrom typing import Any, AsyncGenerator, Dict, List, Optional+import tenacity++from src.logging.logger import get_logger+from . import cloud_provider, local_provider-from .config import LLMConfig, get_llm_config+from .config import get_llm_configfrom .exceptions import (LLMAPIError,LLMAuthenticationError,@@ -47,6 +51,8 @@ from .exceptions import (from .provider import provider_managerfrom .utils import is_local_llm_server+# Initialize logger+logger = get_logger("LLMFactory")# Default retry configurationDEFAULT_MAX_RETRIES = 3@@ -62,18 +68,19 @@ def _is_retriable_error(error: Exception) -> bool:- Timeout errors- Rate limit errors (429)- Server errors (5xx)+ - Network/connection errorsNon-retriable errors:- Authentication errors (401)- Bad request (400)- Not found (404)-- Args:- error: The exception to check-- Returns:- True if the error is retriable+ - Client errors (4xx except 429)"""+ from aiohttp import ClientError+ from requests.exceptions import RequestException++ if isinstance(error, (asyncio.TimeoutError, ClientError, RequestException)):+ return Trueif isinstance(error, LLMTimeoutError):return Trueif isinstance(error, LLMRateLimitError):@@ -96,60 +103,6 @@ def _is_retriable_error(error: Exception) -> bool:return True-async def _execute_with_retry(- func,- max_retries: int = DEFAULT_MAX_RETRIES,- retry_delay: float = DEFAULT_RETRY_DELAY,- exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,- **kwargs,-):- """- Execute a function with retry logic.-- Args:- func: Async function to execute- max_retries: Maximum number of retry attempts- retry_delay: Initial delay between retries (seconds)- exponential_backoff: Whether to use exponential backoff- **kwargs: Arguments to pass to the function-- Returns:- Result from the function-- Raises:- The last exception if all retries fail- """- last_exception = None- delay = retry_delay-- for attempt in range(max_retries + 1):- try:- return await func(**kwargs)- except Exception as e:- last_exception = e-- # Check if we should retry- if attempt >= max_retries or not _is_retriable_error(e):- raise-- # Calculate delay for next attempt- if exponential_backoff:- current_delay = delay * (2**attempt)- else:- current_delay = delay-- # Special handling for rate limit errors with retry_after- if isinstance(e, LLMRateLimitError) and e.retry_after:- current_delay = max(current_delay, e.retry_after)-- # Wait before retrying- await asyncio.sleep(current_delay)-- # Should not reach here, but just in case- if last_exception:- raise last_exception--class LLMMode(str, Enum):"""LLM deployment mode."""@@ -206,7 +159,7 @@ def get_mode_info() -> Dict[str, Any]:"""mode = get_llm_mode()active_provider = provider_manager.get_active_provider()-+try:env_config = get_llm_config()env_configured = bool(env_config.model and (env_config.base_url or env_config.api_key))@@ -291,12 +244,60 @@ async def complete(# Determine which provider to useuse_local = _should_use_local(base_url)- # Define the actual completion function+ # Define helper to determine if a generic LLMAPIError is retriable+ def _is_retriable_llm_api_error(exc: BaseException) -> bool:+ """+ Return True for LLMAPIError instances that represent retriable conditions.++ We only retry on:+ - HTTP 429 (rate limit), or+ - HTTP 5xx server errors.++ All other LLMAPIError instances (e.g., 4xx like 400, 401, 403, 404) are treated+ as non-retriable to avoid unnecessary retries.+ """+ if not isinstance(exc, LLMAPIError):+ return False++ status_code = getattr(exc, "status_code", None)+ if status_code is None:+ # Do not retry when status code is unknown to avoid retrying non-transient errors+ return False++ if status_code == 429:+ return True++ if 500 <= status_code < 600:+ return True++ return False++ # Define the actual completion function with tenacity retry+ @tenacity.retry(+ retry=(+ tenacity.retry_if_exception_type(LLMRateLimitError)+ | tenacity.retry_if_exception_type(LLMTimeoutError)+ | tenacity.retry_if_exception(_is_retriable_llm_api_error)+ ),+ wait=tenacity.wait_exponential(multiplier=retry_delay, min=retry_delay, max=60),+ stop=tenacity.stop_after_attempt(max_retries + 1),+ before_sleep=lambda retry_state: logger.warning(+ f"LLM call failed (attempt {retry_state.attempt_number}/{max_retries + 1}), "+ f"retrying in {retry_state.upcoming_sleep:.1f}s... Error: {str(retry_state.outcome.exception())}"+ ),+ )async def _do_complete(**call_kwargs):- if use_local:- return await local_provider.complete(**call_kwargs)- else:- return await cloud_provider.complete(**call_kwargs)+ try:+ if use_local:+ return await local_provider.complete(**call_kwargs)+ else:+ return await cloud_provider.complete(**call_kwargs)+ except Exception as e:+ # Map raw SDK exceptions to unified exceptions for retry logic+ from .error_mapping import map_error++ mapped_error = map_error(e, provider=call_kwargs.get("binding", "unknown"))+ raise mapped_error from e# Build call kwargscall_kwargs = {@@ -314,14 +315,8 @@ async def complete(call_kwargs["api_version"] = api_versioncall_kwargs["binding"] = binding or "openai"- # Execute with retry- return await _execute_with_retry(- _do_complete,- max_retries=max_retries,- retry_delay=retry_delay,- exponential_backoff=exponential_backoff,- **call_kwargs,- )+ # Execute with retry (handled by tenacity decorator)+ return await _do_complete(**call_kwargs)async def stream(diff --git a/src/services/llm/provider.py b/src/services/llm/provider.pyindex 90c8b1698..9561e8ac2 100644--- a/src/services/llm/provider.py+++ b/src/services/llm/provider.py@@ -6,12 +6,13 @@ Manages LLM provider configurations, persisting them to a JSON file.Supports both API (cloud) and Local (self-hosted) providers."""+import asynciofrom enum import Enumimport jsonfrom pathlib import Pathfrom typing import Any, Dict, List, Literal, Optional-from pydantic import BaseModel, Field+from pydantic import BaseModel, ConfigDict, Field# Define storage pathUSER_DATA_DIR = Path("./data/user")@@ -50,8 +51,7 @@ class LLMProvider(BaseModel):description="Whether this provider requires an API key",)- class Config:- populate_by_name = True+ model_config = ConfigDict(populate_by_name=True)class LLMProviderManager:@@ -79,6 +79,10 @@ class LLMProviderManager:except (json.JSONDecodeError, FileNotFoundError):return []+ async def _load_providers_async(self) -> List[Dict[str, Any]]:+ """Async version of _load_providers."""+ return await asyncio.to_thread(self._load_providers)+def _save_providers(self, providers: List[Dict[str, Any]]):"""Save raw provider data to JSON."""with open(self.storage_path, "w", encoding="utf-8") as f:@@ -105,22 +109,27 @@ class LLMProviderManager:return preturn None+ async def get_active_provider_async(self) -> Optional[LLMProvider]:+ """Async version of get_active_provider."""+ raw_providers = await self._load_providers_async()+ providers = [LLMProvider(**p) for p in raw_providers]+ for p in providers:+ if p.is_active:+ return p+ return None+def add_provider(self, provider: LLMProvider) -> LLMProvider:"""Add a new provider. If name exists, raises ValueError."""providers = self.list_providers()++ # Ensure provider name is uniqueif any(p.name == provider.name for p in providers):- raise ValueError(f"Provider with name '{provider.name}' already exists.")+ raise ValueError(f"Provider with name '{provider.name}' already exists")- # If this is the first provider or set as active, handle activation logic- if not providers or provider.is_active:- # Deactivate others if this one is active- if provider.is_active:- for p in providers:- p.is_active = False- else:- # If it's the only one, make it active by default- if not providers:- provider.is_active = True+ # If the new provider is active, deactivate all others+ if provider.is_active:+ for p in providers:+ p.is_active = Falseproviders.append(provider)self._save_providers([p.model_dump() for p in providers])diff --git a/src/services/llm/providers/anthropic.py b/src/services/llm/providers/anthropic.pynew file mode 100644index 000000000..f80aea73c--- /dev/null+++ b/src/services/llm/providers/anthropic.py@@ -0,0 +1,95 @@+import anthropic++from ..registry import register_provider+from ..telemetry import track_llm_call+from ..types import AsyncStreamGenerator, TutorResponse, TutorStreamChunk+from .base_provider import BaseLLMProvider+++@register_provider("anthropic")+class AnthropicProvider(BaseLLMProvider):+ """Anthropic Claude Provider."""++ def __init__(self, config):+ super().__init__(config)++ self.client = anthropic.AsyncAnthropic(+ api_key=self.api_key,+ )++ @track_llm_call("anthropic")+ async def complete(self, prompt: str, **kwargs) -> TutorResponse:+ model = kwargs.pop("model", None) or self.config.model_name or "claude-3-sonnet-20240229"+ kwargs.pop("stream", None)++ async def _call_api():+ response = await self.client.messages.create(+ model=model,+ max_tokens=kwargs.pop("max_tokens", 1024),+ messages=[{"role": "user", "content": prompt}],+ **kwargs,+ )++ content = response.content[0].text if response.content else ""+ usage = {+ "input_tokens": response.usage.input_tokens,+ "output_tokens": response.usage.output_tokens,+ }++ return TutorResponse(+ content=content,+ raw_response=response.model_dump(),+ usage=usage,+ provider="anthropic",+ model=model,+ finish_reason=response.stop_reason,+ cost_estimate=self.calculate_cost(usage),+ )++ return await self.execute_with_retry(_call_api)++ @track_llm_call("anthropic")+ async def stream(self, prompt: str, **kwargs) -> AsyncStreamGenerator:+ model = kwargs.pop("model", None) or self.config.model_name or "claude-3-sonnet-20240229"+ max_tokens = kwargs.pop("max_tokens", 1024)++ async def _create_stream():+ return await self.client.messages.create(+ model=model,+ max_tokens=max_tokens,+ messages=[{"role": "user", "content": prompt}],+ stream=True,+ **kwargs,+ )++ stream = await self.execute_with_retry(_create_stream)+ accumulated_content = ""+ usage = None++ async for chunk in stream:+ if chunk.type == "content_block_delta" and chunk.delta.text:+ delta = chunk.delta.text+ accumulated_content += delta++ yield TutorStreamChunk(+ content=accumulated_content,+ delta=delta,+ provider="anthropic",+ model=model,+ is_complete=False,+ )+ elif chunk.type == "message_delta" and hasattr(chunk, "usage"):+ # Extract usage from the final message delta+ usage = {+ "input_tokens": chunk.usage.input_tokens,+ "output_tokens": chunk.usage.output_tokens,+ }++ yield TutorStreamChunk(+ content=accumulated_content,+ delta="",+ provider="anthropic",+ model=model,+ is_complete=True,+ usage=usage,+ )diff --git a/src/services/llm/providers/base_provider.py b/src/services/llm/providers/base_provider.pynew file mode 100644index 000000000..60686a743--- /dev/null+++ b/src/services/llm/providers/base_provider.py@@ -0,0 +1,93 @@+"""+Base LLM Provider - Unified interface and configuration.+"""++from abc import ABC, abstractmethod+import asyncio+import logging+import random+from typing import Any, Callable, Dict++from ...utils.error_rate_tracker import record_provider_call+from ...utils.network.circuit_breaker import is_call_allowed, record_call_success+from ..error_mapping import map_error+from ..exceptions import (+ LLMAPIError,+ LLMError,+ LLMRateLimitError,+ LLMTimeoutError,+)+from ..types import AsyncStreamGenerator, TutorResponse++logger = logging.getLogger(__name__)+++class BaseLLMProvider(ABC):+ """Base class for all LLM providers with unified config and retries."""++ def __init__(self, config):+ self.config = config+ self.provider_name = config.provider_name+ self.api_key = config.api_key+ self.base_url = getattr(config, "base_url", "")++ # Isolation: Each provider gets its own traffic controller instance+ self.traffic_controller = getattr(config, "traffic_controller", None)+ if self.traffic_controller is None:+ from ..traffic_control import TrafficController++ self.traffic_controller = TrafficController(provider_name=self.provider_name)++ @abstractmethod+ async def complete(self, prompt: str, **kwargs) -> TutorResponse:+ pass++ @abstractmethod+ async def stream(self, prompt: str, **kwargs) -> AsyncStreamGenerator:+ pass++ def _map_exception(self, e: Exception) -> LLMError:+ return map_error(e, provider=self.provider_name)++ def calculate_cost(self, usage: Dict[str, Any]) -> float:+ """Placeholder for cost calculation logic."""+ return 0.0++ async def execute_with_retry(self, func: Callable, *args, max_retries=3, **kwargs):+ """Standard retry wrapper with exponential backoff."""+ if not is_call_allowed(self.provider_name):+ record_provider_call(self.provider_name, success=False)++ raise LLMError(f"Circuit breaker open for provider {self.provider_name}")++ for attempt in range(max_retries + 1):+ try:+ async with self.traffic_controller:+ result = await func(*args, **kwargs)+ record_provider_call(self.provider_name, success=True)+ record_call_success(self.provider_name)+ return result+ except Exception as e:+ mapped_e = self._map_exception(e)++ # Logic check: should we retry?+ is_retriable = isinstance(mapped_e, (LLMRateLimitError, LLMTimeoutError))+ if isinstance(mapped_e, LLMAPIError):+ status_code = getattr(mapped_e, "status_code", None)+ if status_code is not None and status_code >= 500:+ is_retriable = True++ if attempt >= max_retries or not is_retriable:+ record_provider_call(self.provider_name, success=False)+ raise mapped_e from e++ delay = (1.5**attempt) + (random.random() * 0.5)+ logger.warning(+ "[%s] Call failed. Retry %d/%d in %.2fs. Error: %s",+ self.provider_name,+ attempt + 1,+ max_retries,+ delay,+ str(mapped_e),+ )+ await asyncio.sleep(delay)diff --git a/src/services/llm/providers/open_ai.py b/src/services/llm/providers/open_ai.pynew file mode 100644index 000000000..d9ca71278--- /dev/null+++ b/src/services/llm/providers/open_ai.py@@ -0,0 +1,83 @@+import os++import httpx+import openai++from ..registry import register_provider+from ..telemetry import track_llm_call+from ..types import AsyncStreamGenerator, TutorResponse, TutorStreamChunk+from .base_provider import BaseLLMProvider+++@register_provider("openai")+class OpenAIProvider(BaseLLMProvider):+ """Production-ready OpenAI Provider."""++ def __init__(self, config):+ super().__init__(config)++ # SSL handling for dev/troubleshooting+ http_client = None+ if os.getenv("DISABLE_SSL_VERIFY", "").lower() in ("true", "1", "yes"):+ http_client = httpx.AsyncClient(verify=False)++ self.client = openai.AsyncOpenAI(+ api_key=self.api_key,+ base_url=self.base_url or None,+ http_client=http_client,+ )++ @track_llm_call("openai")+ async def complete(self, prompt: str, **kwargs) -> TutorResponse:+ model = kwargs.pop("model", None) or self.config.model_name or "gpt-4o"+ kwargs.pop("stream", None)++ async def _call_api():+ response = await self.client.chat.completions.create(+ model=model,+ messages=[{"role": "user", "content": prompt}],+ **kwargs,+ )++ choice = response.choices[0]+ usage = response.usage.model_dump() if response.usage else {}++ return TutorResponse(+ content=choice.message.content or "",+ raw_response=response.model_dump(),+ usage=usage,+ provider="openai",+ model=model,+ finish_reason=choice.finish_reason,+ cost_estimate=self.calculate_cost(usage),+ )++ return await self.execute_with_retry(_call_api)++ async def stream(self, prompt: str, **kwargs) -> AsyncStreamGenerator:+ model = kwargs.pop("model", None) or self.config.model_name or "gpt-4o"++ async def _create_stream():+ return await self.client.chat.completions.create(+ model=model, messages=[{"role": "user", "content": prompt}], stream=True, **kwargs+ )++ stream = await self.execute_with_retry(_create_stream)+ accumulated_content = ""++ async for chunk in stream:+ if chunk.choices and chunk.choices[0].delta.content:+ delta = chunk.choices[0].delta.content+ accumulated_content += delta++ yield TutorStreamChunk(+ content=accumulated_content,+ delta=delta,+ provider="openai",+ model=model,+ is_complete=False,+ )++ yield TutorStreamChunk(+ content=accumulated_content, delta="", provider="openai", model=model, is_complete=True+ )diff --git a/src/services/llm/registry.py b/src/services/llm/registry.pynew file mode 100644index 000000000..fa58b7d9d--- /dev/null+++ b/src/services/llm/registry.py@@ -0,0 +1,71 @@+"""+LLM Provider Registry+====================++Simple provider registration system for LLM providers.+"""++from typing import Dict, Type++# Global registry for LLM providers+_provider_registry: Dict[str, Type] = {}+++def register_provider(name: str):+ """+ Decorator to register an LLM provider class.++ Args:+ name: Name to register the provider under++ Returns:+ Decorator function+ """++ def decorator(cls):+ if name in _provider_registry:+ raise ValueError(f"Provider '{name}' is already registered")+ _provider_registry[name] = cls+ cls.__provider_name__ = name # Store name on class for introspection+ return cls++ return decorator+++def get_provider_class(name: str) -> Type:+ """+ Get a registered provider class by name.++ Args:+ name: Provider name++ Returns:+ Provider class++ Raises:+ KeyError: If provider is not registered+ """+ return _provider_registry[name]+++def list_providers() -> list[str]:+ """+ List all registered provider names.++ Returns:+ List of provider names+ """+ return list(_provider_registry.keys())+++def is_provider_registered(name: str) -> bool:+ """+ Check if a provider is registered.++ Args:+ name: Provider name++ Returns:+ True if registered, False otherwise+ """+ return name in _provider_registrydiff --git a/src/services/llm/telemetry.py b/src/services/llm/telemetry.pynew file mode 100644index 000000000..ee9f72d8c--- /dev/null+++ b/src/services/llm/telemetry.py@@ -0,0 +1,40 @@+"""+LLM Telemetry+=============++Basic telemetry tracking for LLM calls.+"""++import functools+import logging+from typing import Any, Callable++logger = logging.getLogger(__name__)+++def track_llm_call(provider_name: str):+ """+ Decorator to track LLM calls for telemetry.++ Args:+ provider_name: Name of the provider being called++ Returns:+ Decorator function+ """++ def decorator(func: Callable) -> Callable:+ @functools.wraps(func)+ async def wrapper(*args, **kwargs) -> Any:+ logger.debug(f"LLM call to {provider_name}: {func.__name__}")+ try:+ result = await func(*args, **kwargs)+ logger.debug(f"LLM call to {provider_name} completed successfully")+ return result+ except Exception as e:+ logger.warning(f"LLM call to {provider_name} failed: {e}")+ raise++ return wrapper++ return decoratordiff --git a/src/services/llm/types.py b/src/services/llm/types.pynew file mode 100644index 000000000..d7e8c92cb--- /dev/null+++ b/src/services/llm/types.py@@ -0,0 +1,27 @@+from typing import Any, AsyncGenerator, Dict, Optional++from pydantic import BaseModel, Field+++class TutorResponse(BaseModel):+ content: str+ raw_response: Dict[str, Any]+ usage: Dict[str, int] = Field(+ default_factory=lambda: {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}+ )+ provider: str+ model: str+ finish_reason: Optional[str] = None+ cost_estimate: float = 0.0+++class TutorStreamChunk(BaseModel):+ content: str+ delta: str+ provider: str+ model: str+ is_complete: bool = False+ usage: Optional[Dict[str, int]] = None+++AsyncStreamGenerator = AsyncGenerator[TutorStreamChunk, None]diff --git a/src/services/llm/utils.py b/src/services/llm/utils.pyindex 52da888b5..b0eec0ec4 100644--- a/src/services/llm/utils.py+++ b/src/services/llm/utils.py@@ -29,14 +29,14 @@ CLOUD_DOMAINS = [# Common local server portsLOCAL_PORTS = [- ":1234", # LM Studio+ ":1234", # LM Studio":11434", # Ollama- ":8000", # vLLM- ":8080", # llama.cpp- ":5000", # Common dev port- ":3000", # Common dev port- ":8001", # Alternative vLLM- ":5001", # Alternative dev port+ ":8000", # vLLM+ ":8080", # llama.cpp+ ":5000", # Common dev port+ ":3000", # Common dev port+ ":8001", # Alternative vLLM+ ":5001", # Alternative dev port]# Local hostname indicators@@ -49,10 +49,10 @@ LOCAL_HOSTS = [# Ports that need /v1 suffix for OpenAI compatibilityV1_SUFFIX_PORTS = {":11434", # Ollama- ":1234", # LM Studio- ":8000", # vLLM- ":8001", # Alternative vLLM- ":8080", # llama.cpp+ ":1234", # LM Studio+ ":8000", # vLLM+ ":8001", # Alternative vLLM+ ":8080", # llama.cpp}diff --git a/src/services/rag/components/indexers/graph.py b/src/services/rag/components/indexers/graph.pyindex f20f3303e..ebde56651 100644--- a/src/services/rag/components/indexers/graph.py+++ b/src/services/rag/components/indexers/graph.py@@ -61,7 +61,9 @@ class GraphIndexer(BaseComponent):embed_client = get_embedding_client()# LLM function using services- def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):+ def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):+ if history_messages is None:+ history_messages = []return openai_complete_if_cache(llm_client.config.model,prompt,@@ -115,8 +117,26 @@ class GraphIndexer(BaseComponent):for doc in documents:if doc.content:- # RAGAnything uses process_document_complete_lightrag_api instead of ainsert- await rag.process_document_complete_lightrag_api(doc.content)+ # Write content to temporary file+ import os+ import tempfile++ tmp_path = None+ try:+ with tempfile.NamedTemporaryFile(+ mode="w", encoding="utf-8", suffix=".txt", delete=False+ ) as tmp_file:+ tmp_file.write(doc.content)+ tmp_path = tmp_file.name++ # Use RAGAnything API+ working_dir = str(Path(self.kb_base_dir) / kb_name / "rag_storage")+ output_dir = os.path.join(working_dir, "output")+ os.makedirs(output_dir, exist_ok=True)+ await rag.process_document_complete(tmp_path, output_dir)+ finally:+ if tmp_path and os.path.exists(tmp_path):+ os.unlink(tmp_path)self.logger.info("Knowledge graph built successfully")return Truediff --git a/src/services/rag/components/indexers/lightrag.py b/src/services/rag/components/indexers/lightrag.pyindex e7170264f..2e91a6966 100644--- a/src/services/rag/components/indexers/lightrag.py+++ b/src/services/rag/components/indexers/lightrag.py@@ -62,7 +62,9 @@ class LightRAGIndexer(BaseComponent):embed_client = get_embedding_client()# LLM function using services (SYNC - LightRAG expects sync functions)- def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):+ def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):+ if history_messages is None:+ history_messages = []return openai_complete_if_cache(llm_client.config.model,prompt,@@ -106,12 +108,13 @@ class LightRAGIndexer(BaseComponent):# Use log forwarding contextwith LightRAGLogContext(scene="LightRAG-Indexer"):rag = self._get_lightrag_instance(kb_name)-+# Initialize storages (required for LightRAG)await rag.initialize_storages()-+# Initialize pipeline status (required for document processing)from lightrag.kg.shared_storage import initialize_pipeline_status+await initialize_pipeline_status()for doc in documents:diff --git a/src/services/rag/components/indexers/vector.py b/src/services/rag/components/indexers/vector.pyindex 38fcac3d8..551b63ce5 100644--- a/src/services/rag/components/indexers/vector.py+++ b/src/services/rag/components/indexers/vector.py@@ -7,8 +7,8 @@ Provides fast similarity search for RAG retrieval."""import json-import picklefrom pathlib import Path+import picklefrom typing import List, Optionalimport numpy as np@@ -22,7 +22,7 @@ class VectorIndexer(BaseComponent):Vector indexer using FAISS for fast similarity search.Creates and stores vector embeddings for efficient retrieval.- Falls back to simple cosine similarity if FAISS is not available.+ Falls back to simple vector storage if FAISS is not available."""name = "vector_indexer"@@ -40,11 +40,12 @@ class VectorIndexer(BaseComponent):/ "data"/ "knowledge_bases")-+# Try to import FAISS, fallback to simple storage if not availableself.use_faiss = Falsetry:import faiss+self.faiss = faissself.use_faiss = Trueself.logger.info("Using FAISS for vector indexing")@@ -87,37 +88,41 @@ class VectorIndexer(BaseComponent):kb_dir.mkdir(parents=True, exist_ok=True)# Convert embeddings to numpy array- embeddings = np.array([- chunk.embedding if isinstance(chunk.embedding, list)- else chunk.embedding.tolist()- for chunk in all_chunks- ], dtype=np.float32)-+ embeddings = np.array(+ [+ chunk.embedding if isinstance(chunk.embedding, list) else chunk.embedding.tolist()+ for chunk in all_chunks+ ],+ dtype=np.float32,+ )+# Store metadata separatelymetadata = []for i, chunk in enumerate(all_chunks):- metadata.append({- "id": i,- "content": chunk.content,- "type": chunk.chunk_type,- "metadata": chunk.metadata,- })-+ metadata.append(+ {+ "id": i,+ "content": chunk.content,+ "type": chunk.chunk_type,+ "metadata": chunk.metadata,+ }+ )+# Save metadatawith open(kb_dir / "metadata.json", "w", encoding="utf-8") as f:json.dump(metadata, f, ensure_ascii=False, indent=2)-+if self.use_faiss:- # Create FAISS index+ # Create FAISS index for inner product (cosine similarity with normalized vectors)dimension = embeddings.shape[1]- index = self.faiss.IndexFlatL2(dimension) # L2 distance (euclidean)-- # Normalize vectors for cosine similarity+ index = self.faiss.IndexFlatIP(dimension) # Inner product for cosine similarity++ # Normalize vectors for cosine similarity (inner product of normalized vectors = cosine similarity)self.faiss.normalize_L2(embeddings)-+# Add vectors to indexindex.add(embeddings)-+# Save FAISS indexself.faiss.write_index(index, str(kb_dir / "index.faiss"))self.logger.info(f"FAISS index saved with {index.ntotal} vectors")diff --git a/src/services/rag/components/retrievers/dense.py b/src/services/rag/components/retrievers/dense.pyindex 8597b6d5c..bfbeb56ce 100644--- a/src/services/rag/components/retrievers/dense.py+++ b/src/services/rag/components/retrievers/dense.py@@ -6,9 +6,9 @@ Dense vector-based retriever using FAISS or cosine similarity."""import json-import picklefrom pathlib import Path-from typing import Any, Dict, List, Optional+import pickle+from typing import Any, Dict, Optionalimport numpy as np@@ -40,11 +40,12 @@ class DenseRetriever(BaseComponent):/ "knowledge_bases")self.top_k = top_k-+# Try to import FAISSself.use_faiss = Falsetry:import faiss+self.faiss = faissself.use_faiss = Trueexcept ImportError:@@ -70,7 +71,7 @@ class DenseRetriever(BaseComponent):# Get query embeddingclient = get_embedding_client()query_embedding = np.array((await client.embed([query]))[0], dtype=np.float32)-+# Load indexkb_dir = Path(self.kb_base_dir) / kb_name / "vector_store"metadata_file = kb_dir / "metadata.json"@@ -87,32 +88,38 @@ class DenseRetriever(BaseComponent):"results": [],}- # Load metadata and info+ # Load metadata and info (info.json is optional)with open(metadata_file, "r", encoding="utf-8") as f:metadata = json.load(f)-- with open(info_file, "r", encoding="utf-8") as f:- info = json.load(f)-++ if info_file.exists():+ with open(info_file, "r", encoding="utf-8") as f:+ info = json.load(f)+ else:+ info = {"use_faiss": False}+use_faiss = info.get("use_faiss", False)-+if use_faiss and self.use_faiss:# Use FAISS for fast searchindex_file = kb_dir / "index.faiss"if not index_file.exists():self.logger.error(f"FAISS index file not found: {index_file}")return self._empty_response(query)-+# Load FAISS indexindex = self.faiss.read_index(str(index_file))-- # Normalize query vector for cosine similarity- query_vec = query_embedding.reshape(1, -1)- self.faiss.normalize_L2(query_vec)-++ # Normalize query vector for cosine similarity without modifying original+ norm = np.linalg.norm(query_embedding)+ if norm > 0:+ query_vec = (query_embedding / norm).reshape(1, -1)+ else:+ query_vec = query_embedding.reshape(1, -1)+# Searchdistances, indices = index.search(query_vec, min(top_k, len(metadata)))-+# Build resultsresults = []for dist, idx in zip(distances[0], indices[0]):@@ -125,20 +132,28 @@ class DenseRetriever(BaseComponent):if not embeddings_file.exists():self.logger.error(f"Embeddings file not found: {embeddings_file}")return self._empty_response(query)-+with open(embeddings_file, "rb") as f:embeddings = pickle.load(f)-- # Normalize for cosine similarity- query_vec = query_embedding / np.linalg.norm(query_embedding)- doc_vecs = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)-++ # Normalize for cosine similarity (avoid division by zero)+ query_norm = np.linalg.norm(query_embedding)+ if query_norm > 0:+ query_vec = query_embedding / query_norm+ else:+ query_vec = query_embedding # Keep as is if zero norm++ norms = np.linalg.norm(embeddings, axis=1, keepdims=True)+ # Replace zero norms with 1 to avoid division by zero+ norms = np.where(norms == 0, 1, norms)+ doc_vecs = embeddings / norms+# Compute similaritiessimilarities = np.dot(doc_vecs, query_vec)-+# Get top-k resultstop_indices = np.argsort(similarities)[::-1][:top_k]-+results = []for idx in top_indices:score = float(similarities[idx])@@ -153,11 +168,13 @@ class DenseRetriever(BaseComponent):if content: # Only include non-empty chunks# Add chunk without score prefix for clean LLM inputcontent_parts.append(content)- sources.append({- "content": content,- "score": score,- "metadata": item.get("metadata", {}),- })+ sources.append(+ {+ "content": content,+ "score": score,+ "metadata": item.get("metadata", {}),+ }+ )# Join chunks with clear separationcontent = "\n\n".join(content_parts)@@ -170,7 +187,7 @@ class DenseRetriever(BaseComponent):"provider": "llamaindex","results": sources,}-+def _empty_response(self, query: str) -> Dict[str, Any]:"""Return empty response when no results found."""return {diff --git a/src/services/rag/components/retrievers/hybrid.py b/src/services/rag/components/retrievers/hybrid.pyindex 9211e4dc4..bb26be42a 100644--- a/src/services/rag/components/retrievers/hybrid.py+++ b/src/services/rag/components/retrievers/hybrid.py@@ -20,7 +20,7 @@ class HybridRetriever(BaseComponent):"""name = "hybrid_retriever"- _instances: Dict[str, any] = {}+ _instances: Dict[str, Any] = {}def __init__(self, kb_base_dir: Optional[str] = None):"""@@ -59,7 +59,9 @@ class HybridRetriever(BaseComponent):llm_client = get_llm_client()embed_client = get_embedding_client()- def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):+ def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):+ if history_messages is None:+ history_messages = []return openai_complete_if_cache(llm_client.config.model,prompt,diff --git a/src/services/rag/components/retrievers/lightrag.py b/src/services/rag/components/retrievers/lightrag.pyindex 00361f91f..907ef6aa4 100644--- a/src/services/rag/components/retrievers/lightrag.py+++ b/src/services/rag/components/retrievers/lightrag.py@@ -7,7 +7,7 @@ Pure LightRAG retriever (text-only, no multimodal).from pathlib import Pathimport sys-from typing import Any, Dict, List, Optional+from typing import Any, ClassVar, Dict, Optionalfrom ..base import BaseComponent@@ -21,7 +21,7 @@ class LightRAGRetriever(BaseComponent):"""name = "lightrag_retriever"- _instances: Dict[str, any] = {}+ _instances: ClassVar[Dict[str, Any]] = {}def __init__(self, kb_base_dir: Optional[str] = None):"""@@ -51,7 +51,7 @@ class LightRAGRetriever(BaseComponent):sys.path.insert(0, str(raganything_path))try:- from lightrag import LightRAG, QueryParam+ from lightrag import LightRAGfrom lightrag.llm.openai import openai_complete_if_cachefrom src.services.embedding import get_embedding_client@@ -61,7 +61,9 @@ class LightRAGRetriever(BaseComponent):embed_client = get_embedding_client()# LLM function using services (SYNC - LightRAG expects sync functions)- def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):+ def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):+ if history_messages is None:+ history_messages = []return openai_complete_if_cache(llm_client.config.model,prompt,@@ -117,6 +119,7 @@ class LightRAGRetriever(BaseComponent):# Initialize storages if not already initializedawait rag.initialize_storages()from lightrag.kg.shared_storage import initialize_pipeline_status+await initialize_pipeline_status()# Import QueryParam for proper query parameter passingdiff --git a/src/services/rag/pipeline.py b/src/services/rag/pipeline.pyindex 0dcec98ea..c9bf09601 100644--- a/src/services/rag/pipeline.py+++ b/src/services/rag/pipeline.py@@ -97,7 +97,7 @@ class RAGPipeline:self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files")if not self._parser:- raise ValueError("No parser configured. Use .parser() to set one.")+ raise ValueError("No parser configured. Use .parser() to set one")# Stage 1: Parse documentsself.logger.info("Stage 1: Parsing documents...")@@ -143,7 +143,7 @@ class RAGPipeline:Search results dictionary"""if not self._retriever:- raise ValueError("No retriever configured. Use .retriever() to set one.")+ raise ValueError("No retriever configured. Use .retriever() to set one")return await self._retriever.process(query, kb_name=kb_name, **kwargs)@@ -157,9 +157,19 @@ class RAGPipeline:Returns:True if successful"""+ # Validate kb_name to prevent path traversal+ if not kb_name or kb_name in (".", "..") or "/" in kb_name or "\\" in kb_name:+ raise ValueError(f"Invalid knowledge base name: {kb_name}")+self.logger.info(f"Deleting KB '{kb_name}'")kb_dir = Path(self.kb_base_dir) / kb_name+ # Ensure the resolved path is within the base directory+ kb_dir = kb_dir.resolve()+ base_dir = Path(self.kb_base_dir).resolve()+ if not kb_dir.is_relative_to(base_dir):+ raise ValueError(f"Knowledge base path outside allowed directory: {kb_name}")+if kb_dir.exists():shutil.rmtree(kb_dir)self.logger.info(f"Deleted KB directory: {kb_dir}")diff --git a/src/services/rag/pipelines/llamaindex.py b/src/services/rag/pipelines/llamaindex.pyindex cb2ddb2fa..eb46dbff7 100644--- a/src/services/rag/pipelines/llamaindex.py+++ b/src/services/rag/pipelines/llamaindex.py@@ -5,12 +5,10 @@ LlamaIndex PipelineTrue LlamaIndex integration using official llama-index library."""-import os+import asynciofrom pathlib import Pathfrom typing import Any, Dict, List, Optional-import asyncio-from llama_index.core import (Document,Settings,@@ -23,7 +21,6 @@ from llama_index.core.bridge.pydantic import PrivateAttrfrom src.logging import get_loggerfrom src.services.embedding import get_embedding_client, get_embedding_config-from src.services.llm import get_llm_config# Default knowledge base directoryDEFAULT_KB_BASE_DIR = str(@@ -34,48 +31,50 @@ DEFAULT_KB_BASE_DIR = str(class CustomEmbedding(BaseEmbedding):"""Custom embedding adapter for OpenAI-compatible APIs.-+Works with any OpenAI-compatible endpoint including:- Google Gemini (text-embedding-004)- OpenAI (text-embedding-ada-002, text-embedding-3-*)- Azure OpenAI- Local models with OpenAI-compatible API"""-+_client: Any = PrivateAttr()-+def __init__(self, **kwargs):super().__init__(**kwargs)self._client = get_embedding_client()-+@classmethoddef class_name(cls) -> str:return "custom_embedding"-+async def _aget_query_embedding(self, query: str) -> List[float]:"""Get embedding for a query."""embeddings = await self._client.embed([query])return embeddings[0]-+async def _aget_text_embedding(self, text: str) -> List[float]:"""Get embedding for a text."""embeddings = await self._client.embed([text])return embeddings[0]-+def _get_query_embedding(self, query: str) -> List[float]:"""Sync version - called by LlamaIndex sync API."""# Use nest_asyncio to allow nested event loopsimport nest_asyncio+nest_asyncio.apply()return asyncio.run(self._aget_query_embedding(query))-+def _get_text_embedding(self, text: str) -> List[float]:"""Sync version - called by LlamaIndex sync API."""# Use nest_asyncio to allow nested event loopsimport nest_asyncio+nest_asyncio.apply()return asyncio.run(self._aget_text_embedding(text))-+async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:"""Get embeddings for multiple texts."""return await self._client.embed(texts)@@ -84,7 +83,7 @@ class CustomEmbedding(BaseEmbedding):class LlamaIndexPipeline:"""True LlamaIndex pipeline using official llama-index library.-+Uses LlamaIndex's native components:- VectorStoreIndex for indexing- CustomEmbedding for OpenAI-compatible embeddings@@ -107,22 +106,20 @@ class LlamaIndexPipeline:"""Configure LlamaIndex global settings."""# Get embedding configembedding_cfg = get_embedding_config()-+# Configure custom embedding that works with any OpenAI-compatible APISettings.embed_model = CustomEmbedding()-+# Configure chunkingSettings.chunk_size = 512Settings.chunk_overlap = 50-+self.logger.info(f"LlamaIndex configured: embedding={embedding_cfg.model} "f"({embedding_cfg.dim}D, {embedding_cfg.binding}), chunk_size=512")- async def initialize(- self, kb_name: str, file_paths: List[str], **kwargs- ) -> bool:+ async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:"""Initialize KB using real LlamaIndex components.@@ -134,7 +131,9 @@ class LlamaIndexPipeline:Returns:True if successful"""- self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files using LlamaIndex")+ self.logger.info(+ f"Initializing KB '{kb_name}' with {len(file_paths)} files using LlamaIndex"+ )kb_dir = Path(self.kb_base_dir) / kb_namestorage_dir = kb_dir / "llamaindex_storage"@@ -146,21 +145,21 @@ class LlamaIndexPipeline:for file_path in file_paths:file_path = Path(file_path)self.logger.info(f"Parsing: {file_path.name}")-+# Extract text based on file typeif file_path.suffix.lower() == ".pdf":text = self._extract_pdf_text(file_path)else:with open(file_path, "r", encoding="utf-8") as f:text = f.read()-+if text.strip():doc = Document(text=text,metadata={"file_name": file_path.name,"file_path": str(file_path),- }+ },)documents.append(doc)self.logger.info(f"Loaded: {file_path.name} ({len(text)} chars)")@@ -173,12 +172,12 @@ class LlamaIndexPipeline:# Create index with LlamaIndex (run sync code in thread pool to avoid blocking)self.logger.info(f"Creating VectorStoreIndex with {len(documents)} documents...")-+# Run sync LlamaIndex code in thread pool to avoid blocking async event looploop = asyncio.get_event_loop()index = await loop.run_in_executor(None, # Use default ThreadPoolExecutor- lambda: VectorStoreIndex.from_documents(documents, show_progress=True)+ lambda: VectorStoreIndex.from_documents(documents, show_progress=True),)# Persist index@@ -191,6 +190,7 @@ class LlamaIndexPipeline:except Exception as e:self.logger.error(f"Failed to initialize KB: {e}")import traceback+self.logger.error(traceback.format_exc())return False@@ -249,17 +249,17 @@ class LlamaIndexPipeline:try:# Load index from storage (run in thread pool)loop = asyncio.get_event_loop()-+def load_and_retrieve():storage_context = StorageContext.from_defaults(persist_dir=str(storage_dir))index = load_index_from_storage(storage_context)top_k = kwargs.get("top_k", 5)-+# Use retriever instead of query_engine to avoid LLM requirementretriever = index.as_retriever(similarity_top_k=top_k)nodes = retriever.retrieve(query)return nodes-+# Execute retrieval in thread pool to avoid blockingnodes = await loop.run_in_executor(None, load_and_retrieve)@@ -281,6 +281,7 @@ class LlamaIndexPipeline:except Exception as e:self.logger.error(f"Search failed: {e}")import traceback+self.logger.error(traceback.format_exc())return {"query": query,diff --git a/src/services/rag/pipelines/raganything.py b/src/services/rag/pipelines/raganything.pyindex d6fa42ac2..eea11f4b9 100644--- a/src/services/rag/pipelines/raganything.py+++ b/src/services/rag/pipelines/raganything.py@@ -78,7 +78,9 @@ class RAGAnythingPipeline:llm_client = get_llm_client()embed_client = get_embedding_client()- def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):+ def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):+ if history_messages is None:+ history_messages = []return openai_complete_if_cache(llm_client.config.model,prompt,diff --git a/src/tools/web_search/__init__.py b/src/tools/web_search/__init__.pyindex 62a50e902..454c5e6c1 100644--- a/src/tools/web_search/__init__.py+++ b/src/tools/web_search/__init__.py@@ -37,8 +37,11 @@ from typing import Anyfrom src.logging import get_loggerfrom src.services.config import PROJECT_ROOT, load_config_with_main-from ._legacy import SearchProvider+from .base import BaseSearchProviderfrom .consolidation import AnswerConsolidator++# Backwards compatibility alias+SearchProvider = BaseSearchProviderfrom .providers import (get_available_providers,get_default_provider,@@ -162,7 +165,7 @@ def web_search(_logger.success(f"[{search_provider.name}] Search completed")except Exception as e:_logger.error(f"[{search_provider.name}] Search failed: {e}")- raise Exception(f"{search_provider.name} search failed: {e}")+ raise Exception(f"{search_provider.name} search failed: {e}") from e# Apply consolidation for SERP providers without LLM answersif consolidation and not search_provider.supports_answer:llm_config = {}diff --git a/src/tools/web_search/_legacy.py b/src/tools/web_search/_legacy.pydeleted file mode 100644index 2ce5bf945..000000000--- a/src/tools/web_search/_legacy.py+++ /dev/null@@ -1,24 +0,0 @@-"""-Legacy SearchProvider enum for backward compatibility.--This enum is kept for any existing code that imports it.-New code should use provider names as strings with the web_search() function.-"""--from enum import Enum---class SearchProvider(str, Enum):- """- Supported search providers.-- DEPRECATED: Use provider names directly as strings with web_search().- Example: web_search(query="...", provider="perplexity")- """-- PERPLEXITY = "perplexity"- BAIDU = "baidu"- TAVILY = "tavily"- EXA = "exa"- SERPER = "serper"- JINA = "jina"diff --git a/src/tools/web_search/consolidation.py b/src/tools/web_search/consolidation.pyindex 880fba3ef..c888bb499 100644--- a/src/tools/web_search/consolidation.py+++ b/src/tools/web_search/consolidation.py@@ -104,7 +104,7 @@ PROVIDER_TEMPLATES = {{% endfor %}----*{{ results|length }} results via Jina Reader{% if not results[0].content %} (no-content mode){% endif %}*+*{{ results|length }} results via Jina Reader{% if results and results|length > 0 and not results[0].content %} (no-content mode){% endif %}*{% if links %}### Extracted Links@@ -165,6 +165,7 @@ class AnswerConsolidator:custom_template: str | None = None,llm_config: dict[str, Any] | None = None,max_results: int = 5,+ autoescape: bool = True,):"""Initialize consolidator.@@ -174,12 +175,20 @@ class AnswerConsolidator:custom_template: Custom Jinja2 template stringllm_config: Optional overrides (system_prompt, max_tokens, temperature)max_results: Maximum results to include in answer+ autoescape: Whether to enable Jinja2 autoescape for security (default: True)"""self.consolidation_type = consolidation_typeself.custom_template = custom_templateself.llm_config = llm_config or {}self.max_results = max_results- self.jinja_env = Environment(loader=BaseLoader())+ self.jinja_env = Environment(loader=BaseLoader(), autoescape=autoescape)++ if self.custom_template is not None and autoescape:+ _logger.warning(+ "Custom Jinja2 templates are rendered with autoescape=True. "+ "HTML in rendered variables will be escaped by default; use the "+ "'safe' filter in your template if you intentionally need raw HTML."+ )def consolidate(self, response: WebSearchResponse) -> WebSearchResponse:"""diff --git a/src/tools/web_search/providers/baidu.py b/src/tools/web_search/providers/baidu.pyindex 750a3fcc8..476fd5d21 100644--- a/src/tools/web_search/providers/baidu.py+++ b/src/tools/web_search/providers/baidu.py@@ -99,13 +99,19 @@ class BaiduProvider(BaseSearchProvider):response = requests.post(self.BASE_URL, headers=headers, json=payload, timeout=timeout)if response.status_code != 200:- error_data = response.json() if response.text else {}+ try:+ error_data = response.json() if response.text else {}+ except Exception:+ error_data = {}raise Exception(f"Baidu AI Search API error: {response.status_code} - "f"{error_data.get('message', response.text)}")- data = response.json()+ try:+ data = response.json()+ except Exception as e:+ raise Exception(f"Failed to parse Baidu API response: {e}")# Extract answer from responseanswer = ""diff --git a/src/tools/web_search/providers/exa.py b/src/tools/web_search/providers/exa.pyindex cad32ba1e..269be40d5 100644--- a/src/tools/web_search/providers/exa.py+++ b/src/tools/web_search/providers/exa.py@@ -115,13 +115,19 @@ class ExaProvider(BaseSearchProvider):response = requests.post(self.BASE_URL, headers=headers, json=payload, timeout=timeout)if response.status_code != 200:- error_data = response.json() if response.text else {}+ try:+ error_data = response.json() if response.text else {}+ except Exception:+ error_data = {}self.logger.error(f"Exa API error: {response.status_code}")raise Exception(f"Exa API error: {response.status_code} - {error_data.get('error', response.text)}")- data = response.json()+ try:+ data = response.json()+ except Exception as e:+ raise Exception(f"Failed to parse Exa API response: {e}")self.logger.debug(f"Exa returned {len(data.get('results', []))} results")# Build answer from summariesdiff --git a/src/tools/web_search/providers/perplexity.py b/src/tools/web_search/providers/perplexity.pyindex 0c80a0470..f27e6614e 100644--- a/src/tools/web_search/providers/perplexity.py+++ b/src/tools/web_search/providers/perplexity.py@@ -37,11 +37,11 @@ class PerplexityProvider(BaseSearchProvider):if self._client is None:try:from perplexity import Perplexity- except ImportError:+ except ImportError as e:raise ImportError(- "perplexity module is not installed. To use Perplexity search, please install: "- "pip install perplexity"- )+ "perplexityai module is not installed. To use Perplexity search, please install: "+ "pip install perplexityai"+ ) from eself._client = Perplexity(api_key=self.api_key)return self._client@@ -73,6 +73,9 @@ class PerplexityProvider(BaseSearchProvider):],)+ if not completion.choices or len(completion.choices) == 0:+ raise ValueError("Perplexity API returned no choices")+answer = completion.choices[0].message.content# Build usage info with safe attribute accessdiff --git a/src/tools/web_search/providers/serper.py b/src/tools/web_search/providers/serper.pyindex ecdc8107d..78c152fe9 100644--- a/src/tools/web_search/providers/serper.py+++ b/src/tools/web_search/providers/serper.py@@ -14,6 +14,7 @@ Features:"""from datetime import datetime+import jsonfrom typing import Anyimport requests@@ -23,6 +24,12 @@ from ..types import Citation, SearchResult, WebSearchResponsefrom . import register_provider+class SerperAPIError(Exception):+ """Serper API error"""++ pass++@register_provider("serper")class SerperProvider(BaseSearchProvider):"""Serper Google SERP provider"""@@ -82,9 +89,12 @@ class SerperProvider(BaseSearchProvider):response = requests.post(url, headers=headers, json=payload, timeout=timeout)if response.status_code != 200:- error_data = response.json() if response.text else {}- self.logger.error(f"Serper API error: {response.status_code}")- raise Exception(+ try:+ error_data = response.json()+ except (json.JSONDecodeError, ValueError):+ error_data = {"message": response.text}+ self.logger.error(f"Serper API error: {response.status_code} - {error_data}")+ raise SerperAPIError(f"Serper API error: {response.status_code} - "f"{error_data.get('message', response.text)}")diff --git a/src/tools/web_search/providers/tavily.py b/src/tools/web_search/providers/tavily.pyindex 4ddcb08ac..446898f90 100644--- a/src/tools/web_search/providers/tavily.py+++ b/src/tools/web_search/providers/tavily.py@@ -13,6 +13,7 @@ Features:"""from datetime import datetime+import jsonfrom typing import Anyimport requests@@ -26,6 +27,7 @@ from . import register_providerclass TavilyProvider(BaseSearchProvider):"""Tavily research-focused search provider"""+ name = "tavily"display_name = "Tavily"description = "Research-focused search"api_key_env_var = "TAVILY_API_KEY"@@ -90,8 +92,11 @@ class TavilyProvider(BaseSearchProvider):response = requests.post(self.BASE_URL, json=payload, timeout=timeout)if response.status_code != 200:- error_data = response.json() if response.text else {}- self.logger.error(f"Tavily API error: {response.status_code}")+ try:+ error_data = response.json()+ except (json.JSONDecodeError, ValueError):+ error_data = {"error": response.text}+ self.logger.error(f"Tavily API error: {response.status_code} - {error_data}")raise Exception(f"Tavily API error: {response.status_code} - "f"{error_data.get('error', response.text)}"diff --git a/src/tools/web_search/types.py b/src/tools/web_search/types.pyindex 745971f37..6694a8f20 100644--- a/src/tools/web_search/types.py+++ b/src/tools/web_search/types.py@@ -98,6 +98,8 @@ class WebSearchResponse:"source": r.source,"content": r.content,"score": r.score,+ "sitelinks": r.sitelinks,+ "attributes": r.attributes,}for r in self.search_results],diff --git a/src/utils/config_manager.py b/src/utils/config_manager.pyindex 84ef34331..a1f937f55 100644--- a/src/utils/config_manager.py+++ b/src/utils/config_manager.py@@ -1,17 +1,18 @@-import osimport logging-import tempfile+import osfrom pathlib import Path+import tempfilefrom threading import Lockfrom typing import Any, Dict, List, Optional-import yamlfrom dotenv import dotenv_values, load_dotenvfrom pydantic import ValidationError+import yaml++from ..config.defaults import DEFAULTS# Use package-relative imports to avoid PYTHONPATH issuesfrom ..config.schema import AppConfig, migrate_config-from ..config.defaults import DEFAULTSfrom ..core.errors import ConfigErrorlogger = logging.getLogger(__name__)@@ -56,7 +57,16 @@ class ConfigManager:load_dotenv(dotenv_path=self.project_root / ".env", override=False)load_dotenv(dotenv_path=self.project_root / ".env.local", override=True)+ def _load_env_file(self, path: Path) -> Dict[str, str]:+ """Load a .env file and return non-None values as strings."""+ if not path.exists():+ return {}+ return {k: str(v) for k, v in dotenv_values(path).items() if v is not None}+def _read_yaml(self) -> Dict[str, Any]:+ """Read the main YAML configuration file safely."""+ if not self.config_path.exists():+ return {}with open(self.config_path, "r", encoding="utf-8") as f:return yaml.safe_load(f) or {}@@ -127,7 +137,9 @@ class ConfigManager:)# Atomic write with backup- fd, tmp_path = tempfile.mkstemp(prefix="main.yaml.", dir=str(self.config_path.parent))+ fd, tmp_path = tempfile.mkstemp(+ prefix="main.yaml.", dir=str(self.config_path.parent)+ )try:with os.fdopen(fd, "w", encoding="utf-8") as tmp:tmp.write(yaml_str)@@ -150,7 +162,11 @@ class ConfigManager:except Exception:passexcept ConfigError as ce:- logger.error("Refusing to save invalid config: %s", ce, extra={"context": getattr(ce, "context", {})})+ logger.error(+ "Refusing to save invalid config: %s",+ ce,+ extra={"context": getattr(ce, "context", {})},+ )return Falseexcept Exception as e:logger.exception("Error saving config: %s", e)@@ -163,11 +179,8 @@ class ConfigManager:"""env_path = self.project_root / ".env"local_path = self.project_root / ".env.local"- parsed_env: Dict[str, str] = {}- if env_path.exists():- parsed_env.update({k: str(v) for k, v in dotenv_values(env_path).items() if v is not None})- if local_path.exists():- parsed_env.update({k: str(v) for k, v in dotenv_values(local_path).items() if v is not None})+ parsed_env = self._load_env_file(env_path)+ parsed_env.update(self._load_env_file(local_path))def _get(key: str, default: str = "") -> str:return str(parsed_env.get(key) or os.environ.get(key, default))@@ -179,11 +192,8 @@ class ConfigManager:def validate_required_env(self, keys: List[str]) -> Dict[str, List[str]]:env_path = self.project_root / ".env"local_path = self.project_root / ".env.local"- parsed_env: Dict[str, str] = {}- if env_path.exists():- parsed_env.update({k: str(v) for k, v in dotenv_values(env_path).items() if v is not None})- if local_path.exists():- parsed_env.update({k: str(v) for k, v in dotenv_values(local_path).items() if v is not None})+ parsed_env = self._load_env_file(env_path)+ parsed_env.update(self._load_env_file(local_path))missing = [k for k in keys if not (parsed_env.get(k) or os.environ.get(k))]if missing:logger.warning("Missing required env keys", extra={"missing": missing})@@ -194,4 +204,3 @@ class ConfigManager:"""Reset singleton to allow re-initialization in tests with a different project_root."""with cls._lock:cls._instance = None-diff --git a/src/utils/document_validator.py b/src/utils/document_validator.pynew file mode 100644index 000000000..fe36e0d98--- /dev/null+++ b/src/utils/document_validator.py@@ -0,0 +1,132 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+Document Validator - Validation utilities for document uploads+"""++import os+import re+from typing import ClassVar+++class DocumentValidator:+ """Document validation utilities"""++ # Maximum file size in bytes (100MB)+ MAX_FILE_SIZE: ClassVar[int] = 100 * 1024 * 1024++ # Allowed file extensions+ ALLOWED_EXTENSIONS: ClassVar[set[str]] = {+ ".pdf",+ ".txt",+ ".md",+ ".doc",+ ".docx",+ ".rtf",+ ".html",+ ".htm",+ ".xml",+ ".json",+ ".csv",+ ".xlsx",+ ".xls",+ ".pptx",+ ".ppt",+ }++ @staticmethod+ def validate_upload_safety(+ filename: str, file_size: int | None, allowed_extensions: set[str] | None = None+ ) -> str:+ """+ Validate file upload safety++ Args:+ filename: Name of the file+ file_size: Size of the file in bytes, or None to skip size validation+ allowed_extensions: Optional override for allowed extensions++ Returns:+ Sanitized filename safe for filesystem use++ Raises:+ ValueError: If validation fails+ """+ # Check file size (skip if size is None)+ if file_size is not None and file_size > DocumentValidator.MAX_FILE_SIZE:+ raise ValueError(+ f"File too large: {file_size} bytes. Maximum allowed: {DocumentValidator.MAX_FILE_SIZE} bytes"+ )++ # Sanitize filename - remove path components and dangerous characters+ # Extract just the filename, removing any path components+ safe_name = os.path.basename(filename)+ # Remove null bytes and other control characters+ safe_name = re.sub(r"[\x00-\x1f\x7f]", "", safe_name)+ # Replace problematic characters+ safe_name = re.sub(r'[<>:"/\\|?*]', "_", safe_name)++ if not safe_name or safe_name in (".", "..") or safe_name.strip("_") == "":+ raise ValueError("Invalid filename")++ # Check file extension+ _, ext = os.path.splitext(safe_name.lower())+ exts_to_check = allowed_extensions or DocumentValidator.ALLOWED_EXTENSIONS+ if ext not in exts_to_check:+ raise ValueError(+ f"Unsupported file type: {ext}. Allowed types: {', '.join(exts_to_check)}"+ )++ return safe_name++ @staticmethod+ def get_file_info(filename: str, file_size: int) -> dict:+ """+ Get file information++ Args:+ filename: Name of the file+ file_size: Size of the file in bytes++ Returns:+ Dictionary with file information+ """+ _, ext = os.path.splitext(filename.lower())+ return {+ "filename": filename,+ "extension": ext,+ "size_bytes": file_size,+ "size_mb": round(file_size / (1024 * 1024), 2),+ "is_allowed": ext in DocumentValidator.ALLOWED_EXTENSIONS,+ }++ @staticmethod+ def validate_file(path: str) -> dict:+ """+ Validate that a file exists, is readable, and has valid content.++ Args:+ path: Path to the file to validate++ Returns:+ File info dictionary++ Raises:+ ValueError: If file is missing or validation fails+ """+ if not os.path.exists(path):+ raise ValueError(f"File not found: {path}")++ if not os.path.isfile(path):+ raise ValueError(f"Not a file: {path}")++ if not os.access(path, os.R_OK):+ raise ValueError(f"File not readable: {path}")++ size = os.path.getsize(path)+ filename = os.path.basename(path)++ # Validate using validate_upload_safety+ safe_name = DocumentValidator.validate_upload_safety(filename, size)++ return DocumentValidator.get_file_info(safe_name, size)diff --git a/src/utils/error_rate_tracker.py b/src/utils/error_rate_tracker.pynew file mode 100644index 000000000..e01fb8d19--- /dev/null+++ b/src/utils/error_rate_tracker.py@@ -0,0 +1,111 @@+"""+Error Rate Tracker - Track error rates per provider with alerting.+"""++from collections import defaultdict, deque+import logging+import threading+import time+from typing import Callable, Dict, Optional++logger = logging.getLogger(__name__)+++class ErrorRateTracker:+ """+ Tracks error rates per provider with sliding window.+ """++ def __init__(+ self,+ window_size: int = 60,+ threshold: float = 0.5,+ alert_callback: Optional[Callable[[str, float], None]] = None,+ ):+ self.window_size = window_size # seconds+ self.threshold = threshold # failure rate threshold+ self.alert_callback = alert_callback+ self._lock = threading.RLock() # Use RLock to allow reentrant locking+ self._errors: Dict[str, deque[float]] = defaultdict(deque)+ self._total_calls: Dict[str, deque[float]] = defaultdict(deque)+ self._alerted: Dict[str, bool] = defaultdict(bool) # to avoid repeated alerts++ def record_call(self, provider: str, success: bool):+ """Record a call for the provider."""+ now = time.time()+ with self._lock:+ self._total_calls[provider].append(now)+ if not success:+ self._errors[provider].append(now)+ self._cleanup_old_entries(provider, now)+ self._check_alert(provider)++ def get_error_rate(self, provider: str) -> float:+ """Get current error rate for provider."""+ now = time.time()+ with self._lock:+ self._cleanup_old_entries(provider, now)+ total = len(self._total_calls[provider])+ errors = len(self._errors[provider])+ return errors / total if total > 0 else 0.0++ def check_threshold(self, provider: str) -> bool:+ """Check if error rate exceeds threshold."""+ rate = self.get_error_rate(provider)+ return rate > self.threshold++ def _check_alert(self, provider: str):+ """Check and trigger alert if needed."""+ rate = self.get_error_rate(provider)+ exceeds_threshold = rate > self.threshold+ if exceeds_threshold and not self._alerted[provider]:+ logger.warning(+ f"Provider {provider} error rate {rate:.2%} exceeds threshold {self.threshold:.2%}"+ )+ if self.alert_callback:+ self.alert_callback(provider, rate)+ self._alerted[provider] = True+ elif not exceeds_threshold:+ self._alerted[provider] = False # reset when below threshold++ def _cleanup_old_entries(self, provider: str, now: float):+ """Remove entries older than window_size."""+ cutoff = now - self.window_size+ while self._total_calls[provider] and self._total_calls[provider][0] <= cutoff:+ self._total_calls[provider].popleft()+ while self._errors[provider] and self._errors[provider][0] <= cutoff:+ self._errors[provider].popleft()+++# Global instance+tracker = ErrorRateTracker()++# Set alert callback to circuit breaker+try:+ from .network.circuit_breaker import alert_callback as cb++ tracker.alert_callback = cb+except ImportError as e:+ logging.getLogger(__name__).warning(+ f"Circuit breaker module not available: {e}. Error rate tracking will work but circuit breaker integration is disabled."+ )+++def record_provider_call(provider: str, success: bool):+ """Global function to record a call."""+ tracker.record_call(provider, success)+++def get_provider_error_rate(provider: str) -> float:+ """Get error rate for provider."""+ return tracker.get_error_rate(provider)+++def check_provider_threshold(provider: str) -> bool:+ """Check if provider exceeds threshold."""+ return tracker.check_threshold(provider)+++def set_alert_callback(callback: Callable[[str, float], None]):+ """Set the alert callback for the tracker."""+ tracker.alert_callback = callbackdiff --git a/src/utils/error_utils.py b/src/utils/error_utils.pynew file mode 100644index 000000000..bce328842--- /dev/null+++ b/src/utils/error_utils.py@@ -0,0 +1,82 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+Error Utilities - Error formatting and handling utilities+"""++import json+from typing import Optional+++def _find_json_block(message: str) -> Optional[str]:+ """Extract potential JSON block from message by matching braces."""+ start_idx = message.find("{")+ if start_idx == -1:+ return None++ brace_count = 0+ in_string = False+ escape_next = False++ for char_idx in range(start_idx, len(message)):+ char = message[char_idx]++ if escape_next:+ escape_next = False+ continue++ if char == "\\":+ escape_next = True+ continue++ if char == '"':+ in_string = not in_string+ continue++ if not in_string:+ if char == "{":+ brace_count += 1+ elif char == "}":+ brace_count -= 1+ if brace_count == 0:+ return message[start_idx : char_idx + 1]++ return None+++def format_exception_message(exc: Exception) -> str:+ """+ Format exception message for better readability++ Args:+ exc: The exception to format++ Returns:+ Formatted error message+ """+ message = str(exc)++ # Try to parse JSON error messages (common in API errors)+ potential_json = _find_json_block(message)+ if potential_json:+ try:+ error_data = json.loads(potential_json)++ # Standard extraction logic+ if isinstance(error_data, dict) and "error" in error_data:+ error_info = error_data["error"]+ if isinstance(error_info, dict):+ parts = []+ if "message" in error_info:+ parts.append(f"Message: {error_info['message']}")+ if "type" in error_info:+ parts.append(f"Type: {error_info['type']}")+ if "code" in error_info:+ parts.append(f"Code: {error_info['code']}")+ if parts:+ return " | ".join(parts)+ except (json.JSONDecodeError, AttributeError):+ pass++ # Return original message if parsing fails+ return messagediff --git a/src/utils/network/circuit_breaker.py b/src/utils/network/circuit_breaker.pynew file mode 100644index 000000000..299d3bfd5--- /dev/null+++ b/src/utils/network/circuit_breaker.py@@ -0,0 +1,79 @@+"""+Circuit Breaker - Simple circuit breaker for providers.+"""++import logging+import threading+import time+from typing import Dict++logger = logging.getLogger(__name__)+++class CircuitBreaker:+ """+ Simple circuit breaker that opens when error rate is high.+ """++ def __init__(self, failure_threshold: int = 5, recovery_timeout: int = 60):+ self.failure_threshold = failure_threshold+ self.recovery_timeout = recovery_timeout+ self.failure_count: Dict[str, int] = {}+ self.last_failure_time: Dict[str, float] = {}+ self.state: Dict[str, str] = {} # 'closed', 'open', 'half-open'+ self.lock = threading.Lock()++ def call(self, provider: str) -> bool:+ """Check if call is allowed."""+ with self.lock:+ state = self.state.get(provider, "closed")+ if state == "closed":+ return True+ elif state == "open":+ if time.time() - self.last_failure_time.get(provider, 0) > self.recovery_timeout:+ self.state[provider] = "half-open"+ logger.info(f"Circuit breaker for {provider} entering half-open state")+ return True+ return False+ elif state == "half-open":+ return True++ def record_success(self, provider: str):+ """Record successful call."""+ with self.lock:+ if self.state.get(provider) == "half-open":+ self.state[provider] = "closed"+ self.failure_count[provider] = 0+ logger.info(f"Circuit breaker for {provider} closed")+ elif self.state.get(provider) == "closed":+ self.failure_count[provider] = 0++ def record_failure(self, provider: str):+ """Record failed call."""+ with self.lock:+ self.failure_count[provider] = self.failure_count.get(provider, 0) + 1+ self.last_failure_time[provider] = time.time()+ if self.failure_count[provider] >= self.failure_threshold:+ self.state[provider] = "open"+ logger.warning(+ f"Circuit breaker for {provider} opened due to {self.failure_count[provider]} failures"+ )+++# Global instance+circuit_breaker = CircuitBreaker()+++def alert_callback(provider: str, rate: float):+ """Alert callback to trigger circuit breaker."""+ circuit_breaker.record_failure(provider)+++def is_call_allowed(provider: str) -> bool:+ """Check if call is allowed by circuit breaker."""+ return circuit_breaker.call(provider)+++def record_call_success(provider: str):+ """Record successful call."""+ circuit_breaker.record_success(provider)diff --git a/tests/core/test_config_manager.py b/tests/core/test_config_manager.pyindex ccdc97c37..980973d07 100644--- a/tests/core/test_config_manager.py+++ b/tests/core/test_config_manager.py@@ -1,5 +1,7 @@from pathlib import Path+import yaml+from src.utils.config_manager import ConfigManager@@ -58,4 +60,3 @@ def test_env_layering(tmp_path: Path):cm = ConfigManager(project_root=project)env = cm.get_env_info()assert env["model"] == "Override"-diff --git a/web/.env.local b/web/.env.localindex 0b6543af3..8840a64d6 100644--- a/web/.env.local+++ b/web/.env.local@@ -3,7 +3,7 @@# ============================================# This file is automatically updated based on config/main.yaml# and environment variables (NEXT_PUBLIC_API_BASE, NEXT_PUBLIC_API_BASE_EXTERNAL)-#+## To configure for remote access, set in your .env file:# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001# ============================================diff --git a/web/app/settings/page.tsx b/web/app/settings/page.tsxindex ce59c17f3..c33fdedfe 100644--- a/web/app/settings/page.tsx+++ b/web/app/settings/page.tsx@@ -681,13 +681,17 @@ export default function SettingsPage() {setEditedEnvVars((prev) => ({ ...prev, [key]: value }));// Sync SEARCH_PROVIDER env var with config dropdown- if (key === "SEARCH_PROVIDER" && value) {+ if (key === "SEARCH_PROVIDER") {setEditedConfig((prev) => {if (!prev) return null;const newConfig = { ...prev };if (!newConfig.tools) newConfig.tools = {};if (!newConfig.tools.web_search) newConfig.tools.web_search = {};- newConfig.tools.web_search.provider = value;+ if (value) {+ newConfig.tools.web_search.provider = value;+ } else {+ delete newConfig.tools.web_search.provider;+ }return newConfig;});}@@ -1599,7 +1603,7 @@ export default function SettingsPage() {handleConfigChange("tools","max_results",- parseInt(e.target.value),+ e.target.value === "" ? 5 : parseInt(e.target.value),"web_search",)}diff --git a/web/package.json b/web/package.jsonindex a64efba31..2b58ab8b6 100644--- a/web/package.json+++ b/web/package.json@@ -30,7 +30,7 @@"tailwind-merge": "^3.4.0"},"devDependencies": {- "@playwright/test": "^1.49.0",+ "@playwright/test": "^1.53.2","@types/node": "^25","@types/react": "^19","@types/react-dom": "^19",diff --git a/web/playwright.config.ts b/web/playwright.config.tsindex f3910d35c..d77bf44ec 100644--- a/web/playwright.config.ts+++ b/web/playwright.config.ts@@ -1,7 +1,9 @@import { defineConfig, devices } from "@playwright/test";const BASE_URL =- process.env.WEB_BASE_URL || process.env.NEXT_PUBLIC_API_BASE || "http://localhost:3000";+ process.env.WEB_BASE_URL ||+ process.env.NEXT_PUBLIC_API_BASE ||+ "http://localhost:3000";const SERIAL_MODE = process.env.PW_SERIAL === "1";export default defineConfig({